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

Implement bounded sequential client recording for #606

of shared·codex-prose-authorship-1··Not checked

Version 107 · Files at version 108

5 files, 399 lines added, 32 removed.

--- a/client/src/api.ts
+++ b/client/src/api.ts
@@ -231,7 +231,13 @@
231231 await new Promise((ok) => setTimeout(ok, 500));
232232 }
233233 }
234− const text = await res.text();
234+ let text: string;
235+ try {
236+ text = await res.text();
237+ } catch (err) {
238+ const reason = err instanceof Error ? err.message : String(err);
239+ throw new ApiError(`${method} ${path} response body ended unexpectedly: ${reason}`, res.status);
240+ }
235241 // 409 is a refusal that says what to do (a drop took out lines your work builds on): print it as it is.
236242 if (!res.ok)
237243 throw new ApiError(
--- a/client/src/commands.ts
+++ b/client/src/commands.ts
@@ -41,6 +41,7 @@
4141import { withFolderLock } from "./lock.ts";
4242import type { OnDisk } from "./modes.ts";
4343import { applyMode, type FullMode, foldModes, onDisk, PLAIN, readKnownModes, writeKnownModes } from "./modes.ts";
44+import { batchRecordItems, sendRecordBatches } from "./record-batches.ts";
4445import { type Refused, screenAnswer, unsafePath } from "./safety.ts";
4546
4647export {
@@ -213,38 +214,77 @@
213214 .map(([rel]) => rel)
214215 .sort();
215216 if (sent === 0) return { sent: 0, paths, deleted, changed: [], news: undefined, leftOut, turnedBinary };
216− await uploadBlobs(api, blobs);
217− const answer = await api.record(
218− Object.fromEntries(files),
219− {},
220− modes,
221− Object.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),
217+ const items = paths.map((path) => ({
218+ path,
219+ ...(files.has(path) ? { text: files.get(path) } : {}),
220+ ...(modes[path] !== undefined ? { mode: modes[path] } : {}),
221+ ...(blobs.has(path) ? { blob: blobs.get(path)?.sha } : {}),
222+ }));
223+ const batches = batchRecordItems(items);
224+ let batchBlobs = new Map<string, BlobToSend>();
225+ const uploaded = new Set<string>();
226+ const answers = await sendRecordBatches(
227+ api,
228+ batches,
229+ async (batch) => {
230+ batchBlobs = new Map(
231+ batch.paths.flatMap((path) => {
232+ const blob = blobs.get(path);
233+ return blob === undefined ? [] : [[path, blob] as const];
234+ }),
235+ );
236+ for (const [path, blob] of batchBlobs) {
237+ if (uploaded.has(blob.sha)) continue;
238+ await uploadBlobs(api, new Map([[path, blob]]));
239+ uploaded.add(blob.sha);
240+ }
241+ },
242+ async (batch, answer) => {
243+ const batchFiles = new Map(Object.entries(batch.files));
244+ // Commit known state only after this batch is confirmed; earlier successful batches stay committed on later failure.
245+ for (const [rel, text] of batchFiles) if (text === null) forgetKnown(root, rel);
246+ for (const [rel, text] of batchFiles) if (text !== null) writeKnown(root, rel, text);
247+ const knownBlobs = readKnownBlobs(root);
248+ if (Object.keys(batch.blobs).length > 0 || batch.paths.some((rel) => knownBlobs.has(rel))) {
249+ for (const rel of new Set([...Object.keys(batch.files), ...Object.keys(batch.blobs)])) knownBlobs.delete(rel);
250+ for (const [rel, sha] of Object.entries(batch.blobs)) {
251+ forgetKnown(root, rel);
252+ knownBlobs.set(rel, sha);
253+ }
254+ writeKnownBlobs(root, knownBlobs);
255+ }
256+ const gone = Object.entries(batch.files)
257+ .filter(([, text]) => text === null)
258+ .map(([rel]) => rel);
259+ const knownModes = readKnownModes(root);
260+ if (Object.keys(batch.modes).length > 0 || gone.some((rel) => knownModes.has(rel))) {
261+ foldModes(knownModes, batch.modes, gone);
262+ writeKnownModes(root, knownModes);
263+ }
264+ heard(root, [
265+ ...newsLines(answer.news),
266+ ...(answer.spelling ?? []).map(spellingText),
267+ ...(answer.uncomposed ?? []).map(uncomposedText),
268+ ]);
269+ },
222270 );
223− if (!answer.ok) throw new Error(`the server refused the record: ${answer.reason ?? "no reason given"}`);
224− // Forget before writing: after a rename that changes only case, known/a.ts and known/A.ts are one file on Windows and macOS.
225− for (const [rel, text] of files) if (text === null) forgetKnown(root, rel);
226− for (const [rel, text] of files) if (text !== null) writeKnown(root, rel, text);
227− const knownBlobs = readKnownBlobs(root);
228− if (blobs.size > 0 || [...files.keys()].some((rel) => knownBlobs.has(rel))) {
229− for (const rel of files.keys()) knownBlobs.delete(rel);
230− for (const [rel, b] of blobs) {
231− forgetKnown(root, rel);
232− knownBlobs.set(rel, b.sha);
233− }
234− writeKnownBlobs(root, knownBlobs);
235− }
236− const gone = [...files].filter(([, text]) => text === null).map(([rel]) => rel);
237− const knownModes = readKnownModes(root);
238− if (Object.keys(modes).length > 0 || gone.some((rel) => knownModes.has(rel))) {
239− foldModes(knownModes, modes, gone);
240− writeKnownModes(root, knownModes);
241− }
242− // Another spelling of an existing file went in as that file (#49); a new name not in composed form gets a gentle word.
243− heard(root, [
244− ...newsLines(answer.news),
245− ...(answer.spelling ?? []).map(spellingText),
246− ...(answer.uncomposed ?? []).map(uncomposedText),
247− ]);
271+ const changed = answers.flatMap((answer) => (Array.isArray(answer.changed) ? answer.changed : []));
272+ const changedCount = answers.some((answer) => typeof answer.changed === "number")
273+ ? answers.reduce(
274+ (sum, answer) =>
275+ sum +
276+ (typeof answer.changed === "number"
277+ ? answer.changed
278+ : Array.isArray(answer.changed)
279+ ? answer.changed.length
280+ : 0),
281+ 0,
282+ )
283+ : changed;
284+ const news = answers.flatMap((answer) => newsLines(answer.news));
285+ const spelling = answers.flatMap((answer) => answer.spelling ?? []);
286+ const uncomposed = answers.flatMap((answer) => answer.uncomposed ?? []);
287+ const answer = { changed: changedCount, news, spelling, uncomposed };
248288 const longPaths = longPathsOf(
249289 root,
250290 [...files].filter(([, text]) => text !== null).map(([path]) => path),
--- /dev/null
+++ b/client/src/record-batches.ts
@@ -0,0 +1,125 @@
1+import { ApiError, type RecordAnswer } from "./api.ts";
2+import type { Mode, Modes } from "./modes.ts";
3+
4+/** One atomic path entry from the folder scan. */
5+export interface RecordItem {
6+ readonly path: string;
7+ readonly text?: string | null;
8+ readonly mode?: Modes[string];
9+ readonly blob?: string;
10+}
12+/** A record request; a path's text, mode, and blob reference always travel together. */
13+export interface RecordBatch {
14+ readonly files: Record<string, string | null>;
15+ readonly modes: Modes;
16+ readonly blobs: Record<string, string>;
17+ readonly paths: readonly string[];
18+}
20+export const RECORD_BODY_BUDGET = 8 * 1024 * 1024;
22+export class RecordItemTooLargeError extends Error {
23+ readonly path: string;
24+ readonly bytes: number;
25+ readonly budget: number;
26+ constructor(path: string, bytes: number, budget: number) {
27+ super(`Not recorded: ${path} needs a ${bytes}-byte record request by itself, over the ${budget}-byte limit.`);
28+ this.name = "RecordItemTooLargeError";
29+ this.path = path;
30+ this.bytes = bytes;
31+ this.budget = budget;
32+ }
33+}
35+function bodyFor(items: readonly RecordItem[]): RecordBatch {
36+ const files: Record<string, string | null> = {};
37+ const modes: Record<string, Mode> = {};
38+ const blobs: Record<string, string> = {};
39+ for (const item of items) {
40+ if (item.text !== undefined) files[item.path] = item.text;
41+ if (item.mode !== undefined) modes[item.path] = item.mode;
42+ if (item.blob !== undefined) blobs[item.path] = item.blob;
43+ }
44+ return { files, modes, blobs, paths: items.map((item) => item.path) };
45+}
47+/** Exact serialized UTF-8 size of the API record body. */
48+export function serializedRecordBytes(batch: RecordBatch): number {
49+ return Buffer.byteLength(
50+ JSON.stringify({
51+ files: batch.files,
52+ ...(Object.keys(batch.modes).length ? { modes: batch.modes } : {}),
53+ ...(Object.keys(batch.blobs).length ? { blobs: batch.blobs } : {}),
54+ }),
55+ "utf8",
56+ );
57+}
59+/** Deterministically split sorted atomic path entries under the serialized body budget. */
60+export function batchRecordItems(items: readonly RecordItem[], budget = RECORD_BODY_BUDGET): RecordBatch[] {
61+ if (!Number.isSafeInteger(budget) || budget <= 0)
62+ throw new RangeError("record body budget must be a positive safe integer");
63+ const sorted = [...items].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
64+ const batches: RecordBatch[] = [];
65+ let current: RecordItem[] = [];
66+ for (const item of sorted) {
67+ const candidate = bodyFor([...current, item]);
68+ if (serializedRecordBytes(candidate) <= budget) {
69+ current.push(item);
70+ continue;
71+ }
72+ if (current.length === 0) throw new RecordItemTooLargeError(item.path, serializedRecordBytes(candidate), budget);
73+ batches.push(bodyFor(current));
74+ current = [item];
75+ const single = bodyFor(current);
76+ const bytes = serializedRecordBytes(single);
77+ if (bytes > budget) throw new RecordItemTooLargeError(item.path, bytes, budget);
78+ }
79+ if (current.length > 0) batches.push(bodyFor(current));
80+ return batches;
81+}
83+export interface RecordApi {
84+ record(
85+ files: Record<string, string | null>,
86+ extra?: { session?: string; subagent?: string },
87+ modes?: Modes,
88+ blobs?: Readonly<Record<string, string>>,
89+ ): Promise<RecordAnswer>;
90+}
92+/** Retry only an outcome that may have been accepted; an identical record is a no-op once its state landed. */
93+export async function sendRecordBatch(api: RecordApi, batch: RecordBatch): Promise<RecordAnswer> {
94+ const blobMap = batch.blobs;
95+ try {
96+ return await api.record(batch.files, {}, batch.modes, blobMap);
97+ } catch (error) {
98+ if (
99+ !(error instanceof ApiError) ||
100+ error.notSent ||
101+ (error.status !== undefined && (error.status < 200 || (error.status >= 300 && error.status < 500)))
102+ )
103+ throw error;
104+ // The server diffs whole-file state against the agent's current view. Replaying these exact maps is idempotent.
105+ return api.record(batch.files, {}, batch.modes, blobMap);
106+ }
107+}
109+/** Run batches in order and expose only confirmed batches to local bookkeeping. */
110+export async function sendRecordBatches(
111+ api: RecordApi,
112+ batches: readonly RecordBatch[],
113+ beforeSend: (batch: RecordBatch) => Promise<void>,
114+ onConfirmed: (batch: RecordBatch, answer: RecordAnswer) => Promise<void>,
115+): Promise<RecordAnswer[]> {
116+ const answers: RecordAnswer[] = [];
117+ for (const batch of batches) {
118+ await beforeSend(batch);
119+ const answer = await sendRecordBatch(api, batch);
120+ if (!answer.ok) throw new Error(`the server refused the record: ${answer.reason ?? "no reason given"}`);
121+ await onConfirmed(batch, answer);
122+ answers.push(answer);
123+ }
124+ return answers;
125+}
--- /dev/null
+++ b/client/test/record-batches.test.ts
@@ -0,0 +1,161 @@
1+import assert from "node:assert/strict";
2+import test from "node:test";
3+import { Api, ApiError, type RecordAnswer } from "../src/api.ts";
4+import {
5+ batchRecordItems,
6+ RECORD_BODY_BUDGET,
7+ type RecordBatch,
8+ type RecordItem,
9+ RecordItemTooLargeError,
10+ sendRecordBatch,
11+ sendRecordBatches,
12+ serializedRecordBytes,
13+} from "../src/record-batches.ts";
15+test("batches use serialized UTF-8 bytes and keep text, mode, blob, and deletion entries atomic", () => {
16+ const items: RecordItem[] = [
17+ { path: "delete.txt", text: null },
18+ { path: "blob.bin", text: "", mode: { exec: true }, blob: "a".repeat(64) },
19+ { path: "emoji.txt", text: "🙂".repeat(80) },
20+ ];
21+ const onePath = batchRecordItems([items[2]!], 10_000)[0]!;
22+ const exact = serializedRecordBytes(onePath);
23+ assert.equal(batchRecordItems([items[2]!], exact).length, 1);
24+ assert.throws(() => batchRecordItems([items[2]!], exact - 1), RecordItemTooLargeError);
26+ const batches = batchRecordItems(items, exact + 100);
27+ assert.deepEqual(
28+ batches.flatMap((batch) => batch.paths),
29+ ["blob.bin", "delete.txt", "emoji.txt"],
30+ );
31+ assert.ok(batches.every((batch) => serializedRecordBytes(batch) <= exact + 100));
32+ const blobBatch = batches.find((batch) => batch.paths.includes("blob.bin"))!;
33+ assert.deepEqual(blobBatch.files, { "blob.bin": "", "delete.txt": null });
34+ assert.deepEqual(blobBatch.modes, { "blob.bin": { exec: true } });
35+ assert.deepEqual(blobBatch.blobs, { "blob.bin": "a".repeat(64) });
36+ assert.ok(blobBatch.paths.includes("delete.txt"));
37+});
39+test("a single entry over the budget is refused before any request can be sent", () => {
40+ assert.throws(() => batchRecordItems([{ path: "big.txt", text: "x".repeat(100) }], 20), /Not recorded: big\.txt/);
41+ assert.equal(RECORD_BODY_BUDGET, 8 * 1024 * 1024);
42+});
44+test("an ambiguous lost reply retries the exact batch once, then returns the accepted result", async () => {
45+ const batch: RecordBatch = {
46+ files: { "a.txt": "same\n" },
47+ modes: {},
48+ blobs: {},
49+ paths: ["a.txt"],
50+ };
51+ const calls: unknown[][] = [];
52+ let accepted = false;
53+ const api = {
54+ async record(...args: unknown[]): Promise<RecordAnswer> {
55+ calls.push(args);
56+ if (!accepted) {
57+ accepted = true;
58+ throw new ApiError("response ended before confirmation", 200);
59+ }
60+ return { ok: true, changed: [], news: [] };
61+ },
62+ };
63+ assert.deepEqual(await sendRecordBatch(api, batch), { ok: true, changed: [], news: [] });
64+ assert.equal(calls.length, 2);
65+ assert.deepEqual(calls[0], calls[1]);
66+});
68+test("the real Api transport retries an accepted request when reading its response stream fails", async () => {
69+ const api = new Api({ server: "https://example.test", project: "p", agent: "a", token: "t" });
70+ let requests = 0;
71+ api.send = async () => {
72+ requests += 1;
73+ if (requests === 1) {
74+ return new Response(
75+ new ReadableStream({
76+ start(controller) {
77+ controller.error(new Error("lost response stream"));
78+ },
79+ }),
80+ { status: 200 },
81+ );
82+ }
83+ return new Response(JSON.stringify({ ok: true, changed: [] }), {
84+ status: 200,
85+ headers: { "content-type": "application/json" },
86+ });
87+ };
88+ const answer = await sendRecordBatch(api, {
89+ files: { "a.txt": "same\n" },
90+ modes: {},
91+ blobs: {},
92+ paths: ["a.txt"],
93+ });
94+ assert.equal(answer.ok, true);
95+ assert.equal(requests, 2);
96+});
98+test("the real Api transport does not retry a definite refusal with a broken response stream", async () => {
99+ const api = new Api({ server: "https://example.test", project: "p", agent: "a", token: "t" });
100+ let requests = 0;
101+ api.send = async () => {
102+ requests += 1;
103+ return new Response(
104+ new ReadableStream({
105+ start(controller) {
106+ controller.error(new Error("broken refusal response"));
107+ },
108+ }),
109+ { status: 413 },
110+ );
111+ };
112+ await assert.rejects(
113+ sendRecordBatch(api, { files: { "a.txt": "x" }, modes: {}, blobs: {}, paths: ["a.txt"] }),
114+ (error: unknown) => error instanceof ApiError && error.status === 413,
115+ );
116+ assert.equal(requests, 1);
117+});
119+test("a definite server refusal is not retried", async () => {
120+ let calls = 0;
121+ const api = {
122+ async record(): Promise<RecordAnswer> {
123+ calls += 1;
124+ throw new ApiError("bad request", 413);
125+ },
126+ };
127+ await assert.rejects(sendRecordBatch(api, { files: { "a.txt": "x" }, modes: {}, blobs: {}, paths: ["a.txt"] }));
128+ assert.equal(calls, 1);
129+});
131+test("later batch failure stops the sequence and confirms only successful batches", async () => {
132+ const batches: RecordBatch[] = ["a.txt", "b.txt", "c.txt"].map((path) => ({
133+ files: { [path]: path },
134+ modes: {},
135+ blobs: {},
136+ paths: [path],
137+ }));
138+ const sent: string[] = [];
139+ const confirmed: string[] = [];
140+ const api = {
141+ async record(files: Record<string, string | null>): Promise<RecordAnswer> {
142+ const path = Object.keys(files)[0]!;
143+ sent.push(path);
144+ if (path === "b.txt") throw new ApiError("request rejected", 413);
145+ return { ok: true, changed: [path] };
146+ },
147+ };
148+ await assert.rejects(
149+ sendRecordBatches(
150+ api,
151+ batches,
152+ async () => {},
153+ async (batch) => {
154+ confirmed.push(batch.paths[0]!);
155+ },
156+ ),
157+ /request rejected/,
158+ );
159+ assert.deepEqual(sent, ["a.txt", "b.txt"]);
160+ assert.deepEqual(confirmed, ["a.txt"]);
161+});
--- /dev/null
+++ b/worker/project/test/record-idempotence.test.ts
@@ -0,0 +1,35 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { MemoryStore, Project } from "../project.ts";
4+
5+const BLOB_A = "a".repeat(64);
6+const BLOB_B = "b".repeat(64);
7+
8+test("replaying identical recorded text, deletion, blob, and mode changes adds no semantic events", () => {
9+ const heldBlobs = new Set([BLOB_A, BLOB_B]);
10+ const store = new MemoryStore();
11+ const project = new Project(store, { hasBlob: (sha) => heldBlobs.has(sha) });
12+ project.init(
13+ { "text.txt": "old text\n", "delete.txt": "remove me\n", "run.sh": "echo hi\n" },
14+ 0,
15+ {},
16+ { "image.bin": BLOB_A },
17+ );
18+ project.sync("ann");
20+ const replay = (record: () => { changed?: readonly string[] }) => {
21+ const before = store.entries.length;
22+ const first = record();
23+ const afterFirst = store.entries.length;
24+ assert.ok(afterFirst > before, "the initial recording creates semantic events");
25+ const second = record();
26+ assert.deepEqual(second.changed, []);
27+ assert.equal(store.entries.length, afterFirst, "an identical replay appends no semantic events");
28+ return first;
29+ };
31+ replay(() => project.record("ann", { "text.txt": "new text\n" }, 1));
32+ replay(() => project.record("ann", { "delete.txt": null }, 2));
33+ replay(() => project.record("ann", {}, 3, {}, { "image.bin": BLOB_B }));
34+ replay(() => project.record("ann", {}, 4, { "run.sh": { exec: true } }));
35+});