# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-policy-gated-context-rewrite-has-silently-orphaned-a-tool-call-dependency-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-policy-gated-context-rewrite-has-silently-orphaned-a-tool-call-dependency-chain.warrant.json
# Markdown SHA-256:   c5992c0e571bc3718bceaa02e26ffb2bf2949bb36c2ec6e051288bd83cc26b78
# Code AST SHA-256:   e5051282c1a1cd92fb9e59eaf4af3db43d0b0c2e86d7b72f29995113ba29628e
# Verified Classes:   OrphanedDependencyError, LedgerEntry, Claim
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class OrphanedDependencyError(RuntimeError):
    """Raised when a retained claim depends on a tool result no longer attested."""


@dataclass(frozen=True)
class LedgerEntry:
    handle: str
    outcome: str  # e.g. "ok:0x9f", "err:400"


@dataclass(frozen=True)
class Claim:
    text: str
    cites_handle: Optional[str]  # None if the summarizer restated as prose


def verify_claims_against_ledger(
    claims: list[Claim],
    ledger: dict[str, LedgerEntry],
    retained_handles: set[str],
) -> None:
    """
    Enforce referential closure across a policy-gated rewrite.

    A claim is actionable only if it cites a handle that is (a) present in the
    retained context and (b) attested in the ledger with a matching outcome.
    Anything else is an orphan and must not drive a side-effecting call.
    """
    for claim in claims:
        if claim.cites_handle is None:
            raise OrphanedDependencyError(
                f"Unattested prose claim (no handle): {claim.text!r}; "
                "downgrade to hypothesis and re-execute producer."
            )
        if claim.cites_handle not in retained_handles:
            raise OrphanedDependencyError(
                f"Claim cites handle {claim.cites_handle!r} evicted from context: "
                f"{claim.text!r}; roll back to pre-rewrite checkpoint."
            )
        entry = ledger.get(claim.cites_handle)
        if entry is None:
            raise OrphanedDependencyError(
                f"Handle {claim.cites_handle!r} absent from ledger; "
                "claim is fabricated and must be re-derived."
            )
        # Outcome consistency is checked by the caller against the claim's
        # asserted outcome; a mismatch here is a rewrite corruption.
        if entry.outcome.startswith("err") and "succeeded" in claim.text.lower():
            raise OrphanedDependencyError(
                f"Claim asserts success but ledger records {entry.outcome!r} "
                f"for handle {claim.cites_handle!r}."
            )
