# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-attenuated-capability-delegation-chains-when-audit-linked-proofs-outlive-the-delegating-agent-s-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-attenuated-capability-delegation-chains-when-audit-linked-proofs-outlive-the-delegating-agent-s-context.warrant.json
# Markdown SHA-256:   5314a60193f1b3416482a31fc010edcd8462fb4e43b3055f69c27cce42056799
# Code AST SHA-256:   d33f172688e60bdffe51f58720ce62cac77f7ae91c832dc1be25450126000c2f
# Verified Classes:   ProofUnreplayableError, ScopeAttenuationViolation, Receipt, DelegationToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProofUnreplayableError(RuntimeError):
    """Raised when an attenuated delegation's proof anchor cannot be fully replayed."""


class ScopeAttenuationViolation(RuntimeError):
    """Raised when a child scope is not a subset of its parent scope."""


@dataclass
class Receipt:
    receipt_id: str
    context_slice: Optional[bytes]
    cited_by: set = field(default_factory=set)

    def digest(self) -> bytes:
        if self.context_slice is None:
            raise ProofUnreplayableError(
                f"receipt {self.receipt_id} has evicted context_slice; cannot recompute digest"
            )
        return hashlib.sha256(self.context_slice).digest()


@dataclass
class DelegationToken:
    token_id: str
    scope: frozenset
    parent_scope: frozenset
    proof_anchor: str
    proof_context_digest: bytes


def verify_delegation(
    token: DelegationToken,
    receipts: dict,
    strict_attenuation: bool = True,
) -> None:
    # 1. Scope attenuation must be monotone.
    if not token.scope.issubset(token.parent_scope):
        raise ScopeAttenuationViolation(
            f"{token.token_id}: scope {token.scope} not subset of {token.parent_scope}"
        )

    attenuating = token.scope < token.parent_scope

    # 2. Resolve the proof anchor. A stub is NOT a pass.
    receipt = receipts.get(token.proof_anchor)
    if receipt is None:
        raise ProofUnreplayableError(
            f"{token.token_id}: proof anchor {token.proof_anchor} unresolvable"
        )

    # 3. Fail-closed on any missing context slice when attenuation is claimed.
    if receipt.context_slice is None:
        if attenuating and strict_attenuation:
            raise ProofUnreplayableError(
                f"{token.token_id}: attenuated scope requires live proof, "
                f"but {receipt.receipt_id}.context_slice is evicted"
            )
        # Non-attenuating + non-strict: explicitly tolerated, but flagged.
        return

    # 4. Digest must recompute exactly; re-derivation is a new proof, not a repair.
    if receipt.digest() != token.proof_context_digest:
        raise ProofUnreplayableError(
            f"{token.token_id}: proof digest mismatch for {receipt.receipt_id}"
        )

    # 5. Pin liveness: this receipt is now cited and must not be GC'd.
    receipt.cited_by.add(token.token_id)


def release_delegation(token: DelegationToken, receipts: dict) -> None:
    receipt = receipts.get(token.proof_anchor)
    if receipt is not None:
        receipt.cited_by.discard(token.token_id)
