# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-self-edit-of-working-memory-as-a-lossy-transaction-rather-than-a-compaction-and-how-does-the-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-self-edit-of-working-memory-as-a-lossy-transaction-rather-than-a-compaction-and-how-does-the-compaction.warrant.json
# Markdown SHA-256:   106f13637b17f8e88133261b488d1acc1f5d2b7ce94804ccff3d93a3b852dd20
# Code AST SHA-256:   9f9cf8ca1046af0f5d71d87d602cfcc3e9aded72d08ba9c3c96511c1cc56dbd9
# Verified Classes:   CompactionLossError, Span, Tombstone, SelfEditingContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CompactionLossError(RuntimeError):
    """Raised when a self-edit evicts a span whose referents are not reconstructible."""
    pass


CONSTRAINT_MARKERS = ("unit", "currency", "iso-4217", "minor", "type", "range",
                      "not ", "never", "must", "forbidden", "permission")


@dataclass
class Span:
    span_id: str
    text: str
    step: int
    is_constraint: bool = False

    def __post_init__(self):
        low = self.text.lower()
        self.is_constraint = any(m in low for m in CONSTRAINT_MARKERS)


@dataclass
class Tombstone:
    span_id: str
    text_hash: str
    reason: str
    step: int


@dataclass
class SelfEditingContext:
    spans: list = field(default_factory=list)
    journal: list = field(default_factory=list)

    def evict(self, span_id: str, reason: str, step: int) -> None:
        target = next((s for s in self.spans if s.span_id == span_id), None)
        if target is None:
            return
        if target.is_constraint and reason == "low_similarity":
            # Constraint spans may be compressed, never similarity-evicted.
            raise CompactionLossError(
                f"refusing similarity-eviction of constraint span {span_id!r} "
                f"at step {step}: referent closure unproven; compress-to-assertion required"
            )
        self.journal.append(Tombstone(
            span_id=target.span_id,
            text_hash=hashlib.sha256(target.text.encode()).hexdigest()[:16],
            reason=reason,
            step=step,
        ))
        self.spans = [s for s in self.spans if s.span_id != span_id]

    def assert_referent_closure(self, dependent_step: int, required_token: str) -> None:
        live = any(required_token in s.text for s in self.spans)
        if live:
            return
        recovered = [t for t in self.journal if t.text_hash]
        if not recovered:
            raise CompactionLossError(
                f"step {dependent_step} requires {required_token!r}; "
                f"no live span and no tombstone — unrecoverable loss"
            )
        raise CompactionLossError(
            f"step {dependent_step} requires {required_token!r}; "
            f"evicted at step {recovered[-1].step} (hash {recovered[-1].text_hash}); "
            f"re-inject from journal before executing"
        )
