# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-when-hierarchical-summarization-compacts-a-mid-task-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-when-hierarchical-summarization-compacts-a-mid-task-context-window.warrant.json
# Markdown SHA-256:   c76d4455b20ec179692ebe0212d4eb98ff5fb7c19ea119f04d3cfa9da2c55f34
# Code AST SHA-256:   2ab5ae60222ab86a960da3c127296f970395d7fb682ceb5d152b0d9ff2af51fc
# Verified Classes:   ProvenanceLossError, Provenance, PinnedLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ProvenanceLossError(RuntimeError):
    """Raised when a mutating tool call is re-derived from a summary
    with no surviving provenance tuple. The agent must halt and
    re-establish ground truth before proceeding."""
    pass


@dataclass(frozen=True)
class Provenance:
    tool: str
    args_hash: str
    step_index: int
    result_status: str


@dataclass
class PinnedLedger:
    # Survives compaction byte-for-byte; never summarized.
    entries: dict = field(default_factory=dict)

    def record(self, tool: str, args: dict, step: int, status: str) -> Provenance:
        h = hashlib.sha256(
            json.dumps(args, sort_keys=True).encode()
        ).hexdigest()
        p = Provenance(tool, h, step, status)
        self.entries[(tool, step)] = p
        return p

    def lookup(self, tool: str, step: int) -> Provenance | None:
        return self.entries.get((tool, step))


def rederive_mutation(
    ledger: PinnedLedger,
    tool: str,
    step: int,
    candidate_args: dict,
) -> Provenance:
    """Called when the agent wants to re-issue a mutating call it believes
    it already made, based on a compacted prose summary."""
    prior = ledger.lookup(tool, step)
    if prior is None:
        raise ProvenanceLossError(
            f"No provenance for {tool}@step{step}; summary-only belief. "
            f"Halt and re-read ground truth before mutating."
        )
    cand_hash = hashlib.sha256(
        json.dumps(candidate_args, sort_keys=True).encode()
    ).hexdigest()
    if cand_hash != prior.args_hash:
        raise ProvenanceLossError(
            f"Re-derived args for {tool}@step{step} diverge from recorded "
            f"hash {prior.args_hash[:12]} (got {cand_hash[:12]}). "
            f"Summary paraphrase is not idempotent with original call."
        )
    return prior
