{"draft":null,"from":145,"to":318,"files":[{"path":"server/src/engine-project.ts","added":884,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/engine-project.ts\n@@ -0,0 +1,884 @@\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 { jsonValueChunks } from \"../../src/engine/json-value-chunks.ts\";\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+import type { PushSnapshotMetadata } from \"./push-snapshot.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+export const LOG_PART_CHARACTERS = 600_000;\n+\n+/** An entry's JSON in rows of at most LOG_PART_CHARACTERS 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 + LOG_PART_CHARACTERS, 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+/** Retains one log row plus an encoder fragment, preserving legacy row boundaries. */\n+export function* streamedLogParts(value: unknown): IterableIterator<string> {\n+\tlet pending = \"\";\n+\tfor (const chunk of jsonValueChunks(value)) {\n+\t\tpending += chunk;\n+\t\twhile (pending.length > LOG_PART_CHARACTERS) {\n+\t\t\tlet end = LOG_PART_CHARACTERS;\n+\t\t\tconst last = pending.charCodeAt(end - 1);\n+\t\t\tif (last >= 0xd800 && last <= 0xdbff) end--;\n+\t\t\tyield pending.slice(0, end);\n+\t\t\tpending = pending.slice(end);\n+\t\t}\n+\t}\n+\tif (pending) yield pending;\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/** Reject an oversized canonical frame before loading its text into JavaScript. */\n+\tframeBytes(seq: number): number {\n+\t\tif (!Number.isSafeInteger(seq) || seq < 0) throw Error(\"invalid canonical frame position\");\n+\t\tconst size = this.storage.sql\n+\t\t\t.exec(\n+\t\t\t\t\"SELECT COUNT(*) AS parts, COALESCE(SUM(LENGTH(CAST(text AS BLOB))), 0) AS bytes FROM log WHERE seq = ?\",\n+\t\t\t\tseq,\n+\t\t\t)\n+\t\t\t.toArray()[0] as { parts: number; bytes: number };\n+\t\tif (!size || size.parts < 1 || size.parts > 256 || size.bytes < 1 || !Number.isSafeInteger(size.bytes))\n+\t\t\tthrow Error(\"canonical frame exceeds hard decoding bound or is missing\");\n+\t\treturn size.bytes;\n+\t}\n+\t/** A larger first frame gets its own budget; later frames are deferred. */\n+\tadoptionPageBytes(from: number): number {\n+\t\treturn Math.max(1_048_576, this.frameBytes(from));\n+\t}\n+\n+\tboundedFrame(seq: number, maxBytes: number): string {\n+\t\tif (\n+\t\t\t!Number.isSafeInteger(seq) ||\n+\t\t\tseq < 0 ||\n+\t\t\t!Number.isSafeInteger(maxBytes) ||\n+\t\t\tmaxBytes < 1 ||\n+\t\t\tmaxBytes > 8_000_000\n+\t\t)\n+\t\t\tthrow new Error(\"invalid canonical frame bound\");\n+\t\tconst size = this.storage.sql\n+\t\t\t.exec(\n+\t\t\t\t\"SELECT COUNT(*) AS parts, COALESCE(SUM(LENGTH(CAST(text AS BLOB))), 0) AS bytes FROM log WHERE seq = ?\",\n+\t\t\t\tseq,\n+\t\t\t)\n+\t\t\t.toArray()[0] as { parts: number; bytes: number };\n+\t\tif (!size || size.parts < 1 || size.parts > 256 || size.bytes > maxBytes)\n+\t\t\tthrow new Error(\"canonical frame exceeds adoption bound or is missing\");\n+\t\tconst rows = this.storage.sql.exec(\"SELECT part, text FROM log WHERE seq = ? ORDER BY part\", seq).toArray() as {\n+\t\t\tpart: number;\n+\t\t\ttext: string;\n+\t\t}[];\n+\t\tif (rows.length !== size.parts || rows.some((row, part) => row.part !== part))\n+\t\t\tthrow new Error(\"canonical frame parts are incomplete\");\n+\t\treturn rows.map((row) => row.text).join(\"\");\n+\t}\n+\n+\t/** Stream one canonical frame without retaining its complete JSON text. */\n+\t*frameChunks(seq: number): IterableIterator<string> {\n+\t\tif (!Number.isSafeInteger(seq) || seq < 0) throw Error(\"invalid canonical frame position\");\n+\t\tlet expected = 0;\n+\t\tfor (;;) {\n+\t\t\tconst rows = this.storage.sql\n+\t\t\t\t.exec(\"SELECT part, text FROM log WHERE seq = ? AND part >= ? ORDER BY part LIMIT 1\", seq, expected)\n+\t\t\t\t.toArray() as { part: number; text: string }[];\n+\t\t\tif (!rows.length) {\n+\t\t\t\tif (!expected) throw Error(\"canonical frame is missing\");\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\tconst row = rows[0]!;\n+\t\t\tif (row.part !== expected || row.text.length > LOG_PART_CHARACTERS)\n+\t\t\t\tthrow Error(\"canonical frame parts are incomplete or oversized\");\n+\t\t\texpected++;\n+\t\t\tyield row.text;\n+\t\t}\n+\t}\n+\n+\t/** Refreshes the in-memory cursor after an enclosing transaction rolls back. */\n+\trefreshSequence(): void {\n+\t\tconst rows = this.storage.sql.exec(\"SELECT COALESCE(MAX(seq), -1) AS last FROM log\").toArray() as {\n+\t\t\tlast: number;\n+\t\t}[];\n+\t\tthis.next = (rows[0]?.last ?? -1) + 1;\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\tlet part = 0;\n+\t\t\t\tfor (const text of streamedLogParts(entry)) {\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, version?: number) {\n+\t\treturn why(this.project, file, line, {\n+\t\t\t...(draft ? { draft } : {}),\n+\t\t\t...(agent ? { agent } : {}),\n+\t\t\t...(version !== undefined ? { version } : {}),\n+\t\t});\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, summary?: boolean) {\n+\t\tconst where = { draft, ...(agent ? { agent } : {}) };\n+\t\treturn summary ? this.project.compareSummary(from, to, where) : this.project.compare(from, to, where);\n+\t}\n+\twithout(version: number, versions: readonly number[]) {\n+\t\treturn this.project.without(version, versions);\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+\t/** A seat's earlier chat hears that another chat used the seat (277, groups); as abso's worker has it. */\n+\tseatNotice(agent: string, place: string, key: string) {\n+\t\treturn this.project.seatNotice(agent, place, key);\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+\tprivate readonly historical: (<T>(at: number, operation: (project: Project) => T) => T) | undefined;\n+\n+\tconstructor(\n+\t\tproject: Project,\n+\t\tread?: (from: number, limit: number) => Entry[],\n+\t\tstore?: SqliteLog,\n+\t\thistorical?: <T>(at: number, operation: (project: Project) => T) => T,\n+\t) {\n+\t\tthis.project = project;\n+\t\tthis.read = read;\n+\t\tthis.store = store;\n+\t\tthis.historical = historical;\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\t// Discard each canonical payload after extracting its event. A feed page must\n+\t\t// not retain every historical file payload in the requested range.\n+\t\tconst events = [];\n+\t\tlet next = start;\n+\t\twhile (next < end && next - start < limit) {\n+\t\t\tconst entries = this.read(next, 1);\n+\t\t\tif (entries.length === 0) break;\n+\t\t\tevents.push(...feedEvents(entries, next));\n+\t\t\tnext += entries.length;\n+\t\t}\n+\t\t// A drop event names the files it took out (#41), so a timeline needs no read per drop.\n+\t\tconst enriched = events.map((e) => {\n+\t\t\tif (e.type !== \"drop\" || e.version === undefined) return e;\n+\t\t\tconst v = this.project.log({ limit: 1, before: e.version + 1 }).versions[0];\n+\t\t\treturn v && v.version === e.version ? { ...e, dropped: v.files } : e;\n+\t\t});\n+\t\treturn { next, end, events: enriched };\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\tif (this.historical)\n+\t\t\treturn this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({\n+\t\t\t\tat: Math.min(at, this.project.logLength),\n+\t\t\t\t...(p.initialized ? p.status() : { version: -1, agents: [] }),\n+\t\t\t}));\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\tif (this.historical)\n+\t\t\treturn this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({\n+\t\t\t\tat: Math.min(at, this.project.logLength),\n+\t\t\t\t...(p.initialized ? where(p) : { version: -1, files: {} }),\n+\t\t\t}));\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+\tfileTextAt(version: number, path: string): string {\n+\t\treturn this.project.viewAt(version).text(path);\n+\t}\n+\t/** One scoped batch: at most 64 files and 64 Ki characters plus one whole file. */\n+\tfileTextsAt(version: number, paths: readonly string[]): Record<string, string> {\n+\t\tconst view = this.project.viewAt(version);\n+\t\tconst files: Record<string, string> = Object.create(null);\n+\t\tlet characters = 0;\n+\t\tfor (const path of paths.slice(0, 64)) {\n+\t\t\tconst text = view.attrs(path).link !== null ? \"\" : view.text(path);\n+\t\t\tfiles[path] = text;\n+\t\t\tcharacters += text.length;\n+\t\t\tif (characters >= 65536) break;\n+\t\t}\n+\t\treturn files;\n+\t}\n+\t/** Capture metadata now; each text read reopens the captured version in a fresh host scope. */\n+\tsharedPushMetadata(): PushSnapshotMetadata {\n+\t\tconst version = this.project.version;\n+\t\tconst view = this.project.viewAt(version);\n+\t\tconst paths: string[] = [];\n+\t\tconst modes: PushSnapshotMetadata[\"modes\"] = Object.create(null);\n+\t\tconst blobs: Record<string, string> = Object.create(null);\n+\t\tfor (const path of view.paths()) {\n+\t\t\tconst attrs = view.attrs(path);\n+\t\t\tmodes[path] = { exec: attrs.exec, link: attrs.link };\n+\t\t\tif (attrs.blob !== null) blobs[path] = attrs.blob;\n+\t\t\telse paths.push(path);\n+\t\t}\n+\t\tconst by = version > 0 ? this.project.published(version) : undefined;\n+\t\treturn { version, paths, modes, blobs, ...(by ? { last: { agent: by.agent, message: by.message } } : {}) };\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+}"}],"unmatched":[]}