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 149 to 318

Compare

+884 −0 in 1 place
new file, 884 lines
1+// The engine's Project (worker/project/project.ts) behind the server's calls, with its append-only log kept in the
2+// Durable Object's SQLite. An entry longer than one row allows (init holds every starting file; SQLite rows stop at
3+// 2 MB) is split across rows and joined on load. Ported from the platform's worker/src/engine-project.ts; the
4+// writer-adoption and R2 version parts are left out.
5+
6+import { jsonValueChunks } from "../../src/engine/json-value-chunks.ts";
7+import { blame, folderBlame, why } from "../../worker/project/blame.ts";
8+import { feedEvents } from "../../worker/project/feed.ts";
9+import { type Entry, type ProjectStore as LogStore, MemoryStore, Project } from "../../worker/project/project.ts";
10+import type { EditBody, ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts";
11+import { where } from "../../worker/project/where.ts";
12+import type { PushSnapshotMetadata } from "./push-snapshot.ts";
14+/** The parts of a Durable Object's storage the log and blob store use, declared structurally so tests can stand in. */
15+export interface SqliteStorage {
16+ sql: { exec(query: string, ...bindings: unknown[]): { toArray(): unknown[] } };
17+ transactionSync<T>(fn: () => T): T;
18+}
20+// Characters per row. SQLite's 2 MB cap is in bytes, and a character is at
21+// most 3 bytes of UTF-8 (an emoji is 2 characters and 4 bytes), so 600,000 stays under it.
22+export const LOG_PART_CHARACTERS = 600_000;
24+/** An entry's JSON in rows of at most LOG_PART_CHARACTERS characters, never cutting an emoji's two halves apart. */
25+export function logParts(text: string): string[] {
26+ const parts: string[] = [];
27+ let at = 0;
28+ do {
29+ let end = Math.min(at + LOG_PART_CHARACTERS, text.length);
30+ const c = text.charCodeAt(end - 1);
31+ if (end < text.length && c >= 0xd800 && c <= 0xdbff) end--;
32+ parts.push(text.slice(at, end));
33+ at = end;
34+ } while (at < text.length);
35+ return parts;
36+}
38+/** Retains one log row plus an encoder fragment, preserving legacy row boundaries. */
39+export function* streamedLogParts(value: unknown): IterableIterator<string> {
40+ let pending = "";
41+ for (const chunk of jsonValueChunks(value)) {
42+ pending += chunk;
43+ while (pending.length > LOG_PART_CHARACTERS) {
44+ let end = LOG_PART_CHARACTERS;
45+ const last = pending.charCodeAt(end - 1);
46+ if (last >= 0xd800 && last <= 0xdbff) end--;
47+ yield pending.slice(0, end);
48+ pending = pending.slice(end);
49+ }
50+ }
51+ if (pending) yield pending;
52+}
54+/** The lines an entry's atoms write: what a loaded project's size grows with (#46, #56). */
55+function linesIn(entry: Entry): number {
56+ let n = 0;
57+ for (const a of [
58+ (entry as { atom?: { inserts?: { lines: unknown[] }[] } }).atom,
59+ (entry as { tie?: { inserts?: { lines: unknown[] }[] } }).tie,
60+ ]) {
61+ for (const r of a?.inserts ?? []) n += r.lines.length;
62+ }
63+ return n;
64+}
66+/** The version of shared an entry makes, or undefined (abso issue 78: the access check reads it without loading). */
67+function sharedVersionOf(entry: Entry): number | undefined {
68+ if (entry.type === "init") return 0;
69+ if (entry.type === "land" || entry.type === "drop") return entry.version;
70+ if (entry.type === "publish" && (entry.space ?? "") === "") return entry.version;
71+ return undefined;
72+}
74+/** Who made that version of shared, and when. Init is not a publish (abso issue 86). */
75+function lastPublishOf(entry: Entry): { agent: string; time: number } | undefined {
76+ if (entry.type === "land" || entry.type === "drop") return { agent: entry.agent, time: entry.time };
77+ if (entry.type === "publish" && (entry.space ?? "") === "") return { agent: entry.agent, time: entry.time };
78+ return undefined;
79+}
81+/** An entry's claim keys and deletes (#46): with entries and lines, what the load guard estimates memory by. */
82+function keysIn(entry: Entry): number {
83+ let n = 0;
84+ for (const a of [
85+ (entry as { atom?: Partial<Record<"writes" | "reads" | "holds" | "deletes", unknown[]>> }).atom,
86+ (entry as { tie?: Partial<Record<"writes" | "reads" | "holds" | "deletes", unknown[]>> }).tie,
87+ ]) {
88+ if (a) n += (a.writes?.length ?? 0) + (a.reads?.length ?? 0) + (a.holds?.length ?? 0) + (a.deletes?.length ?? 0);
89+ }
90+ return n;
91+}
93+export class SqliteLog implements LogStore {
94+ private storage: SqliteStorage;
95+ private next: number;
97+ constructor(storage: SqliteStorage) {
98+ this.storage = storage;
99+ storage.sql.exec(
100+ "CREATE TABLE IF NOT EXISTS log (seq INTEGER, part INTEGER, text TEXT NOT NULL, PRIMARY KEY (seq, part))",
101+ );
102+ storage.sql.exec(
103+ "CREATE TABLE IF NOT EXISTS shapes (space TEXT NOT NULL, version INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY (space, version))",
104+ );
105+ storage.sql.exec("CREATE TABLE IF NOT EXISTS counts (name TEXT PRIMARY KEY, value INTEGER NOT NULL)");
106+ storage.sql.exec("CREATE TABLE IF NOT EXISTS marks (name TEXT PRIMARY KEY, value TEXT NOT NULL)");
107+ const rows = storage.sql.exec("SELECT COALESCE(MAX(seq), -1) AS last FROM log").toArray() as { last: number }[];
108+ this.next = (rows[0]?.last ?? -1) + 1;
109+ }
111+ /** The seq the next entry would take. A copy's next page must start here. */
112+ seq(): number {
113+ return this.next;
114+ }
116+ /** Reject an oversized canonical frame before loading its text into JavaScript. */
117+ frameBytes(seq: number): number {
118+ if (!Number.isSafeInteger(seq) || seq < 0) throw Error("invalid canonical frame position");
119+ const size = this.storage.sql
120+ .exec(
121+ "SELECT COUNT(*) AS parts, COALESCE(SUM(LENGTH(CAST(text AS BLOB))), 0) AS bytes FROM log WHERE seq = ?",
122+ seq,
123+ )
124+ .toArray()[0] as { parts: number; bytes: number };
125+ if (!size || size.parts < 1 || size.parts > 256 || size.bytes < 1 || !Number.isSafeInteger(size.bytes))
126+ throw Error("canonical frame exceeds hard decoding bound or is missing");
127+ return size.bytes;
128+ }
129+ /** A larger first frame gets its own budget; later frames are deferred. */
130+ adoptionPageBytes(from: number): number {
131+ return Math.max(1_048_576, this.frameBytes(from));
132+ }
134+ boundedFrame(seq: number, maxBytes: number): string {
135+ if (
136+ !Number.isSafeInteger(seq) ||
137+ seq < 0 ||
138+ !Number.isSafeInteger(maxBytes) ||
139+ maxBytes < 1 ||
140+ maxBytes > 8_000_000
141+ )
142+ throw new Error("invalid canonical frame bound");
143+ const size = this.storage.sql
144+ .exec(
145+ "SELECT COUNT(*) AS parts, COALESCE(SUM(LENGTH(CAST(text AS BLOB))), 0) AS bytes FROM log WHERE seq = ?",
146+ seq,
147+ )
148+ .toArray()[0] as { parts: number; bytes: number };
149+ if (!size || size.parts < 1 || size.parts > 256 || size.bytes > maxBytes)
150+ throw new Error("canonical frame exceeds adoption bound or is missing");
151+ const rows = this.storage.sql.exec("SELECT part, text FROM log WHERE seq = ? ORDER BY part", seq).toArray() as {
152+ part: number;
153+ text: string;
154+ }[];
155+ if (rows.length !== size.parts || rows.some((row, part) => row.part !== part))
156+ throw new Error("canonical frame parts are incomplete");
157+ return rows.map((row) => row.text).join("");
158+ }
160+ /** Stream one canonical frame without retaining its complete JSON text. */
161+ *frameChunks(seq: number): IterableIterator<string> {
162+ if (!Number.isSafeInteger(seq) || seq < 0) throw Error("invalid canonical frame position");
163+ let expected = 0;
164+ for (;;) {
165+ const rows = this.storage.sql
166+ .exec("SELECT part, text FROM log WHERE seq = ? AND part >= ? ORDER BY part LIMIT 1", seq, expected)
167+ .toArray() as { part: number; text: string }[];
168+ if (!rows.length) {
169+ if (!expected) throw Error("canonical frame is missing");
170+ return;
171+ }
172+ const row = rows[0]!;
173+ if (row.part !== expected || row.text.length > LOG_PART_CHARACTERS)
174+ throw Error("canonical frame parts are incomplete or oversized");
175+ expected++;
176+ yield row.text;
177+ }
178+ }
180+ /** Refreshes the in-memory cursor after an enclosing transaction rolls back. */
181+ refreshSequence(): void {
182+ const rows = this.storage.sql.exec("SELECT COALESCE(MAX(seq), -1) AS last FROM log").toArray() as {
183+ last: number;
184+ }[];
185+ this.next = (rows[0]?.last ?? -1) + 1;
186+ }
188+ /** Monotonic cache invalidation epoch for every canonical log mutation. */
189+ generation(): number {
190+ const rows = this.storage.sql.exec("SELECT value FROM marks WHERE name = ?", "generation").toArray() as {
191+ value: string;
192+ }[];
193+ const generation = Number(rows[0]?.value ?? 0);
194+ if (!Number.isSafeInteger(generation) || generation < 0) throw new Error("canonical log generation is invalid");
195+ return generation;
196+ }
198+ /**
199+ * Lines ever recorded (#46, #56): what loading the project costs grows with
200+ * this, not with the log's size, so a guard can read it without loading.
201+ * Kept with each append; undefined for a log written before the count,
202+ * until it next loads.
203+ */
204+ lineCount(): number | undefined {
205+ const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'lines'").toArray() as {
206+ value: number;
207+ }[];
208+ return rows[0]?.value;
209+ }
211+ /**
212+ * The newest version of shared, without loading the project (abso issue 78: the website's access check asked
213+ * every project's engine for it). Kept with each append; a log from before the count is read once by streaming.
214+ */
215+ sharedVersion(): number {
216+ const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'shared'").toArray() as {
217+ value: number;
218+ }[];
219+ if (rows[0] !== undefined) return rows[0].value;
220+ let version = -1;
221+ for (const e of this.#entries()) version = sharedVersionOf(e) ?? version;
222+ if (version >= 0)
223+ this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('shared', ?)", version);
224+ return version;
225+ }
227+ /**
228+ * Who published shared's newest version, and when, without loading the project (abso issue 86).
229+ * Null when shared has no publish yet. A log from before the mark is read once by streaming.
230+ */
231+ lastPublish(): { agent: string; time: number } | null {
232+ const rows = this.storage.sql.exec("SELECT value FROM marks WHERE name = ?", "last").toArray() as {
233+ value: string;
234+ }[];
235+ if (rows[0] !== undefined) return JSON.parse(rows[0].value) as { agent: string; time: number };
236+ let last: { agent: string; time: number } | null = null;
237+ for (const e of this.#entries()) {
238+ const found = lastPublishOf(e);
239+ if (found) last = found;
240+ }
241+ if (last)
242+ this.storage.sql.exec("INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)", "last", JSON.stringify(last));
243+ return last;
244+ }
246+ /**
247+ * How big the log is, without loading the project or scanning it twice (ask 160).
248+ * Entries are the next seq. Chars are kept like lines; a log from before the
249+ * count is summed once, then kept. GET /projects' 2-second wait needs this
250+ * to stay a storage read: SUM(LENGTH(text)) over abso's log misses it.
251+ */
252+ logSize(): { chars: number; entries: number } {
253+ const entries = this.next;
254+ const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'chars'").toArray() as {
255+ value: number;
256+ }[];
257+ if (rows[0] !== undefined) return { chars: rows[0].value, entries };
258+ if (entries === 0) return { chars: 0, entries: 0 };
259+ const summed = this.storage.sql.exec("SELECT COALESCE(SUM(LENGTH(text)), 0) AS chars FROM log").toArray()[0] as
260+ | { chars: number }
261+ | undefined;
262+ const chars = summed?.chars ?? 0;
263+ this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('chars', ?)", chars);
264+ return { chars, entries };
265+ }
267+ /** Claim keys and deletes ever recorded (#46), kept like the line count; undefined before they were counted. */
268+ keyCount(): number | undefined {
269+ const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'keys'").toArray() as { value: number }[];
270+ return rows[0]?.value;
271+ }
273+ /**
274+ * The lines and keys ever recorded, counting a log from before either count without loading the project
275+ * (#46): one entry parsed at a time, so a log the load guard would refuse can still be measured. Kept once counted.
276+ */
277+ countSizes(): { lines: number; keys: number } {
278+ const lines = this.lineCount();
279+ const keys = this.keyCount();
280+ if (lines !== undefined && keys !== undefined) return { lines, keys };
281+ let l = 0;
282+ let k = 0;
283+ for (const e of this.#entries()) {
284+ l += linesIn(e);
285+ k += keysIn(e);
286+ }
287+ this.#keep(lines === undefined ? l : undefined, keys === undefined ? k : undefined);
288+ return { lines: lines ?? l, keys: keys ?? k };
289+ }
291+ /** Stores the counts given. */
292+ #keep(lines: number | undefined, keys: number | undefined): void {
293+ if (lines !== undefined)
294+ this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('lines', ?)", lines);
295+ if (keys !== undefined)
296+ this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('keys', ?)", keys);
297+ }
299+ /** Every stored entry, in order. Rows are read one at a time, so loading never holds the whole log's text at once (#43). */
300+ *entries(): Iterable<Entry> {
301+ // A log from before the counts: counted as it loads, and kept.
302+ const countLines = this.lineCount() === undefined;
303+ const countKeys = this.keyCount() === undefined;
304+ let lines = 0;
305+ let keys = 0;
306+ for (const e of this.#entries()) {
307+ if (countLines) lines += linesIn(e);
308+ if (countKeys) keys += keysIn(e);
309+ yield e;
310+ }
311+ this.#keep(countLines ? lines : undefined, countKeys ? keys : undefined);
312+ }
314+ *#entries(from = 0): Iterable<Entry> {
315+ // A Workers cursor is iterable; a test's stand-in may only have toArray.
316+ const cursor = this.storage.sql.exec("SELECT seq, text FROM log WHERE seq >= ? ORDER BY seq, part", from) as {
317+ toArray(): unknown[];
318+ } & Partial<Iterable<unknown>>;
319+ const rows = (cursor[Symbol.iterator] ? cursor : cursor.toArray()) as Iterable<{ seq: number; text: string }>;
320+ let seq = -1;
321+ let text = "";
322+ for (const r of rows) {
323+ if (r.seq !== seq && seq >= 0) yield JSON.parse(text) as Entry;
324+ if (r.seq !== seq) text = "";
325+ seq = r.seq;
326+ text += r.text;
327+ }
328+ if (seq >= 0) yield JSON.parse(text) as Entry;
329+ }
331+ /**
332+ * For backups (#29): the entries from seq `from` on as their stored JSON
333+ * text (not parsed, so an export holds the project up as little as it
334+ * can), at most `limit` of them and about 8 MB (always at least one), and
335+ * the seq to ask for next, or null at the end.
336+ */
337+ page(from: number, limit: number): { texts: string[]; next: number | null } {
338+ const rows = this.storage.sql
339+ .exec("SELECT seq, text FROM log WHERE seq >= ? AND seq < ? ORDER BY seq, part", from, from + limit)
340+ .toArray() as { seq: number; text: string }[];
341+ const texts: string[] = [];
342+ let seq = -1;
343+ let text = "";
344+ let size = 0;
345+ let next: number | null = null;
346+ for (const r of rows) {
347+ if (r.seq < from || r.seq >= from + limit) continue;
348+ if (r.seq !== seq && seq >= 0) {
349+ texts.push(text);
350+ size += text.length;
351+ if (size > 8_000_000) {
352+ next = r.seq;
353+ break;
354+ }
355+ }
356+ if (r.seq !== seq) text = "";
357+ seq = r.seq;
358+ text += r.text;
359+ }
360+ if (next === null && seq >= 0) texts.push(text);
361+ if (next === null && from + limit < this.next) next = from + limit;
362+ return { texts, next };
363+ }
365+ /** Up to `limit` entries from position `from`, parsed (#41: the feed and replay). */
366+ since(from: number, limit: number): Entry[] {
367+ const out: Entry[] = [];
368+ for (let at = from; out.length < limit; ) {
369+ const { texts, next } = this.page(at, limit - out.length);
370+ for (const t of texts) out.push(JSON.parse(t) as Entry);
371+ if (next === null || texts.length === 0) break;
372+ at = next;
373+ }
374+ return out;
375+ }
377+ /** Removes every entry: only for a restore whose log didn't load (#29). */
378+ clear(): void {
379+ const generation = this.generation() + 1;
380+ this.storage.transactionSync(() => {
381+ this.storage.sql.exec("DELETE FROM log");
382+ this.storage.sql.exec("DELETE FROM shapes");
383+ this.storage.sql.exec("DELETE FROM counts");
384+ this.storage.sql.exec("DELETE FROM marks WHERE name != ?", "generation");
385+ this.storage.sql.exec(
386+ "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)",
387+ "generation",
388+ String(generation),
389+ );
390+ });
391+ this.next = 0;
392+ }
394+ /**
395+ * Each version's changed files, kept between loads (#41, the Files pages):
396+ * worked out from the log, never part of it, so an older Worker ignores
397+ * the table and nothing about the project depends on it.
398+ */
399+ shapes(): {
400+ get(space: string, version: number): string | undefined;
401+ put(space: string, version: number, value: string): void;
402+ } {
403+ const sql = this.storage.sql;
404+ return {
405+ get: (space, version) =>
406+ (
407+ sql.exec("SELECT value FROM shapes WHERE space = ? AND version = ?", space, version).toArray() as {
408+ value: string;
409+ }[]
410+ )[0]?.value,
411+ put: (space, version, value) =>
412+ void sql.exec("INSERT OR REPLACE INTO shapes (space, version, value) VALUES (?, ?, ?)", space, version, value),
413+ };
414+ }
416+ append(entries: readonly Entry[]): void {
417+ if (!entries.length) return;
418+ let next = this.next;
419+ this.storage.transactionSync(() => {
420+ const lines = entries.reduce((n, e) => n + linesIn(e), 0);
421+ if (lines > 0)
422+ this.storage.sql.exec(
423+ "INSERT INTO counts (name, value) VALUES ('lines', ?) ON CONFLICT(name) DO UPDATE SET value = value + ?",
424+ lines,
425+ lines,
426+ );
427+ // The newest version of shared: appended entries are the newest, so the last one that makes a version wins.
428+ for (const e of entries) {
429+ const v = sharedVersionOf(e);
430+ if (v !== undefined)
431+ this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('shared', ?)", v);
432+ const last = lastPublishOf(e);
433+ if (last)
434+ this.storage.sql.exec(
435+ "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)",
436+ "last",
437+ JSON.stringify(last),
438+ );
439+ }
440+ // Keys are only added to once counted: a log from before the key count is counted whole first (countSizes).
441+ const keys = entries.reduce((n, e) => n + keysIn(e), 0);
442+ if (keys > 0) this.storage.sql.exec("UPDATE counts SET value = value + ? WHERE name = 'keys'", keys);
443+ let chars = 0;
444+ for (const entry of entries) {
445+ let part = 0;
446+ for (const text of streamedLogParts(entry)) {
447+ chars += text.length;
448+ this.storage.sql.exec("INSERT INTO log (seq, part, text) VALUES (?, ?, ?)", next, part++, text);
449+ }
450+ next++;
451+ }
452+ // Chars are only added to once counted: a log from before the count is summed whole first (logSize).
453+ if (chars > 0) this.storage.sql.exec("UPDATE counts SET value = value + ? WHERE name = 'chars'", chars);
454+ const generation = this.generation() + 1;
455+ this.storage.sql.exec(
456+ "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)",
457+ "generation",
458+ String(generation),
459+ );
460+ });
461+ this.next = next;
462+ }
463+}
465+/** The engine's Project as the Worker's ProjectCalls; the clock comes from here. */
466+export class EngineProject implements ProjectCalls, ProjectHistory {
467+ blame(file: string, from?: number, to?: number, version?: number, draft?: string, agent?: string) {
468+ return blame(this.project, file, from, to, version, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });
469+ }
470+ folderBlame(folder: string, version?: number, draft?: string, agent?: string) {
471+ return folderBlame(this.project, folder, version, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });
472+ }
473+ tree(folder: string, version?: number, draft?: string | null, agent?: string, authors?: boolean) {
474+ return this.project.tree(folder, {
475+ ...(version !== undefined ? { version } : {}),
476+ draft: draft ?? null,
477+ ...(agent !== undefined ? { agent } : {}),
478+ ...(authors ? { authors } : {}),
479+ });
480+ }
481+ pathLife(path: string, version?: number, draft?: string | null) {
482+ return this.project.pathLife(path, { ...(version !== undefined ? { version } : {}), draft: draft ?? null });
483+ }
484+ follow(path: string, version: number, from: number, to: number, at?: number, draft?: string | null) {
485+ return this.project.follow(path, version, from, to, { ...(at !== undefined ? { at } : {}), draft: draft ?? null });
486+ }
487+ pathsOf(agent: string) {
488+ return this.project.pathsOf(agent);
489+ }
490+ draftState(name: string) {
491+ return this.project.draftState(name);
492+ }
493+ collisions(file?: string, folder?: string) {
494+ return this.project.collisions({
495+ ...(file !== undefined ? { file } : {}),
496+ ...(folder !== undefined ? { folder } : {}),
497+ });
498+ }
499+ why(file: string, line: number, draft?: string, agent?: string, version?: number) {
500+ return why(this.project, file, line, {
501+ ...(draft ? { draft } : {}),
502+ ...(agent ? { agent } : {}),
503+ ...(version !== undefined ? { version } : {}),
504+ });
505+ }
506+ where() {
507+ return where(this.project);
508+ }
509+ refusals(agent?: string, limit?: number) {
510+ return this.project.refusals({ ...(agent ? { agent } : {}), ...(limit !== undefined ? { limit } : {}) });
511+ }
513+ log(draft: string | null, limit?: number, path?: string, agent?: string, before?: number, follow?: boolean) {
514+ return this.project.log({
515+ draft,
516+ ...(limit !== undefined ? { limit } : {}),
517+ ...(path !== undefined ? { path } : {}),
518+ ...(agent ? { agent } : {}),
519+ ...(before !== undefined ? { before } : {}),
520+ ...(follow ? { follow } : {}),
521+ });
522+ }
523+ fileAt(path: string, version: number, draft: string | null, agent?: string) {
524+ return this.project.fileAt(path, version, { draft, ...(agent ? { agent } : {}) });
525+ }
526+ compare(from: number, to: number, draft: string | null, agent?: string, summary?: boolean) {
527+ const where = { draft, ...(agent ? { agent } : {}) };
528+ return summary ? this.project.compareSummary(from, to, where) : this.project.compare(from, to, where);
529+ }
530+ without(version: number, versions: readonly number[]) {
531+ return this.project.without(version, versions);
532+ }
533+ show(version: number, draft: string | null, agent?: string) {
534+ return this.project.show(version, { draft, ...(agent ? { agent } : {}) });
535+ }
536+ diff(agent: string) {
537+ return this.project.diff(agent);
538+ }
539+ syncFull(agent: string, label?: string) {
540+ return this.project.sync(agent, { full: true, ...(label !== undefined ? { label } : {}) });
541+ }
542+ agentPaths(agent: string) {
543+ return this.project.agentPaths(agent);
544+ }
545+ pathsAt(version?: number, draft?: string | null) {
546+ return this.project.pathsAt(version, draft ?? null);
547+ }
548+ syncTo(agent: string, label: string) {
549+ return this.project.sync(agent, { label });
550+ }
551+ label(agent: string, name: string, version?: number, remove?: boolean) {
552+ return this.project.label(agent, name, version, Date.now(), { remove: remove === true });
553+ }
554+ labels() {
555+ return this.project.labels();
556+ }
557+ amend(agent: string, message: string) {
558+ return this.project.amend(agent, message, Date.now());
559+ }
560+ pluck(agent: string, draft: string, versions: number[], message: string, withDependencies?: boolean) {
561+ return this.project.pluck(agent, draft, versions, message, Date.now(), {
562+ withDependencies: withDependencies === true,
563+ });
564+ }
565+ drop(agent: string, versions: number[], message: string, withDependents?: boolean) {
566+ return this.project.drop(agent, versions, message, Date.now(), { withDependents: withDependents === true });
567+ }
568+ announce(agent: string, text: string, to?: string[], how?: string) {
569+ return this.project.announce(agent, text, to, Date.now(), how);
570+ }
572+ announcePerson(person: { id: string; name: string }, text: string, to?: string[]) {
573+ return this.project.announcePerson(person, text, to, Date.now());
574+ }
575+ /** A seat's earlier chat hears that another chat used the seat (277, groups); as abso's worker has it. */
576+ seatNotice(agent: string, place: string, key: string) {
577+ return this.project.seatNotice(agent, place, key);
578+ }
579+ starting(agent: string, text: string | null, files?: string[], options: { issue?: unknown; done?: unknown } = {}) {
580+ return this.project.starting(agent, text, files, Date.now(), options);
581+ }
582+ news(agent: string) {
583+ return this.project.news(agent);
584+ }
585+ restore(agent: string, files: string[] | null) {
586+ return this.project.restore(agent, files, Date.now());
587+ }
589+ private project: Project;
591+ /** Reads stored entries by log position, for the feed and replay (#41); absent, those answer 501. */
592+ private readonly read: ((from: number, limit: number) => Entry[]) | undefined;
593+ private readonly store: SqliteLog | undefined;
594+ private readonly historical: (<T>(at: number, operation: (project: Project) => T) => T) | undefined;
596+ constructor(
597+ project: Project,
598+ read?: (from: number, limit: number) => Entry[],
599+ store?: SqliteLog,
600+ historical?: <T>(at: number, operation: (project: Project) => T) => T,
601+ ) {
602+ this.project = project;
603+ this.read = read;
604+ this.store = store;
605+ this.historical = historical;
606+ }
608+ /** The project's events from log position `from` (#41): reading consumes nothing. */
609+ feed(from: number, limit = 500) {
610+ if (!this.read) throw Object.assign(new Error("the feed needs the log"), { code: "not-implemented" });
611+ const end = this.project.logLength;
612+ const start = Math.max(0, Math.min(from, end));
613+ // Discard each canonical payload after extracting its event. A feed page must
614+ // not retain every historical file payload in the requested range.
615+ const events = [];
616+ let next = start;
617+ while (next < end && next - start < limit) {
618+ const entries = this.read(next, 1);
619+ if (entries.length === 0) break;
620+ events.push(...feedEvents(entries, next));
621+ next += entries.length;
622+ }
623+ // A drop event names the files it took out (#41), so a timeline needs no read per drop.
624+ const enriched = events.map((e) => {
625+ if (e.type !== "drop" || e.version === undefined) return e;
626+ const v = this.project.log({ limit: 1, before: e.version + 1 }).versions[0];
627+ return v && v.version === e.version ? { ...e, dropped: v.files } : e;
628+ });
629+ return { next, end, events: enriched };
630+ }
632+ /** The log position for a time (ms since 1970) or a version of shared (#41). */
633+ position(q: { time?: number; version?: number }) {
634+ return this.project.position(q);
635+ }
636+ /** Whether the Worker runs the queue's check; until it does, "queue": true does nothing. */
637+ setCheckerReady(ready: boolean): void {
638+ this.project.checkerReady = ready;
639+ }
640+ /** An agent withdraws what it has queued (#39). */
641+ unqueue(agent: string) {
642+ return this.project.unqueue(agent, Date.now());
643+ }
644+ /** The log length now: what a long-poll waits to see grow. */
645+ logLength() {
646+ return this.project.logLength;
647+ }
648+ /** An agent's draft diff for a reader: never creates the agent (#41). */
649+ diffOf(agent: string) {
650+ return this.project.diffOf(agent);
651+ }
652+ /** Every agent with unpublished changes: its files and how many changes (#41). */
653+ change(id: number) {
654+ return this.project.change(id);
655+ }
657+ changes(since: number, limit: number, before?: number, issue?: number) {
658+ return this.project.changes(since, limit, before, issue);
659+ }
661+ move(agent: string, from: string, to: string) {
662+ return this.project.move(agent, from, to, Date.now());
663+ }
665+ note(agent: string, body: Record<string, unknown>) {
666+ return this.project.note(agent, body, Date.now());
667+ }
669+ notePerson(person: { id: string; name: string }, body: Record<string, unknown>) {
670+ return this.project.notePerson(person, body, Date.now());
671+ }
673+ closeNotePerson(person: { id: string; name: string }, id: number, how: unknown) {
674+ return this.project.closeNotePerson(person, id, how, Date.now());
675+ }
677+ closeNote(agent: string, id: number, how: unknown) {
678+ return this.project.closeNote(agent, id, how, Date.now());
679+ }
681+ notes(options: { file?: string; change?: number; open?: boolean }) {
682+ return this.project.notes(options);
683+ }
685+ ribbon() {
686+ return this.project.ribbon();
687+ }
689+ drafts() {
690+ const s = this.project.status();
691+ return {
692+ version: s.version,
693+ drafts: s.agents
694+ .filter((a) => a.draftChanges > 0)
695+ .map((a) => ({ agent: a.agent, draft: a.draft, base: a.base, draftChanges: a.draftChanges, files: a.files })),
696+ };
697+ }
698+ /** The last copy replay loaded: scrubbing forward from it applies only the entries after it. */
699+ private replica: Project | undefined;
701+ /** The project as it stood with the first `at` log entries (#41, replay). */
702+ private at(at: number): Project {
703+ if (!this.read) throw Object.assign(new Error("replay needs the log"), { code: "not-implemented" });
704+ const n = Math.max(0, Math.min(at, this.project.logLength));
705+ const r = this.replica;
706+ if (r && r.logLength === n) return r;
707+ if (r && r.logLength < n) {
708+ r.catchUp(this.read(r.logLength, n - r.logLength));
709+ return r;
710+ }
711+ this.replica = Project.load(this.read(0, n), new MemoryStore());
712+ return this.replica;
713+ }
714+ statusAt(at: number) {
715+ if (this.historical)
716+ return this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({
717+ at: Math.min(at, this.project.logLength),
718+ ...(p.initialized ? p.status() : { version: -1, agents: [] }),
719+ }));
720+ const p = this.at(at);
721+ const answer = {
722+ at: Math.min(at, this.project.logLength),
723+ ...(p.initialized ? p.status() : { version: -1, agents: [] }),
724+ };
725+ this.release();
726+ return answer;
727+ }
728+ whereAt(at: number) {
729+ if (this.historical)
730+ return this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({
731+ at: Math.min(at, this.project.logLength),
732+ ...(p.initialized ? where(p) : { version: -1, files: {} }),
733+ }));
734+ const p = this.at(at);
735+ const answer = {
736+ at: Math.min(at, this.project.logLength),
737+ ...(p.initialized ? where(p) : { version: -1, files: {} }),
738+ };
739+ this.release();
740+ return answer;
741+ }
743+ /**
744+ * Drop the replay copy after each read (#46): a second copy of a large
745+ * project's history doubles its memory, past a Durable Object's 128 MB.
746+ * Each scrub replays from the start instead (about 0.2 s on game).
747+ */
748+ private release(): void {
749+ this.replica = undefined;
750+ }
752+ /** hasBlob says whether the project holds a blob's bytes (#27); without it, every blob is refused. */
753+ /** whole stores and reads files kept whole (#46); without it every text file is tracked by line. */
754+ static open(
755+ storage: SqliteStorage,
756+ hasBlob?: (sha256: string) => boolean,
757+ whole?: { keep(text: string): string; read(sha: string): string | null },
758+ ): EngineProject {
759+ const log = new SqliteLog(storage);
760+ return new EngineProject(
761+ Project.load(log.entries(), log, {
762+ ...(hasBlob ? { hasBlob } : {}),
763+ ...(whole ? { whole } : {}),
764+ now: () => Date.now(),
765+ shapes: log.shapes(),
766+ entryAt: (at) => log.since(at, 1)[0]!,
767+ }),
768+ (from, limit) => log.since(from, limit),
769+ log,
770+ );
771+ }
773+ exists() {
774+ return this.project.initialized;
775+ }
776+ /** Committed log epoch for host-side cache invalidation; it does not dispatch work. */
777+ committedGeneration(): number {
778+ return this.store?.generation() ?? 0;
779+ }
780+ init(
781+ files: Record<string, string>,
782+ modes?: Record<string, { exec?: boolean; link?: string | null }>,
783+ blobs?: Record<string, string>,
784+ ) {
785+ return this.project.init(files, Date.now(), modes ?? {}, blobs ?? {});
786+ }
787+ edit(agent: string, body: EditBody) {
788+ return this.project.edit(agent, body as Parameters<Project["edit"]>[1], Date.now());
789+ }
790+ record(
791+ agent: string,
792+ files: Record<string, string | null>,
793+ modes?: Record<string, { exec?: boolean; link?: string | null }>,
794+ blobs?: Record<string, string>,
795+ meta?: { session?: string; subagent?: string; client?: string },
796+ ) {
797+ return this.project.record(agent, files, Date.now(), modes ?? {}, blobs ?? {}, meta ?? {});
798+ }
799+ publish(agent: string, message: string, asIs?: boolean) {
800+ return this.project.publish(agent, message, Date.now(), { asIs: asIs === true });
801+ }
802+ sync(agent: string) {
803+ return this.project.sync(agent);
804+ }
805+ status() {
806+ return this.project.status();
807+ }
808+ switchTo(agent: string, name: string | null, carry = false) {
809+ return this.project.switchTo(agent, name, Date.now(), { carry });
810+ }
811+ land(agent: string, message: string) {
812+ return this.project.land(agent, message, Date.now());
813+ }
814+ ingest(input: Parameters<Project["ingest"]>[0], time: number) {
815+ return this.project.ingest(input, time);
816+ }
817+ syncDraft(agent: string) {
818+ return this.project.syncDraft(agent, Date.now());
819+ }
820+ filesAt(version: number) {
821+ return this.project.viewAt(version).files();
822+ }
823+ fileTextAt(version: number, path: string): string {
824+ return this.project.viewAt(version).text(path);
825+ }
826+ /** One scoped batch: at most 64 files and 64 Ki characters plus one whole file. */
827+ fileTextsAt(version: number, paths: readonly string[]): Record<string, string> {
828+ const view = this.project.viewAt(version);
829+ const files: Record<string, string> = Object.create(null);
830+ let characters = 0;
831+ for (const path of paths.slice(0, 64)) {
832+ const text = view.attrs(path).link !== null ? "" : view.text(path);
833+ files[path] = text;
834+ characters += text.length;
835+ if (characters >= 65536) break;
836+ }
837+ return files;
838+ }
839+ /** Capture metadata now; each text read reopens the captured version in a fresh host scope. */
840+ sharedPushMetadata(): PushSnapshotMetadata {
841+ const version = this.project.version;
842+ const view = this.project.viewAt(version);
843+ const paths: string[] = [];
844+ const modes: PushSnapshotMetadata["modes"] = Object.create(null);
845+ const blobs: Record<string, string> = Object.create(null);
846+ for (const path of view.paths()) {
847+ const attrs = view.attrs(path);
848+ modes[path] = { exec: attrs.exec, link: attrs.link };
849+ if (attrs.blob !== null) blobs[path] = attrs.blob;
850+ else paths.push(path);
851+ }
852+ const by = version > 0 ? this.project.published(version) : undefined;
853+ return { version, paths, modes, blobs, ...(by ? { last: { agent: by.agent, message: by.message } } : {}) };
854+ }
855+ blobsAt(version: number) {
856+ return this.project.viewAt(version).blobs();
857+ }
858+ /**
859+ * Shared's newest version. Its files and modes are laid out on first read: every call reads shared().version
860+ * before and after its op, and laying out the files reads each file's text from the log, about 0.5 s on abso
861+ * (abso 299).
862+ */
863+ shared() {
864+ const version = this.project.version;
865+ const by = version > 0 ? this.project.published(version) : undefined;
866+ const blobs = this.project.blobs();
867+ const project = this.project;
868+ let files: Record<string, string> | undefined;
869+ let modes: ReturnType<Project["modes"]> | undefined;
870+ return {
871+ version,
872+ get files() {
873+ files ??= project.files();
874+ return files;
875+ },
876+ get modes() {
877+ modes ??= project.modes();
878+ return modes;
879+ },
880+ ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
881+ ...(by ? { last: { agent: by.agent, message: by.message } } : {}),
882+ };
883+ }
884+}
MCP
compare on this site's /mcp
CLI
abso diff 149 318 server/src/engine-project.ts --json
JSON
/christopher/abso-core/compare/149..318?file=server%2Fsrc%2Fengine-project.ts&format=json