{"draft":null,"from":157,"to":158,"files":[{"path":"server/src/project-object.ts","added":202,"removed":38,"diff":"--- a/server/src/project-object.ts\n+++ b/server/src/project-object.ts\n@@ -7,6 +7,7 @@\n import { type Answer, answer, type Readers } from \"../../worker/project/http.ts\";\n import type { ProjectCalls, ProjectHistory } from \"../../worker/project/project-api.ts\";\n import { BLOB_MAX, BlobStore } from \"./blobs.ts\";\n+import { DiskFirstRuntime } from \"./disk-first-runtime.ts\";\n import { EngineProject, SqliteLog } from \"./engine-project.ts\";\n import { artifactsOf, type Env } from \"./env.ts\";\n import { pushedSince, remoteHead } from \"./ingest.ts\";\n@@ -23,7 +24,34 @@\n \trevokeKey,\n } from \"./keys.ts\";\n import { type PushResult, pushShared, repoName } from \"./push.ts\";\n+import { SqliteWriterState } from \"./writer-host.ts\";\n \n+const READ_OPS = new Set([\n+\t\"status\",\n+\t\"blame\",\n+\t\"why\",\n+\t\"tree\",\n+\t\"path\",\n+\t\"follow\",\n+\t\"collisions\",\n+\t\"draft-state\",\n+\t\"refusals\",\n+\t\"labels\",\n+\t\"log\",\n+\t\"show\",\n+\t\"file\",\n+\t\"files\",\n+\t\"compare\",\n+\t\"where\",\n+\t\"feed\",\n+\t\"drafts\",\n+\t\"diff\",\n+\t\"ribbon\",\n+\t\"position\",\n+\t\"changes\",\n+\t\"notes\",\n+]);\n+\n /** At most one push out a minute: each one clones the repo, so publishes in a burst share one. */\n export const PUSH_EVERY_MS = 60_000;\n /** While agents are working, how often a call looks for plain-git pushes to the repo. */\n@@ -78,6 +106,7 @@\n \t/** Why the log didn't load, if it didn't. */\n \tprivate loadError: unknown;\n \tprivate tried = false;\n+\tprivate authorityRevision = 0;\n \t/** Feed long-polls waiting for the log to grow; woken after every call that wrote. */\n \tprivate waiting: (() => void)[] = [];\n \t/** When this object last asked the repo for pushes made with plain git. */\n@@ -94,8 +123,109 @@\n \t\treturn { keep: (text: string) => this.blobs.putText(text), read: (sha: string) => this.blobs.textOf(sha) };\n \t}\n \n+\tprivate diskRuntime(): DiskFirstRuntime | undefined {\n+\t\treturn this.env.ABSO_DISK_FIRST === \"on\"\n+\t\t\t? new DiskFirstRuntime(this.ctx.storage, this.ctx.id.toString(), \"server-disk-v1\", {\n+\t\t\t\t\thasBlob: (sha) => this.blobs.has(sha),\n+\t\t\t\t\twhole: this.wholeFiles(),\n+\t\t\t\t})\n+\t\t\t: undefined;\n+\t}\n+\tprivate async prepareDisk(validate: () => void = () => {}) {\n+\t\tconst runtime = this.diskRuntime();\n+\t\tif (!runtime) return undefined;\n+\t\tconst progress = runtime.preparePage(validate);\n+\t\tif (!progress.ready && progress.phase !== \"empty\") await this.soon(Date.now() + 100);\n+\t\treturn progress;\n+\t}\n+\t/** Once indexing starts, legacy writes would invalidate the persistent root. */\n+\tprivate legacyWritesHeld(): boolean {\n+\t\tif (this.env.ABSO_DISK_FIRST === \"on\") return false;\n+\t\tconst tables = this.ctx.storage.sql\n+\t\t\t.exec(\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'writer_state'\")\n+\t\t\t.toArray();\n+\t\treturn (\n+\t\t\ttables.length > 0 &&\n+\t\t\tnew SqliteWriterState(this.ctx.storage, \"server-disk-v1\").read(\"runtime\", \"format\") !== undefined\n+\t\t);\n+\t}\n+\tprivate useProject<T>(operation: (calls: EngineProject) => T, write = false): T {\n+\t\tconst runtime = this.diskRuntime();\n+\t\tif (runtime) return write ? runtime.write(operation, () => {}) : runtime.read(operation, () => {});\n+\t\tif (write && this.legacyWritesHeld())\n+\t\t\tthrow Error(\"disk-first indexes exist; enable ABSO_DISK_FIRST before writing\");\n+\t\treturn operation(this.project as EngineProject);\n+\t}\n+\tprivate async diskCall(\n+\t\tname: string,\n+\t\top: string,\n+\t\tagent: string | undefined,\n+\t\tbody: unknown,\n+\t\thow: string | undefined,\n+\t\trevision: number,\n+\t): Promise<Answer> {\n+\t\tconst runtime = this.diskRuntime()!;\n+\t\tconst validate = () => {\n+\t\t\tif (revision !== this.authorityRevision)\n+\t\t\t\tthrow Object.assign(Error(\"project authorization changed during call setup\"), { code: \"authority-changed\" });\n+\t\t};\n+\t\tconst progress = await this.prepareDisk(validate);\n+\t\tconst known = new Set((await this.ctx.storage.get<string[]>(\"readers\")) ?? []);\n+\t\tvalidate();\n+\t\tlet readersChanged = false;\n+\t\tconst readers: Readers = {\n+\t\t\thas: (a) => known.has(a),\n+\t\t\tlist: () => [...known].sort(),\n+\t\t\tset: (a, on) => {\n+\t\t\t\tif (on === known.has(a)) return;\n+\t\t\t\tif (on) known.add(a);\n+\t\t\t\telse known.delete(a);\n+\t\t\t\treadersChanged = true;\n+\t\t\t},\n+\t\t};\n+\t\tif (progress?.phase === \"empty\" && op !== \"init\")\n+\t\t\treturn { status: 404, body: { error: \"no such project; run init first\" } };\n+\t\tif (!progress?.ready && !(progress?.phase === \"empty\" && op === \"init\"))\n+\t\t\treturn { status: 503, body: { error: \"project indexes are being prepared\", retryAfter: 1, progress } };\n+\t\tconst before = new SqliteLog(this.ctx.storage).seq();\n+\t\tconst action = (calls: EngineProject) => {\n+\t\t\tconst result = answer(calls, op, agent, body, readers, how);\n+\t\t\tif (result.status >= 500) throw Error(`project operation failed: ${JSON.stringify(result.body)}`);\n+\t\t\treturn result;\n+\t\t};\n+\n+\t\tconst result =\n+\t\t\tprogress.phase === \"empty\"\n+\t\t\t\t? runtime.initialize(action, validate)\n+\t\t\t\t: READ_OPS.has(op) || op.startsWith(\"change/\")\n+\t\t\t\t\t? runtime.read(action, validate)\n+\t\t\t\t\t: runtime.write(action, validate);\n+\t\tif (readersChanged) {\n+\t\t\tthis.authorityRevision++;\n+\t\t\tawait this.ctx.storage.put(\"readers\", readers.list());\n+\t\t}\n+\t\tconst log = new SqliteLog(this.ctx.storage);\n+\t\tif (log.seq() !== before) {\n+\t\t\tthis.wake();\n+\t\t\tawait this.ctx.storage.put(\"name\", name);\n+\t\t\tawait this.soon(Date.now() + 100);\n+\t\t}\n+\t\tif (\n+\t\t\tresult.status === 200 &&\n+\t\t\tartifactsOf(this.env) &&\n+\t\t\tDate.now() - this.gitCheckedAt > GIT_CHECK_MS &&\n+\t\t\t(await this.ctx.storage.get(\"name\")) !== undefined &&\n+\t\t\t(await this.ctx.storage.getAlarm()) === null\n+\t\t)\n+\t\t\tawait this.ctx.storage.setAlarm(Date.now());\n+\t\tif (result.status === 200 && op === \"starting\") result.body = await this.startingHooks(name, result.body);\n+\t\tif (result.status === 200) result.body = this.withBlobSizes(op, result.body);\n+\t\treturn result;\n+\t}\n+\n \t/** The project, loaded from its log on first use. A log too big for memory is refused, not loaded. */\n \tprivate ensure(): ProjectCalls | undefined {\n+\t\tif (this.diskRuntime()) throw Error(\"legacy project load forbidden in disk-first mode\");\n \t\tif (this.loaded || this.tried) return this.loaded;\n \t\tthis.tried = true;\n \t\ttry {\n@@ -216,6 +346,7 @@\n \t\thow?: string,\n \t\tkey?: KeyForCall,\n \t): Promise<Answer> {\n+\t\tconst revision = this.authorityRevision;\n \t\tif (key) {\n \t\t\tconst decided = await this.checkAgentKey(key.presented, agent, key.address);\n \t\t\tif (!decided.ok) return { status: decided.status, body: { error: decided.error } };\n@@ -224,6 +355,17 @@\n \t\t\thow = decided.as;\n \t\t}\n \t\tif (op === \"feed\" && !inFeed) return this.feed(name, body);\n+\t\tif (this.diskRuntime()) {\n+\t\t\ttry {\n+\t\t\t\treturn await this.diskCall(name, op, agent, body, how, revision);\n+\t\t\t} catch (error) {\n+\t\t\t\tif ((error as { code?: string })?.code === \"authority-changed\")\n+\t\t\t\t\treturn { status: 409, body: { error: \"project authorization changed; retry the request\", retryable: true } };\n+\t\t\t\tthrow error;\n+\t\t\t}\n+\t\t}\n+\t\tif (this.legacyWritesHeld() && !READ_OPS.has(op) && !op.startsWith(\"change/\"))\n+\t\t\treturn { status: 409, body: { error: \"disk-first indexes exist; enable ABSO_DISK_FIRST before writing\" } };\n \t\tif (SOFT_HELD_OPS.has(op)) {\n \t\t\tconst held = this.softHeld();\n \t\t\tif (held) return { status: 507, body: { error: held } };\n@@ -332,16 +474,20 @@\n \t}\n \n \tprivate async gitSyncOnce(): Promise<{ head: string; commits: number; answer: unknown } | null> {\n+\t\tif (this.legacyWritesHeld()) return null;\n \t\tconst artifacts = artifactsOf(this.env);\n \t\tif (!artifacts) return null;\n \t\tthis.gitCheckedAt = Date.now();\n \t\tconst name = await this.ctx.storage.get<string>(\"name\");\n-\t\tif (!name || !this.project.exists()) return null;\n+\t\tif (!name) return null;\n+\t\tconst progress = await this.prepareDisk();\n+\t\tif (progress && !progress.ready) return null;\n+\t\tif (!this.useProject((p) => p.exists())) return null;\n \t\tconst seen = await this.ctx.storage.get<string>(\"git:head\");\n \t\tconst pushed = await this.ctx.storage.get<PushResult>(\"pushed\");\n \t\tconst head = await remoteHead(artifacts, name);\n \t\tif (!head || head === seen || head === pushed?.commit) return null;\n-\t\tconst sharedBlobs = this.project.shared().blobs ?? {};\n+\t\tconst sharedBlobs = this.useProject((p) => p.shared().blobs ?? {});\n \t\tconst found = await pushedSince(\n \t\t\tartifacts,\n \t\t\tname,\n@@ -355,7 +501,10 @@\n \t\t}\n \t\tlet result: unknown;\n \t\ttry {\n-\t\t\tresult = this.project.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now());\n+\t\t\tresult = this.useProject(\n+\t\t\t\t(p) => p.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now()),\n+\t\t\t\ttrue,\n+\t\t\t);\n \t\t} catch (e) {\n \t\t\tresult = { error: e instanceof Error ? e.message : String(e) };\n \t\t}\n@@ -383,10 +532,14 @@\n \t * most once a minute, backing off on failure. Without an ARTIFACTS binding (local dev) it does nothing.\n \t */\n \tasync alarm(): Promise<void> {\n+\t\tif (!this.diskRuntime() && !artifactsOf(this.env)) return;\n+\t\tif (!this.diskRuntime() && !this.ensure()) return;\n+\t\tconst progress = await this.prepareDisk();\n+\t\tif (progress && !progress.ready) return;\n \t\tconst artifacts = artifactsOf(this.env);\n \t\tif (!artifacts) return;\n \t\tconst name = await this.ctx.storage.get<string>(\"name\");\n-\t\tif (!name || !this.ensure()?.exists()) return;\n+\t\tif (!name || !this.useProject((p) => p.exists())) return;\n \t\tawait this.gitSync().then(\n \t\t\t() => this.ctx.storage.delete(\"git:error\"),\n \t\t\t(e) =>\n@@ -395,7 +548,7 @@\n \t\t\t\t\terror: e instanceof Error ? e.message : String(e),\n \t\t\t\t}),\n \t\t);\n-\t\tconst shared = this.project.shared();\n+\t\tconst shared = this.useProject((p) => p.shared());\n \t\tconst done = await this.ctx.storage.get<PushResult>(\"pushed\");\n \t\tif (done && done.version >= shared.version) return;\n \t\tconst pushedAt = (await this.ctx.storage.get<number>(\"pushedAt\")) ?? 0;\n@@ -422,17 +575,16 @@\n \t\tawait this.ctx.storage.put({ pushed: result, \"git:head\": result.commit, pushedAt: Date.now() });\n \t\tawait this.ctx.storage.delete(\"pushError\");\n \t\t// Another publish may have landed while this push ran.\n-\t\tif (this.project.shared().version > result.version) await this.soon(Date.now() + PUSH_EVERY_MS);\n+\t\tif (this.useProject((p) => p.shared().version) > result.version) await this.soon(Date.now() + PUSH_EVERY_MS);\n \t}\n \n \t/** The push out: the repo, the last version pushed, and plain-git intake. */\n \tasync out() {\n \t\tconst name = await this.ctx.storage.get<string>(\"name\");\n-\t\tconst p = this.ensure();\n \t\treturn {\n \t\t\trepo: name ? repoName(name) : null,\n \t\t\tartifacts: artifactsOf(this.env) ? \"bound\" : \"unbound\",\n-\t\t\tversion: p?.exists() ? p.shared().version : null,\n+\t\t\tversion: this.logChars().entries ? new SqliteLog(this.ctx.storage).sharedVersion() : null,\n \t\t\tpushed: (await this.ctx.storage.get<PushResult>(\"pushed\")) ?? null,\n \t\t\terror: (await this.ctx.storage.get(\"pushError\")) ?? null,\n \t\t\tgit: {\n@@ -471,6 +623,7 @@\n \t\tif (typeof when !== \"number\") return { error: when.error };\n \t\tconst state = await this.keyState();\n \t\tconst issued = await issueKey(state, secret, agent, \"admin\", Date.now(), address, when, role);\n+\t\tthis.authorityRevision++;\n \t\tawait this.ctx.storage.put(\"agent-keys\", state);\n \t\treturn issued;\n \t}\n@@ -480,6 +633,7 @@\n \t\tif (!secret) return { revoked: false };\n \t\tconst state = await this.keyState();\n \t\tconst revoked = revokeKey(state, id, Date.now(), await hmac(secret, address));\n+\t\tthis.authorityRevision++;\n \t\tawait this.ctx.storage.put(\"agent-keys\", state);\n \t\treturn { revoked };\n \t}\n@@ -492,9 +646,11 @@\n \n \t/** The project's agent names, for the ask seat check. None when there's no project. */\n \tasync agents(_project: string): Promise<string[]> {\n-\t\tconst p = this.ensure();\n-\t\tif (!p?.exists()) return [];\n-\t\treturn p.status().agents.map((a) => a.agent);\n+\t\tif (!this.diskRuntime() && !this.ensure()) return [];\n+\t\tconst progress = await this.prepareDisk();\n+\t\tif (progress?.phase === \"empty\") return [];\n+\t\tif (progress && !progress.ready) throw Error(\"project indexes are being prepared\");\n+\t\treturn this.useProject((p) => (p.exists() ? p.status().agents.map((a) => a.agent) : []));\n \t}\n \n \t/**\n@@ -502,33 +658,41 @@\n \t * its issue and to the known agents in `to`, never back to its writer.\n \t */\n \tasync news(_project: string, items: IssueNews[]): Promise<{ to: string[] }[]> {\n-\t\tconst p = this.ensure();\n-\t\tif (!p?.exists()) return items.map(() => ({ to: [] }));\n-\t\tconst engine = p as ProjectCalls & ProjectHistory;\n-\t\tconst out: { to: string[] }[] = [];\n-\t\tfor (const item of items) {\n-\t\t\tconst status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] };\n-\t\t\tconst known = new Set(status.agents.map((a) => a.agent));\n-\t\t\tconst to = new Set([\n-\t\t\t\t...(item.issue !== null\n-\t\t\t\t\t? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent)\n-\t\t\t\t\t: []),\n-\t\t\t\t...(item.to ?? []).filter((t) => known.has(t)),\n-\t\t\t]);\n-\t\t\tto.delete(item.from);\n-\t\t\tif (to.size === 0) {\n-\t\t\t\tout.push({ to: [] });\n-\t\t\t\tcontinue;\n+\t\tif (!this.diskRuntime() && !this.ensure()) return items.map(() => ({ to: [] }));\n+\t\tconst progress = await this.prepareDisk();\n+\t\tif (progress?.phase === \"empty\") return items.map(() => ({ to: [] }));\n+\t\tif (progress && !progress.ready) throw Error(\"project indexes are being prepared\");\n+\t\treturn this.useProject((p) => {\n+\t\t\tif (!p.exists()) return items.map(() => ({ to: [] }));\n+\t\t\tconst engine = p as ProjectCalls & ProjectHistory;\n+\t\t\tconst out: { to: string[] }[] = [];\n+\t\t\tfor (const item of items) {\n+\t\t\t\tconst status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] };\n+\t\t\t\tconst known = new Set(status.agents.map((a) => a.agent));\n+\t\t\t\tconst to = new Set([\n+\t\t\t\t\t...(item.issue !== null\n+\t\t\t\t\t\t? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent)\n+\t\t\t\t\t\t: []),\n+\t\t\t\t\t...(item.to ?? []).filter((t) => known.has(t)),\n+\t\t\t\t]);\n+\t\t\t\tto.delete(item.from);\n+\t\t\t\tif (to.size === 0) {\n+\t\t\t\t\tout.push({ to: [] });\n+\t\t\t\t\tcontinue;\n+\t\t\t\t}\n+\t\t\t\ttry {\n+\t\t\t\t\tengine.announce(item.from, item.text, [...to]);\n+\t\t\t\t\tout.push({ to: [...to] });\n+\t\t\t\t} catch (e) {\n+\t\t\t\t\t// Persistent writer state may already have changed. Let the outer\n+\t\t\t\t\t// transaction undo the whole batch before reporting a failure.\n+\t\t\t\t\tif (this.env.ABSO_DISK_FIRST === \"on\") throw e;\n+\t\t\t\t\tconsole.log(JSON.stringify({ event: \"issues-news\", error: String(e).slice(0, 200) }));\n+\t\t\t\t\tout.push({ to: [] });\n+\t\t\t\t}\n \t\t\t}\n-\t\t\ttry {\n-\t\t\t\tengine.announce(item.from, item.text, [...to]);\n-\t\t\t\tout.push({ to: [...to] });\n-\t\t\t} catch (e) {\n-\t\t\t\tconsole.log(JSON.stringify({ event: \"issues-news\", error: String(e).slice(0, 200) }));\n-\t\t\t\tout.push({ to: [] });\n-\t\t\t}\n-\t\t}\n-\t\tthis.wake();\n-\t\treturn out;\n+\t\t\tthis.wake();\n+\t\t\treturn out;\n+\t\t}, true);\n \t}\n }"}],"unmatched":[]}