# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-capability-warrant-attenuation-collapse-when-a-delegated-agent-re-signs-its-own-scope-during-cross-org-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-capability-warrant-attenuation-collapse-when-a-delegated-agent-re-signs-its-own-scope-during-cross-org-handoff.warrant.json
# Markdown SHA-256:   aa7793b76d192ef1d2160354298328864bdae35185a06d101bff449691916a03
# Code AST SHA-256:   d004af4af5ec36033e707e08c76de4888b646ffd06935210c156636237835f08
# Verified Classes:   ScopeAttenuationError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeAttenuationError(RuntimeError):
    """Raised when a child warrant's scope is not a subset of its parent chain."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope: FrozenSet[str]
    parent_hash: str | None
    depth_remaining: int
    signature: str  # opaque; assumed verified upstream
    warrant_hash: str = field(default="")


def compute_effective_scope(chain: list[Warrant]) -> FrozenSet[str]:
    """Intersection of all ancestor scopes, root first. Monotone by construction."""
    if not chain:
        raise ScopeAttenuationError("empty warrant chain")
    effective = chain[0].scope
    for w in chain[1:]:
        effective = effective & w.scope
    return effective


def verify_chain(chain: list[Warrant], max_depth: int) -> FrozenSet[str]:
    """Recompute ancestor intersection and enforce monotonic attenuation.

    chain is ordered root -> leaf. Signatures and parent_hash linkage are
    assumed already verified; this function checks the scope lattice only.
    """
    root = chain[0]
    if root.depth_remaining > max_depth:
        raise ScopeAttenuationError(
            f"root depth_remaining {root.depth_remaining} exceeds max_depth {max_depth}"
        )

    effective = compute_effective_scope(chain)

    for i, w in enumerate(chain):
        # A child warrant may never carry a token absent from the intersection
        # of every ancestor, including itself.
        illegal = w.scope - effective
        if illegal:
            raise ScopeAttenuationError(
                f"hop {i} ({w.issuer}->{w.subject}) widens scope: "
                f"tokens {sorted(illegal)} not present in ancestor intersection "
                f"{sorted(effective)}"
            )
        # Depth budget must strictly decrease per hop.
        if i > 0 and w.depth_remaining >= chain[i - 1].depth_remaining:
            raise ScopeAttenuationError(
                f"hop {i} did not consume depth: {w.depth_remaining} >= "
                f"{chain[i - 1].depth_remaining}"
            )

    return effective


def authorize_tool_call(effective_scope: FrozenSet[str], requested_token: str) -> None:
    """Call-time check: a valid narrow warrant can still be misused by the model."""
    if requested_token not in effective_scope:
        raise ScopeAttenuationError(
            f"tool call requests '{requested_token}' outside effective scope "
            f"{sorted(effective_scope)}"
        )
