# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-model-driven-context-rewriting-as-a-lossy-non-commutative-transform-that-invalidates-prior-tool-call-prov.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-model-driven-context-rewriting-as-a-lossy-non-commutative-transform-that-invalidates-prior-tool-call-prov.warrant.json
# Markdown SHA-256:   eff89e51a70101e332e5b8221a3c55643f8153908a7788179b7586be8b1d9a84
# Code AST SHA-256:   368e26c2db2ec752ad4eb4f076f3c4265d79481da699c58db727ee146c0de370
# Verified Classes:   ProvenanceError, Consumption, ToolCallRecord, ShadowLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional


class ProvenanceError(RuntimeError):
    """Raised when a self-edited context cannot substantiate a claim of retrieval."""
    pass


class Consumption(Enum):
    UNCONSUMED = "acknowledged_but_unconsumed"
    CONSUMED = "body_read_into_context"
    FAILED = "call_failed"


@dataclass
class ToolCallRecord:
    call_id: str
    outcome: str                 # e.g. "200", "404", "timeout"
    consumption: Consumption
    body_digest: Optional[str]   # None if body never entered context


@dataclass
class ShadowLedger:
    """External, rewriter-immutable log. The self-editing model may not write here."""
    records: Dict[str, ToolCallRecord] = field(default_factory=dict)

    def record(self, rec: ToolCallRecord) -> None:
        self.records[rec.call_id] = rec

    def get(self, call_id: str) -> ToolCallRecord:
        if call_id not in self.records:
            raise ProvenanceError(
                f"tool-call {call_id} absent from ledger; cannot verify claim"
            )
        return self.records[call_id]


def reconcile_rewrite(
    ledger: ShadowLedger,
    summary_claims: List[str],       # call_ids the summary asserts were retrieved
    rewrite_depth: int,
) -> List[str]:
    """
    Gate a model-authored context rewrite against the shadow ledger.
    Returns call_ids that must be re-fetched before the agent may plan on them.
    """
    if rewrite_depth > 1:
        raise ProvenanceError(
            f"rewrite depth {rewrite_depth} exceeds bound; evidence spans may "
            f"have compounded unverifiable confidence across summaries"
        )

    must_refetch: List[str] = []
    for call_id in summary_claims:
        rec = ledger.get(call_id)  # raises if summary invented the call
        if rec.consumption is Consumption.UNCONSUMED:
            # The summary says "retrieved"; the ledger says "never read".
            # The agent must NOT cite this; it must re-issue the call.
            must_refetch.append(call_id)
        elif rec.consumption is Consumption.FAILED:
            raise ProvenanceError(
                f"summary asserts retrieval of {call_id} but ledger records failure "
                f"({rec.outcome}); rewrite has inverted an outcome"
            )
        # CONSUMED with matching digest is the only cite-eligible state.
        elif rec.body_digest is None:
            raise ProvenanceError(
                f"{call_id} marked consumed but carries no body digest; "
                f"provenance record is internally inconsistent"
            )
    return must_refetch


def resume_subgoal(
    ledger: ShadowLedger,
    summary_claims: List[str],
    rewrite_depth: int,
    plan_depends_on_body: bool,
) -> None:
    """Checked resume transition. Raises rather than planning on unverified evidence."""
    refetch = reconcile_rewrite(ledger, summary_claims, rewrite_depth)
    if plan_depends_on_body and refetch:
        raise ProvenanceError(
            f"subgoal plan requires body tokens but {len(refetch)} call(s) "
            f"were only acknowledged: {refetch}. Re-issue before planning."
        )
