# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-from-corrupting-the-agent-s-own-working-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-from-corrupting-the-agent-s-own-working-memory.warrant.json
# Markdown SHA-256:   6743373379071880848900afb087d5d1fcb880f0bf66c3e7f9b19e885b67a71e
# Code AST SHA-256:   66688ae6c837d42a435c8ba519a01794b24f03dda790b6b9875e87a11baa799d
# Verified Classes:   AnchorInvalidationError, Span, Anchor, Scratchpad
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AnchorInvalidationError(RuntimeError):
    """Raised when a structured edit would orphan a live anchor."""
    pass


@dataclass
class Span:
    start: int
    end: int

    def overlaps(self, other: "Span") -> bool:
        return self.start < other.end and other.start < self.end


@dataclass
class Anchor:
    name: str
    span: Span
    live: bool = True


@dataclass
class Scratchpad:
    content: str
    anchors: dict[str, Anchor] = field(default_factory=dict)

    def add_anchor(self, name: str, span: Span) -> None:
        self.anchors[name] = Anchor(name=name, span=span)

    def live_anchors(self) -> list[Anchor]:
        return [a for a in self.anchors.values() if a.live]

    def apply_edit(self, edit: Span, replacement: str, *, copy_on_write: bool = False) -> None:
        # Invariant check: a length-changing in-place edit must not overlap
        # any live anchor's referent span.
        length_delta = len(replacement) - (edit.end - edit.start)
        if length_delta != 0 and not copy_on_write:
            for anchor in self.live_anchors():
                if anchor.span.overlaps(edit):
                    raise AnchorInvalidationError(
                        f"edit on {edit} would reflow anchor '{anchor.name}' "
                        f"at {anchor.span}; re-derive or use copy-on-write"
                    )
        # Apply the mutation.
        self.content = self.content[: edit.start] + replacement + self.content[edit.end:]
        # If in-place and length-changing, shift downstream anchors that did not overlap.
        if length_delta != 0 and not copy_on_write:
            for anchor in self.live_anchors():
                if anchor.span.start >= edit.end:
                    anchor.span = Span(
                        anchor.span.start + length_delta,
                        anchor.span.end + length_delta,
                    )
