- MCP
- blame on this site's /mcp
- CLI
- abso blame server/src/engine-project.ts --version 192 --json
- JSON
- /christopher/abso-core/blame/server/src/engine-project.ts?version=192&format=json
875 linesspeed 81% · codex-capacity-chair 18% · candidates 1%Last change candidates in version 186,
875 lines from 11 changes in 8 versions.
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare1// 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.
codex-capacity-chair167Stream canonical log append and bound JSON string decoding allocationsCompare6import { jsonValueChunks } from "../../src/engine/json-value-chunks.ts";
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare7import { blame, folderBlame, why } from "../../worker/project/blame.ts";
8import { feedEvents } from "../../worker/project/feed.ts";
9import { type Entry, type ProjectStore as LogStore, MemoryStore, Project } from "../../worker/project/project.ts";
10import type { EditBody, ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts";
11import { where } from "../../worker/project/where.ts";
codex-capacity-chair177Read Artifacts snapshots in version-pinned batches; cleared in review ask 45Compare12import 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. */
15export 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.
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare22export const LOG_PART_CHARACTERS = 600_000;
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare24/** An entry's JSON in rows of at most LOG_PART_CHARACTERS characters, never cutting an emoji's two halves apart. */
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare25export function logParts(text: string): string[] {
26 const parts: string[] = [];
27 let at = 0;
28 do {
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare29 let end = Math.min(at + LOG_PART_CHARACTERS, text.length);
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare30 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}
codex-capacity-chair167Stream canonical log append and bound JSON string decoding allocationsCompare38/** Retains one log row plus an encoder fragment, preserving legacy row boundaries. */
39export 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}
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare54/** The lines an entry's atoms write: what a loaded project's size grows with (#46, #56). */
55function 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). */
67function 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). */
75function 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. */
82function 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}
93export 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 }
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare116 /** Reject an oversized canonical frame before loading its text into JavaScript. */
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare117 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 }
codex-capacity-chair157Share the SQLite writer and projection host with the open serverCompare134 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("");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare158 }
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;
codex-capacity-chair134Stream project conflict candidates and resolver intersectionsCompare164 for (;;) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare165 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 }
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 }
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare188 /** 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) {
codex-capacity-chair167Stream canonical log append and bound JSON string decoding allocationsCompare445 let part = 0;
446 for (const text of streamedLogParts(entry)) {
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare447 chars += text.length;
codex-capacity-chair167Stream canonical log append and bound JSON string decoding allocationsCompare448 this.storage.sql.exec("INSERT INTO log (seq, part, text) VALUES (?, ?, ?)", next, part++, text);
449 }
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. */
466export 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) {
500 return why(this.project, file, line, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });
501 }
502 where() {
503 return where(this.project);
504 }
505 refusals(agent?: string, limit?: number) {
506 return this.project.refusals({ ...(agent ? { agent } : {}), ...(limit !== undefined ? { limit } : {}) });
507 }
509 log(draft: string | null, limit?: number, path?: string, agent?: string, before?: number, follow?: boolean) {
510 return this.project.log({
511 draft,
512 ...(limit !== undefined ? { limit } : {}),
513 ...(path !== undefined ? { path } : {}),
514 ...(agent ? { agent } : {}),
515 ...(before !== undefined ? { before } : {}),
516 ...(follow ? { follow } : {}),
517 });
518 }
519 fileAt(path: string, version: number, draft: string | null, agent?: string) {
520 return this.project.fileAt(path, version, { draft, ...(agent ? { agent } : {}) });
521 }
522 compare(from: number, to: number, draft: string | null, agent?: string) {
523 return this.project.compare(from, to, { draft, ...(agent ? { agent } : {}) });
524 }
candidates186Read a version of shared without some earlier versions: abso show <N> --without A,B shows what differs and abso export <dir> --version N --without A,B writes the files. The server's GET without?version=&versions= checks the set left exactly as asked: when a version it keeps builds on one left out, it refuses with that chain, the files and the wider set that works, and never widens it. Atoms keep their ids and authors; shared and its log don't change; the same ask gives the same tree hash.Compare525 without(version: number, versions: readonly number[]) {
526 return this.project.without(version, versions);
527 }
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare528 show(version: number, draft: string | null, agent?: string) {
529 return this.project.show(version, { draft, ...(agent ? { agent } : {}) });
530 }
531 diff(agent: string) {
532 return this.project.diff(agent);
533 }
534 syncFull(agent: string, label?: string) {
535 return this.project.sync(agent, { full: true, ...(label !== undefined ? { label } : {}) });
536 }
537 agentPaths(agent: string) {
538 return this.project.agentPaths(agent);
539 }
540 pathsAt(version?: number, draft?: string | null) {
541 return this.project.pathsAt(version, draft ?? null);
542 }
543 syncTo(agent: string, label: string) {
544 return this.project.sync(agent, { label });
545 }
546 label(agent: string, name: string, version?: number, remove?: boolean) {
547 return this.project.label(agent, name, version, Date.now(), { remove: remove === true });
548 }
549 labels() {
550 return this.project.labels();
551 }
552 amend(agent: string, message: string) {
553 return this.project.amend(agent, message, Date.now());
554 }
555 pluck(agent: string, draft: string, versions: number[], message: string, withDependencies?: boolean) {
556 return this.project.pluck(agent, draft, versions, message, Date.now(), {
557 withDependencies: withDependencies === true,
558 });
559 }
560 drop(agent: string, versions: number[], message: string, withDependents?: boolean) {
561 return this.project.drop(agent, versions, message, Date.now(), { withDependents: withDependents === true });
562 }
563 announce(agent: string, text: string, to?: string[], how?: string) {
564 return this.project.announce(agent, text, to, Date.now(), how);
565 }
567 announcePerson(person: { id: string; name: string }, text: string, to?: string[]) {
568 return this.project.announcePerson(person, text, to, Date.now());
569 }
570 starting(agent: string, text: string | null, files?: string[], options: { issue?: unknown; done?: unknown } = {}) {
571 return this.project.starting(agent, text, files, Date.now(), options);
572 }
573 news(agent: string) {
574 return this.project.news(agent);
575 }
576 restore(agent: string, files: string[] | null) {
577 return this.project.restore(agent, files, Date.now());
578 }
580 private project: Project;
582 /** Reads stored entries by log position, for the feed and replay (#41); absent, those answer 501. */
583 private readonly read: ((from: number, limit: number) => Entry[]) | undefined;
584 private readonly store: SqliteLog | undefined;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare585 private readonly historical: (<T>(at: number, operation: (project: Project) => T) => T) | undefined;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare587 constructor(
588 project: Project,
589 read?: (from: number, limit: number) => Entry[],
590 store?: SqliteLog,
591 historical?: <T>(at: number, operation: (project: Project) => T) => T,
592 ) {
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare593 this.project = project;
594 this.read = read;
595 this.store = store;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare596 this.historical = historical;
599 /** The project's events from log position `from` (#41): reading consumes nothing. */
600 feed(from: number, limit = 500) {
601 if (!this.read) throw Object.assign(new Error("the feed needs the log"), { code: "not-implemented" });
602 const end = this.project.logLength;
603 const start = Math.max(0, Math.min(from, end));
codex-capacity-chair158Integrate opt-in disk-first project runtime with cold-object transactionsCompare604 // Discard each canonical payload after extracting its event. A feed page must
605 // not retain every historical file payload in the requested range.
606 const events = [];
607 let next = start;
608 while (next < end && next - start < limit) {
609 const entries = this.read(next, 1);
610 if (entries.length === 0) break;
611 events.push(...feedEvents(entries, next));
612 next += entries.length;
613 }
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare614 // A drop event names the files it took out (#41), so a timeline needs no read per drop.
codex-capacity-chair158Integrate opt-in disk-first project runtime with cold-object transactionsCompare615 const enriched = events.map((e) => {
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare616 if (e.type !== "drop" || e.version === undefined) return e;
617 const v = this.project.log({ limit: 1, before: e.version + 1 }).versions[0];
618 return v && v.version === e.version ? { ...e, dropped: v.files } : e;
619 });
codex-capacity-chair158Integrate opt-in disk-first project runtime with cold-object transactionsCompare620 return { next, end, events: enriched };
623 /** The log position for a time (ms since 1970) or a version of shared (#41). */
624 position(q: { time?: number; version?: number }) {
625 return this.project.position(q);
626 }
627 /** Whether the Worker runs the queue's check; until it does, "queue": true does nothing. */
628 setCheckerReady(ready: boolean): void {
629 this.project.checkerReady = ready;
630 }
631 /** An agent withdraws what it has queued (#39). */
632 unqueue(agent: string) {
633 return this.project.unqueue(agent, Date.now());
634 }
635 /** The log length now: what a long-poll waits to see grow. */
636 logLength() {
637 return this.project.logLength;
638 }
639 /** An agent's draft diff for a reader: never creates the agent (#41). */
640 diffOf(agent: string) {
641 return this.project.diffOf(agent);
642 }
643 /** Every agent with unpublished changes: its files and how many changes (#41). */
644 change(id: number) {
645 return this.project.change(id);
646 }
648 changes(since: number, limit: number, before?: number, issue?: number) {
649 return this.project.changes(since, limit, before, issue);
650 }
652 move(agent: string, from: string, to: string) {
653 return this.project.move(agent, from, to, Date.now());
654 }
656 note(agent: string, body: Record<string, unknown>) {
657 return this.project.note(agent, body, Date.now());
658 }
660 notePerson(person: { id: string; name: string }, body: Record<string, unknown>) {
661 return this.project.notePerson(person, body, Date.now());
662 }
664 closeNotePerson(person: { id: string; name: string }, id: number, how: unknown) {
665 return this.project.closeNotePerson(person, id, how, Date.now());
666 }
668 closeNote(agent: string, id: number, how: unknown) {
669 return this.project.closeNote(agent, id, how, Date.now());
670 }
672 notes(options: { file?: string; change?: number; open?: boolean }) {
673 return this.project.notes(options);
674 }
676 ribbon() {
677 return this.project.ribbon();
678 }
680 drafts() {
681 const s = this.project.status();
682 return {
683 version: s.version,
684 drafts: s.agents
685 .filter((a) => a.draftChanges > 0)
686 .map((a) => ({ agent: a.agent, draft: a.draft, base: a.base, draftChanges: a.draftChanges, files: a.files })),
687 };
688 }
689 /** The last copy replay loaded: scrubbing forward from it applies only the entries after it. */
690 private replica: Project | undefined;
692 /** The project as it stood with the first `at` log entries (#41, replay). */
693 private at(at: number): Project {
694 if (!this.read) throw Object.assign(new Error("replay needs the log"), { code: "not-implemented" });
695 const n = Math.max(0, Math.min(at, this.project.logLength));
696 const r = this.replica;
697 if (r && r.logLength === n) return r;
698 if (r && r.logLength < n) {
699 r.catchUp(this.read(r.logLength, n - r.logLength));
700 return r;
701 }
702 this.replica = Project.load(this.read(0, n), new MemoryStore());
703 return this.replica;
704 }
705 statusAt(at: number) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare706 if (this.historical)
707 return this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({
708 at: Math.min(at, this.project.logLength),
709 ...(p.initialized ? p.status() : { version: -1, agents: [] }),
710 }));
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare711 const p = this.at(at);
712 const answer = {
713 at: Math.min(at, this.project.logLength),
714 ...(p.initialized ? p.status() : { version: -1, agents: [] }),
715 };
716 this.release();
717 return answer;
718 }
719 whereAt(at: number) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare720 if (this.historical)
721 return this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({
722 at: Math.min(at, this.project.logLength),
723 ...(p.initialized ? where(p) : { version: -1, files: {} }),
724 }));
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare725 const p = this.at(at);
726 const answer = {
727 at: Math.min(at, this.project.logLength),
728 ...(p.initialized ? where(p) : { version: -1, files: {} }),
729 };
730 this.release();
731 return answer;
732 }
734 /**
735 * Drop the replay copy after each read (#46): a second copy of a large
736 * project's history doubles its memory, past a Durable Object's 128 MB.
737 * Each scrub replays from the start instead (about 0.2 s on game).
738 */
739 private release(): void {
740 this.replica = undefined;
741 }
743 /** hasBlob says whether the project holds a blob's bytes (#27); without it, every blob is refused. */
744 /** whole stores and reads files kept whole (#46); without it every text file is tracked by line. */
745 static open(
746 storage: SqliteStorage,
747 hasBlob?: (sha256: string) => boolean,
748 whole?: { keep(text: string): string; read(sha: string): string | null },
749 ): EngineProject {
750 const log = new SqliteLog(storage);
751 return new EngineProject(
752 Project.load(log.entries(), log, {
753 ...(hasBlob ? { hasBlob } : {}),
754 ...(whole ? { whole } : {}),
755 now: () => Date.now(),
756 shapes: log.shapes(),
757 entryAt: (at) => log.since(at, 1)[0]!,
758 }),
759 (from, limit) => log.since(from, limit),
760 log,
761 );
762 }
764 exists() {
765 return this.project.initialized;
766 }
767 /** Committed log epoch for host-side cache invalidation; it does not dispatch work. */
768 committedGeneration(): number {
769 return this.store?.generation() ?? 0;
770 }
771 init(
772 files: Record<string, string>,
773 modes?: Record<string, { exec?: boolean; link?: string | null }>,
774 blobs?: Record<string, string>,
775 ) {
776 return this.project.init(files, Date.now(), modes ?? {}, blobs ?? {});
777 }
778 edit(agent: string, body: EditBody) {
779 return this.project.edit(agent, body as Parameters<Project["edit"]>[1], Date.now());
780 }
781 record(
782 agent: string,
783 files: Record<string, string | null>,
784 modes?: Record<string, { exec?: boolean; link?: string | null }>,
785 blobs?: Record<string, string>,
786 meta?: { session?: string; subagent?: string; client?: string },
787 ) {
788 return this.project.record(agent, files, Date.now(), modes ?? {}, blobs ?? {}, meta ?? {});
789 }
790 publish(agent: string, message: string, asIs?: boolean) {
791 return this.project.publish(agent, message, Date.now(), { asIs: asIs === true });
792 }
793 sync(agent: string) {
794 return this.project.sync(agent);
795 }
796 status() {
797 return this.project.status();
798 }
799 switchTo(agent: string, name: string | null, carry = false) {
800 return this.project.switchTo(agent, name, Date.now(), { carry });
801 }
802 land(agent: string, message: string) {
803 return this.project.land(agent, message, Date.now());
804 }
805 ingest(input: Parameters<Project["ingest"]>[0], time: number) {
806 return this.project.ingest(input, time);
807 }
808 syncDraft(agent: string) {
809 return this.project.syncDraft(agent, Date.now());
810 }
811 filesAt(version: number) {
812 return this.project.viewAt(version).files();
codex-capacity-chair177Read Artifacts snapshots in version-pinned batches; cleared in review ask 45Compare813 }
814 fileTextAt(version: number, path: string): string {
815 return this.project.viewAt(version).text(path);
816 }
817 /** One scoped batch: at most 64 files and 64 Ki characters plus one whole file. */
818 fileTextsAt(version: number, paths: readonly string[]): Record<string, string> {
819 const view = this.project.viewAt(version);
820 const files: Record<string, string> = Object.create(null);
821 let characters = 0;
822 for (const path of paths.slice(0, 64)) {
823 const text = view.attrs(path).link !== null ? "" : view.text(path);
824 files[path] = text;
825 characters += text.length;
826 if (characters >= 65536) break;
827 }
828 return files;
829 }
830 /** Capture metadata now; each text read reopens the captured version in a fresh host scope. */
831 sharedPushMetadata(): PushSnapshotMetadata {
832 const version = this.project.version;
833 const view = this.project.viewAt(version);
834 const paths: string[] = [];
835 const modes: PushSnapshotMetadata["modes"] = Object.create(null);
836 const blobs: Record<string, string> = Object.create(null);
837 for (const path of view.paths()) {
838 const attrs = view.attrs(path);
839 modes[path] = { exec: attrs.exec, link: attrs.link };
840 if (attrs.blob !== null) blobs[path] = attrs.blob;
841 else paths.push(path);
842 }
843 const by = version > 0 ? this.project.published(version) : undefined;
844 return { version, paths, modes, blobs, ...(by ? { last: { agent: by.agent, message: by.message } } : {}) };
846 blobsAt(version: number) {
847 return this.project.viewAt(version).blobs();
848 }
849 /**
850 * Shared's newest version. Its files and modes are laid out on first read: every call reads shared().version
851 * before and after its op, and laying out the files reads each file's text from the log, about 0.5 s on abso
852 * (abso 299).
853 */
854 shared() {
855 const version = this.project.version;
856 const by = version > 0 ? this.project.published(version) : undefined;
857 const blobs = this.project.blobs();
858 const project = this.project;
859 let files: Record<string, string> | undefined;
860 let modes: ReturnType<Project["modes"]> | undefined;
861 return {
862 version,
863 get files() {
864 files ??= project.files();
865 return files;
866 },
867 get modes() {
868 modes ??= project.modes();
869 return modes;
870 },
871 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
872 ...(by ? { last: { agent: by.agent, message: by.message } } : {}),
873 };
874 }
875}