# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-its-own-context-the-self-edit-watermark-and-the-compaction-induced-amnesia-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-its-own-context-the-self-edit-watermark-and-the-compaction-induced-amnesia-loop.warrant.json
# Markdown SHA-256:   006fb7c8d3831c2990aae6cde58740af3c9f093dad886ba2f6e283cecb938ca3
# Code AST SHA-256:   0f1c329c66b26119b9defda4dfcc80c89c2707ee42f2e5329c42ea1490459236
# Verified Classes:   SelfEditWatermarkViolation, Span, EditRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class SelfEditWatermarkViolation(RuntimeError):
    """Raised when a model-driven context rewrite would destroy the cues
    needed to recover the pruned span, or would summarize a negative
    constraint into prose without a pinned copy."""
    pass


CONSTRAINT_TAGS = {"constraint", "invariant", "deprecation", "version_ceiling"}


@dataclass
class Span:
    span_id: str
    text: str
    tags: set[str] = field(default_factory=set)
    entities: set[str] = field(default_factory=set)


@dataclass
class EditRecord:
    span_id: str
    pruned_entities: set[str]
    replacement: str
    cues_preserved: bool
    checkpoint_ref: Optional[str]


def _entity_cues(text: str, entities: set[str]) -> set[str]:
    lowered = text.lower()
    return {e for e in entities if e.lower() in lowered}


def commit_self_edit(
    span: Span,
    replacement: str,
    surviving_window_text: str,
    checkpoint_ref: Optional[str],
    pinned_region: set[str],
) -> EditRecord:
    """Enforce the watermark before a self-edit is committed.

    Rules:
      1. Every entity from the pruned span must appear either in the
         replacement, in the surviving window, or in the pinned region.
      2. Any span carrying a negative-constraint tag must have a verbatim
         copy in the pinned region; prose summaries are not sufficient.
      3. If cues cannot be shown to survive and no checkpoint exists,
         the commit is refused.
    """
    # Rule 2: negative constraints must be pinned verbatim, never summarized.
    if span.tags & CONSTRAINT_TAGS:
        if span.text not in pinned_region:
            raise SelfEditWatermarkViolation(
                f"span {span.span_id!r} carries constraint tags "
                f"{sorted(span.tags)} but has no verbatim pinned copy; "
                f"refusing to summarize a binding constraint into prose"
            )

    # Rule 1: cue survival across replacement, window, and pinned region.
    haystack = " ".join([replacement, surviving_window_text, " ".join(pinned_region)])
    surviving_cues = _entity_cues(haystack, span.entities)
    lost_cues = span.entities - surviving_cues

    if lost_cues and checkpoint_ref is None:
        # Rule 3: no cue survival and no checkpoint -> refuse.
        raise SelfEditWatermarkViolation(
            f"span {span.span_id!r}: entities {sorted(lost_cues)} would be "
            f"unrecoverable after edit (no cue in replacement/window/pinned, "
            f"no checkpoint); refusing commit to avoid compaction amnesia"
        )

    if lost_cues and checkpoint_ref is not None:
        # Checkpoint exists: commit but flag that re-fetch is mandatory
        # for any action touching these entities.
        cues_preserved = False
    else:
        cues_preserved = True

    return EditRecord(
        span_id=span.span_id,
        pruned_entities=span.entities,
        replacement=replacement,
        cues_preserved=cues_preserved,
        checkpoint_ref=checkpoint_ref,
    )


def assert_edit_auditable(record: EditRecord, audit_log: list[EditRecord]) -> None:
    """The audit record must live outside the editable window; a record
    that cannot be located after the edit is itself an amnesia event."""
    digest = hashlib.sha256(
        f"{record.span_id}|{sorted(record.pruned_entities)}|{record.replacement}".encode()
    ).hexdigest()
    if not any(
        hashlib.sha256(
            f"{r.span_id}|{sorted(r.pruned_entities)}|{r.replacement}".encode()
        ).hexdigest() == digest
        for r in audit_log
    ):
        raise SelfEditWatermarkViolation(
            f"edit record for {record.span_id!r} is not present in the "
            f"external audit log; the instance cannot later discover what it removed"
        )
