# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-task-critical-state-loss-when-automatic-context-compaction-rewrites-the-working-set.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-task-critical-state-loss-when-automatic-context-compaction-rewrites-the-working-set.warrant.json
# Markdown SHA-256:   4367842c1ba99074fe94b73f9549b8d96c91f2a780a18ac3c81a3e7dae7b6612
# Code AST SHA-256:   4d526a00523af8360659f14e2e81d917dcab4e3fa26c616ad05ffec5612c22e9
# Verified Classes:   CompactionInvariantError, Segment, BindingStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class CompactionInvariantError(RuntimeError):
    """Raised when a compaction pass would make task-critical binding state unrecoverable."""
    pass

@dataclass
class Segment:
    text: str
    binding_literals: frozenset[str] = frozenset()  # exact strings the continuation may need

@dataclass
class BindingStore:
    _data: dict[str, str] = field(default_factory=dict)
    def put(self, key: str, value: str) -> str:
        self._data[key] = value
        return f"<<{key}>>"
    def resolve(self, ref: str) -> str:
        key = ref.strip("<>")
        if key not in self._data:
            raise CompactionInvariantError(f"dangling reference {ref}: binding state lost")
        return self._data[key]

def compact(
    segments: Iterable[Segment],
    pending_plan_literals: frozenset[str],
    store: BindingStore,
    fold_depth: int,
) -> str:
    # C3: bound fold depth — never re-judge binding literals across folds.
    if fold_depth > 2:
        raise CompactionInvariantError(
            f"fold_depth {fold_depth} exceeds bound; binding demotion risk"
        )
    out: list[str] = []
    for seg in segments:
        # C1/C2: externalize every literal the pending plan depends on, verbatim.
        critical = seg.binding_literals & pending_plan_literals
        if critical:
            refs = [store.put(f"lit_{i}", lit) for i, lit in enumerate(sorted(critical))]
            # C5 pre-check: verify each reference resolves before releasing.
            for r in refs:
                try:
                    store.resolve(r)
                except CompactionInvariantError as e:
                    raise CompactionInvariantError(f"post-externalize verify failed: {e}") from e
            out.append(f"[binding preserved: {', '.join(refs)}]")
        else:
            out.append(seg.text)  # narrative: safe to rewrite
    # C4: manifest must be emitted so continuation knows a fold occurred.
    return "COMPACTED(fold=%d)\n" % fold_depth + "\n".join(out)
