{"version":146,"agent":"codex-capacity-chair","message":"Page atom adoption and move reconciliation with restart-safe private state","time":1791858113718,"timeIso":"2026-10-13T02:21:53.718Z","changes":12,"change":1284,"files":["src/engine/experimental/projection-atom-adoption.ts","src/engine/experimental/projection-marker.ts","src/engine/experimental/projection-move-adoption.ts","src/engine/experimental/projection-move-resolution.ts","src/engine/test/projection-atom-adoption.test.ts","src/engine/test/projection-marker-cycle.test.ts","src/engine/test/projection-move-resolution.test.ts"],"draft":null,"diff":[{"path":"src/engine/experimental/projection-atom-adoption.ts","added":293,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-atom-adoption.ts\n@@ -0,0 +1,293 @@\n+import { createHash } from \"node:crypto\";\n+import type { Atom } from \"../types.ts\";\n+import type { ExperimentalMarkerProjection, MarkerState } from \"./projection-marker.ts\";\n+import { adoptMovesStep } from \"./projection-move-adoption.ts\";\n+\n+const phases = [\n+\t\"dependencies\",\n+\t\"files\",\n+\t\"lines\",\n+\t\"deletes\",\n+\t\"counts\",\n+\t\"attributes\",\n+\t\"contributions\",\n+\t\"membership\",\n+\t\"moves\",\n+\t\"cleanup\",\n+\t\"done\",\n+] as const;\n+type Phase = (typeof phases)[number];\n+interface Cursor {\n+\tidentity: string;\n+\tphase: Phase;\n+\tindex: number;\n+\trun: number;\n+\tline: number;\n+\tk: number;\n+\tstate: MarkerState;\n+}\n+const digest = (value: unknown) => createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n+function shape(value: unknown, names: string): asserts value is Record<string, unknown> {\n+\tconst keys = names.split(\" \");\n+\tif (\n+\t\t!value ||\n+\t\ttypeof value !== \"object\" ||\n+\t\tArray.isArray(value) ||\n+\t\tObject.keys(value).length !== keys.length ||\n+\t\tkeys.some((key) => !Object.hasOwn(value, key))\n+\t)\n+\t\tthrow Error(\"invalid atom adoption record\");\n+}\n+function readCursor(value: unknown): Cursor | undefined {\n+\tif (value === undefined) return undefined;\n+\tshape(value, \"format checksum cursor\");\n+\tif (value.format !== 1 || typeof value.checksum !== \"string\" || value.checksum !== digest(value.cursor))\n+\t\tthrow Error(\"damaged atom adoption cursor\");\n+\tshape(value.cursor, \"identity phase index run line k state\");\n+\tconst cursor = value.cursor;\n+\tshape(cursor.state, \"context sequence locator membership children attributeFiles\");\n+\tfor (const key of [\"locator\", \"membership\", \"children\", \"attributeFiles\"])\n+\t\tif (cursor.state[key] !== null && (!Number.isSafeInteger(cursor.state[key]) || Number(cursor.state[key]) < 0))\n+\t\t\tthrow Error(\"invalid atom adoption page reference\");\n+\tshape(cursor.state.sequence, \"map root next\");\n+\tconst sequence = cursor.state.sequence;\n+\tif (\n+\t\t!Number.isSafeInteger(sequence.next) ||\n+\t\tNumber(sequence.next) < 0 ||\n+\t\tNumber(sequence.next) > 2 ** 32 ||\n+\t\t(sequence.map !== null && (!Number.isSafeInteger(sequence.map) || Number(sequence.map) < 0)) ||\n+\t\t(sequence.root !== null &&\n+\t\t\t(!Number.isSafeInteger(sequence.root) ||\n+\t\t\t\tNumber(sequence.root) < 0 ||\n+\t\t\t\tNumber(sequence.root) >= Number(sequence.next))) ||\n+\t\t(sequence.root === null) !== (sequence.next === 0) ||\n+\t\t(sequence.map === null) !== (sequence.root === null)\n+\t)\n+\t\tthrow Error(\"invalid atom adoption sequence\");\n+\treturn cursor as unknown as Cursor;\n+}\n+\n+/** Private adoption experiment. Partial state must never be published as a read root.\n+ * The host must pin source identity and atomically retain this cursor with each page.\n+ * Move reconciliation advances through private persisted pages.\n+ */\n+export class ProjectionAtomAdoption {\n+\treadonly adapter: ExperimentalMarkerProjection;\n+\treadonly task: string;\n+\tconstructor(adapter: ExperimentalMarkerProjection, task: string) {\n+\t\tif (!task || task.length > 128) throw Error(\"invalid atom adoption task\");\n+\t\tthis.adapter = adapter;\n+\t\tthis.task = task;\n+\t}\n+\tpage(input: {\n+\t\tprevious: MarkerState;\n+\t\tatom: Atom;\n+\t\tremove: boolean;\n+\t\tsource: string;\n+\t\tmaxSteps: number;\n+\t\tvalidateSource(): void;\n+\t}): {\n+\t\tdone: boolean;\n+\t\tstate: MarkerState;\n+\t\tsteps: number;\n+\t\tatomicMoveWork: boolean;\n+\t} {\n+\t\tconst { adapter: p } = this;\n+\t\tif (\n+\t\t\t!/^[a-f0-9]{64}$/.test(input.source) ||\n+\t\t\t!Number.isSafeInteger(input.maxSteps) ||\n+\t\t\tinput.maxSteps < 1 ||\n+\t\t\tinput.maxSteps > 256\n+\t\t)\n+\t\t\tthrow Error(\"invalid atom adoption page bounds\");\n+\t\tconst atom = input.atom;\n+\t\tconst identity = digest([input.source, input.previous, atom, input.remove]);\n+\t\tif (digest(p.graph.atom(atom.id)) !== digest(atom)) throw Error(\"canonical adoption atom mismatch\");\n+\t\tconst collection = `atom-adoption:${this.task}`;\n+\t\tconst validate = () => {\n+\t\t\tconst result: unknown = input.validateSource();\n+\t\t\tif (result && typeof result === \"object\" && \"then\" in result)\n+\t\t\t\tthrow Error(\"atom adoption source validation must be synchronous\");\n+\t\t};\n+\t\treturn p.storage.transaction(() => {\n+\t\t\tvalidate();\n+\t\t\tlet cursor = readCursor(p.storage.read(collection, \"cursor\"));\n+\t\t\tif (cursor !== undefined) {\n+\t\t\t\tif (\n+\t\t\t\t\t!cursor ||\n+\t\t\t\t\tcursor.identity !== identity ||\n+\t\t\t\t\t!phases.includes(cursor.phase) ||\n+\t\t\t\t\t![cursor.index, cursor.run, cursor.line, cursor.k].every((n) => Number.isSafeInteger(n) && n >= 0)\n+\t\t\t\t)\n+\t\t\t\t\tthrow Error(\"invalid or changed atom adoption cursor\");\n+\t\t\t\tp.assertContext(cursor.state);\n+\t\t\t\tif (cursor.run > atom.inserts.length || cursor.line > (atom.inserts[cursor.run]?.lines.length ?? 0))\n+\t\t\t\t\tthrow Error(\"invalid atom adoption line position\");\n+\t\t\t\tconst limits: Record<Phase, number> = {\n+\t\t\t\t\tdependencies: atom.deps.length,\n+\t\t\t\t\tfiles: atom.inserts.length + 1,\n+\t\t\t\t\tlines: 0,\n+\t\t\t\t\tdeletes: atom.deletes.length,\n+\t\t\t\t\tcounts: atom.deps.length,\n+\t\t\t\t\tattributes: atom.attrs?.length ?? 0,\n+\t\t\t\t\tcontributions: p.graph.filesOf(atom.id).length,\n+\t\t\t\t\tmembership: 0,\n+\t\t\t\t\tmoves: 0,\n+\t\t\t\t\tcleanup: atom.attrs?.length ?? 0,\n+\t\t\t\t\tdone: 0,\n+\t\t\t\t};\n+\t\t\t\tif (cursor.index > limits[cursor.phase]) throw Error(\"invalid atom adoption phase position\");\n+\t\t\t} else {\n+\t\t\t\tp.assertContext(input.previous);\n+\t\t\t\tconst member = p.members.get(input.previous.membership, atom.seq);\n+\t\t\t\tif (input.remove && member?.dependents) throw Error(\"included dependent prevents removal\");\n+\t\t\t\tcursor = {\n+\t\t\t\t\tidentity,\n+\t\t\t\t\tphase: (member?.present ?? false) === !input.remove ? \"done\" : \"dependencies\",\n+\t\t\t\t\tindex: 0,\n+\t\t\t\t\trun: 0,\n+\t\t\t\t\tline: 0,\n+\t\t\t\t\tk: 0,\n+\t\t\t\t\tstate: structuredClone(input.previous),\n+\t\t\t\t};\n+\t\t\t}\n+\t\t\tlet steps = 0;\n+\t\t\tconst atomicMoveWork = false;\n+\t\t\tconst next = () => {\n+\t\t\t\tcursor!.phase = phases[phases.indexOf(cursor!.phase) + 1]!;\n+\t\t\t\tcursor!.index = 0;\n+\t\t\t};\n+\t\t\tconst state = cursor.state;\n+\t\t\tconst contributionFiles = p.graph.filesOf(atom.id);\n+\t\t\twhile (cursor.phase !== \"done\" && steps < input.maxSteps) {\n+\t\t\t\tsteps++;\n+\t\t\t\tswitch (cursor.phase) {\n+\t\t\t\t\tcase \"dependencies\": {\n+\t\t\t\t\t\tif (input.remove || cursor.index === atom.deps.length) {\n+\t\t\t\t\t\t\tnext();\n+\t\t\t\t\t\t\tbreak;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tconst id = atom.deps[cursor.index++]!;\n+\t\t\t\t\t\tif (!p.members.get(state.membership, p.graph.atom(id).seq)?.present) throw Error(\"missing dependency\");\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tcase \"files\": {\n+\t\t\t\t\t\tif (input.remove || cursor.index > atom.inserts.length) {\n+\t\t\t\t\t\t\tnext();\n+\t\t\t\t\t\t\tbreak;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tp.ensureFile(state, cursor.index === 0 ? p.path : atom.inserts[cursor.index - 1]!.file);\n+\t\t\t\t\t\tcursor.index++;\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tcase \"lines\": {\n+\t\t\t\t\t\tif (cursor.run === atom.inserts.length) {\n+\t\t\t\t\t\t\tnext();\n+\t\t\t\t\t\t\tbreak;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tconst run = atom.inserts[cursor.run]!;\n+\t\t\t\t\t\tif (cursor.line === run.lines.length) {\n+\t\t\t\t\t\t\tcursor.run++;\n+\t\t\t\t\t\t\tcursor.line = 0;\n+\t\t\t\t\t\t\tbreak;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tconst line = `${atom.id}.${cursor.k++}`;\n+\t\t\t\t\t\tcursor.line++;\n+\t\t\t\t\t\tif (!input.remove) p.insertLine(state, line);\n+\t\t\t\t\t\telse {\n+\t\t\t\t\t\t\tconst marker = p.markers.get(state.locator, p.graph.lineN(line) + 1);\n+\t\t\t\t\t\t\tif (!marker) throw Error(\"missing inserted marker\");\n+\t\t\t\t\t\t\tstate.sequence = p.sequence.update(state.sequence, { kind: \"visibility\", id: marker.enter, delta: 1 });\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tcase \"deletes\": {\n+\t\t\t\t\t\tif (cursor.index === atom.deletes.length) {\n+\t\t\t\t\t\t\tnext();\n+\t\t\t\t\t\t\tbreak;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tconst marker = p.markers.get(state.locator, p.graph.lineN(atom.deletes[cursor.index++]!) + 1);\n+\t\t\t\t\t\tif (!marker) throw Error(\"missing deleted marker\");\n+\t\t\t\t\t\tstate.sequence = p.sequence.update(state.sequence, {\n+\t\t\t\t\t\t\tkind: \"visibility\",\n+\t\t\t\t\t\t\tid: marker.enter,\n+\t\t\t\t\t\t\tdelta: input.remove ? -1 : 1,\n+\t\t\t\t\t\t});\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tcase \"counts\": {\n+\t\t\t\t\t\tif (cursor.index === atom.deps.length) {\n+\t\t\t\t\t\t\tnext();\n+\t\t\t\t\t\t\tbreak;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tconst seq = p.graph.atom(atom.deps[cursor.index++]!).seq;\n+\t\t\t\t\t\tconst member = p.members.get(state.membership, seq);\n+\t\t\t\t\t\tif (!member?.present || (input.remove && member.dependents < 1)) throw Error(\"invalid dependency count\");\n+\t\t\t\t\t\tstate.membership = p.members.set(state.membership, seq, {\n+\t\t\t\t\t\t\t...member,\n+\t\t\t\t\t\t\tdependents: member.dependents + (input.remove ? -1 : 1),\n+\t\t\t\t\t\t});\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tcase \"attributes\": {\n+\t\t\t\t\t\tconst attrs = atom.attrs ?? [];\n+\t\t\t\t\t\tif (cursor.index === attrs.length) {\n+\t\t\t\t\t\t\tnext();\n+\t\t\t\t\t\t\tbreak;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tconst attr = attrs[cursor.index++]!;\n+\t\t\t\t\t\tconst key = JSON.stringify([attr.file, attr.name]);\n+\t\t\t\t\t\tif (!p.storage.read(`${collection}:attributes`, key)) {\n+\t\t\t\t\t\t\tp.updateAttributes(state, { ...atom, attrs: [attr] }, !input.remove);\n+\t\t\t\t\t\t\tp.storage.write(`${collection}:attributes`, key, true);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tcase \"contributions\": {\n+\t\t\t\t\t\tif (cursor.index === contributionFiles.length) {\n+\t\t\t\t\t\t\tnext();\n+\t\t\t\t\t\t\tbreak;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tconst path = contributionFiles[cursor.index++]!;\n+\t\t\t\t\t\tp.ensureFile(state, path);\n+\t\t\t\t\t\tconst key = p.fileKey(path)!;\n+\t\t\t\t\t\tconst marker = p.markers.get(state.locator, key);\n+\t\t\t\t\t\tconst delta = input.remove ? -1 : 1;\n+\t\t\t\t\t\tif (marker?.kind !== \"file\" || marker.contributions + delta < 0)\n+\t\t\t\t\t\t\tthrow Error(\"invalid file contribution count\");\n+\t\t\t\t\t\tstate.locator = p.markers.set(state.locator, key, {\n+\t\t\t\t\t\t\t...marker,\n+\t\t\t\t\t\t\tcontributions: marker.contributions + delta,\n+\t\t\t\t\t\t});\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tcase \"membership\":\n+\t\t\t\t\t\tstate.membership = p.members.set(state.membership, atom.seq, { present: !input.remove, dependents: 0 });\n+\t\t\t\t\t\tnext();\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\tcase \"moves\":\n+\t\t\t\t\t\tif (atom.moves?.length) {\n+\t\t\t\t\t\t\tconst result = adoptMovesStep(p, state, this.task, identity);\n+\t\t\t\t\t\t\tObject.assign(state, result.state);\n+\t\t\t\t\t\t\tif (!result.done) break;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tnext();\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\tcase \"cleanup\": {\n+\t\t\t\t\t\tconst attrs = atom.attrs ?? [];\n+\t\t\t\t\t\tif (cursor.index === attrs.length) {\n+\t\t\t\t\t\t\tnext();\n+\t\t\t\t\t\t\tbreak;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tconst attr = attrs[cursor.index++]!;\n+\t\t\t\t\t\tp.storage.remove(`${collection}:attributes`, JSON.stringify([attr.file, attr.name]));\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tvalidate();\n+\t\t\tp.storage.write(collection, \"cursor\", { format: 1, checksum: digest(cursor), cursor });\n+\t\t\treturn { done: cursor.phase === \"done\", state: structuredClone(state), steps, atomicMoveWork };\n+\t\t});\n+\t}\n+}"},{"path":"src/engine/experimental/projection-marker.ts","added":41,"removed":41,"diff":"--- a/src/engine/experimental/projection-marker.ts\n+++ b/src/engine/experimental/projection-marker.ts\n@@ -119,50 +119,10 @@\n \t\treturn this.storage.transaction(() => {\n \t\t\tconst state = { ...previous };\n \t\t\tconst sequence = this.sequence;\n-\t\t\tconst insert = (rank: number, text: string, hidden = false): number => {\n-\t\t\t\tconst id = state.sequence.next;\n-\t\t\t\tstate.sequence = sequence.update(state.sequence, { kind: \"insert\", rank, text });\n-\t\t\t\tif (hidden) state.sequence = sequence.update(state.sequence, { kind: \"visibility\", id, delta: 1 });\n-\t\t\t\treturn id;\n-\t\t\t};\n \t\t\tthis.ensureFile(state, this.path);\n \t\t\tfor (const run of atom.inserts) this.ensureFile(state, run.file);\n \t\t\tlet k = 0;\n-\t\t\tfor (const run of atom.inserts)\n-\t\t\t\tfor (const text of run.lines) {\n-\t\t\t\t\tconst line = `${atom.id}.${k++}`,\n-\t\t\t\t\t\tn = this.graph.lineN(line),\n-\t\t\t\t\t\tparent = this.graph.parentCodeOf(n);\n-\t\t\t\t\tif (n + 1 >= 0x80000000) throw Error(\"prototype line identity limit\");\n-\t\t\t\t\tconst existing = this.markers.get(state.locator, n + 1);\n-\t\t\t\t\tif (existing) {\n-\t\t\t\t\t\tstate.sequence = sequence.update(state.sequence, { kind: \"visibility\", id: existing.enter, delta: -1 });\n-\t\t\t\t\t\tcontinue;\n-\t\t\t\t\t}\n-\t\t\t\t\tconst parentMarker = this.markers.get(state.locator, this.parentKey(parent));\n-\t\t\t\t\tif (!parentMarker) throw Error(\"missing parent marker\");\n-\t\t\t\t\tconst parentKey = this.parentKey(parent);\n-\t\t\t\t\tconst index = this.priorities;\n-\t\t\t\t\tconst root = this.childRoots.get(state.children, parentKey)?.root ?? null;\n-\t\t\t\t\tconst seq = this.graph.writerSeqOf(n);\n-\t\t\t\t\tconst key = orderedChildKey({\n-\t\t\t\t\t\tn,\n-\t\t\t\t\t\treplaces: this.graph.replacesN(n) ? 1 : 0,\n-\t\t\t\t\t\tlamport: this.graph.lamportOfSeq(seq),\n-\t\t\t\t\t\tseq,\n-\t\t\t\t\t\tk: this.graph.kOf(n),\n-\t\t\t\t\t});\n-\t\t\t\t\tconst preceding = index.before(root, key);\n-\t\t\t\t\tconst anchor =\n-\t\t\t\t\t\tpreceding === undefined\n-\t\t\t\t\t\t\t? parentMarker.enter\n-\t\t\t\t\t\t\t: required(this.markers.get(state.locator, preceding + 1)).exit;\n-\t\t\t\t\tstate.children = this.childRoots.set(state.children, parentKey, { root: index.insert(root, key, n) });\n-\t\t\t\t\tconst at = sequence.rank(state.sequence, anchor) + 1;\n-\t\t\t\t\tconst enter = insert(at, line),\n-\t\t\t\t\t\texit = insert(at + 1, `${line}:end`, true);\n-\t\t\t\t\tstate.locator = this.markers.set(state.locator, n + 1, { kind: \"line\", enter, exit, parentKey, key });\n-\t\t\t\t}\n+\t\t\tfor (const run of atom.inserts) for (const _ of run.lines) this.insertLine(state, `${atom.id}.${k++}`);\n \t\t\tfor (const line of atom.deletes) {\n \t\t\t\tconst marker = this.markers.get(state.locator, this.graph.lineN(line) + 1);\n \t\t\t\tif (!marker) throw Error(\"missing deleted marker\");\n@@ -179,6 +139,46 @@\n \t\t\treturn atom.moves?.length ? this.reconcileMoves(state) : state;\n \t\t});\n \t}\n+\t/** One canonical line insertion; used by atomic apply and resumable inactive adoption. */\n+\tinsertLine(state: MarkerState, line: string): void {\n+\t\tthis.assertContext(state);\n+\t\tconst sequence = this.sequence;\n+\t\tconst insert = (rank: number, text: string, hidden = false): number => {\n+\t\t\tconst id = state.sequence.next;\n+\t\t\tstate.sequence = sequence.update(state.sequence, { kind: \"insert\", rank, text });\n+\t\t\tif (hidden) state.sequence = sequence.update(state.sequence, { kind: \"visibility\", id, delta: 1 });\n+\t\t\treturn id;\n+\t\t};\n+\t\tconst n = this.graph.lineN(line),\n+\t\t\tparent = this.graph.parentCodeOf(n);\n+\t\tif (n + 1 >= 0x80000000) throw Error(\"prototype line identity limit\");\n+\t\tconst existing = this.markers.get(state.locator, n + 1);\n+\t\tif (existing) {\n+\t\t\tstate.sequence = sequence.update(state.sequence, { kind: \"visibility\", id: existing.enter, delta: -1 });\n+\t\t\treturn;\n+\t\t}\n+\t\tconst parentMarker = this.markers.get(state.locator, this.parentKey(parent));\n+\t\tif (!parentMarker) throw Error(\"missing parent marker\");\n+\t\tconst parentKey = this.parentKey(parent);\n+\t\tconst index = this.priorities;\n+\t\tconst root = this.childRoots.get(state.children, parentKey)?.root ?? null;\n+\t\tconst seq = this.graph.writerSeqOf(n);\n+\t\tconst key = orderedChildKey({\n+\t\t\tn,\n+\t\t\treplaces: this.graph.replacesN(n) ? 1 : 0,\n+\t\t\tlamport: this.graph.lamportOfSeq(seq),\n+\t\t\tseq,\n+\t\t\tk: this.graph.kOf(n),\n+\t\t});\n+\t\tconst preceding = index.before(root, key);\n+\t\tconst anchor =\n+\t\t\tpreceding === undefined ? parentMarker.enter : required(this.markers.get(state.locator, preceding + 1)).exit;\n+\t\tstate.children = this.childRoots.set(state.children, parentKey, { root: index.insert(root, key, n) });\n+\t\tconst at = sequence.rank(state.sequence, anchor) + 1;\n+\t\tconst enter = insert(at, line),\n+\t\t\texit = insert(at + 1, `${line}:end`, true);\n+\t\tstate.locator = this.markers.set(state.locator, n + 1, { kind: \"line\", enter, exit, parentKey, key });\n+\t}\n \tremoveDeleter(previous: MarkerState, atom: Atom): MarkerState {\n \t\treturn this.removeAtom(previous, atom);\n \t}"},{"path":"src/engine/experimental/projection-move-adoption.ts","added":186,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-move-adoption.ts\n@@ -0,0 +1,186 @@\n+import { createHash } from \"node:crypto\";\n+import type { RelocationInfo } from \"../graph.ts\";\n+import { orderedChildKey } from \"../ordered-index.ts\";\n+import type { GraphStateStorage } from \"../state-source.ts\";\n+import type { ExperimentalMarkerProjection, MarkerState } from \"./projection-marker.ts\";\n+import { resolveMovesPage } from \"./projection-move-resolution.ts\";\n+\n+type Phase = \"files\" | \"resolve\" | \"plans\" | \"park\" | \"place\" | \"cleanup\" | \"done\";\n+interface Cursor {\n+\tidentity: string;\n+\tphase: Phase;\n+\tmover: number;\n+\tmove: number;\n+\tcount: number;\n+\titem: number;\n+\tcollection: number;\n+}\n+interface Plan {\n+\tn: number;\n+\tparentKey: number;\n+\tkey: string;\n+}\n+const collections = [\"selected\", \"seen\", \"work\", \"ignored\", \"reached\", \"progress\", \"planned\", \"plans\"];\n+const digest = (value: unknown) => createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n+\n+function shape(value: unknown, fields: string): asserts value is Record<string, unknown> {\n+\tconst keys = fields.split(\" \");\n+\tif (\n+\t\t!value ||\n+\t\ttypeof value !== \"object\" ||\n+\t\tArray.isArray(value) ||\n+\t\tObject.keys(value).length !== keys.length ||\n+\t\tkeys.some((key) => !Object.hasOwn(value, key))\n+\t)\n+\t\tthrow Error(\"invalid move adoption record\");\n+}\n+\n+/** The caller must persist the returned private root in the same transaction. */\n+export function adoptMovesStep(\n+\tp: ExperimentalMarkerProjection,\n+\tprevious: MarkerState,\n+\ttask: string,\n+\tidentity: string,\n+): { done: boolean; state: MarkerState } {\n+\tp.assertContext(previous);\n+\tif (!task || task.length > 128 || !/^[a-f0-9]{64}$/.test(identity)) throw Error(\"invalid move adoption identity\");\n+\tconst name = `move-adoption:${task}`;\n+\tconst scratch: GraphStateStorage = {\n+\t\tread: (c, k) => p.storage.read(`${name}:${c}`, k),\n+\t\twrite: (c, k, v) => p.storage.write(`${name}:${c}`, k, v),\n+\t\tremove: (c, k) => p.storage.remove(`${name}:${c}`, k),\n+\t\tentries: (c) => p.storage.entries(`${name}:${c}`),\n+\t\ttransaction: (body) => p.storage.transaction(body),\n+\t};\n+\treturn p.storage.transaction(() => {\n+\t\tconst saved = p.storage.read(name, \"cursor\");\n+\t\tlet restored: Cursor | undefined;\n+\t\tif (saved !== undefined) {\n+\t\t\tshape(saved, \"format checksum cursor\");\n+\t\t\tif (saved.format !== 1 || saved.checksum !== digest(saved.cursor)) throw Error(\"damaged move adoption cursor\");\n+\t\t\tshape(saved.cursor, \"identity phase mover move count item collection\");\n+\t\t\trestored = saved.cursor as unknown as Cursor;\n+\t\t}\n+\t\tconst cursor: Cursor = restored ?? {\n+\t\t\tidentity,\n+\t\t\tphase: \"files\",\n+\t\t\tmover: 0,\n+\t\t\tmove: 0,\n+\t\t\tcount: 0,\n+\t\t\titem: 0,\n+\t\t\tcollection: 0,\n+\t\t};\n+\t\tif (\n+\t\t\tcursor.identity !== identity ||\n+\t\t\t![\"files\", \"resolve\", \"plans\", \"park\", \"place\", \"cleanup\", \"done\"].includes(cursor.phase) ||\n+\t\t\t![cursor.mover, cursor.move, cursor.count, cursor.item, cursor.collection].every(\n+\t\t\t\t(n) => Number.isSafeInteger(n) && n >= 0,\n+\t\t\t) ||\n+\t\t\tcursor.mover > p.graph.movers().length ||\n+\t\t\tcursor.item > cursor.count ||\n+\t\t\tcursor.count > p.graph.lineCount ||\n+\t\t\tcursor.collection > collections.length\n+\t\t)\n+\t\t\tthrow Error(\"invalid move adoption cursor\");\n+\t\tconst mover = p.graph.movers()[cursor.mover];\n+\t\tif (cursor.move > (mover === undefined ? 0 : (p.graph.atom(mover).moves?.length ?? 0)))\n+\t\t\tthrow Error(\"invalid move adoption offset\");\n+\t\tlet state = { ...previous };\n+\t\tconst has = (id: string) => p.members.get(state.membership, p.graph.atom(id).seq)?.present ?? false;\n+\t\tswitch (cursor.phase) {\n+\t\t\tcase \"files\":\n+\t\t\tcase \"plans\": {\n+\t\t\t\tif (cursor.mover === p.graph.movers().length) {\n+\t\t\t\t\tcursor.phase = cursor.phase === \"files\" ? \"resolve\" : \"park\";\n+\t\t\t\t\tcursor.mover = 0;\n+\t\t\t\t\tcursor.move = 0;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tconst moves = p.graph.atom(p.graph.movers()[cursor.mover]!).moves ?? [];\n+\t\t\t\tif (cursor.move > moves.length) throw Error(\"invalid move adoption offset\");\n+\t\t\t\tif (cursor.move === moves.length) {\n+\t\t\t\t\tcursor.mover++;\n+\t\t\t\t\tcursor.move = 0;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tconst move = moves[cursor.move++]!;\n+\t\t\t\tif (cursor.phase === \"files\") {\n+\t\t\t\t\tif (move.parent.startsWith(\"^\")) p.ensureFile(state, move.parent.slice(1));\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tif (scratch.read(\"planned\", move.line)) break;\n+\t\t\t\tscratch.write(\"planned\", move.line, true);\n+\t\t\t\tconst n = p.graph.lineN(move.line);\n+\t\t\t\tif (!has(p.graph.idOfSeq(p.graph.writerSeqOf(n)))) break;\n+\t\t\t\tconst marker = p.markers.get(state.locator, n + 1);\n+\t\t\t\tif (marker?.kind !== \"line\") throw Error(\"missing selected relocation marker\");\n+\t\t\t\tconst selected = scratch.read(\"selected\", move.line) as RelocationInfo | undefined;\n+\t\t\t\tconst parent = selected?.parent ?? p.graph.lineParent(move.line);\n+\t\t\t\tif (parent === undefined) throw Error(\"missing relocation ancestry\");\n+\t\t\t\tconst parentKey = parent.startsWith(\"^\") ? p.fileKey(parent.slice(1)) : p.graph.lineN(parent) + 1;\n+\t\t\t\tif (parentKey === undefined) throw Error(\"missing relocation file\");\n+\t\t\t\tconst seq = selected ? p.graph.atom(selected.atom).seq : p.graph.writerSeqOf(n);\n+\t\t\t\tconst key = orderedChildKey({\n+\t\t\t\t\tn,\n+\t\t\t\t\treplaces: selected ? 0 : Number(p.graph.replacesN(n)),\n+\t\t\t\t\tlamport: p.graph.lamportOfSeq(seq),\n+\t\t\t\t\tseq,\n+\t\t\t\t\tk: selected ? selected.k : p.graph.kOf(n),\n+\t\t\t\t});\n+\t\t\t\tif (parentKey !== marker.parentKey || key !== marker.key)\n+\t\t\t\t\tscratch.write(\"plans\", String(cursor.count++), { n, parentKey, key });\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tcase \"resolve\":\n+\t\t\t\tif (resolveMovesPage(p.graph, has, scratch, identity, 1).done) cursor.phase = \"plans\";\n+\t\t\t\tbreak;\n+\t\t\tcase \"park\":\n+\t\t\tcase \"place\": {\n+\t\t\t\tif (cursor.item === cursor.count) {\n+\t\t\t\t\tcursor.phase = cursor.phase === \"park\" ? \"place\" : \"cleanup\";\n+\t\t\t\t\tcursor.item = 0;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tconst plan = scratch.read(\"plans\", String(cursor.item++)) as Plan | undefined;\n+\t\t\t\tif (\n+\t\t\t\t\t!plan ||\n+\t\t\t\t\t!Number.isSafeInteger(plan.n) ||\n+\t\t\t\t\tplan.n < 0 ||\n+\t\t\t\t\t!Number.isSafeInteger(plan.parentKey) ||\n+\t\t\t\t\tplan.parentKey < 0 ||\n+\t\t\t\t\t!/^[0-9a-f]{57}$/.test(plan.key)\n+\t\t\t\t)\n+\t\t\t\t\tthrow Error(\"invalid saved relocation plan\");\n+\t\t\t\tconst marker = p.markers.get(state.locator, plan.n + 1);\n+\t\t\t\tif (marker?.kind !== \"line\") throw Error(\"missing relocation marker\");\n+\t\t\t\tstate = p.relocate(\n+\t\t\t\t\tstate,\n+\t\t\t\t\tplan.n,\n+\t\t\t\t\tcursor.phase === \"park\" ? 0 : plan.parentKey,\n+\t\t\t\t\tcursor.phase === \"park\" ? marker.key : plan.key,\n+\t\t\t\t);\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tcase \"cleanup\": {\n+\t\t\t\tif (cursor.collection === collections.length) {\n+\t\t\t\t\tcursor.phase = \"done\";\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tconst collection = collections[cursor.collection]!;\n+\t\t\t\tconst iterator = scratch.entries(collection)[Symbol.iterator]();\n+\t\t\t\tlet row: IteratorResult<readonly [string, unknown]>;\n+\t\t\t\ttry {\n+\t\t\t\t\trow = iterator.next();\n+\t\t\t\t} finally {\n+\t\t\t\t\titerator.return?.();\n+\t\t\t\t}\n+\t\t\t\tif (row.done) cursor.collection++;\n+\t\t\t\telse scratch.remove(collection, row.value[0]);\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n+\t\tif (cursor.phase === \"done\") p.storage.remove(name, \"cursor\");\n+\t\telse p.storage.write(name, \"cursor\", { format: 1, checksum: digest(cursor), cursor });\n+\t\treturn { done: cursor.phase === \"done\", state };\n+\t});\n+}"},{"path":"src/engine/experimental/projection-move-resolution.ts","added":234,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-move-resolution.ts\n@@ -0,0 +1,234 @@\n+import { createHash } from \"node:crypto\";\n+import type { Graph, RelocationInfo } from \"../graph.ts\";\n+import { isStartNode } from \"../keys.ts\";\n+import type { GraphStateStorage } from \"../state-source.ts\";\n+import type { NodeId } from \"../types.ts\";\n+\n+interface Progress {\n+\tidentity: string;\n+\tphase: \"scan\" | \"walk\" | \"entry\" | \"weakest\" | \"repick\" | \"mark\" | \"done\";\n+\tmover: number;\n+\tmove: number;\n+\twork: number;\n+\titem: number;\n+\tline: NodeId | null;\n+\tslow: NodeId | null;\n+\tfast: NodeId | null;\n+\tmeeting: NodeId | null;\n+\tentry: NodeId | null;\n+\tcurrent: NodeId | null;\n+\tweakest: RelocationInfo | null;\n+\tbest: RelocationInfo | null;\n+}\n+const digest = (value: unknown) => createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n+const integer = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;\n+function shape(value: unknown, fields: string): asserts value is Record<string, unknown> {\n+\tconst keys = fields.split(\" \");\n+\tif (\n+\t\t!value ||\n+\t\ttypeof value !== \"object\" ||\n+\t\tArray.isArray(value) ||\n+\t\tObject.keys(value).length !== keys.length ||\n+\t\tkeys.some((key) => !Object.hasOwn(value, key))\n+\t)\n+\t\tthrow Error(\"invalid move resolution record\");\n+}\n+function readProgress(value: unknown, graph: Graph): Progress | undefined {\n+\tif (value === undefined) return undefined;\n+\tshape(value, \"format checksum state\");\n+\tif (value.format !== 1 || value.checksum !== digest(value.state)) throw Error(\"damaged move resolution cursor\");\n+\tshape(value.state, \"identity phase mover move work item line slow fast meeting entry current weakest best\");\n+\tconst state = value.state;\n+\tif (\n+\t\ttypeof state.identity !== \"string\" ||\n+\t\t!state.identity ||\n+\t\tstate.identity.length > 4096 ||\n+\t\t![\"scan\", \"walk\", \"entry\", \"weakest\", \"repick\", \"mark\", \"done\"].includes(String(state.phase)) ||\n+\t\t![state.mover, state.move, state.work, state.item].every(integer) ||\n+\t\tNumber(state.mover) > graph.movers().length ||\n+\t\tNumber(state.item) > Number(state.work) ||\n+\t\tNumber(state.work) > graph.lineCount\n+\t)\n+\t\tthrow Error(\"invalid move resolution position\");\n+\tconst mover = graph.movers()[Number(state.mover)];\n+\tif (Number(state.move) > (mover === undefined ? 0 : (graph.atom(mover).moves?.length ?? 0)))\n+\t\tthrow Error(\"invalid move offset\");\n+\tfor (const key of [\"line\", \"slow\", \"fast\", \"meeting\", \"entry\", \"current\"])\n+\t\tif (state[key] !== null && (typeof state[key] !== \"string\" || !state[key] || String(state[key]).length > 4096))\n+\t\t\tthrow Error(\"invalid move ancestry cursor\");\n+\tfor (const key of [\"weakest\", \"best\"]) {\n+\t\tconst move = state[key];\n+\t\tif (move === null) continue;\n+\t\tshape(move, \"atom line parent k\");\n+\t\tif (typeof move.atom !== \"string\" || !integer(move.k)) throw Error(\"invalid saved move\");\n+\t\tconst canonical = graph.atom(move.atom).moves?.[move.k];\n+\t\tif (!canonical || canonical.line !== move.line || canonical.parent !== move.parent)\n+\t\t\tthrow Error(\"saved move identity mismatch\");\n+\t}\n+\tif (\n+\t\t(state.phase === \"repick\" && state.weakest === null) ||\n+\t\t([\"entry\", \"weakest\", \"repick\", \"mark\"].includes(String(state.phase)) && state.line === null) ||\n+\t\t(state.phase === \"entry\" && (state.entry === null || state.meeting === null)) ||\n+\t\t(state.phase === \"weakest\" && (state.entry === null || state.current === null))\n+\t)\n+\t\tthrow Error(\"incomplete move resolution cursor\");\n+\treturn state as unknown as Progress;\n+}\n+\n+/** Private paged equivalent of resolveScratchMoves. Caller isolates storage and\n+ * binds identity to immutable graph, membership and source before every page. */\n+export function resolveMovesPage(\n+\tgraph: Graph,\n+\thas: (id: string) => boolean,\n+\tstorage: GraphStateStorage,\n+\tidentity: string,\n+\tmaxSteps: number,\n+): { done: boolean; steps: number } {\n+\tif (!identity || identity.length > 4096 || !Number.isSafeInteger(maxSteps) || maxSteps < 1 || maxSteps > 256)\n+\t\tthrow Error(\"invalid move resolution page\");\n+\treturn storage.transaction(() => {\n+\t\tlet state = readProgress(storage.read(\"progress\", \"cursor\"), graph);\n+\t\tif (state && state.identity !== identity) throw Error(\"move resolution identity changed\");\n+\t\tstate ??= {\n+\t\t\tidentity,\n+\t\t\tphase: \"scan\",\n+\t\t\tmover: 0,\n+\t\t\tmove: 0,\n+\t\t\twork: 0,\n+\t\t\titem: 0,\n+\t\t\tline: null,\n+\t\t\tslow: null,\n+\t\t\tfast: null,\n+\t\t\tmeeting: null,\n+\t\t\tentry: null,\n+\t\t\tcurrent: null,\n+\t\t\tweakest: null,\n+\t\t\tbest: null,\n+\t\t};\n+\t\tconst selected = (line: string) => storage.read(\"selected\", line) as RelocationInfo | undefined;\n+\t\tconst parent = (line: string): NodeId => {\n+\t\t\tconst value = selected(line)?.parent ?? graph.lineParent(line);\n+\t\t\tif (value === undefined) throw Error(\"missing relocation ancestry\");\n+\t\t\treturn value;\n+\t\t};\n+\t\tconst terminal = (node: NodeId | null) => node === null || isStartNode(node) || !!storage.read(\"reached\", node);\n+\t\tconst step = (node: NodeId | null): NodeId | null => (terminal(node) ? null : parent(node!));\n+\t\tconst stronger = (a: RelocationInfo, b: RelocationInfo) => graph.comparePriority(a.atom, b.atom) > 0;\n+\t\tconst moveKey = (move: RelocationInfo) => JSON.stringify([move.atom, move.k]);\n+\t\tconst restartWalk = () => {\n+\t\t\tstate!.phase = \"walk\";\n+\t\t\tstate!.slow = state!.line;\n+\t\t\tstate!.fast = state!.line;\n+\t\t};\n+\t\tlet steps = 0;\n+\t\twhile (state.phase !== \"done\" && steps < maxSteps) {\n+\t\t\tsteps++;\n+\t\t\tswitch (state.phase) {\n+\t\t\t\tcase \"scan\":\n+\t\t\t\tcase \"repick\": {\n+\t\t\t\t\tif (state.mover === graph.movers().length) {\n+\t\t\t\t\t\tif (state.phase === \"scan\") {\n+\t\t\t\t\t\t\tstate.phase = \"walk\";\n+\t\t\t\t\t\t\tstate.line = null;\n+\t\t\t\t\t\t} else {\n+\t\t\t\t\t\t\tconst line = state.weakest!.line;\n+\t\t\t\t\t\t\tif (state.best) storage.write(\"selected\", line, state.best);\n+\t\t\t\t\t\t\telse storage.remove(\"selected\", line);\n+\t\t\t\t\t\t\trestartWalk();\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tconst id = graph.movers()[state.mover]!;\n+\t\t\t\t\tif (!has(id)) {\n+\t\t\t\t\t\tstate.mover++;\n+\t\t\t\t\t\tstate.move = 0;\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tconst moves = graph.atom(id).moves ?? [];\n+\t\t\t\t\tif (state.move === moves.length) {\n+\t\t\t\t\t\tstate.mover++;\n+\t\t\t\t\t\tstate.move = 0;\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tconst k = state.move++;\n+\t\t\t\t\tconst candidate: RelocationInfo = { atom: id, ...moves[k]!, k };\n+\t\t\t\t\tif (state.phase === \"scan\") {\n+\t\t\t\t\t\tif (!storage.read(\"seen\", candidate.line)) {\n+\t\t\t\t\t\t\tstorage.write(\"seen\", candidate.line, true);\n+\t\t\t\t\t\t\tstorage.write(\"work\", String(state.work++), candidate.line);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tconst best = selected(candidate.line);\n+\t\t\t\t\t\tif (!best || stronger(candidate, best)) storage.write(\"selected\", candidate.line, candidate);\n+\t\t\t\t\t} else if (\n+\t\t\t\t\t\tcandidate.line === state.weakest!.line &&\n+\t\t\t\t\t\t!storage.read(\"ignored\", moveKey(candidate)) &&\n+\t\t\t\t\t\t(!state.best || stronger(candidate, state.best))\n+\t\t\t\t\t)\n+\t\t\t\t\t\tstate.best = candidate;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tcase \"walk\": {\n+\t\t\t\t\tif (state.line === null) {\n+\t\t\t\t\t\tif (state.item === state.work) {\n+\t\t\t\t\t\t\tstate.phase = \"done\";\n+\t\t\t\t\t\t\tbreak;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tstate.line = storage.read(\"work\", String(state.item)) as string;\n+\t\t\t\t\t\trestartWalk();\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tstate.slow = step(state.slow);\n+\t\t\t\t\tstate.fast = step(step(state.fast));\n+\t\t\t\t\tif (terminal(state.slow) || terminal(state.fast)) {\n+\t\t\t\t\t\tstate.phase = \"mark\";\n+\t\t\t\t\t\tstate.current = state.line;\n+\t\t\t\t\t} else if (state.slow === state.fast) {\n+\t\t\t\t\t\tstate.phase = \"entry\";\n+\t\t\t\t\t\tstate.meeting = state.slow;\n+\t\t\t\t\t\tstate.entry = state.line;\n+\t\t\t\t\t}\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tcase \"entry\": {\n+\t\t\t\t\tif (state.entry === state.meeting) {\n+\t\t\t\t\t\tstate.phase = \"weakest\";\n+\t\t\t\t\t\tstate.current = state.entry;\n+\t\t\t\t\t\tstate.weakest = null;\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tstate.entry = step(state.entry);\n+\t\t\t\t\tstate.meeting = step(state.meeting);\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tcase \"weakest\": {\n+\t\t\t\t\tconst move = selected(state.current!);\n+\t\t\t\t\tif (move && (!state.weakest || stronger(state.weakest, move))) state.weakest = move;\n+\t\t\t\t\tstate.current = parent(state.current!);\n+\t\t\t\t\tif (state.current === state.entry) {\n+\t\t\t\t\t\tif (!state.weakest) throw Error(\"canonical ancestry unexpectedly cycles\");\n+\t\t\t\t\t\tstorage.write(\"ignored\", moveKey(state.weakest), true);\n+\t\t\t\t\t\tstate.phase = \"repick\";\n+\t\t\t\t\t\tstate.mover = 0;\n+\t\t\t\t\t\tstate.move = 0;\n+\t\t\t\t\t\tstate.best = null;\n+\t\t\t\t\t}\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tcase \"mark\": {\n+\t\t\t\t\tif (terminal(state.current)) {\n+\t\t\t\t\t\tstate.item++;\n+\t\t\t\t\t\tstate.line = null;\n+\t\t\t\t\t\tstate.phase = \"walk\";\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t\tconst next = parent(state.current!);\n+\t\t\t\t\tstorage.write(\"reached\", state.current!, true);\n+\t\t\t\t\tstate.current = next;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t}\n+\t\t}\n+\t\tstorage.write(\"progress\", \"cursor\", { format: 1, checksum: digest(state), state });\n+\t\treturn { done: state.phase === \"done\", steps };\n+\t});\n+}"},{"path":"src/engine/test/projection-atom-adoption.test.ts","added":327,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-atom-adoption.test.ts\n@@ -0,0 +1,327 @@\n+import assert from \"node:assert/strict\";\n+import { createHash } from \"node:crypto\";\n+import { mkdtempSync, rmdirSync, unlinkSync } from \"node:fs\";\n+import { tmpdir } from \"node:os\";\n+import { join } from \"node:path\";\n+import { test } from \"node:test\";\n+import { ProjectionAtomAdoption } from \"../experimental/projection-atom-adoption.ts\";\n+import { ExperimentalMarkerProjection } from \"../experimental/projection-marker.ts\";\n+import { adoptMovesStep } from \"../experimental/projection-move-adoption.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { CachedStateStorage } from \"../state-source.ts\";\n+import { Repo } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"an unfinished atom resumes after closing and reopening its SQLite database\", () => {\n+\tconst directory = mkdtempSync(join(tmpdir(), \"abso-atom-adoption-\"));\n+\tconst filename = join(directory, \"state.sqlite\");\n+\tlet db = new SqlState(filename);\n+\ttry {\n+\t\tconst repo = Repo.init({ \"a.txt\": \"one\\ntwo\\nthree\\nfour\\n\" });\n+\t\tconst atom = repo.graph.atom(\"a0\");\n+\t\tnew Graph({ storage: db }).add(atom);\n+\t\tconst previous = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), \"a.txt\", \"restart\").empty();\n+\t\tlet done = false,\n+\t\t\tpages = 0;\n+\t\twhile (!done) {\n+\t\t\tconst adapter = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), \"a.txt\", \"restart\");\n+\t\t\tconst result = new ProjectionAtomAdoption(adapter, \"initial\").page({\n+\t\t\t\tprevious,\n+\t\t\t\tatom,\n+\t\t\t\tremove: false,\n+\t\t\t\tsource: \"d\".repeat(64),\n+\t\t\t\tmaxSteps: 2,\n+\t\t\t\tvalidateSource: () => {},\n+\t\t\t});\n+\t\t\tassert.ok(result.steps <= 2);\n+\t\t\tdone = result.done;\n+\t\t\tif (done)\n+\t\t\t\tassert.deepEqual(\n+\t\t\t\t\tadapter.lines(result.state),\n+\t\t\t\t\trepo\n+\t\t\t\t\t\t.view()\n+\t\t\t\t\t\t.lines(\"a.txt\")\n+\t\t\t\t\t\t.map((line) => line.id),\n+\t\t\t\t);\n+\t\t\tassert.ok(++pages < 50);\n+\t\t\tdb.db.close();\n+\t\t\tdb = new SqlState(filename);\n+\t\t}\n+\t\tassert.ok(pages > 5);\n+\t} finally {\n+\t\tdb.db.close();\n+\t\tunlinkSync(filename);\n+\t\trmdirSync(directory);\n+\t}\n+});\n+\n+test(\"atom adoption resumes small pages and matches atomic additions and reverse removals\", () => {\n+\tconst db = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({\n+\t\t\t\"a.txt\": Array.from({ length: 40 }, (_, i) => `line ${i}\\n`).join(\"\"),\n+\t\t\t\"b.txt\": \"other\\n\",\n+\t\t});\n+\t\tconst graph = new Graph({ storage: new CachedStateStorage(db) });\n+\t\tconst atoms = [repo.graph.atom(\"a0\")];\n+\t\tatoms.push(\n+\t\t\trepo.edit({\n+\t\t\t\tedits: [{ file: \"a.txt\", old: repo.view().text(\"a.txt\"), new: \"replacement\\n\" }],\n+\t\t\t\tattrs: [{ file: \"b.txt\", name: \"exec\", value: \"1\" }],\n+\t\t\t}),\n+\t\t);\n+\t\tatoms.push(repo.edit({ move: { file: \"a.txt\", start: 0, end: 1, to: \"b.txt\", at: 0 } }));\n+\t\tfor (const atom of atoms) graph.add(atom);\n+\t\tconst adapter = () => new ExperimentalMarkerProjection(db, graph, \"a.txt\", \"paged\");\n+\t\tconst oracle = new ExperimentalMarkerProjection(db, graph, \"a.txt\", \"atomic\");\n+\t\tlet state = adapter().empty(),\n+\t\t\texpected = oracle.empty(),\n+\t\t\ttask = 0;\n+\t\tfor (const [atom, remove] of [\n+\t\t\t...atoms.map((a) => [a, false] as const),\n+\t\t\t...atoms.toReversed().map((a) => [a, true] as const),\n+\t\t]) {\n+\t\t\tconst previous = state,\n+\t\t\t\tid = String(task++);\n+\t\t\tlet done = false,\n+\t\t\t\tpages = 0,\n+\t\t\t\tatomicMovePages = 0;\n+\t\t\twhile (!done) {\n+\t\t\t\tconst result = new ProjectionAtomAdoption(adapter(), id).page({\n+\t\t\t\t\tprevious,\n+\t\t\t\t\tatom,\n+\t\t\t\t\tremove,\n+\t\t\t\t\tsource: \"a\".repeat(64),\n+\t\t\t\t\tmaxSteps: 3,\n+\t\t\t\t\tvalidateSource: () => {},\n+\t\t\t\t});\n+\t\t\t\tassert.ok(result.steps <= 3);\n+\t\t\t\tif (result.atomicMoveWork) atomicMovePages++;\n+\t\t\t\tstate = result.state;\n+\t\t\t\tdone = result.done;\n+\t\t\t\tassert.ok(++pages < 200);\n+\t\t\t}\n+\t\t\tassert.ok(pages > 1);\n+\t\t\tassert.equal(atomicMovePages, 0);\n+\t\t\tassert.equal(\n+\t\t\t\tdb.db.prepare(\"SELECT COUNT(*) AS n FROM state WHERE collection LIKE ?\").get(\"%move-adoption:%\")!.n,\n+\t\t\t\t0,\n+\t\t\t);\n+\t\t\texpected = remove ? oracle.removeAtom(expected, atom) : oracle.apply(expected, atom);\n+\t\t\tfor (const path of [\"a.txt\", \"b.txt\"]) {\n+\t\t\t\tassert.deepEqual(adapter().lines(state, path), oracle.lines(expected, path));\n+\t\t\t\tassert.deepEqual(adapter().attrs(state, path), oracle.attrs(expected, path));\n+\t\t\t}\n+\t\t\tassert.deepEqual(adapter().knownPaths(state), oracle.knownPaths(expected));\n+\t\t}\n+\t} finally {\n+\t\tdb.db.close();\n+\t}\n+});\n+\n+test(\"source drift rolls back an atom page and a changed atom cannot resume its cursor\", () => {\n+\tconst db = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"a.txt\": \"one\\ntwo\\nthree\\n\" });\n+\t\tconst graph = new Graph({ storage: db });\n+\t\tconst atom = repo.graph.atom(\"a0\");\n+\t\tgraph.add(atom);\n+\t\tconst adapter = new ExperimentalMarkerProjection(db, graph, \"a.txt\", \"failure\");\n+\t\tconst job = new ProjectionAtomAdoption(adapter, \"one\");\n+\t\tconst input = {\n+\t\t\tprevious: adapter.empty(),\n+\t\t\tatom,\n+\t\t\tremove: false,\n+\t\t\tsource: \"b\".repeat(64),\n+\t\t\tmaxSteps: 3,\n+\t\t\tvalidateSource: () => {},\n+\t\t};\n+\t\tjob.page(input);\n+\t\tconst rows = () => db.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\t\tconst before = rows();\n+\t\tconst saved = adapter.storage.read(\"atom-adoption:one\", \"cursor\") as {\n+\t\t\tformat: number;\n+\t\t\tchecksum: string;\n+\t\t\tcursor: { index: number; run: number; phase: string; state: { sequence: { next: number } } };\n+\t\t};\n+\t\tfor (const field of [\"checksum\", \"index\", \"run\", \"sequence\", \"phase\"]) {\n+\t\t\tconst damaged = structuredClone(saved);\n+\t\t\tif (field === \"checksum\") damaged.checksum = \"bad\";\n+\t\t\telse {\n+\t\t\t\tif (field === \"index\") damaged.cursor.index = Number.MAX_SAFE_INTEGER;\n+\t\t\t\tif (field === \"run\") damaged.cursor.run = atom.inserts.length + 1;\n+\t\t\t\tif (field === \"sequence\") damaged.cursor.state.sequence.next = -1;\n+\t\t\t\tif (field === \"phase\") damaged.cursor.phase = \"unknown\";\n+\t\t\t\tdamaged.checksum = createHash(\"sha256\").update(JSON.stringify(damaged.cursor)).digest(\"hex\");\n+\t\t\t}\n+\t\t\tadapter.storage.write(\"atom-adoption:one\", \"cursor\", damaged);\n+\t\t\tconst corruptRows = rows();\n+\t\t\tassert.throws(() => job.page(input), /invalid|damaged/, field);\n+\t\t\tassert.deepEqual(rows(), corruptRows, field);\n+\t\t\tadapter.storage.write(\"atom-adoption:one\", \"cursor\", saved);\n+\t\t}\n+\t\tassert.deepEqual(rows(), before);\n+\t\tassert.throws(() => job.page({ ...input, validateSource: () => Promise.resolve() }), /must be synchronous/);\n+\t\tassert.deepEqual(rows(), before);\n+\t\tlet asyncChecks = 0;\n+\t\tassert.throws(\n+\t\t\t() => job.page({ ...input, validateSource: () => (++asyncChecks === 2 ? Promise.resolve() : undefined) }),\n+\t\t\t/must be synchronous/,\n+\t\t);\n+\t\tassert.deepEqual(rows(), before);\n+\t\tlet checks = 0;\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\tjob.page({\n+\t\t\t\t\t...input,\n+\t\t\t\t\tvalidateSource: () => {\n+\t\t\t\t\t\tif (++checks === 2) throw Error(\"source drift\");\n+\t\t\t\t\t},\n+\t\t\t\t}),\n+\t\t\t/source drift/,\n+\t\t);\n+\t\tassert.deepEqual(rows(), before);\n+\t\tassert.throws(\n+\t\t\t() => job.page({ ...input, atom: { ...atom, message: \"changed\" } }),\n+\t\t\t/canonical adoption atom mismatch/,\n+\t\t);\n+\t\tassert.deepEqual(rows(), before);\n+\t\tassert.throws(() => job.page({ ...input, source: \"c\".repeat(64) }), /changed atom adoption cursor/);\n+\t\tassert.deepEqual(rows(), before);\n+\t\tassert.equal(job.page(input).steps, 3);\n+\t} finally {\n+\t\tdb.db.close();\n+\t}\n+});\n+\n+test(\"move adoption rolls back complete pages and resumes every phase after SQLite reopen\", () => {\n+\tconst directory = mkdtempSync(join(tmpdir(), \"abso-move-restart-\"));\n+\tconst filename = join(directory, \"state.sqlite\");\n+\tlet db = new SqlState(filename);\n+\ttry {\n+\t\tconst repo = Repo.init({ \"a.txt\": \"one\\ntwo\\nthree\\n\", \"b.txt\": \"other\\n\" });\n+\t\tconst initial = repo.graph.atom(\"a0\");\n+\t\tconst move = repo.edit({ move: { file: \"a.txt\", start: 0, end: 2, to: \"b.txt\", at: 1 } });\n+\t\tconst graph = new Graph({ storage: db });\n+\t\tgraph.add(initial);\n+\t\tgraph.add(move);\n+\t\tconst first = new ExperimentalMarkerProjection(db, graph, \"a.txt\", \"restart-moves\");\n+\t\tlet state = first.apply(first.empty(), initial);\n+\t\tconst phases = new Set<string>();\n+\t\tfor (const remove of [false, true]) {\n+\t\t\tconst previous = state;\n+\t\t\tlet done = false,\n+\t\t\t\tpages = 0;\n+\t\t\twhile (!done) {\n+\t\t\t\tconst adapter = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), \"a.txt\", \"restart-moves\");\n+\t\t\t\tconst job = new ProjectionAtomAdoption(adapter, remove ? \"remove\" : \"add\");\n+\t\t\t\tconst input = { previous, atom: move, remove, source: \"f\".repeat(64), maxSteps: 1, validateSource: () => {} };\n+\t\t\t\tconst before = db.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\t\t\t\tlet validations = 0;\n+\t\t\t\tassert.throws(\n+\t\t\t\t\t() =>\n+\t\t\t\t\t\tjob.page({\n+\t\t\t\t\t\t\t...input,\n+\t\t\t\t\t\t\tvalidateSource: () => {\n+\t\t\t\t\t\t\t\tif (++validations === 2) throw Error(\"source changed after page\");\n+\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t}),\n+\t\t\t\t\t/source changed after page/,\n+\t\t\t\t);\n+\t\t\t\tassert.deepEqual(db.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+\t\t\t\tconst result = job.page(input);\n+\t\t\t\tstate = result.state;\n+\t\t\t\tdone = result.done;\n+\t\t\t\tassert.equal(result.atomicMoveWork, false);\n+\t\t\t\tassert.ok(result.steps <= 1);\n+\t\t\t\tconst saved = adapter.storage.read(`move-adoption:${remove ? \"remove\" : \"add\"}`, \"cursor\") as\n+\t\t\t\t\t| { cursor: { phase: string } }\n+\t\t\t\t\t| undefined;\n+\t\t\t\tif (saved) phases.add(saved.cursor.phase);\n+\t\t\t\tassert.ok(++pages < 300);\n+\t\t\t\tdb.db.close();\n+\t\t\t\tdb = new SqlState(filename);\n+\t\t\t}\n+\t\t\tconst adapter = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), \"a.txt\", \"restart-moves\");\n+\t\t\tconst oracle = new ExperimentalMarkerProjection(\n+\t\t\t\tdb,\n+\t\t\t\tnew Graph({ storage: db }),\n+\t\t\t\t\"a.txt\",\n+\t\t\t\tremove ? \"oracle-remove\" : \"oracle-add\",\n+\t\t\t);\n+\t\t\tlet expected = oracle.apply(oracle.empty(), initial);\n+\t\t\tif (!remove) expected = oracle.apply(expected, move);\n+\t\t\tfor (const path of [\"a.txt\", \"b.txt\"]) assert.deepEqual(adapter.lines(state, path), oracle.lines(expected, path));\n+\t\t\tassert.equal(\n+\t\t\t\tdb.db.prepare(\"SELECT COUNT(*) AS n FROM state WHERE collection LIKE ?\").get(\"%move-adoption:%\")!.n,\n+\t\t\t\t0,\n+\t\t\t);\n+\t\t}\n+\t\tfor (const phase of [\"files\", \"resolve\", \"plans\", \"park\", \"place\", \"cleanup\"]) assert.ok(phases.has(phase), phase);\n+\t} finally {\n+\t\tdb.db.close();\n+\t\tunlinkSync(filename);\n+\t\trmdirSync(directory);\n+\t}\n+});\n+\n+test(\"move application rejects damaged cursor envelopes and invalid positions without mutation\", () => {\n+\tconst db = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"a.txt\": \"one\\ntwo\\n\" });\n+\t\tconst adapter = new ExperimentalMarkerProjection(db, repo.graph, \"a.txt\", \"corrupt-move\");\n+\t\tconst state = adapter.apply(adapter.empty(), repo.graph.atom(\"a0\"));\n+\t\tconst identity = \"e\".repeat(64);\n+\t\tadoptMovesStep(adapter, state, \"job\", identity);\n+\t\tconst saved = adapter.storage.read(\"move-adoption:job\", \"cursor\") as {\n+\t\t\tformat: number;\n+\t\t\tchecksum: string;\n+\t\t\tcursor: Record<string, unknown>;\n+\t\t};\n+\t\tconst changes: Array<(record: typeof saved) => void> = [\n+\t\t\t(row) => {\n+\t\t\t\trow.checksum = \"bad\";\n+\t\t\t},\n+\t\t\t(row) => {\n+\t\t\t\trow.format = 2;\n+\t\t\t},\n+\t\t\t(row) => {\n+\t\t\t\trow.cursor.phase = \"unknown\";\n+\t\t\t},\n+\t\t\t(row) => {\n+\t\t\t\trow.cursor.identity = \"another\";\n+\t\t\t},\n+\t\t\t(row) => {\n+\t\t\t\trow.cursor.mover = 1;\n+\t\t\t},\n+\t\t\t(row) => {\n+\t\t\t\trow.cursor.move = 1;\n+\t\t\t},\n+\t\t\t(row) => {\n+\t\t\t\trow.cursor.count = repo.graph.lineCount + 1;\n+\t\t\t},\n+\t\t\t(row) => {\n+\t\t\t\trow.cursor.item = 1;\n+\t\t\t},\n+\t\t\t(row) => {\n+\t\t\t\trow.cursor.collection = 9;\n+\t\t\t},\n+\t\t\t(row) => {\n+\t\t\t\trow.cursor.extra = true;\n+\t\t\t},\n+\t\t];\n+\t\tfor (const [index, change] of changes.entries()) {\n+\t\t\tconst bad = structuredClone(saved);\n+\t\t\tchange(bad);\n+\t\t\tif (index > 0) bad.checksum = createHash(\"sha256\").update(JSON.stringify(bad.cursor)).digest(\"hex\");\n+\t\t\tadapter.storage.write(\"move-adoption:job\", \"cursor\", bad);\n+\t\t\tconst before = db.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\t\t\tassert.throws(() => adoptMovesStep(adapter, state, \"job\", identity), /invalid|damaged/);\n+\t\t\tassert.deepEqual(db.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+\t\t}\n+\t\tadapter.storage.write(\"move-adoption:job\", \"cursor\", saved);\n+\t\tassert.equal(adoptMovesStep(adapter, state, \"job\", identity).done, false);\n+\t} finally {\n+\t\tdb.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-marker-cycle.test.ts","added":95,"removed":72,"diff":"--- a/src/engine/test/projection-marker-cycle.test.ts\n+++ b/src/engine/test/projection-marker-cycle.test.ts\n@@ -1,83 +1,106 @@\n import assert from \"node:assert/strict\";\n import { test } from \"node:test\";\n+import { ProjectionAtomAdoption } from \"../experimental/projection-atom-adoption.ts\";\n import { ExperimentalMarkerProjection as MarkerProjection } from \"../experimental/projection-marker.ts\";\n import { Graph } from \"../graph.ts\";\n import { CachedStateStorage } from \"../state-source.ts\";\n+import type { Atom } from \"../types.ts\";\n import { Repo, Rng } from \"./helpers.ts\";\n import { SqlState } from \"./storage-helper.ts\";\n \n-test(\"typed marker projection matches competing cyclic moves and removals\", () => {\n-\tconst db = new SqlState();\n-\ttry {\n-\t\tconst repo = Repo.init({ \"f.txt\": Array.from({ length: 12 }, (_, n) => `${n}\\n`).join(\"\") }),\n-\t\t\tgraph = new Graph({ storage: new CachedStateStorage(db) }),\n-\t\t\trng = new Rng(45131);\n-\t\tgraph.add(repo.graph.atom(\"a0\"));\n-\t\tconst p = new MarkerProjection(db, graph, \"f.txt\", \"typed-\" + \"cycle\");\n-\t\tlet state = p.apply(p.empty(), repo.graph.atom(\"a0\")),\n-\t\t\tchecks = 0;\n-\t\tconst atoms = [];\n-\t\tconst check = () => {\n-\t\t\tconst view = repo.view();\n-\t\t\tassert.deepEqual(\n-\t\t\t\tp.lines(state),\n-\t\t\t\tview.lines(\"f.txt\").map((x) => x.id),\n-\t\t\t);\n-\t\t\tfor (let n = 0; n < 12; n++) {\n-\t\t\t\tconst parent = view.parentOf(`a0.${n}`);\n-\t\t\t\tassert.equal(\n-\t\t\t\t\t(p.markers.get(state.locator, n + 1) as { parentKey: number }).parentKey,\n-\t\t\t\t\tparent.startsWith(\"^\") ? 0 : graph.lineN(parent) + 1,\n+for (const paged of [false, true])\n+\ttest(`typed marker projection matches competing cyclic moves and removals (paged=${paged})`, () => {\n+\t\tconst db = new SqlState();\n+\t\ttry {\n+\t\t\tconst repo = Repo.init({ \"f.txt\": Array.from({ length: 12 }, (_, n) => `${n}\\n`).join(\"\") }),\n+\t\t\t\tgraph = new Graph({ storage: new CachedStateStorage(db) }),\n+\t\t\t\trng = new Rng(45131);\n+\t\t\tgraph.add(repo.graph.atom(\"a0\"));\n+\t\t\tconst p = new MarkerProjection(db, graph, \"f.txt\", \"typed-\" + \"cycle\");\n+\t\t\tlet state = p.apply(p.empty(), repo.graph.atom(\"a0\")),\n+\t\t\t\tchecks = 0;\n+\t\t\tconst atoms = [];\n+\t\t\tlet task = 0;\n+\t\t\tconst apply = (atom: Atom, remove: boolean) => {\n+\t\t\t\tif (!paged) return remove ? p.removeAtom(state, atom) : p.apply(state, atom);\n+\t\t\t\tconst job = new ProjectionAtomAdoption(p, String(task++));\n+\t\t\t\tconst previous = state;\n+\t\t\t\tfor (let pages = 0; pages < 10000; pages++) {\n+\t\t\t\t\tconst result = job.page({\n+\t\t\t\t\t\tprevious,\n+\t\t\t\t\t\tatom,\n+\t\t\t\t\t\tremove,\n+\t\t\t\t\t\tsource: \"c\".repeat(64),\n+\t\t\t\t\t\tmaxSteps: 3,\n+\t\t\t\t\t\tvalidateSource: () => {},\n+\t\t\t\t\t});\n+\t\t\t\t\tassert.ok(result.steps <= 3);\n+\t\t\t\t\tassert.equal(result.atomicMoveWork, false);\n+\t\t\t\t\tif (result.done) return result.state;\n+\t\t\t\t}\n+\t\t\t\tthrow Error(\"move adoption did not finish\");\n+\t\t\t};\n+\t\t\tconst check = () => {\n+\t\t\t\tconst view = repo.view();\n+\t\t\t\tassert.deepEqual(\n+\t\t\t\t\tp.lines(state),\n+\t\t\t\t\tview.lines(\"f.txt\").map((x) => x.id),\n \t\t\t\t);\n-\t\t\t}\n-\t\t\tchecks++;\n-\t\t};\n-\t\tfor (let j = 0; j < 24; j++) {\n-\t\t\tconst offset = rng.int(12),\n-\t\t\t\tmoves = Array.from({ length: 3 }, (_, i) => {\n-\t\t\t\t\tconst line = `a0.${(offset + i) % 12}`,\n-\t\t\t\t\t\tcandidate = `a0.${rng.int(12)}`;\n-\t\t\t\t\treturn { line, parent: candidate === line ? \"^f.txt\" : candidate };\n-\t\t\t\t});\n-\t\t\tconst atom = {\n-\t\t\t\tid: repo.graph.nextId(),\n-\t\t\t\tseq: repo.graph.size,\n-\t\t\t\tauthor: \"fixture\",\n-\t\t\t\tmessage: \"move\",\n-\t\t\t\ttime: j,\n-\t\t\t\tinserts: [],\n-\t\t\t\tdeletes: [],\n-\t\t\t\twrites: moves.flatMap((m) => [`P:${m.line}`, `G:${m.parent}`]),\n-\t\t\t\treads: [],\n-\t\t\t\tholds: [],\n-\t\t\t\tneeds: [],\n-\t\t\t\tresolves: [],\n-\t\t\t\treasons: [],\n-\t\t\t\tdeps: [\"a0\"],\n-\t\t\t\tmoves,\n+\t\t\t\tfor (let n = 0; n < 12; n++) {\n+\t\t\t\t\tconst parent = view.parentOf(`a0.${n}`);\n+\t\t\t\t\tassert.equal(\n+\t\t\t\t\t\t(p.markers.get(state.locator, n + 1) as { parentKey: number }).parentKey,\n+\t\t\t\t\t\tparent.startsWith(\"^\") ? 0 : graph.lineN(parent) + 1,\n+\t\t\t\t\t);\n+\t\t\t\t}\n+\t\t\t\tchecks++;\n \t\t\t};\n-\t\t\trepo.graph.add(atom);\n-\t\t\trepo.shared.add(atom.id);\n-\t\t\tgraph.add(atom);\n-\t\t\tatoms.push(atom);\n-\t\t\tstate = p.apply(state, atom);\n-\t\t\tcheck();\n+\t\t\tfor (let j = 0; j < 24; j++) {\n+\t\t\t\tconst offset = rng.int(12),\n+\t\t\t\t\tmoves = Array.from({ length: 3 }, (_, i) => {\n+\t\t\t\t\t\tconst line = `a0.${(offset + i) % 12}`,\n+\t\t\t\t\t\t\tcandidate = `a0.${rng.int(12)}`;\n+\t\t\t\t\t\treturn { line, parent: candidate === line ? \"^f.txt\" : candidate };\n+\t\t\t\t\t});\n+\t\t\t\tconst atom = {\n+\t\t\t\t\tid: repo.graph.nextId(),\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((m) => [`P:${m.line}`, `G:${m.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.graph.add(atom);\n+\t\t\t\trepo.shared.add(atom.id);\n+\t\t\t\tgraph.add(atom);\n+\t\t\t\tatoms.push(atom);\n+\t\t\t\tstate = apply(atom, false);\n+\t\t\t\tcheck();\n+\t\t\t}\n+\t\t\tfor (const atom of atoms.filter((_, i) => i % 2 === 0)) {\n+\t\t\t\trepo.shared.delete(atom.id);\n+\t\t\t\tstate = apply(atom, true);\n+\t\t\t\tcheck();\n+\t\t\t}\n+\t\t\tassert.equal(\n+\t\t\t\tdb.db\n+\t\t\t\t\t.prepare(\n+\t\t\t\t\t\t\"SELECT count(*) AS n FROM state WHERE collection LIKE '%sequence-resolver:%' OR collection LIKE '%sequence-relocation-work:%' OR collection LIKE '%move-adoption:%'\",\n+\t\t\t\t\t)\n+\t\t\t\t\t.get()!.n,\n+\t\t\t\t0,\n+\t\t\t);\n+\t\t\tassert.equal(checks, 36);\n+\t\t} finally {\n+\t\t\tdb.db.close();\n \t\t}\n-\t\tfor (const atom of atoms.filter((_, i) => i % 2 === 0)) {\n-\t\t\trepo.shared.delete(atom.id);\n-\t\t\tstate = p.removeAtom(state, atom);\n-\t\t\tcheck();\n-\t\t}\n-\t\tassert.equal(\n-\t\t\tdb.db\n-\t\t\t\t.prepare(\n-\t\t\t\t\t\"SELECT count(*) AS n FROM state WHERE collection LIKE '%sequence-resolver:%' OR collection LIKE '%sequence-relocation-work:%'\",\n-\t\t\t\t)\n-\t\t\t\t.get()!.n,\n-\t\t\t0,\n-\t\t);\n-\t\tassert.equal(checks, 36);\n-\t} finally {\n-\t\tdb.db.close();\n-\t}\n-});\n+\t});"},{"path":"src/engine/test/projection-move-resolution.test.ts","added":136,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-move-resolution.test.ts\n@@ -0,0 +1,136 @@\n+import assert from \"node:assert/strict\";\n+import { createHash } from \"node:crypto\";\n+import { test } from \"node:test\";\n+import { resolveMovesPage } from \"../experimental/projection-move-resolution.ts\";\n+import type { RelocationInfo } from \"../graph.ts\";\n+import { resolveScratchMoves } from \"../relocation-scratch.ts\";\n+import { Repo, Rng } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"one-step move pages preserve cycle resolution across competing and excluded moves\", () => {\n+\tconst rng = new Rng(45131);\n+\tlet resolvedCycles = 0;\n+\tfor (let trial = 0; trial < 8; trial++) {\n+\t\tconst repo = Repo.init({ \"f.txt\": Array.from({ length: 12 }, (_, i) => `${i}\\n`).join(\"\"), \"g.txt\": \"\" });\n+\t\tfor (let j = 0; j < 12; j++) {\n+\t\t\tconst offset = rng.int(12);\n+\t\t\tconst moves = Array.from({ length: 3 }, (_, k) => {\n+\t\t\t\tconst line = `a0.${(offset + k) % 12}`,\n+\t\t\t\t\tparent = `a0.${rng.int(12)}`;\n+\t\t\t\treturn { line, parent: parent === line ? \"^g.txt\" : parent };\n+\t\t\t});\n+\t\t\tconst id = repo.graph.nextId();\n+\t\t\trepo.graph.add({\n+\t\t\t\tid,\n+\t\t\t\tseq: repo.graph.size,\n+\t\t\t\tauthor: \"fixture\",\n+\t\t\t\tmessage: \"move\",\n+\t\t\t\ttime: j,\n+\t\t\t\tinserts: [],\n+\t\t\t\tdeletes: [],\n+\t\t\t\twrites: moves.flatMap((m) => [`P:${m.line}`, `G:${m.parent}`]),\n+\t\t\t\treads: [],\n+\t\t\t\tholds: [],\n+\t\t\t\tneeds: [],\n+\t\t\t\tresolves: [],\n+\t\t\t\treasons: [],\n+\t\t\t\tdeps: [\"a0\"],\n+\t\t\t\tmoves,\n+\t\t\t});\n+\t\t\tif ((j + trial) % 3) repo.shared.add(id);\n+\t\t}\n+\t\tconst expected = new SqlState(),\n+\t\t\tactual = new SqlState();\n+\t\ttry {\n+\t\t\tconst oracle = resolveScratchMoves(repo.graph, (id) => repo.shared.has(id), expected);\n+\t\t\tlet done = false,\n+\t\t\t\tpages = 0;\n+\t\t\twhile (!done) {\n+\t\t\t\tconst before = actual.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\t\t\t\tactual.failWrite = actual.writes + 1;\n+\t\t\t\tassert.throws(\n+\t\t\t\t\t() => resolveMovesPage(repo.graph, (id) => repo.shared.has(id), actual, `trial-${trial}`, 1),\n+\t\t\t\t\t/injected storage failure/,\n+\t\t\t\t);\n+\t\t\t\tassert.deepEqual(actual.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+\t\t\t\tactual.failWrite = Infinity;\n+\t\t\t\tconst result = resolveMovesPage(repo.graph, (id) => repo.shared.has(id), actual, `trial-${trial}`, 1);\n+\t\t\t\tassert.ok(result.steps <= 1);\n+\t\t\t\tdone = result.done;\n+\t\t\t\tassert.ok(++pages < 10000);\n+\t\t\t}\n+\t\t\tfor (let n = 0; n < 12; n++) {\n+\t\t\t\tconst line = `a0.${n}`,\n+\t\t\t\t\tselected = actual.read(\"selected\", line) as RelocationInfo | undefined;\n+\t\t\t\tassert.deepEqual(selected, oracle.selected(line));\n+\t\t\t\tassert.equal(selected?.parent ?? repo.graph.lineParent(line), oracle.parent(line));\n+\t\t\t}\n+\t\t\tresolvedCycles += [...actual.entries(\"ignored\")].length;\n+\t\t\tconst rows = actual.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\t\t\tassert.throws(() => resolveMovesPage(repo.graph, () => true, actual, \"changed\", 1), /identity changed/);\n+\t\t\tassert.deepEqual(actual.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), rows);\n+\t\t} finally {\n+\t\t\texpected.db.close();\n+\t\t\tactual.db.close();\n+\t\t}\n+\t}\n+\tassert.ok(resolvedCycles > 0, \"the fixture must exercise cycle breaking\");\n+});\n+\n+test(\"damaged and structurally invalid move cursors refuse without changing stored state\", () => {\n+\tconst repo = Repo.init({ \"f.txt\": \"a\\nb\\n\" });\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tresolveMovesPage(repo.graph, () => true, storage, \"source\", 1);\n+\t\tconst valid = storage.read(\"progress\", \"cursor\") as {\n+\t\t\tformat: number;\n+\t\t\tchecksum: string;\n+\t\t\tstate: Record<string, unknown>;\n+\t\t};\n+\t\tconst changes: Array<(record: typeof valid) => void> = [\n+\t\t\t(record) => {\n+\t\t\t\trecord.checksum = \"damaged\";\n+\t\t\t},\n+\t\t\t(record) => {\n+\t\t\t\trecord.format = 2;\n+\t\t\t},\n+\t\t\t(record) => {\n+\t\t\t\trecord.state.phase = \"unknown\";\n+\t\t\t},\n+\t\t\t(record) => {\n+\t\t\t\trecord.state.mover = 1;\n+\t\t\t},\n+\t\t\t(record) => {\n+\t\t\t\trecord.state.move = 1;\n+\t\t\t},\n+\t\t\t(record) => {\n+\t\t\t\trecord.state.item = 1;\n+\t\t\t},\n+\t\t\t(record) => {\n+\t\t\t\trecord.state.work = repo.graph.lineCount + 1;\n+\t\t\t},\n+\t\t\t(record) => {\n+\t\t\t\trecord.state.slow = 4;\n+\t\t\t},\n+\t\t\t(record) => {\n+\t\t\t\trecord.state.phase = \"repick\";\n+\t\t\t},\n+\t\t\t(record) => {\n+\t\t\t\trecord.state.extra = true;\n+\t\t\t},\n+\t\t];\n+\t\tfor (const [index, change] of changes.entries()) {\n+\t\t\tconst damaged = structuredClone(valid);\n+\t\t\tchange(damaged);\n+\t\t\tif (index > 0) damaged.checksum = createHash(\"sha256\").update(JSON.stringify(damaged.state)).digest(\"hex\");\n+\t\t\tstorage.write(\"progress\", \"cursor\", damaged);\n+\t\t\tconst before = storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\t\t\tassert.throws(() => resolveMovesPage(repo.graph, () => true, storage, \"source\", 1), /invalid|damaged|incomplete/);\n+\t\t\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+\t\t}\n+\t\tstorage.write(\"progress\", \"cursor\", valid);\n+\t\tassert.equal(resolveMovesPage(repo.graph, () => true, storage, \"source\", 1).done, true);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"}],"ci":null}