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

Integrate reviewed disk-backed operations, queue and bounded read caches

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

Version 162 · Files at version 163

23 files, 701 lines added, 24 removed.

--- a/server/src/decoded-frames.ts
+++ b/server/src/decoded-frames.ts
@@ -2,6 +2,7 @@
22import type { WriterAdoptionFrame } from "../../worker/project/project.ts";
33import type { Entry } from "../../worker/project/project-types.ts";
44import type { SqliteLog, SqliteStorage } from "./engine-project.ts";
5+import { smallFrameJson } from "./small-frame-json.ts";
56import { StoredJson, storeJson } from "./stored-json.ts";
67import { storedJsonView } from "./stored-json-view.ts";
78import { SqliteWriterState, writerFrameChunksDigest } from "./writer-host.ts";
@@ -26,7 +27,7 @@
2627 return storage.transactionSync(() => {
2728 SqliteWriterState.initialize(storage);
2829 const state = new SqliteWriterState(storage, namespace);
29− // Temporary nodes are immutable after parsing; cap retained reads for the whole page.
30+ // Bound cached reads across all disk-backed frames in this page.
3031 const reads = new CachedStateStorage(state, 64 * 1024, 256);
3132 if (
3233 storage.sql.exec("SELECT 1 AS present FROM writer_state WHERE namespace = ? LIMIT 1", namespace).toArray().length
@@ -44,9 +45,13 @@
4445 throw Error("decoded frame exceeds page byte bound");
4546 }
4647 digest = writerFrameChunksDigest(digest, seq, log.frameChunks(seq));
47− storeJson(state, String(seq), log.frameChunks(seq));
4848 bytes += size;
49− yield { seq, bytes: size, entry: storedJsonView(new StoredJson(reads, String(seq))) as Entry };
49+ if (size <= 4096) {
50+ yield { seq, bytes: size, entry: smallFrameJson(log.frameChunks(seq)) as Entry };
51+ } else {
52+ storeJson(state, String(seq), log.frameChunks(seq));
53+ yield { seq, bytes: size, entry: storedJsonView(new StoredJson(reads, String(seq))) as Entry };
54+ }
5055 }
5156 };
5257 try {
--- /dev/null
+++ b/server/src/small-frame-json.ts
@@ -0,0 +1,15 @@
1+import { jsonEvents } from "./json-events.ts";
2+
3+/** Decode a small canonical frame with the same validation as the streamed path. */
4+export function smallFrameJson(chunks: Iterable<string>): unknown {
5+ let text = "";
6+ for (const chunk of chunks) {
7+ if (text.length + chunk.length > 4096) throw Error("small canonical frame exceeds bound");
8+ text += chunk;
9+ }
10+ // Count UTF-8 after joining so a surrogate pair split across chunks counts once.
11+ if (new TextEncoder().encode(text).byteLength > 4096) throw Error("small canonical frame exceeds bound");
12+ // Preserve depth, key and scalar limits; the fast path must not change acceptance.
13+ for (const event of jsonEvents([text])) void event;
14+ return JSON.parse(text);
15+}
--- /dev/null
+++ b/server/test/decoded-frames-small.test.ts
@@ -0,0 +1,72 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { withDecodedFrames } from "../src/decoded-frames.ts";
4+import { logParts, SqliteLog } from "../src/engine-project.ts";
5+import { SqliteWriterState, writerFrameDigest } from "../src/writer-host.ts";
6+import { memoryStorage } from "./helpers.ts";
7+
8+test("decoded frame pages retain views through consumption and remove scratch on all exits", (t) => {
9+ const storage = memoryStorage();
10+ t.after(() => storage.db.close());
11+ const log = new SqliteLog(storage);
12+ const json = JSON.stringify({ type: "join", agent: "alice", version: 0 });
13+ for (const [part, text] of logParts(json).entries())
14+ storage.sql.exec("INSERT INTO log(seq,part,text) VALUES(?,?,?)", 0, part, text);
15+ SqliteWriterState.initialize(storage);
16+ const before = storage.db.prepare("SELECT * FROM writer_state").all();
17+ const input = { from: 0, to: 1, maxEntries: 1, maxBytes: 1000, digest: "" };
18+ const result = withDecodedFrames(storage, "decoded-page", log, input, (frames) => {
19+ const frame = [...frames][0]!;
20+ assert.ok("entry" in frame);
21+ assert.equal(frame.entry.type, "join");
22+ assert.equal(
23+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?").get("decoded-page")!.n,
24+ 0,
25+ );
26+ return frame.entry.type;
27+ });
28+ assert.equal(result.result, "join");
29+ assert.equal(result.digest, writerFrameDigest("", 0, json));
30+ assert.deepEqual(storage.db.prepare("SELECT * FROM writer_state").all(), before);
31+ assert.throws(
32+ () =>
33+ withDecodedFrames(storage, "decoded-page", log, input, (frames) => {
34+ [...frames];
35+ throw Error("consumer failure");
36+ }),
37+ /consumer failure/,
38+ );
39+ assert.deepEqual(storage.db.prepare("SELECT * FROM writer_state").all(), before);
40+});
42+test("frames above the small bound still use temporary disk storage", (t) => {
43+ const storage = memoryStorage();
44+ t.after(() => storage.db.close());
45+ const log = new SqliteLog(storage);
46+ const agent = "a".repeat(5000);
47+ const json = JSON.stringify({ type: "join", agent, version: 0 });
48+ for (const [part, text] of logParts(json).entries())
49+ storage.sql.exec("INSERT INTO log(seq,part,text) VALUES(?,?,?)", 0, part, text);
50+ const result = withDecodedFrames(
51+ storage,
52+ "large-decoded-page",
53+ log,
54+ { from: 0, to: 1, maxEntries: 1, maxBytes: 10000, digest: "" },
55+ (frames) => {
56+ const frame = [...frames][0]!;
57+ assert.ok("entry" in frame);
58+ assert.ok(
59+ Number(
60+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?").get("large-decoded-page")!.n,
61+ ) > 0,
62+ );
63+ assert.equal((frame.entry as { agent: string }).agent, agent);
64+ return frame.entry.type;
65+ },
66+ );
67+ assert.equal(result.result, "join");
68+ assert.equal(
69+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?").get("large-decoded-page")!.n,
70+ 0,
71+ );
72+});
--- a/server/test/project-object-disk-first.test.ts
+++ b/server/test/project-object-disk-first.test.ts
@@ -285,8 +285,13 @@
285285 throw Error("empty test repository");
286286 });
287287 let pushed = 0;
288+ let failPush = true;
288289 let remoteFiles: MemoryFS | undefined;
289290 t.mock.method(git, "push", async (options: Parameters<typeof git.push>[0]) => {
291+ if (failPush) {
292+ failPush = false;
293+ throw Error("injected Artifacts transport failure");
294+ }
290295 const oid = await git.resolveRef({ fs: options.fs, dir: options.dir, ref: "main" });
291296 const commit = await git.readCommit({ fs: options.fs, dir: options.dir, oid });
292297 assert.match(commit.commit.message, /abso-version: 2/);
@@ -304,8 +309,17 @@
304309 }),
305310 };
306311 const bound = () => new ProjectObject(context as never, { ABSO_DISK_FIRST: "on", ARTIFACTS: artifacts } as never);
312+ // Deliver the pending alarm: the fake storage must clear it as the host does.
313+ alarm = null;
307314 await bound().alarm();
315+ assert.equal(pushed, 0);
316+ assert.equal(values.get("pushed"), undefined, "failed transport must not acknowledge a push");
317+ assert.match(JSON.stringify(values.get("pushError")), /injected Artifacts transport failure/);
318+ assert.deepEqual(rows(), stable, "failed remote transport leaves canonical state unchanged");
319+ assert.ok(alarm !== null && alarm > Date.now(), "failed transport schedules a retry");
320+ await bound().alarm();
308321 assert.equal(pushed, 1);
322+ assert.equal(values.get("pushError"), undefined, "cold retry clears the transport error");
309323 assert.equal((await bound().out()).pushed?.version, 2);
310324 assert.deepEqual(rows(), stable, "pushing shared does not mutate canonical project state");
311325 await bound().alarm();
--- /dev/null
+++ b/server/test/projected-compare.test.ts
@@ -0,0 +1,36 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { answer } from "../../worker/project/http.ts";
4+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts";
5+import { memoryStorage } from "./helpers.ts";
6+
7+test("disk runtime compares published versions through indexed views", (t) => {
8+ const storage = memoryStorage();
9+ t.after(() => storage.db.close());
10+ const runtime = () => new DiskFirstRuntime(storage, "compare", "compare");
11+ runtime().initialize(
12+ (c) => answer(c, "init", undefined, { files: { "a.txt": "before\n" } }),
13+ () => {},
14+ );
15+ while (!runtime().preparePage(() => {}).ready) {}
16+ assert.equal(
17+ runtime().write(
18+ (c) => answer(c, "record", "alice", { files: { "a.txt": "after\n" } }),
19+ () => {},
20+ ).status,
21+ 200,
22+ );
23+ assert.equal(
24+ runtime().write(
25+ (c) => answer(c, "publish", "alice", { message: "change" }),
26+ () => {},
27+ ).status,
28+ 200,
29+ );
30+ const result = runtime().read(
31+ (c) => answer(c, "compare", undefined, { from: 0, to: 1 }),
32+ () => {},
33+ );
34+ assert.equal(result.status, 200, JSON.stringify(result));
35+ assert.equal((result.body as { files: unknown[] }).files.length, 1);
36+});
--- /dev/null
+++ b/server/test/projected-diff.test.ts
@@ -0,0 +1,31 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { answer } from "../../worker/project/http.ts";
4+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts";
5+import { memoryStorage } from "./helpers.ts";
6+
7+test("disk runtime reads the unpublished diff from indexed membership", (t) => {
8+ const storage = memoryStorage();
9+ t.after(() => storage.db.close());
10+ const runtime = () => new DiskFirstRuntime(storage, "diff", "diff");
11+ runtime().initialize(
12+ (c) => answer(c, "init", undefined, { files: { "a.txt": "before\n" } }),
13+ () => {},
14+ );
15+ while (!runtime().preparePage(() => {}).ready) {}
16+ assert.equal(
17+ runtime().write(
18+ (c) => answer(c, "record", "alice", { files: { "a.txt": "after\n" } }),
19+ () => {},
20+ ).status,
21+ 200,
22+ );
23+ const result = runtime().write(
24+ (c) => answer(c, "diff", "alice", {}),
25+ () => {},
26+ );
27+ assert.equal(result.status, 200, JSON.stringify(result));
28+ assert.deepEqual((result.body as { files: unknown }).files, [
29+ { path: "a.txt", before: "before\n", after: "after\n" },
30+ ]);
31+});
--- /dev/null
+++ b/server/test/projected-move-sync.test.ts
@@ -0,0 +1,51 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { answer } from "../../worker/project/http.ts";
4+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts";
5+import { memoryStorage } from "./helpers.ts";
6+
7+test("disk runtime syncs overlapping edits after a published move", (t) => {
8+ const storage = memoryStorage();
9+ t.after(() => storage.db.close());
10+ const runtime = () => new DiskFirstRuntime(storage, "sync", "sync");
11+ runtime().initialize(
12+ (c) => answer(c, "init", undefined, { files: { "a.txt": "one\ntwo\nthree\n" } }),
13+ () => {},
14+ );
15+ while (!runtime().preparePage(() => {}).ready) {}
16+ const call = (op: string, agent: string, body: unknown) =>
17+ runtime().write(
18+ (c) => answer(c, op, agent, body),
19+ () => {},
20+ );
21+ assert.equal(call("move", "alice", { from: "a.txt", to: "b.txt" }).status, 200);
22+ assert.equal(call("publish", "alice", { message: "Move" }).status, 200);
23+ for (const agent of ["alice", "bob"]) assert.equal(call("sync", agent, {}).status, 200);
24+ assert.equal(call("record", "alice", { files: { "b.txt": "one\nalice\nthree\n" } }).status, 200);
25+ assert.equal(call("record", "bob", { files: { "b.txt": "one\nbob\nthree\n" } }).status, 200);
26+ assert.equal(call("publish", "alice", { message: "alice" }).status, 200);
27+ const result = {
28+ status: 200,
29+ body: runtime().write(
30+ (c) => c.sync("bob"),
31+ () => {},
32+ ),
33+ };
34+ assert.equal(result.status, 200, JSON.stringify(result));
35+ const body = result.body as {
36+ version: number;
37+ files: Record<string, string>;
38+ collisions: { kind: string; marked?: boolean }[];
39+ };
40+ assert.equal(body.version, 2);
41+ assert.equal(body.collisions.length, 1);
42+ assert.equal(body.collisions[0]!.kind, "lines");
43+ assert.equal(body.collisions[0]!.marked, true);
44+ assert.match(body.files["b.txt"]!, /<<<<<<< yours/);
45+ assert.match(body.files["b.txt"]!, /bob/);
46+ assert.match(body.files["b.txt"]!, /alice/);
47+ const repeated = call("sync", "bob", {});
48+ assert.equal(repeated.status, 200);
49+ assert.equal((repeated.body as typeof body).collisions.length, 1);
50+ assert.equal((repeated.body as typeof body).collisions[0]!.marked, true);
51+});
--- /dev/null
+++ b/server/test/projected-move.test.ts
@@ -0,0 +1,35 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { answer } from "../../worker/project/http.ts";
4+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts";
5+import { memoryStorage } from "./helpers.ts";
6+
7+test("disk runtime moves a text file without using a stale reader", (t) => {
8+ const storage = memoryStorage();
9+ t.after(() => storage.db.close());
10+ const runtime = () => new DiskFirstRuntime(storage, "move", "move");
11+ runtime().initialize(
12+ (c) => answer(c, "init", undefined, { files: { "a.txt": "one\ntwo\n" } }),
13+ () => {},
14+ );
15+ while (!runtime().preparePage(() => {}).ready) {}
16+ const result = runtime().write(
17+ (c) => answer(c, "move", "alice", { from: "a.txt", to: "b.txt" }),
18+ () => {},
19+ );
20+ assert.equal(result.status, 200, JSON.stringify(result));
21+ assert.equal(
22+ runtime().write(
23+ (c) => answer(c, "publish", "alice", { message: "move" }),
24+ () => {},
25+ ).status,
26+ 200,
27+ );
28+ assert.deepEqual(
29+ runtime().read(
30+ (c) => c.shared().files,
31+ () => {},
32+ ),
33+ { "b.txt": "one\ntwo\n" },
34+ );
35+});
--- /dev/null
+++ b/server/test/projected-queue.test.ts
@@ -0,0 +1,182 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { answer } from "../../worker/project/http.ts";
4+import type { Project } from "../../worker/project/project.ts";
5+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts";
6+import { memoryStorage } from "./helpers.ts";
7+
8+test("disk queue preserves a dropped base without restoring dropped changes", (t) => {
9+ const storage = memoryStorage();
10+ t.after(() => storage.db.close());
11+ const runtime = () => new DiskFirstRuntime(storage, "queue-drop", "queue-drop");
12+ runtime().initialize(
13+ (c) => answer(c, "init", undefined, { files: { "avcs.json": '{"queue":true}', "a.txt": "before\n" } }),
14+ () => {},
15+ );
16+ while (!runtime().preparePage(() => {}).ready) {}
17+ runtime().write(
18+ (c) => {
19+ assert.equal(answer(c, "record", "alice", { files: { "a.txt": "temporary\n" } }).status, 200);
20+ assert.equal(answer(c, "publish", "alice", { message: "Temporary" }).status, 200);
21+ c.sync("old");
22+ assert.equal(c.drop("alice", [1], "Undo temporary").ok, true);
23+ },
24+ () => {},
25+ );
26+ for (const [agent, file] of [
27+ ["ahead", "ahead.txt"],
28+ ["old", "old.txt"],
29+ ] as const) {
30+ runtime().write(
31+ (c) => {
32+ c.setCheckerReady(true);
33+ assert.equal(answer(c, "record", agent, { files: { [file]: `${agent}\n` } }).status, 200);
34+ const result = answer(c, "publish", agent, { message: agent });
35+ assert.equal(result.status, 200, JSON.stringify(result));
36+ assert.equal((result.body as { queued: number }).queued, agent === "ahead" ? 1 : 2);
37+ },
38+ () => {},
39+ );
40+ }
41+ const candidate = runtime().read(
42+ (c) => (c as unknown as { project: Project }).project.queueCandidate(2),
43+ () => {},
44+ );
45+ assert.equal(candidate.files["a.txt"], "before\n");
46+ assert.equal(candidate.files["ahead.txt"], "ahead\n");
47+ assert.equal(candidate.files["old.txt"], "old\n");
48+});
50+test("disk runtime builds and lands a queued candidate", (t) => {
51+ const storage = memoryStorage();
52+ t.after(() => storage.db.close());
53+ const runtime = () => new DiskFirstRuntime(storage, "queue", "queue");
54+ runtime().initialize(
55+ (c) => answer(c, "init", undefined, { files: { "avcs.json": '{"queue":true}', "a.txt": "before\n" } }),
56+ () => {},
57+ );
58+ while (!runtime().preparePage(() => {}).ready) {}
59+ runtime().write(
60+ (c) => {
61+ c.setCheckerReady(true);
62+ assert.equal(answer(c, "record", "alice", { files: { "a.txt": "after\n" } }).status, 200);
63+ const result = answer(c, "publish", "alice", { message: "Queued" });
64+ assert.equal((result.body as { queued: number }).queued, 1);
65+ },
66+ () => {},
67+ );
68+ // Queue-driver methods are internal to the Project adapter, not public HTTP commands.
69+ const candidate = runtime().read(
70+ (c) => (c as unknown as { project: Project }).project.queueCandidate(1),
71+ () => {},
72+ );
73+ assert.equal(candidate.files["a.txt"], "after\n");
74+ const landed = runtime().write(
75+ (c) => (c as unknown as { project: Project }).project.queueLand(1, 10),
76+ () => {},
77+ );
78+ assert.deepEqual(landed.versions, [{ id: 1, version: 1 }]);
79+ assert.equal(
80+ runtime().read(
81+ (c) => c.shared().files["a.txt"],
82+ () => {},
83+ ),
84+ "after\n",
85+ );
86+});
88+test("disk runtime builds and lands two queued candidates in order", (t) => {
89+ const storage = memoryStorage();
90+ t.after(() => storage.db.close());
91+ const runtime = () => new DiskFirstRuntime(storage, "queue", "queue");
92+ runtime().initialize(
93+ (c) => answer(c, "init", undefined, { files: { "avcs.json": '{"queue":true}', "a.txt": "before\n" } }),
94+ () => {},
95+ );
96+ while (!runtime().preparePage(() => {}).ready) {}
97+ runtime().write(
98+ (c) => {
99+ c.setCheckerReady(true);
100+ assert.equal(answer(c, "record", "alice", { files: { "a.txt": "after\n" } }).status, 200);
101+ const result = answer(c, "publish", "alice", { message: "Queued" });
102+ assert.equal((result.body as { queued: number }).queued, 1);
103+ },
104+ () => {},
105+ );
106+ runtime().write(
107+ (c) => {
108+ c.setCheckerReady(true);
109+ assert.equal(answer(c, "record", "bob", { files: { "b.txt": "second\n" } }).status, 200);
110+ const result = answer(c, "publish", "bob", { message: "Second" });
111+ assert.equal(result.status, 200, JSON.stringify(result));
112+ assert.equal((result.body as { queued: number }).queued, 2);
113+ },
114+ () => {},
115+ );
116+ // Queue-driver methods are internal to the Project adapter, not public HTTP commands.
117+ const candidate = runtime().read(
118+ (c) => (c as unknown as { project: Project }).project.queueCandidate(2),
119+ () => {},
120+ );
121+ assert.equal(candidate.files["a.txt"], "after\n");
122+ assert.equal(candidate.files["b.txt"], "second\n");
123+ const landed = runtime().write(
124+ (c) => (c as unknown as { project: Project }).project.queueLand(2, 10),
125+ () => {},
126+ );
127+ assert.deepEqual(landed.versions, [
128+ { id: 1, version: 1 },
129+ { id: 2, version: 2 },
130+ ]);
131+ assert.equal(
132+ runtime().read(
133+ (c) => c.shared().files["a.txt"],
134+ () => {},
135+ ),
136+ "after\n",
137+ );
138+});
140+test("disk queue refuses overlapping edits and accepts an older nonconflicting base", (t) => {
141+ const storage = memoryStorage();
142+ t.after(() => storage.db.close());
143+ const runtime = () => new DiskFirstRuntime(storage, "queue-edge", "queue-edge");
144+ runtime().initialize(
145+ (c) => answer(c, "init", undefined, { files: { "avcs.json": '{"queue":true}', "a.txt": "before\n" } }),
146+ () => {},
147+ );
148+ while (!runtime().preparePage(() => {}).ready) {}
149+ const call = (op: string, agent: string, body: unknown) =>
150+ runtime().write(
151+ (c) => {
152+ c.setCheckerReady(true);
153+ return answer(c, op, agent, body);
154+ },
155+ () => {},
156+ );
157+ for (const agent of ["alice", "bob", "old"]) assert.equal(call("sync", agent, {}).status, 200);
158+ assert.equal(call("record", "alice", { files: { "a.txt": "alice\n" } }).status, 200);
159+ assert.equal((call("publish", "alice", { message: "Alice" }).body as { queued: number }).queued, 1);
160+ assert.equal(call("record", "bob", { files: { "a.txt": "bob\n" } }).status, 200);
161+ const refused = call("publish", "bob", { message: "Bob conflict" });
162+ assert.equal(refused.status, 200, JSON.stringify(refused));
163+ assert.equal((refused.body as { ok: boolean }).ok, false);
164+ assert.ok((refused.body as { collisions: unknown[] }).collisions.length > 0);
165+ runtime().write(
166+ (c) => (c as unknown as { project: Project }).project.queueLand(1, 20),
167+ () => {},
168+ );
169+ assert.equal(call("record", "alice", { files: { "next.txt": "next\n" } }).status, 200);
170+ assert.equal((call("publish", "alice", { message: "Next" }).body as { queued: number }).queued, 2);
171+ assert.equal(call("record", "old", { files: { "old.txt": "old base\n" } }).status, 200);
172+ const queued = call("publish", "old", { message: "Old base" });
173+ assert.equal(queued.status, 200, JSON.stringify(queued));
174+ assert.equal((queued.body as { queued: number }).queued, 3);
175+ const candidate = runtime().read(
176+ (c) => (c as unknown as { project: Project }).project.queueCandidate(2),
177+ () => {},
178+ );
179+ assert.equal(candidate.files["a.txt"], "alice\n");
180+ assert.equal(candidate.files["next.txt"], "next\n");
181+ assert.equal(candidate.files["old.txt"], "old base\n");
182+});
--- /dev/null
+++ b/server/test/projected-restore.test.ts
@@ -0,0 +1,69 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { answer } from "../../worker/project/http.ts";
4+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts";
5+import { memoryStorage } from "./helpers.ts";
6+
7+test("disk runtime restores unpublished files and preserves published history", (t) => {
8+ const storage = memoryStorage();
9+ t.after(() => storage.db.close());
10+ const runtime = () => new DiskFirstRuntime(storage, "restore", "restore");
11+ runtime().initialize(
12+ (c) => answer(c, "init", undefined, { files: { "a.txt": "original\n", "b.txt": "kept\n" } }),
13+ () => {},
14+ );
15+ while (!runtime().preparePage(() => {}).ready) {}
16+ const call = (op: string, body: unknown) =>
17+ runtime().write(
18+ (c) => answer(c, op, "alice", body),
19+ () => {},
20+ );
21+ assert.equal(call("record", { files: { "a.txt": "changed\n", "b.txt": "different\n" } }).status, 200);
22+ const result = call("restore", { all: true });
23+ assert.equal(result.status, 200, JSON.stringify(result));
24+ assert.deepEqual((result.body as { files: unknown }).files, { "a.txt": "original\n", "b.txt": "kept\n" });
25+ assert.deepEqual(
26+ runtime().read(
27+ (c) => c.shared().files,
28+ () => {},
29+ ),
30+ { "a.txt": "original\n", "b.txt": "kept\n" },
31+ );
32+});
34+for (const queued of [false, true]) {
35+ test(`disk restore preserves ${queued ? "queued" : "untargeted"} edits`, (t) => {
36+ const storage = memoryStorage();
37+ t.after(() => storage.db.close());
38+ const runtime = () => new DiskFirstRuntime(storage, "partial", "partial");
39+ runtime().initialize(
40+ (c) =>
41+ answer(c, "init", undefined, {
42+ files: { "avcs.json": JSON.stringify({ queue: queued }), "a.txt": "original\n", "b.txt": "original b\n" },
43+ }),
44+ () => {},
45+ );
46+ while (!runtime().preparePage(() => {}).ready) {}
47+ const call = (op: string, body: unknown) =>
48+ runtime().write(
49+ (c) => {
50+ c.setCheckerReady(true);
51+ return answer(c, op, "alice", body);
52+ },
53+ () => {},
54+ );
55+ assert.equal(call("record", { files: { "b.txt": "preserved\n" } }).status, 200);
56+ if (queued) {
57+ const published = call("publish", { message: "queued work" });
58+ assert.equal(published.status, 200, JSON.stringify(published));
59+ assert.equal((published.body as { queued?: number }).queued, 1);
60+ }
61+ assert.equal(call("record", { files: { "a.txt": "discard me\n" } }).status, 200);
62+ const restored = call("restore", queued ? { all: true } : { files: ["a.txt"] });
63+ assert.equal(restored.status, 200, JSON.stringify(restored));
64+ assert.deepEqual((restored.body as { files: unknown }).files, { "a.txt": "original\n" });
65+ const synced = call("sync", {});
66+ assert.equal(synced.status, 200, JSON.stringify(synced));
67+ assert.equal((synced.body as { files: Record<string, string> }).files["b.txt"], "preserved\n");
68+ });
69+}
--- /dev/null
+++ b/server/test/projected-sync.test.ts
@@ -0,0 +1,43 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { answer } from "../../worker/project/http.ts";
4+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts";
5+import { memoryStorage } from "./helpers.ts";
6+
7+test("disk runtime syncs overlapping edits without unkeyed membership", (t) => {
8+ const storage = memoryStorage();
9+ t.after(() => storage.db.close());
10+ const runtime = () => new DiskFirstRuntime(storage, "sync", "sync");
11+ runtime().initialize(
12+ (c) => answer(c, "init", undefined, { files: { "a.txt": "one\ntwo\nthree\n" } }),
13+ () => {},
14+ );
15+ while (!runtime().preparePage(() => {}).ready) {}
16+ const call = (op: string, agent: string, body: unknown) =>
17+ runtime().write(
18+ (c) => answer(c, op, agent, body),
19+ () => {},
20+ );
21+ for (const agent of ["alice", "bob"]) assert.equal(call("sync", agent, {}).status, 200);
22+ assert.equal(call("record", "alice", { files: { "a.txt": "one\nalice\nthree\n" } }).status, 200);
23+ assert.equal(call("record", "bob", { files: { "a.txt": "one\nbob\nthree\n" } }).status, 200);
24+ assert.equal(call("publish", "alice", { message: "alice" }).status, 200);
25+ const result = call("sync", "bob", {});
26+ assert.equal(result.status, 200, JSON.stringify(result));
27+ const body = result.body as {
28+ version: number;
29+ files: Record<string, string>;
30+ collisions: { kind: string; marked?: boolean }[];
31+ };
32+ assert.equal(body.version, 1);
33+ assert.equal(body.collisions.length, 1);
34+ assert.equal(body.collisions[0]!.kind, "lines");
35+ assert.equal(body.collisions[0]!.marked, true);
36+ assert.match(body.files["a.txt"]!, /<<<<<<< yours/);
37+ assert.match(body.files["a.txt"]!, /bob/);
38+ assert.match(body.files["a.txt"]!, /alice/);
39+ const repeated = call("sync", "bob", {});
40+ assert.equal(repeated.status, 200);
41+ assert.equal((repeated.body as typeof body).collisions.length, 1);
42+ assert.equal((repeated.body as typeof body).collisions[0]!.marked, true);
43+});
--- /dev/null
+++ b/server/test/small-frame-json.test.ts
@@ -0,0 +1,21 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { smallFrameJson } from "../src/small-frame-json.ts";
4+
5+test("small frame decoding enforces a byte bound and streamed parser rules", () => {
6+ assert.deepEqual(smallFrameJson(['{"type":"jo', 'in","agent":"alice"}']), { type: "join", agent: "alice" });
7+ assert.deepEqual(smallFrameJson(['{"x":1,"x":2}']), { x: 2 });
8+ assert.throws(() => smallFrameJson(['"' + "\u00e9".repeat(2048) + '"']), /exceeds bound/);
9+ assert.throws(() => smallFrameJson(["[".repeat(130) + "0" + "]".repeat(130)]), /nesting/);
10+ assert.throws(() => smallFrameJson(["1" + "0".repeat(256)]), /scalar/);
11+ assert.throws(() => smallFrameJson(["{} trailing"]), /trailing/);
12+});
13+test("small frame byte accounting handles a split surrogate pair at the limit", () => {
14+ const pair = String.fromCodePoint(0x1f600);
15+ const body = "x".repeat(4090) + pair;
16+ const json = JSON.stringify(body);
17+ assert.equal(new TextEncoder().encode(json).byteLength, 4096);
18+ const split = json.indexOf(pair) + 1;
19+ assert.equal(smallFrameJson([json.slice(0, split), json.slice(split)]), body);
20+ assert.throws(() => smallFrameJson([JSON.stringify(body + "x")]), /exceeds bound/);
21+});
--- a/src/engine/experimental/projection-reader.ts
+++ b/src/engine/experimental/projection-reader.ts
@@ -175,9 +175,21 @@
175175 fileOf(line: string): string {
176176 this.#assertLive();
177177 if (line.startsWith("^")) return line.slice(1);
178− const marker = this.#adapter.markers.get(this.#state.locator, this.graph.lineN(line) + 1);
179− if (marker?.kind !== "line") throw Error("missing projected line");
180− return this.#adapter.sequence.fileAt(this.#state.sequence, marker.enter);
178+ let current = line;
179+ while (!current.startsWith("^")) {
180+ const n = this.graph.lineN(current);
181+ if (n < 0) throw Error("unknown projected line");
182+ const marker = this.#adapter.markers.get(this.#state.locator, n + 1);
183+ if (marker?.kind === "line") return this.#adapter.sequence.fileAt(this.#state.sequence, marker.enter);
184+ // A line written outside this view has no marker. Follow canonical ancestry
185+ // until it reaches a line whose placement this view actually contains.
186+ if (marker || this.#adapter.members.get(this.#state.membership, this.graph.writerSeqOf(n))?.present)
187+ throw Error("missing projected line");
188+ const parent = this.graph.lineParent(current);
189+ if (parent === undefined) throw Error("missing projected line parent");
190+ current = parent;
191+ }
192+ return current.slice(1);
181193 }
182194 text(path: string): string {
183195 this.#assertLive();
--- a/src/engine/experimental/projection-sequence.ts
+++ b/src/engine/experimental/projection-sequence.ts
@@ -143,7 +143,21 @@
143143 // One operation changes an AVL path plus rotation neighbors, not history.
144144 // Keep only those decoded records and persist each final record once.
145145 const changed = new Map<number, SequenceNode>();
146− const get = (id: number): SequenceNode => changed.get(id) ?? this.get(map, id);
146+ // The immutable input map is fixed for this batch. Cache only its bounded reads;
147+ // changed nodes always take precedence and the cache never survives a transaction.
148+ const original = new Map<number, SequenceNode>();
149+ let originalBytes = 0;
150+ const get = (id: number): SequenceNode => {
151+ const found = changed.get(id) ?? original.get(id);
152+ if (found) return found;
153+ const node = this.get(map, id);
154+ const bytes = 192 + node.text.length * 2;
155+ if (original.size < 256 && originalBytes + bytes <= 65536) {
156+ original.set(id, node);
157+ originalBytes += bytes;
158+ }
159+ return node;
160+ };
147161 const put = (node: SequenceNode): number => {
148162 changed.set(node.id, node);
149163 return node.id;
--- a/src/engine/test/projection-sequence.test.ts
+++ b/src/engine/test/projection-sequence.test.ts
@@ -47,3 +47,28 @@
4747 storage.db.close();
4848 }
4949});
51+test("sequence batches match individual updates and retry after rollback", () => {
52+ const storage = new SqlState();
53+ try {
54+ const sequence = new ProjectionSequence(storage, "batch-cache");
55+ let state = sequence.empty();
56+ for (let i = 0; i < 48; i++) state = sequence.update(state, { kind: "insert", rank: i, text: String(i) });
57+ const before = state;
58+ const operations = Array.from({ length: 16 }, (_, i) => ({ kind: "visibility" as const, id: i, delta: 1 }));
59+ const rows = () => JSON.stringify(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all());
60+ const original = rows();
61+ storage.failWrite = storage.writes + 3;
62+ assert.throws(() => sequence.updateMany(before, operations), /injected/);
63+ assert.equal(rows(), original);
64+ storage.failWrite = Infinity;
65+ const batch = sequence.updateMany(before, operations);
66+ let individual = before;
67+ for (const operation of operations) individual = sequence.update(individual, operation);
68+ assert.deepEqual([...sequence.values(batch)], [...sequence.values(individual)]);
69+ assert.equal([...sequence.values(before)].length, 48);
70+ assert.equal([...sequence.values(batch)].length, 32);
71+ } finally {
72+ storage.db.close();
73+ }
74+});
--- a/worker/project/draft-diff.ts
+++ b/worker/project/draft-diff.ts
@@ -18,6 +18,7 @@
1818 needInit(): void;
1919 draft(agent: Agent): AtomId[];
2020 agentView(agent: Agent): ReadView;
21+ agentViewWithout?(agent: Agent, excluded: ReadonlySet<AtomId>): ReadView;
2122 view(set: ReadonlySet<AtomId>): ReadView;
2223 touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;
2324}
@@ -35,7 +36,9 @@
3536 const draft = host.draft(agent);
3637 const after = host.agentView(agent);
3738 const without = new Set(draft);
38− const before = host.view(new Set([...after.set].filter((id) => !without.has(id))));
39+ const before = host.agentViewWithout
40+ ? host.agentViewWithout(agent, without)
41+ : host.view(new Set([...after.set].filter((id) => !without.has(id))));
3942 const files = host.touchedFiles(draft, [before, after]);
4043 return {
4144 draft: agent.space === SHARED ? null : agent.space,
--- a/worker/project/merge-identical.ts
+++ b/worker/project/merge-identical.ts
@@ -89,7 +89,7 @@
8989 }
9090 }
9191 if ([...involved].some((f) => shown.has(f))) return [];
92− const baseView = host.view(oldBase);
92+ const baseView = host.viewAt(host.spaceOf(agent), oldVersion);
9393 const theirs = host.viewAt(host.spaceOf(agent), agent.base);
9494 const textOf = (v: ReadView, path: string): string | null => (v.hasFile(path) ? v.text(path) : null);
9595 const merged = new Map<string, { text: string | null; mode: Mode; hunks?: Hunk[] }>();
--- a/worker/project/move.ts
+++ b/worker/project/move.ts
@@ -73,8 +73,9 @@
7373 const lines = view.lines(from).length;
7474 const mode: Mode = { exec: attrs.exec, link: attrs.link };
7575 if (lines > 0 && attrs.blob === null) {
76+ const text = view.text(from);
7677 host.addDraft(agent, view, { edits: [], move: { file: from, start: 0, end: lines, to, at: 0 } }, time, {}, entries);
77− host.recordFile(agent, host.agentView(agent), to, view.text(from), time, {}, entries, mode);
78+ host.recordFile(agent, host.agentView(agent), to, text, time, {}, entries, mode);
7879 } else {
7980 // A binary or empty file has no lines to carry: the new name takes its blob and modes.
8081 host.recordFile(agent, host.agentView(agent), to, "", time, {}, entries, mode, attrs.blob ?? undefined);
--- a/worker/project/project.ts
+++ b/worker/project/project.ts
@@ -1837,6 +1837,10 @@
18371837 needInit: () => this.#needInit(),
18381838 draft: (agent) => this.#draft(agent as AgentState),
18391839 agentView: (agent) => this.#agentView(agent as AgentState),
1840+ agentViewWithout: (agent, excluded) => {
1841+ const state = agent as AgentState;
1842+ return this.#agentView({ ...state, mine: state.mine.filter((id) => !excluded.has(id)) });
1843+ },
18401844 view: (set) => this.#view(set),
18411845 touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
18421846 };
@@ -2093,6 +2097,18 @@
20932097 graph: this.#graph,
20942098 checkerReady: () => this.checkerReady,
20952099 sharedView: () => this.#sharedView(),
2100+ sharedOverlay: (atoms) =>
2101+ this.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(",")}`, () =>
2102+ unionOverlay(this.#setOf(this.#shared), atoms),
2103+ ),
2104+ sharedAgentOverlay: (agent, atoms) => {
2105+ const current = this.#setOf(this.#shared);
2106+ const added = new Set([...atoms, ...agent.mine]);
2107+ // Retain old-base atoms absent from current shared, without copying shared history.
2108+ if (agent.base !== last(this.#shared))
2109+ for (const id of this.#at(this.#spaceOf(agent), agent.base)) if (!current.has(id)) added.add(id);
2110+ return this.#viewKeyed(`a @${last(this.#shared)}+${[...added].join(",")}`, () => unionOverlay(current, added));
2111+ },
20962112 queued: () => this.#queue,
20972113 queuedId: () => this.#queuedId,
20982114 checkingHas: (id) => this.#checking.has(id),
@@ -2248,6 +2264,8 @@
22482264 view: (set) => this.#view(set),
22492265 agentSet: (agent) => this.#agentSet(agent),
22502266 agentView: (agent) => this.#agentView(agent),
2267+ agentViewWithout: (agent, excluded) =>
2268+ this.#agentView({ ...agent, mine: agent.mine.filter((id) => !excluded.has(id)) }),
22512269 recordFile: (agent, view, path, text, time, meta, entries, mode, blob, hunks) =>
22522270 this.#recordFile(agent, view, path, text, time, meta, entries, mode, blob, hunks),
22532271 flush: (entries) => this.#flush(entries),
@@ -2278,6 +2296,12 @@
22782296 agent: (name, entries) => this.#agent(name, entries),
22792297 spaceOf: (agent) => this.#spaceOf(agent),
22802298 agentView: (agent) => this.#agentView(agent),
2299+ captureAgentView: (agent) => {
2300+ const key = this.#agentViewKey(agent);
2301+ const original = this.#agentView(agent);
2302+ // Projected readers reopen the immutable key; only the in-memory fallback uses the original set.
2303+ return () => this.#viewKeyed(key, () => original.set);
2304+ },
22812305 at: (space, version) => this.#at(space, version),
22822306 draft: (agent) => this.#draft(agent),
22832307 strandedFiles: (draft, set) => this.#strandedFiles(draft, set),
--- a/worker/project/queue.ts
+++ b/worker/project/queue.ts
@@ -2,6 +2,7 @@
22// Writes go through QueueHost; today the host is Project.
33
44import { type AtomId, buildAtom, type Graph, type ReadView } from "../../src/engine/index.ts";
5+import { unionOverlay } from "../../src/engine/state-source.ts";
56import type { Pair } from "./collisions.ts";
67import { definedTwice } from "./definitions.ts";
78import { heldMessage, keptOf, lostLines } from "./markers.ts";
@@ -28,6 +29,8 @@
2829 readonly graph: Graph;
2930 checkerReady(): boolean;
3031 sharedView(): ReadView;
32+ sharedOverlay?(atoms: readonly AtomId[]): ReadView;
33+ sharedAgentOverlay?(agent: AgentState, atoms: readonly AtomId[]): ReadView;
3134 queued(): readonly QueuedPublish[];
3235 queuedId(): number;
3336 checkingHas(id: number): boolean;
@@ -117,11 +120,13 @@
117120 const ahead = queuedAtoms(host, agent.name);
118121 const now = host.setOf(space);
119122 if (ahead.size > 0) {
120− const landed = new Set([...now, ...ahead]);
121− const theirsView = host.view(landed);
122− const yoursView = host.view(new Set([...landed, ...host.agentSet(agent)]));
123+ const landed = unionOverlay(now, ahead);
124+ const theirsView = host.sharedOverlay ? host.sharedOverlay([...ahead]) : host.view(landed);
125+ const yoursView = host.sharedAgentOverlay
126+ ? host.sharedAgentOverlay(agent, [...ahead])
127+ : host.view(unionOverlay(landed, host.agentSet(agent)));
123128 const queuedBy = (id: AtomId) => host.queued().find((q) => q.changes.includes(id));
124− const collisions: Collision[] = host.pairs(changes, ahead, new Set([...landed, ...changes])).map((p) => {
129+ const collisions: Collision[] = host.pairs(changes, ahead, unionOverlay(landed, changes)).map((p) => {
125130 const c = host.describe(p, host.agentView(agent), theirsView, agent.space);
126131 const q = queuedBy(p.theirs);
127132 return q ? { ...c, theirs: { ...c.theirs, agent: q.agent, message: q.message, queued: q.id } } : c;
@@ -231,7 +236,10 @@
231236} {
232237 host.needInit();
233238 const items = host.queued().slice(0, Math.max(0, n));
234− const view = host.view(new Set([...host.setOf(host.shared()), ...items.flatMap((q) => q.changes)]));
239+ const changes = items.flatMap((q) => q.changes);
240+ const view = host.sharedOverlay
241+ ? host.sharedOverlay(changes)
242+ : host.view(unionOverlay(host.setOf(host.shared()), changes));
235243 const files = view.files();
236244 const modes = modesOf(view);
237245 const blobs = view.blobs();
@@ -250,8 +258,9 @@
250258 for (const q of host.queued().slice(0, Math.max(0, n))) {
251259 const agent = host.agentOf(q.agent);
252260 const space = host.shared();
253− const union = new Set([...host.setOf(space), ...q.changes]);
254− const tie = buildAtom(host.view(union), {
261+ const union = unionOverlay(host.setOf(space), q.changes);
262+ const view = host.sharedOverlay ? host.sharedOverlay(q.changes) : host.view(union);
263+ const tie = buildAtom(view, {
255264 author: q.agent,
256265 message: q.message,
257266 time,
--- a/worker/project/restore.ts
+++ b/worker/project/restore.ts
@@ -16,6 +16,7 @@
1616 view(set: ReadonlySet<AtomId>): ReadView;
1717 agentSet(agent: AgentState): Set<AtomId>;
1818 agentView(agent: AgentState): ReadView;
19+ agentViewWithout?(agent: AgentState, excluded: ReadonlySet<AtomId>): ReadView;
1920 recordFile(
2021 agent: AgentState,
2122 view: ReadView,
@@ -64,9 +65,15 @@
6465 // Whatever is still changed in a target goes back with a new change.
6566 const now = host.draft(agent);
6667 const without = new Set(now);
67− const original = host.view(new Set([...host.agentSet(agent)].filter((id) => !without.has(id))));
68+ const originalAgent = { ...agent, mine: [...agent.mine] };
69+ const originalView = () =>
70+ host.agentViewWithout
71+ ? host.agentViewWithout(originalAgent, without)
72+ : host.view(new Set([...host.agentSet(originalAgent)].filter((id) => !without.has(id))));
6873 for (const path of [...targets].toSorted()) {
6974 if (!touched.has(path)) continue;
75+ // A previous file may have mutated the graph. Reopen the same base view.
76+ const original = originalView();
7077 const was = original.attrs(path);
7178 host.recordFile(
7279 agent,
--- a/worker/project/sync.ts
+++ b/worker/project/sync.ts
@@ -3,7 +3,6 @@
33// SyncHost; today the host is Project.
44
55import type { AtomId, Graph, ReadView } from "../../src/engine/index.ts";
6−import { outlastsSync } from "./news.ts";
76import { ProjectError } from "./project-error.ts";
87import type { AgentState, Entry, MergedLine, SyncAnswer } from "./project-types.ts";
98import { last, SHARED, type Space } from "./spaces.ts";
@@ -15,6 +14,7 @@
1514 agent(name: string, entries: Entry[]): AgentState;
1615 spaceOf(agent: AgentState): Space;
1716 agentView(agent: AgentState): ReadView;
17+ captureAgentView?(agent: AgentState): () => ReadView;
1818 at(space: Space, version: number): ReadonlySet<AtomId>;
1919 draft(agent: AgentState): AtomId[];
2020 strandedFiles(draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[];
@@ -51,6 +51,7 @@
5151 throw new ProjectError("bad-request", `no version of shared has the label ${JSON.stringify(options.label)}`);
5252 target = versions[versions.length - 1]!;
5353 }
54+ const reopenBefore = agent.synced ? host.captureAgentView?.(agent) : undefined;
5455 const before = agent.synced ? host.agentView(agent) : new View(host.graph, []);
5556 const set = host.at(space, target);
5657 const stranded = host.strandedFiles(host.draft(agent), set);
@@ -80,14 +81,17 @@
8081 entries.push({ type: "sync", agent: agent.name, version: target });
8182 host.apply(entries[entries.length - 1]!);
8283 // News about versions the agent has now synced past is moot: the sync answer lists what's still open (#37).
83− if (agent.news.some((t) => !outlastsSync(t))) {
84+ if (agent.news.some((t) => !t.startsWith("Announcement from "))) {
8485 const heard: Entry = { type: "heard", agent: agent.name, stale: true };
8586 entries.push(heard);
8687 host.apply(heard);
8788 }
8889 const merged = host.mergeIdentical(agent, before, oldBase, oldVersion, Date.now(), entries);
8990 // full (#37, a partial join): every file in the view, as for a first sync, whatever the folder had.
90− const answer = host.changesSince(agent, options.full ? new View(host.graph, []) : before);
91+ const answer = host.changesSince(
92+ agent,
93+ options.full ? new View(host.graph, []) : reopenBefore ? reopenBefore() : before,
94+ );
9195 host.flush(entries);
9296 return merged.length > 0 ? { ...answer, merged } : answer;
9397}
--- a/worker/project/version-log.ts
+++ b/worker/project/version-log.ts
@@ -251,18 +251,22 @@
251251 host.checkVersion(space, to);
252252 const a = host.at(space, from);
253253 const b = host.at(space, to);
254+ const before = host.viewAt(space, from);
255+ const after = host.viewAt(space, to);
254256 const files = new Set<string>();
255257 for (const [x, y] of [
256258 [a, b],
257259 [b, a],
258260 ] as const) {
259261 for (const file of host.touchedFiles(
260− [...x].filter((id) => !y.has(id)),
261− [host.view(a), host.view(b)],
262+ (function* () {
263+ for (const id of x) if (!y.has(id)) yield id;
264+ })(),
265+ [before, after],
262266 ))
263267 files.add(file);
264268 }
265− return { from, to, files: changesBetween(host.view(a), host.view(b), files) };
269+ return { from, to, files: changesBetween(before, after, files) };
266270}
267271
268272/** A version of shared (or of a named draft) as a ReadView, for reading lines (blame at a version). */