# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-preconditions-after-lossy-compaction-rewrites-the-plan-into-prose.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-preconditions-after-lossy-compaction-rewrites-the-plan-into-prose.warrant.json
# Markdown SHA-256:   810d929086cacdd598539d14bbabcf7c19271a2968b94e0935a6a473968cc755
# Code AST SHA-256:   a0e50fbb0c239ad455d75da622d78d2de5e1b2576d5796117c9c3d5844030b0a
# Verified Classes:   PreconditionElisionError, Provenance, RetrievedChunk, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class PreconditionElisionError(RuntimeError):
    """Raised when a tool call would proceed on a summarized (lossy) precondition
    instead of a verbatim or ledger-backed one."""
    pass


class Provenance(Enum):
    RAW_SPAN = "raw_span"
    SUMMARY = "summary"
    LEDGER = "ledger"


@dataclass
class RetrievedChunk:
    provenance: Provenance
    text: str
    carries_guard: bool  # True only if idempotency/run_id/ordering survived


@dataclass
class ToolCall:
    name: str
    args: dict
    idempotent: bool
    run_id: str | None


# Typed ledger that lives OUTSIDE the compactable window.
LEDGER: dict[str, dict] = {
    "migrate:v14": {"idempotent": False, "run_id": "r-8821", "fired": True},
}


def authorize_call(call: ToolCall, retrieved: list[RetrievedChunk]) -> None:
    """Gate a tool call whose target may sit in a compacted region.

    Invariant: a summary may inform recall but may never authorize a
    non-idempotent re-invocation. Authorization requires the ledger or a
    raw span that still carries the guard.
    """
    key = f"{call.name}:{call.args.get('schema', call.args.get('env', ''))}"
    ledger_entry = LEDGER.get(key)

    # Prefer the ledger: it is the authoritative, non-summarized precondition.
    if ledger_entry is not None:
        if ledger_entry["fired"] and not ledger_entry["idempotent"]:
            raise PreconditionElisionError(
                f"Refusing to re-invoke non-idempotent {call.name} "
                f"(run_id={ledger_entry['run_id']}); already fired. "
                f"Summary claiming success does not authorize a re-run."
            )
        return

    # No ledger entry: fall back to retrieval, but only trust raw spans.
    authoritative = [
        c for c in retrieved
        if c.provenance in (Provenance.RAW_SPAN, Provenance.LEDGER) and c.carries_guard
    ]
    if not authoritative:
        raise PreconditionElisionError(
            f"No guard-bearing source for {call.name} after compaction; "
            f"retrieval returned only lossy summaries. Halt and re-query "
            f"actual tool state before proceeding."
        )


def resume_plan(call: ToolCall, retrieved: list[RetrievedChunk]) -> str:
    authorize_call(call, retrieved)
    return f"executed {call.name}"


# Repro: summary ranked above raw span, guard dropped.
if __name__ == "__main__":
    retrieved = [
        RetrievedChunk(Provenance.SUMMARY, "Migration v14 applied successfully.", carries_guard=False),
        RetrievedChunk(Provenance.RAW_SPAN, '{"status":"ok","run_id":"r-8821","idempotent":false}', carries_guard=True),
    ]
    call = ToolCall(name="migrate", args={"schema": "v14"}, idempotent=False, run_id="r-8821")
    try:
        resume_plan(call, retrieved)
    except PreconditionElisionError as e:
        print("BLOCKED:", e)
