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=157&format=json
759 linesspeed 95% · codex-capacity-chair 5%Last change codex-capacity-chair in version 157, 2 versions changed it

You're reading version 157. The newest is 318, and 9 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 boundedFrame(seq: number, maxBytes: number): string {
100 if (
101 !Number.isSafeInteger(seq) ||
102 seq < 0 ||
103 !Number.isSafeInteger(maxBytes) ||
104 maxBytes < 1 ||
105 maxBytes > 8_000_000
106 )
107 throw new Error("invalid canonical frame bound");
108 const size = this.storage.sql
109 .exec(
110 "SELECT COUNT(*) AS parts, COALESCE(SUM(LENGTH(CAST(text AS BLOB))), 0) AS bytes FROM log WHERE seq = ?",
111 seq,
112 )
113 .toArray()[0] as { parts: number; bytes: number };
114 if (!size || size.parts < 1 || size.parts > 256 || size.bytes > maxBytes)
115 throw new Error("canonical frame exceeds adoption bound or is missing");
116 const rows = this.storage.sql.exec("SELECT part, text FROM log WHERE seq = ? ORDER BY part", seq).toArray() as {
117 part: number;
118 text: string;
119 }[];
120 if (rows.length !== size.parts || rows.some((row, part) => row.part !== part))
121 throw new Error("canonical frame parts are incomplete");
122 return rows.map((row) => row.text).join("");
123 }
125 /** Refreshes the in-memory cursor after an enclosing transaction rolls back. */
126 refreshSequence(): void {
127 const rows = this.storage.sql.exec("SELECT COALESCE(MAX(seq), -1) AS last FROM log").toArray() as {
128 last: number;
129 }[];
130 this.next = (rows[0]?.last ?? -1) + 1;
131 }
133 /** Monotonic cache invalidation epoch for every canonical log mutation. */
134 generation(): number {
135 const rows = this.storage.sql.exec("SELECT value FROM marks WHERE name = ?", "generation").toArray() as {
136 value: string;
137 }[];
138 const generation = Number(rows[0]?.value ?? 0);
139 if (!Number.isSafeInteger(generation) || generation < 0) throw new Error("canonical log generation is invalid");
140 return generation;
141 }
143 /**
144 * Lines ever recorded (#46, #56): what loading the project costs grows with
145 * this, not with the log's size, so a guard can read it without loading.
146 * Kept with each append; undefined for a log written before the count,
147 * until it next loads.
148 */
149 lineCount(): number | undefined {
150 const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'lines'").toArray() as {
151 value: number;
152 }[];
153 return rows[0]?.value;
154 }
156 /**
157 * The newest version of shared, without loading the project (abso issue 78: the website's access check asked
158 * every project's engine for it). Kept with each append; a log from before the count is read once by streaming.
159 */
160 sharedVersion(): number {
161 const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'shared'").toArray() as {
162 value: number;
163 }[];
164 if (rows[0] !== undefined) return rows[0].value;
165 let version = -1;
166 for (const e of this.#entries()) version = sharedVersionOf(e) ?? version;
167 if (version >= 0)
168 this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('shared', ?)", version);
169 return version;
170 }
172 /**
173 * Who published shared's newest version, and when, without loading the project (abso issue 86).
174 * Null when shared has no publish yet. A log from before the mark is read once by streaming.
175 */
176 lastPublish(): { agent: string; time: number } | null {
177 const rows = this.storage.sql.exec("SELECT value FROM marks WHERE name = ?", "last").toArray() as {
178 value: string;
179 }[];
180 if (rows[0] !== undefined) return JSON.parse(rows[0].value) as { agent: string; time: number };
181 let last: { agent: string; time: number } | null = null;
182 for (const e of this.#entries()) {
183 const found = lastPublishOf(e);
184 if (found) last = found;
185 }
186 if (last)
187 this.storage.sql.exec("INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)", "last", JSON.stringify(last));
188 return last;
189 }
191 /**
192 * How big the log is, without loading the project or scanning it twice (ask 160).
193 * Entries are the next seq. Chars are kept like lines; a log from before the
194 * count is summed once, then kept. GET /projects' 2-second wait needs this
195 * to stay a storage read: SUM(LENGTH(text)) over abso's log misses it.
196 */
197 logSize(): { chars: number; entries: number } {
198 const entries = this.next;
199 const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'chars'").toArray() as {
200 value: number;
201 }[];
202 if (rows[0] !== undefined) return { chars: rows[0].value, entries };
203 if (entries === 0) return { chars: 0, entries: 0 };
204 const summed = this.storage.sql.exec("SELECT COALESCE(SUM(LENGTH(text)), 0) AS chars FROM log").toArray()[0] as
205 | { chars: number }
206 | undefined;
207 const chars = summed?.chars ?? 0;
208 this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('chars', ?)", chars);
209 return { chars, entries };
210 }
212 /** Claim keys and deletes ever recorded (#46), kept like the line count; undefined before they were counted. */
213 keyCount(): number | undefined {
214 const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'keys'").toArray() as { value: number }[];
215 return rows[0]?.value;
216 }
218 /**
219 * The lines and keys ever recorded, counting a log from before either count without loading the project
220 * (#46): one entry parsed at a time, so a log the load guard would refuse can still be measured. Kept once counted.
221 */
222 countSizes(): { lines: number; keys: number } {
223 const lines = this.lineCount();
224 const keys = this.keyCount();
225 if (lines !== undefined && keys !== undefined) return { lines, keys };
226 let l = 0;
227 let k = 0;
228 for (const e of this.#entries()) {
229 l += linesIn(e);
230 k += keysIn(e);
231 }
232 this.#keep(lines === undefined ? l : undefined, keys === undefined ? k : undefined);
233 return { lines: lines ?? l, keys: keys ?? k };
234 }
236 /** Stores the counts given. */
237 #keep(lines: number | undefined, keys: number | undefined): void {
238 if (lines !== undefined)
239 this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('lines', ?)", lines);
240 if (keys !== undefined)
241 this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('keys', ?)", keys);
242 }
244 /** Every stored entry, in order. Rows are read one at a time, so loading never holds the whole log's text at once (#43). */
245 *entries(): Iterable<Entry> {
246 // A log from before the counts: counted as it loads, and kept.
247 const countLines = this.lineCount() === undefined;
248 const countKeys = this.keyCount() === undefined;
249 let lines = 0;
250 let keys = 0;
251 for (const e of this.#entries()) {
252 if (countLines) lines += linesIn(e);
253 if (countKeys) keys += keysIn(e);
254 yield e;
255 }
256 this.#keep(countLines ? lines : undefined, countKeys ? keys : undefined);
257 }
259 *#entries(from = 0): Iterable<Entry> {
260 // A Workers cursor is iterable; a test's stand-in may only have toArray.
261 const cursor = this.storage.sql.exec("SELECT seq, text FROM log WHERE seq >= ? ORDER BY seq, part", from) as {
262 toArray(): unknown[];
263 } & Partial<Iterable<unknown>>;
264 const rows = (cursor[Symbol.iterator] ? cursor : cursor.toArray()) as Iterable<{ seq: number; text: string }>;
265 let seq = -1;
266 let text = "";
267 for (const r of rows) {
268 if (r.seq !== seq && seq >= 0) yield JSON.parse(text) as Entry;
269 if (r.seq !== seq) text = "";
270 seq = r.seq;
271 text += r.text;
272 }
273 if (seq >= 0) yield JSON.parse(text) as Entry;
274 }
276 /**
277 * For backups (#29): the entries from seq `from` on as their stored JSON
278 * text (not parsed, so an export holds the project up as little as it
279 * can), at most `limit` of them and about 8 MB (always at least one), and
280 * the seq to ask for next, or null at the end.
281 */
282 page(from: number, limit: number): { texts: string[]; next: number | null } {
283 const rows = this.storage.sql
284 .exec("SELECT seq, text FROM log WHERE seq >= ? AND seq < ? ORDER BY seq, part", from, from + limit)
285 .toArray() as { seq: number; text: string }[];
286 const texts: string[] = [];
287 let seq = -1;
288 let text = "";
289 let size = 0;
290 let next: number | null = null;
291 for (const r of rows) {
292 if (r.seq < from || r.seq >= from + limit) continue;
293 if (r.seq !== seq && seq >= 0) {
294 texts.push(text);
295 size += text.length;
296 if (size > 8_000_000) {
297 next = r.seq;
298 break;
299 }
300 }
301 if (r.seq !== seq) text = "";
302 seq = r.seq;
303 text += r.text;
304 }
305 if (next === null && seq >= 0) texts.push(text);
306 if (next === null && from + limit < this.next) next = from + limit;
307 return { texts, next };
308 }
310 /** Up to `limit` entries from position `from`, parsed (#41: the feed and replay). */
311 since(from: number, limit: number): Entry[] {
312 const out: Entry[] = [];
313 for (let at = from; out.length < limit; ) {
314 const { texts, next } = this.page(at, limit - out.length);
315 for (const t of texts) out.push(JSON.parse(t) as Entry);
316 if (next === null || texts.length === 0) break;
317 at = next;
318 }
319 return out;
320 }
322 /** Removes every entry: only for a restore whose log didn't load (#29). */
323 clear(): void {
324 const generation = this.generation() + 1;
325 this.storage.transactionSync(() => {
326 this.storage.sql.exec("DELETE FROM log");
327 this.storage.sql.exec("DELETE FROM shapes");
328 this.storage.sql.exec("DELETE FROM counts");
329 this.storage.sql.exec("DELETE FROM marks WHERE name != ?", "generation");
330 this.storage.sql.exec(
331 "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)",
332 "generation",
333 String(generation),
334 );
335 });
336 this.next = 0;
337 }
339 /**
340 * Each version's changed files, kept between loads (#41, the Files pages):
341 * worked out from the log, never part of it, so an older Worker ignores
342 * the table and nothing about the project depends on it.
343 */
344 shapes(): {
345 get(space: string, version: number): string | undefined;
346 put(space: string, version: number, value: string): void;
347 } {
348 const sql = this.storage.sql;
349 return {
350 get: (space, version) =>
351 (
352 sql.exec("SELECT value FROM shapes WHERE space = ? AND version = ?", space, version).toArray() as {
353 value: string;
354 }[]
355 )[0]?.value,
356 put: (space, version, value) =>
357 void sql.exec("INSERT OR REPLACE INTO shapes (space, version, value) VALUES (?, ?, ?)", space, version, value),
358 };
359 }
361 append(entries: readonly Entry[]): void {
362 if (!entries.length) return;
363 let next = this.next;
364 this.storage.transactionSync(() => {
365 const lines = entries.reduce((n, e) => n + linesIn(e), 0);
366 if (lines > 0)
367 this.storage.sql.exec(
368 "INSERT INTO counts (name, value) VALUES ('lines', ?) ON CONFLICT(name) DO UPDATE SET value = value + ?",
369 lines,
370 lines,
371 );
372 // The newest version of shared: appended entries are the newest, so the last one that makes a version wins.
373 for (const e of entries) {
374 const v = sharedVersionOf(e);
375 if (v !== undefined)
376 this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('shared', ?)", v);
377 const last = lastPublishOf(e);
378 if (last)
379 this.storage.sql.exec(
380 "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)",
381 "last",
382 JSON.stringify(last),
383 );
384 }
385 // Keys are only added to once counted: a log from before the key count is counted whole first (countSizes).
386 const keys = entries.reduce((n, e) => n + keysIn(e), 0);
387 if (keys > 0) this.storage.sql.exec("UPDATE counts SET value = value + ? WHERE name = 'keys'", keys);
388 let chars = 0;
389 for (const entry of entries) {
390 const json = JSON.stringify(entry);
391 logParts(json).forEach((text, part) => {
392 chars += text.length;
393 this.storage.sql.exec("INSERT INTO log (seq, part, text) VALUES (?, ?, ?)", next, part, text);
394 });
395 next++;
396 }
397 // Chars are only added to once counted: a log from before the count is summed whole first (logSize).
398 if (chars > 0) this.storage.sql.exec("UPDATE counts SET value = value + ? WHERE name = 'chars'", chars);
399 const generation = this.generation() + 1;
400 this.storage.sql.exec(
401 "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)",
402 "generation",
403 String(generation),
404 );
405 });
406 this.next = next;
407 }
410/** The engine's Project as the Worker's ProjectCalls; the clock comes from here. */
411export class EngineProject implements ProjectCalls, ProjectHistory {
412 blame(file: string, from?: number, to?: number, version?: number, draft?: string, agent?: string) {
413 return blame(this.project, file, from, to, version, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });
414 }
415 folderBlame(folder: string, version?: number, draft?: string, agent?: string) {
416 return folderBlame(this.project, folder, version, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });
417 }
418 tree(folder: string, version?: number, draft?: string | null, agent?: string, authors?: boolean) {
419 return this.project.tree(folder, {
420 ...(version !== undefined ? { version } : {}),
421 draft: draft ?? null,
422 ...(agent !== undefined ? { agent } : {}),
423 ...(authors ? { authors } : {}),
424 });
425 }
426 pathLife(path: string, version?: number, draft?: string | null) {
427 return this.project.pathLife(path, { ...(version !== undefined ? { version } : {}), draft: draft ?? null });
428 }
429 follow(path: string, version: number, from: number, to: number, at?: number, draft?: string | null) {
430 return this.project.follow(path, version, from, to, { ...(at !== undefined ? { at } : {}), draft: draft ?? null });
431 }
432 pathsOf(agent: string) {
433 return this.project.pathsOf(agent);
434 }
435 draftState(name: string) {
436 return this.project.draftState(name);
437 }
438 collisions(file?: string, folder?: string) {
439 return this.project.collisions({
440 ...(file !== undefined ? { file } : {}),
441 ...(folder !== undefined ? { folder } : {}),
442 });
443 }
444 why(file: string, line: number, draft?: string, agent?: string) {
445 return why(this.project, file, line, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });
446 }
447 where() {
448 return where(this.project);
449 }
450 refusals(agent?: string, limit?: number) {
451 return this.project.refusals({ ...(agent ? { agent } : {}), ...(limit !== undefined ? { limit } : {}) });
452 }
454 log(draft: string | null, limit?: number, path?: string, agent?: string, before?: number, follow?: boolean) {
455 return this.project.log({
456 draft,
457 ...(limit !== undefined ? { limit } : {}),
458 ...(path !== undefined ? { path } : {}),
459 ...(agent ? { agent } : {}),
460 ...(before !== undefined ? { before } : {}),
461 ...(follow ? { follow } : {}),
462 });
463 }
464 fileAt(path: string, version: number, draft: string | null, agent?: string) {
465 return this.project.fileAt(path, version, { draft, ...(agent ? { agent } : {}) });
466 }
467 compare(from: number, to: number, draft: string | null, agent?: string) {
468 return this.project.compare(from, to, { draft, ...(agent ? { agent } : {}) });
469 }
470 show(version: number, draft: string | null, agent?: string) {
471 return this.project.show(version, { draft, ...(agent ? { agent } : {}) });
472 }
473 diff(agent: string) {
474 return this.project.diff(agent);
475 }
476 syncFull(agent: string, label?: string) {
477 return this.project.sync(agent, { full: true, ...(label !== undefined ? { label } : {}) });
478 }
479 agentPaths(agent: string) {
480 return this.project.agentPaths(agent);
481 }
482 pathsAt(version?: number, draft?: string | null) {
483 return this.project.pathsAt(version, draft ?? null);
484 }
485 syncTo(agent: string, label: string) {
486 return this.project.sync(agent, { label });
487 }
488 label(agent: string, name: string, version?: number, remove?: boolean) {
489 return this.project.label(agent, name, version, Date.now(), { remove: remove === true });
490 }
491 labels() {
492 return this.project.labels();
493 }
494 amend(agent: string, message: string) {
495 return this.project.amend(agent, message, Date.now());
496 }
497 pluck(agent: string, draft: string, versions: number[], message: string, withDependencies?: boolean) {
498 return this.project.pluck(agent, draft, versions, message, Date.now(), {
499 withDependencies: withDependencies === true,
500 });
501 }
502 drop(agent: string, versions: number[], message: string, withDependents?: boolean) {
503 return this.project.drop(agent, versions, message, Date.now(), { withDependents: withDependents === true });
504 }
505 announce(agent: string, text: string, to?: string[], how?: string) {
506 return this.project.announce(agent, text, to, Date.now(), how);
507 }
509 announcePerson(person: { id: string; name: string }, text: string, to?: string[]) {
510 return this.project.announcePerson(person, text, to, Date.now());
511 }
512 starting(agent: string, text: string | null, files?: string[], options: { issue?: unknown; done?: unknown } = {}) {
513 return this.project.starting(agent, text, files, Date.now(), options);
514 }
515 news(agent: string) {
516 return this.project.news(agent);
517 }
518 restore(agent: string, files: string[] | null) {
519 return this.project.restore(agent, files, Date.now());
520 }
522 private project: Project;
524 /** Reads stored entries by log position, for the feed and replay (#41); absent, those answer 501. */
525 private readonly read: ((from: number, limit: number) => Entry[]) | undefined;
526 private readonly store: SqliteLog | undefined;
528 constructor(project: Project, read?: (from: number, limit: number) => Entry[], store?: SqliteLog) {
529 this.project = project;
530 this.read = read;
531 this.store = store;
532 }
534 /** The project's events from log position `from` (#41): reading consumes nothing. */
535 feed(from: number, limit = 500) {
536 if (!this.read) throw Object.assign(new Error("the feed needs the log"), { code: "not-implemented" });
537 const end = this.project.logLength;
538 const start = Math.max(0, Math.min(from, end));
539 const entries = start < end ? this.read(start, Math.min(limit, end - start)) : [];
540 // A drop event names the files it took out (#41), so a timeline needs no read per drop.
541 const events = feedEvents(entries, start).map((e) => {
542 if (e.type !== "drop" || e.version === undefined) return e;
543 const v = this.project.log({ limit: 1, before: e.version + 1 }).versions[0];
544 return v && v.version === e.version ? { ...e, dropped: v.files } : e;
545 });
546 return { next: start + entries.length, end, events };
547 }
549 /** The log position for a time (ms since 1970) or a version of shared (#41). */
550 position(q: { time?: number; version?: number }) {
551 return this.project.position(q);
552 }
553 /** Whether the Worker runs the queue's check; until it does, "queue": true does nothing. */
554 setCheckerReady(ready: boolean): void {
555 this.project.checkerReady = ready;
556 }
557 /** An agent withdraws what it has queued (#39). */
558 unqueue(agent: string) {
559 return this.project.unqueue(agent, Date.now());
560 }
561 /** The log length now: what a long-poll waits to see grow. */
562 logLength() {
563 return this.project.logLength;
564 }
565 /** An agent's draft diff for a reader: never creates the agent (#41). */
566 diffOf(agent: string) {
567 return this.project.diffOf(agent);
568 }
569 /** Every agent with unpublished changes: its files and how many changes (#41). */
570 change(id: number) {
571 return this.project.change(id);
572 }
574 changes(since: number, limit: number, before?: number, issue?: number) {
575 return this.project.changes(since, limit, before, issue);
576 }
578 move(agent: string, from: string, to: string) {
579 return this.project.move(agent, from, to, Date.now());
580 }
582 note(agent: string, body: Record<string, unknown>) {
583 return this.project.note(agent, body, Date.now());
584 }
586 notePerson(person: { id: string; name: string }, body: Record<string, unknown>) {
587 return this.project.notePerson(person, body, Date.now());
588 }
590 closeNotePerson(person: { id: string; name: string }, id: number, how: unknown) {
591 return this.project.closeNotePerson(person, id, how, Date.now());
592 }
594 closeNote(agent: string, id: number, how: unknown) {
595 return this.project.closeNote(agent, id, how, Date.now());
596 }
598 notes(options: { file?: string; change?: number; open?: boolean }) {
599 return this.project.notes(options);
600 }
602 ribbon() {
603 return this.project.ribbon();
604 }
606 drafts() {
607 const s = this.project.status();
608 return {
609 version: s.version,
610 drafts: s.agents
611 .filter((a) => a.draftChanges > 0)
612 .map((a) => ({ agent: a.agent, draft: a.draft, base: a.base, draftChanges: a.draftChanges, files: a.files })),
613 };
614 }
615 /** The last copy replay loaded: scrubbing forward from it applies only the entries after it. */
616 private replica: Project | undefined;
618 /** The project as it stood with the first `at` log entries (#41, replay). */
619 private at(at: number): Project {
620 if (!this.read) throw Object.assign(new Error("replay needs the log"), { code: "not-implemented" });
621 const n = Math.max(0, Math.min(at, this.project.logLength));
622 const r = this.replica;
623 if (r && r.logLength === n) return r;
624 if (r && r.logLength < n) {
625 r.catchUp(this.read(r.logLength, n - r.logLength));
626 return r;
627 }
628 this.replica = Project.load(this.read(0, n), new MemoryStore());
629 return this.replica;
630 }
631 statusAt(at: number) {
632 const p = this.at(at);
633 const answer = {
634 at: Math.min(at, this.project.logLength),
635 ...(p.initialized ? p.status() : { version: -1, agents: [] }),
636 };
637 this.release();
638 return answer;
639 }
640 whereAt(at: number) {
641 const p = this.at(at);
642 const answer = {
643 at: Math.min(at, this.project.logLength),
644 ...(p.initialized ? where(p) : { version: -1, files: {} }),
645 };
646 this.release();
647 return answer;
648 }
650 /**
651 * Drop the replay copy after each read (#46): a second copy of a large
652 * project's history doubles its memory, past a Durable Object's 128 MB.
653 * Each scrub replays from the start instead (about 0.2 s on game).
654 */
655 private release(): void {
656 this.replica = undefined;
657 }
659 /** hasBlob says whether the project holds a blob's bytes (#27); without it, every blob is refused. */
660 /** whole stores and reads files kept whole (#46); without it every text file is tracked by line. */
661 static open(
662 storage: SqliteStorage,
663 hasBlob?: (sha256: string) => boolean,
664 whole?: { keep(text: string): string; read(sha: string): string | null },
665 ): EngineProject {
666 const log = new SqliteLog(storage);
667 return new EngineProject(
668 Project.load(log.entries(), log, {
669 ...(hasBlob ? { hasBlob } : {}),
670 ...(whole ? { whole } : {}),
671 now: () => Date.now(),
672 shapes: log.shapes(),
673 entryAt: (at) => log.since(at, 1)[0]!,
674 }),
675 (from, limit) => log.since(from, limit),
676 log,
677 );
678 }
680 exists() {
681 return this.project.initialized;
682 }
683 /** Committed log epoch for host-side cache invalidation; it does not dispatch work. */
684 committedGeneration(): number {
685 return this.store?.generation() ?? 0;
686 }
687 init(
688 files: Record<string, string>,
689 modes?: Record<string, { exec?: boolean; link?: string | null }>,
690 blobs?: Record<string, string>,
691 ) {
692 return this.project.init(files, Date.now(), modes ?? {}, blobs ?? {});
693 }
694 edit(agent: string, body: EditBody) {
695 return this.project.edit(agent, body as Parameters<Project["edit"]>[1], Date.now());
696 }
697 record(
698 agent: string,
699 files: Record<string, string | null>,
700 modes?: Record<string, { exec?: boolean; link?: string | null }>,
701 blobs?: Record<string, string>,
702 meta?: { session?: string; subagent?: string; client?: string },
703 ) {
704 return this.project.record(agent, files, Date.now(), modes ?? {}, blobs ?? {}, meta ?? {});
705 }
706 publish(agent: string, message: string, asIs?: boolean) {
707 return this.project.publish(agent, message, Date.now(), { asIs: asIs === true });
708 }
709 sync(agent: string) {
710 return this.project.sync(agent);
711 }
712 status() {
713 return this.project.status();
714 }
715 switchTo(agent: string, name: string | null, carry = false) {
716 return this.project.switchTo(agent, name, Date.now(), { carry });
717 }
718 land(agent: string, message: string) {
719 return this.project.land(agent, message, Date.now());
720 }
721 ingest(input: Parameters<Project["ingest"]>[0], time: number) {
722 return this.project.ingest(input, time);
723 }
724 syncDraft(agent: string) {
725 return this.project.syncDraft(agent, Date.now());
726 }
727 filesAt(version: number) {
728 return this.project.viewAt(version).files();
729 }
730 blobsAt(version: number) {
731 return this.project.viewAt(version).blobs();
732 }
733 /**
734 * Shared's newest version. Its files and modes are laid out on first read: every call reads shared().version
735 * before and after its op, and laying out the files reads each file's text from the log, about 0.5 s on abso
736 * (abso 299).
737 */
738 shared() {
739 const version = this.project.version;
740 const by = version > 0 ? this.project.published(version) : undefined;
741 const blobs = this.project.blobs();
742 const project = this.project;
743 let files: Record<string, string> | undefined;
744 let modes: ReturnType<Project["modes"]> | undefined;
745 return {
746 version,
747 get files() {
748 files ??= project.files();
749 return files;
750 },
751 get modes() {
752 modes ??= project.modes();
753 return modes;
754 },
755 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
756 ...(by ? { last: { agent: by.agent, message: by.message } } : {}),
757 };
758 }