# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-credential-scope-laundering-across-aaif-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-credential-scope-laundering-across-aaif-agent-hops.warrant.json
# Markdown SHA-256:   270e35b5a3c7154e628c302f09e9dd140f5afc4cf105d2cf6d780ccb98582f00
# Code AST SHA-256:   4491be9e140984efadad4c939919dc89d3c9d9a54f3e32dd48602525aac5d390
# Verified Classes:   ScopeLaunderingError, Warrant
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ScopeLaunderingError(RuntimeError):
    """Raised when a delegated warrant chain composes to a scope wider than the root grant."""
    pass

@dataclass
class Warrant:
    actions: frozenset
    resources: str
    budget: Optional[int]
    max_hops: int
    root_warrant_id: str
    grammar_hash: str
    caveat_keys: frozenset = field(default_factory=frozenset)

def verify_chain(root: Warrant, chain: list[Warrant]) -> Warrant:
    if not chain:
        raise ScopeLaunderingError("empty delegation chain")
    for i, w in enumerate(chain):
        if w.root_warrant_id != root.root_warrant_id:
            raise ScopeLaunderingError(
                f"hop {i}: root_warrant_id mismatch ({w.root_warrant_id} != {root.root_warrant_id})"
            )
        if w.grammar_hash != root.grammar_hash:
            raise ScopeLaunderingError(
                f"hop {i}: resource grammar re-projected ({w.grammar_hash} != {root.grammar_hash}); "
                "subset check across grammars is unsound"
            )
        missing = root.caveat_keys - w.caveat_keys
        if missing:
            raise ScopeLaunderingError(
                f"hop {i}: dropped ancestor caveats {sorted(missing)}; "
                "absence must mean inherited, not unconstrained"
            )
        if not w.actions <= root.actions:
            raise ScopeLaunderingError(
                f"hop {i}: action widening {sorted(w.actions - root.actions)}"
            )
        if w.budget is not None and root.budget is not None and w.budget > root.budget:
            raise ScopeLaunderingError(
                f"hop {i}: budget widening ({w.budget} > {root.budget})"
            )
    # Composition fold: effective scope is the last hop, but must still be root-bounded.
    effective = chain[-1]
    if not effective.actions <= root.actions:
        raise ScopeLaunderingError("composed action scope exceeds root after fold")
    if effective.budget is None and root.budget is not None:
        raise ScopeLaunderingError(
            "composed warrant has unbounded budget but root was bounded; "
            "treat absent budget as inherited, not infinite"
        )
    return effective
