# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-capability-token-across-a-context-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-capability-token-across-a-context-compaction-boundary.warrant.json
# Markdown SHA-256:   f339ab9cc5b3b28be3f4abc750d550f4420363a278e23b1c3615266f063cfcdd
# Code AST SHA-256:   4c02ff289fdbc3c062a133812f1b8a0ec6f3378e848fe5ce6f8815790f8a4f5a
# Verified Classes:   DelegationProvenanceError, CapabilityToken, ResumedAgentState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationProvenanceError(RuntimeError):
    """Raised when a resumed agent holds a token whose narrowing
    constraints are not recoverable from signed material alone."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    verbs: FrozenSet[str]
    parent_sig: str
    ttl_s: int
    # Constraints that survived INTO the token (signed, compaction-proof)
    signed_constraints: FrozenSet[str] = field(default_factory=frozenset)


@dataclass(frozen=True)
class ResumedAgentState:
    token: CapabilityToken
    # Constraints that lived only in context and may have been evicted
    contextual_constraints: FrozenSet[str]


def authorize_on_resume(state: ResumedAgentState, requested_verb: str) -> None:
    token = state.token

    if requested_verb not in token.verbs:
        raise DelegationProvenanceError(
            f"verb {requested_verb!r} not in token scope {sorted(token.verbs)}"
        )

    # The invariant: every restriction that applied at mint time must be
    # reconstructable from signed material. Contextual constraints are
    # treated as UNTRUSTED after a compaction boundary -- we cannot know
    # whether they survived, so we cannot rely on them to narrow scope.
    contextual_only = state.contextual_constraints - token.signed_constraints
    if contextual_only:
        raise DelegationProvenanceError(
            "resume blocked: token scope is wider than intent; the following "
            f"narrowing constraints are not signed into the token and may have "
            f"been evicted by compaction: {sorted(contextual_only)}. "
            "Re-attenuate to precise verbs or re-attest to parent before acting."
        )


def demo() -> None:
    # Parent intended "dry-run only" but minted a coarse deploy verb and
    # carried "dry-run only" only in context.
    coarse = CapabilityToken(
        verbs=frozenset({"repo:read", "deploy:staging"}),
        parent_sig="sig:abc",
        ttl_s=900,
        signed_constraints=frozenset(),
    )
    resumed = ResumedAgentState(
        token=coarse,
        contextual_constraints=frozenset({"dry-run only"}),
    )
    authorize_on_resume(resumed, "deploy:staging")  # raises


if __name__ == "__main__":
    demo()
