# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-warrant-whose-capability-set-silently-widens-after-the-second-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-warrant-whose-capability-set-silently-widens-after-the-second-hop.warrant.json
# Markdown SHA-256:   27d159099fd3b52e0303c525052501a029eb95058406463d253bec642a3f8e83
# Code AST SHA-256:   6e1f20784ec4090b994831b0f5f5b740382be6a6354325a76caa5f11e902b397
# Verified Classes:   WarrantAttenuationError, Capability
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class WarrantAttenuationError(RuntimeError):
    """Raised when a delegation chain widens capability beyond an ancestor's grant."""


@dataclass(frozen=True)
class Capability:
    kind: str          # "http:get", "fs:read", "tool"
    scope: str         # "*.arxiv.org", "/corpus", "summarize"


def subsumes(parent: Capability, child: Capability) -> bool:
    """True iff child is no broader than parent. Glob-aware, not string-prefix."""
    if parent.kind != child.kind:
        return False
    if parent.scope == "*":
        return True
    if parent.scope.startswith("*."):
        suffix = parent.scope[1:]              # ".arxiv.org"
        return child.scope == parent.scope or child.scope.endswith(suffix)
    if parent.scope.endswith("/*"):
        prefix = parent.scope[:-1]             # "/corpus/"
        return child.scope == parent.scope or child.scope.startswith(prefix)
    return parent.scope == child.scope


def intersect_chain(chain: list[set[Capability]]) -> set[Capability]:
    """Running intersection from root to leaf. Root is chain[0]."""
    effective = set(chain[0])
    for caps in chain[1:]:
        effective = {c for c in effective if any(subsumes(c, d) for d in caps)}
    return effective


def admit(chain: list[set[Capability]], leaf_index: int = -1) -> set[Capability]:
    """Admission gate: reject any leaf capability not backed by every ancestor."""
    effective = intersect_chain(chain)
    leaf = chain[leaf_index]
    for cap in leaf:
        if not any(subsumes(e, cap) for e in effective):
            raise WarrantAttenuationError(
                f"capability {cap.kind}:{cap.scope} at leaf is not subsumed by "
                f"the chain intersection; delegation widened at some hop"
            )
    return effective


# Reproduction of the observed failure:
root = {Capability("http:get", "*.arxiv.org"), Capability("tool", "summarize")}
planner = {Capability("http:get", "*.arxiv.org"), Capability("tool", "summarize")}
leaf = {Capability("http:get", "*"), Capability("tool", "write_memory")}

# admit([root, planner, leaf]) raises WarrantAttenuationError on http:get:*.
# A per-link signature verifier would have admitted the leaf verbatim.
