# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-lossy-auto-compaction-from-silently-rewriting-the-agent-s-own-success-criteria.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-lossy-auto-compaction-from-silently-rewriting-the-agent-s-own-success-criteria.warrant.json
# Markdown SHA-256:   3220ac6e1e652e5e8cfb47187af4477a41e3bb9b09de7d16a0650c919f5e2529
# Code AST SHA-256:   db6ddce6ce7d5f89d22e3a2e0d7715526f9f6c93cedfba7127a3af4511366bf1
# Verified Classes:   CompactionFidelityError, TaskContract, CompactionEvent
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CompactionFidelityError(RuntimeError):
    """Raised when a compaction event would drop an irreversible obligation."""


@dataclass(frozen=True)
class TaskContract:
    goal: str
    irreversible_constraints: FrozenSet[str]  # e.g. {"no DROP", "no data loss"}
    acceptance: FrozenSet[str]


@dataclass
class CompactionEvent:
    summary: str
    similarity_fidelity: float          # scorer vs. mutable working restatement
    preserved_obligations: FrozenSet[str]


def admit_compaction(
    contract: TaskContract,
    event: CompactionEvent,
    similarity_gate: float = 0.85,
) -> None:
    # Similarity gate: necessary but NOT sufficient for irreversible tasks.
    if event.similarity_fidelity < similarity_gate:
        raise CompactionFidelityError(
            f"summary fidelity {event.similarity_fidelity:.2f} below gate "
            f"{similarity_gate:.2f}; compaction rejected"
        )

    # Obligation gate: exact set membership against the frozen anchor.
    # This is the invariant the similarity score cannot substitute for.
    missing = contract.irreversible_constraints - event.preserved_obligations
    if missing:
        raise CompactionFidelityError(
            "compaction would launder irreversible constraints out of context: "
            f"{sorted(missing)}; re-inject pinned obligation region and retry"
        )

    # Only reached when both gates pass. Pinned region must still be
    # re-injected post-commit by the caller; admission alone is not enough.
    return None
