# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-warrant-it-cannot-re-verify-the-transitive-attenuation-gap-in-agent-delegation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-warrant-it-cannot-re-verify-the-transitive-attenuation-gap-in-agent-delegation-chains.warrant.json
# Markdown SHA-256:   c820f136783b1a5d8f927dafe1e0269c60b629d3af1e9abb701711cd39fb136d
# Code AST SHA-256:   b4f7096ae2bb10f468ad6e905f1a4812fb9f35ce4ceb6411ddd9ec30d85b33f9
# Verified Classes:   TransitiveAttenuationGap, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TransitiveAttenuationGap(RuntimeError):
    """Raised when a terminal agent cannot recompute containment W_C ⊆ W_B ⊆ W_A
    from artifacts alone and must refuse rather than trust an intermediate's
    self-reported scope."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    resources: FrozenSet[str]
    token_budget: int
    parent: "Warrant | None" = None  # embedded parent artifact, not a hash ref
    parent_hash_only: bool = False   # set True when only a reference is available


def atten(parent: Warrant, requested: FrozenSet[str], budget: int) -> Warrant:
    """Deterministic attenuation: child scope is intersection of parent scope
    with requested scope. This is the function the terminal agent re-runs."""
    return Warrant(
        issuer=parent.subject,
        subject="<child>",
        resources=parent.resources & requested,
        token_budget=min(parent.token_budget, budget),
        parent=parent,
    )


def verify_chain(terminal: Warrant) -> None:
    """Verify containment at every hop by recomputation, not by trust.

    Raises TransitiveAttenuationGap if any hop's containment cannot be
    recomputed from embedded artifacts.
    """
    node = terminal
    while node.parent is not None:
        parent = node.parent
        if node.parent_hash_only:
            raise TransitiveAttenuationGap(
                f"hop {parent.issuer}->{node.issuer}: parent referenced by hash "
                f"only; containment {node.resources} ⊆ {parent.resources} is "
                f"unverifiable at this hop. Refusing."
            )
        # Recompute the attenuation the intermediate claims to have performed.
        # The requested scope is recoverable as the child's own resource set
        # only if the child is a subset; if not, the intermediate over-granted.
        if not node.resources.issubset(parent.resources):
            raise TransitiveAttenuationGap(
                f"hop {parent.issuer}->{node.issuer}: child resources "
                f"{sorted(node.resources)} are NOT a subset of parent "
                f"{sorted(parent.resources)}. Intermediate over-attenuated "
                f"against a drifted belief of its own warrant. Refusing."
            )
        if node.token_budget > parent.token_budget:
            raise TransitiveAttenuationGap(
                f"hop {parent.issuer}->{node.issuer}: child budget "
                f"{node.token_budget} exceeds parent {parent.token_budget}."
            )
        node = parent


def delegate(parent: Warrant, requested: FrozenSet[str], budget: int) -> Warrant:
    """Safe delegation: compute child by artifact-attenuation, embed parent."""
    child = atten(parent, requested, budget)
    # Re-verify before emitting: catch our own drift at issue time.
    verify_chain(child)
    return child


# Demonstration of the failure the invariant catches:
root = Warrant(issuer="planner", subject="retriever",
               resources=frozenset({"P1", "P2", "P3", "P4", "P5"}),
               token_budget=80_000)

# Retriever's context saturated; it "remembers" it can read P1..P8 and
# attenuates against that drifted belief instead of the signed artifact.
drifted_child = Warrant(issuer="retriever", subject="summarizer",
                        resources=frozenset({"P3", "P4", "P5", "P6", "P7", "P8"}),
                        token_budget=30_000, parent=root)

try:
    verify_chain(drifted_child)
except TransitiveAttenuationGap as e:
    print(f"REFUSED: {e}")

# Correct path: artifact-attenuation produces a verifiable child.
safe_child = delegate(root, frozenset({"P3", "P4", "P5"}), 30_000)
verify_chain(safe_child)
print(f"ACCEPTED: {sorted(safe_child.resources)}")
