{"version":150,"agent":"speed","message":"Open server: the project Worker, Durable Object and Artifacts (issue 17)","time":1791907522179,"timeIso":"2026-10-13T16:05:22.179Z","changes":33,"change":1800,"files":[".absoignore","biome.json","package-lock.json","package.json","server/package-lock.json","server/package.json","server/src/blobs.ts","server/src/engine-project.ts","server/src/env.ts","server/src/index.ts","server/src/ingest.ts","server/src/issues-entry.ts","server/src/keys.ts","server/src/memory-fs.ts","server/src/project-object.ts","server/src/push.ts","server/src/router.ts","server/test/blobs.test.ts","server/test/e2e-transcript.md","server/test/engine-project.test.ts","server/test/helpers.ts","server/test/push.test.ts","server/test/router.test.ts","server/tsconfig.json","server/wrangler.jsonc"],"draft":null,"diff":[{"path":".absoignore","added":3,"removed":1,"diff":"--- a/.absoignore\n+++ b/.absoignore\n@@ -6,7 +6,9 @@\n # Each session's own Claude Code state\n .claude/\n \n-# Local config and secrets\n+# Local config and secrets (the open server's server/.dev.vars and server/.wrangler/ are named too)\n+server/.dev.vars\n+server/.wrangler/\n .env\n .env.*\n .dev.vars*"},{"path":"biome.json","added":1,"removed":0,"diff":"--- a/biome.json\n+++ b/biome.json\n@@ -6,6 +6,7 @@\n \t\t\t\"src/**\",\n \t\t\t\"worker/project/**\",\n \t\t\t\"scripts/**\",\n+\t\t\t\"server/**\",\n \t\t\t\"*.json\",\n \t\t\t\"!**/node_modules\",\n \t\t\t\"!**/.abso\","},{"path":"package-lock.json","blob":{"before":"b10521cd9bad10eb98035f0fbc6a047bd7cd4c708d1db2dd836dc455e32db3ad","after":"2e1381de46c1647eeb3290e5515c5c82a67dc8770b7ba666782c32aa461f399a"},"added":0,"removed":0,"diff":"Binary file package-lock.json changed: b10521cd9bad -> 2e1381de46c1"},{"path":"package.json","added":5,"removed":3,"diff":"--- a/package.json\n+++ b/package.json\n@@ -9,15 +9,17 @@\n \t\t\"node\": \">=24\"\n \t},\n \t\"scripts\": {\n-\t\t\"test\": \"node --import ./client/test/setup.ts --test \\\"src/**/*.test.ts\\\" \\\"worker/project/**/*.test.ts\\\" \\\"client/test/**/*.test.ts\\\" \\\"scripts/**/*.test.ts\\\"\",\n+\t\t\"test\": \"node --import ./client/test/setup.ts --test \\\"src/**/*.test.ts\\\" \\\"worker/project/**/*.test.ts\\\" \\\"client/test/**/*.test.ts\\\" \\\"scripts/**/*.test.ts\\\" \\\"server/test/**/*.test.ts\\\"\",\n \t\t\"typecheck\": \"tsc --noEmit -p tsconfig.json\",\n-\t\t\"check\": \"npm run typecheck && npm test\",\n+\t\t\"check\": \"npm run typecheck && npm run typecheck:server && npm test\",\n \t\t\"check:changed\": \"node scripts/check-changed.mjs\",\n \t\t\"format\": \"biome check --write .\",\n-\t\t\"lint\": \"biome ci .\"\n+\t\t\"lint\": \"biome ci .\",\n+\t\t\"typecheck:server\": \"tsc --noEmit -p server/tsconfig.json\"\n \t},\n \t\"devDependencies\": {\n \t\t\"@biomejs/biome\": \"2.5.15\",\n+\t\t\"@cloudflare/workers-types\": \"^5.20261013.1\",\n \t\t\"@types/node\": \"^24.19.1\",\n \t\t\"typescript\": \"^5.9.3\"\n \t},"},{"path":"server/package-lock.json","blob":{"before":null,"after":"f5cebad6e233fae6b9d2ca0f5a1af43e25387f52e0f1760e8d1f35551bcacd81"},"added":0,"removed":0,"diff":"Binary file server/package-lock.json changed: none -> f5cebad6e233"},{"path":"server/package.json","added":22,"removed":0,"diff":"--- /dev/null\n+++ b/server/package.json\n@@ -0,0 +1,22 @@\n+{\n+\t\"name\": \"abso-server\",\n+\t\"version\": \"0.0.1\",\n+\t\"private\": true,\n+\t\"type\": \"module\",\n+\t\"description\": \"abso's open server: one Worker with a Durable Object per project, on your own Cloudflare account.\",\n+\t\"license\": \"MIT\",\n+\t\"scripts\": {\n+\t\t\"dev\": \"wrangler dev --local\",\n+\t\t\"deploy\": \"wrangler deploy\",\n+\t\t\"typecheck\": \"tsc --noEmit -p tsconfig.json\"\n+\t},\n+\t\"dependencies\": {\n+\t\t\"isomorphic-git\": \"^1.43.0\"\n+\t},\n+\t\"devDependencies\": {\n+\t\t\"@cloudflare/workers-types\": \"^5.20261001.1\",\n+\t\t\"@types/node\": \"^24.19.1\",\n+\t\t\"typescript\": \"^5.9.3\",\n+\t\t\"wrangler\": \"^4.147.0\"\n+\t}\n+}"},{"path":"server/src/blobs.ts","added":237,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/blobs.ts\n@@ -0,0 +1,237 @@\n+// Binary files' bytes (#27), content-addressed by SHA-256, kept in the\n+// project's own Durable Object SQLite: 1 MB rows, so a blob is never larger\n+// than a row allows, and hasBlob is a synchronous lookup the engine can call.\n+// Uploads stream in (a Durable Object RPC message stops at 32 MiB) and are\n+// hashed as they arrive; a blob whose bytes don't match its name isn't kept.\n+import { createHash } from \"node:crypto\";\n+import type { SqliteStorage } from \"./engine-project.ts\";\n+\n+/** Per file. The push out to Artifacts holds a tree in memory, and a Durable Object has 128 MB. */\n+export const BLOB_MAX = 20 * 1024 * 1024;\n+const PART = 1024 * 1024;\n+const SHA = /^[0-9a-f]{64}$/;\n+const SCHEMA =\n+\t\"CREATE TABLE blobs (sha TEXT NOT NULL, part INTEGER NOT NULL, data BLOB NOT NULL, PRIMARY KEY (sha, part))\";\n+\n+const normalizedSchema = (sql: string) => sql.replace(/\\s+/g, \" \").trim().toUpperCase();\n+\n+export type PutBlob =\n+\t| { status: 200; body: { sha256: string; size: number; stored: boolean } }\n+\t| { status: 400 | 413; body: { error: string } };\n+\n+export class BlobStore {\n+\tprivate storage: SqliteStorage;\n+\n+\tconstructor(storage: SqliteStorage) {\n+\t\tthis.storage = storage;\n+\t}\n+\n+\t/** Reads must not create storage, including when a cold object has no blobs. */\n+\tprivate hasSchema(): boolean {\n+\t\tconst rows = this.storage.sql.exec(\"SELECT type, sql FROM sqlite_master WHERE name = 'blobs'\").toArray() as {\n+\t\t\ttype: string;\n+\t\t\tsql: string | null;\n+\t\t}[];\n+\t\tif (rows.length === 0) return false;\n+\t\tif (\n+\t\t\trows.length !== 1 ||\n+\t\t\trows[0]?.type !== \"table\" ||\n+\t\t\ttypeof rows[0].sql !== \"string\" ||\n+\t\t\tnormalizedSchema(rows[0].sql) !== normalizedSchema(SCHEMA)\n+\t\t)\n+\t\t\tthrow new Error(\"unsupported blob storage schema\");\n+\t\treturn true;\n+\t}\n+\n+\t/** Only mutation paths may initialize the exact supported table. Never repair a mismatch. */\n+\tprivate ensureSchema(): void {\n+\t\tif (!this.hasSchema()) this.storage.sql.exec(SCHEMA);\n+\t}\n+\n+\t/** Blobs in sha order after `after`, with their sizes (temporary uploads left out). */\n+\tlist(after: string, limit: number): { blobs: { sha: string; size: number }[]; next: string | null } {\n+\t\tif (!this.hasSchema()) return { blobs: [], next: null };\n+\t\tconst rows = this.storage.sql\n+\t\t\t.exec(\n+\t\t\t\t\"SELECT sha, SUM(LENGTH(data)) AS size FROM blobs WHERE sha > ? AND sha NOT LIKE 'tmp-%' GROUP BY sha ORDER BY sha LIMIT ?\",\n+\t\t\t\tafter,\n+\t\t\t\tlimit + 1,\n+\t\t\t)\n+\t\t\t.toArray() as { sha: string; size: number }[];\n+\t\tconst more = rows.length > limit;\n+\t\tconst blobs = rows.slice(0, limit);\n+\t\treturn { blobs, next: more ? blobs.at(-1)!.sha : null };\n+\t}\n+\n+\thas(sha: string): boolean {\n+\t\treturn (\n+\t\t\tthis.hasSchema() &&\n+\t\t\tSHA.test(sha) &&\n+\t\t\tthis.storage.sql.exec(\"SELECT 1 FROM blobs WHERE sha = ? LIMIT 1\", sha).toArray().length > 0\n+\t\t);\n+\t}\n+\n+\t/** Every byte, for the push out. Blobs are at most BLOB_MAX. */\n+\tread(sha: string): Uint8Array | null {\n+\t\tif (!this.hasSchema()) return null;\n+\t\tconst rows = this.storage.sql.exec(\"SELECT data FROM blobs WHERE sha = ? ORDER BY part\", sha).toArray() as {\n+\t\t\tdata: ArrayBuffer;\n+\t\t}[];\n+\t\tif (rows.length === 0) return null;\n+\t\tconst out = new Uint8Array(rows.reduce((n, r) => n + r.data.byteLength, 0));\n+\t\tlet at = 0;\n+\t\tfor (const r of rows) {\n+\t\t\tout.set(new Uint8Array(r.data), at);\n+\t\t\tat += r.data.byteLength;\n+\t\t}\n+\t\treturn out;\n+\t}\n+\n+\t/** The bytes as a stream, one row at a time, or null. */\n+\tstream(sha: string): ReadableStream<Uint8Array> | null {\n+\t\tif (!this.has(sha)) return null;\n+\t\tconst parts = (\n+\t\t\tthis.storage.sql.exec(\"SELECT part FROM blobs WHERE sha = ? ORDER BY part\", sha).toArray() as { part: number }[]\n+\t\t).map((r) => r.part);\n+\t\tlet i = 0;\n+\t\treturn new ReadableStream<Uint8Array>({\n+\t\t\tpull: (c) => {\n+\t\t\t\tif (i >= parts.length) return c.close();\n+\t\t\t\tconst [row] = this.storage.sql\n+\t\t\t\t\t.exec(\"SELECT data FROM blobs WHERE sha = ? AND part = ?\", sha, parts[i++]!)\n+\t\t\t\t\t.toArray() as { data: ArrayBuffer }[];\n+\t\t\t\tc.enqueue(new Uint8Array(row!.data));\n+\t\t\t},\n+\t\t});\n+\t}\n+\n+\t/**\n+\t * A whole file's text (#46), stored as UTF-8 under its SHA-256. Synchronous,\n+\t * so the engine can call it while it records.\n+\t */\n+\tputText(text: string): string {\n+\t\tconst bytes = new TextEncoder().encode(text);\n+\t\tconst sha = createHash(\"sha256\").update(bytes).digest(\"hex\");\n+\t\tif (!this.has(sha)) this.write(sha, bytes, 0);\n+\t\treturn sha;\n+\t}\n+\n+\t/** A whole file's text back, or null. */\n+\ttextOf(sha: string): string | null {\n+\t\tconst bytes = this.read(sha);\n+\t\treturn bytes ? new TextDecoder().decode(bytes) : null;\n+\t}\n+\n+\t/** Stores bytes already in memory (plain-git intake), under their own hash. */\n+\tasync putBytes(bytes: Uint8Array): Promise<string> {\n+\t\tconst sha = hex(await crypto.subtle.digest(\"SHA-256\", bytes));\n+\t\tif (!this.has(sha)) this.write(sha, bytes, 0);\n+\t\treturn sha;\n+\t}\n+\n+\t/** Streams an upload in, checking its size and that its SHA-256 is `sha`. */\n+\t/** `max` lowers BLOB_MAX for this put (a capped project's file cap, abso issue 249). */\n+\tasync put(sha: string, body: ReadableStream<Uint8Array>, max: number = BLOB_MAX): Promise<PutBlob> {\n+\t\tif (!SHA.test(sha)) return { status: 400, body: { error: \"a blob's name is its SHA-256 in lowercase hex\" } };\n+\t\tif (this.has(sha)) {\n+\t\t\tawait body.cancel().catch(() => {});\n+\t\t\treturn { status: 200, body: { sha256: sha, size: this.size(sha), stored: false } };\n+\t\t}\n+\t\tconst temp = `tmp-${crypto.randomUUID()}`;\n+\t\tconst digest = new crypto.DigestStream(\"SHA-256\");\n+\t\tconst hashing = digest.getWriter();\n+\t\tlet size = 0;\n+\t\tlet part = 0;\n+\t\tlet pending: Uint8Array[] = [];\n+\t\tlet pendingSize = 0;\n+\t\tconst flush = () => {\n+\t\t\tif (pendingSize === 0) return;\n+\t\t\tpart = this.write(temp, concat(pending, pendingSize), part);\n+\t\t\tpending = [];\n+\t\t\tpendingSize = 0;\n+\t\t};\n+\t\ttry {\n+\t\t\tfor await (const chunk of body) {\n+\t\t\t\tsize += chunk.byteLength;\n+\t\t\t\tif (size > max) {\n+\t\t\t\t\tthis.drop(temp);\n+\t\t\t\t\treturn { status: 413, body: { error: `blobs are at most ${max / 1024 / 1024} MB` } };\n+\t\t\t\t}\n+\t\t\t\tawait hashing.write(chunk);\n+\t\t\t\tpending.push(chunk);\n+\t\t\t\tpendingSize += chunk.byteLength;\n+\t\t\t\tif (pendingSize >= PART) flush();\n+\t\t\t}\n+\t\t\tflush();\n+\t\t\tif (part === 0) part = this.write(temp, new Uint8Array(), 0); // an empty file is a blob too\n+\t\t\tawait hashing.close();\n+\t\t\tconst got = hex(await digest.digest);\n+\t\t\tif (got !== sha) {\n+\t\t\t\tthis.drop(temp);\n+\t\t\t\treturn { status: 400, body: { error: `the bytes hash to ${got}, not ${sha}` } };\n+\t\t\t}\n+\t\t\t// Another upload of the same bytes may have finished meanwhile.\n+\t\t\tif (this.has(sha)) this.drop(temp);\n+\t\t\telse {\n+\t\t\t\tthis.ensureSchema();\n+\t\t\t\tthis.storage.sql.exec(\"UPDATE blobs SET sha = ? WHERE sha = ?\", sha, temp);\n+\t\t\t}\n+\t\t\treturn { status: 200, body: { sha256: sha, size, stored: true } };\n+\t\t} catch (e) {\n+\t\t\tthis.drop(temp);\n+\t\t\tthrow e;\n+\t\t}\n+\t}\n+\n+\t/** Every blob's bytes together, referenced or not (a capped project's total, 249). Uploads in progress don't count. */\n+\ttotal(): number {\n+\t\tif (!this.hasSchema()) return 0;\n+\t\tconst [row] = this.storage.sql\n+\t\t\t.exec(\"SELECT COALESCE(SUM(LENGTH(data)), 0) AS n FROM blobs WHERE sha NOT LIKE 'tmp-%'\")\n+\t\t\t.toArray() as { n: number }[];\n+\t\treturn row?.n ?? 0;\n+\t}\n+\n+\t/** A blob's size in bytes: 0 when the project doesn't hold it. */\n+\tsize(sha: string): number {\n+\t\tif (!this.hasSchema()) return 0;\n+\t\tconst [row] = this.storage.sql\n+\t\t\t.exec(\"SELECT COALESCE(SUM(LENGTH(data)), 0) AS n FROM blobs WHERE sha = ?\", sha)\n+\t\t\t.toArray() as { n: number }[];\n+\t\treturn row?.n ?? 0;\n+\t}\n+\n+\t/** Writes bytes as rows of at most PART from part `first` on; answers the next part. An empty blob is one empty row. */\n+\tprivate write(sha: string, bytes: Uint8Array, first: number): number {\n+\t\tthis.ensureSchema();\n+\t\tlet part = first;\n+\t\tfor (let at = 0; at < bytes.byteLength || (at === 0 && part === 0); at += PART) {\n+\t\t\tthis.storage.sql.exec(\n+\t\t\t\t\"INSERT INTO blobs (sha, part, data) VALUES (?, ?, ?)\",\n+\t\t\t\tsha,\n+\t\t\t\tpart++,\n+\t\t\t\tbytes.slice(at, at + PART),\n+\t\t\t);\n+\t\t\tif (bytes.byteLength === 0) break;\n+\t\t}\n+\t\treturn part;\n+\t}\n+\n+\tprivate drop(sha: string) {\n+\t\tthis.ensureSchema();\n+\t\tthis.storage.sql.exec(\"DELETE FROM blobs WHERE sha = ?\", sha);\n+\t}\n+}\n+\n+function concat(chunks: Uint8Array[], size: number): Uint8Array {\n+\tif (chunks.length === 1) return chunks[0]!;\n+\tconst out = new Uint8Array(size);\n+\tlet at = 0;\n+\tfor (const c of chunks) {\n+\t\tout.set(c, at);\n+\t\tat += c.byteLength;\n+\t}\n+\treturn out;\n+}\n+\n+const hex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");"},{"path":"server/src/engine-project.ts","added":724,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/engine-project.ts\n@@ -0,0 +1,724 @@\n+// The engine's Project (worker/project/project.ts) behind the server's calls, with its append-only log kept in the\n+// Durable Object's SQLite. An entry longer than one row allows (init holds every starting file; SQLite rows stop at\n+// 2 MB) is split across rows and joined on load. Ported from the platform's worker/src/engine-project.ts; the\n+// writer-adoption and R2 version parts are left out.\n+\n+import { blame, folderBlame, why } from \"../../worker/project/blame.ts\";\n+import { feedEvents } from \"../../worker/project/feed.ts\";\n+import { type Entry, type ProjectStore as LogStore, MemoryStore, Project } from \"../../worker/project/project.ts\";\n+import type { EditBody, ProjectCalls, ProjectHistory } from \"../../worker/project/project-api.ts\";\n+import { where } from \"../../worker/project/where.ts\";\n+\n+/** The parts of a Durable Object's storage the log and blob store use, declared structurally so tests can stand in. */\n+export interface SqliteStorage {\n+\tsql: { exec(query: string, ...bindings: unknown[]): { toArray(): unknown[] } };\n+\ttransactionSync<T>(fn: () => T): T;\n+}\n+\n+// Characters per row. SQLite's 2 MB cap is in bytes, and a character is at\n+// most 3 bytes of UTF-8 (an emoji is 2 characters and 4 bytes), so 600,000 stays under it.\n+const PART = 600_000;\n+\n+/** An entry's JSON in rows of at most PART characters, never cutting an emoji's two halves apart. */\n+export function logParts(text: string): string[] {\n+\tconst parts: string[] = [];\n+\tlet at = 0;\n+\tdo {\n+\t\tlet end = Math.min(at + PART, text.length);\n+\t\tconst c = text.charCodeAt(end - 1);\n+\t\tif (end < text.length && c >= 0xd800 && c <= 0xdbff) end--;\n+\t\tparts.push(text.slice(at, end));\n+\t\tat = end;\n+\t} while (at < text.length);\n+\treturn parts;\n+}\n+\n+/** The lines an entry's atoms write: what a loaded project's size grows with (#46, #56). */\n+function linesIn(entry: Entry): number {\n+\tlet n = 0;\n+\tfor (const a of [\n+\t\t(entry as { atom?: { inserts?: { lines: unknown[] }[] } }).atom,\n+\t\t(entry as { tie?: { inserts?: { lines: unknown[] }[] } }).tie,\n+\t]) {\n+\t\tfor (const r of a?.inserts ?? []) n += r.lines.length;\n+\t}\n+\treturn n;\n+}\n+\n+/** The version of shared an entry makes, or undefined (abso issue 78: the access check reads it without loading). */\n+function sharedVersionOf(entry: Entry): number | undefined {\n+\tif (entry.type === \"init\") return 0;\n+\tif (entry.type === \"land\" || entry.type === \"drop\") return entry.version;\n+\tif (entry.type === \"publish\" && (entry.space ?? \"\") === \"\") return entry.version;\n+\treturn undefined;\n+}\n+\n+/** Who made that version of shared, and when. Init is not a publish (abso issue 86). */\n+function lastPublishOf(entry: Entry): { agent: string; time: number } | undefined {\n+\tif (entry.type === \"land\" || entry.type === \"drop\") return { agent: entry.agent, time: entry.time };\n+\tif (entry.type === \"publish\" && (entry.space ?? \"\") === \"\") return { agent: entry.agent, time: entry.time };\n+\treturn undefined;\n+}\n+\n+/** An entry's claim keys and deletes (#46): with entries and lines, what the load guard estimates memory by. */\n+function keysIn(entry: Entry): number {\n+\tlet n = 0;\n+\tfor (const a of [\n+\t\t(entry as { atom?: Partial<Record<\"writes\" | \"reads\" | \"holds\" | \"deletes\", unknown[]>> }).atom,\n+\t\t(entry as { tie?: Partial<Record<\"writes\" | \"reads\" | \"holds\" | \"deletes\", unknown[]>> }).tie,\n+\t]) {\n+\t\tif (a) n += (a.writes?.length ?? 0) + (a.reads?.length ?? 0) + (a.holds?.length ?? 0) + (a.deletes?.length ?? 0);\n+\t}\n+\treturn n;\n+}\n+\n+export class SqliteLog implements LogStore {\n+\tprivate storage: SqliteStorage;\n+\tprivate next: number;\n+\n+\tconstructor(storage: SqliteStorage) {\n+\t\tthis.storage = storage;\n+\t\tstorage.sql.exec(\n+\t\t\t\"CREATE TABLE IF NOT EXISTS log (seq INTEGER, part INTEGER, text TEXT NOT NULL, PRIMARY KEY (seq, part))\",\n+\t\t);\n+\t\tstorage.sql.exec(\n+\t\t\t\"CREATE TABLE IF NOT EXISTS shapes (space TEXT NOT NULL, version INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY (space, version))\",\n+\t\t);\n+\t\tstorage.sql.exec(\"CREATE TABLE IF NOT EXISTS counts (name TEXT PRIMARY KEY, value INTEGER NOT NULL)\");\n+\t\tstorage.sql.exec(\"CREATE TABLE IF NOT EXISTS marks (name TEXT PRIMARY KEY, value TEXT NOT NULL)\");\n+\t\tconst rows = storage.sql.exec(\"SELECT COALESCE(MAX(seq), -1) AS last FROM log\").toArray() as { last: number }[];\n+\t\tthis.next = (rows[0]?.last ?? -1) + 1;\n+\t}\n+\n+\t/** The seq the next entry would take. A copy's next page must start here. */\n+\tseq(): number {\n+\t\treturn this.next;\n+\t}\n+\n+\t/** Monotonic cache invalidation epoch for every canonical log mutation. */\n+\tgeneration(): number {\n+\t\tconst rows = this.storage.sql.exec(\"SELECT value FROM marks WHERE name = ?\", \"generation\").toArray() as {\n+\t\t\tvalue: string;\n+\t\t}[];\n+\t\tconst generation = Number(rows[0]?.value ?? 0);\n+\t\tif (!Number.isSafeInteger(generation) || generation < 0) throw new Error(\"canonical log generation is invalid\");\n+\t\treturn generation;\n+\t}\n+\n+\t/**\n+\t * Lines ever recorded (#46, #56): what loading the project costs grows with\n+\t * this, not with the log's size, so a guard can read it without loading.\n+\t * Kept with each append; undefined for a log written before the count,\n+\t * until it next loads.\n+\t */\n+\tlineCount(): number | undefined {\n+\t\tconst rows = this.storage.sql.exec(\"SELECT value FROM counts WHERE name = 'lines'\").toArray() as {\n+\t\t\tvalue: number;\n+\t\t}[];\n+\t\treturn rows[0]?.value;\n+\t}\n+\n+\t/**\n+\t * The newest version of shared, without loading the project (abso issue 78: the website's access check asked\n+\t * every project's engine for it). Kept with each append; a log from before the count is read once by streaming.\n+\t */\n+\tsharedVersion(): number {\n+\t\tconst rows = this.storage.sql.exec(\"SELECT value FROM counts WHERE name = 'shared'\").toArray() as {\n+\t\t\tvalue: number;\n+\t\t}[];\n+\t\tif (rows[0] !== undefined) return rows[0].value;\n+\t\tlet version = -1;\n+\t\tfor (const e of this.#entries()) version = sharedVersionOf(e) ?? version;\n+\t\tif (version >= 0)\n+\t\t\tthis.storage.sql.exec(\"INSERT OR REPLACE INTO counts (name, value) VALUES ('shared', ?)\", version);\n+\t\treturn version;\n+\t}\n+\n+\t/**\n+\t * Who published shared's newest version, and when, without loading the project (abso issue 86).\n+\t * Null when shared has no publish yet. A log from before the mark is read once by streaming.\n+\t */\n+\tlastPublish(): { agent: string; time: number } | null {\n+\t\tconst rows = this.storage.sql.exec(\"SELECT value FROM marks WHERE name = ?\", \"last\").toArray() as {\n+\t\t\tvalue: string;\n+\t\t}[];\n+\t\tif (rows[0] !== undefined) return JSON.parse(rows[0].value) as { agent: string; time: number };\n+\t\tlet last: { agent: string; time: number } | null = null;\n+\t\tfor (const e of this.#entries()) {\n+\t\t\tconst found = lastPublishOf(e);\n+\t\t\tif (found) last = found;\n+\t\t}\n+\t\tif (last)\n+\t\t\tthis.storage.sql.exec(\"INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)\", \"last\", JSON.stringify(last));\n+\t\treturn last;\n+\t}\n+\n+\t/**\n+\t * How big the log is, without loading the project or scanning it twice (ask 160).\n+\t * Entries are the next seq. Chars are kept like lines; a log from before the\n+\t * count is summed once, then kept. GET /projects' 2-second wait needs this\n+\t * to stay a storage read: SUM(LENGTH(text)) over abso's log misses it.\n+\t */\n+\tlogSize(): { chars: number; entries: number } {\n+\t\tconst entries = this.next;\n+\t\tconst rows = this.storage.sql.exec(\"SELECT value FROM counts WHERE name = 'chars'\").toArray() as {\n+\t\t\tvalue: number;\n+\t\t}[];\n+\t\tif (rows[0] !== undefined) return { chars: rows[0].value, entries };\n+\t\tif (entries === 0) return { chars: 0, entries: 0 };\n+\t\tconst summed = this.storage.sql.exec(\"SELECT COALESCE(SUM(LENGTH(text)), 0) AS chars FROM log\").toArray()[0] as\n+\t\t\t| { chars: number }\n+\t\t\t| undefined;\n+\t\tconst chars = summed?.chars ?? 0;\n+\t\tthis.storage.sql.exec(\"INSERT OR REPLACE INTO counts (name, value) VALUES ('chars', ?)\", chars);\n+\t\treturn { chars, entries };\n+\t}\n+\n+\t/** Claim keys and deletes ever recorded (#46), kept like the line count; undefined before they were counted. */\n+\tkeyCount(): number | undefined {\n+\t\tconst rows = this.storage.sql.exec(\"SELECT value FROM counts WHERE name = 'keys'\").toArray() as { value: number }[];\n+\t\treturn rows[0]?.value;\n+\t}\n+\n+\t/**\n+\t * The lines and keys ever recorded, counting a log from before either count without loading the project\n+\t * (#46): one entry parsed at a time, so a log the load guard would refuse can still be measured. Kept once counted.\n+\t */\n+\tcountSizes(): { lines: number; keys: number } {\n+\t\tconst lines = this.lineCount();\n+\t\tconst keys = this.keyCount();\n+\t\tif (lines !== undefined && keys !== undefined) return { lines, keys };\n+\t\tlet l = 0;\n+\t\tlet k = 0;\n+\t\tfor (const e of this.#entries()) {\n+\t\t\tl += linesIn(e);\n+\t\t\tk += keysIn(e);\n+\t\t}\n+\t\tthis.#keep(lines === undefined ? l : undefined, keys === undefined ? k : undefined);\n+\t\treturn { lines: lines ?? l, keys: keys ?? k };\n+\t}\n+\n+\t/** Stores the counts given. */\n+\t#keep(lines: number | undefined, keys: number | undefined): void {\n+\t\tif (lines !== undefined)\n+\t\t\tthis.storage.sql.exec(\"INSERT OR REPLACE INTO counts (name, value) VALUES ('lines', ?)\", lines);\n+\t\tif (keys !== undefined)\n+\t\t\tthis.storage.sql.exec(\"INSERT OR REPLACE INTO counts (name, value) VALUES ('keys', ?)\", keys);\n+\t}\n+\n+\t/** Every stored entry, in order. Rows are read one at a time, so loading never holds the whole log's text at once (#43). */\n+\t*entries(): Iterable<Entry> {\n+\t\t// A log from before the counts: counted as it loads, and kept.\n+\t\tconst countLines = this.lineCount() === undefined;\n+\t\tconst countKeys = this.keyCount() === undefined;\n+\t\tlet lines = 0;\n+\t\tlet keys = 0;\n+\t\tfor (const e of this.#entries()) {\n+\t\t\tif (countLines) lines += linesIn(e);\n+\t\t\tif (countKeys) keys += keysIn(e);\n+\t\t\tyield e;\n+\t\t}\n+\t\tthis.#keep(countLines ? lines : undefined, countKeys ? keys : undefined);\n+\t}\n+\n+\t*#entries(from = 0): Iterable<Entry> {\n+\t\t// A Workers cursor is iterable; a test's stand-in may only have toArray.\n+\t\tconst cursor = this.storage.sql.exec(\"SELECT seq, text FROM log WHERE seq >= ? ORDER BY seq, part\", from) as {\n+\t\t\ttoArray(): unknown[];\n+\t\t} & Partial<Iterable<unknown>>;\n+\t\tconst rows = (cursor[Symbol.iterator] ? cursor : cursor.toArray()) as Iterable<{ seq: number; text: string }>;\n+\t\tlet seq = -1;\n+\t\tlet text = \"\";\n+\t\tfor (const r of rows) {\n+\t\t\tif (r.seq !== seq && seq >= 0) yield JSON.parse(text) as Entry;\n+\t\t\tif (r.seq !== seq) text = \"\";\n+\t\t\tseq = r.seq;\n+\t\t\ttext += r.text;\n+\t\t}\n+\t\tif (seq >= 0) yield JSON.parse(text) as Entry;\n+\t}\n+\n+\t/**\n+\t * For backups (#29): the entries from seq `from` on as their stored JSON\n+\t * text (not parsed, so an export holds the project up as little as it\n+\t * can), at most `limit` of them and about 8 MB (always at least one), and\n+\t * the seq to ask for next, or null at the end.\n+\t */\n+\tpage(from: number, limit: number): { texts: string[]; next: number | null } {\n+\t\tconst rows = this.storage.sql\n+\t\t\t.exec(\"SELECT seq, text FROM log WHERE seq >= ? AND seq < ? ORDER BY seq, part\", from, from + limit)\n+\t\t\t.toArray() as { seq: number; text: string }[];\n+\t\tconst texts: string[] = [];\n+\t\tlet seq = -1;\n+\t\tlet text = \"\";\n+\t\tlet size = 0;\n+\t\tlet next: number | null = null;\n+\t\tfor (const r of rows) {\n+\t\t\tif (r.seq < from || r.seq >= from + limit) continue;\n+\t\t\tif (r.seq !== seq && seq >= 0) {\n+\t\t\t\ttexts.push(text);\n+\t\t\t\tsize += text.length;\n+\t\t\t\tif (size > 8_000_000) {\n+\t\t\t\t\tnext = r.seq;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif (r.seq !== seq) text = \"\";\n+\t\t\tseq = r.seq;\n+\t\t\ttext += r.text;\n+\t\t}\n+\t\tif (next === null && seq >= 0) texts.push(text);\n+\t\tif (next === null && from + limit < this.next) next = from + limit;\n+\t\treturn { texts, next };\n+\t}\n+\n+\t/** Up to `limit` entries from position `from`, parsed (#41: the feed and replay). */\n+\tsince(from: number, limit: number): Entry[] {\n+\t\tconst out: Entry[] = [];\n+\t\tfor (let at = from; out.length < limit; ) {\n+\t\t\tconst { texts, next } = this.page(at, limit - out.length);\n+\t\t\tfor (const t of texts) out.push(JSON.parse(t) as Entry);\n+\t\t\tif (next === null || texts.length === 0) break;\n+\t\t\tat = next;\n+\t\t}\n+\t\treturn out;\n+\t}\n+\n+\t/** Removes every entry: only for a restore whose log didn't load (#29). */\n+\tclear(): void {\n+\t\tconst generation = this.generation() + 1;\n+\t\tthis.storage.transactionSync(() => {\n+\t\t\tthis.storage.sql.exec(\"DELETE FROM log\");\n+\t\t\tthis.storage.sql.exec(\"DELETE FROM shapes\");\n+\t\t\tthis.storage.sql.exec(\"DELETE FROM counts\");\n+\t\t\tthis.storage.sql.exec(\"DELETE FROM marks WHERE name != ?\", \"generation\");\n+\t\t\tthis.storage.sql.exec(\n+\t\t\t\t\"INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)\",\n+\t\t\t\t\"generation\",\n+\t\t\t\tString(generation),\n+\t\t\t);\n+\t\t});\n+\t\tthis.next = 0;\n+\t}\n+\n+\t/**\n+\t * Each version's changed files, kept between loads (#41, the Files pages):\n+\t * worked out from the log, never part of it, so an older Worker ignores\n+\t * the table and nothing about the project depends on it.\n+\t */\n+\tshapes(): {\n+\t\tget(space: string, version: number): string | undefined;\n+\t\tput(space: string, version: number, value: string): void;\n+\t} {\n+\t\tconst sql = this.storage.sql;\n+\t\treturn {\n+\t\t\tget: (space, version) =>\n+\t\t\t\t(\n+\t\t\t\t\tsql.exec(\"SELECT value FROM shapes WHERE space = ? AND version = ?\", space, version).toArray() as {\n+\t\t\t\t\t\tvalue: string;\n+\t\t\t\t\t}[]\n+\t\t\t\t)[0]?.value,\n+\t\t\tput: (space, version, value) =>\n+\t\t\t\tvoid sql.exec(\"INSERT OR REPLACE INTO shapes (space, version, value) VALUES (?, ?, ?)\", space, version, value),\n+\t\t};\n+\t}\n+\n+\tappend(entries: readonly Entry[]): void {\n+\t\tif (!entries.length) return;\n+\t\tlet next = this.next;\n+\t\tthis.storage.transactionSync(() => {\n+\t\t\tconst lines = entries.reduce((n, e) => n + linesIn(e), 0);\n+\t\t\tif (lines > 0)\n+\t\t\t\tthis.storage.sql.exec(\n+\t\t\t\t\t\"INSERT INTO counts (name, value) VALUES ('lines', ?) ON CONFLICT(name) DO UPDATE SET value = value + ?\",\n+\t\t\t\t\tlines,\n+\t\t\t\t\tlines,\n+\t\t\t\t);\n+\t\t\t// The newest version of shared: appended entries are the newest, so the last one that makes a version wins.\n+\t\t\tfor (const e of entries) {\n+\t\t\t\tconst v = sharedVersionOf(e);\n+\t\t\t\tif (v !== undefined)\n+\t\t\t\t\tthis.storage.sql.exec(\"INSERT OR REPLACE INTO counts (name, value) VALUES ('shared', ?)\", v);\n+\t\t\t\tconst last = lastPublishOf(e);\n+\t\t\t\tif (last)\n+\t\t\t\t\tthis.storage.sql.exec(\n+\t\t\t\t\t\t\"INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)\",\n+\t\t\t\t\t\t\"last\",\n+\t\t\t\t\t\tJSON.stringify(last),\n+\t\t\t\t\t);\n+\t\t\t}\n+\t\t\t// Keys are only added to once counted: a log from before the key count is counted whole first (countSizes).\n+\t\t\tconst keys = entries.reduce((n, e) => n + keysIn(e), 0);\n+\t\t\tif (keys > 0) this.storage.sql.exec(\"UPDATE counts SET value = value + ? WHERE name = 'keys'\", keys);\n+\t\t\tlet chars = 0;\n+\t\t\tfor (const entry of entries) {\n+\t\t\t\tconst json = JSON.stringify(entry);\n+\t\t\t\tlogParts(json).forEach((text, part) => {\n+\t\t\t\t\tchars += text.length;\n+\t\t\t\t\tthis.storage.sql.exec(\"INSERT INTO log (seq, part, text) VALUES (?, ?, ?)\", next, part, text);\n+\t\t\t\t});\n+\t\t\t\tnext++;\n+\t\t\t}\n+\t\t\t// Chars are only added to once counted: a log from before the count is summed whole first (logSize).\n+\t\t\tif (chars > 0) this.storage.sql.exec(\"UPDATE counts SET value = value + ? WHERE name = 'chars'\", chars);\n+\t\t\tconst generation = this.generation() + 1;\n+\t\t\tthis.storage.sql.exec(\n+\t\t\t\t\"INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)\",\n+\t\t\t\t\"generation\",\n+\t\t\t\tString(generation),\n+\t\t\t);\n+\t\t});\n+\t\tthis.next = next;\n+\t}\n+}\n+\n+/** The engine's Project as the Worker's ProjectCalls; the clock comes from here. */\n+export class EngineProject implements ProjectCalls, ProjectHistory {\n+\tblame(file: string, from?: number, to?: number, version?: number, draft?: string, agent?: string) {\n+\t\treturn blame(this.project, file, from, to, version, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });\n+\t}\n+\tfolderBlame(folder: string, version?: number, draft?: string, agent?: string) {\n+\t\treturn folderBlame(this.project, folder, version, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });\n+\t}\n+\ttree(folder: string, version?: number, draft?: string | null, agent?: string, authors?: boolean) {\n+\t\treturn this.project.tree(folder, {\n+\t\t\t...(version !== undefined ? { version } : {}),\n+\t\t\tdraft: draft ?? null,\n+\t\t\t...(agent !== undefined ? { agent } : {}),\n+\t\t\t...(authors ? { authors } : {}),\n+\t\t});\n+\t}\n+\tpathLife(path: string, version?: number, draft?: string | null) {\n+\t\treturn this.project.pathLife(path, { ...(version !== undefined ? { version } : {}), draft: draft ?? null });\n+\t}\n+\tfollow(path: string, version: number, from: number, to: number, at?: number, draft?: string | null) {\n+\t\treturn this.project.follow(path, version, from, to, { ...(at !== undefined ? { at } : {}), draft: draft ?? null });\n+\t}\n+\tpathsOf(agent: string) {\n+\t\treturn this.project.pathsOf(agent);\n+\t}\n+\tdraftState(name: string) {\n+\t\treturn this.project.draftState(name);\n+\t}\n+\tcollisions(file?: string, folder?: string) {\n+\t\treturn this.project.collisions({\n+\t\t\t...(file !== undefined ? { file } : {}),\n+\t\t\t...(folder !== undefined ? { folder } : {}),\n+\t\t});\n+\t}\n+\twhy(file: string, line: number, draft?: string, agent?: string) {\n+\t\treturn why(this.project, file, line, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });\n+\t}\n+\twhere() {\n+\t\treturn where(this.project);\n+\t}\n+\trefusals(agent?: string, limit?: number) {\n+\t\treturn this.project.refusals({ ...(agent ? { agent } : {}), ...(limit !== undefined ? { limit } : {}) });\n+\t}\n+\n+\tlog(draft: string | null, limit?: number, path?: string, agent?: string, before?: number, follow?: boolean) {\n+\t\treturn this.project.log({\n+\t\t\tdraft,\n+\t\t\t...(limit !== undefined ? { limit } : {}),\n+\t\t\t...(path !== undefined ? { path } : {}),\n+\t\t\t...(agent ? { agent } : {}),\n+\t\t\t...(before !== undefined ? { before } : {}),\n+\t\t\t...(follow ? { follow } : {}),\n+\t\t});\n+\t}\n+\tfileAt(path: string, version: number, draft: string | null, agent?: string) {\n+\t\treturn this.project.fileAt(path, version, { draft, ...(agent ? { agent } : {}) });\n+\t}\n+\tcompare(from: number, to: number, draft: string | null, agent?: string) {\n+\t\treturn this.project.compare(from, to, { draft, ...(agent ? { agent } : {}) });\n+\t}\n+\tshow(version: number, draft: string | null, agent?: string) {\n+\t\treturn this.project.show(version, { draft, ...(agent ? { agent } : {}) });\n+\t}\n+\tdiff(agent: string) {\n+\t\treturn this.project.diff(agent);\n+\t}\n+\tsyncFull(agent: string, label?: string) {\n+\t\treturn this.project.sync(agent, { full: true, ...(label !== undefined ? { label } : {}) });\n+\t}\n+\tagentPaths(agent: string) {\n+\t\treturn this.project.agentPaths(agent);\n+\t}\n+\tpathsAt(version?: number, draft?: string | null) {\n+\t\treturn this.project.pathsAt(version, draft ?? null);\n+\t}\n+\tsyncTo(agent: string, label: string) {\n+\t\treturn this.project.sync(agent, { label });\n+\t}\n+\tlabel(agent: string, name: string, version?: number, remove?: boolean) {\n+\t\treturn this.project.label(agent, name, version, Date.now(), { remove: remove === true });\n+\t}\n+\tlabels() {\n+\t\treturn this.project.labels();\n+\t}\n+\tamend(agent: string, message: string) {\n+\t\treturn this.project.amend(agent, message, Date.now());\n+\t}\n+\tpluck(agent: string, draft: string, versions: number[], message: string, withDependencies?: boolean) {\n+\t\treturn this.project.pluck(agent, draft, versions, message, Date.now(), {\n+\t\t\twithDependencies: withDependencies === true,\n+\t\t});\n+\t}\n+\tdrop(agent: string, versions: number[], message: string, withDependents?: boolean) {\n+\t\treturn this.project.drop(agent, versions, message, Date.now(), { withDependents: withDependents === true });\n+\t}\n+\tannounce(agent: string, text: string, to?: string[], how?: string) {\n+\t\treturn this.project.announce(agent, text, to, Date.now(), how);\n+\t}\n+\n+\tannouncePerson(person: { id: string; name: string }, text: string, to?: string[]) {\n+\t\treturn this.project.announcePerson(person, text, to, Date.now());\n+\t}\n+\tstarting(agent: string, text: string | null, files?: string[], options: { issue?: unknown; done?: unknown } = {}) {\n+\t\treturn this.project.starting(agent, text, files, Date.now(), options);\n+\t}\n+\tnews(agent: string) {\n+\t\treturn this.project.news(agent);\n+\t}\n+\trestore(agent: string, files: string[] | null) {\n+\t\treturn this.project.restore(agent, files, Date.now());\n+\t}\n+\n+\tprivate project: Project;\n+\n+\t/** Reads stored entries by log position, for the feed and replay (#41); absent, those answer 501. */\n+\tprivate readonly read: ((from: number, limit: number) => Entry[]) | undefined;\n+\tprivate readonly store: SqliteLog | undefined;\n+\n+\tconstructor(project: Project, read?: (from: number, limit: number) => Entry[], store?: SqliteLog) {\n+\t\tthis.project = project;\n+\t\tthis.read = read;\n+\t\tthis.store = store;\n+\t}\n+\n+\t/** The project's events from log position `from` (#41): reading consumes nothing. */\n+\tfeed(from: number, limit = 500) {\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// 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\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}\n+\n+\t/** The log position for a time (ms since 1970) or a version of shared (#41). */\n+\tposition(q: { time?: number; version?: number }) {\n+\t\treturn this.project.position(q);\n+\t}\n+\t/** Whether the Worker runs the queue's check; until it does, \"queue\": true does nothing. */\n+\tsetCheckerReady(ready: boolean): void {\n+\t\tthis.project.checkerReady = ready;\n+\t}\n+\t/** An agent withdraws what it has queued (#39). */\n+\tunqueue(agent: string) {\n+\t\treturn this.project.unqueue(agent, Date.now());\n+\t}\n+\t/** The log length now: what a long-poll waits to see grow. */\n+\tlogLength() {\n+\t\treturn this.project.logLength;\n+\t}\n+\t/** An agent's draft diff for a reader: never creates the agent (#41). */\n+\tdiffOf(agent: string) {\n+\t\treturn this.project.diffOf(agent);\n+\t}\n+\t/** Every agent with unpublished changes: its files and how many changes (#41). */\n+\tchange(id: number) {\n+\t\treturn this.project.change(id);\n+\t}\n+\n+\tchanges(since: number, limit: number, before?: number, issue?: number) {\n+\t\treturn this.project.changes(since, limit, before, issue);\n+\t}\n+\n+\tmove(agent: string, from: string, to: string) {\n+\t\treturn this.project.move(agent, from, to, Date.now());\n+\t}\n+\n+\tnote(agent: string, body: Record<string, unknown>) {\n+\t\treturn this.project.note(agent, body, Date.now());\n+\t}\n+\n+\tnotePerson(person: { id: string; name: string }, body: Record<string, unknown>) {\n+\t\treturn this.project.notePerson(person, body, Date.now());\n+\t}\n+\n+\tcloseNotePerson(person: { id: string; name: string }, id: number, how: unknown) {\n+\t\treturn this.project.closeNotePerson(person, id, how, Date.now());\n+\t}\n+\n+\tcloseNote(agent: string, id: number, how: unknown) {\n+\t\treturn this.project.closeNote(agent, id, how, Date.now());\n+\t}\n+\n+\tnotes(options: { file?: string; change?: number; open?: boolean }) {\n+\t\treturn this.project.notes(options);\n+\t}\n+\n+\tribbon() {\n+\t\treturn this.project.ribbon();\n+\t}\n+\n+\tdrafts() {\n+\t\tconst s = this.project.status();\n+\t\treturn {\n+\t\t\tversion: s.version,\n+\t\t\tdrafts: s.agents\n+\t\t\t\t.filter((a) => a.draftChanges > 0)\n+\t\t\t\t.map((a) => ({ agent: a.agent, draft: a.draft, base: a.base, draftChanges: a.draftChanges, files: a.files })),\n+\t\t};\n+\t}\n+\t/** The last copy replay loaded: scrubbing forward from it applies only the entries after it. */\n+\tprivate replica: Project | undefined;\n+\n+\t/** The project as it stood with the first `at` log entries (#41, replay). */\n+\tprivate at(at: number): Project {\n+\t\tif (!this.read) throw Object.assign(new Error(\"replay needs the log\"), { code: \"not-implemented\" });\n+\t\tconst n = Math.max(0, Math.min(at, this.project.logLength));\n+\t\tconst r = this.replica;\n+\t\tif (r && r.logLength === n) return r;\n+\t\tif (r && r.logLength < n) {\n+\t\t\tr.catchUp(this.read(r.logLength, n - r.logLength));\n+\t\t\treturn r;\n+\t\t}\n+\t\tthis.replica = Project.load(this.read(0, n), new MemoryStore());\n+\t\treturn this.replica;\n+\t}\n+\tstatusAt(at: number) {\n+\t\tconst p = this.at(at);\n+\t\tconst answer = {\n+\t\t\tat: Math.min(at, this.project.logLength),\n+\t\t\t...(p.initialized ? p.status() : { version: -1, agents: [] }),\n+\t\t};\n+\t\tthis.release();\n+\t\treturn answer;\n+\t}\n+\twhereAt(at: number) {\n+\t\tconst p = this.at(at);\n+\t\tconst answer = {\n+\t\t\tat: Math.min(at, this.project.logLength),\n+\t\t\t...(p.initialized ? where(p) : { version: -1, files: {} }),\n+\t\t};\n+\t\tthis.release();\n+\t\treturn answer;\n+\t}\n+\n+\t/**\n+\t * Drop the replay copy after each read (#46): a second copy of a large\n+\t * project's history doubles its memory, past a Durable Object's 128 MB.\n+\t * Each scrub replays from the start instead (about 0.2 s on game).\n+\t */\n+\tprivate release(): void {\n+\t\tthis.replica = undefined;\n+\t}\n+\n+\t/** hasBlob says whether the project holds a blob's bytes (#27); without it, every blob is refused. */\n+\t/** whole stores and reads files kept whole (#46); without it every text file is tracked by line. */\n+\tstatic open(\n+\t\tstorage: SqliteStorage,\n+\t\thasBlob?: (sha256: string) => boolean,\n+\t\twhole?: { keep(text: string): string; read(sha: string): string | null },\n+\t): EngineProject {\n+\t\tconst log = new SqliteLog(storage);\n+\t\treturn new EngineProject(\n+\t\t\tProject.load(log.entries(), log, {\n+\t\t\t\t...(hasBlob ? { hasBlob } : {}),\n+\t\t\t\t...(whole ? { whole } : {}),\n+\t\t\t\tnow: () => Date.now(),\n+\t\t\t\tshapes: log.shapes(),\n+\t\t\t\tentryAt: (at) => log.since(at, 1)[0]!,\n+\t\t\t}),\n+\t\t\t(from, limit) => log.since(from, limit),\n+\t\t\tlog,\n+\t\t);\n+\t}\n+\n+\texists() {\n+\t\treturn this.project.initialized;\n+\t}\n+\t/** Committed log epoch for host-side cache invalidation; it does not dispatch work. */\n+\tcommittedGeneration(): number {\n+\t\treturn this.store?.generation() ?? 0;\n+\t}\n+\tinit(\n+\t\tfiles: Record<string, string>,\n+\t\tmodes?: Record<string, { exec?: boolean; link?: string | null }>,\n+\t\tblobs?: Record<string, string>,\n+\t) {\n+\t\treturn this.project.init(files, Date.now(), modes ?? {}, blobs ?? {});\n+\t}\n+\tedit(agent: string, body: EditBody) {\n+\t\treturn this.project.edit(agent, body as Parameters<Project[\"edit\"]>[1], Date.now());\n+\t}\n+\trecord(\n+\t\tagent: string,\n+\t\tfiles: Record<string, string | null>,\n+\t\tmodes?: Record<string, { exec?: boolean; link?: string | null }>,\n+\t\tblobs?: Record<string, string>,\n+\t\tmeta?: { session?: string; subagent?: string; client?: string },\n+\t) {\n+\t\treturn this.project.record(agent, files, Date.now(), modes ?? {}, blobs ?? {}, meta ?? {});\n+\t}\n+\tpublish(agent: string, message: string, asIs?: boolean) {\n+\t\treturn this.project.publish(agent, message, Date.now(), { asIs: asIs === true });\n+\t}\n+\tsync(agent: string) {\n+\t\treturn this.project.sync(agent);\n+\t}\n+\tstatus() {\n+\t\treturn this.project.status();\n+\t}\n+\tswitchTo(agent: string, name: string | null, carry = false) {\n+\t\treturn this.project.switchTo(agent, name, Date.now(), { carry });\n+\t}\n+\tland(agent: string, message: string) {\n+\t\treturn this.project.land(agent, message, Date.now());\n+\t}\n+\tingest(input: Parameters<Project[\"ingest\"]>[0], time: number) {\n+\t\treturn this.project.ingest(input, time);\n+\t}\n+\tsyncDraft(agent: string) {\n+\t\treturn this.project.syncDraft(agent, Date.now());\n+\t}\n+\tfilesAt(version: number) {\n+\t\treturn this.project.viewAt(version).files();\n+\t}\n+\tblobsAt(version: number) {\n+\t\treturn this.project.viewAt(version).blobs();\n+\t}\n+\t/**\n+\t * Shared's newest version. Its files and modes are laid out on first read: every call reads shared().version\n+\t * before and after its op, and laying out the files reads each file's text from the log, about 0.5 s on abso\n+\t * (abso 299).\n+\t */\n+\tshared() {\n+\t\tconst version = this.project.version;\n+\t\tconst by = version > 0 ? this.project.published(version) : undefined;\n+\t\tconst blobs = this.project.blobs();\n+\t\tconst project = this.project;\n+\t\tlet files: Record<string, string> | undefined;\n+\t\tlet modes: ReturnType<Project[\"modes\"]> | undefined;\n+\t\treturn {\n+\t\t\tversion,\n+\t\t\tget files() {\n+\t\t\t\tfiles ??= project.files();\n+\t\t\t\treturn files;\n+\t\t\t},\n+\t\t\tget modes() {\n+\t\t\t\tmodes ??= project.modes();\n+\t\t\t\treturn modes;\n+\t\t\t},\n+\t\t\t...(Object.keys(blobs).length > 0 ? { blobs } : {}),\n+\t\t\t...(by ? { last: { agent: by.agent, message: by.message } } : {}),\n+\t\t};\n+\t}\n+}"},{"path":"server/src/env.ts","added":36,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/env.ts\n@@ -0,0 +1,36 @@\n+// What the open server's Worker is given: wrangler.jsonc's bindings and the secrets set with `wrangler secret put`.\n+\n+import type { IssueProject } from \"./issues-entry.ts\";\n+import type { ProjectObject } from \"./project-object.ts\";\n+\n+export interface Env {\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. */\n+\tISSUES_DO: DurableObjectNamespace<IssueProject>;\n+\t/** Each project's shared, pushed out as a git repo abso-<project>. Unbound under local `wrangler dev`: skipped. */\n+\tARTIFACTS?: Artifacts;\n+\t/** \"off\" leaves Artifacts alone even where it is bound: local `wrangler dev --local` binds it but cannot reach it. */\n+\tABSO_ARTIFACTS?: string;\n+\tCF_VERSION_METADATA?: WorkerVersionMetadata;\n+\t/** The shared token every agent signs in with. AVCS_TOKEN is its old name. With neither set, every call is refused. */\n+\tABSO_TOKEN?: string;\n+\tAVCS_TOKEN?: string;\n+\t/** For /admin/agent-keys, sent as the x-abso-admin header beside the shared token. */\n+\tABSO_ADMIN_TOKEN?: string;\n+\tAVCS_ADMIN_TOKEN?: string;\n+\t/** Per-agent keys: \"on\" with KEY_HMAC_SECRET set. */\n+\tAGENT_KEYS?: string;\n+\tKEY_HMAC_SECRET?: string;\n+}\n+\n+/** A secret by its abso name, or its avcs name from before the rename. Empty counts as unset. */\n+export function secret(env: Env, name: \"TOKEN\" | \"ADMIN_TOKEN\"): string | undefined {\n+\tfor (const v of [env[`ABSO_${name}`], env[`AVCS_${name}`]]) if (typeof v === \"string\" && v !== \"\") return v;\n+\treturn undefined;\n+}\n+\n+/** The Artifacts binding, unless it is unbound or ABSO_ARTIFACTS is \"off\": then nothing is pushed out or taken in. */\n+export function artifactsOf(env: Env): Artifacts | undefined {\n+\treturn env.ABSO_ARTIFACTS === \"off\" ? undefined : env.ARTIFACTS;\n+}"},{"path":"server/src/index.ts","added":12,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/index.ts\n@@ -0,0 +1,12 @@\n+// The Worker's entry: the router (router.ts) and the Durable Object classes wrangler.jsonc binds.\n+\n+import type { Env } from \"./env.ts\";\n+import { issuesFetch } from \"./issues-entry.ts\";\n+import { handle } from \"./router.ts\";\n+\n+export { IssueProject } from \"./issues-entry.ts\";\n+export { ProjectObject } from \"./project-object.ts\";\n+\n+export default {\n+\tfetch: (request, env, ctx) => handle(request, env, ctx, issuesFetch),\n+} satisfies ExportedHandler<Env>;"},{"path":"server/src/ingest.ts","added":174,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/ingest.ts\n@@ -0,0 +1,174 @@\n+// In from plain git (#8, demo moment 5): commits a person pushed to the\n+// project's Artifacts repo, read back for project.ingest. Every commit the\n+// Worker pushes ends \"abso-version: N\" (\"avcs-version: N\" before the rename); the commits above the newest such\n+// commit that haven't been taken in yet are the person's, and N is their base.\n+import git from \"isomorphic-git\";\n+import http from \"isomorphic-git/http/web\";\n+import type { FileModes } from \"../../worker/project/project-api.ts\";\n+import { MemoryFS } from \"./memory-fs.ts\";\n+import { repoName } from \"./push.ts\";\n+\n+const EXEC = 0o100755;\n+const LINK = 0o120000;\n+\n+/** How far back to look for the Worker's last commit. */\n+const DEPTH = 50;\n+const text = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false });\n+\n+export interface PushedCommits {\n+\t/** main's head when read. */\n+\thead: string;\n+\tauthor: string;\n+\tbase: number;\n+\t/** Oldest first, each with its whole tree as text and every file's mode. Binary files are left out. */\n+\tcommits: {\n+\t\tsha: string;\n+\t\tmessage: string;\n+\t\tfiles: Record<string, string>;\n+\t\tmodes: FileModes;\n+\t\tblobs: Record<string, string>;\n+\t}[];\n+\t/** Binary files over the blob limit, left out of the commits. */\n+\ttooBig: string[];\n+}\n+\n+export function absoVersion(message: string): number | undefined {\n+\tconst m = /^(?:abso|avcs)-version: (\\d+)\\s*$/m.exec(message);\n+\treturn m ? Number(m[1]) : undefined;\n+}\n+\n+async function readAccess(\n+\tartifacts: Artifacts,\n+\tproject: string,\n+): Promise<{ url: string; onAuth: () => { username: string; password: string } } | null> {\n+\tlet repo: Awaited<ReturnType<Artifacts[\"get\"]>>;\n+\ttry {\n+\t\trepo = await artifacts.get(repoName(project));\n+\t} catch {\n+\t\treturn null;\n+\t}\n+\tusing r = repo;\n+\tconst [info, token] = await Promise.all([r.info(), r.createToken(\"read\", 600)]);\n+\tconst password = token.plaintext.split(\"?expires=\")[0]!;\n+\treturn { url: info!.remote, onAuth: () => ({ username: \"x\", password }) };\n+}\n+\n+/** main's head on the project's repo, or null when there's no repo or no main yet. Cheap: one ref listing. */\n+export async function remoteHead(artifacts: Artifacts, project: string): Promise<string | null> {\n+\tconst access = await readAccess(artifacts, project);\n+\tif (!access) return null;\n+\tconst refs = await git.listServerRefs({ http, url: access.url, onAuth: access.onAuth, prefix: \"refs/heads/main\" });\n+\treturn refs.find((r) => r.ref === \"refs/heads/main\")?.oid ?? null;\n+}\n+\n+/**\n+ * The commits pushed since `seen` (the last head this project handled), or\n+ * none when every commit above the Worker's last one has been seen.\n+ */\n+/** Stores a binary file's bytes and answers their SHA-256, or null when they're over the limit. */\n+export type StoreBlob = (bytes: Uint8Array) => Promise<string | null>;\n+\n+/**\n+ * `oldBlob` gives shared's blob for a path: a binary file over the limit\n+ * keeps it, since a path missing from a commit would mean the file was deleted.\n+ */\n+export async function pushedSince(\n+\tartifacts: Artifacts,\n+\tproject: string,\n+\tseen: string | undefined,\n+\tstoreBlob?: StoreBlob,\n+\toldBlob: (path: string) => string | undefined = () => undefined,\n+): Promise<PushedCommits | null> {\n+\tconst access = await readAccess(artifacts, project);\n+\tif (!access) return null;\n+\tconst fs = new MemoryFS();\n+\tconst dir = \"/repo\";\n+\tawait git.clone({\n+\t\tfs,\n+\t\thttp,\n+\t\tdir,\n+\t\turl: access.url,\n+\t\tonAuth: access.onAuth,\n+\t\tref: \"main\",\n+\t\tsingleBranch: true,\n+\t\tdepth: DEPTH,\n+\t\tnoCheckout: true,\n+\t});\n+\tconst log = await git.log({ fs, dir, ref: \"main\", depth: DEPTH });\n+\tif (log.length === 0) return null;\n+\tconst head = log[0]!.oid;\n+\tconst fresh: typeof log = [];\n+\tlet base: number | undefined;\n+\tlet past = false;\n+\tfor (const c of log) {\n+\t\tif (c.oid === seen) past = true;\n+\t\tbase = absoVersion(c.commit.message);\n+\t\tif (base !== undefined) break;\n+\t\tif (!past) fresh.unshift(c);\n+\t}\n+\tif (base === undefined) throw new Error(`no abso-version commit in main's last ${DEPTH} commits`);\n+\tconst commits = [];\n+\tconst tooBig = new Set<string>();\n+\tfor (const c of fresh)\n+\t\tcommits.push({\n+\t\t\tsha: c.oid,\n+\t\t\tmessage: c.commit.message.trim(),\n+\t\t\t...(await treeText(fs, dir, c.oid, storeBlob, tooBig, oldBlob)),\n+\t\t});\n+\treturn { head, author: fresh.at(-1)?.commit.author.name ?? \"git\", base, commits, tooBig: [...tooBig] };\n+}\n+\n+/**\n+ * A commit's whole tree as text, and every file's mode: 100755 is exec, and\n+ * a link (120000) is \"\" with its target in modes. Files that aren't UTF-8\n+ * are left out.\n+ */\n+async function treeText(\n+\tfs: MemoryFS,\n+\tdir: string,\n+\toid: string,\n+\tstoreBlob: StoreBlob | undefined,\n+\ttooBig: Set<string>,\n+\toldBlob: (path: string) => string | undefined,\n+): Promise<{ files: Record<string, string>; modes: FileModes; blobs: Record<string, string> }> {\n+\tconst files: Record<string, string> = {};\n+\tconst modes: FileModes = {};\n+\tconst blobs: Record<string, string> = {};\n+\tawait git.walk({\n+\t\tfs,\n+\t\tdir,\n+\t\ttrees: [git.TREE({ ref: oid })],\n+\t\tmap: async (path, [entry]) => {\n+\t\t\tif (!entry || path === \".\") return true;\n+\t\t\tif ((await entry.type()) !== \"blob\") return true;\n+\t\t\tconst bytes = await entry.content();\n+\t\t\tif (!bytes) return true;\n+\t\t\tlet body: string;\n+\t\t\ttry {\n+\t\t\t\tbody = text.decode(bytes);\n+\t\t\t} catch {\n+\t\t\t\t// Binary (#27): the bytes go to the blob store, and the file is a pointer to them.\n+\t\t\t\tconst sha = storeBlob ? await storeBlob(bytes) : null;\n+\t\t\t\tif (sha) {\n+\t\t\t\t\tblobs[path] = sha;\n+\t\t\t\t\tmodes[path] = { exec: (await entry.mode()) === EXEC, link: null };\n+\t\t\t\t} else if (storeBlob) {\n+\t\t\t\t\ttooBig.add(path);\n+\t\t\t\t\tconst kept = oldBlob(path);\n+\t\t\t\t\tif (kept) blobs[path] = kept;\n+\t\t\t\t}\n+\t\t\t\treturn true;\n+\t\t\t}\n+\t\t\tconst mode = await entry.mode();\n+\t\t\tif (mode === LINK) {\n+\t\t\t\tfiles[path] = \"\";\n+\t\t\t\tmodes[path] = { exec: false, link: body };\n+\t\t\t} else {\n+\t\t\t\tfiles[path] = body;\n+\t\t\t\tmodes[path] = { exec: mode === EXEC, link: null };\n+\t\t\t}\n+\t\t\treturn true;\n+\t\t},\n+\t});\n+\treturn { files, modes, blobs };\n+}"},{"path":"server/src/issues-entry.ts","added":27,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/issues-entry.ts\n@@ -0,0 +1,27 @@\n+// Where the router meets issues, asks and news (server/src/issues/, built alongside this file). Until that folder\n+// lands, this is a stand-in with the same exports, so the Worker builds and its tests run. When it lands, this file\n+// becomes one line:\n+//\n+//   export { IssueProject, issuesFetch } from \"./issues/index.ts\";\n+//\n+// The agreed interface: issuesFetch(request, env, ctx, {project, rest, auth}), where rest is the path after\n+// /issues/p/<project> and auth is {kind: \"token\"} or {kind: \"key\", agent, role}. The router has checked auth before it\n+// calls. The issues code reaches the project through env.PROJECT and its RPC methods agents(project) and\n+// news(project, items) on ProjectObject.\n+\n+import { DurableObject } from \"cloudflare:workers\";\n+import type { Env } from \"./env.ts\";\n+import type { KeyRole } from \"./keys.ts\";\n+\n+export type IssuesAuth = { kind: \"token\" } | { kind: \"key\"; agent: string; role: KeyRole };\n+\n+export class IssueProject extends DurableObject<Env> {}\n+\n+export async function issuesFetch(\n+\t_request: Request,\n+\t_env: Env,\n+\t_ctx: ExecutionContext,\n+\t_where: { project: string; rest: string; auth: IssuesAuth },\n+): Promise<Response> {\n+\treturn Response.json({ error: \"issues aren't on this server yet\" }, { status: 404 });\n+}"},{"path":"server/src/keys.ts","added":253,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/keys.ts\n@@ -0,0 +1,253 @@\n+// Per-agent keys, ported from the platform's worker/src/keys.ts. They run when AGENT_KEYS is \"on\" and\n+// KEY_HMAC_SECRET is set. Each key belongs to one agent of one project; the project's Durable Object keeps only the\n+// key's HMAC, never the key. Without keys, the shared token (ABSO_TOKEN) is the only way in.\n+\n+export const KEY_PREFIX = \"abso_sk_\";\n+const FAIL_LIMIT = 8;\n+const FAIL_WINDOW_MS = 10 * 60 * 1000;\n+const AUDIT_CAP = 200;\n+const DAY_MS = 24 * 60 * 60 * 1000;\n+\n+export interface KeyEnv {\n+\tAGENT_KEYS?: string;\n+\tKEY_HMAC_SECRET?: string;\n+}\n+\n+/** What a key may do in its project: the admin's choice when it was issued. */\n+export type KeyRole = \"owner\" | \"writer\" | \"reader\";\n+\n+export interface KeyRow {\n+\tid: string;\n+\thmac: string;\n+\tagent: string;\n+\tissuedBy: string;\n+\tat: number;\n+\tlastUsed: number | null;\n+\trevokedAt: number | null;\n+\texpiresAt?: number | null;\n+\t/** Absent on a key issued before roles existed: it counts as reader, so it fails closed. */\n+\trole?: KeyRole;\n+}\n+\n+export interface FailRow {\n+\tn: number;\n+\tat: number;\n+}\n+\n+export interface AuditRow {\n+\tt: number;\n+\tkind: \"issue\" | \"revoke\" | \"use\" | \"fail\";\n+\tid: string | null;\n+\taddr: string;\n+}\n+\n+export interface KeyState {\n+\trows: KeyRow[];\n+\tfails: Record<string, FailRow>;\n+\tseen: Record<string, string>;\n+\taudit: AuditRow[];\n+}\n+\n+export function emptyKeyState(): KeyState {\n+\treturn { rows: [], fails: {}, seen: {}, audit: [] };\n+}\n+\n+/** Keys run when the switch and the secret are both set. */\n+export function keysEnabled(env: KeyEnv): boolean {\n+\treturn env.AGENT_KEYS === \"on\" && !!env.KEY_HMAC_SECRET;\n+}\n+\n+/** 90 days when omitted. 1d to 365d otherwise. */\n+export function expiresAt(now: number, raw: string | null): number | { error: string } {\n+\tif (raw === null || raw === \"\") return now + 90 * DAY_MS;\n+\tconst match = /^(\\d+)d$/.exec(raw);\n+\tif (!match) return { error: \"expires is a number of days, like 7d, from 1d to 365d\" };\n+\tconst days = Number(match[1]);\n+\tif (days < 1 || days > 365) return { error: \"expires is from 1d to 365d\" };\n+\treturn now + days * DAY_MS;\n+}\n+\n+export function isAgentKey(presented: string | undefined): boolean {\n+\treturn typeof presented === \"string\" && presented.startsWith(KEY_PREFIX) && presented.length > KEY_PREFIX.length;\n+}\n+\n+export async function hmac(secret: string, message: string): Promise<string> {\n+\tconst key = await crypto.subtle.importKey(\n+\t\t\"raw\",\n+\t\tnew TextEncoder().encode(secret),\n+\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n+\t\tfalse,\n+\t\t[\"sign\"],\n+\t);\n+\tconst mac = new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, new TextEncoder().encode(message)));\n+\treturn [...mac].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n+}\n+\n+/** Whether two strings are equal, taking the same time wherever they differ. */\n+export function timingSame(a: string, b: string): boolean {\n+\tif (a.length !== b.length) return false;\n+\tlet diff = 0;\n+\tfor (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n+\treturn diff === 0;\n+}\n+\n+function randomHex(bytes: number): string {\n+\tconst b = new Uint8Array(bytes);\n+\tcrypto.getRandomValues(b);\n+\treturn [...b].map((n) => n.toString(16).padStart(2, \"0\")).join(\"\");\n+}\n+\n+export function newKey(): { id: string; key: string } {\n+\tconst raw = new Uint8Array(32);\n+\tcrypto.getRandomValues(raw);\n+\tconst body = btoa(String.fromCharCode(...raw))\n+\t\t.replaceAll(\"+\", \"-\")\n+\t\t.replaceAll(\"/\", \"_\")\n+\t\t.replace(/=+$/, \"\");\n+\treturn { id: `k_${randomHex(4)}`, key: `${KEY_PREFIX}${body}` };\n+}\n+\n+function note(state: KeyState, row: AuditRow): void {\n+\tstate.audit.push(row);\n+\tif (state.audit.length > AUDIT_CAP) state.audit.splice(0, state.audit.length - AUDIT_CAP);\n+}\n+\n+export interface Issued {\n+\tid: string;\n+\tkey: string;\n+\tagent: string;\n+}\n+\n+/** Issues a key. The returned value is the only copy; the state keeps the HMAC. */\n+export async function issueKey(\n+\tstate: KeyState,\n+\tsecret: string,\n+\tagent: string,\n+\tby: string,\n+\tnow: number,\n+\taddress: string,\n+\texpires: number,\n+\trole: KeyRole,\n+): Promise<Issued> {\n+\tconst made = newKey();\n+\tconst addr = await hmac(secret, address);\n+\tstate.rows.push({\n+\t\tid: made.id,\n+\t\thmac: await hmac(secret, made.key),\n+\t\tagent,\n+\t\tissuedBy: by,\n+\t\tat: now,\n+\t\tlastUsed: null,\n+\t\trevokedAt: null,\n+\t\texpiresAt: expires,\n+\t\trole,\n+\t});\n+\tnote(state, { t: now, kind: \"issue\", id: made.id, addr });\n+\treturn { id: made.id, key: made.key, agent };\n+}\n+\n+export function revokeKey(state: KeyState, id: string, now: number, addr: string): boolean {\n+\tconst row = state.rows.find((r) => r.id === id);\n+\tif (!row || row.revokedAt !== null) return false;\n+\trow.revokedAt = now;\n+\tnote(state, { t: now, kind: \"revoke\", id, addr });\n+\treturn true;\n+}\n+\n+export function listKeys(state: KeyState, agent?: string) {\n+\treturn state.rows\n+\t\t.filter((r) => agent === undefined || r.agent === agent)\n+\t\t.map(({ id, agent: a, issuedBy, at, lastUsed, revokedAt, expiresAt: exp, role }) => ({\n+\t\t\tid,\n+\t\t\tagent: a,\n+\t\t\trole: role ?? \"reader\",\n+\t\t\tissuedBy,\n+\t\t\tat,\n+\t\t\tlastUsed,\n+\t\t\trevokedAt,\n+\t\t\texpiresAt: exp ?? null,\n+\t\t}));\n+}\n+\n+export type KeyDecision =\n+\t| { ok: true; id: string; as: string; role: KeyRole; dirty: boolean }\n+\t| { ok: false; status: number; error: string; dirty: boolean };\n+\n+/**\n+ * Checks a presented key against one project. The URL's agent must match the key's agent: a mismatch is a 403, and\n+ * the agent is not rewritten. A missing secret is a 503 that names no key. Failures are counted per address and\n+ * slowed after a few. Nothing returned or recorded contains the key.\n+ */\n+export async function checkKey(\n+\tstate: KeyState,\n+\tsecret: string | undefined,\n+\tpresented: string,\n+\tagent: string | undefined,\n+\tnow: number,\n+\taddress: string,\n+): Promise<KeyDecision> {\n+\tif (!secret) return { ok: false, status: 503, error: \"the key secret (KEY_HMAC_SECRET) is not set\", dirty: false };\n+\tconst addr = await hmac(secret, address);\n+\tconst fail = state.fails[addr];\n+\tif (fail && now - fail.at < FAIL_WINDOW_MS && fail.n >= FAIL_LIMIT) {\n+\t\treturn { ok: false, status: 429, error: \"too many failed keys; try again shortly\", dirty: false };\n+\t}\n+\tconst mac = await hmac(secret, presented);\n+\tconst row = state.rows.find((r) => timingSame(r.hmac, mac));\n+\tconst bump = () => {\n+\t\tconst cur = state.fails[addr];\n+\t\tstate.fails[addr] = !cur || now - cur.at >= FAIL_WINDOW_MS ? { n: 1, at: now } : { n: cur.n + 1, at: cur.at };\n+\t\tnote(state, { t: now, kind: \"fail\", id: row?.id ?? null, addr });\n+\t};\n+\tif (!row || row.revokedAt !== null || (row.expiresAt != null && now >= row.expiresAt)) {\n+\t\tbump();\n+\t\tconst error = !row\n+\t\t\t? \"that key is not for this project\"\n+\t\t\t: row.revokedAt !== null\n+\t\t\t\t? \"that key was revoked\"\n+\t\t\t\t: \"that key has expired\";\n+\t\treturn { ok: false, status: 403, error, dirty: true };\n+\t}\n+\tif (agent !== undefined && row.agent !== agent) {\n+\t\tbump();\n+\t\treturn { ok: false, status: 403, error: \"that key is not for this agent\", dirty: true };\n+\t}\n+\tlet dirty = false;\n+\tif (state.fails[addr]) {\n+\t\tdelete state.fails[addr];\n+\t\tdirty = true;\n+\t}\n+\tif (state.seen[row.id] !== addr) {\n+\t\tstate.seen[row.id] = addr;\n+\t\tnote(state, { t: now, kind: \"use\", id: row.id, addr });\n+\t\tdirty = true;\n+\t}\n+\tif (row.lastUsed === null || now - row.lastUsed >= 60_000) {\n+\t\trow.lastUsed = now;\n+\t\tdirty = true;\n+\t}\n+\treturn { ok: true, id: row.id, as: `key ${row.id}`, role: row.role ?? \"reader\", dirty };\n+}\n+\n+/** Project routes only an owner's key may use, whatever the method. */\n+const OWNER_ONLY = new Set([\"git-remote\", \"git-sync\", \"export\"]);\n+\n+/**\n+ * Whether a key's role allows a request. A reader only reads. A writer also writes, but only on its own agent's\n+ * routes (/a/:agent/..., where checkKey has matched the agent), and blob uploads, which a record needs. Owner-only\n+ * routes need an owner's key.\n+ */\n+export function keyAllows(\n+\trole: KeyRole,\n+\trequest: { write: boolean; agent: string | undefined; route: string | undefined; method?: string },\n+): { ok: true } | { ok: false; status: number; error: string } {\n+\tif (role === \"owner\") return { ok: true };\n+\tif (request.route !== undefined && OWNER_ONLY.has(request.route))\n+\t\treturn { ok: false, status: 403, error: `${request.route} needs an owner's key` };\n+\tif (!request.write) return { ok: true };\n+\tif (role === \"reader\") return { ok: false, status: 403, error: \"this key only reads\" };\n+\tif (request.method === \"PUT\" && /^blobs\\/[0-9a-f]{64}$/.test(request.route ?? \"\")) return { ok: true };\n+\tif (request.agent === undefined)\n+\t\treturn { ok: false, status: 403, error: \"a writer's key writes only on its own agent's routes\" };\n+\treturn { ok: true };\n+}"},{"path":"server/src/memory-fs.ts","added":235,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/memory-fs.ts\n@@ -0,0 +1,235 @@\n+// From Cloudflare's isomorphic-git example, with fixes isomorphic-git 1.43\n+// needs: errors carry .code (isomorphic-git checks err.code === \"ENOENT\"),\n+// stats are plain fields it can normalize in place, and the executable bit\n+// and symbolic links are kept (#27), so a checkout of a repo with either works.\n+\n+function fsError(code: string, path: string): Error {\n+\treturn Object.assign(new Error(`${code}: ${path}`), { code });\n+}\n+\n+type Entry =\n+\t| { kind: \"dir\"; children: Set<string>; mtimeMs: number }\n+\t| { kind: \"file\"; data: Uint8Array; exec: boolean; mtimeMs: number }\n+\t| { kind: \"link\"; target: string; mtimeMs: number };\n+\n+const enc = new TextEncoder();\n+\n+/** Plain fields, not getters: isomorphic-git writes to them when it normalizes stats. */\n+class MemoryStats {\n+\tsize: number;\n+\tmtimeMs: number;\n+\tctimeMs: number;\n+\tmode: number;\n+\tprivate kind: Entry[\"kind\"];\n+\n+\tconstructor(entry: Entry) {\n+\t\tthis.kind = entry.kind;\n+\t\tthis.size =\n+\t\t\tentry.kind === \"file\" ? entry.data.byteLength : entry.kind === \"link\" ? enc.encode(entry.target).byteLength : 0;\n+\t\tthis.mtimeMs = entry.mtimeMs;\n+\t\tthis.ctimeMs = entry.mtimeMs;\n+\t\tthis.mode = entry.kind === \"dir\" ? 0o040000 : entry.kind === \"link\" ? 0o120000 : entry.exec ? 0o100755 : 0o100644;\n+\t}\n+\n+\tisFile() {\n+\t\treturn this.kind === \"file\";\n+\t}\n+\n+\tisDirectory() {\n+\t\treturn this.kind === \"dir\";\n+\t}\n+\n+\tisSymbolicLink() {\n+\t\treturn this.kind === \"link\";\n+\t}\n+}\n+\n+export class MemoryFS {\n+\tencoder = new TextEncoder();\n+\tdecoder = new TextDecoder();\n+\tentries = new Map<string, Entry>([[\"/\", { kind: \"dir\", children: new Set(), mtimeMs: Date.now() }]]);\n+\n+\tpromises = {\n+\t\treadFile: this.readFile.bind(this),\n+\t\twriteFile: this.writeFile.bind(this),\n+\t\tunlink: this.unlink.bind(this),\n+\t\treaddir: this.readdir.bind(this),\n+\t\tmkdir: this.mkdir.bind(this),\n+\t\trmdir: this.rmdir.bind(this),\n+\t\tstat: this.stat.bind(this),\n+\t\tlstat: this.lstat.bind(this),\n+\t\treadlink: this.readlink.bind(this),\n+\t\tsymlink: this.symlink.bind(this),\n+\t\tchmod: this.chmod.bind(this),\n+\t};\n+\n+\tnormalize(input: string) {\n+\t\tconst segments: string[] = [];\n+\n+\t\tfor (const part of input.split(\"/\")) {\n+\t\t\tif (!part || part === \".\") {\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\n+\t\t\tif (part === \"..\") {\n+\t\t\t\tsegments.pop();\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\n+\t\t\tsegments.push(part);\n+\t\t}\n+\n+\t\treturn `/${segments.join(\"/\")}` || \"/\";\n+\t}\n+\n+\tparent(path: string) {\n+\t\tconst normalized = this.normalize(path);\n+\t\tif (normalized === \"/\") {\n+\t\t\treturn \"/\";\n+\t\t}\n+\n+\t\tconst parts = normalized.split(\"/\").filter(Boolean);\n+\t\tparts.pop();\n+\t\treturn parts.length ? `/${parts.join(\"/\")}` : \"/\";\n+\t}\n+\n+\tbasename(path: string) {\n+\t\treturn this.normalize(path).split(\"/\").filter(Boolean).pop() ?? \"\";\n+\t}\n+\n+\tgetEntry(path: string) {\n+\t\treturn this.entries.get(this.normalize(path));\n+\t}\n+\n+\trequireEntry(path: string) {\n+\t\tconst entry = this.getEntry(path);\n+\t\tif (!entry) {\n+\t\t\tthrow fsError(\"ENOENT\", path);\n+\t\t}\n+\n+\t\treturn entry;\n+\t}\n+\n+\trequireDir(path: string) {\n+\t\tconst entry = this.requireEntry(path);\n+\t\tif (entry.kind !== \"dir\") {\n+\t\t\tthrow fsError(\"ENOTDIR\", path);\n+\t\t}\n+\n+\t\treturn entry;\n+\t}\n+\n+\tasync mkdir(path: string, options?: { recursive?: boolean } | number) {\n+\t\tconst target = this.normalize(path);\n+\t\tif (target === \"/\") {\n+\t\t\treturn;\n+\t\t}\n+\n+\t\tconst recursive = typeof options === \"object\" && options !== null && options.recursive;\n+\t\tconst parent = this.parent(target);\n+\n+\t\tif (!this.entries.has(parent)) {\n+\t\t\tif (!recursive) {\n+\t\t\t\tthrow fsError(\"ENOENT\", parent);\n+\t\t\t}\n+\n+\t\t\tawait this.mkdir(parent, { recursive: true });\n+\t\t}\n+\n+\t\tif (this.entries.has(target)) {\n+\t\t\treturn;\n+\t\t}\n+\n+\t\tthis.entries.set(target, {\n+\t\t\tkind: \"dir\",\n+\t\t\tchildren: new Set(),\n+\t\t\tmtimeMs: Date.now(),\n+\t\t});\n+\n+\t\tthis.requireDir(parent).children.add(this.basename(target));\n+\t}\n+\n+\t/** options.mode with any execute bit (isomorphic-git passes 0o777 for 100755) makes the file executable. */\n+\tasync writeFile(path: string, data: string | Uint8Array | ArrayBuffer, options?: string | { mode?: number }) {\n+\t\tconst target = this.normalize(path);\n+\t\tawait this.mkdir(this.parent(target), { recursive: true });\n+\n+\t\tconst bytes =\n+\t\t\ttypeof data === \"string\" ? this.encoder.encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data);\n+\t\tconst mode = typeof options === \"object\" && options !== null ? options.mode : undefined;\n+\n+\t\tthis.entries.set(target, {\n+\t\t\tkind: \"file\",\n+\t\t\tdata: bytes,\n+\t\t\texec: mode !== undefined && (mode & 0o111) !== 0,\n+\t\t\tmtimeMs: Date.now(),\n+\t\t});\n+\n+\t\tthis.requireDir(this.parent(target)).children.add(this.basename(target));\n+\t}\n+\n+\tasync readFile(path: string, options?: string | { encoding?: string }) {\n+\t\tconst entry = this.requireEntry(path);\n+\t\tif (entry.kind === \"dir\") {\n+\t\t\tthrow fsError(\"EISDIR\", path);\n+\t\t}\n+\n+\t\tconst data = entry.kind === \"link\" ? this.encoder.encode(entry.target) : entry.data;\n+\t\tconst encoding = typeof options === \"string\" ? options : options?.encoding;\n+\t\treturn encoding ? this.decoder.decode(data) : data;\n+\t}\n+\n+\tasync readdir(path: string) {\n+\t\treturn [...this.requireDir(path).children].sort();\n+\t}\n+\n+\tasync unlink(path: string) {\n+\t\tconst target = this.normalize(path);\n+\t\tconst entry = this.requireEntry(target);\n+\t\tif (entry.kind === \"dir\") {\n+\t\t\tthrow fsError(\"EISDIR\", path);\n+\t\t}\n+\n+\t\tthis.entries.delete(target);\n+\t\tthis.requireDir(this.parent(target)).children.delete(this.basename(target));\n+\t}\n+\n+\tasync rmdir(path: string) {\n+\t\tconst target = this.normalize(path);\n+\t\tconst entry = this.requireDir(target);\n+\t\tif (entry.children.size > 0) {\n+\t\t\tthrow fsError(\"ENOTEMPTY\", path);\n+\t\t}\n+\n+\t\tthis.entries.delete(target);\n+\t\tthis.requireDir(this.parent(target)).children.delete(this.basename(target));\n+\t}\n+\n+\tasync stat(path: string) {\n+\t\treturn new MemoryStats(this.requireEntry(path));\n+\t}\n+\n+\t/** Links aren't followed anywhere here, so lstat and stat agree. */\n+\tasync lstat(path: string) {\n+\t\treturn this.stat(path);\n+\t}\n+\n+\tasync readlink(path: string): Promise<string> {\n+\t\tconst entry = this.requireEntry(path);\n+\t\tif (entry.kind !== \"link\") throw fsError(\"EINVAL\", path);\n+\t\treturn entry.target;\n+\t}\n+\n+\tasync symlink(target: string, path: string): Promise<void> {\n+\t\tconst at = this.normalize(path);\n+\t\tif (this.entries.has(at)) throw fsError(\"EEXIST\", path);\n+\t\tawait this.mkdir(this.parent(at), { recursive: true });\n+\t\tthis.entries.set(at, { kind: \"link\", target, mtimeMs: Date.now() });\n+\t\tthis.requireDir(this.parent(at)).children.add(this.basename(at));\n+\t}\n+\n+\tasync chmod(path: string, mode: number): Promise<void> {\n+\t\tconst entry = this.requireEntry(path);\n+\t\tif (entry.kind === \"file\") entry.exec = (mode & 0o111) !== 0;\n+\t}\n+}"},{"path":"server/src/project-object.ts","added":534,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/project-object.ts\n@@ -0,0 +1,534 @@\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 { 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 { EngineProject, SqliteLog } from \"./engine-project.ts\";\n+import { artifactsOf, type Env } from \"./env.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+\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+\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+\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}\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+\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.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): Promise<Answer> {\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}\n+\t\tif (op === \"feed\" && !inFeed) return this.feed(name, body);\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\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\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 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);\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\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} catch (e) {\n+\t\t\tresult = { error: e instanceof Error ? e.message : String(e) };\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\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\tawait this.gitSync().then(\n+\t\t\t() => this.ctx.storage.delete(\"git:error\"),\n+\t\t\t(e) =>\n+\t\t\t\tthis.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);\n+\t\tconst shared = this.project.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+\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(artifacts, name, shared, (sha) => this.blobs.read(sha));\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.project.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\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\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\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\tconst p = this.ensure();\n+\t\tif (!p?.exists()) return [];\n+\t\treturn 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\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\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}\n+}"},{"path":"server/src/push.ts","added":256,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/push.ts\n@@ -0,0 +1,256 @@\n+// Out to Artifacts (#8): shared's files as one git commit on main of the\n+// project's repo, with the publish message and the agent as author. The repo\n+// is created on first use. isomorphic-git works in an in-memory filesystem:\n+// a depth-1 clone of main with nothing checked out, then a new tree from\n+// shared's files that compresses and writes only what changed (abso issue 293).\n+import git from \"isomorphic-git\";\n+import http from \"isomorphic-git/http/web\";\n+import type { FileModes } from \"../../worker/project/project-api.ts\";\n+import { MemoryFS } from \"./memory-fs.ts\";\n+\n+export interface PushResult {\n+\trepo: string;\n+\tremote: string;\n+\tcommit: string;\n+\tversion: number;\n+\tms: number;\n+}\n+\n+/** New blob bytes per push before the push out splits into parts: Artifacts refuses a push much over 20 MB. */\n+const PUSH_BATCH = 16 * 1024 * 1024;\n+\n+/** A file as a tree entry holds it: its blob and its mode (\"100644\", \"100755\", \"120000\"). */\n+export interface TreeFile {\n+\toid: string;\n+\tmode: string;\n+}\n+\n+/** Every file in a tree, and every folder's tree oid (\"\" is the root), read from tree objects only. */\n+export async function readTreeFiles(\n+\tfs: MemoryFS,\n+\tdir: string,\n+\toid: string,\n+\tprefix = \"\",\n+\tfiles = new Map<string, TreeFile>(),\n+\ttrees = new Map<string, string>(),\n+): Promise<{ files: Map<string, TreeFile>; trees: Map<string, string> }> {\n+\ttrees.set(prefix, oid);\n+\tconst { tree } = await git.readTree({ fs, dir, oid });\n+\tfor (const e of tree) {\n+\t\tconst path = prefix === \"\" ? e.path : `${prefix}/${e.path}`;\n+\t\tif (e.type === \"tree\") await readTreeFiles(fs, dir, e.oid, path, files, trees);\n+\t\telse if (e.type === \"blob\") files.set(path, { oid: e.oid, mode: e.mode });\n+\t}\n+\treturn { files, trees };\n+}\n+\n+/**\n+ * A blob's git oid, with the platform's SHA-1 (abso issue 293): native and awaited, so hashing every file of a big\n+ * project neither burns the object's CPU in JavaScript nor holds its other requests back for long.\n+ */\n+export async function blobOid(bytes: Uint8Array): Promise<string> {\n+\tconst head = new TextEncoder().encode(`blob ${bytes.byteLength}\\0`);\n+\tconst all = new Uint8Array(head.byteLength + bytes.byteLength);\n+\tall.set(head);\n+\tall.set(bytes, head.byteLength);\n+\tconst d = new Uint8Array(await crypto.subtle.digest(\"SHA-1\", all));\n+\treturn [...d].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n+}\n+\n+const parentOf = (path: string) => {\n+\tconst cut = path.lastIndexOf(\"/\");\n+\treturn cut < 0 ? \"\" : path.slice(0, cut);\n+};\n+\n+/**\n+ * The tree for `files`, written bottom up. A folder with nothing changed under it keeps its old tree oid (`before`),\n+ * so only the folders on a changed path are written again.\n+ */\n+export async function writeTrees(\n+\tfs: MemoryFS,\n+\tdir: string,\n+\tfiles: Map<string, TreeFile>,\n+\tbefore: Map<string, string>,\n+\tchanged: Set<string>,\n+): Promise<string> {\n+\tconst dirty = new Set<string>([\"\"]);\n+\tfor (const path of changed) for (let d = parentOf(path); d !== \"\"; d = parentOf(d)) dirty.add(d);\n+\ttype Entry = { mode: string; oid: string; type: \"blob\" | \"tree\" };\n+\tconst kids = new Map<string, Map<string, Entry>>([[\"\", new Map()]]);\n+\tconst folder = (d: string) => {\n+\t\tlet k = kids.get(d);\n+\t\tif (!k) {\n+\t\t\tkids.set(d, (k = new Map()));\n+\t\t\tif (d !== \"\") folder(parentOf(d));\n+\t\t}\n+\t\treturn k;\n+\t};\n+\tfor (const [path, f] of files)\n+\t\tfolder(parentOf(path)).set(path.slice(path.lastIndexOf(\"/\") + 1), { ...f, type: \"blob\" });\n+\t// Deepest first, so a folder's subfolders have their oids before it is written.\n+\tconst depth = (d: string) => (d === \"\" ? 0 : d.split(\"/\").length);\n+\tconst order = [...kids.keys()].sort((a, b) => depth(b) - depth(a));\n+\tlet root = \"\";\n+\tfor (const d of order) {\n+\t\tconst old = before.get(d);\n+\t\tconst oid =\n+\t\t\told !== undefined && !dirty.has(d)\n+\t\t\t\t? old\n+\t\t\t\t: await git.writeTree({ fs, dir, tree: [...kids.get(d)!].map(([path, e]) => ({ path, ...e })) });\n+\t\tif (d === \"\") root = oid;\n+\t\telse folder(parentOf(d)).set(d.slice(d.lastIndexOf(\"/\") + 1), { mode: \"040000\", oid, type: \"tree\" });\n+\t}\n+\treturn root;\n+}\n+\n+/**\n+ * A project's Artifacts repo: abso-<project>. Project names are letters, digits, \".\", \"_\" and \"-\" (validName), which\n+ * repo names take as they are.\n+ */\n+export function repoName(project: string): string {\n+\treturn `abso-${project}`;\n+}\n+\n+/** The project one of our repos holds, or null for a repo that isn't ours. */\n+export function projectOfRepo(repo: string): string | null {\n+\treturn repo.startsWith(\"abso-\") && repo.length > \"abso-\".length ? repo.slice(\"abso-\".length) : null;\n+}\n+\n+/** The repo's remote and a write token good for `seconds`, creating the repo if it's new. */\n+export async function writeAccess(\n+\tartifacts: Artifacts,\n+\tname: string,\n+\tseconds = 600,\n+): Promise<{ remote: string; secret: string }> {\n+\ttry {\n+\t\tusing repo = await artifacts.get(name);\n+\t\tconst [info, token] = await Promise.all([repo.info(), repo.createToken(\"write\", seconds)]);\n+\t\treturn { remote: info!.remote, secret: token.plaintext.split(\"?expires=\")[0]! };\n+\t} catch {\n+\t\tconst created = await artifacts.create(name, { description: `abso project ${name}`, setDefaultBranch: \"main\" });\n+\t\treturn { remote: created.remote, secret: created.token.split(\"?expires=\")[0]! };\n+\t}\n+}\n+\n+export interface SharedFiles {\n+\tversion: number;\n+\tfiles: Record<string, string>;\n+\tmodes?: FileModes;\n+\tblobs?: Record<string, string>;\n+\tlast?: { agent: string; message: string };\n+}\n+\n+/**\n+ * Shared's files as commits on top of `head` (null: a repo with no main yet), in the repo at `dir`. `part` is called\n+ * with each earlier part's commit when the new blobs are too big for one push. Answers the last commit and how many\n+ * paths changed.\n+ */\n+export async function commitShared(\n+\tfs: MemoryFS,\n+\tdir: string,\n+\thead: string | null,\n+\tshared: SharedFiles,\n+\treadBlob: (sha256: string) => Uint8Array | null,\n+\tpart: (commit: string) => Promise<void> = async () => {},\n+): Promise<{ commit: string; changed: number }> {\n+\tconst old = head\n+\t\t? await readTreeFiles(fs, dir, (await git.readCommit({ fs, dir, oid: head })).commit.tree)\n+\t\t: { files: new Map<string, TreeFile>(), trees: new Map<string, string>() };\n+\tconst blobs = shared.blobs ?? {};\n+\tconst now = new Map<string, TreeFile>();\n+\tconst changed = new Set<string>();\n+\tfor (const path of old.files.keys()) if (!(path in shared.files) && !(path in blobs)) changed.add(path);\n+\t// A file whose blob and mode match the last push keeps its entry; only a new blob is compressed and written.\n+\tconst put = async (path: string, bytes: Uint8Array, mode: string, oid: string) => {\n+\t\tconst was = old.files.get(path);\n+\t\tif (was?.oid !== oid) await git.writeBlob({ fs, dir, blob: bytes });\n+\t\tif (was?.oid !== oid || was.mode !== mode) changed.add(path);\n+\t\tnow.set(path, { oid, mode });\n+\t};\n+\t// Each file goes into the tree as a blob with its mode (#27): 100755 for exec, 120000 for a link, whose blob is\n+\t// its target.\n+\tconst enc = new TextEncoder();\n+\tfor (const [path, text] of Object.entries(shared.files)) {\n+\t\tconst mode = shared.modes?.[path];\n+\t\tconst link = typeof mode?.link === \"string\" ? mode.link : null;\n+\t\tconst bytes = enc.encode(link ?? text);\n+\t\tawait put(path, bytes, link !== null ? \"120000\" : mode?.exec ? \"100755\" : \"100644\", await blobOid(bytes));\n+\t}\n+\tconst agent = shared.last?.agent ?? \"abso\";\n+\tconst author = { name: agent, email: `${agent}@abso.invalid` };\n+\tconst committer = { name: \"abso\", email: \"abso@abso.invalid\" };\n+\tconst say = (p: string) => `${shared.last?.message ?? \"Start the project\"}${p}\\n\\nabso-version: ${shared.version}\\n`;\n+\tlet parent = head;\n+\t// A part holds what's written so far, and the last push's entries for the binary files not reached yet.\n+\tconst commitNow = async (message: string) => {\n+\t\tconst files = new Map(now);\n+\t\tfor (const [path, f] of old.files) if (!files.has(path) && path in blobs) files.set(path, f);\n+\t\tconst tree = await writeTrees(fs, dir, files, old.trees, changed);\n+\t\tparent = await git.commit({\n+\t\t\tfs,\n+\t\t\tdir,\n+\t\t\tmessage,\n+\t\t\tauthor,\n+\t\t\tcommitter,\n+\t\t\ttree,\n+\t\t\tparent: parent ? [parent] : [],\n+\t\t\tref: \"main\",\n+\t\t});\n+\t\treturn parent;\n+\t};\n+\t// Binary files (#27) aren't in files: their bytes come from the blob store.\n+\t// Artifacts refuses a push much over 20 MB, so when the new blobs add up\n+\t// to more than PUSH_BATCH, the earlier ones go in commits of their own\n+\t// first. Every part carries abso-version, so intake never takes them in.\n+\tlet pending = 0;\n+\tlet parts = 0;\n+\tfor (const [path, sha] of Object.entries(blobs)) {\n+\t\tconst bytes = readBlob(sha);\n+\t\tif (!bytes) throw new Error(`${path}: blob ${sha} is missing from the project's store`);\n+\t\tconst oid = await blobOid(bytes);\n+\t\tconst fresh = old.files.get(path)?.oid !== oid;\n+\t\tif (fresh && pending > 0 && pending + bytes.byteLength > PUSH_BATCH) {\n+\t\t\tawait part(await commitNow(say(` (part ${++parts})`)));\n+\t\t\tpending = 0;\n+\t\t}\n+\t\tif (fresh) pending += bytes.byteLength;\n+\t\tawait put(path, bytes, shared.modes?.[path]?.exec ? \"100755\" : \"100644\", oid);\n+\t}\n+\tconst commit = await commitNow(say(parts > 0 ? ` (part ${parts + 1}, last)` : \"\"));\n+\treturn { commit, changed: changed.size };\n+}\n+\n+export async function pushShared(\n+\tartifacts: Artifacts,\n+\tproject: string,\n+\tshared: SharedFiles,\n+\t/** A binary file's bytes by SHA-256 (#27), from the project's blob store. */\n+\treadBlob: (sha256: string) => Uint8Array | null = () => null,\n+): Promise<PushResult> {\n+\tconst t0 = Date.now();\n+\tconst name = repoName(project);\n+\tconst { remote, secret } = await writeAccess(artifacts, name);\n+\tconst onAuth = () => ({ username: \"x\", password: secret });\n+\tlet fs = new MemoryFS();\n+\tconst dir = \"/repo\";\n+\t// A new repo has no main yet. isomorphic-git \"clones\" an empty repo without\n+\t// an error but leaves HEAD on master, so check for main and start clean.\n+\t// Nothing is checked out: the new tree is built from tree objects (293).\n+\tconst head = await git\n+\t\t.clone({ fs, http, dir, url: remote, ref: \"main\", singleBranch: true, depth: 1, noCheckout: true, onAuth })\n+\t\t.then(() => git.resolveRef({ fs, dir, ref: \"main\" }))\n+\t\t.catch(() => null);\n+\tif (head === null) {\n+\t\tfs = new MemoryFS();\n+\t\tawait git.init({ fs, dir, defaultBranch: \"main\" });\n+\t}\n+\tconst t1 = Date.now();\n+\tconst push = () => git.push({ fs, http, dir, url: remote, ref: \"main\", remoteRef: \"main\", onAuth });\n+\tconst { commit, changed } = await commitShared(fs, dir, head, shared, readBlob, async () => void (await push()));\n+\tconst t2 = Date.now();\n+\tawait push();\n+\tconsole.log(\n+\t\t`push ${project} v${shared.version}: clone ${t1 - t0} ms, files ${t2 - t1} ms (${changed} changed), push ${Date.now() - t2} ms`,\n+\t);\n+\treturn { repo: name, remote, commit, version: shared.version, ms: Date.now() - t0 };\n+}"},{"path":"server/src/router.ts","added":299,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/router.ts\n@@ -0,0 +1,299 @@\n+// The open server's router (index.ts is the Worker's entry). abso's open server: one Worker that anyone deploys to their own Cloudflare account (`cd server && npx wrangler\n+// deploy`). Every project is a Durable Object named by the project's name; its shared is pushed out to an Artifacts\n+// repo abso-<project>. The routes are the platform's core routes, so the stock client works against it:\n+//\n+//   GET  /version                          the deployed version's tag; no token needed\n+//   /p/<project>/<read or init>            init, status, log, show, file, blame, feed and the other reads (http.ts)\n+//   /p/<project>/a/<agent>/<op>            an agent's calls: record, publish, sync, draft, land, announce, ...\n+//   GET  /p/<project>/head                 shared's newest version, read from storage without loading the project\n+//   PUT|GET /p/<project>/blobs/<sha256>    a binary file's bytes; a PUT whose bytes don't hash to the name is refused\n+//   GET  /p/<project>/out                  the push out to Artifacts: repo, last version pushed, plain-git intake\n+//   POST /p/<project>/git-remote           the repo's remote and a write token good for an hour, for plain git\n+//   POST /p/<project>/git-sync             takes in commits pushed with plain git now (the alarm also does)\n+//   GET  /p/<project>/export?from=&limit=  the log as JSON lines, for backups\n+//   /issues/p/<project>/...                issues, asks and news (issues-entry.ts)\n+//   GET|POST /admin/agent-keys?project=    per-agent keys: list, or issue (?agent=&role=&expires=); POST .../revoke?id=\n+//\n+// Every route but /version needs Authorization: Bearer <ABSO_TOKEN>, or an agent's key when AGENT_KEYS is on. With no\n+// ABSO_TOKEN set, the server refuses every call.\n+\n+import { type Answer, validName } from \"../../worker/project/http.ts\";\n+import { artifactsOf, type Env, secret } from \"./env.ts\";\n+import type { IssuesAuth, issuesFetch } from \"./issues-entry.ts\";\n+import { isAgentKey, type KeyRole, keyAllows, keysEnabled, timingSame } from \"./keys.ts\";\n+import type { KeyForCall } from \"./project-object.ts\";\n+import { repoName, writeAccess } from \"./push.ts\";\n+\n+const AGENT_OPS =\n+\t\"edit|record|publish|sync|draft|draft-sync|land|pluck|amend|diff|restore|drop|label|announce|news|note|note-close|move|starting|reader|files|status|unqueue\";\n+const TOP_ROUTES =\n+\t\"init|status|head|out|export|blobs/[^/]+|git-sync|git-remote|blame|why|tree|path|follow|collisions|draft-state|where|feed|drafts|diff|ribbon|position|changes|notes|change/[0-9]{1,12}|refusals|labels|files|announce|log|show|file|compare|visibility|ci|queue\";\n+\n+/** A project's routes: the project, the top-level route, and an agent's name and op under /a/. */\n+export const PROJECT_ROUTE = new RegExp(`^/p/([^/]+)/(${TOP_ROUTES}|a/([^/]+)/(${AGENT_OPS}))$`);\n+/** Issues, asks and news: the project and the rest of the path, handed to the issues code. */\n+export const ISSUES_ROUTE = /^\\/issues\\/p\\/([^/]+)(\\/.*)?$/;\n+\n+/** Routes answered here or by a direct object method, not through the project call. */\n+const DIRECT = new Set([\"head\", \"out\", \"export\", \"git-remote\", \"git-sync\", \"ci\", \"queue\", \"visibility\"]);\n+/** Reads whose query string is the call's body. */\n+const QUERY_READS = 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+const SHA = /^[0-9a-f]{64}$/;\n+\n+const json = (status: number, body: unknown) =>\n+\tResponse.json(body, { status, headers: { \"cache-control\": \"no-store\" } });\n+\n+/** Whether two secrets match, in constant time whatever their lengths: their SHA-256 digests are compared. */\n+export async function sameSecret(a: string, b: string): Promise<boolean> {\n+\tconst digest = async (s: string) =>\n+\t\t[...new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(s)))]\n+\t\t\t.map((n) => n.toString(16).padStart(2, \"0\"))\n+\t\t\t.join(\"\");\n+\treturn timingSame(await digest(a), await digest(b));\n+}\n+\n+export type Caller = { kind: \"token\" } | { kind: \"key\"; presented: string };\n+\n+/**\n+ * Who is calling: the shared token, or an agent key to be checked by its project. A Response is a refusal. With no\n+ * shared token set, everything is refused.\n+ */\n+export async function authorize(request: Request, env: Env): Promise<Caller | Response> {\n+\tconst shared = secret(env, \"TOKEN\");\n+\tif (!shared)\n+\t\treturn json(503, {\n+\t\t\terror:\n+\t\t\t\t\"this server has no ABSO_TOKEN set, so it refuses every call; set one with npx wrangler secret put ABSO_TOKEN\",\n+\t\t});\n+\tconst presented = (request.headers.get(\"authorization\") ?? \"\").replace(/^Bearer /, \"\");\n+\tif (presented && isAgentKey(presented) && keysEnabled(env)) return { kind: \"key\", presented };\n+\tif (presented && (await sameSecret(presented, shared))) return { kind: \"token\" };\n+\treturn json(401, { error: \"missing or wrong token\" });\n+}\n+\n+/** The x-abso-admin header against ABSO_ADMIN_TOKEN, in constant time. */\n+async function isAdmin(request: Request, env: Env): Promise<boolean> {\n+\tconst token = secret(env, \"ADMIN_TOKEN\");\n+\tconst sent = request.headers.get(\"x-abso-admin\") ?? request.headers.get(\"x-avcs-admin\");\n+\treturn !!token && !!sent && (await sameSecret(sent, token));\n+}\n+\n+const addressOf = (request: Request) => request.headers.get(\"cf-connecting-ip\") ?? \"unknown\";\n+const projectObject = (env: Env, project: string) => env.PROJECT.get(env.PROJECT.idFromName(project));\n+\n+/** Per-agent keys for one project: list (GET), issue (POST ?agent=&role=&expires=), revoke (POST .../revoke?id=). */\n+async function agentKeys(request: Request, env: Env, url: URL, caller: Caller): Promise<Response> {\n+\tif (!keysEnabled(env))\n+\t\treturn json(404, { error: \"agent keys are off here: AGENT_KEYS=on and KEY_HMAC_SECRET turn them on\" });\n+\tif (caller.kind !== \"token\") return json(401, { error: \"missing or wrong token\" });\n+\tif (!(await isAdmin(request, env))) return json(403, { error: \"agent keys need x-abso-admin: <the admin token>\" });\n+\tconst project = url.searchParams.get(\"project\") ?? \"\";\n+\tif (!validName(project)) return json(400, { error: \"agent keys need ?project=<name>\" });\n+\tconst obj = projectObject(env, project);\n+\tif (url.pathname === \"/admin/agent-keys/revoke\") {\n+\t\tif (request.method !== \"POST\") return json(405, { error: \"revoking a key is a POST\" });\n+\t\treturn json(200, await obj.revokeAgentKey(url.searchParams.get(\"id\") ?? \"\", addressOf(request)));\n+\t}\n+\tif (request.method === \"GET\")\n+\t\treturn json(200, { keys: await obj.listAgentKeys(url.searchParams.get(\"agent\") ?? undefined) });\n+\tif (request.method !== \"POST\") return json(405, { error: \"agent keys take GET or POST\" });\n+\tconst agent = url.searchParams.get(\"agent\") ?? \"\";\n+\tif (!validName(agent)) return json(400, { error: \"issuing a key needs ?agent=<name>\" });\n+\tconst role = url.searchParams.get(\"role\") ?? \"writer\";\n+\tif (role !== \"owner\" && role !== \"writer\" && role !== \"reader\")\n+\t\treturn json(400, { error: \"role is owner, writer or reader\" });\n+\tconst issued = await obj.issueAgentKey(agent, addressOf(request), url.searchParams.get(\"expires\"), role);\n+\treturn \"error\" in issued ? json(400, issued) : json(200, issued);\n+}\n+\n+/** The engine's ci and queue reads, for a server with neither: empty, so status and log say nothing about them. */\n+const NO_CI = { latest: null, checked: null, running: null, red: null, behind: null };\n+const NO_QUEUE = { items: [], paused: null };\n+\n+async function projectRoute(\n+\trequest: Request,\n+\tenv: Env,\n+\turl: URL,\n+\tcaller: Caller,\n+\tmatch: RegExpExecArray,\n+): Promise<Response> {\n+\tconst [, project, top, agent, op] = match as unknown as [\n+\t\tstring,\n+\t\tstring,\n+\t\tstring,\n+\t\tstring | undefined,\n+\t\tstring | undefined,\n+\t];\n+\tif (!validName(project)) return json(400, { error: \"project names use letters, digits, '.', '_' and '-'\" });\n+\tconst obj = projectObject(env, project);\n+\tconst route = agent === undefined ? top : op;\n+\tconst write = request.method !== \"GET\" && request.method !== \"HEAD\";\n+\tconst blob = top.startsWith(\"blobs/\");\n+\tlet keyForCall: KeyForCall | undefined;\n+\tlet how: string | undefined;\n+\tif (caller.kind === \"key\") {\n+\t\tif (DIRECT.has(top) || blob) {\n+\t\t\tconst decided = await obj.checkAgentKey(caller.presented, agent, addressOf(request));\n+\t\t\tif (!decided.ok) return json(decided.status, { error: decided.error });\n+\t\t\tconst allowed = keyAllows(decided.role, { write, agent, route, method: request.method });\n+\t\t\tif (!allowed.ok) return json(allowed.status, { error: allowed.error });\n+\t\t\thow = decided.as;\n+\t\t} else keyForCall = { presented: caller.presented, address: addressOf(request), write, route };\n+\t}\n+\n+\tif (top === \"head\") {\n+\t\tif (request.method !== \"GET\") return json(405, { error: \"head is a GET\" });\n+\t\tconst head = await obj.head();\n+\t\treturn head ? json(200, head) : json(404, { error: \"no such project; run init first\" });\n+\t}\n+\tif (top === \"out\") return json(200, await obj.out());\n+\tif (top === \"ci\") return json(200, NO_CI);\n+\tif (top === \"queue\") return json(200, NO_QUEUE);\n+\tif (top === \"visibility\") {\n+\t\tif (request.method !== \"GET\")\n+\t\t\treturn json(400, { error: \"every project on this server is private: it answers only its token and keys\" });\n+\t\treturn json(200, { project, visibility: \"private\" });\n+\t}\n+\tif (blob) {\n+\t\tconst sha = top.slice(\"blobs/\".length);\n+\t\tif (!SHA.test(sha)) return json(400, { error: \"a blob's name is its SHA-256 in lowercase hex\" });\n+\t\tif (request.method === \"PUT\") {\n+\t\t\tif (!request.body) return json(400, { error: \"PUT the blob's bytes as the body\" });\n+\t\t\tconst a = (await obj.putBlob(sha, request.body)) as unknown as Answer;\n+\t\t\treturn json(a.status, a.body);\n+\t\t}\n+\t\tif (request.method !== \"GET\") return json(405, { error: \"blobs take GET or PUT\" });\n+\t\tconst bytes = await obj.getBlob(sha);\n+\t\tif (!bytes) return json(404, { error: `no blob ${sha} in this project` });\n+\t\treturn new Response(bytes, {\n+\t\t\theaders: { \"content-type\": \"application/octet-stream\", \"cache-control\": \"private, max-age=31536000, immutable\" },\n+\t\t});\n+\t}\n+\tif (top === \"export\") {\n+\t\tconst from = Number(url.searchParams.get(\"from\") ?? \"0\");\n+\t\tconst limit = Number(url.searchParams.get(\"limit\") ?? \"500\");\n+\t\tif (!Number.isInteger(from) || from < 0 || !Number.isInteger(limit) || limit < 1 || limit > 5000)\n+\t\t\treturn json(400, { error: \"export takes ?from=<seq>&limit=<1-5000>\" });\n+\t\tconst page = await obj.exportLog(from, limit);\n+\t\tif (page === null) return json(404, { error: \"no such project; run init first\" });\n+\t\treturn new Response(page.lines, {\n+\t\t\theaders: {\n+\t\t\t\t\"content-type\": \"application/x-ndjson\",\n+\t\t\t\t\"x-abso-next\": page.next === null ? \"\" : String(page.next),\n+\t\t\t\t\"cache-control\": \"no-store\",\n+\t\t\t},\n+\t\t});\n+\t}\n+\tif (top === \"git-remote\") {\n+\t\t// For a person who works with plain git: clone, commit, push; the project takes the commits in.\n+\t\tif (request.method !== \"POST\") return json(405, { error: \"git-remote is a POST\" });\n+\t\tconst artifacts = artifactsOf(env);\n+\t\tif (!artifacts) return json(501, { error: \"this server has no Artifacts binding, so no git remote\" });\n+\t\tif ((await obj.head()) === null) return json(404, { error: \"no such project; run init first\" });\n+\t\tconst { remote, secret: token } = await writeAccess(artifacts, repoName(project), 3600);\n+\t\t// The token goes in a header for each git call, never in the remote URL or a credential store.\n+\t\tconst header = `Authorization: Basic ${btoa(`x:${token}`)}`;\n+\t\tconst git = `git -c credential.helper= -c http.extraHeader=\"${header}\"`;\n+\t\treturn json(200, {\n+\t\t\tremote,\n+\t\t\ttoken,\n+\t\t\texpiresIn: 3600,\n+\t\t\theader,\n+\t\t\tclone: `${git} clone ${remote}`,\n+\t\t\tfetch: `${git} fetch`,\n+\t\t\tpush: `${git} push`,\n+\t\t});\n+\t}\n+\tif (top === \"git-sync\") {\n+\t\tif (request.method !== \"POST\") return json(405, { error: \"git-sync is a POST\" });\n+\t\ttry {\n+\t\t\treturn json(200, { taken: await obj.gitSync() });\n+\t\t} catch (e) {\n+\t\t\treturn json(502, { error: `could not read the project's repo: ${e instanceof Error ? e.message : String(e)}` });\n+\t\t}\n+\t}\n+\n+\tlet body: unknown;\n+\tif (request.method === \"POST\") {\n+\t\tconst text = await request.text();\n+\t\tif (text) {\n+\t\t\ttry {\n+\t\t\t\tbody = JSON.parse(text);\n+\t\t\t} catch {\n+\t\t\t\treturn json(400, { error: \"the body must be JSON\" });\n+\t\t\t}\n+\t\t}\n+\t} else if (request.method === \"GET\" && (QUERY_READS.has(route ?? \"\") || top.startsWith(\"change/\"))) {\n+\t\tbody = Object.fromEntries(url.searchParams);\n+\t} else return json(405, { error: `${route} is a POST` });\n+\t// Which client sent a recording goes in the log with it.\n+\tif ((op === \"edit\" || op === \"record\") && body && typeof body === \"object\") {\n+\t\tconst client = request.headers.get(\"x-abso-client\") ?? request.headers.get(\"x-avcs-client\") ?? \"\";\n+\t\tconst { client: _, ...rest } = body as Record<string, unknown>;\n+\t\tbody = { ...rest, ...(/^[\\w.+-]{1,20}\\/[\\w.+-]{1,40}$/.test(client) ? { client } : {}) };\n+\t}\n+\ttry {\n+\t\tconst a = (await obj.call(project, (op ?? top)!, agent, body, false, how, keyForCall)) as unknown as Answer;\n+\t\treturn json(a.status, a.body);\n+\t} catch (e) {\n+\t\tconst error = `the project object failed: ${e instanceof Error ? e.message : String(e)}`;\n+\t\tconsole.error(`${project} ${op ?? top}: ${error}`);\n+\t\treturn json(500, { error });\n+\t}\n+}\n+\n+/** One request. The issues code comes in as an argument, so this file loads without the Workers runtime (tests). */\n+export async function handle(\n+\trequest: Request,\n+\tenv: Env,\n+\tctx: ExecutionContext,\n+\tissues: typeof issuesFetch,\n+): Promise<Response> {\n+\tconst url = new URL(request.url);\n+\tif (url.pathname === \"/version\") return json(200, { commit: env.CF_VERSION_METADATA?.tag || null });\n+\tconst caller = await authorize(request, env);\n+\tif (caller instanceof Response) return caller;\n+\tif (url.pathname === \"/\")\n+\t\treturn new Response(\"abso: agent-first version control. The API lives under /p/<project>.\\n\");\n+\tif (url.pathname === \"/admin/agent-keys\" || url.pathname === \"/admin/agent-keys/revoke\")\n+\t\treturn agentKeys(request, env, url, caller);\n+\tconst onIssues = ISSUES_ROUTE.exec(url.pathname);\n+\tif (onIssues) {\n+\t\tconst project = decodeURIComponent(onIssues[1]!);\n+\t\tif (!validName(project)) return json(400, { error: \"project names use letters, digits, '.', '_' and '-'\" });\n+\t\tlet auth: IssuesAuth = { kind: \"token\" };\n+\t\tif (caller.kind === \"key\") {\n+\t\t\tconst decided = await projectObject(env, project).checkAgentKey(caller.presented, undefined, addressOf(request));\n+\t\t\tif (!decided.ok) return json(decided.status, { error: decided.error });\n+\t\t\tauth = { kind: \"key\", agent: decided.agent, role: decided.role as KeyRole };\n+\t\t}\n+\t\treturn issues(request, env, ctx, { project, rest: onIssues[2] ?? \"\", auth });\n+\t}\n+\tconst m = PROJECT_ROUTE.exec(url.pathname);\n+\tif (!m) return json(404, { error: \"no such route\" });\n+\treturn projectRoute(request, env, url, caller, m);\n+}"},{"path":"server/test/blobs.test.ts","added":44,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/blobs.test.ts\n@@ -0,0 +1,44 @@\n+import assert from \"node:assert/strict\";\n+import { createHash } from \"node:crypto\";\n+import { before, describe, it } from \"node:test\";\n+import { BlobStore } from \"../src/blobs.ts\";\n+import { installDigestStream, memoryStorage, streamOf } from \"./helpers.ts\";\n+\n+const sha = (text: string) => createHash(\"sha256\").update(text).digest(\"hex\");\n+\n+describe(\"the blob store\", () => {\n+\tbefore(installDigestStream);\n+\n+\tit(\"keeps bytes whose SHA-256 is their name\", async () => {\n+\t\tconst store = new BlobStore(memoryStorage());\n+\t\tconst a = await store.put(sha(\"hello\"), streamOf(\"hello\"));\n+\t\tassert.deepEqual(a, { status: 200, body: { sha256: sha(\"hello\"), size: 5, stored: true } });\n+\t\tassert.equal(store.has(sha(\"hello\")), true);\n+\t\tassert.equal(new TextDecoder().decode(store.read(sha(\"hello\"))!), \"hello\");\n+\t\tconst again = await store.put(sha(\"hello\"), streamOf(\"hello\"));\n+\t\tassert.equal((again.body as { stored: boolean }).stored, false);\n+\t});\n+\n+\tit(\"refuses bytes that hash to something else, and keeps nothing\", async () => {\n+\t\tconst store = new BlobStore(memoryStorage());\n+\t\tconst a = await store.put(sha(\"hello\"), streamOf(\"goodbye\"));\n+\t\tassert.equal(a.status, 400);\n+\t\tassert.match((a.body as { error: string }).error, new RegExp(`hash to ${sha(\"goodbye\")}`));\n+\t\tassert.equal(store.has(sha(\"hello\")), false);\n+\t\tassert.equal(store.has(sha(\"goodbye\")), false);\n+\t\tassert.deepEqual(store.list(\"\", 10), { blobs: [], next: null });\n+\t});\n+\n+\tit(\"refuses a name that isn't a lowercase SHA-256\", async () => {\n+\t\tconst store = new BlobStore(memoryStorage());\n+\t\tassert.equal((await store.put(\"abc\", streamOf(\"x\"))).status, 400);\n+\t\tassert.equal((await store.put(sha(\"x\").toUpperCase(), streamOf(\"x\"))).status, 400);\n+\t});\n+\n+\tit(\"refuses a blob over the size cap\", async () => {\n+\t\tconst store = new BlobStore(memoryStorage());\n+\t\tconst a = await store.put(sha(\"too big\"), streamOf(\"too big\"), 3);\n+\t\tassert.equal(a.status, 413);\n+\t\tassert.equal(store.total(), 0);\n+\t});\n+});"},{"path":"server/test/e2e-transcript.md","added":132,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/e2e-transcript.md\n@@ -0,0 +1,132 @@\n+# End to end: the stock client against `wrangler dev --local`\n+\n+Server: `http://127.0.0.1:8799` (server/ in abso-core, run with `npx wrangler dev --local`, Artifacts off).\n+Token: an invented local test token in `server/.dev.vars`, given to the client as `ABSO_TOKEN`.\n+Project: `e2e-1791907434`. Folders are temporary, outside abso-core. Run 2026-10-13T16:03Z.\n+\n+## Init and join\n+\n+```\n+(starter) $ abso init . --server http://127.0.0.1:8799 --project e2e-1791907434 --agent starter\n+Created project e2e-1791907434 at version 0 from 3 text files in <temp>\\starter.\n+Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore.\n+No abso.json written: package.json gives no check or build to guess, so CI has nothing to run on each new version. To give it a check, push an abso.json like {\"check\": \"npm test\"} (abso ci --help says what it runs).\n+This folder is agent starter. Settings are in .abso/config.json.\n+Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node <abso-core>\\client\\install-mod.ts installs it, and new chats load it. Anything else: abso record.\n+[exit 0]\n+```\n+\n+```\n+(alice) $ abso join e2e-1791907434 --agent alice --dir . --server http://127.0.0.1:8799\n+Joined e2e-1791907434 as alice at version 0: wrote 3 files into <temp>\\alice.\n+Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node <abso-core>\\client\\install-mod.ts installs it, and new chats load it. Anything else: abso record.\n+[exit 0]\n+```\n+\n+```\n+(bob) $ abso join e2e-1791907434 --agent bob --dir . --server http://127.0.0.1:8799\n+Joined e2e-1791907434 as bob at version 0: wrote 3 files into <temp>\\bob.\n+Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node <abso-core>\\client\\install-mod.ts installs it, and new chats load it. Anything else: abso record.\n+[exit 0]\n+```\n+\n+## Both agents edit and push (different files)\n+\n+```\n+(alice) $ abso push -m Alice edits line two\n+Recorded first: 1 changed (hello.txt).\n+Pushed version 1.\n+[exit 0]\n+```\n+\n+```\n+(bob) $ abso push -m Bob writes the notes\n+Recorded first: 1 changed (notes.md).\n+Pushed version 2. It went on top of version 1 (alice: \"Alice edits line two\"), which your folder doesn't have yet. Nothing of theirs was overwritten; run abso pull to see both.\n+[exit 0]\n+```\n+\n+## A collision: both change line four\n+\n+```\n+(alice) $ abso pull\n+Pulled to version 2: 1 file updated, 0 deleted.\n+  updated: notes.md\n+[exit 0]\n+```\n+\n+```\n+(bob) $ abso pull\n+Pulled to version 2: 1 file updated, 0 deleted.\n+  updated: hello.txt\n+[exit 0]\n+```\n+\n+```\n+(alice) $ abso push -m Alice rewrites line four\n+Recorded first: 1 changed (hello.txt).\n+Pushed version 3.\n+[exit 0]\n+```\n+\n+```\n+(bob) $ abso push -m Bob rewrites line four\n+Recorded first: 1 changed (hello.txt).\n+Not pushed: 1 collision with work pushed since your last pull.\n+  hello.txt:\n+    yours (line 4):\n+      line four, as bob wants it\n+    theirs, by alice in version 3 (\"Alice rewrites line four\") (line 4):\n+      line four, as alice wants it\n+Run abso pull: each of those files comes back holding both sides' lines, with no markers. Edit it to what it should be, then push again.\n+News:\n+  alice pushed \"Alice rewrites line four\" (version 3), which changes hello.txt lines 4-4, where your draft also changes lines; run abso pull to see both versions.\n+[exit 2]\n+```\n+\n+## Log and status\n+\n+```\n+(bob) $ abso log\n+shared is at version 3.\n+version 3 by alice, 2026-10-13 16:03 UTC: Alice rewrites line four\n+  1 file: hello.txt\n+version 2 by bob, 2026-10-13 16:03 UTC: Bob writes the notes\n+  1 file: notes.md\n+version 1 by alice, 2026-10-13 16:03 UTC: Alice edits line two\n+  1 file: hello.txt\n+version 0 by init, 2026-10-13 16:03 UTC: Start the project\n+  3 files: .absoignore, hello.txt, notes.md\n+[exit 0]\n+```\n+\n+```\n+(bob) $ abso status\n+Project e2e-1791907434: shared is at version 3. This folder is bob, working in shared. Signed in with shared token.\n+Everything in this folder is recorded.\n+Agents:\n+    alice, base 3, 0 draft changes\n+  * bob, base 2, 1 draft change: hello.txt\n+    starter, base 0, 0 draft changes\n+[exit 0]\n+```\n+\n+```\n+(alice) $ abso status\n+Project e2e-1791907434: shared is at version 3. This folder is alice, working in shared. Signed in with shared token.\n+Everything in this folder is recorded.\n+Agents:\n+  * alice, base 3, 0 draft changes\n+    bob, base 2, 1 draft change: hello.txt\n+    starter, base 0, 0 draft changes\n+[exit 0]\n+```\n+\n+## Other checks against the same server, with curl\n+\n+- No token, or a wrong one: 401 `missing or wrong token`. `GET /version` answers without one.\n+- Per-agent keys (`AGENT_KEYS=on`, a local `KEY_HMAC_SECRET`): `POST /admin/agent-keys` without `x-abso-admin` is 403; with it, a writer key for `carol` is issued and listed. Carol's key syncs as carol; as `dave` it is 403 `that key is not for this agent`; on another project, 403 `that key is not for this project`.\n+- Blobs: a PUT whose bytes don't hash to the name is 400 `the bytes hash to …, not …`; the right hash is stored and read back; a name that isn't a SHA-256 is 400.\n+- `GET head` answers `{version, at}` from storage. `GET feed?from=<end>&wait=3` holds for 3 seconds, then answers with no events.\n+- `/issues/p/<project>/...` reaches the issues stand-in (404 `issues aren't on this server yet`) after auth.\n+- `POST git-remote` with Artifacts off: 501 `this server has no Artifacts binding, so no git remote`."},{"path":"server/test/engine-project.test.ts","added":37,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/engine-project.test.ts\n@@ -0,0 +1,37 @@\n+import assert from \"node:assert/strict\";\n+import { describe, it } from \"node:test\";\n+import { answer } from \"../../worker/project/http.ts\";\n+import { EngineProject, SqliteLog } from \"../src/engine-project.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+describe(\"the engine over the object's SQLite log\", () => {\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);\n+\t\tassert.equal(answer(p, \"init\", undefined, { files: { \"a.txt\": \"one\\ntwo\\nthree\\n\" } }).status, 200);\n+\t\tfor (const agent of [\"alice\", \"bob\"]) assert.equal(answer(p, \"sync\", agent, {}).status, 200);\n+\t\tanswer(p, \"record\", \"alice\", { files: { \"a.txt\": \"one\\nTWO by alice\\nthree\\n\" } });\n+\t\tanswer(p, \"record\", \"bob\", { files: { \"a.txt\": \"one\\ntwo by bob\\nthree\\n\" } });\n+\t\tconst first = answer(p, \"publish\", \"alice\", { message: \"Alice's two\" });\n+\t\tassert.deepEqual(first, { status: 200, body: { ok: true, version: 1, changes: 1 } });\n+\t\tconst second = answer(p, \"publish\", \"bob\", { message: \"Bob's two\" }).body as { ok: boolean; collisions: unknown[] };\n+\t\tassert.equal(second.ok, false);\n+\t\tassert.equal(second.collisions.length, 1);\n+\t});\n+\n+\tit(\"loads the same project back from the log\", () => {\n+\t\tconst storage = memoryStorage();\n+\t\tconst p = EngineProject.open(storage);\n+\t\tanswer(p, \"init\", undefined, { files: { \"a.txt\": \"one\\n\" } });\n+\t\tanswer(p, \"sync\", \"alice\", {});\n+\t\tanswer(p, \"record\", \"alice\", { files: { \"a.txt\": \"one\\ntwo\\n\" } });\n+\t\tanswer(p, \"publish\", \"alice\", { message: \"Add two\" });\n+\t\tconst again = EngineProject.open(storage);\n+\t\tassert.equal(again.shared().version, 1);\n+\t\tassert.equal(again.shared().files[\"a.txt\"], \"one\\ntwo\\n\");\n+\t\tconst log = new SqliteLog(storage);\n+\t\tassert.equal(log.sharedVersion(), 1);\n+\t\tassert.deepEqual(log.lastPublish()?.agent, \"alice\");\n+\t\tassert.equal(log.logSize().entries, log.seq());\n+\t});\n+});"},{"path":"server/test/helpers.ts","added":82,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/helpers.ts\n@@ -0,0 +1,82 @@\n+// Stand-ins for the Workers runtime in Node tests: a Durable Object's SQLite storage over node:sqlite, and the\n+// DigestStream the blob store hashes uploads with.\n+\n+import { createHash } from \"node:crypto\";\n+import { DatabaseSync } from \"node:sqlite\";\n+import type { SqliteStorage } from \"../src/engine-project.ts\";\n+\n+export function memoryStorage(): SqliteStorage & { db: DatabaseSync } {\n+\tconst db = new DatabaseSync(\":memory:\");\n+\tlet depth = 0;\n+\treturn {\n+\t\tdb,\n+\t\tsql: {\n+\t\t\texec(query: string, ...bindings: unknown[]) {\n+\t\t\t\tconst statement = db.prepare(query);\n+\t\t\t\tconst args = bindings as never[];\n+\t\t\t\tconst rows = statement.columns().length > 0 ? statement.all(...args) : (statement.run(...args), []);\n+\t\t\t\t// Workers hands BLOB columns back as ArrayBuffers.\n+\t\t\t\treturn {\n+\t\t\t\t\ttoArray: () =>\n+\t\t\t\t\t\trows.map((r) =>\n+\t\t\t\t\t\t\tObject.fromEntries(\n+\t\t\t\t\t\t\t\tObject.entries(r as Record<string, unknown>).map(([k, v]) => [\n+\t\t\t\t\t\t\t\t\tk,\n+\t\t\t\t\t\t\t\t\tv instanceof Uint8Array ? v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength) : v,\n+\t\t\t\t\t\t\t\t]),\n+\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t),\n+\t\t\t\t};\n+\t\t\t},\n+\t\t},\n+\t\ttransactionSync<T>(fn: () => T): T {\n+\t\t\tconst name = `t${depth++}`;\n+\t\t\tdb.exec(`SAVEPOINT ${name}`);\n+\t\t\ttry {\n+\t\t\t\tconst value = fn();\n+\t\t\t\tdb.exec(`RELEASE ${name}`);\n+\t\t\t\treturn value;\n+\t\t\t} catch (e) {\n+\t\t\t\tdb.exec(`ROLLBACK TO ${name}; RELEASE ${name}`);\n+\t\t\t\tthrow e;\n+\t\t\t} finally {\n+\t\t\t\tdepth--;\n+\t\t\t}\n+\t\t},\n+\t};\n+}\n+\n+/** Workers' crypto.DigestStream, for the blob store's streaming hash. */\n+export function installDigestStream(): void {\n+\tconst c = (globalThis as unknown as { crypto: { DigestStream?: unknown } }).crypto;\n+\tif (c.DigestStream) return;\n+\tclass DigestStream extends WritableStream<Uint8Array> {\n+\t\treadonly digest: Promise<ArrayBuffer>;\n+\t\tconstructor(algorithm: string) {\n+\t\t\tconst hash = createHash(algorithm.replace(\"-\", \"\").toLowerCase());\n+\t\t\tlet done!: (b: ArrayBuffer) => void;\n+\t\t\tconst digest = new Promise<ArrayBuffer>((ok) => {\n+\t\t\t\tdone = ok;\n+\t\t\t});\n+\t\t\tsuper({\n+\t\t\t\twrite: (chunk) => void hash.update(chunk),\n+\t\t\t\tclose: () => {\n+\t\t\t\t\tconst b = hash.digest();\n+\t\t\t\t\tdone(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength));\n+\t\t\t\t},\n+\t\t\t});\n+\t\t\tthis.digest = digest;\n+\t\t}\n+\t}\n+\tc.DigestStream = DigestStream;\n+}\n+\n+export function streamOf(text: string): ReadableStream<Uint8Array> {\n+\tconst bytes = new TextEncoder().encode(text);\n+\treturn new ReadableStream({\n+\t\tstart(c) {\n+\t\t\tc.enqueue(bytes);\n+\t\t\tc.close();\n+\t\t},\n+\t});\n+}"},{"path":"server/test/push.test.ts","added":68,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/push.test.ts\n@@ -0,0 +1,68 @@\n+import assert from \"node:assert/strict\";\n+import { describe, it } from \"node:test\";\n+import git from \"isomorphic-git\";\n+import { absoVersion } from \"../src/ingest.ts\";\n+import { MemoryFS } from \"../src/memory-fs.ts\";\n+import { commitShared, projectOfRepo, readTreeFiles, repoName } from \"../src/push.ts\";\n+\n+describe(\"repo names\", () => {\n+\tit(\"names a project's Artifacts repo abso-<project>, and back\", () => {\n+\t\tassert.equal(repoName(\"game\"), \"abso-game\");\n+\t\tassert.equal(repoName(\"my.site_2\"), \"abso-my.site_2\");\n+\t\tassert.equal(projectOfRepo(\"abso-game\"), \"game\");\n+\t\tassert.equal(projectOfRepo(\"avcs-game\"), null);\n+\t\tassert.equal(projectOfRepo(\"abso-\"), null);\n+\t});\n+\n+\tit(\"reads the version a pushed commit carries, under either name\", () => {\n+\t\tassert.equal(absoVersion(\"Fix it\\n\\nabso-version: 12\\n\"), 12);\n+\t\tassert.equal(absoVersion(\"Fix it\\n\\navcs-version: 7\\n\"), 7);\n+\t\tassert.equal(absoVersion(\"a person's own commit\"), undefined);\n+\t});\n+});\n+\n+describe(\"commitShared\", () => {\n+\tit(\"writes shared as a commit with its modes, then only what changed\", async () => {\n+\t\tconst fs = new MemoryFS();\n+\t\tconst dir = \"/repo\";\n+\t\tawait git.init({ fs, dir, defaultBranch: \"main\" });\n+\t\tconst noBlobs = () => null;\n+\t\tconst first = await commitShared(\n+\t\t\tfs,\n+\t\t\tdir,\n+\t\t\tnull,\n+\t\t\t{\n+\t\t\t\tversion: 0,\n+\t\t\t\tfiles: { \"a.txt\": \"one\\n\", \"run.sh\": \"echo hi\\n\", link: \"\" },\n+\t\t\t\tmodes: { \"run.sh\": { exec: true }, link: { link: \"a.txt\" } },\n+\t\t\t},\n+\t\t\tnoBlobs,\n+\t\t);\n+\t\tassert.equal(first.changed, 3);\n+\t\tconst commit = (await git.readCommit({ fs, dir, oid: first.commit })).commit;\n+\t\tassert.match(commit.message, /^Start the project\\n\\nabso-version: 0\\n$/);\n+\t\tconst { files } = await readTreeFiles(fs, dir, commit.tree);\n+\t\tassert.deepEqual(Object.fromEntries([...files].map(([p, f]) => [p, f.mode])), {\n+\t\t\t\"a.txt\": \"100644\",\n+\t\t\tlink: \"120000\",\n+\t\t\t\"run.sh\": \"100755\",\n+\t\t});\n+\t\tconst second = await commitShared(\n+\t\t\tfs,\n+\t\t\tdir,\n+\t\t\tfirst.commit,\n+\t\t\t{\n+\t\t\t\tversion: 1,\n+\t\t\t\tfiles: { \"a.txt\": \"one\\ntwo\\n\", \"run.sh\": \"echo hi\\n\", link: \"\" },\n+\t\t\t\tmodes: { \"run.sh\": { exec: true }, link: { link: \"a.txt\" } },\n+\t\t\t\tlast: { agent: \"alice\", message: \"Add two\" },\n+\t\t\t},\n+\t\t\tnoBlobs,\n+\t\t);\n+\t\tassert.equal(second.changed, 1);\n+\t\tconst next = (await git.readCommit({ fs, dir, oid: second.commit })).commit;\n+\t\tassert.equal(next.author.name, \"alice\");\n+\t\tassert.deepEqual(next.parent, [first.commit]);\n+\t\tassert.equal(absoVersion(next.message), 1);\n+\t});\n+});"},{"path":"server/test/router.test.ts","added":224,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/router.test.ts\n@@ -0,0 +1,224 @@\n+import assert from \"node:assert/strict\";\n+import { describe, it } from \"node:test\";\n+import type { Env } from \"../src/env.ts\";\n+import { authorize, handle, ISSUES_ROUTE, PROJECT_ROUTE, sameSecret } from \"../src/router.ts\";\n+\n+const TOKEN = \"test-token-for-the-router\";\n+\n+/** A project namespace whose objects record every call and answer what each test needs. */\n+function fakeEnv(extra: Partial<Env> = {}) {\n+\tconst calls: { project: string; method: string; args: unknown[] }[] = [];\n+\tconst object = (project: string) =>\n+\t\tnew Proxy(\n+\t\t\t{},\n+\t\t\t{\n+\t\t\t\tget:\n+\t\t\t\t\t(_t, method: string) =>\n+\t\t\t\t\tasync (...args: unknown[]) => {\n+\t\t\t\t\t\tcalls.push({ project, method, args });\n+\t\t\t\t\t\tif (method === \"call\") return { status: 200, body: { op: args[1], agent: args[2], body: args[3] } };\n+\t\t\t\t\t\tif (method === \"putBlob\") return { status: 200, body: { stored: true } };\n+\t\t\t\t\t\tif (method === \"head\") return { version: 3, at: \"now\" };\n+\t\t\t\t\t\tif (method === \"checkAgentKey\")\n+\t\t\t\t\t\t\treturn { ok: true, id: \"k_1\", as: \"key k_1\", role: \"writer\", agent: \"carol\", dirty: false };\n+\t\t\t\t\t\tif (method === \"issueAgentKey\") return { id: \"k_2\", key: \"abso_sk_new\", agent: args[0] };\n+\t\t\t\t\t\treturn null;\n+\t\t\t\t\t},\n+\t\t\t},\n+\t\t);\n+\tconst env = {\n+\t\tPROJECT: { idFromName: (n: string) => n, get: (id: string) => object(id) },\n+\t\tISSUES_DO: { idFromName: (n: string) => n, get: () => ({}) },\n+\t\tABSO_TOKEN: TOKEN,\n+\t\t...extra,\n+\t} as unknown as Env;\n+\treturn { env, calls };\n+}\n+\n+const ctx = {} as ExecutionContext;\n+const noIssues = async () => new Response(\"issues\", { status: 299 });\n+const request = (path: string, init: RequestInit & { token?: string | null } = {}) => {\n+\tconst { token = TOKEN, ...rest } = init;\n+\tconst headers = new Headers(rest.headers);\n+\tif (token) headers.set(\"authorization\", `Bearer ${token}`);\n+\treturn new Request(`http://abso.test${path}`, { ...rest, headers });\n+};\n+\n+describe(\"routes\", () => {\n+\tit(\"matches the project's top routes and an agent's ops\", () => {\n+\t\tassert.deepEqual(PROJECT_ROUTE.exec(\"/p/game/status\")?.slice(1, 3), [\"game\", \"status\"]);\n+\t\tassert.deepEqual(PROJECT_ROUTE.exec(\"/p/game/a/alice/publish\")?.slice(1), [\n+\t\t\t\"game\",\n+\t\t\t\"a/alice/publish\",\n+\t\t\t\"alice\",\n+\t\t\t\"publish\",\n+\t\t]);\n+\t\tassert.equal(PROJECT_ROUTE.exec(\"/p/game/change/12\")?.[2], \"change/12\");\n+\t\tassert.equal(PROJECT_ROUTE.exec(\"/p/game/a/alice/run\"), null, \"boxes are not on the open server\");\n+\t\tassert.equal(PROJECT_ROUTE.exec(\"/p/game/ci/log\"), null, \"nor CI's output\");\n+\t\tassert.equal(PROJECT_ROUTE.exec(\"/p/game/members\"), null);\n+\t\tassert.deepEqual(ISSUES_ROUTE.exec(\"/issues/p/game/issues/4\")?.slice(1), [\"game\", \"/issues/4\"]);\n+\t\tassert.deepEqual(ISSUES_ROUTE.exec(\"/issues/p/game\")?.slice(1), [\"game\", undefined]);\n+\t});\n+\n+\tit(\"sends an agent's op to the project's object, with the JSON body\", async () => {\n+\t\tconst { env, calls } = fakeEnv();\n+\t\tconst res = await handle(\n+\t\t\trequest(\"/p/game/a/alice/publish\", { method: \"POST\", body: JSON.stringify({ message: \"why\" }) }),\n+\t\t\tenv,\n+\t\t\tctx,\n+\t\t\tnoIssues,\n+\t\t);\n+\t\tassert.equal(res.status, 200);\n+\t\tassert.deepEqual(await res.json(), { op: \"publish\", agent: \"alice\", body: { message: \"why\" } });\n+\t\tassert.equal(calls[0]?.project, \"game\");\n+\t});\n+\n+\tit(\"reads take their query as the body, and a read refuses a POST-only op as a GET\", async () => {\n+\t\tconst { env } = fakeEnv();\n+\t\tconst log = await handle(request(\"/p/game/log?limit=5\"), env, ctx, noIssues);\n+\t\tassert.deepEqual(await log.json(), { op: \"log\", body: { limit: \"5\" } });\n+\t\tconst publish = await handle(request(\"/p/game/a/alice/publish\"), env, ctx, noIssues);\n+\t\tassert.equal(publish.status, 405);\n+\t});\n+\n+\tit(\"refuses a project name the engine wouldn't take\", async () => {\n+\t\tconst { env, calls } = fakeEnv();\n+\t\tconst res = await handle(request(\"/p/..bad/status\"), env, ctx, noIssues);\n+\t\tassert.equal(res.status, 400);\n+\t\tassert.equal(calls.length, 0);\n+\t});\n+\n+\tit(\"answers head from the object, and ci and queue as empty\", async () => {\n+\t\tconst { env } = fakeEnv();\n+\t\tassert.deepEqual(await (await handle(request(\"/p/game/head\"), env, ctx, noIssues)).json(), {\n+\t\t\tversion: 3,\n+\t\t\tat: \"now\",\n+\t\t});\n+\t\tconst ci = (await (await handle(request(\"/p/game/ci\"), env, ctx, noIssues)).json()) as Record<string, unknown>;\n+\t\tassert.equal(ci.red, null);\n+\t\tassert.deepEqual(await (await handle(request(\"/p/game/queue\"), env, ctx, noIssues)).json(), {\n+\t\t\titems: [],\n+\t\t\tpaused: null,\n+\t\t});\n+\t});\n+\n+\tit(\"checks a blob's name before its bytes go anywhere\", async () => {\n+\t\tconst { env, calls } = fakeEnv();\n+\t\tconst bad = await handle(request(\"/p/game/blobs/not-a-hash\", { method: \"PUT\", body: \"x\" }), env, ctx, noIssues);\n+\t\tassert.equal(bad.status, 400);\n+\t\tconst upper = await handle(\n+\t\t\trequest(`/p/game/blobs/${\"A\".repeat(64)}`, { method: \"PUT\", body: \"x\" }),\n+\t\t\tenv,\n+\t\t\tctx,\n+\t\t\tnoIssues,\n+\t\t);\n+\t\tassert.equal(upper.status, 400);\n+\t\tassert.equal(calls.length, 0);\n+\t\tconst good = await handle(\n+\t\t\trequest(`/p/game/blobs/${\"a\".repeat(64)}`, { method: \"PUT\", body: \"x\" }),\n+\t\t\tenv,\n+\t\t\tctx,\n+\t\t\tnoIssues,\n+\t\t);\n+\t\tassert.equal(good.status, 200);\n+\t\tassert.equal(calls[0]?.method, \"putBlob\");\n+\t});\n+\n+\tit(\"hands /issues to the issues code with the rest of the path and who is calling\", async () => {\n+\t\tconst { env } = fakeEnv();\n+\t\tlet seen: unknown;\n+\t\tconst res = await handle(request(\"/issues/p/game/issues?open=1\"), env, ctx, async (_r, _e, _c, where) => {\n+\t\t\tseen = where;\n+\t\t\treturn new Response(\"ok\");\n+\t\t});\n+\t\tassert.equal(await res.text(), \"ok\");\n+\t\tassert.deepEqual(seen, { project: \"game\", rest: \"/issues\", auth: { kind: \"token\" } });\n+\t});\n+\n+\tit(\"gives the issues code a key's agent and role\", async () => {\n+\t\tconst { env } = fakeEnv({ AGENT_KEYS: \"on\", KEY_HMAC_SECRET: \"s\" });\n+\t\tlet seen: unknown;\n+\t\tawait handle(request(\"/issues/p/game/issues\", { token: \"abso_sk_abc\" }), env, ctx, async (_r, _e, _c, where) => {\n+\t\t\tseen = where;\n+\t\t\treturn new Response(\"ok\");\n+\t\t});\n+\t\tassert.deepEqual(seen, { project: \"game\", rest: \"/issues\", auth: { kind: \"key\", agent: \"carol\", role: \"writer\" } });\n+\t});\n+\n+\tit(\"answers /version without a token\", async () => {\n+\t\tconst { env } = fakeEnv({ ABSO_TOKEN: undefined });\n+\t\tconst res = await handle(request(\"/version\", { token: null }), env, ctx, noIssues);\n+\t\tassert.equal(res.status, 200);\n+\t});\n+});\n+\n+describe(\"auth\", () => {\n+\tit(\"refuses everything when no shared token is set\", async () => {\n+\t\tconst { env, calls } = fakeEnv({ ABSO_TOKEN: undefined });\n+\t\tconst res = await handle(request(\"/p/game/status\", { token: \"anything\" }), env, ctx, noIssues);\n+\t\tassert.equal(res.status, 503);\n+\t\tassert.match(((await res.json()) as { error: string }).error, /no ABSO_TOKEN/);\n+\t\tconst empty = await authorize(request(\"/p/game/status\", { token: null }), { ...env, ABSO_TOKEN: \"\" });\n+\t\tassert.ok(empty instanceof Response && empty.status === 503);\n+\t\tassert.equal(calls.length, 0);\n+\t});\n+\n+\tit(\"refuses a missing or wrong token, and takes the right one\", async () => {\n+\t\tconst { env, calls } = fakeEnv();\n+\t\tassert.equal((await handle(request(\"/p/game/status\", { token: null }), env, ctx, noIssues)).status, 401);\n+\t\tassert.equal((await handle(request(\"/p/game/status\", { token: \"wrong\" }), env, ctx, noIssues)).status, 401);\n+\t\tassert.equal((await handle(request(\"/p/game/status\", { token: `${TOKEN}x` }), env, ctx, noIssues)).status, 401);\n+\t\tassert.equal((await handle(request(\"/\", { token: \"wrong\" }), env, ctx, noIssues)).status, 401);\n+\t\tassert.equal(calls.length, 0);\n+\t\tassert.equal((await handle(request(\"/p/game/status\"), env, ctx, noIssues)).status, 200);\n+\t});\n+\n+\tit(\"takes the token under its old name, AVCS_TOKEN\", async () => {\n+\t\tconst { env } = fakeEnv({ ABSO_TOKEN: undefined, AVCS_TOKEN: TOKEN });\n+\t\tassert.deepEqual(await authorize(request(\"/p/game/status\"), env), { kind: \"token\" });\n+\t});\n+\n+\tit(\"treats an agent key as a key only when keys are on\", async () => {\n+\t\tconst off = fakeEnv();\n+\t\tconst refused = await authorize(request(\"/p/game/status\", { token: \"abso_sk_abc\" }), off.env);\n+\t\tassert.ok(refused instanceof Response && refused.status === 401);\n+\t\tconst on = fakeEnv({ AGENT_KEYS: \"on\", KEY_HMAC_SECRET: \"s\" });\n+\t\tassert.deepEqual(await authorize(request(\"/p/game/status\", { token: \"abso_sk_abc\" }), on.env), {\n+\t\t\tkind: \"key\",\n+\t\t\tpresented: \"abso_sk_abc\",\n+\t\t});\n+\t});\n+\n+\tit(\"compares secrets whatever their lengths\", async () => {\n+\t\tassert.equal(await sameSecret(\"abc\", \"abc\"), true);\n+\t\tassert.equal(await sameSecret(\"abc\", \"abcd\"), false);\n+\t\tassert.equal(await sameSecret(\"\", \"abc\"), false);\n+\t});\n+\n+\tit(\"issues agent keys only with the admin token beside the shared one\", async () => {\n+\t\tconst { env, calls } = fakeEnv({ AGENT_KEYS: \"on\", KEY_HMAC_SECRET: \"s\", ABSO_ADMIN_TOKEN: \"admin-secret\" });\n+\t\tconst path = \"/admin/agent-keys?project=game&agent=carol\";\n+\t\tassert.equal((await handle(request(path, { method: \"POST\" }), env, ctx, noIssues)).status, 403);\n+\t\tconst wrong = request(path, { method: \"POST\", headers: { \"x-abso-admin\": \"nope\" } });\n+\t\tassert.equal((await handle(wrong, env, ctx, noIssues)).status, 403);\n+\t\tconst key = request(path, { method: \"POST\", token: \"abso_sk_abc\", headers: { \"x-abso-admin\": \"admin-secret\" } });\n+\t\tassert.equal((await handle(key, env, ctx, noIssues)).status, 401);\n+\t\tassert.equal(calls.length, 0);\n+\t\tconst ok = request(path, { method: \"POST\", headers: { \"x-abso-admin\": \"admin-secret\" } });\n+\t\tconst res = await handle(ok, env, ctx, noIssues);\n+\t\tassert.equal(res.status, 200);\n+\t\tassert.deepEqual(await res.json(), { id: \"k_2\", key: \"abso_sk_new\", agent: \"carol\" });\n+\t});\n+\n+\tit(\"has no agent keys routes while keys are off\", async () => {\n+\t\tconst { env } = fakeEnv({ ABSO_ADMIN_TOKEN: \"admin-secret\" });\n+\t\tconst res = await handle(\n+\t\t\trequest(\"/admin/agent-keys?project=game\", { headers: { \"x-abso-admin\": \"admin-secret\" } }),\n+\t\t\tenv,\n+\t\t\tctx,\n+\t\t\tnoIssues,\n+\t\t);\n+\t\tassert.equal(res.status, 404);\n+\t});\n+});"},{"path":"server/tsconfig.json","added":17,"removed":0,"diff":"--- /dev/null\n+++ b/server/tsconfig.json\n@@ -0,0 +1,17 @@\n+{\n+\t\"compilerOptions\": {\n+\t\t\"target\": \"es2023\",\n+\t\t\"module\": \"es2022\",\n+\t\t\"moduleResolution\": \"bundler\",\n+\t\t\"lib\": [\"es2023\"],\n+\t\t\"strict\": true,\n+\t\t\"noEmit\": true,\n+\t\t\"allowImportingTsExtensions\": true,\n+\t\t\"verbatimModuleSyntax\": true,\n+\t\t\"erasableSyntaxOnly\": true,\n+\t\t\"noUncheckedIndexedAccess\": true,\n+\t\t\"skipLibCheck\": true,\n+\t\t\"types\": [\"@cloudflare/workers-types\", \"node\"]\n+\t},\n+\t\"include\": [\"src/**/*.ts\", \"test/**/*.ts\"]\n+}"},{"path":"server/wrangler.jsonc","added":33,"removed":0,"diff":"--- /dev/null\n+++ b/server/wrangler.jsonc\n@@ -0,0 +1,33 @@\n+// abso's open server: deploy it to your own Cloudflare account with `npx wrangler deploy` from this folder, after\n+// `npx wrangler secret put ABSO_TOKEN`. Without that secret the server refuses every call. Local development:\n+// `npx wrangler dev --local` (or `npm run dev`), with ABSO_TOKEN=<anything> in .dev.vars (never recorded: .absoignore\n+// leaves it out). Keep --local: Artifacts is a remote binding, and without it wrangler dev connects to your account.\n+// Put ABSO_ARTIFACTS=off in .dev.vars too: --local still binds Artifacts, but nothing local can reach it.\n+{\n+\t\"$schema\": \"./node_modules/wrangler/config-schema.json\",\n+\t\"name\": \"abso\",\n+\t\"main\": \"src/index.ts\",\n+\t\"compatibility_date\": \"2026-10-01\",\n+\t\"compatibility_flags\": [\"nodejs_compat\"],\n+\t\"workers_dev\": true,\n+\t\"observability\": { \"enabled\": true },\n+\t// CPU per request: 2 minutes, not the default 30 seconds, so a heavy push finishes instead of resetting the\n+\t// project's object. Billed only for CPU used.\n+\t\"limits\": { \"cpu_ms\": 120000 },\n+\t// GET /version answers with the deployed version's tag.\n+\t\"version_metadata\": { \"binding\": \"CF_VERSION_METADATA\" },\n+\t\"vars\": {\n+\t\t// Per-agent keys: on once KEY_HMAC_SECRET is set (npx wrangler secret put KEY_HMAC_SECRET). Until then, only\n+\t\t// the shared token signs in.\n+\t\t\"AGENT_KEYS\": \"on\"\n+\t},\n+\t// Each project's shared is pushed out to its own repo, abso-<project>, in this namespace.\n+\t\"artifacts\": [{ \"binding\": \"ARTIFACTS\", \"namespace\": \"abso\" }],\n+\t\"durable_objects\": {\n+\t\t\"bindings\": [\n+\t\t\t{ \"name\": \"PROJECT\", \"class_name\": \"ProjectObject\" },\n+\t\t\t{ \"name\": \"ISSUES_DO\", \"class_name\": \"IssueProject\" }\n+\t\t]\n+\t},\n+\t\"migrations\": [{ \"tag\": \"v1\", \"new_sqlite_classes\": [\"ProjectObject\", \"IssueProject\"] }]\n+}"}],"ci":null}