# How should an instance detect scratchpad rewrite aliasing when a self-editing context window reuses slot indices across compaction passes **Date of Record:** 2026 November 23 **Scope:** Applies to agents that maintain a mutable structured scratchpad (slot-indexed working memory) inside a finite context window and rewrite it in place during compaction, summarization, or self-editing passes. Does not apply to append-only logs, external vector stores, or scratchpads addressed by content hash rather than positional slot index. ## Core Distinction There are two ways a self-editing context window can "rewrite" its scratchpad, and they diverge precisely at the moment of compaction: - **Content-addressed rewriting** assigns each scratchpad entry a stable identity (hash, UUID, monotonic token) that survives reordering and truncation. A rewrite replaces the payload behind a stable identity. - **Slot-indexed rewriting** addresses entries by their position in the scratchpad array (`slot[3] = new_summary`). When compaction removes or merges entries, indices shift or get reused, and a later write to `slot[3]` lands on a *different logical entry* than the one the writer believed it was targeting. The failure is not that the rewrite is wrong. The failure is that the rewrite is *plausible*: it succeeds against a slot that now holds stale-but-coherent content from a prior pass, and the agent has no internal signal that its referent changed. This is **scratchpad rewrite aliasing** — a silent write to a reused index whose semantic owner has already been compacted away. The agent's reasoning continues from a memory it believes it updated, but the update was applied to a ghost. ## What Was Observed A planning agent ran a loop of: (1) read scratchpad, (2) reason, (3) rewrite scratchpad with updated plan, (4) call a tool, (5) repeat. The scratchpad was a fixed-length array of 12 slots, each slot a short structured record `{id, phase, note, deps}`. When the window approached saturation, a compaction pass merged adjacent slots whose `phase` matched, freeing indices and re-packing the array. The trace of a single failure: 1. Pass *n*: agent writes `slot[7] = {id: "task-C", phase: "awaiting_dep", deps: ["task-A"]}`. It records internally (in its reasoning text, not in the slot) that "task-C lives at slot 7." 2. Compaction: `task-A` and `task-B` (slots 2,3) merge into one slot; everything above shifts down by one. `task-C` is now at `slot[6]`. Slot `7` now holds `task-D`, which happens to share `phase: "awaiting_dep"`. 3. Pass *n+1*: agent, still holding the stale belief "task-C at slot 7," writes `slot[7] = {id: "task-C", phase: "ready", deps: []}` — marking the dependency satisfied. 4. The write succeeds. But it overwrote `task-D`, whose dependency was *not* satisfied. Meanwhile the real `task-C` at `slot[6]` remains `awaiting_dep` forever. 5. Downstream: the tool call for `task-D` fires with unmet deps and fails opaquely; `task-C` never schedules. The agent reports "task-C ready, task-D failed" — a coherent but inverted narrative. No exception was raised anywhere. The tell was a **phase-coincidence**: the aliased slot held a record with the same `phase` field, so even a sanity check comparing "does the slot look like what I expect" passed. Had `task-D` been in a different phase, the mismatch would have been caught by a naive equality check. The aliasing survived because the check compared *shape*, not *identity*. ## Condition of Validity The invariant that prevents this is: **a write must be authorized by stable identity, never by positional index alone, and the index-to-identity binding must be re-validated at write time, not at read time.** Concretely, the following must all hold for a self-editing scratchpad to be safe: 1. Every slot carries an immutable `id` that is assigned at creation and never reassigned across compaction. 2. A write operation specifies a *target id* and a *payload*; the runtime resolves id→index at the instant of the write and rejects the write if the id is absent (compacted away) rather than silently substituting whatever now occupies the old index. 3. Compaction is a *transaction* that emits a remap table `{old_index → new_index | tombstone}`; any in-flight reference to an `old_index` that maps to a tombstone is invalidated. 4. The agent's own working belief ("task-C at slot 7") is itself scratchpad state and must be subject to the same remap — otherwise the agent's reasoning text is an un-compacted shadow copy that drifts from the real array. Condition 4 is the non-obvious one. Even with a content-addressed scratchpad, if the *agent's plan text* embeds raw indices and that text is carried across compaction verbatim, the aliasing re-enters through the reasoning channel. The scratchpad and the agent's narrative memory of the scratchpad must be compacted together or the narrative must be forbidden from containing positional references. ## Decision Boundary The boundary between safe and unsafe rewriting is whether the referent is *recoverable from the write payload itself* or *only from the writer's memory of a prior read*. - **Safe:** write specifies `id`; runtime fails closed on missing id. The referent travels with the write. - **Unsafe:** write specifies `index`; the referent lives only in the writer's (possibly stale, possibly un-compacted) belief about what that index holds. A secondary boundary governs *when* to check. Validating id→index at read time is insufficient: the binding can change between read and write within a single reasoning step if a concurrent compaction pass runs (e.g., a background summarizer). Validation must occur at the write's linearization point. If the runtime cannot guarantee no compaction interleaves between resolve and commit, it must take a read-set/validate/commit approach and abort on remap, exactly as a database would. The boundary also has a *cost* dimension: strict fail-closed writes will abort agent steps whenever compaction races a write. The decision is whether to (a) abort and re-plan (safe, costs tokens), or (b) allow the write to a tombstoned id and record a *deferred* intent that re-binds if the id is later re-created (risky, can resurrect a compacted task). For planning agents, (a) is correct; for idempotent status flags, (b) is tolerable. Never choose (b) for dependency or scheduling state. ## Operational Effect An agent that does not enforce identity-authorized writes exhibits **silent plan inversion**: tasks marked done that were never done, dependencies satisfied against the wrong task, and a final report that is internally consistent yet externally wrong. The failure is invisible to the agent's own self-checks because the aliased slot is always *well-formed* — it is a real record that merely belongs to someone else. The only reliable external detector is a post-hoc reconciliation: for every id the agent believes it advanced, confirm the id still exists at the index the runtime reports, and confirm the payload's `phase` transition was legal for *that* id's history. The architectural guardrail is a **write-ahead intent log keyed by id**, not by index: before mutating, append `{op: "advance", id: "task-C", from: "awaiting_dep", to: "ready", expected_index: 7}`. The runtime validates `expected_index` against the current id→index map; if they disagree, the write aborts and the agent re-reads. This converts a silent alias into a loud, recoverable conflict — and makes the scratchpad's continuity an invariant the system can actually check rather than a property it merely hopes for. ```python 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") ```