# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-its-capability-scope-after-an-aaif-token-is-attenuated-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-its-capability-scope-after-an-aaif-token-is-attenuated-mid-handoff.warrant.json
# Markdown SHA-256:   1a2dc5c7a077bf9808e318d29d9daa65e05fd830f957004a483fe6338cdf1d85
# Code AST SHA-256:   ed5d421d8cd398d41b8e9f00bc2435479086be8fb0386594fb1595903411349a
# Verified Classes:   ScopeInsufficiencyError, AAIFToken, ScopeResolutionGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeInsufficiencyError(RuntimeError):
    """Raised when an agent's effective scope cannot satisfy its planned capabilities."""
    pass


@dataclass(frozen=True)
class AAIFToken:
    subject: str
    scope: FrozenSet[str]
    attenuation_chain: tuple = field(default_factory=tuple)  # parent scopes, outermost first
    depth: int = 0

    def effective_scope(self) -> FrozenSet[str]:
        # Effective scope is the intersection of the leaf scope and every ancestor.
        effective = set(self.scope)
        for ancestor_scope in self.attenuation_chain:
            effective &= set(ancestor_scope)
        return frozenset(effective)


class ScopeResolutionGate:
    """Sits between the reasoning loop and any durable state commitment."""

    def __init__(self, token: AAIFToken):
        self.token = token
        self._resolved = token.effective_scope()

    def assert_plan_admissible(self, planned_capabilities: FrozenSet[str]) -> None:
        missing = planned_capabilities - self._resolved
        if missing:
            raise ScopeInsufficiencyError(
                f"subject={self.token.subject} depth={self.token.depth} "
                f"planned={sorted(planned_capabilities)} "
                f"effective={sorted(self._resolved)} "
                f"missing={sorted(missing)} "
                f"-- refusing to commit state under unconfirmed capability"
            )

    def commit_checkpoint(self, planned_capabilities: FrozenSet[str], payload: dict) -> dict:
        # Gate runs BEFORE any mutation; no phantom verification can be written.
        self.assert_plan_admissible(planned_capabilities)
        return {"status": "committed", "subject": self.token.subject, "payload": payload}

    def on_token_refresh(self, new_token: AAIFToken) -> None:
        # Scope drift guard: re-derive on every refresh, not only initial receipt.
        self.token = new_token
        self._resolved = new_token.effective_scope()
        if self._resolved < self.token.effective_scope():
            raise ScopeInsufficiencyError(
                f"scope drift detected on refresh for subject={self.token.subject}"
            )
