# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-aaif-delegation-chain-when-the-leaf-warrant-is-still-cryptographically-valid.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-aaif-delegation-chain-when-the-leaf-warrant-is-still-cryptographically-valid.warrant.json
# Markdown SHA-256:   a260a3c763e7ffec90c3fa8edbc0125316012b15e9a8f5b251e431c74908aa23
# Code AST SHA-256:   093a99d4f3c8a40a2eb43f7f7d4384f711aff584342177f4169f42cc6fd1e7e6
# Verified Classes:   DelegationChainError, Warrant, VerifierState
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DelegationChainError(RuntimeError):
    """Raised when an AAIF chain is signature-valid but authorization-discontinuous."""


@dataclass
class Warrant:
    warrant_id: str
    issuer: str
    subject: str
    parent_warrant_id: Optional[str]
    scope: dict
    signature_valid: bool = True


@dataclass
class VerifierState:
    # Warrants the verifier actually observed being issued in this chain.
    issued_set: set = field(default_factory=set)
    root_max_depth: int = 0


def verify_chain(chain: list[Warrant], state: VerifierState) -> None:
    if not chain:
        raise DelegationChainError("empty chain: no root warrant presented")

    root = chain[0]
    state.root_max_depth = root.scope.get("max_delegation_depth", 0)
    state.issued_set.add(root.warrant_id)

    for i in range(1, len(chain)):
        parent, child = chain[i - 1], chain[i]

        # (1) signature validity is necessary but not the failure we catch here
        if not child.signature_valid:
            raise DelegationChainError(f"hop {i}: invalid signature on {child.warrant_id}")

        # (2) contiguity: child must point at the parent we actually hold,
        #     and that parent must be one the verifier saw issued.
        if child.parent_warrant_id != parent.warrant_id:
            raise DelegationChainError(
                f"hop {i}: parent_warrant_id {child.parent_warrant_id!r} "
                f"!= held parent {parent.warrant_id!r}"
            )
        if parent.warrant_id not in state.issued_set:
            # This is the checkpoint-resume re-mint: a valid signature over a
            # warrant_id the verifier never observed being issued.
            raise DelegationChainError(
                f"hop {i}: parent {parent.warrant_id} was never issued in this chain "
                f"(re-minted from local state?)"
            )

        # (3) monotonic depth recomputed from ROOT, not from parent's field
        remaining = state.root_max_depth - i
        declared = child.scope.get("max_delegation_depth", -1)
        if remaining < 0:
            raise DelegationChainError(
                f"hop {i}: depth budget exhausted (root={state.root_max_depth}, hop={i})"
            )
        if declared > remaining:
            raise DelegationChainError(
                f"hop {i}: depth widened: child declares {declared} > remaining {remaining}"
            )

        # (4) full-lattice subset check on every dimension the root declares
        for dim, root_val in root.scope.items():
            if dim == "max_delegation_depth":
                continue
            child_val = child.scope.get(dim)
            if not _subset(child_val, root_val):
                raise DelegationChainError(
                    f"hop {i}: scope widening on {dim!r}: {child_val!r} not ⊆ {root_val!r}"
                )

        state.issued_set.add(child.warrant_id)


def _subset(child, parent) -> bool:
    if parent is None:
        return child is None
    if isinstance(parent, list):
        if not isinstance(child, list):
            return False
        return all(c in parent for c in child)
    if isinstance(parent, str) and parent.endswith("*"):
        prefix = parent[:-1]
        return isinstance(child, str) and child.startswith(prefix)
    return child == parent


# Trace of the observed failure: B' re-minted W1' after checkpoint-resume.
W0 = Warrant("w0", "svc:pipeline", "agent:B", None,
             {"tools": ["read_db", "write_report"], "max_delegation_depth": 2})
W1_prime = Warrant("w1p", "agent:B", "agent:C", "w0",
                   {"tools": ["write_report"], "max_delegation_depth": 2})  # reset!
W2 = Warrant("w2", "agent:C", "tool:write_report", "w1p",
             {"tools": ["write_report"], "max_delegation_depth": 2})

state = VerifierState()
state.issued_set.add("w0")  # verifier saw W0 issued; it never saw w1p issued

try:
    verify_chain([W0, W1_prime, W2], state)
except DelegationChainError as e:
    print(f"BLOCKED: {e}")
