# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-self-editing-of-its-own-context-window-as-a-transactional-mutation-rather-than-an-in-place-rewrite-and-what-i.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-self-editing-of-its-own-context-window-as-a-transactional-mutation-rather-than-an-in-place-rewrite-and-what-i.warrant.json
# Markdown SHA-256:   a43b25636631ffdd625c750913141a2acc12ba75f6fa6810a1ca822d15d1f5ae
# Code AST SHA-256:   4e879fc147f5b3a0f9a20ac3171b480182d484823cacb343fdaa134bd3240d11
# Verified Classes:   AnchorResolutionError, ProtectedRegionViolation, Span, ContextBuffer
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class AnchorResolutionError(RuntimeError):
    """Raised when a self-edit cannot be resolved against the live buffer."""
    pass


class ProtectedRegionViolation(RuntimeError):
    """Raised when a self-edit targets a region whose loss is undetectable."""
    pass


@dataclass
class Span:
    anchor: str          # content hash of the span at snapshot time
    start: int
    end: int
    text: str
    protected: bool = False


def _hash(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]


@dataclass
class ContextBuffer:
    spans: list[Span] = field(default_factory=list)
    edit_log: list[dict] = field(default_factory=list)

    def snapshot(self) -> dict[str, Span]:
        # Anchors are content hashes; duplicate content collapses, which is
        # exactly why ambiguous anchors must fail closed rather than guess.
        return {s.anchor: s for s in self.spans}

    def apply_transaction(self, edits: list[dict]) -> None:
        """Apply a batch of self-edits atomically against the pre-batch snapshot.

        Each edit: {"op": "delete"|"replace"|"summarize", "anchor": str, ...}
        All anchors resolve against the snapshot taken before any edit lands.
        If any anchor is missing, ambiguous, or protected, the whole batch
        is rejected and the buffer is left untouched.
        """
        snap = self.snapshot()
        resolved: list[tuple[Span, dict]] = []

        for edit in edits:
            anchor = edit.get("anchor")
            if anchor is None:
                raise AnchorResolutionError(
                    f"edit {edit!r} has no content anchor; positional self-edits "
                    f"are forbidden because offsets drift within a batch"
                )
            if anchor not in snap:
                raise AnchorResolutionError(
                    f"anchor {anchor!r} not present in pre-batch snapshot; "
                    f"target was likely deleted or rewritten by an earlier edit"
                )
            target = snap[anchor]
            if target.protected:
                raise ProtectedRegionViolation(
                    f"anchor {anchor!r} resolves to protected region "
                    f"(spec/constraints/anchor-table/edit-log); loss would be "
                    f"undetectable from the model's own trace"
                )
            resolved.append((target, edit))

        # Commit phase: only reached if every anchor validated.
        drop = {id(t) for t, e in resolved if e["op"] == "delete"}
        new_spans: list[Span] = []
        for s in self.spans:
            if id(s) in drop:
                self.edit_log.append({"op": "delete", "anchor": s.anchor,
                                      "hash": _hash(s.text)})
                continue
            new_spans.append(s)

        for target, edit in resolved:
            if edit["op"] == "replace":
                replacement = edit["text"]
                if _hash(replacement) == target.anchor:
                    continue
                new_spans.append(Span(anchor=_hash(replacement),
                                      start=target.start, end=target.end,
                                      text=replacement,
                                      protected=target.protected))
                self.edit_log.append({"op": "replace",
                                      "anchor": target.anchor,
                                      "hash": _hash(replacement)})
            elif edit["op"] == "summarize":
                summary = edit["summary"]
                if not summary:
                    raise AnchorResolutionError(
                        f"summarize of {target.anchor!r} produced empty summary; "
                        f"refusing to commit a silent full deletion"
                    )
                new_spans.append(Span(anchor=_hash(summary),
                                      start=target.start, end=target.end,
                                      text=summary, protected=False))
                self.edit_log.append({"op": "summarize",
                                      "anchor": target.anchor,
                                      "hash": _hash(summary)})

        self.spans = new_spans
        # Edit log is append-only and never itself summarized; a later step
        # can always ask "what did I destroy?" and get a truthful answer.

    def render_for_model(self) -> str:
        """Post-commit re-render; model must reason over this, not its stale view."""
        body = "\n---\n".join(s.text for s in self.spans)
        log = "\n".join(f"{e['op']} {e['anchor']} -> {e['hash']}"
                        for e in self.edit_log[-20:])
        return f"{body}\n\n==EDIT LOG==\n{log}"


# --- demonstrating the failure the guardrail prevents -------------------

def compress_working_set(buf: ContextBuffer) -> None:
    spec = next((s for s in buf.spans if s.protected), None)
    if spec is None:
        raise ProtectedRegionViolation(
            "no protected task-spec span present; refusing to compress because "
            "the constraint list cannot be guaranteed to survive"
        )
    # Model intent expressed as anchors, never offsets.
    stale_plan = next((s for s in buf.spans
                       if not s.protected and "PLAN_v3" in s.text), None)
    if stale_plan is None:
        raise AnchorResolutionError(
            "stale plan anchor <<PLAN_v3>> not found; cannot safely delete"
        )
    buf.apply_transaction([
        {"op": "delete", "anchor": stale_plan.anchor},
        # If this second edit carried a stale offset instead of an anchor,
        # it would silently overwrite the spec. The anchor check rejects it.
        {"op": "replace", "anchor": spec.anchor, "text": "..."},
    ])
