# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-own-edit-trail-self-referential-pruning-corruption-when-a-model-rewrites-the-context-it-is-reasoning-inside.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-own-edit-trail-self-referential-pruning-corruption-when-a-model-rewrites-the-context-it-is-reasoning-inside.warrant.json
# Markdown SHA-256:   d2d8f272c4fcb2a023d3c12c0f002501ba4d614d7d886929d5b0ab3e0a4ad711
# Code AST SHA-256:   bca2505b7a1601be0589eecbdfb22d8f147de3922135520a77fa904351f78c99
# Verified Classes:   PruneCorruptionError, Constraint, ContextBuffer, ConstraintLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class PruneCorruptionError(RuntimeError):
    """Raised when a model-driven prune would drop a structurally
    preserved constraint with no tombstone in the rewritten buffer."""
    pass


@dataclass(frozen=True)
class Constraint:
    cid: str
    text: str
    provenance: str  # "user" | "spec" -- never model-authored


@dataclass
class ContextBuffer:
    spans: list[str] = field(default_factory=list)
    tombstones: list[str] = field(default_factory=list)


class ConstraintLedger:
    """Append-only, model-unwritable. The source of truth for what a
    self-edit is not permitted to forget."""

    def __init__(self) -> None:
        self._entries: list[Constraint] = []

    def ingest(self, constraints: Iterable[Constraint]) -> None:
        self._entries.extend(constraints)

    def preserved_ids(self) -> set[str]:
        return {c.cid for c in self._entries}


def apply_self_prune(
    buffer: ContextBuffer,
    proposed_summary: str,
    ledger: ConstraintLedger,
    cited_ids: set[str],
) -> ContextBuffer:
    """Commit a model-authored rewrite only if every ledger constraint is
    either cited in the summary or tombstoned. Otherwise reject."""
    missing = ledger.preserved_ids() - cited_ids
    if missing:
        # The model cannot see what it dropped; the ledger can.
        raise PruneCorruptionError(
            f"prune rejected: constraints {sorted(missing)} would be lost "
            f"with no tombstone; original spans must be retained or cited"
        )
    return ContextBuffer(
        spans=[proposed_summary],
        tombstones=buffer.tombstones + sorted(ledger.preserved_ids()),
    )
