{"version":132,"agent":"codex-capacity-chair","message":"Bound persistent relocation projection memory with rollback-only scratch","time":1791842416230,"timeIso":"2026-10-12T22:00:16.230Z","changes":8,"change":1284,"files":["src/engine/graph.ts","src/engine/projection-scratch.ts","src/engine/relocation-scratch.ts","src/engine/test/projection-scratch.test.ts","src/engine/test/relocation-scratch.test.ts","src/engine/view.ts"],"draft":null,"diff":[{"path":"src/engine/graph.ts","added":14,"removed":0,"diff":"--- a/src/engine/graph.ts\n+++ b/src/engine/graph.ts\n@@ -16,6 +16,7 @@\n \tstartNode,\n } from \"./keys.ts\";\n import { OrderedIndex, orderedChildKey } from \"./ordered-index.ts\";\n+import { withProjectionScratch } from \"./projection-scratch.ts\";\n import {\n \ttype GraphStateStorage,\n \ttype StateMap,\n@@ -635,6 +636,19 @@\n \tget hasOrderedChildren(): boolean {\n \t\treturn this.#storage !== undefined;\n \t}\n+\t/** Synchronous derived work against one graph identity. Scratch never commits. */\n+\twithProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T {\n+\t\tif (!this.#storage) throw new Error(\"projection scratch requires persistent graph storage\");\n+\t\tconst size = this.size;\n+\t\tconst lines = this.lineCount;\n+\t\treturn withProjectionScratch(\n+\t\t\tthis.#storage,\n+\t\t\t() => {\n+\t\t\t\tif (this.size !== size || this.lineCount !== lines) throw new Error(\"projection graph identity changed\");\n+\t\t\t},\n+\t\t\toperation,\n+\t\t);\n+\t}\n \t#childPriority(n: number): string {\n \t\tconst seq = this.writerSeqOf(n);\n \t\treturn orderedChildKey({"},{"path":"src/engine/projection-scratch.ts","added":60,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/projection-scratch.ts\n@@ -0,0 +1,60 @@\n+import type { GraphStateStorage } from \"./state-source.ts\";\n+\n+let nextScope = 0;\n+\n+/** Synchronous derived-state work only. All scratch writes roll back, even on\n+ * success. The outer canonical transaction is left intact. Returned values\n+ * must be detached data, never iterators, promises or storage handles. */\n+export function withProjectionScratch<T>(\n+\tstorage: GraphStateStorage,\n+\tvalidateIdentity: () => void,\n+\toperation: (scratch: GraphStateStorage) => T,\n+): T {\n+\tif (nextScope >= Number.MAX_SAFE_INTEGER) throw new Error(\"projection scope identity exhausted\");\n+\tconst prefix = `projection-scratch:${++nextScope}:`;\n+\tconst finished = {};\n+\tlet active = true;\n+\tlet result: T;\n+\tconst collection = (name: string): string => {\n+\t\tif (!active) throw new Error(\"projection scratch scope has ended\");\n+\t\treturn prefix + name;\n+\t};\n+\tconst scratch: GraphStateStorage = {\n+\t\tread: (name, key) => storage.read(collection(name), key),\n+\t\twrite: (name, key, value) => storage.write(collection(name), key, value),\n+\t\tremove: (name, key) => storage.remove(collection(name), key),\n+\t\t*entries(name) {\n+\t\t\tfor (const entry of storage.entries(collection(name))) {\n+\t\t\t\tcollection(name);\n+\t\t\t\tyield entry;\n+\t\t\t}\n+\t\t},\n+\t\ttransaction: (body) => {\n+\t\t\tcollection(\"\");\n+\t\t\treturn storage.transaction(body);\n+\t\t},\n+\t};\n+\ttry {\n+\t\tstorage.transaction(() => {\n+\t\t\tvalidateIdentity();\n+\t\t\tconst value = operation(scratch);\n+\t\t\tif (\n+\t\t\t\tvalue &&\n+\t\t\t\t(typeof (value as { then?: unknown }).then === \"function\" ||\n+\t\t\t\t\ttypeof (value as { next?: unknown }).next === \"function\")\n+\t\t\t)\n+\t\t\t\tthrow new Error(\"projection must complete synchronously\");\n+\t\t\t// Detach successful output before rollback; rejects embedded functions,\n+\t\t\t// storage capabilities and generators instead of leaking their scope.\n+\t\t\tresult = structuredClone(value);\n+\t\t\tvalidateIdentity();\n+\t\t\tthrow finished;\n+\t\t});\n+\t} catch (error) {\n+\t\tif (error !== finished) throw error;\n+\t\treturn result!;\n+\t} finally {\n+\t\tactive = false;\n+\t}\n+\tthrow new Error(\"storage did not propagate projection rollback\");\n+}"},{"path":"src/engine/relocation-scratch.ts","added":144,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/relocation-scratch.ts\n@@ -0,0 +1,144 @@\n+import type { Graph, RelocationInfo } from \"./graph.ts\";\n+import { isStartNode } from \"./keys.ts\";\n+import { OrderedIndex, orderedChildKey } from \"./ordered-index.ts\";\n+import type { GraphStateStorage } from \"./state-source.ts\";\n+import type { AtomId, LineId, NodeId } from \"./types.ts\";\n+\n+/** Scope-local relocation state. The caller must consume this handle inside\n+ * withProjectionScratch; selected moves and cycle bookkeeping live on disk. */\n+export function resolveScratchMoves(\n+\tgraph: Graph,\n+\thas: (id: AtomId) => boolean,\n+\tscratch: GraphStateStorage,\n+): { selected(line: LineId): RelocationInfo | undefined; parent(line: LineId): NodeId } {\n+\tconst selected = (line: LineId) => scratch.read(\"selected\", line) as RelocationInfo | undefined;\n+\tconst identity = (move: RelocationInfo) => JSON.stringify([move.atom, move.k]);\n+\tconst stronger = (a: RelocationInfo, b: RelocationInfo) => graph.comparePriority(a.atom, b.atom) > 0;\n+\tconst pick = (line: LineId): RelocationInfo | undefined => {\n+\t\tlet best: RelocationInfo | undefined;\n+\t\tfor (const move of graph.eachRelocationOf(line)) {\n+\t\t\tif (has(move.atom) && !scratch.read(\"ignored\", identity(move)) && (!best || stronger(move, best))) best = move;\n+\t\t}\n+\t\treturn best;\n+\t};\n+\tlet work = 0;\n+\tfor (const id of graph.movers()) {\n+\t\tif (!has(id)) continue;\n+\t\tfor (const move of graph.atom(id).moves!) {\n+\t\t\tif (scratch.read(\"seen\", move.line)) continue;\n+\t\t\tscratch.write(\"seen\", move.line, true);\n+\t\t\tscratch.write(\"work\", String(work++), move.line);\n+\t\t\tconst best = pick(move.line);\n+\t\t\tif (best) scratch.write(\"selected\", move.line, best);\n+\t\t}\n+\t}\n+\tconst parent = (line: LineId): NodeId => {\n+\t\tconst node = selected(line)?.parent ?? graph.lineParent(line);\n+\t\tif (node === undefined) throw new Error(`missing relocation ancestry for ${line}`);\n+\t\treturn node;\n+\t};\n+\tconst terminal = (node: NodeId | null): boolean =>\n+\t\tnode === null || isStartNode(node) || !!scratch.read(\"reached\", node);\n+\tconst step = (node: NodeId | null): NodeId | null => (terminal(node) ? null : parent(node!));\n+\tfor (let item = 0; item < work; item++) {\n+\t\tconst line = scratch.read(\"work\", String(item)) as LineId;\n+\t\tfor (;;) {\n+\t\t\t// Floyd's walk finds the exact cycle entry without a retained path.\n+\t\t\tlet slow: NodeId | null = line;\n+\t\t\tlet fast: NodeId | null = line;\n+\t\t\tlet meeting: NodeId | null = null;\n+\t\t\tfor (;;) {\n+\t\t\t\tslow = step(slow);\n+\t\t\t\tfast = step(step(fast));\n+\t\t\t\tif (terminal(slow) || terminal(fast)) break;\n+\t\t\t\tif (slow === fast) {\n+\t\t\t\t\tmeeting = slow;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif (meeting === null) {\n+\t\t\t\tlet current: NodeId = line;\n+\t\t\t\twhile (!terminal(current)) {\n+\t\t\t\t\tconst next = parent(current);\n+\t\t\t\t\tscratch.write(\"reached\", current, true);\n+\t\t\t\t\tcurrent = next;\n+\t\t\t\t}\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tlet entry: NodeId | null = line;\n+\t\t\twhile (entry !== meeting) {\n+\t\t\t\tentry = step(entry);\n+\t\t\t\tmeeting = step(meeting);\n+\t\t\t}\n+\t\t\tlet current = entry!;\n+\t\t\tlet weakest: RelocationInfo | undefined;\n+\t\t\tdo {\n+\t\t\t\tconst move = selected(current);\n+\t\t\t\tif (move && (!weakest || stronger(weakest, move))) weakest = move;\n+\t\t\t\tcurrent = parent(current);\n+\t\t\t} while (current !== entry);\n+\t\t\tif (!weakest) throw new Error(\"canonical ancestry unexpectedly cycles\");\n+\t\t\tscratch.write(\"ignored\", identity(weakest), true);\n+\t\t\tconst next = pick(weakest.line);\n+\t\t\tif (next) scratch.write(\"selected\", weakest.line, next);\n+\t\t\telse scratch.remove(\"selected\", weakest.line);\n+\t\t}\n+\t}\n+\treturn { selected, parent };\n+}\n+\n+/** Consume entirely within the projection scope. Traversal retains one line;\n+ * both priority ordering and parent links are held in rollback-only storage. */\n+export function* scratchLayoutNodes(\n+\tgraph: Graph,\n+\thas: (id: AtomId) => boolean,\n+\tscratch: GraphStateStorage,\n+\tstart: NodeId,\n+): IterableIterator<number> {\n+\tconst moves = resolveScratchMoves(graph, has, scratch);\n+\tfor (let n = 0; n < graph.lineCount; n++) {\n+\t\tif (!has(graph.idOfSeq(graph.writerSeqOf(n)))) continue;\n+\t\tconst line = graph.nodeOf(n);\n+\t\tconst move = moves.selected(line);\n+\t\tconst seq = move ? graph.atom(move.atom).seq : graph.writerSeqOf(n);\n+\t\tconst key = orderedChildKey({\n+\t\t\tn,\n+\t\t\treplaces: move ? 0 : Number(graph.replacesN(n)),\n+\t\t\tlamport: graph.lamportOfSeq(seq),\n+\t\t\tseq,\n+\t\t\tk: move ? move.k : graph.kOf(n),\n+\t\t});\n+\t\tconst parent = moves.parent(line);\n+\t\tscratch.write(\"layout-parent\", line, { parent, key });\n+\t\tnew OrderedIndex(scratch, \"layout-children\", parent).insert(key, n);\n+\t}\n+\tconst first = (parent: NodeId, after?: string): number | undefined => {\n+\t\tfor (const n of new OrderedIndex(scratch, \"layout-children\", parent).values(after)) return n;\n+\t\treturn undefined;\n+\t};\n+\tlet n = first(start);\n+\twhile (n !== undefined) {\n+\t\tyield n;\n+\t\tconst line = graph.nodeOf(n);\n+\t\tconst child = first(line);\n+\t\tif (child !== undefined) {\n+\t\t\tn = child;\n+\t\t\tcontinue;\n+\t\t}\n+\t\tlet previous = line;\n+\t\tfor (;;) {\n+\t\t\tconst row = scratch.read(\"layout-parent\", previous) as { parent: NodeId; key: string } | undefined;\n+\t\t\tif (!row) throw new Error(\"missing scratch layout ancestry\");\n+\t\t\tconst sibling = first(row.parent, row.key);\n+\t\t\tif (sibling !== undefined) {\n+\t\t\t\tn = sibling;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tif (row.parent === start) {\n+\t\t\t\tn = undefined;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tprevious = row.parent;\n+\t\t}\n+\t}\n+}"},{"path":"src/engine/test/projection-scratch.test.ts","added":98,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-scratch.test.ts\n@@ -0,0 +1,98 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { withProjectionScratch } from \"../projection-scratch.ts\";\n+import { CachedStateStorage, type GraphStateStorage } from \"../state-source.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"projection scratch is isolated, detached and rolled back inside canonical transactions\", () => {\n+\tconst source = new SqlState();\n+\tconst storage = new CachedStateStorage(source);\n+\ttry {\n+\t\tstorage.transaction(() => {\n+\t\t\tstorage.write(\"canonical\", \"before\", 1);\n+\t\t\tlet escaped: GraphStateStorage | undefined;\n+\t\t\tconst result = withProjectionScratch(\n+\t\t\t\tstorage,\n+\t\t\t\t() => {},\n+\t\t\t\t(scratch) => {\n+\t\t\t\t\tescaped = scratch;\n+\t\t\t\t\tscratch.write(\"canonical\", \"before\", 99);\n+\t\t\t\t\tconst inner = withProjectionScratch(\n+\t\t\t\t\t\tstorage,\n+\t\t\t\t\t\t() => {},\n+\t\t\t\t\t\t(nested) => {\n+\t\t\t\t\t\t\tassert.equal(nested.read(\"canonical\", \"before\"), undefined);\n+\t\t\t\t\t\t\tnested.write(\"canonical\", \"before\", 101);\n+\t\t\t\t\t\t\treturn nested.read(\"canonical\", \"before\");\n+\t\t\t\t\t\t},\n+\t\t\t\t\t);\n+\t\t\t\t\tassert.equal(inner, 101);\n+\t\t\t\t\treturn { value: scratch.read(\"canonical\", \"before\"), data: new Int32Array([1, 2]) };\n+\t\t\t\t},\n+\t\t\t);\n+\t\t\tassert.deepEqual(result, { value: 99, data: new Int32Array([1, 2]) });\n+\t\t\tassert.throws(() => escaped!.write(\"x\", \"y\", true), /ended/);\n+\t\t\tassert.equal(storage.read(\"canonical\", \"before\"), 1);\n+\t\t\tstorage.write(\"canonical\", \"after\", 2);\n+\t\t});\n+\t\tassert.equal(source.db.prepare(\"SELECT count(*) AS n FROM state\").get()!.n, 2);\n+\t\tassert.equal(storage.retainedEntries, 1);\n+\t\tassert.equal(storage.read(\"canonical\", \"after\"), 2);\n+\t} finally {\n+\t\tsource.db.close();\n+\t}\n+});\n+\n+test(\"projection errors, changed identities and escaping capabilities cannot commit scratch\", () => {\n+\tconst source = new SqlState();\n+\ttry {\n+\t\tlet checks = 0;\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\twithProjectionScratch(\n+\t\t\t\t\tsource,\n+\t\t\t\t\t() => {\n+\t\t\t\t\t\tif (++checks === 2) throw new Error(\"identity changed\");\n+\t\t\t\t\t},\n+\t\t\t\t\t(scratch) => {\n+\t\t\t\t\t\tscratch.write(\"x\", \"y\", 1);\n+\t\t\t\t\t\treturn 2;\n+\t\t\t\t\t},\n+\t\t\t\t),\n+\t\t\t/identity changed/,\n+\t\t);\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\twithProjectionScratch(\n+\t\t\t\t\tsource,\n+\t\t\t\t\t() => {},\n+\t\t\t\t\t(scratch) => {\n+\t\t\t\t\t\tscratch.write(\"x\", \"y\", 1);\n+\t\t\t\t\t\tthrow new Error(\"failed computation\");\n+\t\t\t\t\t},\n+\t\t\t\t),\n+\t\t\t/failed computation/,\n+\t\t);\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\twithProjectionScratch(\n+\t\t\t\t\tsource,\n+\t\t\t\t\t() => {},\n+\t\t\t\t\t(scratch) => scratch,\n+\t\t\t\t),\n+\t\t\t/clone|cloned/i,\n+\t\t);\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\twithProjectionScratch(\n+\t\t\t\t\tsource,\n+\t\t\t\t\t() => {},\n+\t\t\t\t\t() => Promise.resolve(1),\n+\t\t\t\t),\n+\t\t\t/synchronously/,\n+\t\t);\n+\t\tassert.equal(source.db.prepare(\"SELECT count(*) AS n FROM state\").get()!.n, 0);\n+\t} finally {\n+\t\tsource.db.close();\n+\t}\n+});"},{"path":"src/engine/test/relocation-scratch.test.ts","added":135,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/relocation-scratch.test.ts\n@@ -0,0 +1,135 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { Graph } from \"../graph.ts\";\n+import { withProjectionScratch } from \"../projection-scratch.ts\";\n+import { resolveScratchMoves } from \"../relocation-scratch.ts\";\n+import { CachedStateStorage, StableOverlaySet } from \"../state-source.ts\";\n+import { View } from \"../view.ts\";\n+import { Repo, Rng } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"scratch relocation cycle selection matches View across differing memberships and tied moves\", () => {\n+\tconst rng = new Rng(45131);\n+\tconst source = new SqlState();\n+\tconst storage = new CachedStateStorage(source, 4096, 16);\n+\ttry {\n+\t\tfor (let trial = 0; trial < 24; trial++) {\n+\t\t\tconst repo = Repo.init({ \"f.txt\": Array.from({ length: 24 }, (_, n) => `line ${n}\\n`).join(\"\"), \"g.txt\": \"\" });\n+\t\t\tconst earlier = new Set(repo.shared);\n+\t\t\tfor (let j = 0; j < 32; j++) {\n+\t\t\t\tconst offset = rng.int(24);\n+\t\t\t\tconst moves = Array.from({ length: 3 }, (_, index) => {\n+\t\t\t\t\tconst line = `a0.${(offset + index) % 24}`;\n+\t\t\t\t\tconst candidate = `a0.${rng.int(24)}`;\n+\t\t\t\t\treturn { line, parent: candidate === line ? (j % 2 ? \"^f.txt\" : \"^g.txt\") : candidate };\n+\t\t\t\t});\n+\t\t\t\tconst id = repo.graph.nextId();\n+\t\t\t\trepo.graph.add({\n+\t\t\t\t\tid,\n+\t\t\t\t\tseq: repo.graph.size,\n+\t\t\t\t\tauthor: \"fixture\",\n+\t\t\t\t\tmessage: \"move\",\n+\t\t\t\t\ttime: j,\n+\t\t\t\t\tinserts: [],\n+\t\t\t\t\tdeletes: [],\n+\t\t\t\t\twrites: moves.flatMap((move) => [`P:${move.line}`, `G:${move.parent}`]),\n+\t\t\t\t\treads: [],\n+\t\t\t\t\tholds: [],\n+\t\t\t\t\tneeds: [],\n+\t\t\t\t\tresolves: [],\n+\t\t\t\t\treasons: [],\n+\t\t\t\t\tdeps: [\"a0\"],\n+\t\t\t\t\tmoves,\n+\t\t\t\t});\n+\t\t\t\trepo.shared.add(id);\n+\t\t\t\tif (j < 16) earlier.add(id);\n+\t\t\t}\n+\t\t\tfor (const membership of [repo.shared, earlier, repo.shared]) {\n+\t\t\t\tconst oracle = new View(repo.graph, membership);\n+\t\t\t\tconst parents = withProjectionScratch(\n+\t\t\t\t\tstorage,\n+\t\t\t\t\t() => {},\n+\t\t\t\t\t(scratch) => {\n+\t\t\t\t\t\tconst resolved = resolveScratchMoves(repo.graph, (id) => membership.has(id), scratch);\n+\t\t\t\t\t\treturn Array.from({ length: 24 }, (_, n) => resolved.parent(`a0.${n}`));\n+\t\t\t\t\t},\n+\t\t\t\t);\n+\t\t\t\tassert.deepEqual(\n+\t\t\t\t\tparents,\n+\t\t\t\t\tArray.from({ length: 24 }, (_, n) => oracle.parentOf(`a0.${n}`)),\n+\t\t\t\t);\n+\t\t\t\tassert.equal(source.db.prepare(\"SELECT count(*) AS n FROM state\").get()!.n, 0);\n+\t\t\t\tassert.equal(storage.retainedEntries, 0);\n+\t\t\t}\n+\t\t\tif (trial < 4) {\n+\t\t\t\tconst persisted = new SqlState();\n+\t\t\t\ttry {\n+\t\t\t\t\tconst indexed = new Graph({ storage: new CachedStateStorage(persisted, 8192, 32) });\n+\t\t\t\t\tfor (const id of repo.shared) indexed.add(repo.graph.atom(id));\n+\t\t\t\t\tconst before = persisted.db.prepare(\"SELECT * FROM state ORDER BY collection, key\").all();\n+\t\t\t\t\t// Restart before projecting, then alternate membership on the same graph.\n+\t\t\t\t\tconst reopened = new Graph({ storage: new CachedStateStorage(persisted, 8192, 32) });\n+\t\t\t\t\tfor (const membership of [repo.shared, earlier, repo.shared]) {\n+\t\t\t\t\t\tconst expected = new View(repo.graph, membership);\n+\t\t\t\t\t\tconst actual = new View(reopened, new StableOverlaySet(membership));\n+\t\t\t\t\t\tfor (const path of [\"f.txt\", \"g.txt\"]) {\n+\t\t\t\t\t\t\tassert.equal(actual.text(path), expected.text(path));\n+\t\t\t\t\t\t\tassert.deepEqual(actual.sequence(path), expected.sequence(path));\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tfor (const n of [0, 11, 23]) {\n+\t\t\t\t\t\t\tassert.equal(actual.parentOf(`a0.${n}`), expected.parentOf(`a0.${n}`));\n+\t\t\t\t\t\t\tassert.equal(actual.fileOf(`a0.${n}`), expected.fileOf(`a0.${n}`));\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tassert.deepEqual(persisted.db.prepare(\"SELECT * FROM state ORDER BY collection, key\").all(), before);\n+\t\t\t\t\t}\n+\t\t\t\t} finally {\n+\t\t\t\t\tpersisted.db.close();\n+\t\t\t\t}\n+\t\t\t}\n+\t\t}\n+\t} finally {\n+\t\tsource.db.close();\n+\t}\n+});\n+\n+test(\"scratch relocation write failure rolls back without changing canonical graph state\", () => {\n+\tconst repo = Repo.init({ f: \"one\\ntwo\\n\" });\n+\tconst source = new SqlState();\n+\ttry {\n+\t\trepo.graph.add({\n+\t\t\tid: \"a1\",\n+\t\t\tseq: 1,\n+\t\t\tauthor: \"fixture\",\n+\t\t\tmessage: \"move\",\n+\t\t\ttime: 1,\n+\t\t\tinserts: [],\n+\t\t\tdeletes: [],\n+\t\t\twrites: [\"P:a0.0\", \"G:a0.1\"],\n+\t\t\treads: [],\n+\t\t\tholds: [],\n+\t\t\tneeds: [],\n+\t\t\tresolves: [],\n+\t\t\treasons: [],\n+\t\t\tdeps: [\"a0\"],\n+\t\t\tmoves: [{ line: \"a0.0\", parent: \"a0.1\" }],\n+\t\t});\n+\t\trepo.shared.add(\"a1\");\n+\t\tconst before = { size: repo.graph.size, lines: repo.graph.lineCount };\n+\t\tsource.failWrite = 3;\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\twithProjectionScratch(\n+\t\t\t\t\tsource,\n+\t\t\t\t\t() => {},\n+\t\t\t\t\t(scratch) => {\n+\t\t\t\t\t\tresolveScratchMoves(repo.graph, (id) => repo.shared.has(id), scratch);\n+\t\t\t\t\t},\n+\t\t\t\t),\n+\t\t\t/injected storage failure/,\n+\t\t);\n+\t\tassert.deepEqual({ size: repo.graph.size, lines: repo.graph.lineCount }, before);\n+\t\tassert.equal(source.db.prepare(\"SELECT count(*) AS n FROM state\").get()!.n, 0);\n+\t} finally {\n+\t\tsource.db.close();\n+\t}\n+});"},{"path":"src/engine/view.ts","added":27,"removed":1,"diff":"--- a/src/engine/view.ts\n+++ b/src/engine/view.ts\n@@ -11,6 +11,7 @@\n \n import type { Graph, RelocationInfo } from \"./graph.ts\";\n import { isStartNode } from \"./keys.ts\";\n+import { resolveScratchMoves, scratchLayoutNodes } from \"./relocation-scratch.ts\";\n import { StableSet } from \"./state-source.ts\";\n import { joinLines } from \"./text.ts\";\n import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from \"./types.ts\";\n@@ -264,6 +265,11 @@\n \n \t/** The node a line hangs off in this set: where it was written, or where a move put it. */\n \tparentOf(line: LineId): NodeId {\n+\t\tif (this.graph.lineParent(line) === undefined) throw new EngineError(\"unknown-line\", `no line ${line}`);\n+\t\tif (this.#hasMoves && this.graph.hasOrderedChildren)\n+\t\t\treturn this.graph.withProjectionScratch((scratch) =>\n+\t\t\t\tresolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line),\n+\t\t\t);\n \t\tconst r = this.#hasMoves ? this.#relocations().get(line) : undefined;\n \t\tif (r) return r.parent;\n \t\tconst parent = this.graph.lineParent(line);\n@@ -290,6 +296,13 @@\n \t#fileOfN(n: number): string {\n \t\tconst graph = this.graph;\n \t\tif (!this.#hasMoves) return graph.writtenIn(n);\n+\t\tif (graph.hasOrderedChildren)\n+\t\t\treturn graph.withProjectionScratch((scratch) => {\n+\t\t\t\tconst moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch);\n+\t\t\t\tlet current = graph.nodeOf(n);\n+\t\t\t\twhile (!isStartNode(current)) current = moves.parent(current);\n+\t\t\t\treturn current.slice(1);\n+\t\t\t});\n \t\tconst relocs = this.#relocationsN();\n \t\t// Keep only a fixed tail of the walk for path compression. The selected\n \t\t// relocation graph is acyclic, so traversal needs no history-sized stack.\n@@ -396,6 +409,19 @@\n \t/** Lay out one file: its line tree from the set's atoms, linearized. */\n \t#layout(path: string, complete: boolean): FileState {\n \t\tconst graph = this.graph;\n+\t\tif (this.#hasMoves && graph.hasOrderedChildren)\n+\t\t\treturn graph.withProjectionScratch((scratch) =>\n+\t\t\t\tthis.#layoutResolved(\n+\t\t\t\t\tpath,\n+\t\t\t\t\tcomplete,\n+\t\t\t\t\tscratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`),\n+\t\t\t\t),\n+\t\t\t);\n+\t\treturn this.#layoutResolved(path, complete);\n+\t}\n+\n+\t#layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState {\n+\t\tconst graph = this.graph;\n \t\t// For each attribute, the highest-priority setter in the set wins.\n \t\tconst setters = new Map<string, { id: AtomId; value: string | null }>();\n \t\tfor (const id of graph.eachAtomIn(path)) {\n@@ -413,7 +439,7 @@\n \n \t\tconst start = graph.startCodeOf(path);\n \t\tconst priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;\n-\t\tfor (const n of start === undefined ? [] : this.#layoutNodes(start)) {\n+\t\tfor (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) {\n \t\t\tlet deleted = false;\n \t\t\tconst by: number[] = [];\n \t\t\tfor (const deleter of graph.eachDeleterSeqOf(n)) {"}],"ci":null}