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
blame on this site's /mcp
CLI
abso blame server/src/writer-host.ts --json
JSON
/christopher/abso-core/blame/server/src/writer-host.ts?format=json
474 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 162,

474 lines from 3 changes in 2 versions.

codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare1// Shared SQLite writer host.
2// Callers provide current authority and own activation; this module adds no route.
3import { createHash } from "node:crypto";
4import { indexAcceptedProjectionAtom } from "../../src/engine/experimental/projection-atom-index.ts";
5import type { GraphStateStorage } from "../../src/engine/state-source.ts";
6import { Project, type WriterSource } from "../../worker/project/project.ts";
7import type { ProjectOptions } from "../../worker/project/project-types.ts";
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare8import { withDecodedFrames } from "./decoded-frames.ts";
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare9import {
10 EngineProject,
11 logParts,
12 LOG_PART_CHARACTERS as PART,
13 SqliteLog,
14 type SqliteStorage,
15} from "./engine-project.ts";
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare16import type { SqliteHistoryHost } from "./history-host.ts";
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare17
18export class SqliteWriterState implements GraphStateStorage {
19 readonly #storage: SqliteStorage;
20 readonly #namespace: string;
21 static readonly maxValueBytes = 8_000_000;
22 constructor(storage: SqliteStorage, namespace: string) {
23 if (!namespace || namespace.length > 128) throw new Error("invalid writer-state namespace");
24 this.#storage = storage;
25 this.#namespace = namespace;
26 }
27 /** Explicit schema setup, reserved for an authorized adoption host. */
28 static initialize(storage: SqliteStorage): void {
29 storage.sql.exec(
30 "CREATE TABLE IF NOT EXISTS writer_state (namespace TEXT NOT NULL, collection TEXT NOT NULL, key TEXT NOT NULL, part INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY(namespace, collection, key, part))",
31 );
32 }
33 read(collection: string, key: string): unknown {
34 const header = this.#storage.sql
35 .exec(
36 "SELECT value FROM writer_state WHERE namespace = ? AND collection = ? AND key = ? AND part = -1",
37 this.#namespace,
38 collection,
39 key,
40 )
41 .toArray() as { value: string }[];
42 if (!header.length) return undefined;
43 const meta = JSON.parse(header[0]!.value) as { parts: number; characters: number; bytes: number };
44 if (
45 !Number.isSafeInteger(meta.parts) ||
46 meta.parts < 1 ||
47 meta.parts > Math.ceil(SqliteWriterState.maxValueBytes / (PART - 1)) ||
48 !Number.isSafeInteger(meta.characters) ||
49 meta.characters < 1 ||
50 meta.characters > SqliteWriterState.maxValueBytes ||
51 !Number.isSafeInteger(meta.bytes) ||
52 meta.bytes < 1 ||
53 meta.bytes > SqliteWriterState.maxValueBytes
54 )
55 throw new Error("invalid writer-state value header");
56 const rows = this.#storage.sql
57 .exec(
58 "SELECT part, value FROM writer_state WHERE namespace = ? AND collection = ? AND key = ? AND part >= 0 ORDER BY part LIMIT ?",
59 this.#namespace,
60 collection,
61 key,
62 meta.parts + 1,
63 )
64 .toArray() as { part: number; value: string }[];
65 if (rows.length !== meta.parts || rows.some((row, index) => row.part !== index || row.value.length > PART))
66 throw new Error("incomplete writer-state value");
67 const json = rows.map((row) => row.value).join("");
68 if (json.length !== meta.characters || new TextEncoder().encode(json).byteLength !== meta.bytes)
69 throw new Error("writer-state value length mismatch");
70 return (JSON.parse(json) as { value?: unknown }).value;
71 }
72 write(collection: string, key: string, value: unknown): void {
73 const json = JSON.stringify({ value });
74 if (json.length > SqliteWriterState.maxValueBytes) throw new Error("writer-state value exceeds byte bound");
75 const bytes = new TextEncoder().encode(json).byteLength;
76 if (bytes > SqliteWriterState.maxValueBytes) throw new Error("writer-state value exceeds byte bound");
77 const parts = logParts(json);
78 this.transaction(() => {
79 this.remove(collection, key);
80 this.#storage.sql.exec(
81 "INSERT INTO writer_state VALUES (?, ?, ?, -1, ?)",
82 this.#namespace,
83 collection,
84 key,
85 JSON.stringify({ parts: parts.length, characters: json.length, bytes }),
86 );
87 for (const [part, text] of parts.entries())
88 this.#storage.sql.exec(
89 "INSERT INTO writer_state VALUES (?, ?, ?, ?, ?)",
90 this.#namespace,
91 collection,
92 key,
93 part,
94 text,
95 );
96 });
97 }
98 remove(collection: string, key: string): void {
99 this.#storage.sql.exec(
100 "DELETE FROM writer_state WHERE namespace = ? AND collection = ? AND key = ?",
101 this.#namespace,
102 collection,
103 key,
104 );
105 }
106 /** Delete one owned temporary projection collection without reading its values. */
107 clearProjectionOverlay(collection: string): void {
108 if (!collection.startsWith("projection:temporary:") || collection === "projection:temporary:")
109 throw Error("invalid temporary projection collection");
110 this.#storage.sql.exec(
111 "DELETE FROM writer_state WHERE namespace = ? AND collection = ?",
112 this.#namespace,
113 collection,
114 );
115 }
116 *entries(collection: string): Iterable<readonly [string, unknown]> {
117 let after: string | undefined;
118 for (;;) {
119 const rows = (
120 after === undefined
121 ? this.#storage.sql.exec(
122 "SELECT key FROM writer_state WHERE namespace = ? AND collection = ? AND part = -1 ORDER BY key LIMIT 1",
123 this.#namespace,
124 collection,
125 )
126 : this.#storage.sql.exec(
127 "SELECT key FROM writer_state WHERE namespace = ? AND collection = ? AND part = -1 AND key > ? ORDER BY key LIMIT 1",
128 this.#namespace,
129 collection,
130 after,
131 )
132 ).toArray() as { key: string }[];
133 if (!rows.length) return;
134 after = rows[0]!.key;
135 yield [after, this.read(collection, after)];
136 }
137 }
138 transaction<T>(body: () => T): T {
139 return this.#storage.transactionSync(body);
140 }
143export interface WriterRoot extends WriterSource {
144 readonly format: 1;
145 readonly digest: string;
148/** Domain-separated SHA-256 chain over exact canonical UTF-8 frames and their positions. */
149export function writerFrameDigest(previous: string, seq: number, json: string): string {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare150 return writerFrameChunksDigest(previous, seq, [json]);
153/** Same canonical digest without retaining the complete frame. */
154export function writerFrameChunksDigest(previous: string, seq: number, chunks: Iterable<string>): string {
155 const hash = createHash("sha256")
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare156 .update("abso-writer-log-v1\n")
157 .update(JSON.stringify([previous, seq]))
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare158 .update("\n");
159 let carry = "";
160 for (const chunk of chunks) {
161 const text = carry + chunk;
162 const last = text.charCodeAt(text.length - 1);
163 const split = last >= 0xd800 && last <= 0xdbff;
164 carry = split ? text.slice(-1) : "";
165 hash.update(split ? text.slice(0, -1) : text, "utf8");
166 }
167 if (carry) hash.update(carry, "utf8");
168 return hash.digest("hex");
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare169}
171export function advanceWriterRoot(log: SqliteLog, previous: WriterRoot, source: WriterSource): WriterRoot {
172 let digest = previous.digest;
173 if (source.logLength < previous.logLength) throw new Error("writer root cannot move backwards");
174 for (let seq = previous.logLength; seq < source.logLength; seq++)
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare175 digest = writerFrameChunksDigest(digest, seq, log.frameChunks(seq));
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare176 return { format: 1, ...source, digest };
179/** Inactive host for explicit adoption and synchronous fenced writer operations. */
180export interface WriterProjectionSession {
181 readonly readViewProvider: NonNullable<ProjectOptions["readViewProvider"]>;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare182 historicalReadViewProvider?(state: GraphStateStorage): NonNullable<ProjectOptions["readViewProvider"]>;
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare183 commit(project: Project, root: WriterRoot): void;
184 /** Cleanup is inside the canonical transaction. Any failure aborts roots and receipt too. */
185 close(): void;
188/** Private integration hook. No endpoint or persisted setting enables it. */
189export interface WriterProjectionHost {
190 open(input: { state: SqliteWriterState; log: SqliteLog; root: WriterRoot }): WriterProjectionSession;
193export class SqliteWriterHost {
194 readonly #storage: SqliteStorage;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare195 readonly #namespace: string;
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare196 readonly #state: SqliteWriterState;
197 readonly #log: SqliteLog;
198 readonly #projection?: WriterProjectionHost;
199 readonly #indexProjectionAtoms: boolean;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare200 readonly #history?: SqliteHistoryHost;
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare201 constructor(
202 storage: SqliteStorage,
203 namespace: string,
204 projection?: WriterProjectionHost,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare205 options: { indexProjectionAtoms?: boolean; history?: SqliteHistoryHost } = {},
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare206 ) {
207 this.#storage = storage;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare208 this.#namespace = namespace;
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare209 this.#state = new SqliteWriterState(storage, namespace);
210 this.#log = new SqliteLog(storage);
211 this.#projection = projection;
212 this.#indexProjectionAtoms = options.indexProjectionAtoms ?? false;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare213 this.#history = options.history;
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare214 }
215 #indexOptions(adopting = false) {
216 const mode = this.#state.read("host", "projection-atom-index-mode");
217 const expected = this.#indexProjectionAtoms ? 1 : 0;
218 if (mode !== undefined && mode !== expected) throw Error("writer atom indexing mode mismatch");
219 if (mode === undefined && this.#indexProjectionAtoms && (!adopting || this.#state.read("atoms:meta", "length")))
220 throw Error("writer atom indexing requires fresh adoption");
221 if (mode === undefined && adopting) this.#state.write("host", "projection-atom-index-mode", expected);
222 return { indexAcceptedAtom: this.#indexProjectionAtoms ? indexAcceptedProjectionAtom : undefined };
223 }
225 source(): WriterSource {
226 this.#log.refreshSequence();
227 const shared = this.#storage.sql.exec("SELECT value FROM counts WHERE name = 'shared'").toArray() as {
228 value: number;
229 }[];
230 if (!Number.isSafeInteger(shared[0]?.value) || shared[0]!.value < 0)
231 throw new Error("canonical shared head must be established before writer adoption");
232 return { generation: this.#log.generation(), logLength: this.#log.seq(), sharedVersion: shared[0]!.value };
233 }
234 static #same(a: WriterSource | undefined, b: WriterSource): boolean {
235 return a?.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion;
236 }
237 root(): WriterRoot {
238 const root = this.#state.read("host", "canonical-root") as WriterRoot | undefined;
239 if (root?.format !== 1 || !/^[a-f0-9]{64}$/.test(root.digest) || !SqliteWriterHost.#same(root, this.source()))
240 throw new Error("writer canonical root is missing or stale");
241 return root;
242 }
243 static #sync(value: unknown): void {
244 if (value && (typeof value === "object" || typeof value === "function") && "then" in value)
245 throw new Error("writer transaction callbacks must be synchronous");
246 }
247 /** Resume one bounded adoption page against an exact source and prior digest. */
248 adoptVerifiedPage(
249 input: {
250 expected: WriterSource;
251 from: number;
252 digest: string;
253 maxEntries: number;
254 maxBytes: number;
255 },
256 validateAuthority: () => void,
257 ) {
258 return this.#storage.transactionSync(() => {
259 SqliteWriterHost.#sync(validateAuthority());
260 if (!SqliteWriterHost.#same(input.expected, this.source())) throw new Error("adoption source changed");
261 if (
262 !Number.isSafeInteger(input.from) ||
263 input.from < 0 ||
264 !Number.isSafeInteger(input.maxEntries) ||
265 input.maxEntries < 1 ||
266 input.maxEntries > 256 ||
267 !Number.isSafeInteger(input.maxBytes) ||
268 input.maxBytes < 1 ||
269 !(input.digest === "" || /^[a-f0-9]{64}$/.test(input.digest))
270 )
271 throw new Error("invalid bounded adoption request");
272 const request = JSON.stringify([
273 input.expected.generation,
274 input.expected.logLength,
275 input.expected.sharedVersion,
276 input.from,
277 input.digest,
278 input.maxEntries,
279 input.maxBytes,
280 ]);
281 const previous = this.#state.read("host", "adoption-page-receipt") as
282 | { request: string; result: { next: number; ready: boolean; digest: string } }
283 | undefined;
284 if (previous?.request === request) return previous.result;
285 const cursor = this.#state.read("host", "adoption-root") as { next: number; digest: string } | undefined;
286 if ((cursor?.next ?? 0) !== input.from || (cursor?.digest ?? "") !== input.digest)
287 throw new Error("adoption cursor or digest changed");
288 const page = this.adoptPage(input.from, input, validateAuthority);
289 const root = this.#state.read("host", "adoption-root") as { digest: string };
290 const result = { next: page.next, ready: page.ready, digest: root.digest };
291 this.#state.write("host", "adoption-page-receipt", { request, result });
292 return result;
293 });
294 }
295 adoptPage(from: number, limits: { maxEntries: number; maxBytes: number }, validateAuthority: () => void) {
296 return this.#storage.transactionSync(() => {
297 SqliteWriterHost.#sync(validateAuthority());
298 const source = this.source();
299 const indexOptions = this.#indexOptions(true);
300 const log = this.#log;
301 const previous = this.#state.read("host", "adoption-root") as
302 | { source: WriterSource; next: number; digest: string }
303 | undefined;
304 if (
305 (from === 0 && previous) ||
306 (from > 0 && (!previous || previous.next !== from || !SqliteWriterHost.#same(previous.source, source)))
307 )
308 throw new Error("writer adoption root cursor is stale");
309 let digest = previous?.digest ?? "";
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare310 const decoded = withDecodedFrames(
311 this.#storage,
312 `${this.#namespace}:decoded`,
313 log,
314 { from, to: source.logLength, ...limits, digest },
315 (frames) => {
316 const result = Project.adoptWriterPage(
317 this.#state,
318 {
319 source,
320 from,
321 frames,
322 ...limits,
323 decodedFrames: true,
324 currentSource: () => this.source(),
325 },
326 indexOptions,
327 );
328 return result;
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare329 },
330 );
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare331 const result = decoded.result;
332 digest = decoded.digest;
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare333 SqliteWriterHost.#sync(validateAuthority());
334 this.#state.write("host", "adoption-root", { source, next: result.next, digest });
335 if (result.ready) {
336 this.#state.write("host", "canonical", source);
337 this.#state.write("host", "canonical-root", { format: 1, ...source, digest } satisfies WriterRoot);
338 }
339 return result;
340 });
341 }
342 /** Read through the existing call adapter with persistent mutations forbidden. */
343 readCalls<T>(input: {
344 expected: WriterSource;
345 validateAuthority(): void;
346 services?: Pick<ProjectOptions, "hasBlob" | "whole">;
347 operation(calls: EngineProject): T;
348 }): T {
349 return this.#storage.transactionSync(() => {
350 SqliteWriterHost.#sync(input.validateAuthority());
351 const source = this.source();
352 this.root();
353 if (!SqliteWriterHost.#same(input.expected, source)) throw new Error("reader source is stale");
354 const refuse = () => {
355 throw new Error("indexed read attempted to mutate persistent state");
356 };
357 const readOnly: GraphStateStorage = {
358 read: (collection, key) => this.#state.read(collection, key),
359 entries: (collection) => this.#state.entries(collection),
360 write: refuse,
361 remove: refuse,
362 transaction: (body) => this.#storage.transactionSync(body),
363 };
364 const projection = this.#projection?.open({ state: this.#state, log: this.#log, root: this.root() });
365 try {
366 const project = Project.openWriter({ append: refuse }, readOnly, source.logLength, {
367 ...input.services,
368 ...(input.services?.whole ? { whole: { read: input.services.whole.read, keep: refuse } } : {}),
369 readViewProvider: projection?.readViewProvider,
370 entryAt: (index) => this.#log.since(index, 1)[0]!,
371 });
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare372 const root = this.root();
373 const result = input.operation(
374 new EngineProject(
375 project,
376 (from, limit) => this.#log.since(from, limit),
377 undefined,
378 this.#history
379 ? (at, operation) =>
380 this.#history!.read(
381 root,
382 () => this.root(),
383 input.validateAuthority,
384 at,
385 operation,
386 projection?.historicalReadViewProvider,
387 )
388 : undefined,
389 ),
390 );
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare391 SqliteWriterHost.#sync(result);
392 SqliteWriterHost.#sync(input.validateAuthority());
393 if (!SqliteWriterHost.#same(source, this.source())) throw new Error("reader source changed");
394 return result;
395 } finally {
396 SqliteWriterHost.#sync(projection?.close());
397 }
398 });
399 }
401 /** Reuse the existing call adapter within one fenced writer transaction. */
402 runCalls<T>(input: {
403 expected: WriterSource;
404 validateAuthority(): void;
405 checkerReady: boolean;
406 services?: Pick<ProjectOptions, "hasBlob" | "whole">;
407 operation(calls: EngineProject): T;
408 commitReceipt(result: NoInfer<T>, source: WriterSource): void;
409 }): T {
410 return this.run({
411 ...input,
412 operation: (project) => {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare413 const root = this.root();
414 const calls = new EngineProject(
415 project,
416 (from, limit) => this.#log.since(from, limit),
417 this.#log,
418 this.#history
419 ? (at, operation) => this.#history!.read(root, () => this.root(), input.validateAuthority, at, operation)
420 : undefined,
421 );
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare422 calls.setCheckerReady(input.checkerReady);
423 return input.operation(calls);
424 },
425 });
426 }
427 /** No asynchronous gap is permitted between authority validation and commit. */
428 run<T>(input: {
429 expected: WriterSource;
430 validateAuthority(): void;
431 operation(project: Project): T;
432 services?: Pick<ProjectOptions, "hasBlob" | "whole">;
433 commitReceipt(result: NoInfer<T>, source: WriterSource): void;
434 }): T {
435 try {
436 return this.#storage.transactionSync(() => {
437 SqliteWriterHost.#sync(input.validateAuthority());
438 const source = this.source();
439 const root = this.root();
440 const bound = this.#state.read("host", "canonical") as WriterSource | undefined;
441 if (!SqliteWriterHost.#same(input.expected, source) || !SqliteWriterHost.#same(bound, source))
442 throw new Error("writer source or adopted generation is stale");
443 const projection = this.#projection?.open({ state: this.#state, log: this.#log, root });
444 try {
445 const project = Project.openWriter(this.#log, this.#state, source.logLength, {
446 ...input.services,
447 ...this.#indexOptions(),
448 readViewProvider: projection?.readViewProvider,
449 shapes: this.#log.shapes(),
450 now: () => Date.now(),
451 });
452 const result = input.operation(project);
453 SqliteWriterHost.#sync(result);
454 SqliteWriterHost.#sync(input.validateAuthority());
455 const committed = this.source();
456 this.#state.write("host", "canonical", committed);
457 const committedRoot = advanceWriterRoot(this.#log, root, committed);
458 this.#state.write("host", "canonical-root", committedRoot);
459 SqliteWriterHost.#sync(projection?.commit(project, committedRoot));
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare460 this.#history?.advance(this.#log, root, committedRoot, () => this.root(), input.validateAuthority);
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare461 SqliteWriterHost.#sync(input.commitReceipt(result, committed));
462 return result;
463 } finally {
464 SqliteWriterHost.#sync(projection?.close());
465 }
466 });
467 } catch (error) {
468 // The Project was scoped to the transaction and is discarded. Restore
469 // SqliteLog's cached sequence after an enclosing rollback as well.
470 this.#log.refreshSequence();
471 throw error;
472 }
473 }