# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-delegation-chain-when-transitive-revocation-outpaces-scope-attenuation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-delegation-chain-when-transitive-revocation-outpaces-scope-attenuation.warrant.json
# Markdown SHA-256:   244b6ee41ce1826782a050b8c633fa5f04ce7b7d0af13843f5f0bf3190f9106a
# Code AST SHA-256:   2a659898a3034ac8120bf6b5debb0147f79b60b268a0f43debb3cf1d8ae3bf22
# Verified Classes:   RevokedAncestryError, ReissuanceOffDeadTrunkError, Warrant, DelegationRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class RevokedAncestryError(RuntimeError):
    """Raised when a leaf warrant's local proof is valid but its ancestry
    resolves to a revoked root. Distinct from signature/scope failures
    because remediation is 're-delegate from a live root', not 'fix request'."""


class ReissuanceOffDeadTrunkError(RuntimeError):
    """Raised when an intermediate attempts to mint a child warrant whose
    parent ancestry is already revoked. Prevents retry storms from
    resurrecting a severed chain."""


@dataclass
class Warrant:
    issuer: str
    subject: str
    scope: frozenset
    parent_digest: Optional[str]
    nonce: str
    digest: str = field(init=False)

    def __post_init__(self):
        canon = f"{self.issuer}|{self.subject}|{sorted(self.scope)}|{self.parent_digest}|{self.nonce}"
        self.digest = hashlib.sha256(canon.encode()).hexdigest()


class DelegationRegistry:
    """Append-only warrant store plus monotone revocation set."""

    def __init__(self):
        self.warrants: dict[str, Warrant] = {}
        self.revoked: set[str] = set()

    def register(self, w: Warrant) -> None:
        self.warrants[w.digest] = w

    def revoke(self, digest: str) -> None:
        # Monotone: revocation is never undone.
        self.revoked.add(digest)

    def resolve_root(self, leaf: Warrant) -> Warrant:
        """Walk parent_digest links to a root. Raises if any link is missing."""
        cur = leaf
        seen = set()
        while cur.parent_digest is not None:
            if cur.digest in seen:
                raise RevokedAncestryError(f"cycle detected at {cur.digest}")
            seen.add(cur.digest)
            parent = self.warrants.get(cur.parent_digest)
            if parent is None:
                raise RevokedAncestryError(
                    f"dangling parent_digest {cur.parent_digest} from {cur.digest}"
                )
            cur = parent
        return cur

    def enforce_leaf(self, leaf: Warrant, requested: frozenset) -> None:
        """Enforcement path: local attenuation AND ancestry liveness."""
        # Local attenuation check (edge proof).
        if not requested.issubset(leaf.scope):
            raise RevokedAncestryError(
                f"scope exceeded: requested {requested} not ⊆ {leaf.scope}"
            )
        # Ancestry resolution (path proof) — the missing check in the failure.
        root = self.resolve_root(leaf)
        if root.digest in self.revoked:
            raise RevokedAncestryError(
                f"leaf {leaf.digest} passes local proof but root {root.digest} is revoked"
            )

    def mint_child(self, parent: Warrant, subject: str, scope: frozenset, nonce: str) -> Warrant:
        """Intermediate re-issuance: gate on parent-root liveness, not just local scope."""
        if not scope.issubset(parent.scope):
            raise ReissuanceOffDeadTrunkError(
                f"attenuation violated: {scope} not ⊆ {parent.scope}"
            )
        root = self.resolve_root(parent)
        if root.digest in self.revoked:
            raise ReissuanceOffDeadTrunkError(
                f"refusing to mint off dead trunk: parent {parent.digest} "
                f"resolves to revoked root {root.digest}"
            )
        child = Warrant(
            issuer=parent.subject,
            subject=subject,
            scope=scope,
            parent_digest=parent.digest,
            nonce=nonce,
        )
        self.register(child)
        return child


def demo():
    reg = DelegationRegistry()
    w_a = Warrant("orchestrator", "B", frozenset({"read:web", "read:internal", "write:scratch"}), None, "n-a")
    reg.register(w_a)
    w_b = reg.mint_child(w_a, "C", frozenset({"read:web", "write:scratch"}), "n-b")
    w_c = reg.mint_child(w_b, "tool", frozenset({"read:web"}), "n-c")

    # Healthy: leaf passes local + ancestry.
    reg.enforce_leaf(w_c, frozenset({"read:web"}))

    # Revoke the root.
    reg.revoke(w_a.digest)

    # Leaf still passes local attenuation, but ancestry is dead.
    try:
        reg.enforce_leaf(w_c, frozenset({"read:web"}))
    except RevokedAncestryError as e:
        print(f"enforced: {e}")

    # Retry storm cannot resurrect the chain.
    try:
        reg.mint_child(w_b, "tool2", frozenset({"read:web"}), "n-c2")
    except ReissuanceOffDeadTrunkError as e:
        print(f"blocked reissuance: {e}")


if __name__ == "__main__":
    demo()
