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

Versions 40 to 318

Compare

+474 −0 in 1 place
new file, 474 lines
1+// Shared SQLite writer host.
2+// Callers provide current authority and own activation; this module adds no route.
3+import { createHash } from "node:crypto";
4+import { indexAcceptedProjectionAtom } from "../../src/engine/experimental/projection-atom-index.ts";
5+import type { GraphStateStorage } from "../../src/engine/state-source.ts";
6+import { Project, type WriterSource } from "../../worker/project/project.ts";
7+import type { ProjectOptions } from "../../worker/project/project-types.ts";
8+import { withDecodedFrames } from "./decoded-frames.ts";
9+import {
10+ EngineProject,
11+ logParts,
12+ LOG_PART_CHARACTERS as PART,
13+ SqliteLog,
14+ type SqliteStorage,
15+} from "./engine-project.ts";
16+import type { SqliteHistoryHost } from "./history-host.ts";
18+export 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+ }
141+}
143+export interface WriterRoot extends WriterSource {
144+ readonly format: 1;
145+ readonly digest: string;
146+}
148+/** Domain-separated SHA-256 chain over exact canonical UTF-8 frames and their positions. */
149+export function writerFrameDigest(previous: string, seq: number, json: string): string {
150+ return writerFrameChunksDigest(previous, seq, [json]);
151+}
153+/** Same canonical digest without retaining the complete frame. */
154+export function writerFrameChunksDigest(previous: string, seq: number, chunks: Iterable<string>): string {
155+ const hash = createHash("sha256")
156+ .update("abso-writer-log-v1\n")
157+ .update(JSON.stringify([previous, seq]))
158+ .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");
169+}
171+export 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++)
175+ digest = writerFrameChunksDigest(digest, seq, log.frameChunks(seq));
176+ return { format: 1, ...source, digest };
177+}
179+/** Inactive host for explicit adoption and synchronous fenced writer operations. */
180+export interface WriterProjectionSession {
181+ readonly readViewProvider: NonNullable<ProjectOptions["readViewProvider"]>;
182+ historicalReadViewProvider?(state: GraphStateStorage): NonNullable<ProjectOptions["readViewProvider"]>;
183+ commit(project: Project, root: WriterRoot): void;
184+ /** Cleanup is inside the canonical transaction. Any failure aborts roots and receipt too. */
185+ close(): void;
186+}
188+/** Private integration hook. No endpoint or persisted setting enables it. */
189+export interface WriterProjectionHost {
190+ open(input: { state: SqliteWriterState; log: SqliteLog; root: WriterRoot }): WriterProjectionSession;
191+}
193+export class SqliteWriterHost {
194+ readonly #storage: SqliteStorage;
195+ readonly #namespace: string;
196+ readonly #state: SqliteWriterState;
197+ readonly #log: SqliteLog;
198+ readonly #projection?: WriterProjectionHost;
199+ readonly #indexProjectionAtoms: boolean;
200+ readonly #history?: SqliteHistoryHost;
201+ constructor(
202+ storage: SqliteStorage,
203+ namespace: string,
204+ projection?: WriterProjectionHost,
205+ options: { indexProjectionAtoms?: boolean; history?: SqliteHistoryHost } = {},
206+ ) {
207+ this.#storage = storage;
208+ this.#namespace = namespace;
209+ this.#state = new SqliteWriterState(storage, namespace);
210+ this.#log = new SqliteLog(storage);
211+ this.#projection = projection;
212+ this.#indexProjectionAtoms = options.indexProjectionAtoms ?? false;
213+ this.#history = options.history;
214+ }
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 ?? "";
310+ 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;
329+ },
330+ );
331+ const result = decoded.result;
332+ digest = decoded.digest;
333+ 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+ });
372+ 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+ );
391+ 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) => {
413+ 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+ );
422+ 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));
460+ this.#history?.advance(this.#log, root, committedRoot, () => this.root(), input.validateAuthority);
461+ 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+ }
474+}
MCP
compare on this site's /mcp
CLI
abso diff 40 318 server/src/writer-host.ts --json
JSON
/christopher/abso-core/compare/40..318?file=server%2Fsrc%2Fwriter-host.ts&format=json