# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-delegated-aaif-credential-scope-has-silently-widened-across-a-multi-hop-agent-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-delegated-aaif-credential-scope-has-silently-widened-across-a-multi-hop-agent-chain.warrant.json
# Markdown SHA-256:   1142fcd1f9447153d81850999f7cec2196f3274965cde9648e1ec1f11d61b667
# Code AST SHA-256:   a47fc7addf1e12a47a730c3307b60f4195de33458685ef784af36820682aaed2
# Verified Classes:   AttenuationDriftError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AttenuationDriftError(RuntimeError):
    """Raised when a delegated credential's effective scope is not a subset
    of its parent's effective scope under the shared evaluator."""


@dataclass(frozen=True)
class Warrant:
    token_id: str
    parent_id: str | None
    schema_version: str
    verbs: FrozenSet[str]
    constraints: FrozenSet[str]          # e.g. frozenset({"write:issues"})
    closed_world: bool = True

    def effective(self, evaluator_schema: str) -> FrozenSet[str]:
        if self.schema_version != evaluator_schema:
            # Cannot reconstruct ancestor semantics under a foreign schema.
            raise AttenuationDriftError(
                f"schema mismatch: token {self.token_id} v{self.schema_version} "
                f"vs evaluator v{evaluator_schema}; refusing to evaluate"
            )
        if not self.closed_world:
            raise AttenuationDriftError(
                f"token {self.token_id} is open-world; unlisted verbs would "
                f"widen authority, cannot bound effective scope"
            )
        return frozenset(f"{v}:{c}" for v in self.verbs for c in self.constraints)


def attenuate(parent: Warrant, child: Warrant, evaluator_schema: str) -> Warrant:
    """Mint a child warrant only if it is a true subset of the parent."""
    if child.parent_id != parent.token_id:
        raise AttenuationDriftError(
            f"child {child.token_id} does not reference parent {parent.token_id}; "
            f"revocation and scope reconstruction would break"
        )
    parent_eff = parent.effective(evaluator_schema)
    child_eff = child.effective(evaluator_schema)
    widened = child_eff - parent_eff
    if widened:
        raise AttenuationDriftError(
            f"attenuation widened scope at {child.token_id}: "
            f"child grants {sorted(widened)} not held by parent {parent.token_id}"
        )
    return child


def authorize(request: str, leaf: Warrant, chain: dict[str, Warrant],
              evaluator_schema: str) -> bool:
    """Walk the full ancestor chain; deny if any ancestor is revoked or absent."""
    node: Warrant | None = leaf
    while node is not None:
        if node.token_id not in chain:
            raise AttenuationDriftError(
                f"broken chain at {node.token_id}: ancestor warrant missing, "
                f"cannot verify revocation or scope dominance"
            )
        if request not in node.effective(evaluator_schema):
            return False
        node = chain.get(node.parent_id) if node.parent_id else None
    return True
