# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-chain-has-silently-widened-scope-through-transitive-attenuation-collapse.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-chain-has-silently-widened-scope-through-transitive-attenuation-collapse.warrant.json
# Markdown SHA-256:   818be3e22da4d0a424e14cfd49ad148e9a235dd4f087aa18c78c4ac0fb766d88
# Code AST SHA-256:   071b18412368b78d9af1621fec62b0f01664f6c86da2bccfd273882aacf65662
# Verified Classes:   AttenuationCollapseError, ScopeElement, CapabilityToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AttenuationCollapseError(RuntimeError):
    """Raised when a delegated scope is not a lattice-subset of its parent scope.

    This is a hard failure: the delegation must not be issued, and the caller
    must not fall back to warn-and-proceed. Signature validity is irrelevant
    to this check.
    """


@dataclass(frozen=True)
class ScopeElement:
    kind: str          # e.g. "fs:read", "tool"
    target: str        # e.g. "/data/reports/*", "summarize"
    # lattice rank: lower is narrower. Callers must supply a correct order.
    rank: int


@dataclass(frozen=True)
class CapabilityToken:
    principal: str
    scope: FrozenSet[ScopeElement]
    parent_fingerprint: str | None = None
    chain: tuple = field(default_factory=tuple)


def _covers(parent: ScopeElement, child: ScopeElement) -> bool:
    """True iff parent's authority contains child's authority.

    A parent covers a child when the child is the same kind and the parent's
    rank is <= the child's rank (broader or equal). This is the lattice
    relation; string/glob comparison is explicitly NOT used.
    """
    return parent.kind == child.kind and parent.rank <= child.rank


def assert_monotonic(parent: CapabilityToken, child_scope: FrozenSet[ScopeElement]) -> None:
    """Enforce scope(child) subset-of scope(parent) at the delegation edge.

    Raises AttenuationCollapseError on the first uncovered element. Must be
    called at issuance, and re-called transitively at every verifier hop.
    """
    for c in child_scope:
        if not any(_covers(p, c) for p in parent.scope):
            raise AttenuationCollapseError(
                f"delegation widens authority: child element {c!r} "
                f"not covered by parent {parent.principal} scope"
            )


def delegate(parent: CapabilityToken, proposed: FrozenSet[ScopeElement],
             child_principal: str) -> CapabilityToken:
    """Issue a child token only if the proposed scope is a lattice-subset.

    `proposed` may originate from an LLM reasoning loop; it is treated as a
    candidate and gated deterministically here. No warn-and-proceed path.
    """
    try:
        assert_monotonic(parent, proposed)
    except AttenuationCollapseError:
        # fail closed: never issue a widening token
        raise
    return CapabilityToken(
        principal=child_principal,
        scope=proposed,
        parent_fingerprint=f"{parent.principal}:{hash(parent.scope)}",
        chain=parent.chain + (parent.principal,),
    )


def verify_chain_transitively(leaf: CapabilityToken,
                              registry: dict) -> None:
    """Walk root->leaf re-checking monotonicity at every edge.

    A verifier that only checks the immediate parent cannot detect an
    upstream violation. This walks the chain and re-runs the subset check
    per edge.
    """
    prev = None
    for principal in leaf.chain:
        token = registry[principal]
        if prev is not None:
            assert_monotonic(prev, token.scope)
        prev = token
    if prev is not None:
        assert_monotonic(prev, leaf.scope)
