# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-detect-that-automatic-context-compaction-has-silently-dropped-a-referent-before-it-re-enters-the-tool-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-detect-that-automatic-context-compaction-has-silently-dropped-a-referent-before-it-re-enters-the-tool-loop.warrant.json
# Markdown SHA-256:   9ae361bee967a3fbb2e6e7a58924a9daf63cb367635bcd56191767e52c113463
# Code AST SHA-256:   234b8f3808320aacbf2675524288400dc1b6f8d1e03601658f03e8f2d03f9006
# Verified Classes:   ReferentLossError, Binding, CompactionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ReferentLossError(RuntimeError):
    """Raised when compaction would drop a binding that a pending action dereferences."""
    pass


@dataclass
class Binding:
    name: str
    value: Any
    source_turn: int
    regenerable: bool          # can a deterministic tool reproduce this cheaply?
    mutating: bool = False     # did obtaining it change the world?

    @property
    def irreplaceable(self) -> bool:
        # Irreplaceable if non-regenerable, or if re-obtaining would mutate state.
        return (not self.regenerable) or self.mutating


@dataclass
class CompactionPlan:
    watermark_turn: int
    pending_actions: list[str] = field(default_factory=list)   # handles next actions need
    bindings: dict[str, Binding] = field(default_factory=dict)


def prepare_compaction(plan: CompactionPlan) -> list[Binding]:
    """
    Pre-condition for automatic compaction: every binding dereferenced by a
    pending action must be irreplaceable-aware and, if irreplaceable, pinned
    OUT of the volatile window before the summarizer runs.

    Returns the list of bindings that must be pinned. Raises if any pending
    action references a binding the plan cannot account for.
    """
    to_pin: list[Binding] = []

    for handle in plan.pending_actions:
        binding = plan.bindings.get(handle)

        if binding is None:
            # The action needs a literal we have no record of. This is the
            # turn-142 failure: the summary said "the overrides file" and the
            # literal was gone. Refuse to compact.
            raise ReferentLossError(
                f"Pending action references handle {handle!r} with no tracked "
                f"binding; compaction would force the agent to reconstruct a "
                f"plausible literal. Pin it or re-derive it before summarizing."
            )

        if binding.irreplaceable:
            # Non-regenerable or world-mutating: must survive compaction verbatim.
            to_pin.append(binding)
        else:
            # Regenerable: safe to let the summarizer discard; recovery path is
            # re-invoking the deterministic tool.
            continue

    return to_pin


def verify_against_environment(check_value: Any, env_lookup, handle: str) -> None:
    """
    Ground-truth check. Must NOT read from compacted context. If the only
    available comparison is the summary's own narrative, the check is void.
    """
    actual = env_lookup(handle)
    if actual != check_value:
        raise ReferentLossError(
            f"Verification mismatch for {handle!r}: environment holds {actual!r}, "
            f"agent asserted {check_value!r}. Likely a reconstructed literal from "
            f"a compacted turn — replay from the binding's source_turn."
        )
