# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-scratchpad-rewrite-aliasing-when-a-self-editing-context-window-reuses-slot-indices-across-compaction-passes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-scratchpad-rewrite-aliasing-when-a-self-editing-context-window-reuses-slot-indices-across-compaction-passes.warrant.json
# Markdown SHA-256:   d3f56c6457a76b04ada8b8991ae3b8f0350644babc7f25dde4d9205b0f9c6477
# Code AST SHA-256:   0aacd8f4ee9a865317b6c78ce286269ee76203785d05eb88ba82fef6c963bea4
# Verified Classes:   ScratchpadAliasingError, Slot, SelfEditingScratchpad
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ScratchpadAliasingError(RuntimeError):
    """Raised when a write targets a slot index whose identity binding has changed."""
    pass


@dataclass
class Slot:
    id: str
    phase: str
    note: str = ""
    deps: tuple = ()


class SelfEditingScratchpad:
    def __init__(self, slots: list):
        self._slots: list = list(slots)
        self._id_to_index: Dict[str, int] = {s.id: i for i, s in enumerate(self._slots)}

    def compact(self, merge_pairs: list) -> Dict[int, Optional[int]]:
        """Merge adjacent same-phase slots; return old_index -> new_index | None (tombstone)."""
        remap: Dict[int, Optional[int]] = {}
        survivors = []
        merged_ids = set()
        for a, b in merge_pairs:
            merged_ids.add(self._slots[a].id)
            merged_ids.add(self._slots[b].id)
        for i, s in enumerate(self._slots):
            if s.id in merged_ids:
                remap[i] = None
                continue
            remap[i] = len(survivors)
            survivors.append(s)
        self._slots = survivors
        self._id_to_index = {s.id: i for i, s in enumerate(self._slots)}
        return remap

    def write(self, target_id: str, expected_index: int, new_phase: str, note: str = "") -> None:
        """Identity-authorized write. Fails closed if the id moved or vanished."""
        if target_id not in self._id_to_index:
            raise ScratchpadAliasingError(
                f"write to id={target_id!r} at expected_index={expected_index}: "
                f"id was compacted away (tombstoned); refusing to write to reused slot"
            )
        actual = self._id_to_index[target_id]
        if actual != expected_index:
            raise ScratchpadAliasingError(
                f"write to id={target_id!r}: caller believed index {expected_index}, "
                f"but id now lives at {actual}; stale positional reference — abort and re-read"
            )
        slot = self._slots[actual]
        slot.phase = new_phase
        slot.note = note


def advance_task(pad: SelfEditingScratchpad, task_id: str, believed_index: int) -> None:
    # Agent acts on a belief formed before a compaction pass may have run.
    pad.write(task_id, expected_index=believed_index, new_phase="ready")


if __name__ == "__main__":
    pad = SelfEditingScratchpad([
        Slot("task-A", "awaiting_dep"),
        Slot("task-B", "awaiting_dep"),
        Slot("task-C", "awaiting_dep", deps=("task-A",)),
        Slot("task-D", "awaiting_dep", deps=("task-B",)),
    ])
    # Agent reads task-C at index 2 and records that belief.
    believed = 2
    # A compaction merges task-A and task-B, shifting everything down by one.
    pad.compact([(0, 1)])
    # task-C now lives at index 1; index 2 is task-D (same phase — would fool a shape check).
    try:
        advance_task(pad, "task-C", believed_index=believed)
    except ScratchpadAliasingError as e:
        print(f"caught: {e}")
        # Correct recovery: re-read, then write against the runtime-reported index.
        pad.write("task-C", expected_index=pad._id_to_index["task-C"], new_phase="ready")
        print("recovered: task-C advanced at its true index; task-D untouched")
