# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-lose-tool-call-preconditions-during-automatic-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-lose-tool-call-preconditions-during-automatic-context-compaction.warrant.json
# Markdown SHA-256:   018e94d9388d0d8648b490e08122990f7b4364a2b5ad33962ed0305b245d083f
# Code AST SHA-256:   23004311930ca9b9a6e9784c8fcf4599b28a99f90a73686d8a7d1774e2316bf0
# Verified Classes:   PreconditionLostError, CompactionBoundary
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PreconditionLostError(RuntimeError):
    """Raised when a tool call's required literal precondition is absent
    from context after compaction and cannot be re-derived from the
    authoritative scratchpad."""
    pass


@dataclass
class CompactionBoundary:
    # Fields that MUST survive compaction byte-identical.
    pinned: dict = field(default_factory=dict)

    def compact(self, prose_summary: str) -> "CompactionBoundary":
        # Lossy pass: prose summary is allowed to paraphrase narrative,
        # but pinned preconditions are carried verbatim, never summarized.
        return CompactionBoundary(pinned=dict(self.pinned))


def assert_preconditions(
    boundary: CompactionBoundary,
    scratchpad: dict,
    required: list[str],
    mutating: bool,
) -> dict:
    """Guard executed immediately before constructing a tool call.

    Invariant: a literal argument, etag, idempotency key, or schema
    version must be present as a literal (pinned or scratchpad), never
    inferred from prose. list-and-match heuristics are disallowed here.
    """
    resolved: dict = {}
    for key in required:
        if key in boundary.pinned:
            resolved[key] = boundary.pinned[key]
        elif key in scratchpad:
            resolved[key] = scratchpad[key]
        elif mutating:
            # A mutating call on a guessed target is a silent-corruption
            # vector; refuse rather than re-derive by heuristic.
            raise PreconditionLostError(
                f"Mutating call requires literal precondition '{key}', "
                f"absent from pinned set and scratchpad after compaction. "
                f"Refusing to reconstruct by heuristic; halt and re-fetch "
                f"from authoritative source."
            )
        else:
            resolved[key] = None  # read-only path may proceed degraded
    return resolved


def resume_after_compaction(
    boundary: CompactionBoundary,
    scratchpad: dict,
    next_call: dict,
) -> dict:
    mutating = next_call.get("method", "GET").upper() in {"POST", "PUT", "PATCH", "DELETE"}
    required = next_call.get("requires_literals", [])
    args = assert_preconditions(boundary, scratchpad, required, mutating)
    return {**next_call, "resolved_args": args}
