# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-pruners-from-deleting-their-own-justification-trail.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-pruners-from-deleting-their-own-justification-trail.warrant.json
# Markdown SHA-256:   6ef73113cc3e590d40d81f5677405afc64861edbaa597ff3b2d04e35f4a717f9
# Code AST SHA-256:   8080cea25288689f996de6a58a295135d9034ee9269ba1a43342451abae75e45
# Verified Classes:   PruneViolation, Class, Passage, Context
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class PruneViolation(RuntimeError):
    """Raised when a self-edit would drop a commitment or conflict without discharge."""
    pass


class Class(str, Enum):
    EXPLORATION = "exploration"   # freely prunable
    CONCLUSION = "conclusion"     # prunable only if provenance retained
    CONFLICT = "conflict"         # never prunable until discharged


@dataclass
class Passage:
    pid: str
    kind: Class
    text: str
    sources: tuple[str, ...] = ()
    discharged: bool = False


@dataclass
class Context:
    passages: dict[str, Passage] = field(default_factory=dict)

    def self_edit(self, keep_ids: set[str]) -> None:
        """Model-driven compaction: drop everything not in keep_ids."""
        for pid, p in list(self.passages.items()):
            if pid in keep_ids:
                continue
            # Invariant 1: conflicts are monotonic until discharged.
            if p.kind is Class.CONFLICT and not p.discharged:
                raise PruneViolation(
                    f"cannot evict open conflict {pid!r}; discharge with evidence first"
                )
            # Invariant 2: a conclusion may not survive without its provenance,
            # and may not be dropped if it is the only carrier of a live premise.
            if p.kind is Class.CONCLUSION and not p.discharged:
                survivors = [q for q in self.passages.values()
                             if q.pid != pid and q.kind is Class.CONCLUSION]
                if not any(s.sources for s in survivors) and p.sources:
                    raise PruneViolation(
                        f"evicting {pid!r} would orphan the only provenance trail"
                    )
            del self.passages[pid]

    def discharge(self, pid: str, resolving_source: str) -> None:
        p = self.passages[pid]
        if not resolving_source:
            raise PruneViolation(f"discharge of {pid!r} requires a resolving source")
        p.discharged = True
        p.sources = p.sources + (resolving_source,)


def run_compaction(ctx: Context, keep_ids: set[str]) -> None:
    try:
        ctx.self_edit(keep_ids)
    except PruneViolation as e:
        # Surface as a blocking unknown rather than silently proceeding.
        raise PruneViolation(f"compaction blocked: {e}") from e
