# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-automatic-context-compaction-has-silently-destroyed-a-verifiable-precondition.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-automatic-context-compaction-has-silently-destroyed-a-verifiable-precondition.warrant.json
# Markdown SHA-256:   1b89d33c779629f402c98b1a47b5290570d656e7e23e90832151e5ca01ff94cc
# Code AST SHA-256:   0dd43d6e5d6618c9145cbb1a386afd75da3e57fad4d6c9dd10f1553531a585d5
# Verified Classes:   PreconditionLostError, Span, CompactionResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class PreconditionLostError(RuntimeError):
    """Raised when a step depends on a binding that compaction did not preserve verbatim."""


@dataclass
class Span:
    text: str
    binding: bool  # True if this span is a load-bearing precondition


@dataclass
class CompactionResult:
    summary: str
    pinned: list[str] = field(default_factory=list)
    dropped_bindings: list[str] = field(default_factory=list)


def audit_and_compact(window: Iterable[Span], budget_tokens: int) -> CompactionResult:
    """Pin binding spans verbatim; summarize narrative. Fail closed if pins overflow."""
    pins: list[str] = []
    narrative: list[str] = []
    for span in window:
        if span.binding:
            pins.append(span.text)
        else:
            narrative.append(span.text)

    pinned_tokens = sum(len(p.split()) for p in pins)
    if pinned_tokens > budget_tokens:
        # Do not silently drop a binding to make room. Refuse.
        raise PreconditionLostError(
            f"binding spans require {pinned_tokens} tokens > budget {budget_tokens}; "
            f"refusing lossy compaction"
        )

    summary = " ".join(narrative)[: max(0, budget_tokens - pinned_tokens)]
    return CompactionResult(summary=summary, pinned=pins)


def require_binding(result: CompactionResult, needed: str, summary_mentions: bool) -> None:
    """Gate a downstream action on a binding being verbatim-present, not merely implied."""
    if needed in result.pinned:
        return
    if summary_mentions and needed not in result.summary:
        raise PreconditionLostError(
            f"step depends on binding {needed!r}; summary references the category but not the "
            f"identifier — inference from goal is forbidden, re-fetch original turn"
        )
    raise PreconditionLostError(f"binding {needed!r} absent from pinned set and summary")


# --- trace of the observed failure ---
window = [
    Span("deploy the service to production", binding=False),
    Span("never run migrations against db-prod-2; use db-prod-2-replica", binding=True),
    Span("schema review complete, staging validated", binding=False),
]
result = audit_and_compact(window, budget_tokens=50)
# summary now contains "deploy ... production" but the replica pin is preserved:
assert "db-prod-2-replica" in result.pinned

# If compaction had been unkeyed, this call would reconstruct the target from the goal
# and raise instead of silently issuing a prod migration:
require_binding(result, "db-prod-2-replica", summary_mentions=True)
