Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
show on this site's /mcp
CLI
abso show 146 --json
JSON
/christopher/abso-core/versions/146?format=json

Page atom adoption and move reconciliation with restart-safe private state

of shared·codex-capacity-chair··Not checked

Version 145 · Files at version 146

7 files, 1312 lines added, 113 removed.

--- /dev/null
+++ b/src/engine/experimental/projection-atom-adoption.ts
@@ -0,0 +1,293 @@
1+import { createHash } from "node:crypto";
2+import type { Atom } from "../types.ts";
3+import type { ExperimentalMarkerProjection, MarkerState } from "./projection-marker.ts";
4+import { adoptMovesStep } from "./projection-move-adoption.ts";
5+
6+const phases = [
7+ "dependencies",
8+ "files",
9+ "lines",
10+ "deletes",
11+ "counts",
12+ "attributes",
13+ "contributions",
14+ "membership",
15+ "moves",
16+ "cleanup",
17+ "done",
18+] as const;
19+type Phase = (typeof phases)[number];
20+interface Cursor {
21+ identity: string;
22+ phase: Phase;
23+ index: number;
24+ run: number;
25+ line: number;
26+ k: number;
27+ state: MarkerState;
28+}
29+const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
30+function shape(value: unknown, names: string): asserts value is Record<string, unknown> {
31+ const keys = names.split(" ");
32+ if (
33+ !value ||
34+ typeof value !== "object" ||
35+ Array.isArray(value) ||
36+ Object.keys(value).length !== keys.length ||
37+ keys.some((key) => !Object.hasOwn(value, key))
38+ )
39+ throw Error("invalid atom adoption record");
40+}
41+function readCursor(value: unknown): Cursor | undefined {
42+ if (value === undefined) return undefined;
43+ shape(value, "format checksum cursor");
44+ if (value.format !== 1 || typeof value.checksum !== "string" || value.checksum !== digest(value.cursor))
45+ throw Error("damaged atom adoption cursor");
46+ shape(value.cursor, "identity phase index run line k state");
47+ const cursor = value.cursor;
48+ shape(cursor.state, "context sequence locator membership children attributeFiles");
49+ for (const key of ["locator", "membership", "children", "attributeFiles"])
50+ if (cursor.state[key] !== null && (!Number.isSafeInteger(cursor.state[key]) || Number(cursor.state[key]) < 0))
51+ throw Error("invalid atom adoption page reference");
52+ shape(cursor.state.sequence, "map root next");
53+ const sequence = cursor.state.sequence;
54+ if (
55+ !Number.isSafeInteger(sequence.next) ||
56+ Number(sequence.next) < 0 ||
57+ Number(sequence.next) > 2 ** 32 ||
58+ (sequence.map !== null && (!Number.isSafeInteger(sequence.map) || Number(sequence.map) < 0)) ||
59+ (sequence.root !== null &&
60+ (!Number.isSafeInteger(sequence.root) ||
61+ Number(sequence.root) < 0 ||
62+ Number(sequence.root) >= Number(sequence.next))) ||
63+ (sequence.root === null) !== (sequence.next === 0) ||
64+ (sequence.map === null) !== (sequence.root === null)
65+ )
66+ throw Error("invalid atom adoption sequence");
67+ return cursor as unknown as Cursor;
68+}
70+/** Private adoption experiment. Partial state must never be published as a read root.
71+ * The host must pin source identity and atomically retain this cursor with each page.
72+ * Move reconciliation advances through private persisted pages.
73+ */
74+export class ProjectionAtomAdoption {
75+ readonly adapter: ExperimentalMarkerProjection;
76+ readonly task: string;
77+ constructor(adapter: ExperimentalMarkerProjection, task: string) {
78+ if (!task || task.length > 128) throw Error("invalid atom adoption task");
79+ this.adapter = adapter;
80+ this.task = task;
81+ }
82+ page(input: {
83+ previous: MarkerState;
84+ atom: Atom;
85+ remove: boolean;
86+ source: string;
87+ maxSteps: number;
88+ validateSource(): void;
89+ }): {
90+ done: boolean;
91+ state: MarkerState;
92+ steps: number;
93+ atomicMoveWork: boolean;
94+ } {
95+ const { adapter: p } = this;
96+ if (
97+ !/^[a-f0-9]{64}$/.test(input.source) ||
98+ !Number.isSafeInteger(input.maxSteps) ||
99+ input.maxSteps < 1 ||
100+ input.maxSteps > 256
101+ )
102+ throw Error("invalid atom adoption page bounds");
103+ const atom = input.atom;
104+ const identity = digest([input.source, input.previous, atom, input.remove]);
105+ if (digest(p.graph.atom(atom.id)) !== digest(atom)) throw Error("canonical adoption atom mismatch");
106+ const collection = `atom-adoption:${this.task}`;
107+ const validate = () => {
108+ const result: unknown = input.validateSource();
109+ if (result && typeof result === "object" && "then" in result)
110+ throw Error("atom adoption source validation must be synchronous");
111+ };
112+ return p.storage.transaction(() => {
113+ validate();
114+ let cursor = readCursor(p.storage.read(collection, "cursor"));
115+ if (cursor !== undefined) {
116+ if (
117+ !cursor ||
118+ cursor.identity !== identity ||
119+ !phases.includes(cursor.phase) ||
120+ ![cursor.index, cursor.run, cursor.line, cursor.k].every((n) => Number.isSafeInteger(n) && n >= 0)
121+ )
122+ throw Error("invalid or changed atom adoption cursor");
123+ p.assertContext(cursor.state);
124+ if (cursor.run > atom.inserts.length || cursor.line > (atom.inserts[cursor.run]?.lines.length ?? 0))
125+ throw Error("invalid atom adoption line position");
126+ const limits: Record<Phase, number> = {
127+ dependencies: atom.deps.length,
128+ files: atom.inserts.length + 1,
129+ lines: 0,
130+ deletes: atom.deletes.length,
131+ counts: atom.deps.length,
132+ attributes: atom.attrs?.length ?? 0,
133+ contributions: p.graph.filesOf(atom.id).length,
134+ membership: 0,
135+ moves: 0,
136+ cleanup: atom.attrs?.length ?? 0,
137+ done: 0,
138+ };
139+ if (cursor.index > limits[cursor.phase]) throw Error("invalid atom adoption phase position");
140+ } else {
141+ p.assertContext(input.previous);
142+ const member = p.members.get(input.previous.membership, atom.seq);
143+ if (input.remove && member?.dependents) throw Error("included dependent prevents removal");
144+ cursor = {
145+ identity,
146+ phase: (member?.present ?? false) === !input.remove ? "done" : "dependencies",
147+ index: 0,
148+ run: 0,
149+ line: 0,
150+ k: 0,
151+ state: structuredClone(input.previous),
152+ };
153+ }
154+ let steps = 0;
155+ const atomicMoveWork = false;
156+ const next = () => {
157+ cursor!.phase = phases[phases.indexOf(cursor!.phase) + 1]!;
158+ cursor!.index = 0;
159+ };
160+ const state = cursor.state;
161+ const contributionFiles = p.graph.filesOf(atom.id);
162+ while (cursor.phase !== "done" && steps < input.maxSteps) {
163+ steps++;
164+ switch (cursor.phase) {
165+ case "dependencies": {
166+ if (input.remove || cursor.index === atom.deps.length) {
167+ next();
168+ break;
169+ }
170+ const id = atom.deps[cursor.index++]!;
171+ if (!p.members.get(state.membership, p.graph.atom(id).seq)?.present) throw Error("missing dependency");
172+ break;
173+ }
174+ case "files": {
175+ if (input.remove || cursor.index > atom.inserts.length) {
176+ next();
177+ break;
178+ }
179+ p.ensureFile(state, cursor.index === 0 ? p.path : atom.inserts[cursor.index - 1]!.file);
180+ cursor.index++;
181+ break;
182+ }
183+ case "lines": {
184+ if (cursor.run === atom.inserts.length) {
185+ next();
186+ break;
187+ }
188+ const run = atom.inserts[cursor.run]!;
189+ if (cursor.line === run.lines.length) {
190+ cursor.run++;
191+ cursor.line = 0;
192+ break;
193+ }
194+ const line = `${atom.id}.${cursor.k++}`;
195+ cursor.line++;
196+ if (!input.remove) p.insertLine(state, line);
197+ else {
198+ const marker = p.markers.get(state.locator, p.graph.lineN(line) + 1);
199+ if (!marker) throw Error("missing inserted marker");
200+ state.sequence = p.sequence.update(state.sequence, { kind: "visibility", id: marker.enter, delta: 1 });
201+ }
202+ break;
203+ }
204+ case "deletes": {
205+ if (cursor.index === atom.deletes.length) {
206+ next();
207+ break;
208+ }
209+ const marker = p.markers.get(state.locator, p.graph.lineN(atom.deletes[cursor.index++]!) + 1);
210+ if (!marker) throw Error("missing deleted marker");
211+ state.sequence = p.sequence.update(state.sequence, {
212+ kind: "visibility",
213+ id: marker.enter,
214+ delta: input.remove ? -1 : 1,
215+ });
216+ break;
217+ }
218+ case "counts": {
219+ if (cursor.index === atom.deps.length) {
220+ next();
221+ break;
222+ }
223+ const seq = p.graph.atom(atom.deps[cursor.index++]!).seq;
224+ const member = p.members.get(state.membership, seq);
225+ if (!member?.present || (input.remove && member.dependents < 1)) throw Error("invalid dependency count");
226+ state.membership = p.members.set(state.membership, seq, {
227+ ...member,
228+ dependents: member.dependents + (input.remove ? -1 : 1),
229+ });
230+ break;
231+ }
232+ case "attributes": {
233+ const attrs = atom.attrs ?? [];
234+ if (cursor.index === attrs.length) {
235+ next();
236+ break;
237+ }
238+ const attr = attrs[cursor.index++]!;
239+ const key = JSON.stringify([attr.file, attr.name]);
240+ if (!p.storage.read(`${collection}:attributes`, key)) {
241+ p.updateAttributes(state, { ...atom, attrs: [attr] }, !input.remove);
242+ p.storage.write(`${collection}:attributes`, key, true);
243+ }
244+ break;
245+ }
246+ case "contributions": {
247+ if (cursor.index === contributionFiles.length) {
248+ next();
249+ break;
250+ }
251+ const path = contributionFiles[cursor.index++]!;
252+ p.ensureFile(state, path);
253+ const key = p.fileKey(path)!;
254+ const marker = p.markers.get(state.locator, key);
255+ const delta = input.remove ? -1 : 1;
256+ if (marker?.kind !== "file" || marker.contributions + delta < 0)
257+ throw Error("invalid file contribution count");
258+ state.locator = p.markers.set(state.locator, key, {
259+ ...marker,
260+ contributions: marker.contributions + delta,
261+ });
262+ break;
263+ }
264+ case "membership":
265+ state.membership = p.members.set(state.membership, atom.seq, { present: !input.remove, dependents: 0 });
266+ next();
267+ break;
268+ case "moves":
269+ if (atom.moves?.length) {
270+ const result = adoptMovesStep(p, state, this.task, identity);
271+ Object.assign(state, result.state);
272+ if (!result.done) break;
273+ }
274+ next();
275+ break;
276+ case "cleanup": {
277+ const attrs = atom.attrs ?? [];
278+ if (cursor.index === attrs.length) {
279+ next();
280+ break;
281+ }
282+ const attr = attrs[cursor.index++]!;
283+ p.storage.remove(`${collection}:attributes`, JSON.stringify([attr.file, attr.name]));
284+ break;
285+ }
286+ }
287+ }
288+ validate();
289+ p.storage.write(collection, "cursor", { format: 1, checksum: digest(cursor), cursor });
290+ return { done: cursor.phase === "done", state: structuredClone(state), steps, atomicMoveWork };
291+ });
292+ }
293+}
--- a/src/engine/experimental/projection-marker.ts
+++ b/src/engine/experimental/projection-marker.ts
@@ -119,50 +119,10 @@
119119 return this.storage.transaction(() => {
120120 const state = { ...previous };
121121 const sequence = this.sequence;
122− const insert = (rank: number, text: string, hidden = false): number => {
123− const id = state.sequence.next;
124− state.sequence = sequence.update(state.sequence, { kind: "insert", rank, text });
125− if (hidden) state.sequence = sequence.update(state.sequence, { kind: "visibility", id, delta: 1 });
126− return id;
127− };
128122 this.ensureFile(state, this.path);
129123 for (const run of atom.inserts) this.ensureFile(state, run.file);
130124 let k = 0;
131− for (const run of atom.inserts)
132− for (const text of run.lines) {
133− const line = `${atom.id}.${k++}`,
134− n = this.graph.lineN(line),
135− parent = this.graph.parentCodeOf(n);
136− if (n + 1 >= 0x80000000) throw Error("prototype line identity limit");
137− const existing = this.markers.get(state.locator, n + 1);
138− if (existing) {
139− state.sequence = sequence.update(state.sequence, { kind: "visibility", id: existing.enter, delta: -1 });
140− continue;
141− }
142− const parentMarker = this.markers.get(state.locator, this.parentKey(parent));
143− if (!parentMarker) throw Error("missing parent marker");
144− const parentKey = this.parentKey(parent);
145− const index = this.priorities;
146− const root = this.childRoots.get(state.children, parentKey)?.root ?? null;
147− const seq = this.graph.writerSeqOf(n);
148− const key = orderedChildKey({
149− n,
150− replaces: this.graph.replacesN(n) ? 1 : 0,
151− lamport: this.graph.lamportOfSeq(seq),
152− seq,
153− k: this.graph.kOf(n),
154− });
155− const preceding = index.before(root, key);
156− const anchor =
157− preceding === undefined
158− ? parentMarker.enter
159− : required(this.markers.get(state.locator, preceding + 1)).exit;
160− state.children = this.childRoots.set(state.children, parentKey, { root: index.insert(root, key, n) });
161− const at = sequence.rank(state.sequence, anchor) + 1;
162− const enter = insert(at, line),
163− exit = insert(at + 1, `${line}:end`, true);
164− state.locator = this.markers.set(state.locator, n + 1, { kind: "line", enter, exit, parentKey, key });
165− }
125+ for (const run of atom.inserts) for (const _ of run.lines) this.insertLine(state, `${atom.id}.${k++}`);
166126 for (const line of atom.deletes) {
167127 const marker = this.markers.get(state.locator, this.graph.lineN(line) + 1);
168128 if (!marker) throw Error("missing deleted marker");
@@ -179,6 +139,46 @@
179139 return atom.moves?.length ? this.reconcileMoves(state) : state;
180140 });
181141 }
142+ /** One canonical line insertion; used by atomic apply and resumable inactive adoption. */
143+ insertLine(state: MarkerState, line: string): void {
144+ this.assertContext(state);
145+ const sequence = this.sequence;
146+ const insert = (rank: number, text: string, hidden = false): number => {
147+ const id = state.sequence.next;
148+ state.sequence = sequence.update(state.sequence, { kind: "insert", rank, text });
149+ if (hidden) state.sequence = sequence.update(state.sequence, { kind: "visibility", id, delta: 1 });
150+ return id;
151+ };
152+ const n = this.graph.lineN(line),
153+ parent = this.graph.parentCodeOf(n);
154+ if (n + 1 >= 0x80000000) throw Error("prototype line identity limit");
155+ const existing = this.markers.get(state.locator, n + 1);
156+ if (existing) {
157+ state.sequence = sequence.update(state.sequence, { kind: "visibility", id: existing.enter, delta: -1 });
158+ return;
159+ }
160+ const parentMarker = this.markers.get(state.locator, this.parentKey(parent));
161+ if (!parentMarker) throw Error("missing parent marker");
162+ const parentKey = this.parentKey(parent);
163+ const index = this.priorities;
164+ const root = this.childRoots.get(state.children, parentKey)?.root ?? null;
165+ const seq = this.graph.writerSeqOf(n);
166+ const key = orderedChildKey({
167+ n,
168+ replaces: this.graph.replacesN(n) ? 1 : 0,
169+ lamport: this.graph.lamportOfSeq(seq),
170+ seq,
171+ k: this.graph.kOf(n),
172+ });
173+ const preceding = index.before(root, key);
174+ const anchor =
175+ preceding === undefined ? parentMarker.enter : required(this.markers.get(state.locator, preceding + 1)).exit;
176+ state.children = this.childRoots.set(state.children, parentKey, { root: index.insert(root, key, n) });
177+ const at = sequence.rank(state.sequence, anchor) + 1;
178+ const enter = insert(at, line),
179+ exit = insert(at + 1, `${line}:end`, true);
180+ state.locator = this.markers.set(state.locator, n + 1, { kind: "line", enter, exit, parentKey, key });
181+ }
182182 removeDeleter(previous: MarkerState, atom: Atom): MarkerState {
183183 return this.removeAtom(previous, atom);
184184 }
--- /dev/null
+++ b/src/engine/experimental/projection-move-adoption.ts
@@ -0,0 +1,186 @@
1+import { createHash } from "node:crypto";
2+import type { RelocationInfo } from "../graph.ts";
3+import { orderedChildKey } from "../ordered-index.ts";
4+import type { GraphStateStorage } from "../state-source.ts";
5+import type { ExperimentalMarkerProjection, MarkerState } from "./projection-marker.ts";
6+import { resolveMovesPage } from "./projection-move-resolution.ts";
7+
8+type Phase = "files" | "resolve" | "plans" | "park" | "place" | "cleanup" | "done";
9+interface Cursor {
10+ identity: string;
11+ phase: Phase;
12+ mover: number;
13+ move: number;
14+ count: number;
15+ item: number;
16+ collection: number;
17+}
18+interface Plan {
19+ n: number;
20+ parentKey: number;
21+ key: string;
22+}
23+const collections = ["selected", "seen", "work", "ignored", "reached", "progress", "planned", "plans"];
24+const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
26+function shape(value: unknown, fields: string): asserts value is Record<string, unknown> {
27+ const keys = fields.split(" ");
28+ if (
29+ !value ||
30+ typeof value !== "object" ||
31+ Array.isArray(value) ||
32+ Object.keys(value).length !== keys.length ||
33+ keys.some((key) => !Object.hasOwn(value, key))
34+ )
35+ throw Error("invalid move adoption record");
36+}
38+/** The caller must persist the returned private root in the same transaction. */
39+export function adoptMovesStep(
40+ p: ExperimentalMarkerProjection,
41+ previous: MarkerState,
42+ task: string,
43+ identity: string,
44+): { done: boolean; state: MarkerState } {
45+ p.assertContext(previous);
46+ if (!task || task.length > 128 || !/^[a-f0-9]{64}$/.test(identity)) throw Error("invalid move adoption identity");
47+ const name = `move-adoption:${task}`;
48+ const scratch: GraphStateStorage = {
49+ read: (c, k) => p.storage.read(`${name}:${c}`, k),
50+ write: (c, k, v) => p.storage.write(`${name}:${c}`, k, v),
51+ remove: (c, k) => p.storage.remove(`${name}:${c}`, k),
52+ entries: (c) => p.storage.entries(`${name}:${c}`),
53+ transaction: (body) => p.storage.transaction(body),
54+ };
55+ return p.storage.transaction(() => {
56+ const saved = p.storage.read(name, "cursor");
57+ let restored: Cursor | undefined;
58+ if (saved !== undefined) {
59+ shape(saved, "format checksum cursor");
60+ if (saved.format !== 1 || saved.checksum !== digest(saved.cursor)) throw Error("damaged move adoption cursor");
61+ shape(saved.cursor, "identity phase mover move count item collection");
62+ restored = saved.cursor as unknown as Cursor;
63+ }
64+ const cursor: Cursor = restored ?? {
65+ identity,
66+ phase: "files",
67+ mover: 0,
68+ move: 0,
69+ count: 0,
70+ item: 0,
71+ collection: 0,
72+ };
73+ if (
74+ cursor.identity !== identity ||
75+ !["files", "resolve", "plans", "park", "place", "cleanup", "done"].includes(cursor.phase) ||
76+ ![cursor.mover, cursor.move, cursor.count, cursor.item, cursor.collection].every(
77+ (n) => Number.isSafeInteger(n) && n >= 0,
78+ ) ||
79+ cursor.mover > p.graph.movers().length ||
80+ cursor.item > cursor.count ||
81+ cursor.count > p.graph.lineCount ||
82+ cursor.collection > collections.length
83+ )
84+ throw Error("invalid move adoption cursor");
85+ const mover = p.graph.movers()[cursor.mover];
86+ if (cursor.move > (mover === undefined ? 0 : (p.graph.atom(mover).moves?.length ?? 0)))
87+ throw Error("invalid move adoption offset");
88+ let state = { ...previous };
89+ const has = (id: string) => p.members.get(state.membership, p.graph.atom(id).seq)?.present ?? false;
90+ switch (cursor.phase) {
91+ case "files":
92+ case "plans": {
93+ if (cursor.mover === p.graph.movers().length) {
94+ cursor.phase = cursor.phase === "files" ? "resolve" : "park";
95+ cursor.mover = 0;
96+ cursor.move = 0;
97+ break;
98+ }
99+ const moves = p.graph.atom(p.graph.movers()[cursor.mover]!).moves ?? [];
100+ if (cursor.move > moves.length) throw Error("invalid move adoption offset");
101+ if (cursor.move === moves.length) {
102+ cursor.mover++;
103+ cursor.move = 0;
104+ break;
105+ }
106+ const move = moves[cursor.move++]!;
107+ if (cursor.phase === "files") {
108+ if (move.parent.startsWith("^")) p.ensureFile(state, move.parent.slice(1));
109+ break;
110+ }
111+ if (scratch.read("planned", move.line)) break;
112+ scratch.write("planned", move.line, true);
113+ const n = p.graph.lineN(move.line);
114+ if (!has(p.graph.idOfSeq(p.graph.writerSeqOf(n)))) break;
115+ const marker = p.markers.get(state.locator, n + 1);
116+ if (marker?.kind !== "line") throw Error("missing selected relocation marker");
117+ const selected = scratch.read("selected", move.line) as RelocationInfo | undefined;
118+ const parent = selected?.parent ?? p.graph.lineParent(move.line);
119+ if (parent === undefined) throw Error("missing relocation ancestry");
120+ const parentKey = parent.startsWith("^") ? p.fileKey(parent.slice(1)) : p.graph.lineN(parent) + 1;
121+ if (parentKey === undefined) throw Error("missing relocation file");
122+ const seq = selected ? p.graph.atom(selected.atom).seq : p.graph.writerSeqOf(n);
123+ const key = orderedChildKey({
124+ n,
125+ replaces: selected ? 0 : Number(p.graph.replacesN(n)),
126+ lamport: p.graph.lamportOfSeq(seq),
127+ seq,
128+ k: selected ? selected.k : p.graph.kOf(n),
129+ });
130+ if (parentKey !== marker.parentKey || key !== marker.key)
131+ scratch.write("plans", String(cursor.count++), { n, parentKey, key });
132+ break;
133+ }
134+ case "resolve":
135+ if (resolveMovesPage(p.graph, has, scratch, identity, 1).done) cursor.phase = "plans";
136+ break;
137+ case "park":
138+ case "place": {
139+ if (cursor.item === cursor.count) {
140+ cursor.phase = cursor.phase === "park" ? "place" : "cleanup";
141+ cursor.item = 0;
142+ break;
143+ }
144+ const plan = scratch.read("plans", String(cursor.item++)) as Plan | undefined;
145+ if (
146+ !plan ||
147+ !Number.isSafeInteger(plan.n) ||
148+ plan.n < 0 ||
149+ !Number.isSafeInteger(plan.parentKey) ||
150+ plan.parentKey < 0 ||
151+ !/^[0-9a-f]{57}$/.test(plan.key)
152+ )
153+ throw Error("invalid saved relocation plan");
154+ const marker = p.markers.get(state.locator, plan.n + 1);
155+ if (marker?.kind !== "line") throw Error("missing relocation marker");
156+ state = p.relocate(
157+ state,
158+ plan.n,
159+ cursor.phase === "park" ? 0 : plan.parentKey,
160+ cursor.phase === "park" ? marker.key : plan.key,
161+ );
162+ break;
163+ }
164+ case "cleanup": {
165+ if (cursor.collection === collections.length) {
166+ cursor.phase = "done";
167+ break;
168+ }
169+ const collection = collections[cursor.collection]!;
170+ const iterator = scratch.entries(collection)[Symbol.iterator]();
171+ let row: IteratorResult<readonly [string, unknown]>;
172+ try {
173+ row = iterator.next();
174+ } finally {
175+ iterator.return?.();
176+ }
177+ if (row.done) cursor.collection++;
178+ else scratch.remove(collection, row.value[0]);
179+ break;
180+ }
181+ }
182+ if (cursor.phase === "done") p.storage.remove(name, "cursor");
183+ else p.storage.write(name, "cursor", { format: 1, checksum: digest(cursor), cursor });
184+ return { done: cursor.phase === "done", state };
185+ });
186+}
--- /dev/null
+++ b/src/engine/experimental/projection-move-resolution.ts
@@ -0,0 +1,234 @@
1+import { createHash } from "node:crypto";
2+import type { Graph, RelocationInfo } from "../graph.ts";
3+import { isStartNode } from "../keys.ts";
4+import type { GraphStateStorage } from "../state-source.ts";
5+import type { NodeId } from "../types.ts";
6+
7+interface Progress {
8+ identity: string;
9+ phase: "scan" | "walk" | "entry" | "weakest" | "repick" | "mark" | "done";
10+ mover: number;
11+ move: number;
12+ work: number;
13+ item: number;
14+ line: NodeId | null;
15+ slow: NodeId | null;
16+ fast: NodeId | null;
17+ meeting: NodeId | null;
18+ entry: NodeId | null;
19+ current: NodeId | null;
20+ weakest: RelocationInfo | null;
21+ best: RelocationInfo | null;
22+}
23+const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
24+const integer = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
25+function shape(value: unknown, fields: string): asserts value is Record<string, unknown> {
26+ const keys = fields.split(" ");
27+ if (
28+ !value ||
29+ typeof value !== "object" ||
30+ Array.isArray(value) ||
31+ Object.keys(value).length !== keys.length ||
32+ keys.some((key) => !Object.hasOwn(value, key))
33+ )
34+ throw Error("invalid move resolution record");
35+}
36+function readProgress(value: unknown, graph: Graph): Progress | undefined {
37+ if (value === undefined) return undefined;
38+ shape(value, "format checksum state");
39+ if (value.format !== 1 || value.checksum !== digest(value.state)) throw Error("damaged move resolution cursor");
40+ shape(value.state, "identity phase mover move work item line slow fast meeting entry current weakest best");
41+ const state = value.state;
42+ if (
43+ typeof state.identity !== "string" ||
44+ !state.identity ||
45+ state.identity.length > 4096 ||
46+ !["scan", "walk", "entry", "weakest", "repick", "mark", "done"].includes(String(state.phase)) ||
47+ ![state.mover, state.move, state.work, state.item].every(integer) ||
48+ Number(state.mover) > graph.movers().length ||
49+ Number(state.item) > Number(state.work) ||
50+ Number(state.work) > graph.lineCount
51+ )
52+ throw Error("invalid move resolution position");
53+ const mover = graph.movers()[Number(state.mover)];
54+ if (Number(state.move) > (mover === undefined ? 0 : (graph.atom(mover).moves?.length ?? 0)))
55+ throw Error("invalid move offset");
56+ for (const key of ["line", "slow", "fast", "meeting", "entry", "current"])
57+ if (state[key] !== null && (typeof state[key] !== "string" || !state[key] || String(state[key]).length > 4096))
58+ throw Error("invalid move ancestry cursor");
59+ for (const key of ["weakest", "best"]) {
60+ const move = state[key];
61+ if (move === null) continue;
62+ shape(move, "atom line parent k");
63+ if (typeof move.atom !== "string" || !integer(move.k)) throw Error("invalid saved move");
64+ const canonical = graph.atom(move.atom).moves?.[move.k];
65+ if (!canonical || canonical.line !== move.line || canonical.parent !== move.parent)
66+ throw Error("saved move identity mismatch");
67+ }
68+ if (
69+ (state.phase === "repick" && state.weakest === null) ||
70+ (["entry", "weakest", "repick", "mark"].includes(String(state.phase)) && state.line === null) ||
71+ (state.phase === "entry" && (state.entry === null || state.meeting === null)) ||
72+ (state.phase === "weakest" && (state.entry === null || state.current === null))
73+ )
74+ throw Error("incomplete move resolution cursor");
75+ return state as unknown as Progress;
76+}
78+/** Private paged equivalent of resolveScratchMoves. Caller isolates storage and
79+ * binds identity to immutable graph, membership and source before every page. */
80+export function resolveMovesPage(
81+ graph: Graph,
82+ has: (id: string) => boolean,
83+ storage: GraphStateStorage,
84+ identity: string,
85+ maxSteps: number,
86+): { done: boolean; steps: number } {
87+ if (!identity || identity.length > 4096 || !Number.isSafeInteger(maxSteps) || maxSteps < 1 || maxSteps > 256)
88+ throw Error("invalid move resolution page");
89+ return storage.transaction(() => {
90+ let state = readProgress(storage.read("progress", "cursor"), graph);
91+ if (state && state.identity !== identity) throw Error("move resolution identity changed");
92+ state ??= {
93+ identity,
94+ phase: "scan",
95+ mover: 0,
96+ move: 0,
97+ work: 0,
98+ item: 0,
99+ line: null,
100+ slow: null,
101+ fast: null,
102+ meeting: null,
103+ entry: null,
104+ current: null,
105+ weakest: null,
106+ best: null,
107+ };
108+ const selected = (line: string) => storage.read("selected", line) as RelocationInfo | undefined;
109+ const parent = (line: string): NodeId => {
110+ const value = selected(line)?.parent ?? graph.lineParent(line);
111+ if (value === undefined) throw Error("missing relocation ancestry");
112+ return value;
113+ };
114+ const terminal = (node: NodeId | null) => node === null || isStartNode(node) || !!storage.read("reached", node);
115+ const step = (node: NodeId | null): NodeId | null => (terminal(node) ? null : parent(node!));
116+ const stronger = (a: RelocationInfo, b: RelocationInfo) => graph.comparePriority(a.atom, b.atom) > 0;
117+ const moveKey = (move: RelocationInfo) => JSON.stringify([move.atom, move.k]);
118+ const restartWalk = () => {
119+ state!.phase = "walk";
120+ state!.slow = state!.line;
121+ state!.fast = state!.line;
122+ };
123+ let steps = 0;
124+ while (state.phase !== "done" && steps < maxSteps) {
125+ steps++;
126+ switch (state.phase) {
127+ case "scan":
128+ case "repick": {
129+ if (state.mover === graph.movers().length) {
130+ if (state.phase === "scan") {
131+ state.phase = "walk";
132+ state.line = null;
133+ } else {
134+ const line = state.weakest!.line;
135+ if (state.best) storage.write("selected", line, state.best);
136+ else storage.remove("selected", line);
137+ restartWalk();
138+ }
139+ break;
140+ }
141+ const id = graph.movers()[state.mover]!;
142+ if (!has(id)) {
143+ state.mover++;
144+ state.move = 0;
145+ break;
146+ }
147+ const moves = graph.atom(id).moves ?? [];
148+ if (state.move === moves.length) {
149+ state.mover++;
150+ state.move = 0;
151+ break;
152+ }
153+ const k = state.move++;
154+ const candidate: RelocationInfo = { atom: id, ...moves[k]!, k };
155+ if (state.phase === "scan") {
156+ if (!storage.read("seen", candidate.line)) {
157+ storage.write("seen", candidate.line, true);
158+ storage.write("work", String(state.work++), candidate.line);
159+ }
160+ const best = selected(candidate.line);
161+ if (!best || stronger(candidate, best)) storage.write("selected", candidate.line, candidate);
162+ } else if (
163+ candidate.line === state.weakest!.line &&
164+ !storage.read("ignored", moveKey(candidate)) &&
165+ (!state.best || stronger(candidate, state.best))
166+ )
167+ state.best = candidate;
168+ break;
169+ }
170+ case "walk": {
171+ if (state.line === null) {
172+ if (state.item === state.work) {
173+ state.phase = "done";
174+ break;
175+ }
176+ state.line = storage.read("work", String(state.item)) as string;
177+ restartWalk();
178+ break;
179+ }
180+ state.slow = step(state.slow);
181+ state.fast = step(step(state.fast));
182+ if (terminal(state.slow) || terminal(state.fast)) {
183+ state.phase = "mark";
184+ state.current = state.line;
185+ } else if (state.slow === state.fast) {
186+ state.phase = "entry";
187+ state.meeting = state.slow;
188+ state.entry = state.line;
189+ }
190+ break;
191+ }
192+ case "entry": {
193+ if (state.entry === state.meeting) {
194+ state.phase = "weakest";
195+ state.current = state.entry;
196+ state.weakest = null;
197+ break;
198+ }
199+ state.entry = step(state.entry);
200+ state.meeting = step(state.meeting);
201+ break;
202+ }
203+ case "weakest": {
204+ const move = selected(state.current!);
205+ if (move && (!state.weakest || stronger(state.weakest, move))) state.weakest = move;
206+ state.current = parent(state.current!);
207+ if (state.current === state.entry) {
208+ if (!state.weakest) throw Error("canonical ancestry unexpectedly cycles");
209+ storage.write("ignored", moveKey(state.weakest), true);
210+ state.phase = "repick";
211+ state.mover = 0;
212+ state.move = 0;
213+ state.best = null;
214+ }
215+ break;
216+ }
217+ case "mark": {
218+ if (terminal(state.current)) {
219+ state.item++;
220+ state.line = null;
221+ state.phase = "walk";
222+ break;
223+ }
224+ const next = parent(state.current!);
225+ storage.write("reached", state.current!, true);
226+ state.current = next;
227+ break;
228+ }
229+ }
230+ }
231+ storage.write("progress", "cursor", { format: 1, checksum: digest(state), state });
232+ return { done: state.phase === "done", steps };
233+ });
234+}
--- /dev/null
+++ b/src/engine/test/projection-atom-adoption.test.ts
@@ -0,0 +1,327 @@
1+import assert from "node:assert/strict";
2+import { createHash } from "node:crypto";
3+import { mkdtempSync, rmdirSync, unlinkSync } from "node:fs";
4+import { tmpdir } from "node:os";
5+import { join } from "node:path";
6+import { test } from "node:test";
7+import { ProjectionAtomAdoption } from "../experimental/projection-atom-adoption.ts";
8+import { ExperimentalMarkerProjection } from "../experimental/projection-marker.ts";
9+import { adoptMovesStep } from "../experimental/projection-move-adoption.ts";
10+import { Graph } from "../graph.ts";
11+import { CachedStateStorage } from "../state-source.ts";
12+import { Repo } from "./helpers.ts";
13+import { SqlState } from "./storage-helper.ts";
15+test("an unfinished atom resumes after closing and reopening its SQLite database", () => {
16+ const directory = mkdtempSync(join(tmpdir(), "abso-atom-adoption-"));
17+ const filename = join(directory, "state.sqlite");
18+ let db = new SqlState(filename);
19+ try {
20+ const repo = Repo.init({ "a.txt": "one\ntwo\nthree\nfour\n" });
21+ const atom = repo.graph.atom("a0");
22+ new Graph({ storage: db }).add(atom);
23+ const previous = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "restart").empty();
24+ let done = false,
25+ pages = 0;
26+ while (!done) {
27+ const adapter = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "restart");
28+ const result = new ProjectionAtomAdoption(adapter, "initial").page({
29+ previous,
30+ atom,
31+ remove: false,
32+ source: "d".repeat(64),
33+ maxSteps: 2,
34+ validateSource: () => {},
35+ });
36+ assert.ok(result.steps <= 2);
37+ done = result.done;
38+ if (done)
39+ assert.deepEqual(
40+ adapter.lines(result.state),
41+ repo
42+ .view()
43+ .lines("a.txt")
44+ .map((line) => line.id),
45+ );
46+ assert.ok(++pages < 50);
47+ db.db.close();
48+ db = new SqlState(filename);
49+ }
50+ assert.ok(pages > 5);
51+ } finally {
52+ db.db.close();
53+ unlinkSync(filename);
54+ rmdirSync(directory);
55+ }
56+});
58+test("atom adoption resumes small pages and matches atomic additions and reverse removals", () => {
59+ const db = new SqlState();
60+ try {
61+ const repo = Repo.init({
62+ "a.txt": Array.from({ length: 40 }, (_, i) => `line ${i}\n`).join(""),
63+ "b.txt": "other\n",
64+ });
65+ const graph = new Graph({ storage: new CachedStateStorage(db) });
66+ const atoms = [repo.graph.atom("a0")];
67+ atoms.push(
68+ repo.edit({
69+ edits: [{ file: "a.txt", old: repo.view().text("a.txt"), new: "replacement\n" }],
70+ attrs: [{ file: "b.txt", name: "exec", value: "1" }],
71+ }),
72+ );
73+ atoms.push(repo.edit({ move: { file: "a.txt", start: 0, end: 1, to: "b.txt", at: 0 } }));
74+ for (const atom of atoms) graph.add(atom);
75+ const adapter = () => new ExperimentalMarkerProjection(db, graph, "a.txt", "paged");
76+ const oracle = new ExperimentalMarkerProjection(db, graph, "a.txt", "atomic");
77+ let state = adapter().empty(),
78+ expected = oracle.empty(),
79+ task = 0;
80+ for (const [atom, remove] of [
81+ ...atoms.map((a) => [a, false] as const),
82+ ...atoms.toReversed().map((a) => [a, true] as const),
83+ ]) {
84+ const previous = state,
85+ id = String(task++);
86+ let done = false,
87+ pages = 0,
88+ atomicMovePages = 0;
89+ while (!done) {
90+ const result = new ProjectionAtomAdoption(adapter(), id).page({
91+ previous,
92+ atom,
93+ remove,
94+ source: "a".repeat(64),
95+ maxSteps: 3,
96+ validateSource: () => {},
97+ });
98+ assert.ok(result.steps <= 3);
99+ if (result.atomicMoveWork) atomicMovePages++;
100+ state = result.state;
101+ done = result.done;
102+ assert.ok(++pages < 200);
103+ }
104+ assert.ok(pages > 1);
105+ assert.equal(atomicMovePages, 0);
106+ assert.equal(
107+ db.db.prepare("SELECT COUNT(*) AS n FROM state WHERE collection LIKE ?").get("%move-adoption:%")!.n,
108+ 0,
109+ );
110+ expected = remove ? oracle.removeAtom(expected, atom) : oracle.apply(expected, atom);
111+ for (const path of ["a.txt", "b.txt"]) {
112+ assert.deepEqual(adapter().lines(state, path), oracle.lines(expected, path));
113+ assert.deepEqual(adapter().attrs(state, path), oracle.attrs(expected, path));
114+ }
115+ assert.deepEqual(adapter().knownPaths(state), oracle.knownPaths(expected));
116+ }
117+ } finally {
118+ db.db.close();
119+ }
120+});
122+test("source drift rolls back an atom page and a changed atom cannot resume its cursor", () => {
123+ const db = new SqlState();
124+ try {
125+ const repo = Repo.init({ "a.txt": "one\ntwo\nthree\n" });
126+ const graph = new Graph({ storage: db });
127+ const atom = repo.graph.atom("a0");
128+ graph.add(atom);
129+ const adapter = new ExperimentalMarkerProjection(db, graph, "a.txt", "failure");
130+ const job = new ProjectionAtomAdoption(adapter, "one");
131+ const input = {
132+ previous: adapter.empty(),
133+ atom,
134+ remove: false,
135+ source: "b".repeat(64),
136+ maxSteps: 3,
137+ validateSource: () => {},
138+ };
139+ job.page(input);
140+ const rows = () => db.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
141+ const before = rows();
142+ const saved = adapter.storage.read("atom-adoption:one", "cursor") as {
143+ format: number;
144+ checksum: string;
145+ cursor: { index: number; run: number; phase: string; state: { sequence: { next: number } } };
146+ };
147+ for (const field of ["checksum", "index", "run", "sequence", "phase"]) {
148+ const damaged = structuredClone(saved);
149+ if (field === "checksum") damaged.checksum = "bad";
150+ else {
151+ if (field === "index") damaged.cursor.index = Number.MAX_SAFE_INTEGER;
152+ if (field === "run") damaged.cursor.run = atom.inserts.length + 1;
153+ if (field === "sequence") damaged.cursor.state.sequence.next = -1;
154+ if (field === "phase") damaged.cursor.phase = "unknown";
155+ damaged.checksum = createHash("sha256").update(JSON.stringify(damaged.cursor)).digest("hex");
156+ }
157+ adapter.storage.write("atom-adoption:one", "cursor", damaged);
158+ const corruptRows = rows();
159+ assert.throws(() => job.page(input), /invalid|damaged/, field);
160+ assert.deepEqual(rows(), corruptRows, field);
161+ adapter.storage.write("atom-adoption:one", "cursor", saved);
162+ }
163+ assert.deepEqual(rows(), before);
164+ assert.throws(() => job.page({ ...input, validateSource: () => Promise.resolve() }), /must be synchronous/);
165+ assert.deepEqual(rows(), before);
166+ let asyncChecks = 0;
167+ assert.throws(
168+ () => job.page({ ...input, validateSource: () => (++asyncChecks === 2 ? Promise.resolve() : undefined) }),
169+ /must be synchronous/,
170+ );
171+ assert.deepEqual(rows(), before);
172+ let checks = 0;
173+ assert.throws(
174+ () =>
175+ job.page({
176+ ...input,
177+ validateSource: () => {
178+ if (++checks === 2) throw Error("source drift");
179+ },
180+ }),
181+ /source drift/,
182+ );
183+ assert.deepEqual(rows(), before);
184+ assert.throws(
185+ () => job.page({ ...input, atom: { ...atom, message: "changed" } }),
186+ /canonical adoption atom mismatch/,
187+ );
188+ assert.deepEqual(rows(), before);
189+ assert.throws(() => job.page({ ...input, source: "c".repeat(64) }), /changed atom adoption cursor/);
190+ assert.deepEqual(rows(), before);
191+ assert.equal(job.page(input).steps, 3);
192+ } finally {
193+ db.db.close();
194+ }
195+});
197+test("move adoption rolls back complete pages and resumes every phase after SQLite reopen", () => {
198+ const directory = mkdtempSync(join(tmpdir(), "abso-move-restart-"));
199+ const filename = join(directory, "state.sqlite");
200+ let db = new SqlState(filename);
201+ try {
202+ const repo = Repo.init({ "a.txt": "one\ntwo\nthree\n", "b.txt": "other\n" });
203+ const initial = repo.graph.atom("a0");
204+ const move = repo.edit({ move: { file: "a.txt", start: 0, end: 2, to: "b.txt", at: 1 } });
205+ const graph = new Graph({ storage: db });
206+ graph.add(initial);
207+ graph.add(move);
208+ const first = new ExperimentalMarkerProjection(db, graph, "a.txt", "restart-moves");
209+ let state = first.apply(first.empty(), initial);
210+ const phases = new Set<string>();
211+ for (const remove of [false, true]) {
212+ const previous = state;
213+ let done = false,
214+ pages = 0;
215+ while (!done) {
216+ const adapter = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "restart-moves");
217+ const job = new ProjectionAtomAdoption(adapter, remove ? "remove" : "add");
218+ const input = { previous, atom: move, remove, source: "f".repeat(64), maxSteps: 1, validateSource: () => {} };
219+ const before = db.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
220+ let validations = 0;
221+ assert.throws(
222+ () =>
223+ job.page({
224+ ...input,
225+ validateSource: () => {
226+ if (++validations === 2) throw Error("source changed after page");
227+ },
228+ }),
229+ /source changed after page/,
230+ );
231+ assert.deepEqual(db.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before);
232+ const result = job.page(input);
233+ state = result.state;
234+ done = result.done;
235+ assert.equal(result.atomicMoveWork, false);
236+ assert.ok(result.steps <= 1);
237+ const saved = adapter.storage.read(`move-adoption:${remove ? "remove" : "add"}`, "cursor") as
238+ | { cursor: { phase: string } }
239+ | undefined;
240+ if (saved) phases.add(saved.cursor.phase);
241+ assert.ok(++pages < 300);
242+ db.db.close();
243+ db = new SqlState(filename);
244+ }
245+ const adapter = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "restart-moves");
246+ const oracle = new ExperimentalMarkerProjection(
247+ db,
248+ new Graph({ storage: db }),
249+ "a.txt",
250+ remove ? "oracle-remove" : "oracle-add",
251+ );
252+ let expected = oracle.apply(oracle.empty(), initial);
253+ if (!remove) expected = oracle.apply(expected, move);
254+ for (const path of ["a.txt", "b.txt"]) assert.deepEqual(adapter.lines(state, path), oracle.lines(expected, path));
255+ assert.equal(
256+ db.db.prepare("SELECT COUNT(*) AS n FROM state WHERE collection LIKE ?").get("%move-adoption:%")!.n,
257+ 0,
258+ );
259+ }
260+ for (const phase of ["files", "resolve", "plans", "park", "place", "cleanup"]) assert.ok(phases.has(phase), phase);
261+ } finally {
262+ db.db.close();
263+ unlinkSync(filename);
264+ rmdirSync(directory);
265+ }
266+});
268+test("move application rejects damaged cursor envelopes and invalid positions without mutation", () => {
269+ const db = new SqlState();
270+ try {
271+ const repo = Repo.init({ "a.txt": "one\ntwo\n" });
272+ const adapter = new ExperimentalMarkerProjection(db, repo.graph, "a.txt", "corrupt-move");
273+ const state = adapter.apply(adapter.empty(), repo.graph.atom("a0"));
274+ const identity = "e".repeat(64);
275+ adoptMovesStep(adapter, state, "job", identity);
276+ const saved = adapter.storage.read("move-adoption:job", "cursor") as {
277+ format: number;
278+ checksum: string;
279+ cursor: Record<string, unknown>;
280+ };
281+ const changes: Array<(record: typeof saved) => void> = [
282+ (row) => {
283+ row.checksum = "bad";
284+ },
285+ (row) => {
286+ row.format = 2;
287+ },
288+ (row) => {
289+ row.cursor.phase = "unknown";
290+ },
291+ (row) => {
292+ row.cursor.identity = "another";
293+ },
294+ (row) => {
295+ row.cursor.mover = 1;
296+ },
297+ (row) => {
298+ row.cursor.move = 1;
299+ },
300+ (row) => {
301+ row.cursor.count = repo.graph.lineCount + 1;
302+ },
303+ (row) => {
304+ row.cursor.item = 1;
305+ },
306+ (row) => {
307+ row.cursor.collection = 9;
308+ },
309+ (row) => {
310+ row.cursor.extra = true;
311+ },
312+ ];
313+ for (const [index, change] of changes.entries()) {
314+ const bad = structuredClone(saved);
315+ change(bad);
316+ if (index > 0) bad.checksum = createHash("sha256").update(JSON.stringify(bad.cursor)).digest("hex");
317+ adapter.storage.write("move-adoption:job", "cursor", bad);
318+ const before = db.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
319+ assert.throws(() => adoptMovesStep(adapter, state, "job", identity), /invalid|damaged/);
320+ assert.deepEqual(db.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before);
321+ }
322+ adapter.storage.write("move-adoption:job", "cursor", saved);
323+ assert.equal(adoptMovesStep(adapter, state, "job", identity).done, false);
324+ } finally {
325+ db.db.close();
326+ }
327+});
--- a/src/engine/test/projection-marker-cycle.test.ts
+++ b/src/engine/test/projection-marker-cycle.test.ts
@@ -1,83 +1,106 @@
11import assert from "node:assert/strict";
22import { test } from "node:test";
3+import { ProjectionAtomAdoption } from "../experimental/projection-atom-adoption.ts";
34import { ExperimentalMarkerProjection as MarkerProjection } from "../experimental/projection-marker.ts";
45import { Graph } from "../graph.ts";
56import { CachedStateStorage } from "../state-source.ts";
7+import type { Atom } from "../types.ts";
68import { Repo, Rng } from "./helpers.ts";
79import { SqlState } from "./storage-helper.ts";
9−test("typed marker projection matches competing cyclic moves and removals", () => {
10− const db = new SqlState();
11− try {
12− const repo = Repo.init({ "f.txt": Array.from({ length: 12 }, (_, n) => `${n}\n`).join("") }),
13− graph = new Graph({ storage: new CachedStateStorage(db) }),
14− rng = new Rng(45131);
15− graph.add(repo.graph.atom("a0"));
16− const p = new MarkerProjection(db, graph, "f.txt", "typed-" + "cycle");
17− let state = p.apply(p.empty(), repo.graph.atom("a0")),
18− checks = 0;
19− const atoms = [];
20− const check = () => {
21− const view = repo.view();
22− assert.deepEqual(
23− p.lines(state),
24− view.lines("f.txt").map((x) => x.id),
25− );
26− for (let n = 0; n < 12; n++) {
27− const parent = view.parentOf(`a0.${n}`);
28− assert.equal(
29− (p.markers.get(state.locator, n + 1) as { parentKey: number }).parentKey,
30− parent.startsWith("^") ? 0 : graph.lineN(parent) + 1,
11+for (const paged of [false, true])
12+ test(`typed marker projection matches competing cyclic moves and removals (paged=${paged})`, () => {
13+ const db = new SqlState();
14+ try {
15+ const repo = Repo.init({ "f.txt": Array.from({ length: 12 }, (_, n) => `${n}\n`).join("") }),
16+ graph = new Graph({ storage: new CachedStateStorage(db) }),
17+ rng = new Rng(45131);
18+ graph.add(repo.graph.atom("a0"));
19+ const p = new MarkerProjection(db, graph, "f.txt", "typed-" + "cycle");
20+ let state = p.apply(p.empty(), repo.graph.atom("a0")),
21+ checks = 0;
22+ const atoms = [];
23+ let task = 0;
24+ const apply = (atom: Atom, remove: boolean) => {
25+ if (!paged) return remove ? p.removeAtom(state, atom) : p.apply(state, atom);
26+ const job = new ProjectionAtomAdoption(p, String(task++));
27+ const previous = state;
28+ for (let pages = 0; pages < 10000; pages++) {
29+ const result = job.page({
30+ previous,
31+ atom,
32+ remove,
33+ source: "c".repeat(64),
34+ maxSteps: 3,
35+ validateSource: () => {},
36+ });
37+ assert.ok(result.steps <= 3);
38+ assert.equal(result.atomicMoveWork, false);
39+ if (result.done) return result.state;
40+ }
41+ throw Error("move adoption did not finish");
42+ };
43+ const check = () => {
44+ const view = repo.view();
45+ assert.deepEqual(
46+ p.lines(state),
47+ view.lines("f.txt").map((x) => x.id),
3148 );
32− }
33− checks++;
34− };
35− for (let j = 0; j < 24; j++) {
36− const offset = rng.int(12),
37− moves = Array.from({ length: 3 }, (_, i) => {
38− const line = `a0.${(offset + i) % 12}`,
39− candidate = `a0.${rng.int(12)}`;
40− return { line, parent: candidate === line ? "^f.txt" : candidate };
41− });
42− const atom = {
43− id: repo.graph.nextId(),
44− seq: repo.graph.size,
45− author: "fixture",
46− message: "move",
47− time: j,
48− inserts: [],
49− deletes: [],
50− writes: moves.flatMap((m) => [`P:${m.line}`, `G:${m.parent}`]),
51− reads: [],
52− holds: [],
53− needs: [],
54− resolves: [],
55− reasons: [],
56− deps: ["a0"],
57− moves,
49+ for (let n = 0; n < 12; n++) {
50+ const parent = view.parentOf(`a0.${n}`);
51+ assert.equal(
52+ (p.markers.get(state.locator, n + 1) as { parentKey: number }).parentKey,
53+ parent.startsWith("^") ? 0 : graph.lineN(parent) + 1,
54+ );
55+ }
56+ checks++;
5857 };
59− repo.graph.add(atom);
60− repo.shared.add(atom.id);
61− graph.add(atom);
62− atoms.push(atom);
63− state = p.apply(state, atom);
64− check();
58+ for (let j = 0; j < 24; j++) {
59+ const offset = rng.int(12),
60+ moves = Array.from({ length: 3 }, (_, i) => {
61+ const line = `a0.${(offset + i) % 12}`,
62+ candidate = `a0.${rng.int(12)}`;
63+ return { line, parent: candidate === line ? "^f.txt" : candidate };
64+ });
65+ const atom = {
66+ id: repo.graph.nextId(),
67+ seq: repo.graph.size,
68+ author: "fixture",
69+ message: "move",
70+ time: j,
71+ inserts: [],
72+ deletes: [],
73+ writes: moves.flatMap((m) => [`P:${m.line}`, `G:${m.parent}`]),
74+ reads: [],
75+ holds: [],
76+ needs: [],
77+ resolves: [],
78+ reasons: [],
79+ deps: ["a0"],
80+ moves,
81+ };
82+ repo.graph.add(atom);
83+ repo.shared.add(atom.id);
84+ graph.add(atom);
85+ atoms.push(atom);
86+ state = apply(atom, false);
87+ check();
88+ }
89+ for (const atom of atoms.filter((_, i) => i % 2 === 0)) {
90+ repo.shared.delete(atom.id);
91+ state = apply(atom, true);
92+ check();
93+ }
94+ assert.equal(
95+ db.db
96+ .prepare(
97+ "SELECT count(*) AS n FROM state WHERE collection LIKE '%sequence-resolver:%' OR collection LIKE '%sequence-relocation-work:%' OR collection LIKE '%move-adoption:%'",
98+ )
99+ .get()!.n,
100+ 0,
101+ );
102+ assert.equal(checks, 36);
103+ } finally {
104+ db.db.close();
65105 }
66− for (const atom of atoms.filter((_, i) => i % 2 === 0)) {
67− repo.shared.delete(atom.id);
68− state = p.removeAtom(state, atom);
69− check();
70− }
71− assert.equal(
72− db.db
73− .prepare(
74− "SELECT count(*) AS n FROM state WHERE collection LIKE '%sequence-resolver:%' OR collection LIKE '%sequence-relocation-work:%'",
75− )
76− .get()!.n,
77− 0,
78− );
79− assert.equal(checks, 36);
80− } finally {
81− db.db.close();
82− }
83−});
106+ });
--- /dev/null
+++ b/src/engine/test/projection-move-resolution.test.ts
@@ -0,0 +1,136 @@
1+import assert from "node:assert/strict";
2+import { createHash } from "node:crypto";
3+import { test } from "node:test";
4+import { resolveMovesPage } from "../experimental/projection-move-resolution.ts";
5+import type { RelocationInfo } from "../graph.ts";
6+import { resolveScratchMoves } from "../relocation-scratch.ts";
7+import { Repo, Rng } from "./helpers.ts";
8+import { SqlState } from "./storage-helper.ts";
9+
10+test("one-step move pages preserve cycle resolution across competing and excluded moves", () => {
11+ const rng = new Rng(45131);
12+ let resolvedCycles = 0;
13+ for (let trial = 0; trial < 8; trial++) {
14+ const repo = Repo.init({ "f.txt": Array.from({ length: 12 }, (_, i) => `${i}\n`).join(""), "g.txt": "" });
15+ for (let j = 0; j < 12; j++) {
16+ const offset = rng.int(12);
17+ const moves = Array.from({ length: 3 }, (_, k) => {
18+ const line = `a0.${(offset + k) % 12}`,
19+ parent = `a0.${rng.int(12)}`;
20+ return { line, parent: parent === line ? "^g.txt" : parent };
21+ });
22+ const id = repo.graph.nextId();
23+ repo.graph.add({
24+ id,
25+ seq: repo.graph.size,
26+ author: "fixture",
27+ message: "move",
28+ time: j,
29+ inserts: [],
30+ deletes: [],
31+ writes: moves.flatMap((m) => [`P:${m.line}`, `G:${m.parent}`]),
32+ reads: [],
33+ holds: [],
34+ needs: [],
35+ resolves: [],
36+ reasons: [],
37+ deps: ["a0"],
38+ moves,
39+ });
40+ if ((j + trial) % 3) repo.shared.add(id);
41+ }
42+ const expected = new SqlState(),
43+ actual = new SqlState();
44+ try {
45+ const oracle = resolveScratchMoves(repo.graph, (id) => repo.shared.has(id), expected);
46+ let done = false,
47+ pages = 0;
48+ while (!done) {
49+ const before = actual.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
50+ actual.failWrite = actual.writes + 1;
51+ assert.throws(
52+ () => resolveMovesPage(repo.graph, (id) => repo.shared.has(id), actual, `trial-${trial}`, 1),
53+ /injected storage failure/,
54+ );
55+ assert.deepEqual(actual.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before);
56+ actual.failWrite = Infinity;
57+ const result = resolveMovesPage(repo.graph, (id) => repo.shared.has(id), actual, `trial-${trial}`, 1);
58+ assert.ok(result.steps <= 1);
59+ done = result.done;
60+ assert.ok(++pages < 10000);
61+ }
62+ for (let n = 0; n < 12; n++) {
63+ const line = `a0.${n}`,
64+ selected = actual.read("selected", line) as RelocationInfo | undefined;
65+ assert.deepEqual(selected, oracle.selected(line));
66+ assert.equal(selected?.parent ?? repo.graph.lineParent(line), oracle.parent(line));
67+ }
68+ resolvedCycles += [...actual.entries("ignored")].length;
69+ const rows = actual.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
70+ assert.throws(() => resolveMovesPage(repo.graph, () => true, actual, "changed", 1), /identity changed/);
71+ assert.deepEqual(actual.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), rows);
72+ } finally {
73+ expected.db.close();
74+ actual.db.close();
75+ }
76+ }
77+ assert.ok(resolvedCycles > 0, "the fixture must exercise cycle breaking");
78+});
80+test("damaged and structurally invalid move cursors refuse without changing stored state", () => {
81+ const repo = Repo.init({ "f.txt": "a\nb\n" });
82+ const storage = new SqlState();
83+ try {
84+ resolveMovesPage(repo.graph, () => true, storage, "source", 1);
85+ const valid = storage.read("progress", "cursor") as {
86+ format: number;
87+ checksum: string;
88+ state: Record<string, unknown>;
89+ };
90+ const changes: Array<(record: typeof valid) => void> = [
91+ (record) => {
92+ record.checksum = "damaged";
93+ },
94+ (record) => {
95+ record.format = 2;
96+ },
97+ (record) => {
98+ record.state.phase = "unknown";
99+ },
100+ (record) => {
101+ record.state.mover = 1;
102+ },
103+ (record) => {
104+ record.state.move = 1;
105+ },
106+ (record) => {
107+ record.state.item = 1;
108+ },
109+ (record) => {
110+ record.state.work = repo.graph.lineCount + 1;
111+ },
112+ (record) => {
113+ record.state.slow = 4;
114+ },
115+ (record) => {
116+ record.state.phase = "repick";
117+ },
118+ (record) => {
119+ record.state.extra = true;
120+ },
121+ ];
122+ for (const [index, change] of changes.entries()) {
123+ const damaged = structuredClone(valid);
124+ change(damaged);
125+ if (index > 0) damaged.checksum = createHash("sha256").update(JSON.stringify(damaged.state)).digest("hex");
126+ storage.write("progress", "cursor", damaged);
127+ const before = storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
128+ assert.throws(() => resolveMovesPage(repo.graph, () => true, storage, "source", 1), /invalid|damaged|incomplete/);
129+ assert.deepEqual(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before);
130+ }
131+ storage.write("progress", "cursor", valid);
132+ assert.equal(resolveMovesPage(repo.graph, () => true, storage, "source", 1).done, true);
133+ } finally {
134+ storage.db.close();
135+ }
136+});