# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-capability-scope-attenuation-leakage-when-a-delegated-aaif-token-is-re-minted-across-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-capability-scope-attenuation-leakage-when-a-delegated-aaif-token-is-re-minted-across-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   b51537050dfd12c018fdae2df67071b9814789277e2be7a6dcdfcce8de5e4e29
# Code AST SHA-256:   f2e7d1610d7d4c47954b25dec81c9c3ddc32c2478f9dae0e06508c1ea7775818
# Verified Classes:   CapabilityShortfallError, DelegatedToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CapabilityShortfallError(RuntimeError):
    """Raised when a delegated token's declared intent requires capabilities
    that its own capability set does not contain. This is a scope shortfall,
    not a transient authorization fault, and MUST NOT be retried."""

    def __init__(self, token_id: str, missing: frozenset[str], intent: str):
        self.token_id = token_id
        self.missing = missing
        self.intent = intent
        super().__init__(
            f"token {token_id!r} intent {intent!r} requires {sorted(missing)} "
            f"which are absent from its capability set; retry is guaranteed to fail"
        )


@dataclass(frozen=True)
class DelegatedToken:
    token_id: str
    capabilities: frozenset[str]
    declared_intent: str
    required_for_intent: frozenset[str]  # derived from intent at mint time
    parent_id: str | None = None


def check_intent_satisfiability(token: DelegatedToken) -> None:
    """Pre-use guard. Run once per token at first presentation, before any
    tool call. Converts a silent attenuation leak into a typed, non-retryable
    failure carrying the exact shortfall set."""
    missing = token.required_for_intent - token.capabilities
    if missing:
        raise CapabilityShortfallError(
            token_id=token.token_id,
            missing=frozenset(missing),
            intent=token.declared_intent,
        )


def recompute_child_intent(
    parent: DelegatedToken,
    child_capabilities: frozenset[str],
    child_required: frozenset[str],
) -> frozenset[str]:
    """Bounding strategy: recompute the child's required set against the
    parent's RESIDUAL capabilities, not the parent's declared intent. Forces
    the shortfall to surface at mint time with full context to escalate."""
    if not child_capabilities <= parent.capabilities:
        raise CapabilityShortfallError(
            token_id="<mint>",
            missing=frozenset(child_capabilities - parent.capabilities),
            intent="child exceeds parent scope",
        )
    residual = parent.capabilities & child_capabilities
    if not child_required <= residual:
        raise CapabilityShortfallError(
            token_id="<mint>",
            missing=frozenset(child_required - residual),
            intent=parent.declared_intent,
        )
    return child_required


def guarded_tool_call(token: DelegatedToken, call: callable) -> object:
    # Gate retries on satisfiability, not on the raw denial.
    check_intent_satisfiability(token)
    return call()
