# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-auto-compaction-checkpoint-has-silently-dropped-a-tool-result-dependency-before-resuming-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-auto-compaction-checkpoint-has-silently-dropped-a-tool-result-dependency-before-resuming-execution.warrant.json
# Markdown SHA-256:   8c0c301442fdfb2cb9ecf82b7fb787066016ea32a771b093206a8608bac75609
# Code AST SHA-256:   a234735e676ccece8cd300e1c3459a9b800b6dd27a0f4dc8bc62daea169010d6
# Verified Classes:   CheckpointDependencyError, Fact, Checkpoint
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class CheckpointDependencyError(RuntimeError):
    """Raised when a resumed agent acts on a fact whose provenance handle
    was dropped by lossy compaction and cannot be re-derived without
    re-executing a mutating (possibly non-idempotent) tool call."""


@dataclass
class Fact:
    statement: str
    source_tool_call_id: str
    status: str                       # "ok" | "partial" | "error"
    handle: Optional[str] = None      # pointer into external state store
    verbatim_output: Optional[str] = None


@dataclass
class Checkpoint:
    prose_summary: str
    fact_ledger: list[Fact] = field(default_factory=list)


# Simulated external state store: tool_call_id -> verbatim output.
# In a real system this is a durable log keyed by call ID.
EXTERNAL_STORE = {
    "tc_88": '{"status":"partial","applied":["host","port"],"skipped":["tls_ca"]}',
}


def rederive(fact: Fact) -> Optional[str]:
    """Attempt to re-derive a fact from its retained handle without
    re-executing any mutating tool. Returns output text or None."""
    if fact.handle and fact.handle in EXTERNAL_STORE:
        return EXTERNAL_STORE[fact.handle]
    if fact.verbatim_output is not None:
        return fact.verbatim_output
    return None


def reconcile_and_gate(checkpoint: Checkpoint) -> list[Fact]:
    """Walk the fact ledger. Any non-ok fact that cannot be re-derived
    from a retained handle must halt the planner before any mutating
    tool call is emitted."""
    unverified: list[Fact] = []
    for fact in checkpoint.fact_ledger:
        derived = rederive(fact)
        if derived is None and fact.status != "ok":
            unverified.append(fact)
        elif derived is None and fact.status == "ok":
            # Even "ok" facts must be re-derivable if the agent will act on them.
            unverified.append(fact)

    if unverified:
        names = ", ".join(f.statement for f in unverified)
        raise CheckpointDependencyError(
            "Resume halted: the following facts were established by tool calls "
            "whose outputs were dropped by lossy compaction and cannot be "
            "re-derived from retained handles without re-executing a mutating "
            f"operation: {names}. Re-read external state (non-mutating) to "
            "establish ground truth, then re-plan. Do NOT re-invoke the "
            "original tool."
        )
    return checkpoint.fact_ledger


def resume(checkpoint: Checkpoint) -> None:
    # Gate runs BEFORE the planner is allowed to emit any tool call.
    reconcile_and_gate(checkpoint)
    # ... planner proceeds only if every actionable fact is re-derivable.


if __name__ == "__main__":
    # The observed failure: prose summary is faithful, ledger is missing the
    # partial-success handle for tc_88.
    bad = Checkpoint(
        prose_summary="DB migrated to v7; config updated to point at new replica.",
        fact_ledger=[
            Fact("config was updated", source_tool_call_id="tc_88",
                 status="partial", handle=None, verbatim_output=None),
        ],
    )
    resume(bad)  # raises CheckpointDependencyError -> loud halt, state intact
