# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-task-fidelity-when-context-compaction-preserves-semantic-similarity-but-drops-procedural-anchors.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-task-fidelity-when-context-compaction-preserves-semantic-similarity-but-drops-procedural-anchors.warrant.json
# Markdown SHA-256:   a0b99be9d1965c089a940b107b0964ebf4ca16f11d3e0a287e6d4fc13aa089af
# Code AST SHA-256:   42deb76d519bb4f7ef5bcc26fc4e39e1a8b9d55a0a26600d82c876c9f532d7ee
# Verified Classes:   CompactionFidelityError, Anchor, CompactedState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class CompactionFidelityError(RuntimeError):
    """Raised when a compacted state is topically faithful but procedurally insufficient."""
    pass

@dataclass
class Anchor:
    key: str          # e.g. "idempotency_key", "tax_rate", "endpoint", "negative_constraint"
    value: str        # byte-exact; never paraphrased
    consumed_by_step: int

@dataclass
class CompactedState:
    summary: str
    similarity: float                 # cosine(summary, transcript)
    anchors: dict[str, str] = field(default_factory=dict)

def validate_compaction(
    state: CompactedState,
    required_anchors: Iterable[Anchor],
    similarity_floor: float = 0.85,
    replay_probe_passed: bool = False,
) -> None:
    # Similarity is a readability pre-filter only; it is NOT sufficient.
    if state.similarity < similarity_floor:
        raise CompactionFidelityError(
            f"summary similarity {state.similarity:.3f} below floor {similarity_floor}; "
            "rejecting compaction and retaining raw window"
        )

    # Invariant: every anchor consumed by a remaining plan step must survive byte-exact.
    missing = [
        a for a in required_anchors
        if a.key not in state.anchors or state.anchors[a.key] != a.value
    ]
    if missing:
        detail = ", ".join(f"{a.key}@step{a.consumed_by_step}" for a in missing)
        raise CompactionFidelityError(
            f"compaction dropped or mutated procedural anchors: {detail}. "
            "Similarity gate would have passed; task replay would diverge. "
            "Rejecting compaction and forcing verbatim retention."
        )

    # Belt-and-suspenders: a replay probe must confirm the compacted state can
    # reproduce the next K actions before the raw window is truncated.
    if not replay_probe_passed:
        raise CompactionFidelityError(
            "replay probe failed: compacted state cannot reproduce next-K actions; "
            "do not truncate raw window"
        )
