# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-whose-policy-hash-matches-but-whose-bounding-predicate-is-evaluated-against-a-stale-peer-snapshot.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-whose-policy-hash-matches-but-whose-bounding-predicate-is-evaluated-against-a-stale-peer-snapshot.warrant.json
# Markdown SHA-256:   a52d4e34702898c7fb71d60b011aab9904efaf822781700849ac0af21def19f2
# Code AST SHA-256:   3407082c7620844ea9b4a0b45556aee7d348de7141da96d8422375c40ba420b1
# Verified Classes:   DelegationUnverifiable, Grant, LocalSnapshot
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DelegationUnverifiable(RuntimeError):
    """Raised when a delegated capability's bounding predicate cannot be
    evaluated against a snapshot that is transitively committed by the
    grant's policy hash. Admission must be refused; the grant must be
    re-issued with a pinned annex_digest."""
    pass


@dataclass(frozen=True)
class Grant:
    cap: str
    policy_hash: str          # H(policy text); may or may not cover annex
    annex_digest: str | None  # None => annex outside hash closure (C2)
    authorization_epoch: int
    predicate: str


@dataclass(frozen=True)
class LocalSnapshot:
    policy_hash: str
    annex_digest: str
    annex_epoch: int


def _digest(s: str) -> str:
    return "sha256:" + hashlib.sha256(s.encode()).hexdigest()


def admit(grant: Grant, snap: LocalSnapshot) -> bool:
    # Clause 1: cryptographic binding of policy text.
    if grant.policy_hash != snap.policy_hash:
        raise DelegationUnverifiable(
            f"policy hash mismatch for {grant.cap}: "
            f"grant={grant.policy_hash} local={snap.policy_hash}"
        )

    # Clause 2: epoch monotonicity — snapshot must not predate authorization.
    if snap.annex_epoch < grant.authorization_epoch:
        # Recoverable only if the annex is committed by the hash.
        if grant.annex_digest is None:
            raise DelegationUnverifiable(
                f"stale-and-uncommitted annex for {grant.cap}: "
                f"annex_epoch={snap.annex_epoch} < "
                f"authorization_epoch={grant.authorization_epoch}, "
                f"and grant carries no annex_digest"
            )
        # Committed: refetch is safe, caller should retry.
        return False

    # Clause 3: annex must be transitively committed by the policy hash.
    if grant.annex_digest is None:
        raise DelegationUnverifiable(
            f"unverifiable-delegation for {grant.cap}: grant format does not "
            f"commit to annex_digest; predicate dereferences mutable annex "
            f"outside hash closure"
        )
    if grant.annex_digest != snap.annex_digest:
        raise DelegationUnverifiable(
            f"annex digest mismatch for {grant.cap}: "
            f"grant={grant.annex_digest} local={snap.annex_digest}"
        )

    return True


# Trace of the observed incident:
grant = Grant(
    cap="purchase.commit",
    policy_hash=_digest("procurement-policy-v3"),
    annex_digest=None,                     # C2: annex outside hash closure
    authorization_epoch=20250601,
    predicate="amount <= annex.max_txn and account.tier == 'gold'",
)
snap_v7 = LocalSnapshot(
    policy_hash=_digest("procurement-policy-v3"),
    annex_digest=_digest("annex@v7"),
    annex_epoch=20250601,
)

# Naive verifier admits (hash matches, predicate against v7 passes).
# Correct verifier refuses:
try:
    admit(grant, snap_v7)
except DelegationUnverifiable as e:
    assert "unverifiable-delegation" in str(e)
