Lines 7–13 at 158 (were 7–12 at 157)
77import { type Answer, answer, type Readers } from "../../worker/project/http.ts"; 88import type { ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts"; 99import { BLOB_MAX, BlobStore } from "./blobs.ts"; 10+import { DiskFirstRuntime } from "./disk-first-runtime.ts"; 1011import { EngineProject, SqliteLog } from "./engine-project.ts"; 1112import { artifactsOf, type Env } from "./env.ts"; 1213import { pushedSince, remoteHead } from "./ingest.ts"; Lines 24–57 at 158 (were 23–29 at 157)
2526import { type PushResult, pushShared, repoName } from "./push.ts"; 27+import { SqliteWriterState } from "./writer-host.ts"; 29+const READ_OPS = new Set([ 2755/** At most one push out a minute: each one clones the repo, so publishes in a burst share one. */ 2856export const PUSH_EVERY_MS = 60_000; 2957/** While agents are working, how often a call looks for plain-git pushes to the repo. */ Lines 106–112 at 158 (were 78–83 at 157)
78106 /** Why the log didn't load, if it didn't. */ 79107 private loadError: unknown; 80108 private tried = false; 109+ private authorityRevision = 0; 81110 /** Feed long-polls waiting for the log to grow; woken after every call that wrote. */ 82111 private waiting: (() => void)[] = []; 83112 /** When this object last asked the repo for pushes made with plain git. */ Lines 123–231 at 158 (were 94–101 at 157)
94123 return { keep: (text: string) => this.blobs.putText(text), read: (sha: string) => this.blobs.textOf(sha) }; 126+ private diskRuntime(): DiskFirstRuntime | undefined { 127+ return this.env.ABSO_DISK_FIRST === "on" 128+ ? new DiskFirstRuntime(this.ctx.storage, this.ctx.id.toString(), "server-disk-v1", { 129+ hasBlob: (sha) => this.blobs.has(sha), 130+ whole: this.wholeFiles(), 134+ private async prepareDisk(validate: () => void = () => {}) { 135+ const runtime = this.diskRuntime(); 136+ if (!runtime) return undefined; 137+ const progress = runtime.preparePage(validate); 138+ if (!progress.ready && progress.phase !== "empty") await this.soon(Date.now() + 100); 141+ /** Once indexing starts, legacy writes would invalidate the persistent root. */ 142+ private legacyWritesHeld(): boolean { 143+ if (this.env.ABSO_DISK_FIRST === "on") return false; 144+ const tables = this.ctx.storage.sql 145+ .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'writer_state'") 148+ tables.length > 0 && 149+ new SqliteWriterState(this.ctx.storage, "server-disk-v1").read("runtime", "format") !== undefined 152+ private useProject<T>(operation: (calls: EngineProject) => T, write = false): T { 153+ const runtime = this.diskRuntime(); 154+ if (runtime) return write ? runtime.write(operation, () => {}) : runtime.read(operation, () => {}); 155+ if (write && this.legacyWritesHeld()) 156+ throw Error("disk-first indexes exist; enable ABSO_DISK_FIRST before writing"); 157+ return operation(this.project as EngineProject); 159+ private async diskCall( 162+ agent: string | undefined, 164+ how: string | undefined, 166+ ): Promise<Answer> { 167+ const runtime = this.diskRuntime()!; 168+ const validate = () => { 169+ if (revision !== this.authorityRevision) 170+ throw Object.assign(Error("project authorization changed during call setup"), { code: "authority-changed" }); 172+ const progress = await this.prepareDisk(validate); 173+ const known = new Set((await this.ctx.storage.get<string[]>("readers")) ?? []); 175+ let readersChanged = false; 176+ const readers: Readers = { 177+ has: (a) => known.has(a), 178+ list: () => [...known].sort(), 180+ if (on === known.has(a)) return; 181+ if (on) known.add(a); 182+ else known.delete(a); 183+ readersChanged = true; 186+ if (progress?.phase === "empty" && op !== "init") 187+ return { status: 404, body: { error: "no such project; run init first" } }; 188+ if (!progress?.ready && !(progress?.phase === "empty" && op === "init")) 189+ return { status: 503, body: { error: "project indexes are being prepared", retryAfter: 1, progress } }; 190+ const before = new SqliteLog(this.ctx.storage).seq(); 191+ const action = (calls: EngineProject) => { 192+ const result = answer(calls, op, agent, body, readers, how); 193+ if (result.status >= 500) throw Error(`project operation failed: ${JSON.stringify(result.body)}`); 198+ progress.phase === "empty" 199+ ? runtime.initialize(action, validate) 200+ : READ_OPS.has(op) || op.startsWith("change/") 201+ ? runtime.read(action, validate) 202+ : runtime.write(action, validate); 203+ if (readersChanged) { 204+ this.authorityRevision++; 205+ await this.ctx.storage.put("readers", readers.list()); 207+ const log = new SqliteLog(this.ctx.storage); 208+ if (log.seq() !== before) { 210+ await this.ctx.storage.put("name", name); 211+ await this.soon(Date.now() + 100); 214+ result.status === 200 && 215+ artifactsOf(this.env) && 216+ Date.now() - this.gitCheckedAt > GIT_CHECK_MS && 217+ (await this.ctx.storage.get("name")) !== undefined && 218+ (await this.ctx.storage.getAlarm()) === null 220+ await this.ctx.storage.setAlarm(Date.now()); 221+ if (result.status === 200 && op === "starting") result.body = await this.startingHooks(name, result.body); 222+ if (result.status === 200) result.body = this.withBlobSizes(op, result.body); 97226 /** The project, loaded from its log on first use. A log too big for memory is refused, not loaded. */ 98227 private ensure(): ProjectCalls | undefined { 228+ if (this.diskRuntime()) throw Error("legacy project load forbidden in disk-first mode"); 99229 if (this.loaded || this.tried) return this.loaded; 100230 this.tried = true; Lines 346–352 at 158 (were 216–221 at 157)
218348 ): Promise<Answer> { 349+ const revision = this.authorityRevision; 220351 const decided = await this.checkAgentKey(key.presented, agent, key.address); 221352 if (!decided.ok) return { status: decided.status, body: { error: decided.error } }; Lines 355–371 at 158 (were 224–229 at 157)
226357 if (op === "feed" && !inFeed) return this.feed(name, body); 358+ if (this.diskRuntime()) { 360+ return await this.diskCall(name, op, agent, body, how, revision); 362+ if ((error as { code?: string })?.code === "authority-changed") 363+ return { status: 409, body: { error: "project authorization changed; retry the request", retryable: true } }; 367+ if (this.legacyWritesHeld() && !READ_OPS.has(op) && !op.startsWith("change/")) 368+ return { status: 409, body: { error: "disk-first indexes exist; enable ABSO_DISK_FIRST before writing" } }; 227369 if (SOFT_HELD_OPS.has(op)) { 228370 const held = this.softHeld(); 229371 if (held) return { status: 507, body: { error: held } }; Lines 474–493 at 158 (were 332–347 at 157)
334476 private async gitSyncOnce(): Promise<{ head: string; commits: number; answer: unknown } | null> { 477+ if (this.legacyWritesHeld()) return null; 335478 const artifacts = artifactsOf(this.env); 336479 if (!artifacts) return null; 337480 this.gitCheckedAt = Date.now(); 338481 const name = await this.ctx.storage.get<string>("name"); 339− if (!name || !this.project.exists()) return null;
482+ if (!name) return null; 483+ const progress = await this.prepareDisk(); 484+ if (progress && !progress.ready) return null; 485+ if (!this.useProject((p) => p.exists())) return null; 340486 const seen = await this.ctx.storage.get<string>("git:head"); 341487 const pushed = await this.ctx.storage.get<PushResult>("pushed"); 342488 const head = await remoteHead(artifacts, name); 343489 if (!head || head === seen || head === pushed?.commit) return null; 344− const sharedBlobs = this.project.shared().blobs ?? {};
490+ const sharedBlobs = this.useProject((p) => p.shared().blobs ?? {}); 345491 const found = await pushedSince( Lines 501–510 at 158 (were 355–361 at 157)
356502 let result: unknown; 358− result = this.project.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now());
504+ result = this.useProject( 505+ (p) => p.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now()), 360509 result = { error: e instanceof Error ? e.message : String(e) }; Lines 532–545 at 158 (were 383–392 at 157)
383532 * most once a minute, backing off on failure. Without an ARTIFACTS binding (local dev) it does nothing. 385534 async alarm(): Promise<void> { 535+ if (!this.diskRuntime() && !artifactsOf(this.env)) return; 536+ if (!this.diskRuntime() && !this.ensure()) return; 537+ const progress = await this.prepareDisk(); 538+ if (progress && !progress.ready) return; 386539 const artifacts = artifactsOf(this.env); 387540 if (!artifacts) return; 388541 const name = await this.ctx.storage.get<string>("name"); 389− if (!name || !this.ensure()?.exists()) return;
542+ if (!name || !this.useProject((p) => p.exists())) return; 390543 await this.gitSync().then( 391544 () => this.ctx.storage.delete("git:error"), Lines 548–554 at 158 (were 395–401 at 157)
395548 error: e instanceof Error ? e.message : String(e), 398− const shared = this.project.shared();
551+ const shared = this.useProject((p) => p.shared()); 399552 const done = await this.ctx.storage.get<PushResult>("pushed"); 400553 if (done && done.version >= shared.version) return; 401554 const pushedAt = (await this.ctx.storage.get<number>("pushedAt")) ?? 0; Lines 575–590 at 158 (were 422–438 at 157)
422575 await this.ctx.storage.put({ pushed: result, "git:head": result.commit, pushedAt: Date.now() }); 423576 await this.ctx.storage.delete("pushError"); 424577 // 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);
578+ if (this.useProject((p) => p.shared().version) > result.version) await this.soon(Date.now() + PUSH_EVERY_MS); 428581 /** The push out: the repo, the last version pushed, and plain-git intake. */ 430583 const name = await this.ctx.storage.get<string>("name"); 431− const p = this.ensure();
433585 repo: name ? repoName(name) : null, 434586 artifacts: artifactsOf(this.env) ? "bound" : "unbound", 435− version: p?.exists() ? p.shared().version : null,
587+ version: this.logChars().entries ? new SqliteLog(this.ctx.storage).sharedVersion() : null, 436588 pushed: (await this.ctx.storage.get<PushResult>("pushed")) ?? null, 437589 error: (await this.ctx.storage.get("pushError")) ?? null, Lines 623–629 at 158 (were 471–476 at 157)
471623 if (typeof when !== "number") return { error: when.error }; 472624 const state = await this.keyState(); 473625 const issued = await issueKey(state, secret, agent, "admin", Date.now(), address, when, role); 626+ this.authorityRevision++; 474627 await this.ctx.storage.put("agent-keys", state); Lines 633–639 at 158 (were 480–485 at 157)
480633 if (!secret) return { revoked: false }; 481634 const state = await this.keyState(); 482635 const revoked = revokeKey(state, id, Date.now(), await hmac(secret, address)); 636+ this.authorityRevision++; 483637 await this.ctx.storage.put("agent-keys", state); 484638 return { revoked }; Lines 646–656 at 158 (were 492–500 at 157)
493647 /** The project's agent names, for the ask seat check. None when there's no project. */ 494648 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);
649+ if (!this.diskRuntime() && !this.ensure()) return []; 650+ const progress = await this.prepareDisk(); 651+ if (progress?.phase === "empty") return []; 652+ if (progress && !progress.ready) throw Error("project indexes are being prepared"); 653+ return this.useProject((p) => (p.exists() ? p.status().agents.map((a) => a.agent) : [])); Lines 658–698 at 158 (were 502–534 at 157)
502658 * its issue and to the known agents in `to`, never back to its writer. 504660 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;
661+ if (!this.diskRuntime() && !this.ensure()) return items.map(() => ({ to: [] })); 662+ const progress = await this.prepareDisk(); 663+ if (progress?.phase === "empty") return items.map(() => ({ to: [] })); 664+ if (progress && !progress.ready) throw Error("project indexes are being prepared"); 665+ return this.useProject((p) => { 666+ if (!p.exists()) return items.map(() => ({ to: [] })); 667+ const engine = p as ProjectCalls & ProjectHistory; 668+ const out: { to: string[] }[] = []; 669+ for (const item of items) { 670+ const status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] }; 671+ const known = new Set(status.agents.map((a) => a.agent)); 672+ const to = new Set([ 673+ ...(item.issue !== null 674+ ? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent) 676+ ...(item.to ?? []).filter((t) => known.has(t)), 678+ to.delete(item.from); 679+ if (to.size === 0) { 680+ out.push({ to: [] }); 684+ engine.announce(item.from, item.text, [...to]); 685+ out.push({ to: [...to] }); 687+ // Persistent writer state may already have changed. Let the outer 688+ // transaction undo the whole batch before reporting a failure. 689+ if (this.env.ABSO_DISK_FIRST === "on") throw e; 690+ console.log(JSON.stringify({ event: "issues-news", error: String(e).slice(0, 200) })); 691+ 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;