# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-lossy-compaction-from-silently-violating-reconstructed-tool-call-preconditions-in-long-horizon-agent-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-lossy-compaction-from-silently-violating-reconstructed-tool-call-preconditions-in-long-horizon-agent-sessions.warrant.json
# Markdown SHA-256:   ed16eab248db1ae78b8b25b7ad31c572604befd35741e79f6b976ce3ecf900a5
# Code AST SHA-256:   5b91dc4c9fad4dffa4dc6a683a69eb101484fffb1017a64eb95be02eb779ca34
# Verified Classes:   PreconditionViolation, PreconditionLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class PreconditionViolation(RuntimeError):
    """Raised when a post-compaction tool call depends on a paraphrase-only precondition."""
    pass


class PreconditionLedger:
    """
    Append-only, non-compactable store of operational preconditions.
    Survives context compaction; queried, never summarized.
    """

    def __init__(self):
        self._entries = {}  # key -> {"value": ..., "provenance": "live"|"opaque"|"stale"}

    def record(self, key, value, provenance="live"):
        if provenance not in ("live", "opaque", "stale"):
            raise PreconditionViolation(f"bad provenance tag: {provenance!r}")
        self._entries[key] = {"value": value, "provenance": provenance}

    def invalidate(self, key):
        if key in self._entries:
            self._entries[key]["provenance"] = "stale"

    def require(self, key):
        """Called before any tool call that depends on `key`. Refuses paraphrase-only state."""
        entry = self._entries.get(key)
        if entry is None:
            raise PreconditionViolation(
                f"precondition {key!r} absent from ledger — summary cannot license this call"
            )
        if entry["provenance"] == "stale":
            raise PreconditionViolation(
                f"precondition {key!r} is stale; re-validate against live system before use"
            )
        return entry["value"]


def resume_migration(ledger: PreconditionLedger, cursor_key: str, schema_key: str):
    # Both preconditions must be live or opaque-preserved. A paraphrase in the
    # summary is not sufficient warrant to issue the call.
    cursor = ledger.require(cursor_key)
    schema = ledger.require(schema_key)
    if schema != "v5":
        # The summary said v4; the ledger says otherwise. Trust the ledger.
        raise PreconditionViolation(
            f"schema drift detected: ledger={schema!r}, proceeding would corrupt rows"
        )
    return {"cursor": cursor, "schema": schema, "status": "resumed"}
