# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-lossy-auto-compaction-before-it-corrupts-a-resumed-trajectory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-lossy-auto-compaction-before-it-corrupts-a-resumed-trajectory.warrant.json
# Markdown SHA-256:   2e79104e327f37302b30a2e6df562518edd273af0bc529e2bc448cf1a3b411bd
# Code AST SHA-256:   4b04cbd5152ebe333804a6b818f042821cb2f26e067dd8f1bc5b578b35962a3d
# Verified Classes:   CompactionInvariantViolation, InvariantType, Invariant, Ledger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CompactionInvariantViolation(RuntimeError):
    """Raised when a resumed trajectory's plan touches a dropped invariant."""


class InvariantType(Enum):
    CONSTRAINT = "constraint"
    FACT = "fact"
    NEGATIVE_RESULT = "negative_result"
    OBLIGATION = "obligation"


@dataclass
class Invariant:
    id: str
    type: InvariantType
    content: str
    source_turn: int
    protected_patterns: list[str] = field(default_factory=list)


@dataclass
class Ledger:
    entries: dict[str, Invariant] = field(default_factory=dict)

    def add(self, inv: Invariant) -> None:
        self.entries[inv.id] = inv

    def reconcile(self, plan: str) -> None:
        """Reject a resumed plan that violates a carried invariant."""
        for inv in self.entries.values():
            if inv.type == InvariantType.NEGATIVE_RESULT and inv.content.lower() in plan.lower():
                raise CompactionInvariantViolation(
                    f"plan re-attempts known negative result {inv.id} "
                    f"(source turn {inv.source_turn}): {inv.content!r}"
                )
            for pat in inv.protected_patterns:
                if pat in plan:
                    raise CompactionInvariantViolation(
                        f"plan touches protected region {pat!r} under "
                        f"{inv.type.value} {inv.id}: {inv.content!r}"
                    )


def resume_from_compaction(summary: str, ledger: Ledger, plan: str) -> str:
    if not ledger.entries:
        raise CompactionInvariantViolation(
            "no invariant ledger present; summary is untrusted and must be "
            "re-derived from environment before proceeding"
        )
    ledger.reconcile(plan)
    return f"resumed: {summary} | invariants={len(ledger.entries)}"
