# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-delegated-token-scope-is-narrower-than-its-parent-s-cached-capability-claim.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-delegated-token-scope-is-narrower-than-its-parent-s-cached-capability-claim.warrant.json
# Markdown SHA-256:   163fda660721ac4430e747bf1727e0e01e61910d43c9cf17748683a7b060737c
# Code AST SHA-256:   79d5ef5e778512da5850435f3cd81a6a08d8fa441f0bcbe9125b81552b78a832
# Verified Classes:   ScopeClaimDivergence, InsufficientScopePermanent, DelegatedToken, CapabilityClaim
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeClaimDivergence(RuntimeError):
    """Raised when an instance's cached capability claim exceeds its delegated token scope."""
    pass


class InsufficientScopePermanent(RuntimeError):
    """insufficient_scope is structural and permanent; must not enter retry loops."""
    pass


@dataclass(frozen=True)
class DelegatedToken:
    subject: str
    scope: FrozenSet[str]          # e.g. {"filesystem.read:/repo", "git.status"}
    expires_at: float
    act_parent: str


@dataclass
class CapabilityClaim:
    """The manifest the instance loaded at cold-start, possibly copied from parent."""
    operations: FrozenSet[str]     # broader than token.scope is the bug


def reconcile_scope(claim: CapabilityClaim, token: DelegatedToken) -> FrozenSet[str]:
    """Intersect intended operations with actual token scope before plan commit."""
    effective = claim.operations & token.scope
    if effective != claim.operations:
        missing = claim.operations - token.scope
        raise ScopeClaimDivergence(
            f"instance {token.subject} plans against {sorted(missing)} "
            f"but token scope excludes them; parent={token.act_parent}. "
            f"Effective scope: {sorted(effective)}. "
            f"Re-mint from parent or narrow plan before execution."
        )
    return effective


def execute_op(op: str, token: DelegatedToken) -> None:
    if op not in token.scope:
        # Permanent structural rejection — never retry.
        raise InsufficientScopePermanent(
            f"op {op!r} not in token scope for {token.subject}; "
            f"do not retry, escalate to parent {token.act_parent}"
        )
    # ... perform op ...


def guarded_plan(claim: CapabilityClaim, token: DelegatedToken, plan: list[str]) -> None:
    effective = reconcile_scope(claim, token)          # fails fast at cold-start
    for op in plan:
        if op not in effective:
            raise ScopeClaimDivergence(
                f"plan step {op!r} outside reconciled scope {sorted(effective)}"
            )
        execute_op(op, token)
