# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-warrant-it-only-holds-as-attenuated-scope-the-transitive-attenuation-collapse-in-aaif-credential-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-warrant-it-only-holds-as-attenuated-scope-the-transitive-attenuation-collapse-in-aaif-credential-chains.warrant.json
# Markdown SHA-256:   88a2a58882712941616c30e574264bc2216ced030fe2c098bea664a9d4a377f7
# Code AST SHA-256:   0824770a1ffdca7a6bf6ad9b49419cbe0dbd0cfb3924854c633ca8ae7bbcf388
# Verified Classes:   ConstraintFoldViolation, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ConstraintFoldViolation(RuntimeError):
    """Raised when an action exceeds the constraints composed across an AAIF chain,
    even though every individual warrant in the chain verifies."""


@dataclass
class Warrant:
    issuer: str
    subject: str
    scope_set: frozenset[str]
    constraints: dict[str, int] = field(default_factory=dict)
    expires: int = 0
    parent_hash: Optional[str] = None
    signature_valid: bool = True


def fold_chain(chain: list[Warrant]) -> tuple[frozenset[str], dict[str, int], int]:
    """Fold root->leaf. Scope intersects; numeric constraints take the min
    (absolute-budget semantics); expiry takes the min."""
    if not chain:
        raise ConstraintFoldViolation("empty chain cannot be folded")
    scope = chain[0].scope_set
    constraints: dict[str, int] = dict(chain[0].constraints)
    expires = chain[0].expires
    for w in chain[1:]:
        scope = scope & w.scope_set
        for k, v in w.constraints.items():
            constraints[k] = min(constraints.get(k, v), v)
        expires = min(expires, w.expires)
    return scope, constraints, expires


def authorize(chain: list[Warrant], action_scope: str, action_params: dict[str, int], now: int) -> None:
    for w in chain:
        if not w.signature_valid:
            raise ConstraintFoldViolation(f"signature invalid at {w.issuer}->{w.subject}")
    scope, constraints, expires = fold_chain(chain)
    if now > expires:
        raise ConstraintFoldViolation("folded chain expired")
    if action_scope not in scope:
        raise ConstraintFoldViolation(f"action scope {action_scope!r} not in folded scope")
    for k, v in action_params.items():
        if k in constraints and v > constraints[k]:
            raise ConstraintFoldViolation(
                f"action param {k}={v} exceeds folded constraint {constraints[k]}"
            )


# Reproduces the observed failure: W1 constrains max_targets=2, W2/W3 drop it,
# leaf-only checking passes, fold rejects the third deploy.
w1 = Warrant("did:root", "did:planner", frozenset({"read:repo", "write:repo", "deploy:staging"}),
             {"max_targets": 2}, expires=1000)
w2 = Warrant("did:planner", "did:executor", frozenset({"write:repo", "deploy:staging"}),
             {}, expires=900, parent_hash="h1")
w3 = Warrant("did:executor", "did:worker", frozenset({"deploy:staging"}),
             {}, expires=800, parent_hash="h2")
chain = [w1, w2, w3]

# Leaf-only check (the buggy path) would pass this:
#   w3.scope_set contains deploy:staging, w3.constraints empty -> VALID
# Folded check rejects it:
authorize(chain, "deploy:staging", {"max_targets": 3}, now=500)  # raises ConstraintFoldViolation
