# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-capability-token-as-invalid-the-moment-its-own-context-is-compacted-or-re-summarized.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-capability-token-as-invalid-the-moment-its-own-context-is-compacted-or-re-summarized.warrant.json
# Markdown SHA-256:   e0833e0f67e4525968fea845101920bc1d7aa200662ebfbefdf45fc6c7d8d99c
# Code AST SHA-256:   efb7a133be3474d8ce14f0052f762d67954ad2912e7969df3e105e4a434bef94
# Verified Classes:   OrphanedCapabilityError, CapabilityToken, DelegationProvenance
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class OrphanedCapabilityError(RuntimeError):
    """Raised when a capability token survives a context discontinuity but its
    narrowing intent does not, leaving its effective authority undefined."""
    pass


@dataclass
class CapabilityToken:
    token_id: str
    delegator: str
    declared_scope: frozenset          # machine-checkable, e.g. {"fs:write"}
    encoded_constraints: dict          # enforced by tool layer, e.g. {"path_glob": "/workspace/staging/**"}
    requires_reaffirmation: bool = False

    def fingerprint(self) -> str:
        raw = f"{self.token_id}|{self.delegator}|{sorted(self.declared_scope)}|{sorted(self.encoded_constraints.items())}"
        return hashlib.sha256(raw.encode()).hexdigest()


@dataclass
class DelegationProvenance:
    """Persisted OUTSIDE the compactable context window."""
    token_fingerprint: str
    delegator: str
    encoded_constraints: dict
    prose_only_constraints: list = field(default_factory=list)  # constraints that could NOT be encoded


def verify_after_discontinuity(token: CapabilityToken,
                              provenance: DelegationProvenance | None,
                              context_was_compacted: bool) -> None:
    if not context_was_compacted:
        return  # no boundary crossed; normal path

    if provenance is None:
        raise OrphanedCapabilityError(
            f"Token {token.token_id} exercised after compaction with no persisted "
            f"delegation provenance; narrowing intent is unrecoverable."
        )

    if provenance.token_fingerprint != token.fingerprint():
        raise OrphanedCapabilityError(
            f"Token {token.token_id} fingerprint does not match persisted provenance; "
            f"token may have been substituted or re-minted across the boundary."
        )

    if provenance.prose_only_constraints:
        raise OrphanedCapabilityError(
            f"Token {token.token_id} carried {len(provenance.prose_only_constraints)} "
            f"prose-only narrowing constraint(s) that compaction may have dropped "
            f"({provenance.prose_only_constraints}). Refusing exercise; re-delegate."
        )

    if token.requires_reaffirmation:
        raise OrphanedCapabilityError(
            f"Token {token.token_id} is flagged requires_reaffirmation; a re-delegation "
            f"handshake is mandatory after any context discontinuity."
        )
