# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-transitive-trust-laundering-in-federated-agent-directories-before-capability-warrants-cross-an-org-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-transitive-trust-laundering-in-federated-agent-directories-before-capability-warrants-cross-an-org-boundary.warrant.json
# Markdown SHA-256:   a2f5bb4cf26d6bc533419a8111e396d83f7071bd671dbdb9081c8f550b6c4bcd
# Code AST SHA-256:   ad6b51097e37047c1786ce0567e64dc62bd7fd26dd780477e063d69f6c173287
# Verified Classes:   TrustLaunderingError, Hop, Warrant
# Defensive Guards:   10 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class TrustLaunderingError(RuntimeError):
    """Raised when a brokered warrant's chain violates predicate monotonicity
    or cumulative delegation-depth accounting."""
    pass

@dataclass(frozen=True)
class Hop:
    issuer_did: str
    allowed_actions: frozenset
    data_class_ceiling: str
    revoked: bool = False

@dataclass(frozen=True)
class Warrant:
    issuance_max_depth: int
    issuance_actions: frozenset
    issuance_data_class: str
    chain: tuple = field(default_factory=tuple)  # oldest issuer first

_CLASS_RANK = {"public": 0, "internal": 1, "restricted": 2}

def validate_warrant(w: Warrant, presenting_did: str) -> None:
    if not w.chain:
        raise TrustLaunderingError("warrant has empty chain; cannot establish provenance")

    # 1. Cumulative depth, computed from chain, never from a mutable counter.
    effective_depth = len(w.chain) - 1
    if effective_depth > w.issuance_max_depth:
        raise TrustLaunderingError(
            f"cumulative depth {effective_depth} exceeds issuance max {w.issuance_max_depth}"
        )

    # 2. Direction consistency: presenting agent must be the terminal hop.
    if w.chain[-1].issuer_did != presenting_did:
        raise TrustLaunderingError(
            f"presenting DID {presenting_did} is not terminal hop {w.chain[-1].issuer_did}"
        )

    # 3. No DID may appear twice (cycle / forged ordering).
    dids = [h.issuer_did for h in w.chain]
    if len(dids) != len(set(dids)):
        raise TrustLaunderingError(f"duplicate DID in chain: {dids}")

    # 4. Predicate monotonicity: each hop must be a subset of its parent,
    #    and the root hop must be a subset of the issuance intent.
    parent_actions = w.issuance_actions
    parent_class_rank = _CLASS_RANK[w.issuance_data_class]
    for i, hop in enumerate(w.chain):
        if not hop.allowed_actions.issubset(parent_actions):
            raise TrustLaunderingError(
                f"hop {i} ({hop.issuer_did}) widens actions beyond parent"
            )
        if _CLASS_RANK[hop.data_class_ceiling] > parent_class_rank:
            raise TrustLaunderingError(
                f"hop {i} ({hop.issuer_did}) widens data_class beyond parent"
            )
        if hop.revoked:
            raise TrustLaunderingError(
                f"hop {i} ({hop.issuer_did}) is revoked; cascade invalidation required"
            )
        parent_actions = hop.allowed_actions
        parent_class_rank = _CLASS_RANK[hop.data_class_ceiling]

def broker_redelegate(parent: Warrant, broker_did: str,
                      new_actions: frozenset, new_class: str) -> Warrant:
    """Broker must re-delegate by appending to the chain, never by resetting depth."""
    if not new_actions.issubset(parent.chain[-1].allowed_actions if parent.chain else parent.issuance_actions):
        raise TrustLaunderingError("broker attempted to widen actions on re-delegation")
    if _CLASS_RANK[new_class] > _CLASS_RANK[parent.chain[-1].data_class_ceiling if parent.chain else parent.issuance_data_class]:
        raise TrustLaunderingError("broker attempted to widen data_class on re-delegation")
    if len(parent.chain) > parent.issuance_max_depth:
        raise TrustLaunderingError("broker attempted to exceed cumulative depth")
    return Warrant(
        issuance_max_depth=parent.issuance_max_depth,
        issuance_actions=parent.issuance_actions,
        issuance_data_class=parent.issuance_data_class,
        chain=parent.chain + (Hop(broker_did, new_actions, new_class),),
    )
