# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-self-referential-context-rewrites-before-the-pruning-pass-consumes-the-invariant-it-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-self-referential-context-rewrites-before-the-pruning-pass-consumes-the-invariant-it-depends-on.warrant.json
# Markdown SHA-256:   1af57804fa9614f1d8bf305762816cc11941077268159e98b879c7e267862b6a
# Code AST SHA-256:   45369d33d2a416ef3c0a6714a3bbdd4312420e5920a019e2ce8becc1626d1251
# Verified Classes:   ContextRewriteViolation, ProtectedManifest, PruneLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class ContextRewriteViolation(RuntimeError):
    """Raised when a self-edit would mutate or drop a protected contract token."""
    pass

@dataclass(frozen=True)
class ProtectedManifest:
    # Byte-identical strings that MUST survive any rewrite of the working buffer.
    # Held outside the buffer; never emitted into it, never rewritten by it.
    required_literals: tuple[str, ...]
    # Categories whose membership must be monotonically non-decreasing across passes.
    protected_ids: frozenset[str] = field(default_factory=frozenset)

@dataclass
class PruneLedger:
    dropped_ids: set[str] = field(default_factory=set)
    passes: int = 0

    def record(self, dropped: Iterable[str]) -> None:
        self.passes += 1
        self.dropped_ids.update(dropped)

    def classify_missing(self, ref_id: str) -> str:
        # Decides recovery action for a dangling reference.
        return "pruned_refetch_with_idempotency_key" if ref_id in self.dropped_ids \
               else "never_issued_treat_as_hallucination"


def validate_rewrite(original: str,
                     proposed: str,
                     manifest: ProtectedManifest,
                     ledger: PruneLedger) -> None:
    """Two-phase compaction validator. Runs AFTER the model proposes, BEFORE commit.
    Containment check is byte-level; no model call, so it cannot drift."""
    for literal in manifest.required_literals:
        if literal not in proposed:
            raise ContextRewriteViolation(
                f"Protected contract literal missing from rewrite: {literal!r}. "
                f"Refusing compaction; fall back to whole-subtask eviction."
            )
    # Protected IDs must be monotonically preserved, not paraphrased away.
    for pid in manifest.protected_ids:
        if pid in original and pid not in proposed:
            raise ContextRewriteViolation(
                f"Protected id {pid!r} dropped by rewrite; would ratchet. "
                f"Evict resolved payload instead."
            )
    if len(proposed) >= len(original):
        raise ContextRewriteViolation(
            "Rewrite did not reduce occupancy; trigger hysteresis insufficient."
        )


def compact(buffer: str, propose_rewrite, manifest: ProtectedManifest,
            ledger: PruneLedger) -> str:
    proposed = propose_rewrite(buffer)          # probabilistic, untrusted
    validate_rewrite(buffer, proposed, manifest, ledger)  # deterministic gate
    dropped = {pid for pid in manifest.protected_ids if pid in buffer and pid not in proposed}
    ledger.record(dropped)
    return proposed
