# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-transitive-trust-widening-fault-when-a-brokered-a2a-peer-re-attests-a-warrant-under-a-policy-it-was-never-authorized-to.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-transitive-trust-widening-fault-when-a-brokered-a2a-peer-re-attests-a-warrant-under-a-policy-it-was-never-authorized-to.warrant.json
# Markdown SHA-256:   564bd55d436573ce7043aff0032307458f40a8586c27884db42b0ca4a44a333f
# Code AST SHA-256:   a1403c47d177370c40c5dc7f12b2a012606b4025bfecb99c98c9f01329be4126
# Verified Classes:   DelegationFault, Policy, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DelegationFault(RuntimeError):
    """Raised when a re-attested warrant widens authority beyond its root."""
    pass


@dataclass(frozen=True)
class Policy:
    lattice_version: str
    max_hops: int
    ops: frozenset
    data_class_rank: int  # lower = more restrictive, per root lattice


@dataclass
class Warrant:
    iss: str
    sub: str
    policy: Policy
    hops_left: int
    parent_hash: Optional[str] = None


def _subset(term: Policy, root: Policy) -> list:
    """Return list of widening violations of term relative to root."""
    faults = []
    if term.lattice_version != root.lattice_version:
        faults.append(f"lattice_version {term.lattice_version} != root {root.lattice_version}")
    if term.max_hops > root.max_hops:
        faults.append(f"max_hops widened {root.max_hops} -> {term.max_hops}")
    extra = term.ops - root.ops
    if extra:
        faults.append(f"ops widened: +{sorted(extra)}")
    if term.data_class_rank > root.data_class_rank:
        faults.append(
            f"data_class widened rank {root.data_class_rank} -> {term.data_class_rank}"
        )
    return faults


def verify_chain(root: Warrant, chain: list, bridge_ok: bool = False) -> Policy:
    """
    Verify a B -> ... -> C warrant chain. Returns the effective terminal
    policy C may act under (already intersected with C's local policy by caller).
    Raises DelegationFault on any widening, hop regression, or unattested
    lattice-version mismatch.
    """
    if not chain:
        raise DelegationFault("empty chain")
    prev = root
    for hop in chain:
        if hop.parent_hash is None:
            raise DelegationFault(f"hop {hop.sub}: missing parent_hash")
        # hops consumed must be non-decreasing; hops_left must not grow
        if hop.hops_left > prev.hops_left:
            raise DelegationFault(
                f"hop {hop.sub}: hops_left regressed {prev.hops_left} -> {hop.hops_left}"
            )
        faults = _subset(hop.policy, root.policy)
        if faults and not (bridge_ok and hop.policy.lattice_version != root.policy.lattice_version):
            raise DelegationFault(
                f"hop {hop.sub}: authority widened under {root.policy.lattice_version}: "
                + "; ".join(faults)
            )
        prev = hop
    return prev.policy


# --- observed failure replay ---
root = Warrant(
    iss="B", sub="a1",
    policy=Policy("L_v3", max_hops=2, ops=frozenset({"read", "summarize"}), data_class_rank=0),
    hops_left=2,
)
bad_hop = Warrant(
    iss="A", sub="a2",
    policy=Policy("L_v3", max_hops=3, ops=frozenset({"read", "summarize", "write"}), data_class_rank=0),
    hops_left=3,
    parent_hash="hash(w0)",
)

try:
    verify_chain(root, [bad_hop])
except DelegationFault as e:
    # Expected: this is the escalation the unguarded verifier missed.
    print(f"REJECTED and reported to broker B: {e}")
