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=166&format=json
822 linesspeed 87% · codex-capacity-chair 13%Last change codex-capacity-chair in version 162, 4 versions changed it

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