# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-measures-context-compaction-fidelity-without-a-fixed-reference-transcript.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-measures-context-compaction-fidelity-without-a-fixed-reference-transcript.warrant.json
# Markdown SHA-256:   004e538aff2d474fc64380e2f67e72e1a066d340d1d472a18e8011f186697e05
# Code AST SHA-256:   f82dd8ca581da7315803da9cd960e88ff719598b9adbf9b349d8df3d2d596618
# Verified Classes:   CompactionFidelityError, PinnedInvariant, FidelityLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class CompactionFidelityError(RuntimeError):
    """Raised when a compaction round violates a pinned fidelity invariant."""
    pass


@dataclass
class PinnedInvariant:
    key: str
    pattern: str  # normalized exact-match pattern, e.g. r"staging-eu-2"
    first_seen_round: int = 0


@dataclass
class FidelityLedger:
    invariants: list[PinnedInvariant] = field(default_factory=list)
    # round_index -> {key: matched_value_or_None}
    history: dict[int, dict[str, str | None]] = field(default_factory=dict)

    def check_round(self, round_index: int, summary_text: str) -> dict[str, str | None]:
        observed: dict[str, str | None] = {}
        for inv in self.invariants:
            m = re.search(inv.pattern, summary_text)
            observed[inv.key] = m.group(0) if m else None
        self.history[round_index] = observed
        return observed

    def assert_stable(self, round_index: int) -> None:
        """Fail if any pinned invariant drifted or vanished relative to round 0."""
        base = self.history.get(0, {})
        current = self.history.get(round_index, {})
        for inv in self.invariants:
            expected = base.get(inv.key)
            got = current.get(inv.key)
            if expected is None:
                # invariant was not present at round 0; nothing to preserve
                continue
            if got is None:
                raise CompactionFidelityError(
                    f"round {round_index}: invariant '{inv.key}' ({expected!r}) "
                    f"vanished from summary — cumulative information loss"
                )
            if got != expected:
                raise CompactionFidelityError(
                    f"round {round_index}: invariant '{inv.key}' drifted "
                    f"{expected!r} -> {got!r} — self-referential scorer would "
                    f"report this as preserved"
                )


def run_compaction_audit(rounds: list[str], invariants: list[PinnedInvariant]) -> FidelityLedger:
    ledger = FidelityLedger(invariants=invariants)
    for i, summary in enumerate(rounds):
        ledger.check_round(i, summary)
        if i > 0:
            ledger.assert_stable(i)  # raises CompactionFidelityError on drift
    return ledger


# Example: round 2 paraphrased the deploy target, round 3 dropped the timeout.
if __name__ == "__main__":
    invs = [
        PinnedInvariant("deploy_target", r"staging-eu-[12]"),
        PinnedInvariant("timeout_s", r"\b45s\b"),
        PinnedInvariant("retry_cap", r"retry cap of 3"),
    ]
    rounds = [
        "deploy to staging-eu-2 with 45s timeout and retry cap of 3",
        "deploy to staging-eu-2, 45s timeout, retry cap of 3",
        "deploy to staging, retry cap of 3",  # timeout dropped, target collapsed
    ]
    run_compaction_audit(rounds, invs)  # raises CompactionFidelityError at round 2
