# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-introduced-by-its-own-lossy-compaction-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-introduced-by-its-own-lossy-compaction-checkpoint.warrant.json
# Markdown SHA-256:   059ca6db6e33e430bce8f263663f245e1432b4dace7e693efae8ffb791e2e951
# Code AST SHA-256:   e32c6ee7790168fe42f9d103d21b30d6b5606070ba6acaccdab3eb9a2765d962
# Verified Classes:   CompactionDriftError, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CompactionDriftError(RuntimeError):
    """Raised when a resumed instance acts on a literal that the checkpoint
    cannot verify against its pinned ledger or the live environment."""
    pass


@dataclass
class Checkpoint:
    narrative: str                      # lossy summary, derived state
    pinned_facts: dict                  # verbatim literals/negations, copied not paraphrased
    pinned_hash: str                    # hash over pinned_facts at creation time
    provenance: str = "derived"         # never "observed"


def make_checkpoint(narrative: str, pinned_facts: dict) -> Checkpoint:
    blob = repr(sorted(pinned_facts.items())).encode()
    return Checkpoint(
        narrative=narrative,
        pinned_facts=dict(pinned_facts),
        pinned_hash=hashlib.sha256(blob).hexdigest(),
    )


def verify_checkpoint_integrity(cp: Checkpoint) -> None:
    blob = repr(sorted(cp.pinned_facts.items())).encode()
    if hashlib.sha256(blob).hexdigest() != cp.pinned_hash:
        raise CompactionDriftError(
            "pinned ledger hash mismatch: checkpoint was truncated or mutated "
            "after creation; refusing to resume on derived state alone"
        )


def assert_literal_verifiable(
    cp: Checkpoint,
    literal_key: str,
    literal_value: str,
    live_lookup,                       # callable(key) -> value | None, hits real env
    irreversible: bool,
) -> None:
    """Gate an irreversible action on a literal the agent is about to use."""
    verify_checkpoint_integrity(cp)

    pinned = cp.pinned_facts.get(literal_key)
    if pinned is not None:
        if pinned != literal_value:
            raise CompactionDriftError(
                f"literal '{literal_key}' drifted: checkpoint pins {pinned!r}, "
                f"agent intends {literal_value!r}"
            )
        return  # verified against pinned ledger

    # Not pinned: must re-derive from the live environment, never from narrative.
    live = live_lookup(literal_key)
    if live is not None and live == literal_value:
        return  # verified against reality

    if irreversible:
        raise CompactionDriftError(
            f"literal '{literal_key}'={literal_value!r} is neither pinned nor "
            f"re-derivable from the environment; refusing irreversible action "
            f"on an unverifiable summary"
        )
    # reversible path may proceed, but the literal stays flagged unverified


def resume_and_act(cp: Checkpoint, pending: dict, live_lookup) -> None:
    # pending: {"key": ..., "value": ..., "irreversible": bool}
    assert_literal_verifiable(
        cp,
        pending["key"],
        pending["value"],
        live_lookup,
        pending["irreversible"],
    )
    # ... execute the gated action only after verification passes
