# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-lossy-auto-compaction-from-silently-corrupting-an-agent-s-working-set.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-lossy-auto-compaction-from-silently-corrupting-an-agent-s-working-set.warrant.json
# Markdown SHA-256:   000f1bedeea6f8c6b69452f144027aa062e0e15612e4786b3cd2f24c8320ca1a
# Code AST SHA-256:   736de88ae65a6cd296068ef03bd7957bda490490dd6901bb9f0a27dd667daf9e
# Verified Classes:   CompactionIntegrityError, Referent, WorkingSet
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class CompactionIntegrityError(RuntimeError):
    """Raised when a lossy compaction drops or mutates a load-bearing referent."""
    pass


@dataclass
class Referent:
    kind: Literal["artifact_id", "negation", "obligation"]
    key: str
    value: str


@dataclass
class WorkingSet:
    narrative: str
    referents: dict[str, Referent] = field(default_factory=dict)


def compact(ws: WorkingSet, summarizer) -> WorkingSet:
    """Lossy channel for narrative; structural channel for referents."""
    summary = summarizer(ws.narrative)          # generative, lossy, allowed
    carried = {k: Referent(r.kind, r.key, r.value) for k, r in ws.referents.items()}
    return WorkingSet(narrative=summary, referents=carried)


def assert_referential_closure(pre: WorkingSet, post: WorkingSet) -> None:
    """Invariant: every pre-compaction referent must survive exactly."""
    for key, before in pre.referents.items():
        after = post.referents.get(key)
        if after is None:
            raise CompactionIntegrityError(
                f"referent {key!r} ({before.kind}) dropped by compaction"
            )
        if after.value != before.value:
            raise CompactionIntegrityError(
                f"referent {key!r} mutated: {before.value!r} -> {after.value!r}"
            )
        if before.kind in ("negation", "obligation") and after.kind != before.kind:
            raise CompactionIntegrityError(
                f"referent {key!r} demoted from {before.kind} to {after.kind}"
            )


def run_compaction(ws: WorkingSet, summarizer) -> WorkingSet:
    post = compact(ws, summarizer)
    assert_referential_closure(ws, post)   # gate: fails closed, never confabulates
    return post
