{"version":158,"agent":"codex-capacity-chair","message":"Integrate opt-in disk-first project runtime with cold-object transactions","time":1791917879117,"timeIso":"2026-10-13T18:57:59.117Z","changes":18,"change":2042,"files":["server/src/disk-first-runtime.ts","server/src/engine-project.ts","server/src/env.ts","server/src/project-object.ts","server/src/writer-host.ts","server/test/disk-first-runtime.test.ts","server/test/engine-project.test.ts","server/test/project-object-disk-first.test.ts","src/engine/experimental/projection-locator.ts","src/engine/experimental/projection-reader.ts","src/engine/test/projection-membership-iterator.test.ts","worker/project/changes-since.ts"],"draft":null,"diff":[{"path":"server/src/disk-first-runtime.ts","added":167,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/disk-first-runtime.ts\n@@ -0,0 +1,167 @@\n+import { canonicalJson } from \"../../worker/project/operation-protocol.ts\";\n+import { Project, type WriterSource } from \"../../worker/project/project.ts\";\n+import type { ProjectOptions } from \"../../worker/project/project-types.ts\";\n+import { EngineProject, SqliteLog, type SqliteStorage } from \"./engine-project.ts\";\n+import { SqliteProjectionStore } from \"./projection-store.ts\";\n+import { SqliteWriterHost, SqliteWriterState } from \"./writer-host.ts\";\n+\n+type Services = Pick<ProjectOptions, \"hasBlob\" | \"whole\">;\n+type Progress = { ready: boolean; phase: \"empty\" | \"writer\" | \"projection\" | \"ready\"; next: number };\n+\n+/** One synchronous page or call per invocation. No object retains a loaded Project.\n+ * The owner schedules subsequent pages and supplies fresh authorization for every call. */\n+export class DiskFirstRuntime {\n+\treadonly #storage: SqliteStorage;\n+\treadonly #namespace: string;\n+\treadonly #projection: SqliteProjectionStore;\n+\treadonly #services: Services;\n+\tconstructor(storage: SqliteStorage, database: string, namespace: string, services: Services = {}) {\n+\t\tthis.#storage = storage;\n+\t\tthis.#namespace = namespace;\n+\t\tthis.#services = services;\n+\t\tthis.#projection = new SqliteProjectionStore(\n+\t\t\t{\n+\t\t\t\tdatabase,\n+\t\t\t\tnamespace: `${namespace}:views`,\n+\t\t\t\tregistry: `${namespace}:roots`,\n+\t\t\t\tdefaultFile: \"__abso_projection_default__\",\n+\t\t\t},\n+\t\t\t1,\n+\t\t\t{ indexedAtoms: true },\n+\t\t);\n+\t}\n+\t#host() {\n+\t\treturn new SqliteWriterHost(this.#storage, this.#namespace, this.#projection, { indexProjectionAtoms: true });\n+\t}\n+\t#state() {\n+\t\treturn new SqliteWriterState(this.#storage, this.#namespace);\n+\t}\n+\t#validate(validate: () => void) {\n+\t\tconst result: unknown = validate();\n+\t\tif (result && (typeof result === \"object\" || typeof result === \"function\") && \"then\" in result)\n+\t\t\tthrow Error(\"runtime authorization must be synchronous\");\n+\t}\n+\t#setup() {\n+\t\tSqliteWriterState.initialize(this.#storage);\n+\t\tconst state = this.#state();\n+\t\tconst format = state.read(\"runtime\", \"format\");\n+\t\tif (format !== undefined && format !== 1) throw Error(\"unsupported disk-first runtime format\");\n+\t\tif (format === undefined) state.write(\"runtime\", \"format\", 1);\n+\t\treturn state;\n+\t}\n+\t/** Initializes an empty canonical log without replay. Existing history must be adopted. */\n+\tinitialize<T>(operation: (calls: EngineProject) => T, validate: () => void): T {\n+\t\treturn this.#storage.transactionSync(() => {\n+\t\t\tthis.#validate(validate);\n+\t\t\tconst log = new SqliteLog(this.#storage);\n+\t\t\tif (log.seq() !== 0) throw Error(\"disk-first initialization requires an empty log\");\n+\t\t\tconst project = new Project(log, { ...this.#services, now: () => Date.now(), shapes: log.shapes() });\n+\t\t\tconst result = structuredClone(operation(new EngineProject(project)));\n+\t\t\tthis.#validate(validate);\n+\t\t\treturn result;\n+\t\t});\n+\t}\n+\tpreparePage(validate: () => void): Progress {\n+\t\treturn this.#storage.transactionSync(() => {\n+\t\t\tthis.#validate(validate);\n+\t\t\tconst log = new SqliteLog(this.#storage);\n+\t\t\tif (log.seq() === 0) {\n+\t\t\t\tthis.#validate(validate);\n+\t\t\t\treturn { ready: false, phase: \"empty\", next: 0 };\n+\t\t\t}\n+\t\t\tconst state = this.#setup();\n+\t\t\tconst host = this.#host();\n+\t\t\tconst ready = state.read(\"runtime\", \"ready\");\n+\t\t\tif (ready !== undefined && ready !== true) throw Error(\"invalid runtime readiness marker\");\n+\t\t\tif (ready === true) {\n+\t\t\t\tconst root = host.root();\n+\t\t\t\tconst scope = this.#projection.open({ state, log, root });\n+\t\t\t\tscope.close();\n+\t\t\t\tthis.#validate(validate);\n+\t\t\t\treturn { ready: true, phase: \"ready\", next: root.logLength };\n+\t\t\t}\n+\t\t\tconst bound = state.read(\"host\", \"canonical-root\");\n+\t\t\tif (bound === undefined) {\n+\t\t\t\tconst cursor = state.read(\"host\", \"adoption-root\") as\n+\t\t\t\t\t| { source: WriterSource; next: number; digest: string }\n+\t\t\t\t\t| undefined;\n+\t\t\t\tconst page = host.adoptVerifiedPage(\n+\t\t\t\t\t{\n+\t\t\t\t\t\texpected: cursor?.source ?? host.source(),\n+\t\t\t\t\t\tfrom: cursor?.next ?? 0,\n+\t\t\t\t\t\tdigest: cursor?.digest ?? \"\",\n+\t\t\t\t\t\tmaxEntries: 32,\n+\t\t\t\t\t\tmaxBytes: 1_048_576,\n+\t\t\t\t\t},\n+\t\t\t\t\tvalidate,\n+\t\t\t\t);\n+\t\t\t\tthis.#validate(validate);\n+\t\t\t\treturn { ready: false, phase: \"writer\", next: page.next };\n+\t\t\t}\n+\t\t\tconst root = host.root();\n+\t\t\tconst page = this.#projection.adopt({\n+\t\t\t\tstate,\n+\t\t\t\texpected: root,\n+\t\t\t\tcurrentRoot: () => host.root(),\n+\t\t\t\tmaxAtoms: 32,\n+\t\t\t\tmaxVersions: 1,\n+\t\t\t\tmaxSteps: 32,\n+\t\t\t});\n+\t\t\tthis.#validate(validate);\n+\t\t\tif (page.ready) state.write(\"runtime\", \"ready\", true);\n+\t\t\treturn { ready: page.ready, phase: page.ready ? \"ready\" : \"projection\", next: root.logLength };\n+\t\t});\n+\t}\n+\t#requireReady() {\n+\t\tif (\n+\t\t\tthis.#storage.sql.exec(\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'writer_state'\").toArray()\n+\t\t\t\t.length === 0\n+\t\t)\n+\t\t\tthrow Error(\"disk-first adoption is not complete\");\n+\t\tif (this.#state().read(\"runtime\", \"format\") !== 1 || this.#state().read(\"runtime\", \"ready\") !== true)\n+\t\t\tthrow Error(\"disk-first adoption is not complete\");\n+\t}\n+\tread<T>(operation: (calls: EngineProject) => T, validate: () => void): T {\n+\t\tthis.#requireReady();\n+\t\tconst host = this.#host();\n+\t\treturn host.readCalls({\n+\t\t\texpected: host.source(),\n+\t\t\tvalidateAuthority: validate,\n+\t\t\tservices: this.#services,\n+\t\t\toperation: (calls) => structuredClone(operation(calls)),\n+\t\t});\n+\t}\n+\twrite<T>(\n+\t\toperation: (calls: EngineProject) => T,\n+\t\tvalidate: () => void,\n+\t\trequest?: { id: string; identity: unknown },\n+\t): T {\n+\t\treturn this.#storage.transactionSync(() => {\n+\t\t\tthis.#validate(validate);\n+\t\t\tthis.#requireReady();\n+\t\t\tconst state = this.#state();\n+\t\t\tconst host = this.#host();\n+\t\t\thost.root();\n+\t\t\tif (request && (!request.id || request.id.length > 128)) throw Error(\"invalid disk-first request identity\");\n+\t\t\tconst identity = request ? canonicalJson(request.identity) : undefined;\n+\t\t\tif (request) {\n+\t\t\t\tconst receipt = state.read(\"runtime:receipts\", request.id) as { identity: string; result: T } | undefined;\n+\t\t\t\tif (receipt) {\n+\t\t\t\t\tif (receipt.identity !== identity) throw Error(\"disk-first request identity was reused\");\n+\t\t\t\t\tthis.#validate(validate);\n+\t\t\t\t\treturn structuredClone(receipt.result);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\treturn host.runCalls({\n+\t\t\t\texpected: host.source(),\n+\t\t\t\tvalidateAuthority: validate,\n+\t\t\t\tservices: this.#services,\n+\t\t\t\tcheckerReady: false,\n+\t\t\t\toperation: (calls) => structuredClone(operation(calls)),\n+\t\t\t\tcommitReceipt: (result) => {\n+\t\t\t\t\tif (request) state.write(\"runtime:receipts\", request.id, { identity, result });\n+\t\t\t\t},\n+\t\t\t});\n+\t\t});\n+\t}\n+}"},{"path":"server/src/engine-project.ts","added":12,"removed":3,"diff":"--- a/server/src/engine-project.ts\n+++ b/server/src/engine-project.ts\n@@ -536,14 +536,23 @@\n \t\tif (!this.read) throw Object.assign(new Error(\"the feed needs the log\"), { code: \"not-implemented\" });\n \t\tconst end = this.project.logLength;\n \t\tconst start = Math.max(0, Math.min(from, end));\n-\t\tconst entries = start < end ? this.read(start, Math.min(limit, end - start)) : [];\n+\t\t// Discard each canonical payload after extracting its event. A feed page must\n+\t\t// not retain every historical file payload in the requested range.\n+\t\tconst events = [];\n+\t\tlet next = start;\n+\t\twhile (next < end && next - start < limit) {\n+\t\t\tconst entries = this.read(next, 1);\n+\t\t\tif (entries.length === 0) break;\n+\t\t\tevents.push(...feedEvents(entries, next));\n+\t\t\tnext += entries.length;\n+\t\t}\n \t\t// A drop event names the files it took out (#41), so a timeline needs no read per drop.\n-\t\tconst events = feedEvents(entries, start).map((e) => {\n+\t\tconst enriched = events.map((e) => {\n \t\t\tif (e.type !== \"drop\" || e.version === undefined) return e;\n \t\t\tconst v = this.project.log({ limit: 1, before: e.version + 1 }).versions[0];\n \t\t\treturn v && v.version === e.version ? { ...e, dropped: v.files } : e;\n \t\t});\n-\t\treturn { next: start + entries.length, end, events };\n+\t\treturn { next, end, events: enriched };\n \t}\n \n \t/** The log position for a time (ms since 1970) or a version of shared (#41). */"},{"path":"server/src/env.ts","added":2,"removed":0,"diff":"--- a/server/src/env.ts\n+++ b/server/src/env.ts\n@@ -4,6 +4,8 @@\n import type { ProjectObject } from \"./project-object.ts\";\n \n export interface Env {\n+\t/** Explicit development opt-in while disk-first server acceptance is in progress. */\n+\tABSO_DISK_FIRST?: string;\n \t/** One Durable Object per project, named by the project's name. */\n \tPROJECT: DurableObjectNamespace<ProjectObject>;\n \t/** Issues, asks and news: one Durable Object per project, named by the project's name. */"},{"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 }"},{"path":"server/src/writer-host.ts","added":1,"removed":1,"diff":"--- a/server/src/writer-host.ts\n+++ b/server/src/writer-host.ts\n@@ -351,7 +351,7 @@\n \t\t\t\t\treadViewProvider: projection?.readViewProvider,\n \t\t\t\t\tentryAt: (index) => this.#log.since(index, 1)[0]!,\n \t\t\t\t});\n-\t\t\t\tconst result = input.operation(new EngineProject(project));\n+\t\t\t\tconst result = input.operation(new EngineProject(project, (from, limit) => this.#log.since(from, limit)));\n \t\t\t\tSqliteWriterHost.#sync(result);\n \t\t\t\tSqliteWriterHost.#sync(input.validateAuthority());\n \t\t\t\tif (!SqliteWriterHost.#same(source, this.source())) throw new Error(\"reader source changed\");"},{"path":"server/test/disk-first-runtime.test.ts","added":132,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/disk-first-runtime.test.ts\n@@ -0,0 +1,132 @@\n+import assert from \"node:assert/strict\";\n+import { mkdtempSync, rmdirSync, unlinkSync } from \"node:fs\";\n+import { tmpdir } from \"node:os\";\n+import { join } from \"node:path\";\n+import { test } from \"node:test\";\n+import { answer } from \"../../worker/project/http.ts\";\n+import { Project } from \"../../worker/project/project.ts\";\n+import { DiskFirstRuntime } from \"../src/disk-first-runtime.ts\";\n+import { SqliteLog } from \"../src/engine-project.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"runtime resumes from disk and detaches reads, with exact authorized retries\", (t) => {\n+\tconst directory = mkdtempSync(join(tmpdir(), \"abso-runtime-\"));\n+\tconst filename = join(directory, \"state.sqlite\");\n+\tlet storage = memoryStorage(filename);\n+\tt.after(() => {\n+\t\tstorage.db.close();\n+\t\tunlinkSync(filename);\n+\t\trmdirSync(directory);\n+\t});\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"project-1\", \"disk-v1\");\n+\tconst validate = () => {};\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full-history load forbidden\");\n+\t});\n+\tassert.equal(runtime().preparePage(validate).phase, \"empty\");\n+\tassert.equal(\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM sqlite_master WHERE name = 'writer_state'\").get()!.n,\n+\t\t0,\n+\t\t\"an empty lookup must not install the legacy-write fence\",\n+\t);\n+\tassert.equal(\n+\t\truntime().initialize((calls) => answer(calls, \"init\", undefined, { files: { \"a.txt\": \"one\\ntwo\\n\" } }), validate)\n+\t\t\t.status,\n+\t\t200,\n+\t);\n+\tassert.throws(() => runtime().write(() => undefined, validate), /not complete/);\n+\tlet pages = 0;\n+\twhile (!runtime().preparePage(validate).ready) {\n+\t\tassert.ok(++pages < 100);\n+\t\tstorage.db.close();\n+\t\tstorage = memoryStorage(filename);\n+\t}\n+\tassert.ok(pages > 0);\n+\tconst req = { id: \"record-1\", identity: { agent: \"alice\", operation: \"record\", files: { \"a.txt\": \"changed\\n\" } } };\n+\tconst operation = (calls: Parameters<Parameters<DiskFirstRuntime[\"write\"]>[0]>[0]) =>\n+\t\tanswer(calls, \"record\", \"alice\", { files: req.identity.files });\n+\tconst first = runtime().write(operation, validate, req);\n+\tassert.equal(first.status, 200);\n+\tconst length = new SqliteLog(storage).seq();\n+\tstorage.db.close();\n+\tstorage = memoryStorage(filename);\n+\tassert.deepEqual(\n+\t\truntime().write(\n+\t\t\t() => {\n+\t\t\t\tthrow Error(\"retry executed\");\n+\t\t\t},\n+\t\t\tvalidate,\n+\t\t\treq,\n+\t\t),\n+\t\tfirst,\n+\t);\n+\tassert.equal(new SqliteLog(storage).seq(), length);\n+\tassert.throws(() => runtime().write(operation, validate, { ...req, identity: { agent: \"bob\" } }), /reused/);\n+\tassert.throws(\n+\t\t() =>\n+\t\t\truntime().write(\n+\t\t\t\toperation,\n+\t\t\t\t() => {\n+\t\t\t\t\tthrow Error(\"revoked\");\n+\t\t\t\t},\n+\t\t\t\treq,\n+\t\t\t),\n+\t\t/revoked/,\n+\t);\n+\tassert.equal(\n+\t\truntime().write((calls) => answer(calls, \"publish\", \"alice\", { message: \"Publish\" }), validate).status,\n+\t\t200,\n+\t);\n+\tconst shared = runtime().read((calls) => calls.shared(), validate);\n+\tassert.equal(Object.getOwnPropertyDescriptor(shared, \"files\")?.get, undefined);\n+\tassert.equal(shared.files[\"a.txt\"], \"changed\\n\");\n+\tstorage.db.close();\n+\tstorage = memoryStorage(filename);\n+\tassert.equal(runtime().preparePage(validate).ready, true);\n+\tassert.equal(\n+\t\truntime().read((calls) => calls.shared().files[\"a.txt\"], validate),\n+\t\t\"changed\\n\",\n+\t);\n+});\n+\n+test(\"runtime page and write authority failures leave no partial state\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst runtime = new DiskFirstRuntime(storage, \"project\", \"disk-v1\");\n+\truntime.initialize(\n+\t\t(calls) => answer(calls, \"init\", undefined, { files: { \"a.txt\": \"one\\n\" } }),\n+\t\t() => {},\n+\t);\n+\tconst rows = () => {\n+\t\tconst tables = storage.db.prepare(\"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name\").all();\n+\t\treturn tables.map((row) => [\n+\t\t\trow.name,\n+\t\t\tstorage.db.prepare(`SELECT * FROM \"${String(row.name).replaceAll('\"', '\"\"')}\" ORDER BY rowid`).all(),\n+\t\t]);\n+\t};\n+\tconst before = rows();\n+\tlet checks = 0;\n+\tassert.throws(\n+\t\t() =>\n+\t\t\truntime.preparePage(() => {\n+\t\t\t\tif (++checks === 3) throw Error(\"authority changed\");\n+\t\t\t}),\n+\t\t/authority changed/,\n+\t);\n+\tassert.deepEqual(rows(), before);\n+\twhile (!runtime.preparePage(() => {}).ready) {}\n+\tconst adopted = rows();\n+\tchecks = 0;\n+\tassert.throws(\n+\t\t() =>\n+\t\t\truntime.write(\n+\t\t\t\t(calls) => answer(calls, \"record\", \"alice\", { files: { \"a.txt\": \"two\\n\" } }),\n+\t\t\t\t() => {\n+\t\t\t\t\tif (++checks === 3) throw Error(\"authority changed\");\n+\t\t\t\t},\n+\t\t\t\t{ id: \"failed\", identity: \"record\" },\n+\t\t\t),\n+\t\t/authority changed/,\n+\t);\n+\tassert.deepEqual(rows(), adopted);\n+});"},{"path":"server/test/engine-project.test.ts","added":20,"removed":0,"diff":"--- a/server/test/engine-project.test.ts\n+++ b/server/test/engine-project.test.ts\n@@ -5,6 +5,26 @@\n import { memoryStorage } from \"./helpers.ts\";\n \n describe(\"the engine over the object's SQLite log\", () => {\n+\tit(\"extracts feed events without retaining a page of canonical payloads\", (t) => {\n+\t\tconst storage = memoryStorage();\n+\t\tt.after(() => storage.db.close());\n+\t\tconst project = EngineProject.open(storage);\n+\t\tanswer(project, \"init\", undefined, { files: { \"a.txt\": \"one\\n\" } });\n+\t\tanswer(project, \"sync\", \"alice\", {});\n+\t\tanswer(project, \"record\", \"alice\", { files: { \"a.txt\": \"two\\n\" } });\n+\t\tanswer(project, \"publish\", \"alice\", { message: \"Changed\" });\n+\t\tconst expected = project.feed(0, 500);\n+\t\tconst original = SqliteLog.prototype.since;\n+\t\tlet reads = 0;\n+\t\tt.mock.method(SqliteLog.prototype, \"since\", function (this: SqliteLog, from: number, limit: number) {\n+\t\t\tassert.equal(limit, 1, \"feed must release each canonical payload before reading another\");\n+\t\t\treads++;\n+\t\t\treturn original.call(this, from, limit);\n+\t\t});\n+\t\tassert.deepEqual(project.feed(0, 500), expected);\n+\t\tassert.equal(reads, expected.next);\n+\t\tassert.deepEqual(project.feed(1, 2).events, expected.events.slice(1, 3));\n+\t});\n \tit(\"serves init, records and pushes through answer(), and holds a collision\", () => {\n \t\tconst storage = memoryStorage();\n \t\tconst p = EngineProject.open(storage);"},{"path":"server/test/project-object-disk-first.test.ts","added":168,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/project-object-disk-first.test.ts\n@@ -0,0 +1,168 @@\n+import assert from \"node:assert/strict\";\n+import { registerHooks } from \"node:module\";\n+import { test } from \"node:test\";\n+import { Project } from \"../../worker/project/project.ts\";\n+import { EngineProject } from \"../src/engine-project.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+const hooks = registerHooks({\n+\tresolve(specifier, context, next) {\n+\t\tif (specifier === \"cloudflare:workers\")\n+\t\t\treturn {\n+\t\t\t\turl: `data:text/javascript,${encodeURIComponent(\"export class DurableObject { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }\")}`,\n+\t\t\t\tshortCircuit: true,\n+\t\t\t};\n+\t\treturn next(specifier, context);\n+\t},\n+});\n+const { ProjectObject } = await import(\"../src/project-object.ts\");\n+hooks.deregister();\n+\n+test(\"empty disk projects and unloadable legacy projects preserve lookup fallbacks\", async (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst context = { id: { toString: () => \"empty\" }, storage: { ...storage, get: async () => undefined } };\n+\tconst disk = new ProjectObject(context as never, { ABSO_DISK_FIRST: \"on\" } as never);\n+\tassert.deepEqual(await disk.call(\"empty\", \"status\", undefined, {}), {\n+\t\tstatus: 404,\n+\t\tbody: { error: \"no such project; run init first\" },\n+\t});\n+\tassert.deepEqual(await disk.agents(\"empty\"), []);\n+\tassert.deepEqual(await disk.news(\"empty\", [{ from: \"alice\", issue: null, text: \"Hello\" }]), [{ to: [] }]);\n+\tawait disk.alarm();\n+\tt.mock.method(EngineProject, \"open\", () => {\n+\t\tthrow Error(\"unloadable legacy log\");\n+\t});\n+\tconst legacy = new ProjectObject(context as never, {} as never);\n+\tassert.deepEqual(await legacy.agents(\"empty\"), []);\n+\tassert.deepEqual(await legacy.news(\"empty\", [{ from: \"alice\", issue: null, text: \"Hello\" }]), [{ to: [] }]);\n+\tawait legacy.alarm();\n+});\n+\n+test(\"ProjectObject disk-first calls survive cold objects without replay\", async (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst values = new Map<string, unknown>();\n+\tlet alarm: number | null = null;\n+\tlet onReaders: (() => Promise<void>) | undefined;\n+\tconst context = {\n+\t\tid: { toString: () => \"project-1\" },\n+\t\tstorage: {\n+\t\t\t...storage,\n+\t\t\tget: async (key: string) => {\n+\t\t\t\tif (key === \"readers\" && onReaders) {\n+\t\t\t\t\tconst action = onReaders;\n+\t\t\t\t\tonReaders = undefined;\n+\t\t\t\t\tawait action();\n+\t\t\t\t}\n+\t\t\t\treturn values.get(key);\n+\t\t\t},\n+\t\t\tput: async (key: string | Record<string, unknown>, value?: unknown) => {\n+\t\t\t\tif (typeof key === \"string\") values.set(key, value);\n+\t\t\t\telse for (const [name, v] of Object.entries(key)) values.set(name, v);\n+\t\t\t},\n+\t\t\tdelete: async (key: string) => values.delete(key),\n+\t\t\tgetAlarm: async () => alarm,\n+\t\t\tsetAlarm: async (value: number) => {\n+\t\t\t\talarm = value;\n+\t\t\t},\n+\t\t},\n+\t};\n+\tconst object = () =>\n+\t\tnew ProjectObject(\n+\t\t\tcontext as never,\n+\t\t\t{ ABSO_DISK_FIRST: \"on\", ABSO_ARTIFACTS: \"off\", KEY_HMAC_SECRET: \"invented-test-secret\" } as never,\n+\t\t);\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full history replay forbidden\");\n+\t});\n+\tconst call = async (op: string, agent: string | undefined, body: unknown) => {\n+\t\tfor (let page = 0; page < 100; page++) {\n+\t\t\tconst result = await object().call(\"project\", op, agent, body);\n+\t\t\tif (result.status !== 503) {\n+\t\t\t\tassert.notEqual(result.status, 500, JSON.stringify({ op, result }));\n+\t\t\t\treturn result;\n+\t\t\t}\n+\t\t\tassert.notEqual(alarm, null);\n+\t\t\tawait object().alarm();\n+\t\t}\n+\t\tthrow Error(\"adoption did not finish\");\n+\t};\n+\tassert.equal((await call(\"init\", undefined, { files: { \"a.txt\": \"one\\ntwo\\n\" } })).status, 200);\n+\tassert.equal((await call(\"sync\", \"alice\", {})).status, 200);\n+\tassert.equal((await call(\"record\", \"alice\", { files: { \"a.txt\": \"changed\\n\" } })).status, 200);\n+\tconst published = await call(\"publish\", \"alice\", { message: \"Disk first\" });\n+\tassert.equal(published.status, 200);\n+\tassert.equal((published.body as { ok: boolean }).ok, true);\n+\tconst file = await call(\"file\", undefined, { path: \"a.txt\", version: \"1\" });\n+\tassert.equal(file.status, 200);\n+\tassert.match(JSON.stringify(file.body), /changed/);\n+\tconst feed = await call(\"feed\", undefined, { from: \"0\", limit: \"2\" });\n+\tassert.equal(feed.status, 200);\n+\tassert.ok((feed.body as { next: number }).next > 0);\n+\tassert.deepEqual(await object().agents(\"project\"), [\"alice\"]);\n+\tassert.equal((await object().out()).version, 1);\n+\tassert.deepEqual(await object().news(\"project\", [{ from: \"bob\", issue: null, text: \"Hello\", to: [\"alice\"] }]), [\n+\t\t{ to: [\"alice\"] },\n+\t]);\n+\tassert.equal((await call(\"status\", undefined, {})).status, 200);\n+\tfor (const agent of [\"alice\", \"bob\"]) assert.equal((await call(\"sync\", agent, {})).status, 200);\n+\tassert.equal((await call(\"record\", \"alice\", { files: { \"a.txt\": \"Alice's change\\n\" } })).status, 200);\n+\tassert.equal((await call(\"record\", \"bob\", { files: { \"a.txt\": \"Bob's change\\n\" } })).status, 200);\n+\tassert.equal((await call(\"publish\", \"alice\", { message: \"Alice wins first\" })).status, 200);\n+\tconst collision = await call(\"publish\", \"bob\", { message: \"Bob conflicts\" });\n+\tassert.equal((collision.body as { ok: boolean }).ok, false);\n+\tassert.equal((collision.body as { collisions: unknown[] }).collisions.length, 1);\n+\tconst historical = await call(\"file\", undefined, { path: \"a.txt\", version: \"1\" });\n+\tassert.equal(historical.status, 200);\n+\tassert.match(JSON.stringify(historical.body), /changed/);\n+\tconst rows = () => ({\n+\t\tlog: storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all(),\n+\t\tstate: storage.db.prepare(\"SELECT * FROM writer_state ORDER BY namespace,collection,key,part\").all(),\n+\t});\n+\tconst stable = rows();\n+\tconst disabled = new ProjectObject(context as never, { ABSO_DISK_FIRST: \"off\" } as never);\n+\tconst held = await disabled.call(\"project\", \"record\", \"alice\", { files: { \"a.txt\": \"legacy write\\n\" } });\n+\tassert.equal(held.status, 409);\n+\tassert.match(JSON.stringify(held.body), /enable ABSO_DISK_FIRST/);\n+\tassert.equal(await disabled.gitSync(), null);\n+\tassert.deepEqual(rows(), stable);\n+\tassert.equal((await call(\"status\", undefined, {})).status, 200, \"re-enabling disk mode preserves the valid root\");\n+\tconst originalAnnounce = EngineProject.prototype.announce;\n+\tconst failingAnnounce = t.mock.method(\n+\t\tEngineProject.prototype,\n+\t\t\"announce\",\n+\t\tfunction (this: EngineProject, ...args: Parameters<EngineProject[\"announce\"]>) {\n+\t\t\toriginalAnnounce.apply(this, args);\n+\t\t\tthrow Error(\"injected after announce\");\n+\t\t},\n+\t);\n+\tawait assert.rejects(\n+\t\t() => object().news(\"project\", [{ from: \"bob\", issue: null, text: \"Must roll back\", to: [\"alice\"] }]),\n+\t\t/injected after announce/,\n+\t);\n+\tassert.deepEqual(rows(), stable);\n+\tfailingAnnounce.mock.restore();\n+\tconst current = object();\n+\tonReaders = async () => {\n+\t\tawait current.revokeAgentKey(\"missing-test-key\", \"127.0.0.1\");\n+\t};\n+\tconst revoked = await current.call(\"project\", \"record\", \"alice\", { files: { \"a.txt\": \"unauthorized\\n\" } });\n+\tassert.equal(revoked.status, 409);\n+\tassert.equal((revoked.body as { retryable: boolean }).retryable, true);\n+\tassert.deepEqual(rows(), stable);\n+\tconst original = EngineProject.prototype.record;\n+\tt.mock.method(\n+\t\tEngineProject.prototype,\n+\t\t\"record\",\n+\t\tfunction (this: EngineProject, ...args: Parameters<EngineProject[\"record\"]>) {\n+\t\t\toriginal.apply(this, args);\n+\t\t\tthrow Error(\"injected after record\");\n+\t\t},\n+\t);\n+\tawait assert.rejects(\n+\t\t() => object().call(\"project\", \"record\", \"alice\", { files: { \"a.txt\": \"failed\\n\" } }),\n+\t\t/injected after record/,\n+\t);\n+\tassert.deepEqual(rows(), stable);\n+});"},{"path":"src/engine/experimental/projection-locator.ts","added":18,"removed":0,"diff":"--- a/src/engine/experimental/projection-locator.ts\n+++ b/src/engine/experimental/projection-locator.ts\n@@ -120,6 +120,24 @@\n \t\t}\n \t\treturn undefined;\n \t}\n+\t/** Stream immutable leaves in numeric key order, retaining at most eight branch levels. */\n+\t*entries(root: Page): IterableIterator<readonly [number, T]> {\n+\t\tpage(root);\n+\t\tconst index = this;\n+\t\tfunction* visit(current: Page, parent?: string, digit?: string, depth = 0): IterableIterator<readonly [number, T]> {\n+\t\t\tif (depth > 8) throw Error(\"invalid locator depth\");\n+\t\t\tif (current === null) return;\n+\t\t\tconst node = index.#read(current, parent, digit);\n+\t\t\tif (node.kind === \"leaf\") {\n+\t\t\t\tyield [Number.parseInt(node.prefix, 16), index.#decode(structuredClone(node.value))];\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\tfor (const digit of Object.keys(node.children).sort())\n+\t\t\t\tyield* visit(node.children[digit]!, node.prefix, digit, depth + 1);\n+\t\t}\n+\t\tyield* visit(root);\n+\t}\n+\n \tset(root: Page, id: number, value: T): number {\n \t\tpage(root);\n \t\tconst key = keyOf(id),"},{"path":"src/engine/experimental/projection-reader.ts","added":17,"removed":4,"diff":"--- a/src/engine/experimental/projection-reader.ts\n+++ b/src/engine/experimental/projection-reader.ts\n@@ -23,18 +23,31 @@\n \tget set(): ReadonlySet<string> {\n \t\tthis.#assertLive();\n \t\tconst has = (id: string) =>\n-\t\t\tthis.graph.has(id) &&\n-\t\t\t(this.#adapter.members.get(this.#state.membership, this.graph.atom(id).seq)?.present ?? false);\n+\t\t\tthis.graph.has(id) && (this.#adapter.members.get(this.#state.membership, Number(id.slice(1)))?.present ?? false);\n \t\tconst assertLive = this.#assertLive;\n+\t\tconst members = this.#adapter.members;\n+\t\tconst root = this.#state.membership;\n+\t\tconst graph = this.graph;\n \t\treturn new (class extends StableSet<string> {\n \t\t\treadonly retainedBytes = 64;\n \t\t\thas(id: string): boolean {\n \t\t\t\tassertLive();\n \t\t\t\treturn has(id);\n \t\t\t}\n-\t\t\tvalues(): SetIterator<string> {\n+\t\t\t*values(): SetIterator<string> {\n \t\t\t\tassertLive();\n-\t\t\t\tthrow Error(\"unsupported projected membership enumeration\");\n+\t\t\t\tconst iterator = members.entries(root);\n+\t\t\t\ttry {\n+\t\t\t\t\tfor (;;) {\n+\t\t\t\t\t\tassertLive();\n+\t\t\t\t\t\tconst item = iterator.next();\n+\t\t\t\t\t\tif (item.done) return;\n+\t\t\t\t\t\tconst [seq, member] = item.value;\n+\t\t\t\t\t\tif (member.present) yield graph.idOfSeq(seq);\n+\t\t\t\t\t}\n+\t\t\t\t} finally {\n+\t\t\t\t\titerator.return?.();\n+\t\t\t\t}\n \t\t\t}\n \t\t})();\n \t}"},{"path":"src/engine/test/projection-membership-iterator.test.ts","added":71,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-membership-iterator.test.ts\n@@ -0,0 +1,71 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { ProjectionLocator } from \"../experimental/projection-locator.ts\";\n+import { ExperimentalMarkerProjection } from \"../experimental/projection-marker.ts\";\n+import { ProjectionReader } from \"../experimental/projection-reader.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { Repo } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"locator streams ordered immutable leaves with bounded first-result reads\", () => {\n+\tconst db = new SqlState();\n+\ttry {\n+\t\tconst index = new ProjectionLocator(db, \"iterate\", (v) => {\n+\t\t\tif (typeof v !== \"number\") throw Error(\"invalid value\");\n+\t\t\treturn v;\n+\t\t});\n+\t\tlet root: number | null = null;\n+\t\tfor (let id = 511; id >= 0; id--) root = index.set(root, id, id);\n+\t\tconst previous = root;\n+\t\troot = index.set(root, 256, -1);\n+\t\tconst before = db.reads;\n+\t\tconst iterator = index.entries(root);\n+\t\tassert.deepEqual(iterator.next().value, [0, 0]);\n+\t\tassert.ok(db.reads - before <= 9);\n+\t\titerator.return?.();\n+\t\tassert.deepEqual(\n+\t\t\t[...index.entries(previous)],\n+\t\t\tArray.from({ length: 512 }, (_, id) => [id, id]),\n+\t\t);\n+\t\tassert.equal([...index.entries(root)][256]?.[1], -1);\n+\t\tdb.write('experimental-locator:\"iterate\"', String(root), {\n+\t\t\tformat: 1,\n+\t\t\tkind: \"branch\",\n+\t\t\tprefix: \"\",\n+\t\t\tchildren: { 0: root, 1: root },\n+\t\t});\n+\t\tassert.throws(() => index.entries(root).next(), /invalid locator child/);\n+\t} finally {\n+\t\tdb.db.close();\n+\t}\n+});\n+\n+test(\"projected membership streams without atom payload reads and expires with its scope\", () => {\n+\tconst db = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"a.txt\": \"one\\n\" });\n+\t\tconst atoms = [repo.graph.atom(\"a0\"), repo.edit({ edits: [{ file: \"a.txt\", old: \"one\\n\", new: \"two\\n\" }] })];\n+\t\tconst graph = new Graph({ storage: db });\n+\t\tfor (const atom of atoms) graph.add(atom);\n+\t\tconst adapter = new ExperimentalMarkerProjection(db, graph, \"a.txt\", \"membership\");\n+\t\tlet state = adapter.empty();\n+\t\tfor (const atom of atoms) state = adapter.apply(state, atom);\n+\t\tlet live = true;\n+\t\tconst reader = new ProjectionReader(adapter, state, () => {\n+\t\t\tif (!live) throw Error(\"expired\");\n+\t\t});\n+\t\tconst read = db.read.bind(db);\n+\t\tdb.read = (collection, key) => {\n+\t\t\tif (collection === \"atoms\") throw Error(\"atom payload read forbidden\");\n+\t\t\treturn read(collection, key);\n+\t\t};\n+\t\tassert.deepEqual([...reader.set], [\"a0\", \"a1\"]);\n+\t\tassert.equal(reader.set.has(\"a1\"), true);\n+\t\tconst iterator = reader.set.values();\n+\t\tassert.equal(iterator.next().value, \"a0\");\n+\t\tlive = false;\n+\t\tassert.throws(() => iterator.next(), /expired/);\n+\t} finally {\n+\t\tdb.db.close();\n+\t}\n+});"},{"path":"worker/project/changes-since.ts","added":4,"removed":5,"diff":"--- a/worker/project/changes-since.ts\n+++ b/worker/project/changes-since.ts\n@@ -26,11 +26,10 @@\n \t\t[before.set, after.set],\n \t\t[after.set, before.set],\n \t] as const) {\n-\t\tfor (const file of host.touchedFiles(\n-\t\t\t[...a].filter((id) => !b.has(id)),\n-\t\t\t[before, after],\n-\t\t))\n-\t\t\ttouched.add(file);\n+\t\tconst changed = function* () {\n+\t\t\tfor (const id of a) if (!b.has(id)) yield id;\n+\t\t};\n+\t\tfor (const file of host.touchedFiles(changed(), [before, after])) touched.add(file);\n \t}\n \tconst files: Files = {};\n \tconst modes: Modes = {};"}],"ci":null}