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=177&format=json
872 linesspeed 82% · codex-capacity-chair 18%Last change codex-capacity-chair in version 177, 6 versions changed it

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