# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-reject-a-valid-delegated-capability-token-after-a-context-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-reject-a-valid-delegated-capability-token-after-a-context-compaction-boundary.warrant.json
# Markdown SHA-256:   a85d9a85a94088721df3da7d91d9d4934e90ab7da2d9527eae755c1ad8a46b7c
# Code AST SHA-256:   e9eac2ab07971967deacff51284200ee976578551bd13e5cde35633c0c72a82c
# Verified Classes:   ScopeAssertionMismatch, CapabilityEnvelope, Hop
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeAssertionMismatch(RuntimeError):
    """Agent's remembered scope diverged from the signed envelope's scope.

    Raised when a tool call asserts a scope set that is not provable from the
    token envelope. This is a *memory corruption* signal, not a policy denial:
    the caller should re-fetch the envelope and recompute, not retry blindly.
    """


@dataclass(frozen=True)
class CapabilityEnvelope:
    chain: tuple  # ordered root -> leaf; each element has .scope (frozenset)
    leaf_token_id: str

    def effective_scope(self) -> FrozenSet[str]:
        # Pure function of the signed envelope. No agent memory consulted.
        acc = self.chain[0].scope
        for hop in self.chain[1:]:
            acc = acc & hop.scope
        return frozenset(acc)


def authorize(
    envelope: CapabilityEnvelope,
    asserted_scope: FrozenSet[str],
    operation: str,
) -> None:
    """Strict verifier: recompute from envelope, compare to assertion, then decide.

    Ordering matters. We check assertion-vs-envelope FIRST so that a compacted
    agent model is reported as SCOPE_ASSERTION_MISMATCH (recoverable: re-fetch
    envelope) rather than SCOPE_VIOLATION (looks like a policy denial and
    triggers the retry-storm pathology).
    """
    derived = envelope.effective_scope()

    if frozenset(asserted_scope) != derived:
        raise ScopeAssertionMismatch(
            f"token {envelope.leaf_token_id}: agent asserted scope "
            f"{sorted(asserted_scope)} but envelope proves {sorted(derived)}; "
            f"likely context-compaction lost an attenuation hop — re-fetch "
            f"envelope and recompute, do not retry the operation."
        )

    if operation not in derived:
        # Genuine policy denial: the envelope itself does not grant this.
        raise PermissionError(
            f"token {envelope.leaf_token_id}: operation {operation!r} "
            f"not in envelope-derived scope {sorted(derived)}"
        )


# --- failure trace reproduction -------------------------------------------

@dataclass(frozen=True)
class Hop:
    principal: str
    scope: FrozenSet[str]


def _demo() -> None:
    root = Hop("O", frozenset({"read:repo", "write:repo", "exec:test", "read:secrets"}))
    planner = Hop("P", frozenset({"read:repo", "write:repo", "exec:test"}))  # drops secrets
    executor = Hop("E", frozenset({"read:repo", "exec:test"}))               # drops write
    env = CapabilityEnvelope(chain=(root, planner, executor), leaf_token_id="tok_E_41")

    # Correct path: agent recomputes from envelope.
    authorize(env, env.effective_scope(), "read:repo")  # ok

    # Compaction pathology: summary said "repo rights", agent asserts a superset.
    corrupted_assertion = frozenset({"read:repo", "write:repo", "exec:test"})
    try:
        authorize(env, corrupted_assertion, "write:repo")
    except ScopeAssertionMismatch as e:
        print(f"[recoverable] {e}")

    # Subset pathology: agent under-asserts and refuses authorized work.
    under_assertion = frozenset({"read:repo"})
    try:
        authorize(env, under_assertion, "exec:test")
    except ScopeAssertionMismatch as e:
        print(f"[recoverable] {e}")


if __name__ == "__main__":
    _demo()
