# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-summarization-drift-when-lossy-context-compaction-silently-violates-fidelity-guarantees.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-summarization-drift-when-lossy-context-compaction-silently-violates-fidelity-guarantees.warrant.json
# Markdown SHA-256:   d0d8803ab917709496621ea315492574a4616429db49c112cd2abe2293341e24
# Code AST SHA-256:   2aac0d6d800219eef0a16cb1fdd2ab4bc56d673d3811e6169b4093a75fbbe907
# Verified Classes:   FidelityViolation, PinnedInvariant, CompactionGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class FidelityViolation(RuntimeError):
    """Raised when a post-compaction context fails to preserve a pinned invariant."""
    pass


@dataclass
class PinnedInvariant:
    invariant_id: str
    # Modal-strength markers that must survive compaction verbatim-or-stronger.
    required_markers: tuple[str, ...]
    # Tokens that indicate the invariant was hedged into an advisory form.
    forbidden_hedges: tuple[str, ...] = ("preferred", "should", "carefully", "ideally")


@dataclass
class CompactionGate:
    pinned: dict[str, PinnedInvariant] = field(default_factory=dict)
    max_resummarization_depth: int = 2

    def pin(self, inv: PinnedInvariant) -> None:
        self.pinned[inv.invariant_id] = inv

    def verify(self, post_summary: str, depth: int) -> None:
        if depth > self.max_resummarization_depth:
            raise FidelityViolation(
                f"re-summarization depth {depth} exceeds cap "
                f"{self.max_resummarization_depth}; drift is unbounded"
            )
        low = post_summary.lower()
        for inv in self.pinned.values():
            missing = [m for m in inv.required_markers if m.lower() not in low]
            hedged = [h for h in inv.forbidden_hedges if h in low]
            if missing or hedged:
                raise FidelityViolation(
                    f"invariant {inv.invariant_id!r} lost modal strength: "
                    f"missing={missing} hedged={hedged}"
                )


def compact(gate: CompactionGate, prior_summary: str, depth: int) -> str:
    # Lossy summarizer stand-in; real implementation calls the model.
    new_summary = prior_summary.replace("Never call", "Prefer not to call")
    gate.verify(new_summary, depth + 1)
    return new_summary


def run_compaction_cycle(gate: CompactionGate, current: str, depth: int) -> str:
    gate.pin(PinnedInvariant(
        invariant_id="migration-dry-run",
        required_markers=("Never call", "dry_run=false"),
    ))
    return compact(gate, current, depth)


if __name__ == "__main__":
    gate = CompactionGate()
    ctx = "Never call the migration endpoint with dry_run=false until checksum matches."
    try:
        run_compaction_cycle(gate, ctx, depth=0)
    except FidelityViolation as exc:
        print(f"drift detected, re-grounding required: {exc}")
