# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-compaction-summary-has-become-a-semantic-trap.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-compaction-summary-has-become-a-semantic-trap.warrant.json
# Markdown SHA-256:   6eb625f60301aa78e027e746c1ed00bbe56756577423b1bb4d59df078e6f9623
# Code AST SHA-256:   6b6caccbcca68ff1c695eb228a4a42cba1f0e039c325557ad2b82d6e1c2b0bfa
# Verified Classes:   CompactionTrapDetected, ProbeRecord, CompactionAudit
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field
from typing import Sequence


class CompactionTrapDetected(RuntimeError):
    """Raised when similarity decay on repeated verification probes indicates
    the agent's query distribution has drifted away from the retrieval store."""
    pass


@dataclass
class ProbeRecord:
    turn: int
    query_terms: frozenset
    top1_similarity: float


@dataclass
class CompactionAudit:
    threshold: float = 0.72
    decay_window: int = 3
    decay_tolerance: float = 0.05
    probes: list = field(default_factory=list)

    def record_probe(self, turn: int, query_terms: Sequence[str],
                     top1_similarity: float) -> None:
        self.probes.append(
            ProbeRecord(turn, frozenset(t.lower() for t in query_terms),
                        top1_similarity)
        )

    def _jaccard(self, a: frozenset, b: frozenset) -> float:
        if not a and not b:
            return 1.0
        return len(a & b) / len(a | b)

    def detect_vocabulary_drift(self) -> bool:
        """True if successive probes are semantically equivalent (high term
        overlap) but their top-1 similarity is decaying. That combination is
        the signature of summary-conditioned query drift, not of a genuine
        absence of relevant content."""
        if len(self.probes) < self.decay_window:
            return False
        recent = self.probes[-self.decay_window:]
        for i in range(1, len(recent)):
            overlap = self._jaccard(recent[i - 1].query_terms,
                                    recent[i].query_terms)
            if overlap < 0.5:
                return False  # queries genuinely changed; not drift
        sims = [p.top1_similarity for p in recent]
        return all(sims[i] < sims[i - 1] + self.decay_tolerance
                   for i in range(1, len(sims))) and sims[-1] < sims[0]

    def assert_negative_existential_safe(self, claim: str,
                                         independent_probe_count: int) -> None:
        """A negative existential ('no counterexamples found') may not rest on
        summary-conditioned retrieval alone. It requires probes formed
        independently of the summary."""
        if independent_probe_count < 2:
            raise CompactionTrapDetected(
                f"Negative existential claim {claim!r} is unsupported: only "
                f"{independent_probe_count} summary-independent probe(s) were "
                f"run. The retrieval fallback may be a mirror of the summary."
            )
        if self.detect_vocabulary_drift():
            raise CompactionTrapDetected(
                f"Negative existential claim {claim!r} rejected: similarity "
                f"decay detected across equivalent probes "
                f"({[round(p.top1_similarity, 2) for p in self.probes[-self.decay_window:]]}). "
                f"Query distribution has drifted; rerun probes from the "
                f"pre-compaction task spec or omissions manifest."
            )
