Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/server/src/engine-project.ts?version=172&format=json
839 linesspeed 85% · codex-capacity-chair 15%Last change codex-capacity-chair in version 167, 5 versions changed it

You're reading version 172. The newest is 318, and 6 versions since then changed this file. Go to the newestCompare with 318

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