# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-across-compaction-checkpoints-while-claiming-fidelity-recovery.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-across-compaction-checkpoints-while-claiming-fidelity-recovery.warrant.json
# Markdown SHA-256:   364af6f2faab326083a66627914ee89dc09ab652b19463e14256b14388ebe276
# Code AST SHA-256:   1b6b94dc8538e9916c11d7cef3933983703fcbc3e4fcc0d75984ce0aa5f74b68
# Verified Classes:   ProvenanceFidelityError, ActionRecord, Checkpoint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceFidelityError(RuntimeError):
    """Raised when a checkpoint claims fidelity recovery but cannot prove
    action-safety provenance for a side-effecting action."""
    pass


@dataclass
class ActionRecord:
    name: str
    idempotency_key: Optional[str]
    applied: bool
    outcome: str


@dataclass
class Checkpoint:
    summary: str
    # Propositional fidelity: summary entails verbatim log. Measured by sampling.
    propositional_fidelity: float
    # Provenance ledger: never summarized, only age-truncated with a hard floor.
    action_ledger: dict[str, ActionRecord] = field(default_factory=dict)


def authorize_reissue(cp: Checkpoint, action_name: str) -> bool:
    """Decide whether a side-effecting action described in the summary may be
    re-issued. Propositional fidelity is necessary but NOT sufficient."""
    if cp.propositional_fidelity < 0.95:
        # Summary is not even trustworthy for belief; do not act.
        raise ProvenanceFidelityError(
            f"propositional fidelity {cp.propositional_fidelity:.2f} below floor"
        )

    rec = cp.action_ledger.get(action_name)
    if rec is None:
        # The summary may mention this action, but the ledger — the only
        # source of action-safety provenance — has no record. The guarantee
        # is scoped to propositions and says nothing here. Refuse.
        raise ProvenanceFidelityError(
            f"action '{action_name}' appears in summary but has no ledger "
            f"record; provenance compacted away, re-issue unsafe"
        )

    if rec.idempotency_key is None:
        raise ProvenanceFidelityError(
            f"action '{action_name}' has no idempotency key; cannot prove "
            f"re-issue is safe even though summary is faithful"
        )

    if rec.applied and rec.outcome != "rejected":
        # Already applied and not rolled back: re-issuing duplicates state.
        raise ProvenanceFidelityError(
            f"action '{action_name}' already applied (outcome={rec.outcome!r}); "
            f"summary's 'verified' proposition omits the prior failure/retry path"
        )

    return True
