{"version":106,"agent":"codex-capacity-policy","message":"Publish reviewed operation framing protocol","time":1791766457867,"timeIso":"2026-10-12T00:54:17.867Z","changes":2,"change":1247,"files":["worker/project/operation-protocol.ts","worker/project/test/operation-protocol.test.ts"],"draft":null,"diff":[{"path":"worker/project/operation-protocol.ts","added":280,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/operation-protocol.ts\n@@ -0,0 +1,280 @@\n+import type { Entry } from \"./project-types.ts\";\n+\n+export const OPERATION_CHUNK_BYTES = 64 * 1024;\n+export const OPERATION_CHUNK_ENTRIES = 32;\n+export const OPERATION_MAX_BYTES = 4 * 1024 * 1024;\n+export const OPERATION_MAX_CHUNKS = 64;\n+\n+export interface OperationHeads {\n+\treadonly log: number;\n+\treadonly shared: number;\n+\treadonly actorMine: number;\n+\treadonly actorBase: number;\n+\treadonly queueRevision: number;\n+}\n+\n+export interface OperationQueueEffect {\n+\treadonly kind: \"enqueue\";\n+\treadonly queueId: number;\n+\treadonly actor: string;\n+\treadonly entryIndex: number;\n+\treadonly position: number;\n+}\n+\n+export interface OperationLogSummary {\n+\treadonly lines: number;\n+\treadonly keys: number;\n+\treadonly chars: number;\n+\treadonly sharedVersion?: number;\n+\treadonly lastPublish?: { readonly agent: string; readonly time: number };\n+}\n+\n+export interface ProjectOperation {\n+\treadonly id: string;\n+\treadonly tenant: string;\n+\treadonly project: string;\n+\treadonly incarnation: string;\n+\treadonly actor: string;\n+\treadonly build: string;\n+\treadonly executorIdentity: string;\n+\treadonly rootDigest: string;\n+\treadonly authorizationRevision: string;\n+\treadonly policyRevision: string;\n+\treadonly operationTime: number;\n+\treadonly queuePolicy: { readonly policyRevision: string; readonly checkerReady: boolean };\n+\treadonly generation: number;\n+\treadonly heads: OperationHeads;\n+\treadonly message: string;\n+\treadonly files: Readonly<Record<string, string | null>>;\n+}\n+\n+export interface OperationFence {\n+\treadonly tenant: string;\n+\treadonly project: string;\n+\treadonly incarnation: string;\n+\treadonly actor: string;\n+\treadonly build: string;\n+\treadonly executorIdentity: string;\n+\treadonly rootDigest: string;\n+\treadonly authorizationRevision: string;\n+\treadonly policyRevision: string;\n+\treadonly generation: number;\n+\treadonly heads: OperationHeads;\n+}\n+\n+export interface OperationProjection {\n+\treadonly sharedHead: number;\n+\treadonly actorMineHead: number;\n+\treadonly actorBaseHead: number;\n+\treadonly queueRevision: number;\n+\treadonly queueEffects: readonly OperationQueueEffect[];\n+\treadonly logSummary: OperationLogSummary;\n+}\n+\n+export interface OperationReceipt {\n+\treadonly id: string;\n+\treadonly tenant: string;\n+\treadonly project: string;\n+\treadonly incarnation: string;\n+\treadonly actor: string;\n+\treadonly build: string;\n+\treadonly executorIdentity: string;\n+\treadonly authorizationRevision: string;\n+\treadonly policyRevision: string;\n+\treadonly generation: number;\n+\treadonly previousRootDigest: string;\n+\treadonly nextRootDigest: string;\n+\treadonly previousHeads: OperationHeads;\n+\treadonly nextHeads: OperationHeads;\n+\treadonly requestDigest: string;\n+\treadonly outputDigest: string;\n+\treadonly entryCount: number;\n+\treadonly queueRevision: number;\n+\treadonly queueEffects: readonly OperationQueueEffect[];\n+\treadonly status: \"committed\";\n+}\n+\n+export interface OperationChunk {\n+\treadonly index: number;\n+\treadonly firstEntry: number;\n+\treadonly count: number;\n+\treadonly bytes: number;\n+\treadonly entries: readonly Entry[];\n+\treadonly text: string;\n+\treadonly digest: string;\n+\treadonly chain: string;\n+}\n+\n+export function canonicalJson(value: unknown): string {\n+\tif (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n+\tif (value && typeof value === \"object\") {\n+\t\tconst record = value as Record<string, unknown>;\n+\t\treturn `{${Object.keys(record)\n+\t\t\t.sort()\n+\t\t\t.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)\n+\t\t\t.join(\",\")}}`;\n+\t}\n+\treturn JSON.stringify(value);\n+}\n+\n+export function encodeEntries(entries: readonly Entry[]): string {\n+\treturn canonicalJson(entries);\n+}\n+\n+export async function digestText(text: string): Promise<string> {\n+\tconst bytes = new TextEncoder().encode(text);\n+\tconst digest = await crypto.subtle.digest(\"SHA-256\", bytes);\n+\treturn [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n+}\n+\n+export async function chainDigest(\n+\tprevious: string,\n+\tindex: number,\n+\tcount: number,\n+\tbytes: number,\n+\tdigest: string,\n+): Promise<string> {\n+\treturn digestText(canonicalJson({ previous, index, count, bytes, digest }));\n+}\n+\n+export async function digestOperation(operation: ProjectOperation): Promise<string> {\n+\treturn digestText(canonicalJson(operation));\n+}\n+\n+function* jsonTokens(value: unknown, ancestors = new Set<object>()): Generator<string> {\n+\tif (value === null || typeof value === \"boolean\") {\n+\t\tyield String(value);\n+\t\treturn;\n+\t}\n+\tif (typeof value === \"number\") {\n+\t\tyield Number.isFinite(value) ? JSON.stringify(value) : \"null\";\n+\t\treturn;\n+\t}\n+\tif (typeof value === \"string\") {\n+\t\tyield '\"';\n+\t\tfor (const point of value) {\n+\t\t\tconst code = point.charCodeAt(0);\n+\t\t\tif (point === '\"') yield '\\\\\"';\n+\t\t\telse if (point === \"\\\\\") yield \"\\\\\\\\\";\n+\t\t\telse if (point === \"\\b\") yield \"\\\\b\";\n+\t\t\telse if (point === \"\\f\") yield \"\\\\f\";\n+\t\t\telse if (point === \"\\n\") yield \"\\\\n\";\n+\t\t\telse if (point === \"\\r\") yield \"\\\\r\";\n+\t\t\telse if (point === \"\\t\") yield \"\\\\t\";\n+\t\t\telse if (code < 0x20 || (point.length === 1 && code >= 0xd800 && code <= 0xdfff))\n+\t\t\t\tyield `\\\\u${code.toString(16).padStart(4, \"0\")}`;\n+\t\t\telse yield point;\n+\t\t}\n+\t\tyield '\"';\n+\t\treturn;\n+\t}\n+\tif (Array.isArray(value)) {\n+\t\tif (ancestors.has(value)) throw new TypeError(\"cannot serialize a cyclic entry\");\n+\t\tancestors.add(value);\n+\t\tyield \"[\";\n+\t\tfor (let index = 0; index < value.length; index++) {\n+\t\t\tif (index) yield \",\";\n+\t\t\tyield* jsonTokens(value[index] ?? null, ancestors);\n+\t\t}\n+\t\tyield \"]\";\n+\t\tancestors.delete(value);\n+\t\treturn;\n+\t}\n+\tif (value && typeof value === \"object\") {\n+\t\tconst record = value as Record<string, unknown>;\n+\t\tif (ancestors.has(record)) throw new TypeError(\"cannot serialize a cyclic entry\");\n+\t\tancestors.add(record);\n+\t\tyield \"{\";\n+\t\tlet first = true;\n+\t\tfor (const key in record) {\n+\t\t\tif (!Object.hasOwn(record, key)) continue;\n+\t\t\tconst child = record[key];\n+\t\t\tif (child === undefined || typeof child === \"function\" || typeof child === \"symbol\") continue;\n+\t\t\tif (!first) yield \",\";\n+\t\t\tfirst = false;\n+\t\t\tyield* jsonTokens(key, ancestors);\n+\t\t\tyield \":\";\n+\t\t\tyield* jsonTokens(child, ancestors);\n+\t\t}\n+\t\tyield \"}\";\n+\t\tancestors.delete(record);\n+\t\treturn;\n+\t}\n+\tif (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") {\n+\t\tyield \"null\";\n+\t\treturn;\n+\t}\n+\tthrow new TypeError(\"entry contains an unsupported JSON value\");\n+}\n+\n+export interface Utf8Frame {\n+\treadonly text: string;\n+\treadonly bytes: number;\n+}\n+\n+export function* utf8JsonFrames(value: unknown): Generator<Utf8Frame> {\n+\tlet frame = \"\";\n+\tlet bytes = 0;\n+\tfor (const token of jsonTokens(value)) {\n+\t\tfor (const point of token) {\n+\t\t\tconst size = new TextEncoder().encode(point).byteLength;\n+\t\t\tif (bytes + size > OPERATION_CHUNK_BYTES) {\n+\t\t\t\tyield { text: frame, bytes };\n+\t\t\t\tframe = \"\";\n+\t\t\t\tbytes = 0;\n+\t\t\t}\n+\t\t\tframe += point;\n+\t\t\tbytes += size;\n+\t\t}\n+\t}\n+\tif (frame || bytes === 0) yield { text: frame, bytes };\n+}\n+\n+export function measureUtf8Json(value: unknown): { bytes: number; frames: number } {\n+\tlet bytes = 0;\n+\tlet frames = 0;\n+\tfor (const frame of utf8JsonFrames(value)) {\n+\t\tbytes += frame.bytes;\n+\t\tframes++;\n+\t}\n+\treturn { bytes, frames };\n+}\n+\n+/**\n+ * Emits bounded JSON chunks for small entries. The store separately frames a\n+ * single large entry; this helper intentionally keeps its array contract.\n+ */\n+export async function* chunkEntries(entries: Iterable<Entry>): AsyncGenerator<OperationChunk> {\n+\tlet index = 0;\n+\tlet firstEntry = 0;\n+\tlet previous = \"\";\n+\tlet batch: Entry[] = [];\n+\tlet batchBytes = 2;\n+\tfor (const entry of entries) {\n+\t\tconst text = canonicalJson(entry);\n+\t\tconst size = new TextEncoder().encode(text).byteLength;\n+\t\tif (size + 2 > OPERATION_CHUNK_BYTES) throw new RangeError(\"one operation entry requires split UTF-8 framing\");\n+\t\tconst withComma = size + (batch.length ? 1 : 0);\n+\t\tif (batch.length && (batch.length >= OPERATION_CHUNK_ENTRIES || batchBytes + withComma > OPERATION_CHUNK_BYTES)) {\n+\t\t\tconst chunkText = encodeEntries(batch);\n+\t\t\tconst bytes = new TextEncoder().encode(chunkText).byteLength;\n+\t\t\tconst digest = await digestText(chunkText);\n+\t\t\tconst chain = await chainDigest(previous, index, batch.length, bytes, digest);\n+\t\t\tyield { index, firstEntry, count: batch.length, bytes, entries: batch, text: chunkText, digest, chain };\n+\t\t\tprevious = chain;\n+\t\t\tfirstEntry += batch.length;\n+\t\t\tindex++;\n+\t\t\tbatch = [];\n+\t\t\tbatchBytes = 2;\n+\t\t}\n+\t\tbatch.push(entry);\n+\t\tbatchBytes += size + (batch.length > 1 ? 1 : 0);\n+\t}\n+\tif (batch.length) {\n+\t\tconst text = encodeEntries(batch);\n+\t\tconst bytes = new TextEncoder().encode(text).byteLength;\n+\t\tconst digest = await digestText(text);\n+\t\tconst chain = await chainDigest(previous, index, batch.length, bytes, digest);\n+\t\tyield { index, firstEntry, count: batch.length, bytes, entries: batch, text, digest, chain };\n+\t}\n+}"},{"path":"worker/project/test/operation-protocol.test.ts","added":85,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/operation-protocol.test.ts\n@@ -0,0 +1,85 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import {\n+\tcanonicalJson,\n+\tchunkEntries,\n+\tdigestOperation,\n+\ttype OperationChunk,\n+\ttype ProjectOperation,\n+\tutf8JsonFrames,\n+} from \"../operation-protocol.ts\";\n+import type { Entry } from \"../project-types.ts\";\n+\n+const operation: ProjectOperation = {\n+\tid: \"op-1\",\n+\ttenant: \"tenant-1\",\n+\tproject: \"project-1\",\n+\tincarnation: \"incarnation-1\",\n+\tactor: \"builder\",\n+\tbuild: \"build-1\",\n+\texecutorIdentity: \"trusted-local-executor\",\n+\trootDigest: \"root-0\",\n+\tauthorizationRevision: \"auth-1\",\n+\tpolicyRevision: \"policy-1\",\n+\toperationTime: 20,\n+\tqueuePolicy: { policyRevision: \"policy-1\", checkerReady: false },\n+\tgeneration: 0,\n+\theads: { log: 0, shared: 0, actorMine: 0, actorBase: 0, queueRevision: 0 },\n+\tmessage: \"record and publish\",\n+\tfiles: { \"readme.txt\": \"updated\\n\" },\n+};\n+\n+test(\"canonical request binding ignores object property order and binds every request field\", async () => {\n+\tconst reordered = {\n+\t\t...operation,\n+\t\tfiles: { \"readme.txt\": \"updated\\n\" },\n+\t\theads: { actorBase: 0, actorMine: 0, shared: 0, log: 0, queueRevision: 0 },\n+\t};\n+\tassert.equal(await digestOperation(operation), await digestOperation(reordered));\n+\tassert.notEqual(\n+\t\tawait digestOperation(operation),\n+\t\tawait digestOperation({ ...operation, authorizationRevision: \"revoked\" }),\n+\t);\n+\tassert.notEqual(\n+\t\tawait digestOperation(operation),\n+\t\tawait digestOperation({ ...operation, files: { \"readme.txt\": \"other\\n\" } }),\n+\t);\n+\tassert.notEqual(await digestOperation(operation), await digestOperation({ ...operation, operationTime: 21 }));\n+\tassert.notEqual(\n+\t\tawait digestOperation(operation),\n+\t\tawait digestOperation({ ...operation, queuePolicy: { ...operation.queuePolicy, checkerReady: true } }),\n+\t);\n+\tassert.equal(canonicalJson({ z: 1, a: 2 }), '{\"a\":2,\"z\":1}');\n+});\n+\n+test(\"chunk generator preserves exact order with bounded entries and UTF-8 byte accounting\", async () => {\n+\tconst entries: Entry[] = Array.from({ length: 70 }, (_, index) => ({\n+\t\ttype: \"join\",\n+\t\tagent: `agent-${index}`,\n+\t\tversion: index,\n+\t\ttime: index,\n+\t}));\n+\tconst chunks: OperationChunk[] = [];\n+\tfor await (const chunk of chunkEntries(entries)) chunks.push(chunk);\n+\tassert.deepEqual(\n+\t\tchunks.flatMap((chunk) => chunk.entries),\n+\t\tentries,\n+\t);\n+\tassert.ok(chunks.every((chunk, index) => chunk.index === index && chunk.count <= 32 && chunk.bytes <= 64 * 1024));\n+\tassert.deepEqual(\n+\t\tchunks.map((chunk) => chunk.firstEntry),\n+\t\t[0, 32, 64],\n+\t);\n+\tassert.ok(chunks.every((chunk, index) => index === 0 || chunk.chain !== chunks[index - 1]!.chain));\n+\n+\tconst large: Entry = { type: \"join\", agent: \"🙂\".repeat(8_000), version: 0, time: 1 };\n+\tconst utf8: OperationChunk[] = [];\n+\tfor await (const chunk of chunkEntries([large])) utf8.push(chunk);\n+\tassert.ok(utf8[0]!.bytes > JSON.stringify(large).length);\n+\tassert.ok(utf8[0]!.bytes <= 64 * 1024);\n+\tconst largeEntry: Entry = { type: \"join\", agent: `🙂\\n\"`.repeat(20_000), version: 0, time: 1 };\n+\tconst frames = [...utf8JsonFrames(largeEntry)];\n+\tassert.ok(frames.length > 1);\n+\tassert.ok(frames.every((frame) => frame.bytes <= 64 * 1024));\n+\tassert.deepEqual(JSON.parse(frames.map((frame) => frame.text).join(\"\")), largeEntry);\n+});"}],"ci":null}