Lines 4–21 at 318 (were 4–14 at 151)
44// R2 copies, edge cache, probes or disk-first writer. 66import { DurableObject } from "cloudflare:workers"; 7−import { type Answer, answer, type Readers } from "../../worker/project/http.ts";
7+import { createHash } from "node:crypto"; 8+import { type Answer, answer, type Readers, readerAnswer } from "../../worker/project/http.ts"; 89import type { ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts"; 10+import { ProjectError } from "../../worker/project/project-error.ts"; 911import { BLOB_MAX, BlobStore } from "./blobs.ts"; 12+import { DiskFirstRuntime } from "./disk-first-runtime.ts"; 1013import { EngineProject, SqliteLog } from "./engine-project.ts"; 1114import { artifactsOf, type Env } from "./env.ts"; 15+import { GitDiskIntake } from "./git-disk-intake.ts"; 16+import { GitFileContents } from "./git-file-contents.ts"; 17+import { GitIntakeLimitError } from "./git-intake-limit.ts"; 18+import { GitIntakeTrees } from "./git-intake-trees.ts"; 1219import { pushedSince, remoteHead } from "./ingest.ts"; Lines 30–74 at 318 (were 23–33 at 151)
2532import { type PushResult, pushShared, repoName } from "./push.ts"; 33+import { pushSnapshot } from "./push-snapshot.ts"; 34+import { SqliteWriterState } from "./writer-host.ts"; 36+const READ_OPS = new Set([ 2763/** At most one push out a minute: each one clones the repo, so publishes in a burst share one. */ 2864export const PUSH_EVERY_MS = 60_000; 2965/** While agents are working, how often a call looks for plain-git pushes to the repo. */ 3066const GIT_CHECK_MS = 15_000; 67+// Disk scratch admission limits, independent of the Worker's resident memory. 68+const GIT_PACK_MAX_BYTES = 128 * 1024 * 1024; 69+const GIT_OBJECT_MAX_BYTES = 64 * 1024 * 1024; 70+const GIT_DECODED_MAX_BYTES = 256 * 1024 * 1024; 71+const GIT_LIMIT_POLICY = `expanded-v2:${GIT_PACK_MAX_BYTES}:${GIT_OBJECT_MAX_BYTES}:${GIT_DECODED_MAX_BYTES}`; 3374 * The load guard (platform issue 46): an estimate of a loaded project's memory from its log entries, lines and claim Lines 119–125 at 318 (were 78–83 at 151)
78119 /** Why the log didn't load, if it didn't. */ 79120 private loadError: unknown; 80121 private tried = false; 122+ private authorityRevision = 0; 81123 /** Feed long-polls waiting for the log to grow; woken after every call that wrote. */ 82124 private waiting: (() => void)[] = []; 83125 /** When this object last asked the repo for pushes made with plain git. */ Lines 129–139 at 318 (were 87–92 at 151)
87129 constructor(ctx: DurableObjectState, env: Env) { 89131 this.blobs = new BlobStore(ctx.storage); 132+ if (env.ABSO_DISK_FIRST === "on") { 133+ GitDiskIntake.recover(ctx.storage); 134+ GitFileContents.recover(ctx.storage); 135+ GitIntakeTrees.recover(ctx.storage); 92139 /** Where files kept whole go: the project's blob store. */ Lines 141–273 at 318 (were 94–101 at 151)
94141 return { keep: (text: string) => this.blobs.putText(text), read: (sha: string) => this.blobs.textOf(sha) }; 144+ private diskRuntime(): DiskFirstRuntime | undefined { 145+ return this.env.ABSO_DISK_FIRST === "on" 146+ ? new DiskFirstRuntime(this.ctx.storage, this.ctx.id.toString(), "server-disk-v1", { 147+ hasBlob: (sha) => this.blobs.has(sha), 148+ whole: this.wholeFiles(), 152+ private async prepareDisk(validate: () => void = () => {}) { 153+ const runtime = this.diskRuntime(); 154+ if (!runtime) return undefined; 155+ const progress = runtime.preparePage(validate); 156+ if (!progress.ready && progress.phase !== "empty") await this.soon(Date.now() + 100); 159+ /** Once indexing starts, legacy writes would invalidate the persistent root. */ 160+ private legacyWritesHeld(): boolean { 161+ if (this.env.ABSO_DISK_FIRST === "on") return false; 162+ const tables = this.ctx.storage.sql 163+ .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'writer_state'") 166+ tables.length > 0 && 167+ new SqliteWriterState(this.ctx.storage, "server-disk-v1").read("runtime", "format") !== undefined 170+ private useProject<T>(operation: (calls: EngineProject) => T, write = false): T { 171+ const runtime = this.diskRuntime(); 172+ if (runtime) return write ? runtime.write(operation, () => {}) : runtime.read(operation, () => {}); 173+ if (write && this.legacyWritesHeld()) 174+ throw Error("disk-first indexes exist; enable ABSO_DISK_FIRST before writing"); 175+ return operation(this.project as EngineProject); 177+ private async diskCall( 180+ agent: string | undefined, 182+ how: string | undefined, 184+ request?: { id: string; principal: string }, 185+ ): Promise<Answer> { 186+ const runtime = this.diskRuntime()!; 187+ const validate = () => { 188+ if (revision !== this.authorityRevision) 189+ throw Object.assign(Error("project authorization changed during call setup"), { code: "authority-changed" }); 191+ const progress = await this.prepareDisk(validate); 192+ const legacyReaders = (await this.ctx.storage.get<string[]>("readers")) ?? []; 193+ const storedReaders = progress?.ready 194+ ? (new SqliteWriterState(this.ctx.storage, "server-disk-v1").read("runtime", "readers") as string[] | undefined) 196+ const known = new Set(storedReaders ?? legacyReaders); 198+ let readersChanged = false; 199+ const readers: Readers = { 200+ has: (a) => known.has(a), 201+ list: () => [...known].sort(), 203+ if (on === known.has(a)) return; 204+ if (on) known.add(a); 205+ else known.delete(a); 206+ readersChanged = true; 209+ if (progress?.phase === "empty" && op !== "init") 210+ return { status: 404, body: { error: "no such project; run init first" } }; 211+ if (!progress?.ready && !(progress?.phase === "empty" && op === "init")) 212+ return { status: 503, body: { error: "project indexes are being prepared", retryAfter: 1, progress } }; 213+ if (agent && op !== "reader") { 214+ const refused = readerAnswer({ status: () => undefined }, op, agent, body, readers); 215+ if (refused) return refused; 217+ const before = new SqliteLog(this.ctx.storage).seq(); 218+ const action = (calls: EngineProject) => { 219+ const result = answer(calls, op, agent, body, readers, how); 220+ if (result.status >= 500) throw Error(`project operation failed: ${JSON.stringify(result.body)}`); 222+ new SqliteWriterState(this.ctx.storage, "server-disk-v1").write("runtime", "readers", readers.list()); 226+ const receipt = request 228+ id: `http:${createHash("sha256").update(request.principal).digest("hex")}:${request.id}`, 231+ principal: request.principal, 232+ agent: agent ?? null, 240+ progress.phase === "empty" 241+ ? runtime.initialize(action, validate, receipt) 242+ : READ_OPS.has(op) || op.startsWith("change/") 243+ ? runtime.read(action, validate) 244+ : runtime.write(action, validate, receipt); 246+ if (readersChanged) { 247+ this.authorityRevision++; 249+ const log = new SqliteLog(this.ctx.storage); 250+ if (log.seq() !== before || (request && !READ_OPS.has(op))) { 252+ await this.ctx.storage.put("name", name); 253+ await this.soon(Date.now() + 100); 256+ result.status === 200 && 257+ artifactsOf(this.env) && 258+ Date.now() - this.gitCheckedAt > GIT_CHECK_MS && 259+ (await this.ctx.storage.get("name")) !== undefined && 260+ (await this.ctx.storage.getAlarm()) === null 262+ await this.ctx.storage.setAlarm(Date.now()); 263+ if (result.status === 200 && op === "starting") result.body = await this.startingHooks(name, result.body); 264+ if (result.status === 200) result.body = this.withBlobSizes(op, result.body); 97268 /** The project, loaded from its log on first use. A log too big for memory is refused, not loaded. */ 98269 private ensure(): ProjectCalls | undefined { 270+ if (this.diskRuntime()) throw Error("legacy project load forbidden in disk-first mode"); 99271 if (this.loaded || this.tried) return this.loaded; 100272 this.tried = true; Lines 387–431 at 318 (were 215–229 at 151)
218391 ): Promise<Answer> { 392+ const revision = this.authorityRevision; 393+ let principal = "shared-token"; 395+ requestId !== undefined && 396+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(requestId) 398+ return { status: 400, body: { error: "Idempotency-Key must be a UUID" } }; 220400 const decided = await this.checkAgentKey(key.presented, agent, key.address); 221401 if (!decided.ok) return { status: decided.status, body: { error: decided.error } }; 222402 const allowed = keyAllows(decided.role, { write: key.write, agent, route: key.route }); 223403 if (!allowed.ok) return { status: allowed.status, body: { error: allowed.error } }; 405+ principal = `key:${decided.id}`; 226407 if (op === "feed" && !inFeed) return this.feed(name, body); 408+ if (this.diskRuntime()) { 410+ return await this.diskCall( 417+ requestId ? { id: requestId, principal } : undefined, 420+ if ((error as { code?: string })?.code === "request-reused") 421+ return { status: 409, body: { error: "Idempotency-Key was reused for a different request" } }; 422+ if ((error as { code?: string })?.code === "authority-changed") 423+ return { status: 409, body: { error: "project authorization changed; retry the request", retryable: true } }; 427+ if (this.legacyWritesHeld() && !READ_OPS.has(op) && !op.startsWith("change/")) 428+ return { status: 409, body: { error: "disk-first indexes exist; enable ABSO_DISK_FIRST before writing" } }; 227429 if (SOFT_HELD_OPS.has(op)) { 228430 const held = this.softHeld(); 229431 if (held) return { status: 507, body: { error: held } }; Lines 534–625 at 318 (were 332–363 at 151)
334536 private async gitSyncOnce(): Promise<{ head: string; commits: number; answer: unknown } | null> { 537+ if (this.legacyWritesHeld()) return null; 335538 const artifacts = artifactsOf(this.env); 336539 if (!artifacts) return null; 337540 this.gitCheckedAt = Date.now(); 338541 const name = await this.ctx.storage.get<string>("name"); 339− if (!name || !this.project.exists()) return null;
542+ if (!name) return null; 543+ const progress = await this.prepareDisk(); 544+ if (progress && !progress.ready) return null; 545+ if (!this.useProject((p) => p.exists())) return null; 340546 const seen = await this.ctx.storage.get<string>("git:head"); 341547 const pushed = await this.ctx.storage.get<PushResult>("pushed"); 342548 const head = await remoteHead(artifacts, name); 549+ const refusal = this.diskRuntime() 550+ ? await this.ctx.storage.get<{ head: string; policy: string; kind: GitIntakeLimitError["kind"]; error: string }>( 558+ head !== pushed?.commit && 559+ refusal.head === head && 560+ refusal.policy === GIT_LIMIT_POLICY 562+ throw new GitIntakeLimitError(refusal.kind, refusal.error); 563+ await this.ctx.storage.delete("git:size-refusal"); 343565 if (!head || head === seen || head === pushed?.commit) return null; 344− const sharedBlobs = this.project.shared().blobs ?? {};
566+ const sharedBlobs = this.useProject((p) => p.shared().blobs ?? {}); 567+ using trees = this.diskRuntime() ? new GitIntakeTrees(this.ctx.storage) : undefined; 345568 const found = await pushedSince( 349572 async (bytes) => (bytes.byteLength > BLOB_MAX ? null : this.blobs.putBytes(bytes)), 350573 (path) => sharedBlobs[path], 351− );
574+ trees ? (files, path, body, oid) => trees.retainFile(files, path, body, oid) : undefined, 577+ storage: this.ctx.storage, 578+ maxPackBytes: GIT_PACK_MAX_BYTES, 579+ maxObjectBytes: GIT_OBJECT_MAX_BYTES, 580+ maxDecodedBytes: GIT_DECODED_MAX_BYTES, 581+ maxBinaryBytes: BLOB_MAX, 582+ retainFileChunks: (files, path, chunks, oid) => trees.retainChunks(files, path, chunks, oid), 585+ ).catch(async (error: unknown) => { 586+ if (trees && error instanceof GitIntakeLimitError) { 589+ policy: GIT_LIMIT_POLICY, 591+ error: error.message, 592+ at: new Date().toISOString(), 594+ await this.ctx.storage.put({ "git:size-refusal": refusal, "git:error": refusal }); 352598 if (!found || found.commits.length === 0) { 353599 if (found) await this.ctx.storage.put("git:head", found.head); 602+ // Unexpected failures leave the cursor unacknowledged for retry. Engine 603+ // refusals are recorded and acknowledged so a later fixing commit can advance. 604+ const ingest = (p: EngineProject) => 605+ p.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now()); 606+ const runtime = this.diskRuntime(); 356607 let result: unknown; 358− result = this.project.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now());
359− } catch (e) {
360− result = { error: e instanceof Error ? e.message : String(e) };
610+ ? runtime.write(ingest, () => {}, { 611+ id: `git:${found.head}`, 616+ commits: found.commits.map((commit) => commit.sha), 619+ : this.useProject(ingest, true); 621+ if (!(error instanceof ProjectError)) throw error; 622+ result = { error: error.message }; 363625 at: new Date().toISOString(), Lines 645–682 at 318 (were 383–401 at 151)
383645 * most once a minute, backing off on failure. Without an ARTIFACTS binding (local dev) it does nothing. 385647 async alarm(): Promise<void> { 648+ if (!this.diskRuntime() && !artifactsOf(this.env)) return; 649+ if (!this.diskRuntime() && !this.ensure()) return; 650+ const progress = await this.prepareDisk(); 651+ if (progress && !progress.ready) return; 386652 const artifacts = artifactsOf(this.env); 387653 if (!artifacts) return; 388654 const name = await this.ctx.storage.get<string>("name"); 389− if (!name || !this.ensure()?.exists()) return;
655+ if (!name || !this.useProject((p) => p.exists())) return; 656+ let intakeFailed = false; 390657 await this.gitSync().then( 391− () => this.ctx.storage.delete("git:error"),
392− (e) =>
393− this.ctx.storage.put("git:error", {
659+ await this.ctx.storage.delete("git:error"); 660+ await this.ctx.storage.delete("git:retry-attempts"); 663+ intakeFailed = true; 664+ const attempts = ((await this.ctx.storage.get<number>("git:retry-attempts")) ?? 0) + 1; 665+ await this.ctx.storage.put("git:retry-attempts", attempts); 666+ await this.ctx.storage.put("git:error", { 394667 at: new Date().toISOString(), 395668 error: e instanceof Error ? e.message : String(e), 396− }),
670+ await this.soon(Date.now() + (attempts === 1 ? 1 : attempts === 2 ? 5 : 15) * 60_000); 398− const shared = this.project.shared();
673+ // Never export over a remote head whose changes could not be taken in. 674+ if (intakeFailed) return; 675+ const shared = pushSnapshot( 676+ this.useProject((p) => p.sharedPushMetadata()), 677+ (version, path) => this.useProject((current) => current.fileTextAt(version, path)), 678+ (version, paths) => this.useProject((current) => current.fileTextsAt(version, paths)), 399680 const done = await this.ctx.storage.get<PushResult>("pushed"); 400681 if (done && done.version >= shared.version) return; 401682 const pushedAt = (await this.ctx.storage.get<number>("pushedAt")) ?? 0; Lines 686–705 at 318 (were 405–411 at 151)
406687 let result: PushResult; 408− result = await pushShared(artifacts, name, shared, (sha) => this.blobs.read(sha));
689+ result = await pushShared( 693+ (sha) => this.blobs.read(sha), 694+ this.env.ABSO_DISK_FIRST === "on" 696+ storage: this.ctx.storage, 697+ maxPackBytes: GIT_PACK_MAX_BYTES, 698+ maxObjectBytes: GIT_OBJECT_MAX_BYTES, 699+ maxDecodedBytes: GIT_DECODED_MAX_BYTES, 410704 // Kept for /out, and tried again with a backoff of our own (a thrown alarm is retried only six times). 411705 const was = await this.ctx.storage.get<{ attempts?: number }>("pushError"); Lines 716–731 at 318 (were 422–438 at 151)
422716 await this.ctx.storage.put({ pushed: result, "git:head": result.commit, pushedAt: Date.now() }); 423717 await this.ctx.storage.delete("pushError"); 424718 // Another publish may have landed while this push ran. 425− if (this.project.shared().version > result.version) await this.soon(Date.now() + PUSH_EVERY_MS);
719+ if (this.useProject((p) => p.shared().version) > result.version) await this.soon(Date.now() + PUSH_EVERY_MS); 428722 /** The push out: the repo, the last version pushed, and plain-git intake. */ 430724 const name = await this.ctx.storage.get<string>("name"); 431− const p = this.ensure();
433726 repo: name ? repoName(name) : null, 434727 artifacts: artifactsOf(this.env) ? "bound" : "unbound", 435− version: p?.exists() ? p.shared().version : null,
728+ version: this.logChars().entries ? new SqliteLog(this.ctx.storage).sharedVersion() : null, 436729 pushed: (await this.ctx.storage.get<PushResult>("pushed")) ?? null, 437730 error: (await this.ctx.storage.get("pushError")) ?? null, Lines 764–770 at 318 (were 471–476 at 151)
471764 if (typeof when !== "number") return { error: when.error }; 472765 const state = await this.keyState(); 473766 const issued = await issueKey(state, secret, agent, "admin", Date.now(), address, when, role); 767+ this.authorityRevision++; 474768 await this.ctx.storage.put("agent-keys", state); Lines 774–780 at 318 (were 480–485 at 151)
480774 if (!secret) return { revoked: false }; 481775 const state = await this.keyState(); 482776 const revoked = revokeKey(state, id, Date.now(), await hmac(secret, address)); 777+ this.authorityRevision++; 483778 await this.ctx.storage.put("agent-keys", state); 484779 return { revoked }; Lines 787–797 at 318 (were 492–500 at 151)
493788 /** The project's agent names, for the ask seat check. None when there's no project. */ 494789 async agents(_project: string): Promise<string[]> { 495− const p = this.ensure();
496− if (!p?.exists()) return [];
497− return p.status().agents.map((a) => a.agent);
790+ if (!this.diskRuntime() && !this.ensure()) return []; 791+ const progress = await this.prepareDisk(); 792+ if (progress?.phase === "empty") return []; 793+ if (progress && !progress.ready) throw Error("project indexes are being prepared"); 794+ return this.useProject((p) => (p.exists() ? p.status().agents.map((a) => a.agent) : [])); Lines 799–839 at 318 (were 502–534 at 151)
502799 * its issue and to the known agents in `to`, never back to its writer. 504801 async news(_project: string, items: IssueNews[]): Promise<{ to: string[] }[]> { 505− const p = this.ensure();
506− if (!p?.exists()) return items.map(() => ({ to: [] }));
507− const engine = p as ProjectCalls & ProjectHistory;
508− const out: { to: string[] }[] = [];
509− for (const item of items) {
510− const status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] };
511− const known = new Set(status.agents.map((a) => a.agent));
512− const to = new Set([
513− ...(item.issue !== null
514− ? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent)
515− : []),
516− ...(item.to ?? []).filter((t) => known.has(t)),
517− ]);
518− to.delete(item.from);
519− if (to.size === 0) {
520− out.push({ to: [] });
521− continue;
802+ if (!this.diskRuntime() && !this.ensure()) return items.map(() => ({ to: [] })); 803+ const progress = await this.prepareDisk(); 804+ if (progress?.phase === "empty") return items.map(() => ({ to: [] })); 805+ if (progress && !progress.ready) throw Error("project indexes are being prepared"); 806+ return this.useProject((p) => { 807+ if (!p.exists()) return items.map(() => ({ to: [] })); 808+ const engine = p as ProjectCalls & ProjectHistory; 809+ const out: { to: string[] }[] = []; 810+ for (const item of items) { 811+ const status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] }; 812+ const known = new Set(status.agents.map((a) => a.agent)); 813+ const to = new Set([ 814+ ...(item.issue !== null 815+ ? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent) 817+ ...(item.to ?? []).filter((t) => known.has(t)), 819+ to.delete(item.from); 820+ if (to.size === 0) { 821+ out.push({ to: [] }); 825+ engine.announce(item.from, item.text, [...to]); 826+ out.push({ to: [...to] }); 828+ // Persistent writer state may already have changed. Let the outer 829+ // transaction undo the whole batch before reporting a failure. 830+ if (this.env.ABSO_DISK_FIRST === "on") throw e; 831+ console.log(JSON.stringify({ event: "issues-news", error: String(e).slice(0, 200) })); 832+ out.push({ to: [] }); 523− try {
524− engine.announce(item.from, item.text, [...to]);
525− out.push({ to: [...to] });
526− } catch (e) {
527− console.log(JSON.stringify({ event: "issues-news", error: String(e).slice(0, 200) }));
528− out.push({ to: [] });
529− }
530− }
531− this.wake();
532− return out;