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 149 --json
JSON
/christopher/abso-core/versions/149?format=json

Index atom metadata for resumable projection adoption

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

Version 148 · Files at version 149

11 files, 591 lines added, 67 removed.

--- a/src/engine/experimental/projection-atom-adoption.ts
+++ b/src/engine/experimental/projection-atom-adoption.ts
@@ -1,5 +1,6 @@
11import { createHash } from "node:crypto";
22import type { Atom } from "../types.ts";
3+import { ProjectionAtomDescriptor } from "./projection-atom-index.ts";
34import type { ExperimentalMarkerProjection, MarkerState } from "./projection-marker.ts";
45import { adoptMovesStep } from "./projection-move-adoption.ts";
56
@@ -81,7 +82,7 @@
8182 }
8283 page(input: {
8384 previous: MarkerState;
84− atom: Atom;
85+ atom: Atom | ProjectionAtomDescriptor;
8586 remove: boolean;
8687 source: string;
8788 maxSteps: number;
@@ -101,8 +102,36 @@
101102 )
102103 throw Error("invalid atom adoption page bounds");
103104 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");
105+ const indexed = atom instanceof ProjectionAtomDescriptor ? atom : undefined;
106+ const full = indexed ? undefined : (atom as Atom);
107+ const identity = digest([
108+ input.source,
109+ input.previous,
110+ indexed ? [indexed.id, indexed.seq, indexed.digest] : atom,
111+ input.remove,
112+ ]);
113+ if (indexed) {
114+ if (p.graph.idOfSeq(indexed.seq) !== indexed.id) throw Error("canonical adoption atom mismatch");
115+ } else if (digest(p.graph.atom(atom.id)) !== digest(full)) throw Error("canonical adoption atom mismatch");
116+ const inserts = indexed?.count("inserts") ?? full!.inserts.length;
117+ const run = (i: number) =>
118+ indexed
119+ ? indexed.item("inserts", i)
120+ : { file: full!.inserts[i]!.file, parent: full!.inserts[i]!.parent, lines: full!.inserts[i]!.lines.length };
121+ const deps = indexed?.count("deps") ?? full!.deps.length;
122+ const dependency = (i: number) => (indexed ? indexed.item("deps", i) : full!.deps[i]!);
123+ const deletes = indexed?.count("deletes") ?? full!.deletes.length;
124+ const deletion = (i: number) => (indexed ? indexed.item("deletes", i) : full!.deletes[i]!);
125+ const attrs = indexed?.count("attrs") ?? full!.attrs?.length ?? 0;
126+ const attribute = (i: number) => (indexed ? indexed.item("attrs", i) : full!.attrs![i]!);
127+ const moves = indexed?.count("moves") ?? full!.moves?.length ?? 0;
128+ const fullFiles = indexed ? undefined : p.graph.filesOf(atom.id);
129+ const files = indexed?.count("files") ?? fullFiles!.length;
130+ const file = (i: number) => (indexed ? indexed.item("files", i) : fullFiles![i]!);
131+ const seqOf = (id: string) => {
132+ if (!p.graph.has(id)) throw Error("missing dependency");
133+ return Number(id.slice(1));
134+ };
106135 const collection = `atom-adoption:${this.task}`;
107136 const validate = () => {
108137 const result: unknown = input.validateSource();
@@ -121,19 +150,19 @@
121150 )
122151 throw Error("invalid or changed atom adoption cursor");
123152 p.assertContext(cursor.state);
124− if (cursor.run > atom.inserts.length || cursor.line > (atom.inserts[cursor.run]?.lines.length ?? 0))
153+ if (cursor.run > inserts || cursor.line > (cursor.run < inserts ? run(cursor.run).lines : 0))
125154 throw Error("invalid atom adoption line position");
126155 const limits: Record<Phase, number> = {
127− dependencies: atom.deps.length,
128− files: atom.inserts.length + 1,
156+ dependencies: deps,
157+ files: inserts + 1,
129158 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,
159+ deletes: deletes,
160+ counts: deps,
161+ attributes: attrs,
162+ contributions: files,
134163 membership: 0,
135164 moves: 0,
136− cleanup: atom.attrs?.length ?? 0,
165+ cleanup: attrs,
137166 done: 0,
138167 };
139168 if (cursor.index > limits[cursor.phase]) throw Error("invalid atom adoption phase position");
@@ -158,35 +187,35 @@
158187 cursor!.index = 0;
159188 };
160189 const state = cursor.state;
161− const contributionFiles = p.graph.filesOf(atom.id);
162191 while (cursor.phase !== "done" && steps < input.maxSteps) {
163192 steps++;
164193 switch (cursor.phase) {
165194 case "dependencies": {
166− if (input.remove || cursor.index === atom.deps.length) {
195+ if (input.remove || cursor.index === deps) {
167196 next();
168197 break;
169198 }
170− const id = atom.deps[cursor.index++]!;
171− if (!p.members.get(state.membership, p.graph.atom(id).seq)?.present) throw Error("missing dependency");
199+ const id = dependency(cursor.index++);
200+ if (!p.members.get(state.membership, seqOf(id))?.present) throw Error("missing dependency");
172201 break;
173202 }
174203 case "files": {
175− if (input.remove || cursor.index > atom.inserts.length) {
204+ if (input.remove || cursor.index > inserts) {
176205 next();
177206 break;
178207 }
179− p.ensureFile(state, cursor.index === 0 ? p.path : atom.inserts[cursor.index - 1]!.file);
208+ p.ensureFile(state, cursor.index === 0 ? p.path : run(cursor.index - 1).file);
180209 cursor.index++;
181210 break;
182211 }
183212 case "lines": {
184− if (cursor.run === atom.inserts.length) {
213+ if (cursor.run === inserts) {
185214 next();
186215 break;
187216 }
188− const run = atom.inserts[cursor.run]!;
189− if (cursor.line === run.lines.length) {
217+ const currentRun = run(cursor.run);
218+ if (cursor.line === currentRun.lines) {
190219 cursor.run++;
191220 cursor.line = 0;
192221 break;
@@ -202,11 +231,11 @@
202231 break;
203232 }
204233 case "deletes": {
205− if (cursor.index === atom.deletes.length) {
234+ if (cursor.index === deletes) {
206235 next();
207236 break;
208237 }
209− const marker = p.markers.get(state.locator, p.graph.lineN(atom.deletes[cursor.index++]!) + 1);
238+ const marker = p.markers.get(state.locator, p.graph.lineN(deletion(cursor.index++)) + 1);
210239 if (!marker) throw Error("missing deleted marker");
211240 state.sequence = p.sequence.update(state.sequence, {
212241 kind: "visibility",
@@ -216,11 +245,11 @@
216245 break;
217246 }
218247 case "counts": {
219− if (cursor.index === atom.deps.length) {
248+ if (cursor.index === deps) {
220249 next();
221250 break;
222251 }
223− const seq = p.graph.atom(atom.deps[cursor.index++]!).seq;
252+ const seq = seqOf(dependency(cursor.index++));
224253 const member = p.members.get(state.membership, seq);
225254 if (!member?.present || (input.remove && member.dependents < 1)) throw Error("invalid dependency count");
226255 state.membership = p.members.set(state.membership, seq, {
@@ -230,25 +259,24 @@
230259 break;
231260 }
232261 case "attributes": {
233− const attrs = atom.attrs ?? [];
234− if (cursor.index === attrs.length) {
262+ if (cursor.index === attrs) {
235263 next();
236264 break;
237265 }
238− const attr = attrs[cursor.index++]!;
266+ const attr = attribute(cursor.index++);
239267 const key = JSON.stringify([attr.file, attr.name]);
240268 if (!p.storage.read(`${collection}:attributes`, key)) {
241− p.updateAttributes(state, { ...atom, attrs: [attr] }, !input.remove);
269+ p.updateAttributes(state, { seq: atom.seq, attrs: [attr] }, !input.remove);
242270 p.storage.write(`${collection}:attributes`, key, true);
243271 }
244272 break;
245273 }
246274 case "contributions": {
247− if (cursor.index === contributionFiles.length) {
275+ if (cursor.index === files) {
248276 next();
249277 break;
250278 }
251− const path = contributionFiles[cursor.index++]!;
279+ const path = file(cursor.index++);
252280 p.ensureFile(state, path);
253281 const key = p.fileKey(path)!;
254282 const marker = p.markers.get(state.locator, key);
@@ -266,20 +294,33 @@
266294 next();
267295 break;
268296 case "moves":
269− if (atom.moves?.length) {
270− const result = adoptMovesStep(p, state, this.task, identity);
297+ if (moves) {
298+ const result = adoptMovesStep(
299+ p,
300+ state,
301+ this.task,
302+ identity,
303+ indexed
304+ ? {
305+ count: (id) => indexed.related(id).count("moves"),
306+ at: (id, k) => {
307+ const atom = indexed.related(id);
308+ return k < atom.count("moves") ? atom.item("moves", k) : undefined;
309+ },
310+ }
311+ : undefined,
312+ );
271313 Object.assign(state, result.state);
272314 if (!result.done) break;
273315 }
274316 next();
275317 break;
276318 case "cleanup": {
277− const attrs = atom.attrs ?? [];
278− if (cursor.index === attrs.length) {
319+ if (cursor.index === attrs) {
279320 next();
280321 break;
281322 }
282− const attr = attrs[cursor.index++]!;
323+ const attr = attribute(cursor.index++);
283324 p.storage.remove(`${collection}:attributes`, JSON.stringify([attr.file, attr.name]));
284325 break;
285326 }
--- /dev/null
+++ b/src/engine/experimental/projection-atom-index.ts
@@ -0,0 +1,177 @@
1+import { createHash } from "node:crypto";
2+import type { GraphStateStorage } from "../state-source.ts";
3+import type { Atom, AttrSet, Relocation } from "../types.ts";
4+
5+type Field = "deps" | "inserts" | "deletes" | "attrs" | "moves" | "files";
6+interface Run {
7+ file: string;
8+ parent: string;
9+ lines: number;
10+}
11+interface Header {
12+ format: 1;
13+ id: string;
14+ seq: number;
15+ digest: string;
16+ counts: Record<Field, number>;
17+ checksum: string;
18+}
19+const fields: Field[] = ["deps", "inserts", "deletes", "attrs", "moves", "files"];
21+// Checksums detect record damage; authority comes from the canonical writer transaction.
22+const checksum = (value: unknown): string => createHash("sha256").update(JSON.stringify(value)).digest("hex");
23+const headerChecksum = (header: Omit<Header, "checksum">): string =>
24+ checksum([header.format, header.id, header.seq, header.digest, fields.map((field) => header.counts[field])]);
26+function shape(value: unknown, keys: readonly string[]): asserts value is Record<string, unknown> {
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 projection atom record");
35+}
36+const integer = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
37+const atomId = (value: unknown): value is string =>
38+ typeof value === "string" && /^a(0|[1-9][0-9]*)$/.test(value) && integer(Number(value.slice(1)));
39+const lineId = (value: unknown): value is string =>
40+ typeof value === "string" &&
41+ /^a(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(value) &&
42+ value.split(".").every((part, i) => integer(Number(i === 0 ? part.slice(1) : part)));
43+const parent = (value: unknown) => typeof value === "string" && (value.startsWith("^") || lineId(value));
44+function itemValue(field: Field, value: unknown): unknown {
45+ if (field === "deps" || field === "deletes" || field === "files") {
46+ if (!(field === "deps" ? atomId(value) : field === "deletes" ? lineId(value) : typeof value === "string"))
47+ throw Error("invalid projection atom item");
48+ } else if (field === "inserts") {
49+ shape(value, ["file", "parent", "lines"]);
50+ if (typeof value.file !== "string" || !parent(value.parent) || !integer(value.lines))
51+ throw Error("invalid projection atom run");
52+ } else if (field === "moves") {
53+ shape(value, ["line", "parent"]);
54+ if (!lineId(value.line) || !parent(value.parent)) throw Error("invalid projection atom move");
55+ } else {
56+ shape(value, ["file", "name", "value"]);
57+ if (
58+ typeof value.file !== "string" ||
59+ !["exists", "exec", "link", "blob"].includes(String(value.name)) ||
60+ (value.value !== null && typeof value.value !== "string")
61+ )
62+ throw Error("invalid projection atom attribute");
63+ }
64+ return structuredClone(value);
65+}
67+/** Derived index only. The caller supplies an already validated canonical atom and
68+ * its digest inside the canonical indexing transaction. This builder does not
69+ * claim bounded decoding of the original atom. */
70+export class ProjectionAtomIndex {
71+ readonly storage: GraphStateStorage;
72+ constructor(storage: GraphStateStorage) {
73+ this.storage = storage;
74+ }
75+ put(atom: Atom, digest: string, files: readonly string[]): void {
76+ if (!/^[a-f0-9]{64}$/.test(digest) || !Number.isSafeInteger(atom.seq) || atom.seq < 0 || atom.id !== `a${atom.seq}`)
77+ throw Error("invalid projection atom identity");
78+ const name = `projection-atom-index:${atom.id}`;
79+ this.storage.transaction(() => {
80+ if (this.storage.read(name, "header") !== undefined) throw Error("projection atom index already exists");
81+ const counts = {} as Record<Field, number>;
82+ for (const field of fields) {
83+ const values = field === "files" ? files : (atom[field] ?? []);
84+ counts[field] = values.length;
85+ for (let i = 0; i < values.length; i++) {
86+ const value =
87+ field === "inserts"
88+ ? { file: atom.inserts[i]!.file, parent: atom.inserts[i]!.parent, lines: atom.inserts[i]!.lines.length }
89+ : values[i];
90+ const item = itemValue(field, value);
91+ this.storage.write(name, `${field}:${i}`, {
92+ value: item,
93+ checksum: checksum([atom.id, digest, field, i, item]),
94+ });
95+ }
96+ }
97+ const header = { format: 1 as const, id: atom.id, seq: atom.seq, digest, counts };
98+ this.storage.write(name, "header", { ...header, checksum: headerChecksum(header) } satisfies Header);
99+ });
100+ }
101+ /** Read a descriptor from a source-fenced, atomically maintained writer index. */
102+ openAccepted(id: string): ProjectionAtomDescriptor {
103+ if (!atomId(id)) throw Error("invalid projection atom identity");
104+ const header = this.storage.read(`projection-atom-index:${id}`, "header");
105+ shape(header, ["format", "id", "seq", "digest", "counts", "checksum"]);
106+ if (typeof header.digest !== "string") throw Error("invalid projection atom digest");
107+ return this.open(id, header.digest);
108+ }
110+ open(id: string, digest: string): ProjectionAtomDescriptor {
111+ if (!/^a(0|[1-9][0-9]*)$/.test(id) || !/^[a-f0-9]{64}$/.test(digest))
112+ throw Error("invalid projection atom identity");
113+ const name = `projection-atom-index:${id}`;
114+ const raw = this.storage.read(name, "header");
115+ shape(raw, ["format", "id", "seq", "digest", "counts", "checksum"]);
116+ shape(raw.counts, fields);
117+ const header = raw as unknown as Header;
118+ if (
119+ header.checksum !== headerChecksum(header) ||
120+ header.format !== 1 ||
121+ header.id !== id ||
122+ header.digest !== digest ||
123+ !Number.isSafeInteger(header.seq) ||
124+ header.seq < 0 ||
125+ id !== `a${header.seq}` ||
126+ !header.counts ||
127+ Object.keys(header.counts).length !== fields.length ||
128+ fields.some((field) => !Number.isSafeInteger(header.counts[field]) || header.counts[field] < 0)
129+ )
130+ throw Error("missing or invalid projection atom index");
131+ return new ProjectionAtomDescriptor(this.storage, name, structuredClone(header));
132+ }
133+}
134+export class ProjectionAtomDescriptor {
135+ readonly id: string;
136+ readonly seq: number;
137+ readonly digest: string;
138+ readonly #storage: GraphStateStorage;
139+ readonly #name: string;
140+ readonly #counts: Record<Field, number>;
141+ constructor(storage: GraphStateStorage, name: string, header: Header) {
142+ this.#storage = storage;
143+ this.#name = name;
144+ this.id = header.id;
145+ this.seq = header.seq;
146+ this.digest = header.digest;
147+ this.#counts = { ...header.counts };
148+ }
149+ related(id: string): ProjectionAtomDescriptor {
150+ return new ProjectionAtomIndex(this.#storage).openAccepted(id);
151+ }
153+ count(field: Field): number {
154+ if (!fields.includes(field)) throw Error("invalid projection atom field");
155+ return this.#counts[field];
156+ }
157+ item(field: "inserts", index: number): Run;
158+ item(field: "attrs", index: number): AttrSet;
159+ item(field: "moves", index: number): Relocation;
160+ item(field: "deps" | "deletes" | "files", index: number): string;
161+ item(field: Field, index: number): unknown {
162+ if (!Number.isSafeInteger(index) || index < 0 || index >= this.count(field))
163+ throw Error("projection atom item out of range");
164+ const value = this.#storage.read(this.#name, `${field}:${index}`);
165+ if (value === undefined) throw Error("missing projection atom item");
166+ shape(value, ["value", "checksum"]);
167+ if (value.checksum !== checksum([this.id, this.digest, field, index, value.value]))
168+ throw Error("invalid projection atom item checksum");
169+ return itemValue(field, value.value);
170+ }
171+}
173+/** Opt-in persistent Graph callback: indexes the just-accepted canonical atom. */
174+export function indexAcceptedProjectionAtom(atom: Atom, files: readonly string[], storage: GraphStateStorage): void {
175+ const digest = createHash("sha256").update(JSON.stringify(atom)).digest("hex");
176+ new ProjectionAtomIndex(storage).put(atom, digest, files);
177+}
--- a/src/engine/experimental/projection-marker.ts
+++ b/src/engine/experimental/projection-marker.ts
@@ -380,7 +380,7 @@
380380 }
381381 return paths.sort();
382382 }
383− updateAttributes(state: MarkerState, atom: Atom, adding: boolean): void {
383+ updateAttributes(state: MarkerState, atom: Pick<Atom, "seq" | "attrs">, adding: boolean): void {
384384 this.assertContext(state);
385385 const index = this.attributePriorities,
386386 hex = (n: number) => n.toString(16).padStart(14, "0");
--- a/src/engine/experimental/projection-move-adoption.ts
+++ b/src/engine/experimental/projection-move-adoption.ts
@@ -3,7 +3,7 @@
33import { orderedChildKey } from "../ordered-index.ts";
44import type { GraphStateStorage } from "../state-source.ts";
55import type { ExperimentalMarkerProjection, MarkerState } from "./projection-marker.ts";
6−import { resolveMovesPage } from "./projection-move-resolution.ts";
6+import { graphMoveSource, type ProjectionMoveSource, resolveMovesPage } from "./projection-move-resolution.ts";
77
88type Phase = "files" | "resolve" | "plans" | "park" | "place" | "cleanup" | "done";
99interface Cursor {
@@ -41,6 +41,7 @@
4141 previous: MarkerState,
4242 task: string,
4343 identity: string,
44+ source: ProjectionMoveSource = graphMoveSource(p.graph),
4445): { done: boolean; state: MarkerState } {
4546 p.assertContext(previous);
4647 if (!task || task.length > 128 || !/^[a-f0-9]{64}$/.test(identity)) throw Error("invalid move adoption identity");
@@ -83,10 +84,9 @@
8384 )
8485 throw Error("invalid move adoption cursor");
8586 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");
87+ if (cursor.move > (mover === undefined ? 0 : source.count(mover))) throw Error("invalid move adoption offset");
8888 let state = { ...previous };
89− const has = (id: string) => p.members.get(state.membership, p.graph.atom(id).seq)?.present ?? false;
89+ const has = (id: string) => p.members.get(state.membership, Number(id.slice(1)))?.present ?? false;
9090 switch (cursor.phase) {
9191 case "files":
9292 case "plans": {
@@ -96,14 +96,16 @@
9696 cursor.move = 0;
9797 break;
9898 }
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) {
99+ const moverId = p.graph.movers()[cursor.mover]!;
100+ const count = source.count(moverId);
101+ if (cursor.move > count) throw Error("invalid move adoption offset");
102+ if (cursor.move === count) {
102103 cursor.mover++;
103104 cursor.move = 0;
104105 break;
105106 }
106− const move = moves[cursor.move++]!;
107+ const move = source.at(moverId, cursor.move++);
108+ if (!move) throw Error("missing indexed move");
107109 if (cursor.phase === "files") {
108110 if (move.parent.startsWith("^")) p.ensureFile(state, move.parent.slice(1));
109111 break;
@@ -119,7 +121,7 @@
119121 if (parent === undefined) throw Error("missing relocation ancestry");
120122 const parentKey = parent.startsWith("^") ? p.fileKey(parent.slice(1)) : p.graph.lineN(parent) + 1;
121123 if (parentKey === undefined) throw Error("missing relocation file");
122− const seq = selected ? p.graph.atom(selected.atom).seq : p.graph.writerSeqOf(n);
124+ const seq = selected ? Number(selected.atom.slice(1)) : p.graph.writerSeqOf(n);
123125 const key = orderedChildKey({
124126 n,
125127 replaces: selected ? 0 : Number(p.graph.replacesN(n)),
@@ -132,7 +134,7 @@
132134 break;
133135 }
134136 case "resolve":
135− if (resolveMovesPage(p.graph, has, scratch, identity, 1).done) cursor.phase = "plans";
137+ if (resolveMovesPage(p.graph, has, scratch, identity, 1, source).done) cursor.phase = "plans";
136138 break;
137139 case "park":
138140 case "place": {
--- a/src/engine/experimental/projection-move-resolution.ts
+++ b/src/engine/experimental/projection-move-resolution.ts
@@ -2,8 +2,16 @@
22import type { Graph, RelocationInfo } from "../graph.ts";
33import { isStartNode } from "../keys.ts";
44import type { GraphStateStorage } from "../state-source.ts";
5−import type { NodeId } from "../types.ts";
5+import type { NodeId, Relocation } from "../types.ts";
66
7+export interface ProjectionMoveSource {
8+ count(id: string): number;
9+ at(id: string, k: number): Relocation | undefined;
10+}
11+export function graphMoveSource(graph: Graph): ProjectionMoveSource {
12+ return { count: (id) => graph.atom(id).moves?.length ?? 0, at: (id, k) => graph.atom(id).moves?.[k] };
13+}
715interface Progress {
816 identity: string;
917 phase: "scan" | "walk" | "entry" | "weakest" | "repick" | "mark" | "done";
@@ -33,7 +41,7 @@
3341 )
3442 throw Error("invalid move resolution record");
3543}
36−function readProgress(value: unknown, graph: Graph): Progress | undefined {
44+function readProgress(value: unknown, graph: Graph, source: ProjectionMoveSource): Progress | undefined {
3745 if (value === undefined) return undefined;
3846 shape(value, "format checksum state");
3947 if (value.format !== 1 || value.checksum !== digest(value.state)) throw Error("damaged move resolution cursor");
@@ -51,8 +59,7 @@
5159 )
5260 throw Error("invalid move resolution position");
5361 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");
62+ if (Number(state.move) > (mover === undefined ? 0 : source.count(mover))) throw Error("invalid move offset");
5663 for (const key of ["line", "slow", "fast", "meeting", "entry", "current"])
5764 if (state[key] !== null && (typeof state[key] !== "string" || !state[key] || String(state[key]).length > 4096))
5865 throw Error("invalid move ancestry cursor");
@@ -61,7 +68,7 @@
6168 if (move === null) continue;
6269 shape(move, "atom line parent k");
6370 if (typeof move.atom !== "string" || !integer(move.k)) throw Error("invalid saved move");
64− const canonical = graph.atom(move.atom).moves?.[move.k];
71+ const canonical = source.at(move.atom, move.k);
6572 if (!canonical || canonical.line !== move.line || canonical.parent !== move.parent)
6673 throw Error("saved move identity mismatch");
6774 }
@@ -83,11 +90,12 @@
8390 storage: GraphStateStorage,
8491 identity: string,
8592 maxSteps: number,
93+ source: ProjectionMoveSource = graphMoveSource(graph),
8694): { done: boolean; steps: number } {
8795 if (!identity || identity.length > 4096 || !Number.isSafeInteger(maxSteps) || maxSteps < 1 || maxSteps > 256)
8896 throw Error("invalid move resolution page");
8997 return storage.transaction(() => {
90− let state = readProgress(storage.read("progress", "cursor"), graph);
98+ let state = readProgress(storage.read("progress", "cursor"), graph, source);
9199 if (state && state.identity !== identity) throw Error("move resolution identity changed");
92100 state ??= {
93101 identity,
@@ -144,14 +152,16 @@
144152 state.move = 0;
145153 break;
146154 }
147− const moves = graph.atom(id).moves ?? [];
148− if (state.move === moves.length) {
155+ const count = source.count(id);
156+ if (state.move === count) {
149157 state.mover++;
150158 state.move = 0;
151159 break;
152160 }
153161 const k = state.move++;
154− const candidate: RelocationInfo = { atom: id, ...moves[k]!, k };
162+ const move = source.at(id, k);
163+ if (!move) throw Error("missing indexed move");
164+ const candidate: RelocationInfo = { atom: id, ...move, k };
155165 if (state.phase === "scan") {
156166 if (!storage.read("seen", candidate.line)) {
157167 storage.write("seen", candidate.line, true);
--- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -277,6 +277,8 @@
277277 #textCache = new Map<number, readonly string[]>();
278278 #textCached = 0;
279279
280+ readonly #indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
280282 /**
281283 * `texts`, when given, says where each atom's lines' text can be read back
282284 * (#46): the graph then keeps no text, only each line's place, and reads an
@@ -287,8 +289,13 @@
287289 texts?: (seq: number) => readonly (readonly string[])[];
288290 lists?: (seq: number) => AtomLists;
289291 storage?: GraphStateStorage;
292+ /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */
293+ indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
290294 } = {},
291295 ) {
296+ if (options.indexAcceptedAtom && !options.storage)
297+ throw Error("accepted atom indexing requires persistent storage");
298+ this.#indexAcceptedAtom = options.indexAcceptedAtom;
292299 if (options.texts) {
293300 this.#texts = options.texts;
294301 this.#lineText = undefined;
@@ -994,7 +1001,13 @@
9941001 * The atom is frozen. Adding to the graph does not add it to any set.
9951002 */
9961003 add(atom: Atom): void {
997− if (this.#storage) this.#storage.transaction(() => this.#add(atom));
1004+ if (this.#storage)
1005+ this.#storage.transaction(() => {
1006+ this.#add(atom);
1007+ const result: unknown = this.#indexAcceptedAtom?.(atom, this.filesOf(atom.id), this.#storage!);
1008+ if (result && typeof result === "object" && "then" in result)
1009+ throw Error("accepted atom indexing must be synchronous");
1010+ });
9981011 else this.#add(atom);
9991012 }
10001013
--- /dev/null
+++ b/src/engine/test/projection-atom-index.test.ts
@@ -0,0 +1,227 @@
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 { indexAcceptedProjectionAtom, ProjectionAtomIndex } from "../experimental/projection-atom-index.ts";
9+import { ExperimentalMarkerProjection } from "../experimental/projection-marker.ts";
10+import { Graph } from "../graph.ts";
11+import { Repo } from "./helpers.ts";
12+import { SqlState } from "./storage-helper.ts";
14+test("projection atom descriptors exclude inserted text and read one indexed item", () => {
15+ const db = new SqlState();
16+ try {
17+ const repo = Repo.init({ "a.txt": "large text\n".repeat(1000) });
18+ const atom = repo.graph.atom("a0"),
19+ digest = "a".repeat(64);
20+ new ProjectionAtomIndex(db).put(atom, digest, ["a.txt"]);
21+ const descriptor = new ProjectionAtomIndex(db).open("a0", digest);
22+ const before = db.reads;
23+ assert.equal(descriptor.count("inserts"), 1);
24+ assert.deepEqual(descriptor.item("inserts", 0), { file: "a.txt", parent: "^a.txt", lines: 1000 });
25+ assert.equal(db.reads - before, 1);
26+ assert.throws(() => descriptor.item("inserts", 1), /out of range/);
27+ assert.throws(() => new ProjectionAtomIndex(db).open("a0", "b".repeat(64)), /invalid/);
28+ const rows = db.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
29+ assert.ok(!JSON.stringify(rows).includes("large text"));
30+ assert.throws(() => new ProjectionAtomIndex(db).put(atom, digest, ["a.txt"]), /already exists/);
31+ assert.deepEqual(db.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), rows);
32+ } finally {
33+ db.db.close();
34+ }
35+});
37+test("descriptor builds roll back every write and corrupted records refuse", () => {
38+ const db = new SqlState();
39+ try {
40+ const repo = Repo.init({ "a.txt": "one\n" });
41+ const atom = repo.graph.atom("a0"),
42+ digest = "c".repeat(64);
43+ const index = new ProjectionAtomIndex(db);
44+ const writeCount =
45+ atom.deps.length +
46+ atom.inserts.length +
47+ atom.deletes.length +
48+ (atom.attrs?.length ?? 0) +
49+ (atom.moves?.length ?? 0) +
50+ 2;
51+ for (let offset = 1; offset <= writeCount; offset++) {
52+ db.failWrite = db.writes + offset;
53+ assert.throws(() => index.put(atom, digest, ["a.txt"]), /injected/);
54+ assert.deepEqual(db.db.prepare("SELECT * FROM state").all(), []);
55+ }
56+ db.failWrite = Infinity;
57+ index.put(atom, digest, ["a.txt"]);
58+ const name = "projection-atom-index:a0";
59+ const header = db.read(name, "header") as { counts: Record<string, number> };
60+ for (const invalid of [
61+ null,
62+ { ...header, extra: true },
63+ { ...header, counts: { ...header.counts, moves: -1 } },
64+ { ...header, counts: [] },
65+ { ...header, counts: { ...header.counts, inserts: 0 } },
66+ ]) {
67+ db.write(name, "header", invalid);
68+ assert.throws(() => new ProjectionAtomIndex(db).open("a0", digest), /invalid/);
69+ }
70+ db.write(name, "header", header);
71+ const descriptor = new ProjectionAtomIndex(db).open("a0", digest);
72+ const original = db.read(name, "inserts:0") as { value: unknown; checksum: string };
73+ for (const invalid of [
74+ null,
75+ { file: "a.txt", parent: "bad", lines: 1 },
76+ { file: "a.txt", parent: "^a.txt", lines: -1 },
77+ { file: "a.txt", parent: "^a.txt", lines: 1, extra: true },
78+ { ...original, value: { file: "a.txt", parent: "^a.txt", lines: 2 } },
79+ ]) {
80+ db.write(name, "inserts:0", invalid);
81+ assert.throws(() => descriptor.item("inserts", 0), /invalid/);
82+ }
83+ db.write(name, "inserts:0", original);
84+ const run = descriptor.item("inserts", 0);
85+ run.lines = 999;
86+ assert.equal(descriptor.item("inserts", 0).lines, 1);
87+ } finally {
88+ db.db.close();
89+ }
90+});
92+test("descriptor-driven insertion adoption never reads full atom storage", () => {
93+ const db = new SqlState();
94+ try {
95+ const repo = Repo.init({ "a.txt": "one\ntwo\nthree\n" });
96+ const atom = repo.graph.atom("a0"),
97+ digest = "d".repeat(64);
98+ const graph = new Graph({ storage: db });
99+ graph.add(atom);
100+ new ProjectionAtomIndex(db).put(atom, digest, graph.filesOf(atom.id));
101+ const projection = new ExperimentalMarkerProjection(db, graph, "a.txt", "indexed-adoption");
102+ const previous = projection.empty();
103+ const read = db.read.bind(db);
104+ db.read = (collection, key) => {
105+ if (collection === "atoms") throw Error("full atom read forbidden");
106+ return read(collection, key);
107+ };
108+ let pages = 0;
109+ for (;;) {
110+ const descriptor = new ProjectionAtomIndex(db).open(atom.id, digest);
111+ const result = new ProjectionAtomAdoption(projection, "indexed").page({
112+ previous,
113+ atom: descriptor,
114+ remove: false,
115+ source: "e".repeat(64),
116+ maxSteps: 2,
117+ validateSource: () => {},
118+ });
119+ assert.ok(result.steps <= 2);
120+ assert.ok(++pages < 100);
121+ if (result.done) {
122+ assert.deepEqual(projection.lines(result.state), ["a0.0", "a0.1", "a0.2"]);
123+ break;
124+ }
125+ }
126+ assert.ok(pages > 1);
127+ } finally {
128+ db.db.close();
129+ }
130+});
132+test("indexed adoption reopens through dependencies, attributes, deletion and reverse removal without atom reads", () => {
133+ const directory = mkdtempSync(join(tmpdir(), "abso-descriptor-")),
134+ filename = join(directory, "state.sqlite");
135+ let db = new SqlState(filename);
136+ const oracleDb = new SqlState();
137+ try {
138+ const repo = Repo.init({ "a.txt": "one\ntwo\nthree\n", "b.txt": "" });
139+ const atoms = [
140+ repo.graph.atom("a0"),
141+ repo.edit({
142+ edits: [{ file: "a.txt", old: "two\n", new: "replacement\n" }],
143+ attrs: [{ file: "b.txt", name: "exec", value: "1" }],
144+ }),
145+ ];
146+ atoms.push(repo.edit({ move: { file: "a.txt", start: 0, end: 1, to: "b.txt", at: 0 } }));
147+ const graph = new Graph({ storage: db });
148+ for (const atom of atoms) {
149+ graph.add(atom);
150+ new ProjectionAtomIndex(db).put(atom, "a".repeat(64), graph.filesOf(atom.id));
151+ }
152+ const oracle = new ExperimentalMarkerProjection(oracleDb, repo.graph, "a.txt", "oracle");
153+ let expected = oracle.empty();
154+ let state = new ExperimentalMarkerProjection(db, graph, "a.txt", "indexed").empty();
155+ let task = 0;
156+ for (const [atom, remove] of [
157+ ...atoms.map((atom) => [atom, false] as const),
158+ ...atoms.toReversed().map((atom) => [atom, true] as const),
159+ ]) {
160+ const previous = state,
161+ id = String(task++);
162+ let pages = 0,
163+ done = false;
164+ while (!done) {
165+ const read = db.read.bind(db);
166+ db.read = (collection, key) => {
167+ if (collection === "atoms") throw Error("full atom read forbidden");
168+ return read(collection, key);
169+ };
170+ const p = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "indexed");
171+ const descriptor = new ProjectionAtomIndex(db).open(atom.id, "a".repeat(64));
172+ const result = new ProjectionAtomAdoption(p, id).page({
173+ previous,
174+ atom: descriptor,
175+ remove,
176+ source: "b".repeat(64),
177+ maxSteps: 2,
178+ validateSource: () => {},
179+ });
180+ state = result.state;
181+ done = result.done;
182+ assert.ok(++pages < 100);
183+ db.db.close();
184+ db = new SqlState(filename);
185+ }
186+ expected = remove ? oracle.removeAtom(expected, atom) : oracle.apply(expected, atom);
187+ const actual = new ExperimentalMarkerProjection(db, new Graph({ storage: db }), "a.txt", "indexed");
188+ for (const path of ["a.txt", "b.txt"]) {
189+ assert.deepEqual(actual.lines(state, path), oracle.lines(expected, path));
190+ assert.deepEqual(actual.attrs(state, path), oracle.attrs(expected, path));
191+ }
192+ assert.deepEqual(actual.knownPaths(state), oracle.knownPaths(expected));
193+ }
194+ } finally {
195+ db.db.close();
196+ oracleDb.db.close();
197+ unlinkSync(filename);
198+ rmdirSync(directory);
199+ }
200+});
202+test("accepted graph and descriptor commit together and retry after callback failure", () => {
203+ const db = new SqlState();
204+ try {
205+ const atom = Repo.init({ "a.txt": "one\n" }).graph.atom("a0");
206+ let fail = true;
207+ const graph = new Graph({
208+ storage: db,
209+ indexAcceptedAtom: (accepted, files, storage) => {
210+ indexAcceptedProjectionAtom(accepted, files, storage);
211+ if (fail) throw Error("after descriptor failure");
212+ },
213+ });
214+ const before = db.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
215+ assert.throws(() => graph.add(atom), /after descriptor failure/);
216+ assert.deepEqual(db.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), before);
217+ assert.equal(graph.size, 0);
218+ fail = false;
219+ graph.add(atom);
220+ const digest = createHash("sha256").update(JSON.stringify(atom)).digest("hex");
221+ assert.equal(new ProjectionAtomIndex(db).open("a0", digest).item("inserts", 0).lines, 1);
222+ assert.equal(new Graph({ storage: db }).size, 1);
223+ assert.throws(() => new Graph({ indexAcceptedAtom: indexAcceptedProjectionAtom }), /requires persistent/);
224+ } finally {
225+ db.db.close();
226+ }
227+});
--- a/src/engine/test/projection-marker-cycle.test.ts
+++ b/src/engine/test/projection-marker-cycle.test.ts
@@ -1,6 +1,7 @@
11import assert from "node:assert/strict";
22import { test } from "node:test";
33import { ProjectionAtomAdoption } from "../experimental/projection-atom-adoption.ts";
4+import { indexAcceptedProjectionAtom, ProjectionAtomIndex } from "../experimental/projection-atom-index.ts";
45import { ExperimentalMarkerProjection as MarkerProjection } from "../experimental/projection-marker.ts";
56import { Graph } from "../graph.ts";
67import { CachedStateStorage } from "../state-source.ts";
@@ -8,12 +9,15 @@
89import { Repo, Rng } from "./helpers.ts";
910import { SqlState } from "./storage-helper.ts";
1011
11−for (const paged of [false, true])
12+for (const paged of [false, true, "indexed"] as const)
1213 test(`typed marker projection matches competing cyclic moves and removals (paged=${paged})`, () => {
1314 const db = new SqlState();
1415 try {
1516 const repo = Repo.init({ "f.txt": Array.from({ length: 12 }, (_, n) => `${n}\n`).join("") }),
16− graph = new Graph({ storage: new CachedStateStorage(db) }),
17+ graph = new Graph({
18+ storage: new CachedStateStorage(db),
19+ indexAcceptedAtom: paged === "indexed" ? indexAcceptedProjectionAtom : undefined,
20+ }),
1721 rng = new Rng(45131);
1822 graph.add(repo.graph.atom("a0"));
1923 const p = new MarkerProjection(db, graph, "f.txt", "typed-" + "cycle");
@@ -26,14 +30,25 @@
2630 const job = new ProjectionAtomAdoption(p, String(task++));
2731 const previous = state;
2832 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− });
33+ const read = db.read.bind(db);
34+ if (paged === "indexed")
35+ db.read = (collection, key) => {
36+ if (collection === "atoms") throw Error("full atom read forbidden");
37+ return read(collection, key);
38+ };
39+ let result;
40+ try {
41+ result = job.page({
42+ previous,
43+ atom: paged === "indexed" ? new ProjectionAtomIndex(db).openAccepted(atom.id) : atom,
44+ remove,
45+ source: "c".repeat(64),
46+ maxSteps: 3,
47+ validateSource: () => {},
48+ });
49+ } finally {
50+ db.read = read;
51+ }
3752 assert.ok(result.steps <= 3);
3853 assert.equal(result.atomicMoveWork, false);
3954 if (result.done) return result.state;
--- a/worker/project/project-types.ts
+++ b/worker/project/project-types.ts
@@ -567,6 +567,8 @@
567567
568568/** What the project needs from the store of binary files' bytes. */
569569export interface ProjectOptions {
570+ /** Optional derived atom indexing within persistent graph acceptance. */
571+ indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
570572 /** Private experimental reader route; never falls back for unsupported membership. */
571573 readViewProvider?: (graph: Graph) => ReadViewProvider;
572574 /**
--- a/worker/project/project.ts
+++ b/worker/project/project.ts
@@ -348,6 +348,8 @@
348348 readonly #hasBlob: (sha256: string) => boolean;
349349
350350 constructor(store: ProjectStore, options: ProjectOptions = {}, checkpoint?: typeof WRITER_REOPEN) {
351+ if (options.indexAcceptedAtom && !options.writerStorage)
352+ throw Error("accepted atom indexing requires writer storage");
351353 this.#store = store;
352354 this.#writerStorage = options.writerStorage ? new CachedStateStorage(options.writerStorage) : undefined;
353355 if (this.#writerStorage) {
@@ -402,7 +404,7 @@
402404 };
403405 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for.
404406 this.#graph = this.#writerStorage
405− ? new Graph({ storage: this.#writerStorage })
407+ ? new Graph({ storage: this.#writerStorage, indexAcceptedAtom: options.indexAcceptedAtom })
406408 : entryAt
407409 ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
408410 : new Graph();
--- a/worker/project/test/project-writer-storage.test.ts
+++ b/worker/project/test/project-writer-storage.test.ts
@@ -1,5 +1,10 @@
11import assert from "node:assert/strict";
2+import { createHash } from "node:crypto";
23import { test } from "node:test";
4+import {
5+ indexAcceptedProjectionAtom,
6+ ProjectionAtomIndex,
7+} from "../../../src/engine/experimental/projection-atom-index.ts";
38import { Graph } from "../../../src/engine/graph.ts";
49import { StableSet, storedArray } from "../../../src/engine/state-source.ts";
510import { SqlState } from "../../../src/engine/test/storage-helper.ts";
@@ -206,3 +211,33 @@
206211 assert.deepEqual(Project.openWriter(store, storage, entries.length).files(), { "a.txt": "ONE\n" });
207212 storage.db.close();
208213});
215+test("opted-in descriptor indexing survives writer reopen and rolls back canonical append failure", () => {
216+ const fixture = setup();
217+ const { storage, entries, store } = fixture;
218+ const options = { indexAcceptedAtom: indexAcceptedProjectionAtom };
219+ try {
220+ let project = new Project(store, { writerStorage: storage, ...options });
221+ storage.transaction(() => project.init({ "a.txt": "one\n" }, 0));
222+ project = Project.openWriter(store, storage, entries.length, options);
223+ const rows = storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all();
224+ fixture.fail();
225+ assert.throws(
226+ () => storage.transaction(() => project.record("writer", { "a.txt": "two\n" }, 1)),
227+ /canonical append failure/,
228+ );
229+ assert.deepEqual(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(), rows);
230+ fixture.recover();
231+ project = Project.openWriter(store, storage, entries.length, options);
232+ storage.transaction(() => project.record("writer", { "a.txt": "two\n" }, 1));
233+ storage.transaction(() => project.publish("writer", "Indexed", 2));
234+ const graph = new Graph({ storage });
235+ for (const atom of graph.atoms()) {
236+ const digest = createHash("sha256").update(JSON.stringify(atom)).digest("hex");
237+ assert.equal(new ProjectionAtomIndex(storage).open(atom.id, digest).seq, atom.seq);
238+ }
239+ assert.deepEqual(Project.openWriter(store, storage, entries.length, options).files(), { "a.txt": "two\n" });
240+ } finally {
241+ storage.db.close();
242+ }
243+});