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

Add opt-in persistent writer state, checked reopen and bounded adoption

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

Version 108 · Files at version 109

16 files, 1455 lines added, 58 removed.

--- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -15,6 +15,7 @@
1515 seqOf,
1616 startNode,
1717} from "./keys.ts";
18+import { type GraphStateStorage, type StateMap, storedArray, storedMap } from "./state-source.ts";
1819import {
1920 ATTR_NAMES,
2021 type Atom,
@@ -76,21 +77,25 @@
7677 * are two (#46): most keys name one atom, and a list for each costs more than
7778 * the value.
7879 */
79−function pushOne<K, V>(map: Map<K, V | V[]>, key: K, value: V): void {
80+function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {
8081 const had = map.get(key);
8182 if (had === undefined) map.set(key, value);
82− else if (Array.isArray(had)) had.push(value);
83− else map.set(key, [had, value]);
83+ else if (Array.isArray(had)) {
84+ had.push(value);
85+ map.set(key, had);
86+ } else map.set(key, [had, value]);
8487}
8588
8689function listOf<V>(had: V | V[] | undefined): readonly V[] {
8790 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
8891}
8992
90−function pushIndex<K, V>(map: Map<K, V[]>, key: K, value: V): void {
93+function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {
9194 const list = map.get(key);
92− if (list) list.push(value);
93− else map.set(key, [value]);
95+ if (list) {
96+ list.push(value);
97+ map.set(key, list);
98+ } else map.set(key, [value]);
9499}
95100
96101const EMPTY: readonly never[] = Object.freeze([]);
@@ -176,7 +181,14 @@
176181}
177182
178183/** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */
179−class Ints {
184+interface NumberIndex {
185+ readonly length: number;
186+ push(n: number): void;
187+ at(i: number): number;
188+ set(i: number, n: number): void;
189+}
191+class Ints implements NumberIndex {
180192 #buf: Int32Array | Uint8Array;
181193 /** bytes: values 0-255 only, one byte each. */
182194 constructor(bytes = false) {
@@ -232,6 +244,7 @@
232244}
233245
234246export class Graph {
247+ readonly #storage?: GraphStateStorage;
235248 #atoms: Atom[] = [];
236249 #lamport: number[] = [];
237250 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
@@ -239,12 +252,14 @@
239252 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
240253 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
241254 #lineBase: number[] = [];
242− #lineAtom = new Ints();
243− #lineFile = new Ints();
244− #lineParent = new Ints();
255+ #lineAtom: NumberIndex = new Ints();
256+ #lineFile: NumberIndex = new Ints();
257+ #lineParent: NumberIndex = new Ints();
245258 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
246259 #lineText: string[] | undefined = [];
247− #lineTotal = 0;
260+ get #lineTotal(): number {
261+ return this.#lineAtom.length;
262+ }
248263 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
249264 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
250265 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
@@ -257,13 +272,69 @@
257272 * atom's text when a line of it is asked for, keeping the most recent.
258273 */
259274 constructor(
260− options: { texts?: (seq: number) => readonly (readonly string[])[]; lists?: (seq: number) => AtomLists } = {},
275+ options: {
276+ texts?: (seq: number) => readonly (readonly string[])[];
277+ lists?: (seq: number) => AtomLists;
278+ storage?: GraphStateStorage;
279+ } = {},
261280 ) {
262281 if (options.texts) {
263282 this.#texts = options.texts;
264283 this.#lineText = undefined;
265284 }
266285 if (options.lists) this.#lists = options.lists;
286+ this.#storage = options.storage;
287+ if (options.storage) {
288+ const storage = options.storage;
289+ const numbers = (name: string): NumberIndex => {
290+ const values = storedArray<number>(storage, name);
291+ return {
292+ get length() {
293+ return values.length;
294+ },
295+ push: (value) => {
296+ values.push(value);
297+ },
298+ at: (index) => values[index]!,
299+ set: (index, value) => {
300+ values[index] = value;
301+ },
302+ };
303+ };
304+ this.#atoms = storedArray<Atom>(storage, "atoms", (atom) =>
305+ freezeAtom(
306+ atom,
307+ (id) => id,
308+ (author) => author,
309+ ),
310+ );
311+ this.#lamport = storedArray(storage, "lamport");
312+ this.#lineBase = storedArray(storage, "line-base");
313+ this.#paths = storedArray(storage, "paths");
314+ this.#movers = storedArray(storage, "movers");
315+ this.#atomFiles = storedArray(storage, "atom-files");
316+ this.#atomDeletes = storedArray(storage, "atom-deletes");
317+ this.#lineAtom = numbers("line-atom");
318+ this.#lineFile = numbers("line-file");
319+ this.#lineParent = numbers("line-parent");
320+ this.#deleter = numbers("deleter");
321+ this.#replacing = numbers("replacing");
322+ this.#lineText = storedArray(storage, "line-text");
323+ this.#pathIndex = storedMap(storage, "path-index");
324+ this.#moreDeleters = storedMap(storage, "more-deleters");
325+ this.#writers = storedMap(storage, "writers");
326+ this.#readers = storedMap(storage, "readers");
327+ this.#holders = storedMap(storage, "holders");
328+ this.#dependents = storedMap(storage, "dependents");
329+ this.#resolvers = storedMap(storage, "resolvers");
330+ this.#together = storedMap(storage, "together");
331+ this.#fileAtoms = storedMap(storage, "file-atoms");
332+ this.#runStarts = storedMap(storage, "run-starts");
333+ this.#relocations = storedMap(storage, "relocations");
334+ this.#relocatedTo = storedMap(storage, "relocated-to");
335+ this.#relocatedToCode = storedMap(storage, "relocated-to-code");
336+ this.#labels = storedMap(storage, "labels");
337+ }
267338 }
268339
269340 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
@@ -352,30 +423,30 @@
352423 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
353424 }
354425 #paths: string[] = [];
355− #pathIndex = new Map<string, number>();
426+ #pathIndex: StateMap<string, number> = new Map();
356427 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
357− #deleter = new Ints();
358− #moreDeleters = new Map<number, number[]>();
359− #writers = new Map<Key | number, AtomId | AtomId[]>();
360− #readers = new Map<Key | number, AtomId | AtomId[]>();
361− #holders = new Map<Key | number, AtomId | AtomId[]>();
362− #dependents = new Map<AtomId, AtomId | AtomId[]>();
363− #resolvers = new Map<AtomId, AtomId | AtomId[]>();
364− #together = new Map<AtomId, TogetherLink[]>();
365− #fileAtoms = new Map<string, AtomId[]>();
428+ #deleter: NumberIndex = new Ints();
429+ #moreDeleters: StateMap<number, number[]> = new Map();
430+ #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
431+ #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
432+ #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
433+ #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
434+ #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
435+ #together: StateMap<AtomId, TogetherLink[]> = new Map();
436+ #fileAtoms: StateMap<string, AtomId[]> = new Map();
366437 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
367− #runStarts = new Map<number, number | number[]>();
438+ #runStarts: StateMap<number, number | number[]> = new Map();
368439 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
369− #replacing = new Ints(true);
370− #relocations = new Map<LineId, RelocationInfo[]>();
371− #relocatedTo = new Map<NodeId, RelocationInfo[]>();
440+ #replacing: NumberIndex = new Ints(true);
441+ #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
442+ #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
372443 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
373− #relocatedToCode = new Map<number, RelocationInfo[]>();
444+ #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
374445 #movers: AtomId[] = [];
375446 #atomFiles: (readonly string[])[] = [];
376447 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
377− #atomDeletes: (Int32Array | undefined)[] = [];
378− #labels = new Map<string, Label>();
448+ #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
449+ #labels: StateMap<string, Label> = new Map();
379450 /** Each author's name kept once (#46). */
380451 #authors = new Map<string, string>();
381452
@@ -776,6 +847,11 @@
776847 * The atom is frozen. Adding to the graph does not add it to any set.
777848 */
778849 add(atom: Atom): void {
850+ if (this.#storage) this.#storage.transaction(() => this.#add(atom));
851+ else this.#add(atom);
852+ }
854+ #add(atom: Atom): void {
779855 validateShape(atom);
780856 const seq = this.#atoms.length;
781857 const bad = (why: string): never => {
@@ -850,6 +926,7 @@
850926 atom,
851927 (id) => this.#atoms[seqOf(id)]!.id,
852928 (author) => {
929+ if (this.#storage) return author;
853930 let a = this.#authors.get(author);
854931 if (a === undefined) this.#authors.set(author, (a = author));
855932 return a;
@@ -857,7 +934,7 @@
857934 this.#texts ? this.#reader(seq) : undefined,
858935 this.#lists ? this.#listReader(seq) : undefined,
859936 );
860− this.#atoms.push(frozen);
937+ this.#atoms.push(this.#storage ? atom : frozen);
861938 let lam = 0;
862939 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
863940 this.#lamport.push(lam);
@@ -866,7 +943,7 @@
866943 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
867944 const deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined;
868945 const deletedN = atom.deletes.map((line) => this.#lineN(line));
869− this.#atomDeletes.push(deletedN.length > 0 ? Int32Array.from(deletedN) : undefined);
946+ this.#atomDeletes.push(deletedN.length > 0 ? (this.#storage ? deletedN : Int32Array.from(deletedN)) : undefined);
870947 this.#lineBase.push(this.#lineTotal);
871948 for (const run of atom.inserts) {
872949 const file = this.#pathOf(run.file);
@@ -874,7 +951,7 @@
874951 const first = this.#lineTotal;
875952 pushOne(this.#runStarts, parent, first);
876953 for (let i = 0; i < run.lines.length; i++) {
877− const n = this.#lineTotal++;
954+ const n = this.#lineTotal;
878955 this.#lineAtom.push(seq);
879956 this.#lineFile.push(file);
880957 this.#lineParent.push(parent);
@@ -974,6 +1051,10 @@
9741051 * their base instead, so their contents don't change.
9751052 */
9761053 removeLabel(name: string): boolean {
1054+ return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1055+ }
1057+ #removeLabel(name: string): boolean {
9771058 const gone = this.#labels.get(name);
9781059 if (!gone) return false;
9791060 this.#labels.delete(name);
--- /dev/null
+++ b/src/engine/state-source.ts
@@ -0,0 +1,274 @@
1+/**
2+ * Indexed graph storage. Values must be copied on write and read: a caller
3+ * mutating a returned list must not silently change persisted state. Hosts
4+ * provide transactions that roll back every write when the callback throws.
5+ * The namespace belongs to one graph and must not be shared by concurrent
6+ * Graph instances. Opening a graph does not scan its stored collections.
7+ */
8+export interface GraphStateStorage {
9+ read(collection: string, key: string): unknown;
10+ write(collection: string, key: string, value: unknown): void;
11+ remove(collection: string, key: string): void;
12+ entries(collection: string): Iterable<readonly [string, unknown]>;
13+ transaction<T>(body: () => T): T;
14+}
16+/** Immutable membership whose implementation does not retain its enumerated keys. */
17+export abstract class StableSet<T> implements ReadonlySet<T> {
18+ abstract has(value: T): boolean;
19+ abstract values(): SetIterator<T>;
20+ /** Only resident membership data; external storage is not charged as heap. */
21+ abstract readonly retainedBytes: number;
22+ get [Symbol.toStringTag](): string {
23+ return "Set";
24+ }
25+ get size(): number {
26+ let count = 0;
27+ for (const _ of this) count++;
28+ return count;
29+ }
30+ keys(): SetIterator<T> {
31+ return this.values();
32+ }
33+ *entries(): SetIterator<[T, T]> {
34+ for (const value of this) yield [value, value];
35+ }
36+ [Symbol.iterator](): SetIterator<T> {
37+ return this.values();
38+ }
39+ forEach(callback: (value: T, key: T, set: ReadonlySet<T>) => void, thisArg?: unknown): void {
40+ for (const value of this) callback.call(thisArg, value, value, this);
41+ }
42+}
44+/** Both operands must be immutable for the lifetime of this union. */
45+export class StableUnionSet<T> extends StableSet<T> {
46+ readonly #left: StableSet<T>;
47+ readonly #right: StableSet<T>;
48+ constructor(left: StableSet<T>, right: StableSet<T>) {
49+ super();
50+ this.#left = left;
51+ this.#right = right;
52+ }
53+ get retainedBytes(): number {
54+ return 32 + this.#left.retainedBytes + this.#right.retainedBytes;
55+ }
56+ has(value: T): boolean {
57+ return this.#left.has(value) || this.#right.has(value);
58+ }
59+ *values(): SetIterator<T> {
60+ yield* this.#left;
61+ for (const value of this.#right) if (!this.#left.has(value)) yield value;
62+ }
63+}
65+/** An immutable snapshot for the operation's small overlay, not its history. */
66+export class StableOverlaySet<T> extends StableSet<T> {
67+ readonly #values: Set<T>;
68+ constructor(values: Iterable<T>) {
69+ super();
70+ this.#values = new Set(values);
71+ }
72+ get retainedBytes(): number {
73+ return 64 + this.#values.size * 32;
74+ }
75+ has(value: T): boolean {
76+ return this.#values.has(value);
77+ }
78+ values(): SetIterator<T> {
79+ return this.#values.values();
80+ }
81+}
83+const indexKey = (key: PropertyKey): key is string =>
84+ typeof key === "string" && /^(0|[1-9][0-9]*)$/.test(key) && Number.isSafeInteger(Number(key));
86+/** Array-shaped access without retaining its historical values in memory. */
87+export function storedArray<T>(storage: GraphStateStorage, name: string, decode?: (value: T) => T): T[] {
88+ const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
89+ const read = (key: string) => {
90+ const value = storage.read(name, key) as T;
91+ return value === undefined || !decode ? value : decode(value);
92+ };
93+ return new Proxy([] as T[], {
94+ get(target, key, receiver) {
95+ if (key === "length") return length();
96+ if (indexKey(key)) return Number(key) < length() ? read(key) : undefined;
97+ return Reflect.get(target, key, receiver);
98+ },
99+ set(_target, key, value) {
100+ if (key === "length") {
101+ if (value !== length()) throw new Error("stored graph arrays cannot be resized directly");
102+ return true;
103+ }
104+ if (!indexKey(key)) throw new Error("invalid stored graph array property");
105+ const index = Number(key);
106+ const size = length();
107+ if (index > size) throw new Error("stored graph arrays cannot contain gaps");
108+ storage.write(name, key, value);
109+ if (index === size) storage.write(`${name}:meta`, "length", size + 1);
110+ return true;
111+ },
112+ has(target, key) {
113+ return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
114+ },
115+ ownKeys() {
116+ return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
117+ },
118+ getOwnPropertyDescriptor(target, key) {
119+ if (indexKey(key) && Number(key) < length())
120+ return { configurable: true, enumerable: true, writable: true, value: read(key) };
121+ return Reflect.getOwnPropertyDescriptor(target, key);
122+ },
123+ });
124+}
126+export interface StateMap<K, V> {
127+ get(key: K): V | undefined;
128+ set(key: K, value: V): StateMap<K, V>;
129+ has(key: K): boolean;
130+ delete(key: K): boolean;
131+ values(): IterableIterator<V>;
132+}
134+/** Keys are tagged so numeric graph codes cannot collide with string keys. */
135+export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
136+ const keyOf = (key: K) => JSON.stringify([typeof key, key]);
137+ const map: StateMap<K, V> = {
138+ get: (key) => storage.read(name, keyOf(key)) as V | undefined,
139+ has: (key) => storage.read(name, keyOf(key)) !== undefined,
140+ set(key, value) {
141+ storage.write(name, keyOf(key), value);
142+ return map;
143+ },
144+ delete(key) {
145+ const existed = map.has(key);
146+ storage.remove(name, keyOf(key));
147+ return existed;
148+ },
149+ *values() {
150+ for (const [, value] of storage.entries(name)) yield value as V;
151+ },
152+ };
153+ return map;
154+}
156+/**
157+ * A Map-compatible persistent index. Iteration follows insertion order and
158+ * decodes one row at a time. Returned objects are copies, so mutations need
159+ * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
160+ */
161+export class StoredMap<K extends string | number, V> extends Map<K, V> {
162+ readonly #storage: GraphStateStorage;
163+ readonly #name: string;
164+ readonly #encode: (value: V) => unknown;
165+ readonly #decode: (value: unknown) => V;
166+ constructor(
167+ storage: GraphStateStorage,
168+ name: string,
169+ codec?: { encode(value: V): unknown; decode(value: unknown): V },
170+ ) {
171+ super();
172+ this.#storage = storage;
173+ this.#name = name;
174+ this.#encode = codec?.encode ?? ((value) => value);
175+ this.#decode = codec?.decode ?? ((value) => value as V);
176+ }
177+ #key(key: K): string {
178+ return JSON.stringify([typeof key, key]);
179+ }
180+ #row(key: K): { slot: number; value: unknown } | undefined {
181+ return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
182+ }
183+ override get size(): number {
184+ return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
185+ }
186+ override has(key: K): boolean {
187+ return this.#row(key) !== undefined;
188+ }
189+ override get(key: K): V | undefined {
190+ const row = this.#row(key);
191+ return row === undefined ? undefined : this.#decode(row.value);
192+ }
193+ override set(key: K, value: V): this {
194+ const row = this.#row(key);
195+ let slot = row?.slot;
196+ if (slot === undefined) {
197+ const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
198+ slot = keys.length;
199+ keys.push(key);
200+ this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
201+ }
202+ this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
203+ return this;
204+ }
205+ override delete(key: K): boolean {
206+ if (!this.has(key)) return false;
207+ this.#storage.remove(this.#name, this.#key(key));
208+ this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
209+ return true;
210+ }
211+ override clear(): void {
212+ for (const key of this.keys()) this.delete(key);
213+ }
214+ override *entries(): MapIterator<[K, V]> {
215+ const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
216+ for (let slot = 0; slot < keys.length; slot++) {
217+ const key = keys[slot]!;
218+ const row = this.#row(key);
219+ if (row?.slot === slot) yield [key, this.#decode(row.value)];
220+ }
221+ }
222+ override *keys(): MapIterator<K> {
223+ for (const [key] of this.entries()) yield key;
224+ }
225+ override *values(): MapIterator<V> {
226+ for (const [, value] of this.entries()) yield value;
227+ }
228+ override [Symbol.iterator](): MapIterator<[K, V]> {
229+ return this.entries();
230+ }
231+ override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
232+ for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
233+ }
234+}
236+/** Persistent membership with streaming iteration and no in-memory key cache. */
237+export class StoredSet<K extends string | number> extends Set<K> {
238+ readonly #map: StoredMap<K, true>;
239+ constructor(storage: GraphStateStorage, name: string) {
240+ super();
241+ this.#map = new StoredMap(storage, name);
242+ }
243+ override get size(): number {
244+ return this.#map.size;
245+ }
246+ override has(key: K): boolean {
247+ return this.#map.has(key);
248+ }
249+ override add(key: K): this {
250+ this.#map.set(key, true);
251+ return this;
252+ }
253+ override delete(key: K): boolean {
254+ return this.#map.delete(key);
255+ }
256+ override clear(): void {
257+ this.#map.clear();
258+ }
259+ override *values(): SetIterator<K> {
260+ yield* this.#map.keys();
261+ }
262+ override keys(): SetIterator<K> {
263+ return this.values();
264+ }
265+ override *entries(): SetIterator<[K, K]> {
266+ for (const key of this.values()) yield [key, key];
267+ }
268+ override [Symbol.iterator](): SetIterator<K> {
269+ return this.values();
270+ }
271+ override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
272+ for (const key of this.values()) callback.call(thisArg, key, key, this);
273+ }
274+}
--- /dev/null
+++ b/src/engine/test/state-source.test.ts
@@ -0,0 +1,96 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { checkDraft, Graph, View } from "../index.ts";
4+import { lines, Repo } from "./helpers.ts";
5+import { SqlState } from "./storage-helper.ts";
6+
7+test("stored graph reopens without replay and preserves moves, conflicts and new edits", () => {
8+ const oracle = Repo.init({ "a.txt": lines("one", "two", "three"), "b.txt": "" });
9+ oracle.edit({ edits: [{ file: "a.txt", old: "two", new: "TWO" }] });
10+ oracle.edit({ move: { file: "a.txt", start: 1, end: 2, to: "b.txt", at: 0 } });
11+ const storage = new SqlState();
12+ const original = new Graph({ storage });
13+ for (const atom of oracle.graph.atoms()) original.add(atom);
14+ original.setLabel({ name: "saved", head: "a2", title: "Saved", message: "" });
15+ const reads = storage.reads;
16+ const reopened = new Graph({ storage });
17+ assert.equal(storage.reads, reads, "opening does not hydrate historical collections");
18+ assert.equal(storage.scans, 0);
19+ assert.equal(reopened.size, oracle.graph.size);
20+ assert.equal(reopened.lineCount, oracle.graph.lineCount);
21+ assert.deepEqual([...reopened.movers()], [...oracle.graph.movers()]);
22+ for (const atom of oracle.graph.atoms()) {
23+ assert.deepEqual(reopened.filesOf(atom.id), oracle.graph.filesOf(atom.id));
24+ for (const move of atom.moves ?? []) {
25+ assert.deepEqual(reopened.relocationsOf(move.line), oracle.graph.relocationsOf(move.line));
26+ assert.deepEqual(reopened.relocatedTo(move.parent), oracle.graph.relocatedTo(move.parent));
27+ assert.equal(reopened.codeOf(move.parent), oracle.graph.codeOf(move.parent));
28+ }
29+ }
30+ assert.deepEqual(new View(reopened, oracle.shared).files(), oracle.files());
31+ assert.equal(reopened.label("saved")?.head, "a2");
32+ const draft = oracle.draft({ edits: [{ file: "a.txt", old: "one", new: "ONE" }] });
33+ assert.deepEqual(checkDraft(reopened, oracle.shared, draft), oracle.check(draft));
34+ oracle.graph.add(draft);
35+ reopened.add(draft);
36+ oracle.shared.add(draft.id);
37+ assert.deepEqual(new View(new Graph({ storage }), oracle.shared).files(), oracle.files());
38+ for (let n = 0; n < oracle.graph.lineCount; n++) {
39+ const id = oracle.graph.lineIdOf(n);
40+ assert.deepEqual(reopened.line(id), oracle.graph.line(id));
41+ assert.deepEqual(reopened.deletersOf(id), oracle.graph.deletersOf(id));
42+ }
43+ assert.ok(Object.isFrozen(reopened.atom("a0")));
44+ storage.db.close();
45+});
47+test("stored indexes retain multiple claimants and preserve a real divergent conflict", () => {
48+ const oracle = Repo.init({ "a.txt": lines("one", "two", "three") });
49+ oracle.edit({ edits: [{ file: "a.txt", old: "one", new: "ONE" }], author: "left" });
50+ const right = oracle.draft({ edits: [{ file: "a.txt", old: "one", new: "uno" }], author: "right" }, ["a0"]);
51+ const storage = new SqlState();
52+ const graph = new Graph({ storage });
53+ for (const atom of oracle.graph.atoms()) graph.add(atom);
54+ assert.equal(oracle.check(right).conflicts.length, 1);
55+ assert.deepEqual(checkDraft(new Graph({ storage }), oracle.shared, right), oracle.check(right));
56+ graph.add(right);
57+ oracle.graph.add(right);
58+ assert.deepEqual(new Graph({ storage }).writersOf("L:a0.0"), oracle.graph.writersOf("L:a0.0"));
59+ assert.deepEqual(new Graph({ storage }).deletedLines(right.id), oracle.graph.deletedLines(right.id));
60+ storage.db.close();
61+});
63+test("failed stored append rolls back all graph indexes and can be retried", () => {
64+ const oracle = Repo.init({ "a.txt": lines("one", "two") });
65+ const storage = new SqlState();
66+ const graph = new Graph({ storage });
67+ graph.add(oracle.graph.atom("a0"));
68+ const before = JSON.stringify(graph.toJSON());
69+ const draft = oracle.draft({ edits: [{ file: "a.txt", old: "one", new: "ONE" }] });
70+ storage.failWrite = storage.writes + 10;
71+ assert.throws(() => graph.add(draft), /injected storage failure/);
72+ assert.equal(JSON.stringify(graph.toJSON()), before);
73+ assert.equal(JSON.stringify(new Graph({ storage }).toJSON()), before);
74+ storage.failWrite = Infinity;
75+ graph.add(draft);
76+ assert.equal(new Graph({ storage }).size, 2);
77+ storage.db.close();
78+});
80+test("removing a stored label rolls back dependent rewrites on failure", () => {
81+ const oracle = Repo.init({ "a.txt": lines("one") });
82+ const storage = new SqlState();
83+ const graph = new Graph({ storage });
84+ graph.add(oracle.graph.atom("a0"));
85+ graph.setLabel({ name: "base", head: "a0", title: "Base", message: "" });
86+ graph.setLabel({ name: "child", head: "a0", base: "base", title: "Child", message: "" });
87+ const before = graph.labels();
88+ storage.failWrite = storage.writes + 1;
89+ assert.throws(() => graph.removeLabel("base"), /injected storage failure/);
90+ assert.deepEqual(new Graph({ storage }).labels(), before);
91+ storage.failWrite = Infinity;
92+ assert.equal(graph.removeLabel("base"), true);
93+ assert.equal(new Graph({ storage }).label("base"), undefined);
94+ assert.equal(new Graph({ storage }).label("child")?.base, "a0");
95+ storage.db.close();
96+});
--- /dev/null
+++ b/src/engine/test/storage-helper.ts
@@ -0,0 +1,43 @@
1+import { DatabaseSync } from "node:sqlite";
2+import type { GraphStateStorage } from "../state-source.ts";
3+
4+export class SqlState implements GraphStateStorage {
5+ readonly db = new DatabaseSync(":memory:");
6+ reads = 0;
7+ writes = 0;
8+ scans = 0;
9+ failWrite = Infinity;
10+ constructor() {
11+ this.db.exec("CREATE TABLE state (collection TEXT, key TEXT, value TEXT, PRIMARY KEY(collection,key))");
12+ }
13+ read(collection: string, key: string): unknown {
14+ this.reads++;
15+ const row = this.db.prepare("SELECT value FROM state WHERE collection = ? AND key = ?").get(collection, key);
16+ return row ? JSON.parse(row.value as string).value : undefined;
17+ }
18+ write(collection: string, key: string, value: unknown): void {
19+ if (++this.writes === this.failWrite) throw new Error("injected storage failure");
20+ this.db.prepare("INSERT OR REPLACE INTO state VALUES (?, ?, ?)").run(collection, key, JSON.stringify({ value }));
21+ }
22+ remove(collection: string, key: string): void {
23+ this.db.prepare("DELETE FROM state WHERE collection = ? AND key = ?").run(collection, key);
24+ }
25+ *entries(collection: string): Iterable<readonly [string, unknown]> {
26+ this.scans++;
27+ for (const row of this.db
28+ .prepare("SELECT key, value FROM state WHERE collection = ? ORDER BY key")
29+ .iterate(collection))
30+ yield [row.key as string, JSON.parse(row.value as string).value];
31+ }
32+ transaction<T>(body: () => T): T {
33+ this.db.exec("SAVEPOINT graph_change");
34+ try {
35+ const value = body();
36+ this.db.exec("RELEASE graph_change");
37+ return value;
38+ } catch (error) {
39+ this.db.exec("ROLLBACK TO graph_change; RELEASE graph_change");
40+ throw error;
41+ }
42+ }
43+}
--- a/src/engine/test/view.test.ts
+++ b/src/engine/test/view.test.ts
@@ -3,9 +3,38 @@
33import assert from "node:assert/strict";
44import { describe, it } from "node:test";
55import { buildBase, conflicts, Graph, project, View } from "../index.ts";
6+import { StableOverlaySet, StableSet } from "../state-source.ts";
7+import type { AtomId } from "../types.ts";
68import { lines, Repo } from "./helpers.ts";
79
810describe("View", () => {
11+ it("immutable indexed membership avoids a history-sized bitmap and remains a snapshot", () => {
12+ class RangeMembership extends StableSet<AtomId> {
13+ readonly retainedBytes = 64;
14+ readonly count: number;
15+ constructor(count: number) {
16+ super();
17+ this.count = count;
18+ }
19+ has(id: AtomId): boolean {
20+ return /^a[0-9]+$/.test(id) && Number(id.slice(1)) < this.count;
21+ }
22+ *values(): SetIterator<AtomId> {
23+ for (let i = 0; i < this.count; i++) yield `a${i}`;
24+ }
25+ }
26+ const repo = Repo.init({ "a.txt": "0\n" });
27+ for (let i = 1; i <= 40; i++) repo.edit({ edits: [{ file: "a.txt", old: `${i - 1}\n`, new: `${i}\n` }] });
28+ const first = new View(repo.graph, new RangeMembership(repo.graph.size));
29+ const weight = first.weight();
30+ for (let i = 41; i <= 80; i++) repo.edit({ edits: [{ file: "a.txt", old: `${i - 1}\n`, new: `${i}\n` }] });
31+ const second = new View(repo.graph, new RangeMembership(repo.graph.size));
32+ assert.equal(second.weight(), weight, "membership resident size does not increase with historical atom count");
33+ assert.equal(first.text("a.txt"), "40\n");
34+ assert.equal(second.text("a.txt"), "80\n");
35+ assert.equal(first.set.has("a80"), false);
36+ assert.throws(() => new View(repo.graph, new StableOverlaySet<AtomId>(["a1"])), /not closed/);
37+ });
938 it("keeps deleted lines as tombstones in the full sequence", () => {
1039 const repo = Repo.init({ "f.txt": lines("one", "two", "three") });
1140 const del = repo.edit({ edits: [{ file: "f.txt", old: "two\n", new: "" }] });
--- a/src/engine/view.ts
+++ b/src/engine/view.ts
@@ -11,6 +11,7 @@
1111
1212import type { Graph, RelocationInfo } from "./graph.ts";
1313import { isStartNode } from "./keys.ts";
14+import { StableSet } from "./state-source.ts";
1415import { joinLines } from "./text.ts";
1516import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from "./types.ts";
1617
@@ -90,7 +91,8 @@
9091export class View {
9192 readonly graph: Graph;
9293 /** The set, made from #in the first time it's asked for: a view keeps a byte per atom, not a copy of the set (#46). */
93− #set: Set<AtomId> | undefined;
94+ #set: AtomSet | undefined;
95+ readonly #stable: StableSet<AtomId> | undefined;
9496 #files = new Map<string, FileState>();
9597 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
9698 #knownList: string[] | undefined;
@@ -109,14 +111,34 @@
109111 #textCache: { path: string; text: string } | undefined;
110112
111113 constructor(graph: Graph, set: Iterable<AtomId>) {
114+ this.graph = graph;
115+ if (set instanceof StableSet) {
116+ this.#stable = set;
117+ this.#set = set;
118+ this.#in = new Uint8Array(0);
119+ for (const id of set) {
120+ const atom = graph.atom(id);
121+ for (const dependency of atom.deps) {
122+ graph.atom(dependency);
123+ if (!set.has(dependency))
124+ throw new EngineError("not-closed", `set is not closed: ${id} depends on ${dependency}`);
125+ }
126+ }
127+ this.#movers = graph.movers().filter((id) => set.has(id));
128+ this.#relocs = this.#movers.length === 0 ? new Map() : undefined;
129+ this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
130+ return;
131+ }
112132 const inSet = new Uint8Array(graph.size);
113− const atoms: { readonly id: AtomId; readonly deps: readonly AtomId[] }[] = [];
114133 for (const id of set) {
115134 const atom = graph.atom(id);
116135 inSet[atom.seq] = 1;
117− atoms.push(atom);
118136 }
119− for (const atom of atoms) {
137+ // Validate one atom at a time. Keeping all decoded atoms here defeats
138+ // storage-backed Graph reads even though the view only needs membership.
139+ for (let seq = 0; seq < inSet.length; seq++) {
140+ if (inSet[seq] !== 1) continue;
141+ const atom = graph.atom(graph.idOfSeq(seq));
120142 for (const d of atom.deps) {
121143 if (inSet[graph.atom(d).seq] !== 1)
122144 throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
@@ -141,6 +163,7 @@
141163
142164 /** Whether the atom with this seq is in the set. */
143165 #has(seq: number): boolean {
166+ if (this.#stable) return this.#stable.has(this.graph.idOfSeq(seq));
144167 return seq < this.#in.length && this.#in[seq] === 1;
145168 }
146169
@@ -272,7 +295,8 @@
272295 if (relocs) {
273296 for (const r of graph.relocatedToCode(code)) {
274297 const n = graph.lineN(r.line);
275− if (relocs.get(n)?.r !== r) continue;
298+ const selected = relocs.get(n)?.r;
299+ if (!selected || selected.atom !== r.atom || selected.k !== r.k) continue;
276300 const seq = graph.atom(r.atom).seq;
277301 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
278302 }
@@ -336,8 +360,12 @@
336360 get #known(): string[] {
337361 if (!this.#knownList) {
338362 const known = new Set<string>();
339− for (let seq = 0; seq < this.#in.length; seq++)
340− if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
363+ if (this.#stable) {
364+ for (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file);
365+ } else {
366+ for (let seq = 0; seq < this.#in.length; seq++)
367+ if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
368+ }
341369 this.#knownList = [...known].sort();
342370 }
343371 return this.#knownList;
@@ -470,7 +498,8 @@
470498 n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;
471499 n += MAP_HEADER_BYTES; // #files exists from construction.
472500 n += MAP_HEADER_BYTES; // #fileOf exists from construction.
473− if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
501+ if (this.#stable) n += this.#stable.retainedBytes;
502+ else if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
474503 if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;
475504 if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;
476505 if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;
--- a/worker/project/apply-entry.ts
+++ b/worker/project/apply-entry.ts
@@ -141,12 +141,21 @@
141141 const { type: _, ...note } = entry;
142142 host.notes.set(entry.id, { ...note, lines: [...entry.lines], at });
143143 host.setLastNote(Math.max(host.lastNote(), entry.id));
144− if (entry.change !== undefined && host.changes.has(entry.change)) host.changes.get(entry.change)!.last = at;
144+ if (entry.change !== undefined) {
145+ const change = host.changes.get(entry.change);
146+ if (change) {
147+ change.last = at;
148+ host.changes.set(entry.change, change);
149+ }
150+ }
145151 break;
146152 }
147153 case "note-closed": {
148154 const note = host.notes.get(entry.id);
149− if (note) note.closed = { agent: entry.agent, how: entry.how, time: entry.time };
155+ if (note) {
156+ note.closed = { agent: entry.agent, how: entry.how, time: entry.time };
157+ host.notes.set(entry.id, note);
158+ }
150159 break;
151160 }
152161 case "pulled":
@@ -249,6 +258,7 @@
249258 files: [...new Set(entry.collisions.map((c) => c.file))].sort(),
250259 });
251260 rec.last = at;
261+ host.changes.set(id, rec);
252262 }
253263 }
254264 break;
--- a/worker/project/change-records.ts
+++ b/worker/project/change-records.ts
@@ -73,6 +73,7 @@
7373 rec.note = { text: agent.starting.text, files: [...agent.starting.files] };
7474 if (agent.starting.issue !== undefined) rec.issue = agent.starting.issue;
7575 }
76+ host.changes.set(id, rec);
7677 return rec;
7778}
7879
@@ -101,6 +102,7 @@
101102 host.versionChange.set(`${draft ?? ""} ${entry.version}`, id);
102103 if (entry.type === "publish") for (const s of entry.settled ?? []) rec.settled.push({ ...s, version: entry.version });
103104 rec.last = at;
105+ host.changes.set(id, rec);
104106 if (old) {
105107 delete agent.starting;
106108 delete agent.noteAt;
--- a/worker/project/notes.ts
+++ b/worker/project/notes.ts
@@ -321,5 +321,6 @@
321321 if (a) host.queueNews(a, [noteClosedItem(agentName, how, id, note)], entries);
322322 }
323323 host.flush(entries);
324− return host.noteAnswer(note);
324+ // Storage-backed maps return snapshots; apply may replace the stored row.
325+ return host.noteAnswer(host.notes.get(id)!);
325326}
--- a/worker/project/project-types.ts
+++ b/worker/project/project-types.ts
@@ -1,4 +1,5 @@
11import type { Atom, AtomId, LineId } from "../../src/engine/index.ts";
2+import type { GraphStateStorage } from "../../src/engine/state-source.ts";
23import type { Kept, MarkedRegion } from "./markers.ts";
34/** Whole files: path -> text, or null for a deleted file. */
45export type Files = Record<string, string | null>;
@@ -565,6 +566,14 @@
565566
566567/** What the project needs from the store of binary files' bytes. */
567568export interface ProjectOptions {
569+ /**
570+ * Writer indexes for a fresh project or adoption into an empty namespace.
571+ * The host must wrap each operation and canonical log append in the same
572+ * storage transaction, and discard this Project if it rolls back. This is
573+ * not the checkpoint reopen API: use Project.openWriter for an existing
574+ * committed namespace, with its authoritative canonical log length.
575+ */
576+ writerStorage?: GraphStateStorage;
568577 /** Whether the bytes for a SHA-256 have been uploaded. Without it, no blob is held, so binary files are refused. */
569578 hasBlob?: (sha256: string) => boolean;
570579 /** The time now, for start notes that end after 2 hours idle (#44). Without it, the newest entry's time. */
--- a/worker/project/project.ts
+++ b/worker/project/project.ts
@@ -13,6 +13,14 @@
1313// unit. Every agent works in one space at a time.
1414
1515import { type Atom, type AtomId, EngineError, Graph, type LineId, type View } from "../../src/engine/index.ts";
16+import {
17+ type GraphStateStorage,
18+ StableOverlaySet,
19+ StableSet,
20+ StableUnionSet,
21+ StoredMap,
22+ storedArray,
23+} from "../../src/engine/state-source.ts";
1624import { type AddDraftHost, addDraft as hostedAddDraft } from "./add-draft.ts";
1725import { type AmendHost, amend as hostedAmend } from "./amend.ts";
1826import { type AnnounceHost, announce as hostedAnnounce, announcePerson as hostedAnnouncePerson } from "./announce.ts";
@@ -191,6 +199,7 @@
191199 wholeRules as hostedWholeRules,
192200 type WholeHost,
193201} from "./whole-files.ts";
202+import { WriterAgents } from "./writer-agents.ts";
194203
195204export { MemoryStore } from "./memory-store.ts";
196205export { checkReadPath, pathProblem } from "./path-rules.ts";
@@ -204,9 +213,21 @@
204213
205214/** A start note lasts this long after the agent's last activity (#44). */
206215const NOTE_IDLE = 2 * 60 * 60 * 1000;
216+const WRITER_REOPEN = Symbol("verified writer checkpoint");
217+export interface WriterSource {
218+ readonly generation: number;
219+ readonly logLength: number;
220+ readonly sharedVersion: number;
221+}
222+interface WriterAdoption {
223+ source: WriterSource;
224+ next: number;
225+ ready: boolean;
226+}
207227
208228export class Project {
209229 readonly #store: ProjectStore;
230+ readonly #writerStorage?: GraphStateStorage;
210231 readonly #graph: Graph;
211232 /** Views laid out from atom sets, cached under a byte budget (views.ts). */
212233 readonly #views: ViewCache;
@@ -248,7 +269,16 @@
248269 /** For each version of shared, the log position of the entry that made it (#41). */
249270 readonly #versionAt: number[] = [];
250271 /** The newest time any applied entry carries: the clock when none was given. */
251− #lastTime = 0;
272+ #lastTimeMemory = 0;
273+ get #lastTime(): number {
274+ return this.#writerStorage
275+ ? ((this.#writerStorage.read("project:meta", "lastTime") as number | undefined) ?? 0)
276+ : this.#lastTimeMemory;
277+ }
278+ set #lastTime(value: number) {
279+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastTime", value);
280+ else this.#lastTimeMemory = value;
281+ }
252282 /** Every change (#44), by id. */
253283 readonly #changes = new Map<number, ChangeRecord>();
254284 /** Each version's change, by "<draft or ''> <version>" (#44): what a note on its lines belongs to. */
@@ -260,12 +290,39 @@
260290 /** The merge queue (#39), in order: publishes to shared waiting for their batch's check. */
261291 #queue: QueuedPublish[] = [];
262292 /** The newest note's id (#44). */
263− #lastNote = 0;
264− #queuedId = 0;
293+ #lastNoteMemory = 0;
294+ get #lastNote(): number {
295+ return this.#writerStorage
296+ ? ((this.#writerStorage.read("project:meta", "lastNote") as number | undefined) ?? 0)
297+ : this.#lastNoteMemory;
298+ }
299+ set #lastNote(value: number) {
300+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "lastNote", value);
301+ else this.#lastNoteMemory = value;
302+ }
303+ #queuedIdMemory = 0;
304+ get #queuedId(): number {
305+ return this.#writerStorage
306+ ? ((this.#writerStorage.read("project:meta", "queuedId") as number | undefined) ?? 0)
307+ : this.#queuedIdMemory;
308+ }
309+ set #queuedId(value: number) {
310+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "queuedId", value);
311+ else this.#queuedIdMemory = value;
312+ }
265313 /** Queued ids in the batch being checked now: not in the log, only for refusing an unqueue mid-check. */
266314 #checking = new Set<number>();
267315 /** How many entries the store holds: the log position of the next one (#41, the website's feed and replay). */
268− #stored = 0;
316+ #storedMemory = 0;
317+ get #stored(): number {
318+ return this.#writerStorage
319+ ? ((this.#writerStorage.read("project:meta", "stored") as number | undefined) ?? 0)
320+ : this.#storedMemory;
321+ }
322+ set #stored(value: number) {
323+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "stored", value);
324+ else this.#storedMemory = value;
325+ }
269326 /** Names on the lines a change replaced, by "<atom> <last replaced line>" (atoms never change). */
270327 #rule?: DefinitionRule;
271328 get #definitionRule(): DefinitionRule {
@@ -273,13 +330,53 @@
273330 return this.#rule;
274331 }
275332 /** The newest announcement's id (announcements are news entries keyed "announce <id>"). */
276− #announced = 0;
333+ #announcedMemory = 0;
334+ get #announced(): number {
335+ return this.#writerStorage
336+ ? ((this.#writerStorage.read("project:meta", "announced") as number | undefined) ?? 0)
337+ : this.#announcedMemory;
338+ }
339+ set #announced(value: number) {
340+ if (this.#writerStorage) this.#writerStorage.write("project:meta", "announced", value);
341+ else this.#announcedMemory = value;
342+ }
277343 #loading = false;
278344
279345 readonly #hasBlob: (sha256: string) => boolean;
280346
281− constructor(store: ProjectStore, options: ProjectOptions = {}) {
347+ constructor(store: ProjectStore, options: ProjectOptions = {}, checkpoint?: typeof WRITER_REOPEN) {
282348 this.#store = store;
349+ this.#writerStorage = options.writerStorage;
350+ if (options.writerStorage) {
351+ const storage = options.writerStorage;
352+ // A stored Graph cannot be replayed over itself. Check before any
353+ // constructor writes so an accidental reopen preserves the namespace.
354+ if (
355+ checkpoint !== WRITER_REOPEN &&
356+ ((storage.read("atoms:meta", "length") as number | undefined) ||
357+ (storage.read('membership:"":versions:meta', "length") as number | undefined))
358+ )
359+ throw new Error("writer indexes already contain history; Project checkpoint reopen is required");
360+ this.#membership = new Membership(storage);
361+ this.#atomAt = storedArray(storage, "project:atom-at");
362+ this.#timeAt = storedArray(storage, "project:time-at");
363+ this.#versionAt = storedArray(storage, "project:version-at");
364+ this.#notes = new StoredMap(storage, "project:notes");
365+ this.#changes = new StoredMap(storage, "project:changes");
366+ this.#labels = new StoredMap(storage, "project:labels");
367+ this.#versionChange = new StoredMap(storage, "project:version-change");
368+ this.#refusals = storedArray(storage, "project:refusals");
369+ this.#agents = new WriterAgents(storage);
370+ if (checkpoint === WRITER_REOPEN) {
371+ this.#mods = storage.read("project:meta", "mods") as string[];
372+ this.#queue = storage.read("project:meta", "queue") as QueuedPublish[];
373+ const tells = storage.read("project:meta", "tells") as [
374+ number,
375+ Omit<TellRecord, "heard"> & { heard: [string, { at: number | undefined } | null][] },
376+ ][];
377+ this.#tells = new Map(tells.map(([id, tell]) => [id, { ...tell, heard: new Map(tell.heard) }]));
378+ }
379+ }
283380 this.#hasBlob = options.hasBlob ?? (() => false);
284381 this.#now = options.now;
285382 this.#whole = options.whole;
@@ -301,9 +398,11 @@
301398 throw new Error(`log entry ${at} holds no atom ${seq}`);
302399 };
303400 // Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for.
304− this.#graph = entryAt
305− ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
306− : new Graph();
401+ this.#graph = options.writerStorage
402+ ? new Graph({ storage: options.writerStorage })
403+ : entryAt
404+ ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })
405+ : new Graph();
307406 this.#views = new ViewCache(this.#graph);
308407 this.#paths = new PathIndex({
309408 graph: this.#graph,
@@ -330,12 +429,135 @@
330429 for (const entry of entries) {
331430 project.#apply(entry);
332431 project.#stored++;
432+ project.#persistMutable();
333433 }
334434 project.#loading = false;
435+ project.#writeCheckpoint();
335436 return project;
336437 }
337438
439+ /** Reopen committed writer indexes. The host supplies the authoritative canonical log length. */
440+ static openWriter(
441+ store: ProjectStore,
442+ storage: GraphStateStorage,
443+ logLength: number,
444+ options: Omit<ProjectOptions, "writerStorage"> = {},
445+ ): Project {
446+ const adoption = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
447+ if (adoption && !adoption.ready) throw new Error("writer adoption is incomplete");
448+ return Project.#openWriter(store, storage, logLength, options);
449+ }
451+ static #openWriter(
452+ store: ProjectStore,
453+ storage: GraphStateStorage,
454+ logLength: number,
455+ options: Omit<ProjectOptions, "writerStorage">,
456+ ): Project {
457+ const checkpoint = storage.read("project:meta", "checkpoint") as
458+ | { format: number; logLength: number; atoms: number; version: number }
459+ | undefined;
460+ const length = (name: string) => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
461+ if (
462+ !Number.isSafeInteger(logLength) ||
463+ logLength < 1 ||
464+ checkpoint?.format !== 1 ||
465+ checkpoint.logLength !== logLength ||
466+ storage.read("project:meta", "stored") !== logLength ||
467+ length("project:time-at") !== logLength ||
468+ length("atoms") !== checkpoint.atoms ||
469+ length("project:atom-at") !== checkpoint.atoms ||
470+ length('membership:"":versions') !== checkpoint.version + 1 ||
471+ length("project:version-at") !== checkpoint.version + 1 ||
472+ !["mods", "queue", "tells"].every((key) => Array.isArray(storage.read("project:meta", key)))
473+ )
474+ throw new Error("writer checkpoint does not match the canonical log and indexes");
475+ return new Project(store, { ...options, writerStorage: storage }, WRITER_REOPEN);
476+ }
338478 /**
479+ * Derive one bounded page from the host's canonical frames. The host reads
480+ * those frames from its own log and revalidates the source inside this same
481+ * transaction. Partial adoption cannot be opened for normal operations.
482+ */
483+ static adoptWriterPage(
484+ storage: GraphStateStorage,
485+ input: {
486+ source: WriterSource;
487+ from: number;
488+ frames: Iterable<{ seq: number; json: string }>;
489+ maxEntries: number;
490+ maxBytes: number;
491+ currentSource(): WriterSource;
492+ },
493+ options: Omit<ProjectOptions, "writerStorage"> = {},
494+ ): { next: number; ready: boolean; entries: number; bytes: number } {
495+ const same = (a: WriterSource, b: WriterSource) =>
496+ a.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion;
497+ if (
498+ ![input.source.generation, input.source.logLength, input.source.sharedVersion, input.from].every(
499+ (n) => Number.isSafeInteger(n) && n >= 0,
500+ ) ||
501+ input.source.logLength < 1 ||
502+ !Number.isSafeInteger(input.maxEntries) ||
503+ input.maxEntries < 1 ||
504+ input.maxEntries > 256 ||
505+ !Number.isSafeInteger(input.maxBytes) ||
506+ input.maxBytes < 1 ||
507+ input.maxBytes > 8_000_000
508+ )
509+ throw new Error("invalid writer adoption bounds or source");
510+ return storage.transaction(() => {
511+ if (!same(input.currentSource(), input.source))
512+ throw new Error("canonical source changed before writer adoption");
513+ const previous = storage.read("project:meta", "adoption") as WriterAdoption | undefined;
514+ if (
515+ (previous && (!same(previous.source, input.source) || previous.ready || previous.next !== input.from)) ||
516+ (!previous && input.from !== 0)
517+ )
518+ throw new Error("writer adoption source or cursor does not match");
519+ const noAppend: ProjectStore = {
520+ append: () => {
521+ throw new Error("adoption must never append canonical history");
522+ },
523+ };
524+ const project = previous
525+ ? Project.#openWriter(noAppend, storage, input.from, options)
526+ : new Project(noAppend, { ...options, writerStorage: storage });
527+ project.#loading = true;
528+ let count = 0;
529+ let bytes = 0;
530+ for (const frame of input.frames) {
531+ if (
532+ count >= input.maxEntries ||
533+ frame.seq !== input.from + count ||
534+ frame.seq >= input.source.logLength ||
535+ typeof frame.json !== "string" ||
536+ frame.json.length > input.maxBytes - bytes
537+ )
538+ throw new Error("writer adoption page exceeds bounds or has a noncontiguous frame");
539+ bytes += new TextEncoder().encode(frame.json).byteLength;
540+ if (bytes > input.maxBytes) throw new Error("writer adoption page exceeds byte bound");
541+ project.#apply(JSON.parse(frame.json) as Entry);
542+ project.#stored++;
543+ project.#persistMutable();
544+ count++;
545+ }
546+ if (count === 0) throw new Error("writer adoption page must advance");
547+ project.#loading = false;
548+ const next = input.from + count;
549+ const ready = next === input.source.logLength;
550+ if (!same(input.currentSource(), input.source))
551+ throw new Error("canonical source changed during writer adoption");
552+ if (ready && project.version !== input.source.sharedVersion)
553+ throw new Error("adopted shared version differs from canonical source");
554+ project.#writeCheckpoint();
555+ storage.write("project:meta", "adoption", { source: input.source, next, ready } satisfies WriterAdoption);
556+ return { next, ready, entries: count, bytes };
557+ });
558+ }
560+ /**
339561 * Apply more stored entries to a copy loaded for reading (#41, replay):
340562 * scrubbing forward applies only what's new. Never for the live project.
341563 */
@@ -1267,11 +1489,34 @@
12671489 #flush(_entries: readonly Entry[]): void {
12681490 if (this.#pending.length === 0) return;
12691491 const out = this.#pending;
1270− this.#pending = [];
12711492 this.#store.append(out);
1493+ this.#persistMutable();
1494+ this.#pending = [];
12721495 this.#stored += out.length;
1496+ this.#writeCheckpoint();
12731497 }
12741498
1499+ #writeCheckpoint(): void {
1500+ this.#writerStorage?.write("project:meta", "checkpoint", {
1501+ format: 1,
1502+ logLength: this.#stored,
1503+ atoms: this.#graph.size,
1504+ version: this.version,
1505+ });
1506+ }
1508+ #persistMutable(): void {
1509+ if (!this.#writerStorage) return;
1510+ if (this.#agents instanceof WriterAgents) this.#agents.flush();
1511+ this.#writerStorage.write("project:meta", "mods", this.#mods);
1512+ this.#writerStorage.write("project:meta", "queue", this.#queue);
1513+ this.#writerStorage.write(
1514+ "project:meta",
1515+ "tells",
1516+ [...this.#tells].map(([id, tell]) => [id, { ...tell, heard: [...tell.heard] }]),
1517+ );
1518+ }
12751520 /**
12761521 * The agent an entry names. Before every applied entry was stored, a call
12771522 * that joined an agent and then threw could leave the join out of the log
@@ -2217,7 +2462,12 @@
22172462 }
22182463
22192464 #agentView(agent: AgentState): View {
2220− return this.#viewKeyed(this.#agentViewKey(agent), () => this.#agentSet(agent));
2465+ return this.#viewKeyed(this.#agentViewKey(agent), () => {
2466+ const base = this.#at(this.#spaceOf(agent), agent.base);
2467+ return base instanceof StableSet
2468+ ? new StableUnionSet(base, new StableOverlaySet(agent.mine))
2469+ : new Set([...base, ...agent.mine]);
2470+ });
22212471 }
22222472
22232473 /** An agent's view, keyed by what the set is made of, not by sorting every atom in it (#46): that cost more than the work. */
--- a/worker/project/spaces.ts
+++ b/worker/project/spaces.ts
@@ -4,6 +4,14 @@
44// live here once.
55
66import type { AtomId } from "../../src/engine/index.ts";
7+import {
8+ type GraphStateStorage,
9+ StableSet,
10+ StableUnionSet,
11+ StoredMap,
12+ StoredSet,
13+ storedArray,
14+} from "../../src/engine/state-source.ts";
715import type { Entry } from "./project.ts";
917export const SHARED = "";
@@ -27,6 +35,8 @@
2735
2836export /** Shared ('') or a named draft. */
2937interface Space {
38+ /** Storage-backed spaces append the historical membership index here. */
39+ indexVersion?: (version: Published) => void;
3040 readonly name: string;
3141 readonly versions: Published[];
3242 /** Every atom published into this space (for shared, everything in it). */
@@ -39,7 +49,19 @@
3949 startedAt?: number;
4050}
4151
42−export function newSpace(name: string): Space {
52+export function newSpace(name: string, storage?: GraphStateStorage): Space {
53+ if (storage) {
54+ const prefix = `membership:${JSON.stringify(name)}`;
55+ return {
56+ name,
57+ indexVersion: (version) => indexMembership(storage, prefix, version),
58+ versions: storedArray(storage, `${prefix}:versions`),
59+ own: new StoredSet(storage, `${prefix}:own`),
60+ publishedIn: new StoredMap(storage, `${prefix}:published`),
61+ droppedIn: new StoredMap(storage, `${prefix}:dropped`),
62+ atCache: new Map(),
63+ };
64+ }
4365 return { name, versions: [], own: new Set(), publishedIn: new Map(), droppedIn: new Map(), atCache: new Map() };
4466}
4567
@@ -53,8 +75,95 @@
5375 space.own.delete(id);
5476 space.droppedIn.set(id, version.version);
5577 }
78+ space.indexVersion?.(version);
5679}
5780
81+interface MembershipEvent {
82+ version: number;
83+ present: boolean;
84+ slot: number;
85+ atom: AtomId;
86+}
88+function membershipEvent(
89+ storage: GraphStateStorage,
90+ prefix: string,
91+ atom: AtomId,
92+ version: number,
93+): MembershipEvent | undefined {
94+ const events = storedArray<MembershipEvent>(storage, `${prefix}:events:${atom}`);
95+ let lo = 0;
96+ let hi = events.length;
97+ while (lo < hi) {
98+ const mid = lo + Math.floor((hi - lo) / 2);
99+ if (events[mid]!.version <= version) lo = mid + 1;
100+ else hi = mid;
101+ }
102+ return lo === 0 ? undefined : events[lo - 1];
103+}
105+function indexMembership(storage: GraphStateStorage, prefix: string, version: Published): void {
106+ const order = storedArray<MembershipEvent>(storage, `${prefix}:events`);
107+ for (const [ids, present] of [
108+ [version.atoms, true],
109+ [version.dropped ?? [], false],
110+ ] as const) {
111+ for (const atom of ids) {
112+ const previous = membershipEvent(storage, prefix, atom, version.version);
113+ if ((previous?.present ?? false) === present) continue;
114+ const event = { atom, version: version.version, present, slot: order.length };
115+ storedArray<MembershipEvent>(storage, `${prefix}:events:${atom}`).push(event);
116+ order.push(event);
117+ }
118+ }
119+}
121+/** Immutable historical shared membership; iteration reads one event at a time. */
122+class StoredVersionSet extends StableSet<AtomId> {
123+ readonly retainedBytes = 64;
124+ readonly #storage: GraphStateStorage;
125+ readonly #prefix: string;
126+ readonly #version: number;
127+ constructor(storage: GraphStateStorage, prefix: string, version: number) {
128+ super();
129+ this.#storage = storage;
130+ this.#prefix = prefix;
131+ this.#version = version;
132+ }
133+ get [Symbol.toStringTag](): string {
134+ return "Set";
135+ }
136+ has(atom: AtomId): boolean {
137+ return membershipEvent(this.#storage, this.#prefix, atom, this.#version)?.present ?? false;
138+ }
139+ get size(): number {
140+ let count = 0;
141+ for (const _ of this) count++;
142+ return count;
143+ }
144+ *values(): SetIterator<AtomId> {
145+ const events = storedArray<MembershipEvent>(this.#storage, `${this.#prefix}:events`);
146+ for (const event of events) {
147+ if (event.version > this.#version) break;
148+ if (!event.present) continue;
149+ const selected = membershipEvent(this.#storage, this.#prefix, event.atom, this.#version);
150+ if (selected?.slot === event.slot) yield event.atom;
151+ }
152+ }
153+ keys(): SetIterator<AtomId> {
154+ return this.values();
155+ }
156+ *entries(): SetIterator<[AtomId, AtomId]> {
157+ for (const atom of this) yield [atom, atom];
158+ }
159+ [Symbol.iterator](): SetIterator<AtomId> {
160+ return this.values();
161+ }
162+ forEach(callback: (value: AtomId, key: AtomId, set: ReadonlySet<AtomId>) => void, thisArg?: unknown): void {
163+ for (const atom of this) callback.call(thisArg, atom, atom, this);
164+ }
165+}
58167export function last(space: Space): number {
59168 return space.versions.length - 1;
60169}
@@ -65,7 +174,26 @@
65174
66175/** Every space, and each one's contents at any of its versions. */
67176export class Membership {
68− readonly spaces = new Map<string, Space>([[SHARED, newSpace(SHARED)]]);
177+ readonly spaces: Map<string, Space>;
178+ readonly #storage?: GraphStateStorage;
179+ constructor(storage?: GraphStateStorage) {
180+ this.#storage = storage;
181+ if (!storage) {
182+ this.spaces = new Map([[SHARED, newSpace(SHARED)]]);
183+ return;
184+ }
185+ this.spaces = new StoredMap(storage, "membership:spaces", {
186+ encode: (space) => ({ name: space.name, startedAt: space.startedAt }),
187+ decode: (value) => {
188+ const meta = value as { name: string; startedAt?: number };
189+ return {
190+ ...newSpace(meta.name, storage),
191+ ...(meta.startedAt === undefined ? {} : { startedAt: meta.startedAt }),
192+ };
193+ },
194+ });
195+ if (!this.spaces.has(SHARED)) storage.transaction(() => this.spaces.set(SHARED, newSpace(SHARED, storage)));
196+ }
69197
70198 get shared(): Space {
71199 return this.spaces.get(SHARED)!;
@@ -73,6 +201,11 @@
73201
74202 /** What an entry (at log position `at`) does to membership; other kinds change none. */
75203 apply(entry: Entry, at: number): void {
204+ if (this.#storage) this.#storage.transaction(() => this.#apply(entry, at));
205+ else this.#apply(entry, at);
206+ }
208+ #apply(entry: Entry, at: number): void {
76209 switch (entry.type) {
77210 case "init":
78211 addVersion(this.shared, {
@@ -108,13 +241,15 @@
108241 });
109242 break;
110243 case "amend": {
111− const p = this.spaces.get(entry.space ?? SHARED)!.versions[entry.version]!;
244+ const space = this.spaces.get(entry.space ?? SHARED)!;
245+ const p = space.versions[entry.version]!;
112246 p.originalMessage ??= p.message;
113247 p.message = entry.message;
248+ space.versions[entry.version] = p;
114249 break;
115250 }
116251 case "space": {
117− const space = newSpace(entry.name);
252+ const space = newSpace(entry.name, this.#storage);
118253 space.startedAt = at;
119254 this.spaces.set(entry.name, space);
120255 addVersion(space, {
@@ -170,6 +305,18 @@
170305 * next version is applied. A caller that keeps it across an apply copies it first.
171306 */
172307 at(space: Space, version: number): ReadonlySet<AtomId> {
308+ if (this.#storage) {
309+ const own = new StoredVersionSet(this.#storage, `membership:${JSON.stringify(space.name)}`, version);
310+ if (space.name === SHARED) return own;
311+ // Named drafts add local atoms over an immutable shared base; drop
312+ // entries target shared, never a named draft's local membership.
313+ const base = new StoredVersionSet(
314+ this.#storage,
315+ `membership:${JSON.stringify(SHARED)}`,
316+ space.versions[version]!.sharedBase!,
317+ );
318+ return new StableUnionSet(base, own);
319+ }
173320 if (space.name === SHARED && version === last(space)) return space.own;
174321 let set = space.atCache.get(version);
175322 if (!set) {
--- /dev/null
+++ b/worker/project/test/project-writer-storage.test.ts
@@ -0,0 +1,142 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { storedArray } from "../../../src/engine/state-source.ts";
4+import { SqlState } from "../../../src/engine/test/storage-helper.ts";
5+import { MemoryStore, Project } from "../project.ts";
6+import type { Entry, ProjectStore } from "../project-types.ts";
7+
8+function setup() {
9+ const storage = new SqlState();
10+ const entries = storedArray<Entry>(storage, "canonical-log");
11+ let failAppend = false;
12+ const store: ProjectStore = {
13+ append(batch) {
14+ for (const entry of batch) {
15+ entries.push(entry);
16+ if (failAppend) throw new Error("injected canonical append failure");
17+ }
18+ },
19+ };
20+ return {
21+ storage,
22+ entries,
23+ store,
24+ fail: () => {
25+ failAppend = true;
26+ },
27+ recover: () => {
28+ failAppend = false;
29+ },
30+ };
31+}
33+test("actual Project record and publish use persistent graph, membership and positional indexes", (t) => {
34+ t.mock.method(Date, "now", () => 100);
35+ const { storage, entries, store } = setup();
36+ let project = new Project(store, { writerStorage: storage });
37+ t.mock.method(Project, "load", () => {
38+ throw new Error("checkpoint path must not replay the log");
39+ });
40+ const oracleLog = new MemoryStore();
41+ const oracle = new Project(oracleLog);
42+ const run = <T>(operation: (p: Project) => T) => {
43+ const expected = operation(oracle);
44+ const actual = storage.transaction(() => operation(project));
45+ assert.deepEqual(actual, expected);
46+ assert.deepEqual(project.files(), oracle.files());
47+ assert.deepEqual(project.changes(0), oracle.changes(0));
48+ assert.deepEqual(project.notes({ file: "a.txt" }), oracle.notes({ file: "a.txt" }));
49+ assert.deepEqual([...entries], oracleLog.entries);
50+ project = Project.openWriter(store, storage, entries.length);
51+ assert.deepEqual(project.files(), oracle.files(), "reopened checkpoint preserves published files");
52+ assert.deepEqual(
53+ project.status(),
54+ oracle.status(),
55+ "reopened checkpoint preserves agents, drafts and history state",
56+ );
57+ };
58+ run((p) => p.init({ "a.txt": "one\ntwo\n", "b.txt": "alpha\n" }, 0));
59+ run((p) => p.record("writer", { "a.txt": "ONE\ntwo\n" }, 1));
60+ run((p) => p.publish("writer", "Edit", 2));
61+ run((p) => p.note("writer", { file: "a.txt", from: 1, to: 1, text: "Review this", kind: "objection" }, 2));
62+ run((p) => p.record("writer", { "a.txt": "ONE\ntwo\n" }, 3));
63+ run((p) => p.record("left", { "a.txt": "LEFT\ntwo\n" }, 4));
64+ run((p) => p.record("right", { "a.txt": "RIGHT\ntwo\n" }, 5));
65+ run((p) => p.publish("left", "Left", 6));
66+ run((p) => p.publish("right", "Right", 7));
67+ run((p) => p.closeNote("writer", 1, "resolved", 8));
68+ run((p) => p.switchTo("writer", "branch", 9));
69+ run((p) => p.record("writer", { "b.txt": "BETA\n" }, 10));
70+ run((p) => p.publish("writer", "Branch edit", 11));
71+ run((p) => p.land("writer", "Land branch", 12));
72+ run((p) => p.announce("writer", "Please review", ["left"], 13));
73+ run((p) => p.news("left"));
74+ assert.deepEqual(project.position({ version: 1 }), oracle.position({ version: 1 }));
75+ assert.deepEqual(project.position({ time: 3 }), oracle.position({ time: 3 }));
76+ assert.throws(() => new Project(store, { writerStorage: storage }), /checkpoint reopen is required/);
77+ assert.throws(() => Project.openWriter(store, storage, entries.length + 1), /does not match/);
78+ storage.db.close();
79+});
81+test("queued publish survives checkpoint reopen and lands with the same candidate", () => {
82+ const { storage, entries, store } = setup();
83+ let project = new Project(store, { writerStorage: storage });
84+ project.checkerReady = true;
85+ storage.transaction(() => project.init({ "avcs.json": '{"queue":true}\n', "a.txt": "one\n" }, 0));
86+ storage.transaction(() => project.record("writer", { "a.txt": "ONE\n" }, 1));
87+ const queued = storage.transaction(() => project.publish("writer", "Queued edit", 2));
88+ assert.ok(queued.ok && "queued" in queued);
89+ const before = project.queueCandidate(1);
90+ project = Project.openWriter(store, storage, entries.length);
91+ project.checkerReady = true;
92+ assert.deepEqual(project.queueCandidate(1), before);
93+ storage.transaction(() => project.queueLand(1, 3));
94+ const reopened = Project.openWriter(store, storage, entries.length);
95+ assert.equal(reopened.files()["a.txt"], "ONE\n");
96+ assert.deepEqual(reopened.queue().items, []);
97+ storage.db.close();
98+});
100+test("failure after log append rolls back the log and persistent Project counters", (t) => {
101+ const { storage, entries, store } = setup();
102+ const project = new Project(store, { writerStorage: storage });
103+ storage.transaction(() => project.init({ "a.txt": "one\n" }, 0));
104+ const snapshot = () => storage.db.prepare("SELECT * FROM state ORDER BY collection, key").all();
105+ const before = snapshot();
106+ const length = entries.length;
107+ const write = storage.write.bind(storage);
108+ t.mock.method(storage, "write", (collection: string, key: string, value: unknown) => {
109+ if (collection === "project:meta" && key === "stored") {
110+ assert.ok(entries.length > length, "the failure occurs after the canonical append");
111+ throw new Error("injected checkpoint counter failure");
112+ }
113+ write(collection, key, value);
114+ });
115+ assert.throws(
116+ () => storage.transaction(() => project.record("writer", { "a.txt": "ONE\n" }, 1)),
117+ /checkpoint counter failure/,
118+ );
119+ assert.deepEqual(snapshot(), before);
120+ storage.db.close();
121+});
123+test("outer transaction rolls back canonical append and every Project writer index", () => {
124+ const { storage, store, entries, fail, recover } = setup();
125+ const project = new Project(store, { writerStorage: storage });
126+ storage.transaction(() => project.init({ "a.txt": "one\n" }, 0));
127+ const snapshot = () => storage.db.prepare("SELECT * FROM state ORDER BY collection, key").all();
128+ const before = snapshot();
129+ fail();
130+ assert.throws(
131+ () => storage.transaction(() => project.record("writer", { "a.txt": "ONE\n" }, 1)),
132+ /canonical append failure/,
133+ );
134+ assert.deepEqual(snapshot(), before, "log, graph, membership and positional state roll back together");
135+ // Discard the failed in-memory instance and retry from the committed root.
136+ recover();
137+ const reopened = Project.openWriter(store, storage, entries.length);
138+ storage.transaction(() => reopened.record("writer", { "a.txt": "ONE\n" }, 1));
139+ storage.transaction(() => reopened.publish("writer", "Retry", 2));
140+ assert.deepEqual(Project.openWriter(store, storage, entries.length).files(), { "a.txt": "ONE\n" });
141+ storage.db.close();
142+});
--- /dev/null
+++ b/worker/project/test/stored-membership.test.ts
@@ -0,0 +1,129 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { StoredMap, StoredSet } from "../../../src/engine/state-source.ts";
4+import { SqlState } from "../../../src/engine/test/storage-helper.ts";
5+import { MemoryStore, Project } from "../project.ts";
6+import { Membership } from "../spaces.ts";
7+
8+test("persistent collections preserve insertion order, deletion, reinsert and undefined values", () => {
9+ const storage = new SqlState();
10+ const map = new StoredMap<string, number | undefined>(storage, "map");
11+ map.set("z", 1).set("a", undefined).set("m", 3);
12+ map.delete("z");
13+ map.set("z", 4);
14+ const reopened = new StoredMap<string, number | undefined>(storage, "map");
15+ assert.equal(reopened.size, 3);
16+ assert.equal(reopened.has("a"), true);
17+ assert.deepEqual(
18+ [...reopened],
19+ [
20+ ["a", undefined],
21+ ["m", 3],
22+ ["z", 4],
23+ ],
24+ );
25+ const set = new StoredSet<string>(storage, "set");
26+ set.add("z").add("a").add("z");
27+ assert.deepEqual([...new StoredSet<string>(storage, "set")], ["z", "a"]);
28+ storage.db.close();
29+});
31+test("membership reopens stored versions and preserves historical drop and amendment semantics", () => {
32+ const log = new MemoryStore();
33+ const project = new Project(log);
34+ project.init({ "a.txt": "one\ntwo\n" }, 0);
35+ project.record("writer", { "a.txt": "ONE\ntwo\n" }, 1);
36+ assert.equal(project.publish("writer", "First edit", 2).ok, true);
37+ project.drop("writer", [1], "Undo", 3);
38+ const oracle = new Membership();
39+ const storage = new SqlState();
40+ const stored = new Membership(storage);
41+ for (const [at, entry] of log.entries.entries()) {
42+ oracle.apply(entry, at);
43+ stored.apply(entry, at);
44+ }
45+ const reads = storage.reads;
46+ const reopened = new Membership(storage);
47+ assert.equal(storage.reads - reads, 1, "reopen only checks the space directory; it does not read version history");
48+ assert.equal(storage.scans, 0);
49+ assert.deepEqual([...reopened.shared.versions], oracle.shared.versions);
50+ assert.deepEqual([...reopened.shared.own], [...oracle.shared.own]);
51+ assert.deepEqual([...reopened.shared.publishedIn], [...oracle.shared.publishedIn]);
52+ assert.deepEqual([...reopened.shared.droppedIn], [...oracle.shared.droppedIn]);
53+ for (let version = 0; version < oracle.shared.versions.length; version++) {
54+ assert.deepEqual([...reopened.at(reopened.shared, version)], [...oracle.at(oracle.shared, version)]);
55+ }
56+ const amend = { type: "amend" as const, agent: "writer", version: 1, message: "Corrected", time: 4 };
57+ reopened.apply(amend, log.entries.length);
58+ const again = new Membership(storage);
59+ assert.equal(again.shared.versions[1]?.message, "Corrected");
60+ assert.equal(again.shared.versions[1]?.originalMessage, "First edit");
61+ storage.db.close();
62+});
64+test("membership application rolls back its version and every index together", () => {
65+ const log = new MemoryStore();
66+ const project = new Project(log);
67+ project.init({ "a.txt": "one\n" }, 0);
68+ const storage = new SqlState();
69+ const membership = new Membership(storage);
70+ storage.failWrite = storage.writes + 5;
71+ assert.throws(() => membership.apply(log.entries[0]!, 0), /injected storage failure/);
72+ const reopened = new Membership(storage);
73+ assert.equal(reopened.shared.versions.length, 0);
74+ assert.equal(reopened.shared.own.size, 0);
75+ assert.equal(reopened.shared.publishedIn.size, 0);
76+ storage.failWrite = Infinity;
77+ reopened.apply(log.entries[0]!, 0);
78+ assert.equal(new Membership(storage).shared.versions.length, 1);
79+ storage.db.close();
80+});
82+test("stored membership preserves named draft bases and land across reopen", () => {
83+ const log = new MemoryStore();
84+ const project = new Project(log);
85+ project.init({ "a.txt": "one\n" }, 0);
86+ project.switchTo("writer", "branch", 1);
87+ project.record("writer", { "a.txt": "ONE\n" }, 2);
88+ assert.equal(project.publish("writer", "Branch edit", 3).ok, true);
89+ assert.equal(project.land("writer", "Land", 4).ok, true);
90+ const storage = new SqlState();
91+ const oracle = new Membership();
92+ const stored = new Membership(storage);
93+ for (const [at, entry] of log.entries.entries()) {
94+ oracle.apply(entry, at);
95+ stored.apply(entry, at);
96+ }
97+ const reopened = new Membership(storage);
98+ for (const [name, space] of oracle.spaces) {
99+ const actual = reopened.spaces.get(name)!;
100+ assert.equal(actual.startedAt, space.startedAt);
101+ assert.deepEqual([...actual.versions], space.versions);
102+ for (let version = 0; version < space.versions.length; version++)
103+ assert.deepEqual([...reopened.at(actual, version)], [...oracle.at(space, version)]);
104+ }
105+ storage.db.close();
106+});
108+test("opening an old shared membership does not hydrate its atom set", () => {
109+ const log = new MemoryStore();
110+ const project = new Project(log);
111+ project.init({ "a.txt": "zero\n" }, 0);
112+ for (let i = 1; i <= 40; i++) {
113+ project.record("writer", { "a.txt": `${i}\n` }, i * 2);
114+ assert.equal(project.publish("writer", `Edit ${i}`, i * 2 + 1).ok, true);
115+ }
116+ const storage = new SqlState();
117+ const membership = new Membership(storage);
118+ for (const [at, entry] of log.entries.entries()) membership.apply(entry, at);
119+ const reopened = new Membership(storage);
120+ const shared = reopened.shared;
121+ const reads = storage.reads;
122+ const old = reopened.at(shared, 20);
123+ assert.equal(storage.reads - reads, 0, "opening a historical membership does not read historical state");
124+ assert.equal(old.size, 41);
125+ assert.equal(old.has("a0"), true);
126+ assert.equal(old.has("a79"), false);
127+ assert.equal(shared.atCache.size, 0, "storage-backed shared history never fills the in-memory set cache");
128+ storage.db.close();
129+});
--- /dev/null
+++ b/worker/project/test/writer-adoption.test.ts
@@ -0,0 +1,101 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { SqlState } from "../../../src/engine/test/storage-helper.ts";
4+import { MemoryStore, Project, type WriterSource } from "../project.ts";
5+
6+function history() {
7+ const log = new MemoryStore();
8+ const project = new Project(log);
9+ project.init({ "a.txt": "zero\n" }, 0);
10+ for (let i = 1; i <= 8; i++) {
11+ project.record("writer", { "a.txt": `${i}\n` }, i * 2);
12+ project.publish("writer", `Edit ${i}`, i * 2 + 1);
13+ }
14+ const source: WriterSource = { generation: 8, logLength: log.entries.length, sharedVersion: project.version };
15+ const frames = log.entries.map((entry, seq) => ({ seq, json: JSON.stringify(entry) }));
16+ return { log, project, source, frames };
17+}
19+test("nonempty canonical history adopts in bounded restartable pages without Project.load", (t) => {
20+ const { log, project: oracle, source, frames } = history();
21+ t.mock.method(Project, "load", () => {
22+ throw new Error("full replay is forbidden");
23+ });
24+ const storage = new SqlState();
25+ const before = JSON.stringify(log.entries);
26+ let next = 0;
27+ while (next < frames.length) {
28+ const result = Project.adoptWriterPage(storage, {
29+ source,
30+ from: next,
31+ frames: frames.slice(next, next + 2),
32+ maxEntries: 2,
33+ maxBytes: 16_384,
34+ currentSource: () => source,
35+ });
36+ assert.ok(result.entries <= 2 && result.bytes <= 16_384);
37+ next = result.next;
38+ if (!result.ready) assert.throws(() => Project.openWriter(log, storage, next), /adoption is incomplete/);
39+ }
40+ assert.equal(JSON.stringify(log.entries), before, "adoption never rewrites or appends canonical entries");
41+ const reopened = Project.openWriter(log, storage, log.entries.length);
42+ assert.deepEqual(reopened.files(), oracle.files());
43+ assert.deepEqual(reopened.status(), oracle.status());
44+ assert.deepEqual(reopened.changes(0), oracle.changes(0));
45+ storage.transaction(() => reopened.record("writer", { "a.txt": "after adoption\n" }, 30));
46+ storage.transaction(() => reopened.publish("writer", "After adoption", 31));
47+ assert.equal(Project.openWriter(log, storage, log.entries.length).files()["a.txt"], "after adoption\n");
48+ storage.db.close();
49+});
51+test("adoption rejects stale source and rolls back a page if the source changes before commit", () => {
52+ const { source, frames } = history();
53+ const storage = new SqlState();
54+ const snapshot = () => storage.db.prepare("SELECT * FROM state ORDER BY collection, key").all();
55+ const input = { source, from: 0, frames: frames.slice(0, 2), maxEntries: 2, maxBytes: 16_384 };
56+ let calls = 0;
57+ assert.throws(
58+ () =>
59+ Project.adoptWriterPage(storage, {
60+ ...input,
61+ currentSource: () => (++calls === 1 ? source : { ...source, generation: source.generation + 1 }),
62+ }),
63+ /source changed during/,
64+ );
65+ assert.deepEqual(snapshot(), []);
66+ Project.adoptWriterPage(storage, { ...input, currentSource: () => source });
67+ const before = snapshot();
68+ assert.throws(
69+ () => Project.adoptWriterPage(storage, { ...input, currentSource: () => source }),
70+ /cursor does not match/,
71+ );
72+ assert.throws(
73+ () =>
74+ Project.adoptWriterPage(storage, {
75+ ...input,
76+ from: 2,
77+ source: { ...source, generation: 9 },
78+ currentSource: () => ({ ...source, generation: 9 }),
79+ }),
80+ /source or cursor/,
81+ );
82+ assert.deepEqual(snapshot(), before);
83+ storage.db.close();
84+});
86+test("oversized and noncontiguous adoption pages leave no partial indexes", () => {
87+ const { source, frames } = history();
88+ for (const page of [
89+ { frames: frames.slice(0, 2), maxEntries: 1, maxBytes: 16_384 },
90+ { frames: frames.slice(0, 2), maxEntries: 2, maxBytes: 1 },
91+ { frames: [frames[0]!, frames[2]!], maxEntries: 2, maxBytes: 16_384 },
92+ ]) {
93+ const storage = new SqlState();
94+ assert.throws(
95+ () => Project.adoptWriterPage(storage, { source, from: 0, currentSource: () => source, ...page }),
96+ /bounds|bound|noncontiguous/,
97+ );
98+ assert.deepEqual(storage.db.prepare("SELECT * FROM state").all(), []);
99+ storage.db.close();
100+ }
101+});
--- /dev/null
+++ b/worker/project/writer-agents.ts
@@ -0,0 +1,54 @@
1+import { type GraphStateStorage, StoredMap } from "../../src/engine/state-source.ts";
2+import type { AgentState } from "./project-types.ts";
3+
4+type StoredAgent = Omit<AgentState, "told" | "parked"> & {
5+ told: string[];
6+ parked: [string, { base: number; mine: AgentState["mine"] }][];
7+};
8+
9+/**
10+ * Identity map for agents touched by the current operation. Project's existing
11+ * reducers share mutable agent references, so copies cannot be substituted
12+ * halfway through an operation. Flush those rows with the canonical append,
13+ * then drop the references. Opening this map does not load any agents.
14+ */
15+export class WriterAgents extends StoredMap<string, AgentState> {
16+ readonly #touched = new Map<string, AgentState>();
17+ constructor(storage: GraphStateStorage) {
18+ super(storage, "project:agents", {
19+ encode: (agent) => ({ ...agent, told: [...agent.told], parked: [...agent.parked] }),
20+ decode: (value) => {
21+ const agent = value as StoredAgent;
22+ return { ...agent, told: new Set(agent.told), parked: new Map(agent.parked) };
23+ },
24+ });
25+ }
26+ override get(key: string): AgentState | undefined {
27+ let value = this.#touched.get(key);
28+ if (!value) {
29+ value = super.get(key);
30+ if (value) this.#touched.set(key, value);
31+ }
32+ return value;
33+ }
34+ override set(key: string, value: AgentState): this {
35+ super.set(key, value);
36+ this.#touched.set(key, value);
37+ return this;
38+ }
39+ override delete(key: string): boolean {
40+ this.#touched.delete(key);
41+ return super.delete(key);
42+ }
43+ override *entries(): MapIterator<[string, AgentState]> {
44+ for (const [key, stored] of super.entries()) {
45+ let value = this.#touched.get(key);
46+ if (!value) this.#touched.set(key, (value = stored));
47+ yield [key, value];
48+ }
49+ }
50+ flush(): void {
51+ for (const [key, value] of this.#touched) super.set(key, value);
52+ this.#touched.clear();
53+ }
54+}