{"draft":null,"from":35,"to":318,"files":[{"path":"server/src/project-object.ts","added":839,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/project-object.ts\n@@ -0,0 +1,839 @@\n+// One project: its append-only log and blobs in the Durable Object's SQLite, the engine loaded from them, and the push\n+// out to the project's Artifacts repo after each new version of shared. Ported from the platform's ProjectObject\n+// (worker/src/index.ts), trimmed to the core path: no CI, merge queue checker, boxes, pipelines, members, visibility,\n+// R2 copies, edge cache, probes or disk-first writer.\n+\n+import { DurableObject } from \"cloudflare:workers\";\n+import { createHash } from \"node:crypto\";\n+import { type Answer, answer, type Readers, readerAnswer } from \"../../worker/project/http.ts\";\n+import type { ProjectCalls, ProjectHistory } from \"../../worker/project/project-api.ts\";\n+import { ProjectError } from \"../../worker/project/project-error.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 { GitDiskIntake } from \"./git-disk-intake.ts\";\n+import { GitFileContents } from \"./git-file-contents.ts\";\n+import { GitIntakeLimitError } from \"./git-intake-limit.ts\";\n+import { GitIntakeTrees } from \"./git-intake-trees.ts\";\n+import { pushedSince, remoteHead } from \"./ingest.ts\";\n+import {\n+\tcheckKey,\n+\temptyKeyState,\n+\texpiresAt,\n+\thmac,\n+\tissueKey,\n+\ttype KeyRole,\n+\ttype KeyState,\n+\tkeyAllows,\n+\tlistKeys,\n+\trevokeKey,\n+} from \"./keys.ts\";\n+import { type PushResult, pushShared, repoName } from \"./push.ts\";\n+import { pushSnapshot } from \"./push-snapshot.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\"without\",\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+const GIT_CHECK_MS = 15_000;\n+// Disk scratch admission limits, independent of the Worker's resident memory.\n+const GIT_PACK_MAX_BYTES = 128 * 1024 * 1024;\n+const GIT_OBJECT_MAX_BYTES = 64 * 1024 * 1024;\n+const GIT_DECODED_MAX_BYTES = 256 * 1024 * 1024;\n+const GIT_LIMIT_POLICY = `expanded-v2:${GIT_PACK_MAX_BYTES}:${GIT_OBJECT_MAX_BYTES}:${GIT_DECODED_MAX_BYTES}`;\n+\n+/**\n+ * The load guard (platform issue 46): an estimate of a loaded project's memory from its log entries, lines and claim\n+ * keys, all read from SQLite without loading. A Durable Object has 128 MB. Past the hard cap a project refuses to\n+ * load (export still reads it); past the soft cap, new work is held so the hard cap is never reached.\n+ */\n+const LOAD_BYTES_PER_ENTRY = 1_200;\n+const LOAD_BYTES_PER_LINE = 20;\n+const LOAD_BYTES_PER_KEY = 20;\n+const LOAD_BASE_BYTES = 10_000_000;\n+const LOAD_MAX_BYTES = 114_000_000;\n+const LOAD_SOFT_BYTES = 94_800_000;\n+/** Before its lines are counted, a log over this many characters refuses to load. */\n+const LOG_LOAD_MAX_CHARS = 12_000_000;\n+/** The ops the soft cap holds: the ones that bring new work into the history. */\n+const SOFT_HELD_OPS: ReadonlySet<string> = new Set([\"record\", \"edit\", \"publish\", \"land\", \"amend\", \"pluck\", \"drop\"]);\n+\n+export function loadEstimate(entries: number, lines: number, keys: number): number {\n+\treturn entries * LOAD_BYTES_PER_ENTRY + lines * LOAD_BYTES_PER_LINE + keys * LOAD_BYTES_PER_KEY + LOAD_BASE_BYTES;\n+}\n+\n+/** A presented agent key, checked inside the call so the check and the call are one trip. */\n+export interface KeyForCall {\n+\tpresented: string;\n+\taddress: string;\n+\twrite: boolean;\n+\troute: string | undefined;\n+}\n+\n+/** A news item from the issues code: delivered as an announcement from its writer. */\n+export interface IssueNews {\n+\tfrom: string;\n+\tissue: number | null;\n+\ttext: string;\n+\tto?: string[];\n+}\n+\n+/** What the issues Durable Object hears when a start note naming an issue begins and ends. Each is optional. */\n+interface IssueHooks {\n+\tclaim?(agent: string, issue: number, change: number): Promise<unknown>;\n+\tunclaim?(agent: string, issue: number): Promise<unknown>;\n+\tdone?(agent: string, issue: number, version: number): Promise<unknown>;\n+}\n+\n+export class ProjectObject extends DurableObject<Env> {\n+\tprivate blobs: BlobStore;\n+\tprivate loaded: ProjectCalls | undefined;\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+\tprivate gitCheckedAt = 0;\n+\tprivate gitSyncing: Promise<{ head: string; commits: number; answer: unknown } | null> | undefined;\n+\n+\tconstructor(ctx: DurableObjectState, env: Env) {\n+\t\tsuper(ctx, env);\n+\t\tthis.blobs = new BlobStore(ctx.storage);\n+\t\tif (env.ABSO_DISK_FIRST === \"on\") {\n+\t\t\tGitDiskIntake.recover(ctx.storage);\n+\t\t\tGitFileContents.recover(ctx.storage);\n+\t\t\tGitIntakeTrees.recover(ctx.storage);\n+\t\t}\n+\t}\n+\n+\t/** Where files kept whole go: the project's blob store. */\n+\tprivate wholeFiles() {\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\trequest?: { id: string; principal: string },\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 legacyReaders = (await this.ctx.storage.get<string[]>(\"readers\")) ?? [];\n+\t\tconst storedReaders = progress?.ready\n+\t\t\t? (new SqliteWriterState(this.ctx.storage, \"server-disk-v1\").read(\"runtime\", \"readers\") as string[] | undefined)\n+\t\t\t: undefined;\n+\t\tconst known = new Set(storedReaders ?? legacyReaders);\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\tif (agent && op !== \"reader\") {\n+\t\t\tconst refused = readerAnswer({ status: () => undefined }, op, agent, body, readers);\n+\t\t\tif (refused) return refused;\n+\t\t}\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\tif (readersChanged)\n+\t\t\t\tnew SqliteWriterState(this.ctx.storage, \"server-disk-v1\").write(\"runtime\", \"readers\", readers.list());\n+\t\t\treturn result;\n+\t\t};\n+\n+\t\tconst receipt = request\n+\t\t\t? {\n+\t\t\t\t\tid: `http:${createHash(\"sha256\").update(request.principal).digest(\"hex\")}:${request.id}`,\n+\t\t\t\t\tidentity: {\n+\t\t\t\t\t\tproject: name,\n+\t\t\t\t\t\tprincipal: request.principal,\n+\t\t\t\t\t\tagent: agent ?? null,\n+\t\t\t\t\t\toperation: op,\n+\t\t\t\t\t\tbody: body ?? null,\n+\t\t\t\t\t\thow: how ?? null,\n+\t\t\t\t\t},\n+\t\t\t\t}\n+\t\t\t: undefined;\n+\t\tconst result =\n+\t\t\tprogress.phase === \"empty\"\n+\t\t\t\t? runtime.initialize(action, validate, receipt)\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, receipt);\n+\n+\t\tif (readersChanged) {\n+\t\t\tthis.authorityRevision++;\n+\t\t}\n+\t\tconst log = new SqliteLog(this.ctx.storage);\n+\t\tif (log.seq() !== before || (request && !READ_OPS.has(op))) {\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+\t\t\tconst why = this.tooBigToLoad();\n+\t\t\tif (why) throw new Error(`${why}, too big to load in a Durable Object's memory; GET export still reads it`);\n+\t\t\tthis.loaded = EngineProject.open(this.ctx.storage, (sha) => this.blobs.has(sha), this.wholeFiles());\n+\t\t} catch (e) {\n+\t\t\tthis.loadError = e;\n+\t\t}\n+\t\treturn this.loaded;\n+\t}\n+\n+\tprivate get project(): ProjectCalls {\n+\t\tconst p = this.ensure();\n+\t\tif (!p) throw this.loadError;\n+\t\treturn p;\n+\t}\n+\n+\tprivate logChars(): { chars: number; entries: number } {\n+\t\tconst tables = this.ctx.storage.sql\n+\t\t\t.exec(\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'log'\")\n+\t\t\t.toArray();\n+\t\treturn tables.length === 0 ? { chars: 0, entries: 0 } : new SqliteLog(this.ctx.storage).logSize();\n+\t}\n+\n+\tprivate sizes(): { lines: number; keys: number } | undefined {\n+\t\tif (this.logChars().entries === 0) return undefined;\n+\t\ttry {\n+\t\t\treturn new SqliteLog(this.ctx.storage).countSizes();\n+\t\t} catch {\n+\t\t\treturn undefined;\n+\t\t}\n+\t}\n+\n+\t/** Why recording new work is held: the estimate is past the soft cap; else null. */\n+\tprivate softHeld(): string | null {\n+\t\tconst counted = this.sizes();\n+\t\tif (counted === undefined) return null;\n+\t\tconst bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys);\n+\t\treturn bytes > LOAD_SOFT_BYTES\n+\t\t\t? `this project is near the most a project can hold (an estimated ${(bytes / 1e6).toFixed(0)} MB of ${LOAD_MAX_BYTES / 1e6} MB), so recording and publishing are held; status and reads keep working`\n+\t\t\t: null;\n+\t}\n+\n+\t/** Why this project mustn't load: its estimated memory, or before its lines are counted, its log's size; else null. */\n+\tprivate tooBigToLoad(): string | null {\n+\t\tconst counted = this.sizes();\n+\t\tif (counted !== undefined) {\n+\t\t\tconst bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys);\n+\t\t\treturn bytes > LOAD_MAX_BYTES\n+\t\t\t\t? `this project holds ${counted.lines} lines and ${this.logChars().entries} entries, an estimated ${(bytes / 1e6).toFixed(0)} MB once loaded`\n+\t\t\t\t: null;\n+\t\t}\n+\t\tconst { chars } = this.logChars();\n+\t\treturn chars > LOG_LOAD_MAX_CHARS ? `this project's log is ${(chars / 1e6).toFixed(1)} MB` : null;\n+\t}\n+\n+\t// Blobs: binary files' bytes, named by their SHA-256.\n+\n+\tasync putBlob(sha: string, body: ReadableStream<Uint8Array>): Promise<Answer> {\n+\t\tconst a = await this.blobs.put(sha, body);\n+\t\t// A push out waiting on missing blobs goes again now.\n+\t\tif (a.status === 200 && (await this.ctx.storage.get(\"pushError\"))) await this.ctx.storage.setAlarm(Date.now());\n+\t\treturn a;\n+\t}\n+\n+\tasync getBlob(sha: string): Promise<ReadableStream<Uint8Array> | null> {\n+\t\treturn this.blobs.stream(sha);\n+\t}\n+\n+\t/** Shared's newest version, from storage alone, never loading the project. Null when there's no project. */\n+\tasync head(): Promise<{ version: number; at: string } | null> {\n+\t\tif (this.logChars().entries === 0) return null;\n+\t\treturn { version: new SqliteLog(this.ctx.storage).sharedVersion(), at: new Date().toISOString() };\n+\t}\n+\n+\t/** Backups: one page of the log as JSON lines. It works even when the log won't load. */\n+\tasync exportLog(from: number, limit: number): Promise<{ lines: string; next: number | null } | null> {\n+\t\tif (this.logChars().entries === 0) return null;\n+\t\tconst { texts, next } = new SqliteLog(this.ctx.storage).page(from, limit);\n+\t\treturn { lines: texts.map((t) => `${t}\\n`).join(\"\"), next };\n+\t}\n+\n+\tprivate wake(): void {\n+\t\tconst all = this.waiting;\n+\t\tthis.waiting = [];\n+\t\tfor (const w of all) w();\n+\t}\n+\n+\t/**\n+\t * GET feed?from=&wait=<seconds, up to 25>: when nothing is new, hold the call until an entry is written or the wait\n+\t * ends, then answer as usual.\n+\t */\n+\tprivate async feed(name: string, body: unknown): Promise<Answer> {\n+\t\tconst q = (body ?? {}) as Record<string, string | undefined>;\n+\t\tconst wait = Math.min(25, Math.max(0, Number(q.wait) || 0));\n+\t\tconst first = await this.call(name, \"feed\", undefined, body, true);\n+\t\tconst from = Number(q.from) || 0;\n+\t\tconst empty = first.status === 200 && (first.body as { next: number }).next <= from;\n+\t\tif (!empty || wait === 0) return first;\n+\t\tawait new Promise<void>((resolve) => {\n+\t\t\tconst timer = setTimeout(resolve, wait * 1000);\n+\t\t\tthis.waiting.push(() => {\n+\t\t\t\tclearTimeout(timer);\n+\t\t\t\tresolve();\n+\t\t\t});\n+\t\t});\n+\t\treturn this.call(name, \"feed\", undefined, body, true);\n+\t}\n+\n+\t/** One project call: the agent key (if any), the size caps, then answer() from worker/project/http.ts. */\n+\tasync call(\n+\t\tname: string,\n+\t\top: string,\n+\t\tagent: string | undefined,\n+\t\tbody: unknown,\n+\t\tinFeed = false,\n+\t\thow?: string,\n+\t\tkey?: KeyForCall,\n+\t\trequestId?: string,\n+\t): Promise<Answer> {\n+\t\tconst revision = this.authorityRevision;\n+\t\tlet principal = \"shared-token\";\n+\t\tif (\n+\t\t\trequestId !== undefined &&\n+\t\t\t!/^[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)\n+\t\t)\n+\t\t\treturn { status: 400, body: { error: \"Idempotency-Key must be a UUID\" } };\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+\t\t\tconst allowed = keyAllows(decided.role, { write: key.write, agent, route: key.route });\n+\t\t\tif (!allowed.ok) return { status: allowed.status, body: { error: allowed.error } };\n+\t\t\thow = decided.as;\n+\t\t\tprincipal = `key:${decided.id}`;\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(\n+\t\t\t\t\tname,\n+\t\t\t\t\top,\n+\t\t\t\t\tagent,\n+\t\t\t\t\tbody,\n+\t\t\t\t\thow,\n+\t\t\t\t\trevision,\n+\t\t\t\t\trequestId ? { id: requestId, principal } : undefined,\n+\t\t\t\t);\n+\t\t\t} catch (error) {\n+\t\t\t\tif ((error as { code?: string })?.code === \"request-reused\")\n+\t\t\t\t\treturn { status: 409, body: { error: \"Idempotency-Key was reused for a different request\" } };\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+\t\t}\n+\t\tconst loaded = this.ensure();\n+\t\tif (!loaded) {\n+\t\t\tconst why = this.loadError instanceof Error ? this.loadError.message : String(this.loadError);\n+\t\t\treturn { status: 507, body: { error: `the project's log did not load: ${why}` } };\n+\t\t}\n+\t\t// Readers live in storage, not the log: a refused call writes nothing, so replay never needs them.\n+\t\tconst list = new Set((await this.ctx.storage.get<string[]>(\"readers\")) ?? []);\n+\t\tlet changed = false;\n+\t\tconst readers: Readers = {\n+\t\t\thas: (a) => list.has(a),\n+\t\t\tset: (a, on) => {\n+\t\t\t\tif (on === list.has(a)) return;\n+\t\t\t\tif (on) list.add(a);\n+\t\t\t\telse list.delete(a);\n+\t\t\t\tchanged = true;\n+\t\t\t},\n+\t\t\tlist: () => [...list].sort(),\n+\t\t};\n+\t\tconst before = loaded.exists() ? loaded.shared().version : -1;\n+\t\tconst logLength = () => (this.loaded as { logLength?: () => number } | undefined)?.logLength?.() ?? 0;\n+\t\tconst entriesBefore = logLength();\n+\t\tconst a = answer(loaded, op, agent, body, readers, how);\n+\t\tif (changed) await this.ctx.storage.put(\"readers\", readers.list());\n+\t\tif (logLength() !== entriesBefore) this.wake();\n+\t\tif (a.status === 200 && op === \"starting\") a.body = await this.startingHooks(name, a.body);\n+\t\tif (a.status === 200) a.body = this.withBlobSizes(op, a.body);\n+\t\tconst after = loaded.exists() ? loaded.shared().version : -1;\n+\t\tif (a.status === 200 && after >= 0 && (op === \"init\" || after > before)) {\n+\t\t\t// A new version of shared: push it out to Artifacts in the background. The alarm retries; the call never waits.\n+\t\t\tawait this.ctx.storage.put(\"name\", name);\n+\t\t\tif (artifactsOf(this.env)) await this.ctx.storage.setAlarm(Date.now());\n+\t\t} else if (\n+\t\t\ta.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\t// While agents are working, the alarm also looks for plain-git pushes.\n+\t\t\tawait this.ctx.storage.setAlarm(Date.now());\n+\t\t}\n+\t\treturn a;\n+\t}\n+\n+\t/**\n+\t * The engine's starting answer carries hooks for the issues code (a start note naming an issue began or ended). They\n+\t * go to the project's IssueProject, and never to the client. A failed hook is logged and never fails the call.\n+\t */\n+\tprivate async startingHooks(name: string, body: unknown): Promise<unknown> {\n+\t\tconst { hooks, ...rest } = body as {\n+\t\t\thooks?: {\n+\t\t\t\tclaim?: { issue: number; agent: string; change: number };\n+\t\t\t\tunclaim?: { issue: number; agent: string; change: number; done?: boolean; version?: number };\n+\t\t\t};\n+\t\t};\n+\t\tif (!hooks) return body;\n+\t\tconst issues = this.env.ISSUES_DO.get(this.env.ISSUES_DO.idFromName(name)) as unknown as IssueHooks;\n+\t\tconst tell = async (what: string, call: () => Promise<unknown> | undefined) => {\n+\t\t\ttry {\n+\t\t\t\tawait call();\n+\t\t\t} catch (e) {\n+\t\t\t\tconsole.log(JSON.stringify({ event: \"issues-hook\", what, project: name, error: String(e).slice(0, 200) }));\n+\t\t\t}\n+\t\t};\n+\t\tconst end = hooks.unclaim;\n+\t\tif (end?.done && end.version !== undefined) {\n+\t\t\tconst version = end.version;\n+\t\t\tawait tell(\"done\", () => issues.done?.(end.agent, end.issue, version));\n+\t\t} else if (end) await tell(\"unclaim\", () => issues.unclaim?.(end.agent, end.issue));\n+\t\tconst claim = hooks.claim;\n+\t\tif (claim) await tell(\"claim\", () => issues.claim?.(claim.agent, claim.issue, claim.change));\n+\t\treturn rest;\n+\t}\n+\n+\t/** A folder's binary files count by their bytes, and a binary file says its size: the blob store knows both. */\n+\tprivate withBlobSizes(op: string, body: unknown): unknown {\n+\t\tif (op === \"tree\" && Array.isArray((body as { entries?: unknown }).entries)) {\n+\t\t\tconst b = body as { entries: { bytes?: number; blobs?: string[] }[] };\n+\t\t\treturn {\n+\t\t\t\t...b,\n+\t\t\t\tentries: b.entries.map(({ blobs, ...e }) =>\n+\t\t\t\t\tblobs ? { ...e, bytes: (e.bytes ?? 0) + blobs.reduce((n, sha) => n + this.blobs.size(sha), 0) } : e,\n+\t\t\t\t),\n+\t\t\t};\n+\t\t}\n+\t\tif (op === \"file\" && typeof (body as { blob?: unknown }).blob === \"string\")\n+\t\t\treturn { ...(body as object), size: this.blobs.size((body as { blob: string }).blob) };\n+\t\treturn body;\n+\t}\n+\n+\t// The push out to Artifacts, and plain-git pushes back in.\n+\n+\t/**\n+\t * Takes in commits pushed to the project's repo with plain git: the ones above the server's last commit that\n+\t * haven't been taken in yet. One run at a time; a call while a run is going gets that run's answer.\n+\t */\n+\tgitSync(): Promise<{ head: string; commits: number; answer: unknown } | null> {\n+\t\tthis.gitSyncing ??= this.gitSyncOnce().finally(() => {\n+\t\t\tthis.gitSyncing = undefined;\n+\t\t});\n+\t\treturn this.gitSyncing;\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) 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\tconst refusal = this.diskRuntime()\n+\t\t\t? await this.ctx.storage.get<{ head: string; policy: string; kind: GitIntakeLimitError[\"kind\"]; error: string }>(\n+\t\t\t\t\t\"git:size-refusal\",\n+\t\t\t\t)\n+\t\t\t: undefined;\n+\t\tif (refusal) {\n+\t\t\tif (\n+\t\t\t\thead &&\n+\t\t\t\thead !== seen &&\n+\t\t\t\thead !== pushed?.commit &&\n+\t\t\t\trefusal.head === head &&\n+\t\t\t\trefusal.policy === GIT_LIMIT_POLICY\n+\t\t\t)\n+\t\t\t\tthrow new GitIntakeLimitError(refusal.kind, refusal.error);\n+\t\t\tawait this.ctx.storage.delete(\"git:size-refusal\");\n+\t\t}\n+\t\tif (!head || head === seen || head === pushed?.commit) return null;\n+\t\tconst sharedBlobs = this.useProject((p) => p.shared().blobs ?? {});\n+\t\tusing trees = this.diskRuntime() ? new GitIntakeTrees(this.ctx.storage) : undefined;\n+\t\tconst found = await pushedSince(\n+\t\t\tartifacts,\n+\t\t\tname,\n+\t\t\tseen,\n+\t\t\tasync (bytes) => (bytes.byteLength > BLOB_MAX ? null : this.blobs.putBytes(bytes)),\n+\t\t\t(path) => sharedBlobs[path],\n+\t\t\ttrees ? (files, path, body, oid) => trees.retainFile(files, path, body, oid) : undefined,\n+\t\t\ttrees\n+\t\t\t\t? {\n+\t\t\t\t\t\tstorage: this.ctx.storage,\n+\t\t\t\t\t\tmaxPackBytes: GIT_PACK_MAX_BYTES,\n+\t\t\t\t\t\tmaxObjectBytes: GIT_OBJECT_MAX_BYTES,\n+\t\t\t\t\t\tmaxDecodedBytes: GIT_DECODED_MAX_BYTES,\n+\t\t\t\t\t\tmaxBinaryBytes: BLOB_MAX,\n+\t\t\t\t\t\tretainFileChunks: (files, path, chunks, oid) => trees.retainChunks(files, path, chunks, oid),\n+\t\t\t\t\t}\n+\t\t\t\t: undefined,\n+\t\t).catch(async (error: unknown) => {\n+\t\t\tif (trees && error instanceof GitIntakeLimitError) {\n+\t\t\t\tconst refusal = {\n+\t\t\t\t\thead,\n+\t\t\t\t\tpolicy: GIT_LIMIT_POLICY,\n+\t\t\t\t\tkind: error.kind,\n+\t\t\t\t\terror: error.message,\n+\t\t\t\t\tat: new Date().toISOString(),\n+\t\t\t\t};\n+\t\t\t\tawait this.ctx.storage.put({ \"git:size-refusal\": refusal, \"git:error\": refusal });\n+\t\t\t}\n+\t\t\tthrow error;\n+\t\t});\n+\t\tif (!found || found.commits.length === 0) {\n+\t\t\tif (found) await this.ctx.storage.put(\"git:head\", found.head);\n+\t\t\treturn null;\n+\t\t}\n+\t\t// Unexpected failures leave the cursor unacknowledged for retry. Engine\n+\t\t// refusals are recorded and acknowledged so a later fixing commit can advance.\n+\t\tconst ingest = (p: EngineProject) =>\n+\t\t\tp.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now());\n+\t\tconst runtime = this.diskRuntime();\n+\t\tlet result: unknown;\n+\t\ttry {\n+\t\t\tresult = runtime\n+\t\t\t\t? runtime.write(ingest, () => {}, {\n+\t\t\t\t\t\tid: `git:${found.head}`,\n+\t\t\t\t\t\tidentity: {\n+\t\t\t\t\t\t\tproject: name,\n+\t\t\t\t\t\t\thead: found.head,\n+\t\t\t\t\t\t\tbase: found.base,\n+\t\t\t\t\t\t\tcommits: found.commits.map((commit) => commit.sha),\n+\t\t\t\t\t\t},\n+\t\t\t\t\t})\n+\t\t\t\t: this.useProject(ingest, true);\n+\t\t} catch (error) {\n+\t\t\tif (!(error instanceof ProjectError)) throw error;\n+\t\t\tresult = { error: error.message };\n+\t\t}\n+\t\tconst taken = {\n+\t\t\tat: new Date().toISOString(),\n+\t\t\thead: found.head,\n+\t\t\tcommits: found.commits.length,\n+\t\t\tanswer: result,\n+\t\t\t...(found.tooBig.length ? { tooBig: found.tooBig } : {}),\n+\t\t};\n+\t\tawait this.ctx.storage.put({ \"git:head\": found.head, \"git:last\": taken });\n+\t\tthis.wake();\n+\t\tif ((result as { landed?: boolean }).landed) await this.ctx.storage.setAlarm(Date.now());\n+\t\treturn taken;\n+\t}\n+\n+\t/** Sets the alarm for `at` unless one is due sooner. */\n+\tprivate async soon(at: number): Promise<void> {\n+\t\tconst now = await this.ctx.storage.getAlarm();\n+\t\tif (now === null || now > at) await this.ctx.storage.setAlarm(at);\n+\t}\n+\n+\t/**\n+\t * Plain-git pushes in first, so the push out builds on them; then shared out to the project's Artifacts repo, at\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.useProject((p) => p.exists())) return;\n+\t\tlet intakeFailed = false;\n+\t\tawait this.gitSync().then(\n+\t\t\tasync () => {\n+\t\t\t\tawait this.ctx.storage.delete(\"git:error\");\n+\t\t\t\tawait this.ctx.storage.delete(\"git:retry-attempts\");\n+\t\t\t},\n+\t\t\tasync (e) => {\n+\t\t\t\tintakeFailed = true;\n+\t\t\t\tconst attempts = ((await this.ctx.storage.get<number>(\"git:retry-attempts\")) ?? 0) + 1;\n+\t\t\t\tawait this.ctx.storage.put(\"git:retry-attempts\", attempts);\n+\t\t\t\tawait this.ctx.storage.put(\"git:error\", {\n+\t\t\t\t\tat: new Date().toISOString(),\n+\t\t\t\t\terror: e instanceof Error ? e.message : String(e),\n+\t\t\t\t});\n+\t\t\t\tawait this.soon(Date.now() + (attempts === 1 ? 1 : attempts === 2 ? 5 : 15) * 60_000);\n+\t\t\t},\n+\t\t);\n+\t\t// Never export over a remote head whose changes could not be taken in.\n+\t\tif (intakeFailed) return;\n+\t\tconst shared = pushSnapshot(\n+\t\t\tthis.useProject((p) => p.sharedPushMetadata()),\n+\t\t\t(version, path) => this.useProject((current) => current.fileTextAt(version, path)),\n+\t\t\t(version, paths) => this.useProject((current) => current.fileTextsAt(version, paths)),\n+\t\t);\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+\t\tif (Date.now() - pushedAt < PUSH_EVERY_MS) {\n+\t\t\tawait this.soon(pushedAt + PUSH_EVERY_MS);\n+\t\t\treturn;\n+\t\t}\n+\t\tlet result: PushResult;\n+\t\ttry {\n+\t\t\tresult = await pushShared(\n+\t\t\t\tartifacts,\n+\t\t\t\tname,\n+\t\t\t\tshared,\n+\t\t\t\t(sha) => this.blobs.read(sha),\n+\t\t\t\tthis.env.ABSO_DISK_FIRST === \"on\"\n+\t\t\t\t\t? {\n+\t\t\t\t\t\t\tstorage: this.ctx.storage,\n+\t\t\t\t\t\t\tmaxPackBytes: GIT_PACK_MAX_BYTES,\n+\t\t\t\t\t\t\tmaxObjectBytes: GIT_OBJECT_MAX_BYTES,\n+\t\t\t\t\t\t\tmaxDecodedBytes: GIT_DECODED_MAX_BYTES,\n+\t\t\t\t\t\t}\n+\t\t\t\t\t: undefined,\n+\t\t\t);\n+\t\t} catch (e) {\n+\t\t\t// Kept for /out, and tried again with a backoff of our own (a thrown alarm is retried only six times).\n+\t\t\tconst was = await this.ctx.storage.get<{ attempts?: number }>(\"pushError\");\n+\t\t\tconst attempts = (was?.attempts ?? 0) + 1;\n+\t\t\tawait this.ctx.storage.put(\"pushError\", {\n+\t\t\t\tversion: shared.version,\n+\t\t\t\tat: new Date().toISOString(),\n+\t\t\t\tattempts,\n+\t\t\t\terror: e instanceof Error ? e.message : String(e),\n+\t\t\t});\n+\t\t\tawait this.soon(Date.now() + Math.min(10 * 60_000, 15_000 * 2 ** Math.min(attempts - 1, 6)));\n+\t\t\treturn;\n+\t\t}\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.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\treturn {\n+\t\t\trepo: name ? repoName(name) : null,\n+\t\t\tartifacts: artifactsOf(this.env) ? \"bound\" : \"unbound\",\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+\t\t\t\thead: (await this.ctx.storage.get<string>(\"git:head\")) ?? null,\n+\t\t\t\tlast: (await this.ctx.storage.get(\"git:last\")) ?? null,\n+\t\t\t\terror: (await this.ctx.storage.get(\"git:error\")) ?? null,\n+\t\t\t},\n+\t\t};\n+\t}\n+\n+\t// Per-agent keys: the HMACs live here, one project's keys per object.\n+\n+\tprivate async keyState(): Promise<KeyState> {\n+\t\treturn (await this.ctx.storage.get<KeyState>(\"agent-keys\")) ?? emptyKeyState();\n+\t}\n+\n+\tasync checkAgentKey(presented: string, agent: string | undefined, address: string) {\n+\t\tconst state = await this.keyState();\n+\t\tconst decided = await checkKey(state, this.env.KEY_HMAC_SECRET, presented, agent, Date.now(), address);\n+\t\tif (decided.dirty) await this.ctx.storage.put(\"agent-keys\", state);\n+\t\tif (!decided.ok) return decided;\n+\t\tconst row = state.rows.find((r) => r.id === decided.id);\n+\t\treturn { ...decided, agent: row?.agent ?? \"\" };\n+\t}\n+\n+\t/** Issues a key. The returned key is the only copy. */\n+\tasync issueAgentKey(\n+\t\tagent: string,\n+\t\taddress: string,\n+\t\texpiresRaw: string | null,\n+\t\trole: KeyRole,\n+\t): Promise<{ id: string; key: string; agent: string } | { error: string }> {\n+\t\tconst secret = this.env.KEY_HMAC_SECRET;\n+\t\tif (!secret) return { error: \"the key secret (KEY_HMAC_SECRET) is not set\" };\n+\t\tconst when = expiresAt(Date.now(), expiresRaw);\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+\n+\tasync revokeAgentKey(id: string, address: string): Promise<{ revoked: boolean }> {\n+\t\tconst secret = this.env.KEY_HMAC_SECRET;\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+\n+\tasync listAgentKeys(agent?: string) {\n+\t\treturn listKeys(await this.keyState(), agent);\n+\t}\n+\n+\t// For the issues code (server/src/issues/).\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\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+\t * Issues news, delivered through the engine's announce path: each item goes to the agents whose start note names\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\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\tthis.wake();\n+\t\t\treturn out;\n+\t\t}, true);\n+\t}\n+}"}],"unmatched":[]}