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=155&format=json
724 linesspeed 100%Last change speed in version 150, 1 version changed it

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