{"version":165,"agent":"codex-capacity-chair","message":"Stream projection atom hashing and comparison and reduce locator writes","time":1791953498109,"timeIso":"2026-10-14T04:51:38.109Z","changes":8,"change":2465,"files":["src/engine/experimental/projection-atom-index.ts","src/engine/experimental/projection-locator.ts","src/engine/experimental/projection-marker.ts","src/engine/json-value-chunks.ts","src/engine/test/json-value-chunks.test.ts","src/engine/test/projection-atom-index.test.ts","src/engine/test/projection-locator.test.ts","src/engine/test/projection-marker.test.ts"],"draft":null,"diff":[{"path":"src/engine/experimental/projection-atom-index.ts","added":4,"removed":1,"diff":"--- a/src/engine/experimental/projection-atom-index.ts\n+++ b/src/engine/experimental/projection-atom-index.ts\n@@ -1,4 +1,5 @@\n import { createHash } from \"node:crypto\";\n+import { jsonValueChunks } from \"../json-value-chunks.ts\";\n import type { GraphStateStorage } from \"../state-source.ts\";\n import type { Atom, AttrSet, Relocation } from \"../types.ts\";\n \n@@ -173,6 +174,8 @@\n \n /** Opt-in persistent Graph callback: indexes the just-accepted canonical atom. */\n export function indexAcceptedProjectionAtom(atom: Atom, files: readonly string[], storage: GraphStateStorage): void {\n-\tconst digest = createHash(\"sha256\").update(JSON.stringify(atom)).digest(\"hex\");\n+\tconst hash = createHash(\"sha256\");\n+\tfor (const chunk of jsonValueChunks(atom)) hash.update(chunk);\n+\tconst digest = hash.digest(\"hex\");\n \tnew ProjectionAtomIndex(storage).put(atom, digest, files);\n }"},{"path":"src/engine/experimental/projection-locator.ts","added":3,"removed":34,"diff":"--- a/src/engine/experimental/projection-locator.ts\n+++ b/src/engine/experimental/projection-locator.ts\n@@ -55,14 +55,6 @@\n \t\t\tif (!/^[0-9a-f]$/.test(digit) || !safe(child) || child === id) throw Error(\"invalid locator child\");\n \t\treturn row as unknown as Branch;\n \t}\n-\t#write(node: Node): number {\n-\t\tconst next = this.#storage.read(this.#collection, \"next\") ?? 0;\n-\t\tif (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error(\"invalid locator allocation\");\n-\t\tif (this.#storage.read(this.#collection, String(next)) !== undefined) throw Error(\"locator allocation collision\");\n-\t\tthis.#storage.write(this.#collection, String(next), node);\n-\t\tthis.#storage.write(this.#collection, \"next\", next + 1);\n-\t\treturn next;\n-\t}\n \t/** Update each touched branch once, retaining at most 256 decoded values. */\n \tsetMany(root: Page, values: ReadonlyArray<readonly [number, T]>): Page {\n \t\tpage(root);\n@@ -149,31 +141,8 @@\n \t}\n \n \tset(root: Page, id: number, value: T): number {\n-\t\tpage(root);\n-\t\tconst key = keyOf(id),\n-\t\t\tchecked = structuredClone(this.#decode(structuredClone(value)));\n-\t\treturn this.#storage.transaction(() => {\n-\t\t\tconst visit = (current: Page, parent?: string, digit?: string, depth = 0): number => {\n-\t\t\t\tif (depth > 8) throw Error(\"invalid locator depth\");\n-\t\t\t\tif (current === null) return this.#write({ format: 1, kind: \"leaf\", prefix: key, value: checked });\n-\t\t\t\tconst node = this.#read(current, parent, digit);\n-\t\t\t\tlet common = 0;\n-\t\t\t\twhile (common < node.prefix.length && node.prefix[common] === key[common]) common++;\n-\t\t\t\tif (common < node.prefix.length) {\n-\t\t\t\t\tconst leaf = this.#write({ format: 1, kind: \"leaf\", prefix: key, value: checked });\n-\t\t\t\t\treturn this.#write({\n-\t\t\t\t\t\tformat: 1,\n-\t\t\t\t\t\tkind: \"branch\",\n-\t\t\t\t\t\tprefix: key.slice(0, common),\n-\t\t\t\t\t\tchildren: { [node.prefix[common]!]: current, [key[common]!]: leaf },\n-\t\t\t\t\t});\n-\t\t\t\t}\n-\t\t\t\tif (node.kind === \"leaf\") return this.#write({ format: 1, kind: \"leaf\", prefix: key, value: checked });\n-\t\t\t\tconst nextDigit = key[common]!;\n-\t\t\t\tconst child = visit(node.children[nextDigit] ?? null, node.prefix, nextDigit, depth + 1);\n-\t\t\t\treturn this.#write({ ...node, children: { ...node.children, [nextDigit]: child } });\n-\t\t\t};\n-\t\t\treturn visit(root);\n-\t\t});\n+\t\t// A nonempty batch always produces a root. Share its single allocation-counter\n+\t\t// commit instead of rewriting that counter for every copied path node.\n+\t\treturn this.setMany(root, [[id, value]])!;\n \t}\n }"},{"path":"src/engine/experimental/projection-marker.ts","added":3,"removed":2,"diff":"--- a/src/engine/experimental/projection-marker.ts\n+++ b/src/engine/experimental/projection-marker.ts\n@@ -1,4 +1,5 @@\n import type { Graph } from \"../graph.ts\";\n+import { equalJsonValues } from \"../json-value-chunks.ts\";\n import { orderedChildKey } from \"../ordered-index.ts\";\n import { resolveScratchMoves } from \"../relocation-scratch.ts\";\n import type { GraphStateStorage } from \"../state-source.ts\";\n@@ -112,7 +113,7 @@\n \t}\n \tapply(previous: MarkerState, atom: Atom): MarkerState {\n \t\tthis.assertContext(previous);\n-\t\tif (JSON.stringify(this.graph.atom(atom.id)) !== JSON.stringify(atom)) throw Error(\"canonical atom mismatch\");\n+\t\tif (!equalJsonValues(this.graph.atom(atom.id), atom)) throw Error(\"canonical atom mismatch\");\n \t\tif (this.members.get(previous.membership, atom.seq)?.present) return previous;\n \t\tfor (const id of atom.deps)\n \t\t\tif (!this.members.get(previous.membership, this.graph.atom(id).seq)?.present) throw Error(\"missing dependency\");\n@@ -187,7 +188,7 @@\n \t}\n \tremoveAtom(previous: MarkerState, atom: Atom): MarkerState {\n \t\tthis.assertContext(previous);\n-\t\tif (JSON.stringify(this.graph.atom(atom.id)) !== JSON.stringify(atom)) throw Error(\"canonical atom mismatch\");\n+\t\tif (!equalJsonValues(this.graph.atom(atom.id), atom)) throw Error(\"canonical atom mismatch\");\n \t\tif (!this.members.get(previous.membership, atom.seq)?.present) return previous;\n \t\tif (required(this.members.get(previous.membership, atom.seq)).dependents)\n \t\t\tthrow Error(\"included dependent prevents removal\");"},{"path":"src/engine/json-value-chunks.ts","added":94,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/json-value-chunks.ts\n@@ -0,0 +1,94 @@\n+/** JSON.stringify-compatible chunks for canonical data, without a whole-value string.\n+ * Individual input strings and object key lists still belong to the caller.\n+ */\n+export function* jsonValueChunks(input: unknown): IterableIterator<string> {\n+\tconst active = new Set<object>();\n+\tfunction* string(value: string): IterableIterator<string> {\n+\t\tyield '\"';\n+\t\tfor (let from = 0; from < value.length; ) {\n+\t\t\tlet end = Math.min(from + 16384, value.length);\n+\t\t\tconst last = value.charCodeAt(end - 1),\n+\t\t\t\tnext = value.charCodeAt(end);\n+\t\t\tif (last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) end--;\n+\t\t\tyield JSON.stringify(value.slice(from, end)).slice(1, -1);\n+\t\t\tfrom = end;\n+\t\t}\n+\t\tyield '\"';\n+\t}\n+\tconst normalize = (value: unknown, key: string): unknown => {\n+\t\tif (value !== null && typeof value === \"object\") {\n+\t\t\tconst toJSON = (value as { toJSON?: unknown }).toJSON;\n+\t\t\tif (typeof toJSON === \"function\") return toJSON.call(value, key);\n+\t\t}\n+\t\treturn value;\n+\t};\n+\tconst omitted = (value: unknown) => value === undefined || typeof value === \"function\" || typeof value === \"symbol\";\n+\tfunction* encode(value: unknown): IterableIterator<string> {\n+\t\tif (typeof value === \"string\") yield* string(value);\n+\t\telse if (value === null || typeof value === \"boolean\" || typeof value === \"number\") yield JSON.stringify(value);\n+\t\telse if (typeof value !== \"object\" || value === null) throw Error(\"unsupported canonical JSON value\");\n+\t\telse {\n+\t\t\tif (active.has(value)) throw Error(\"cyclic canonical JSON value\");\n+\t\t\tif (active.size >= 128) throw Error(\"canonical JSON depth exceeds bound\");\n+\t\t\tactive.add(value);\n+\t\t\ttry {\n+\t\t\t\tif (Array.isArray(value)) {\n+\t\t\t\t\tyield \"[\";\n+\t\t\t\t\tconst length = value.length;\n+\t\t\t\t\tfor (let i = 0; i < length; i++) {\n+\t\t\t\t\t\tif (i) yield \",\";\n+\t\t\t\t\t\tconst child = normalize(value[i], String(i));\n+\t\t\t\t\t\tyield* encode(omitted(child) ? null : child);\n+\t\t\t\t\t}\n+\t\t\t\t\tyield \"]\";\n+\t\t\t\t} else {\n+\t\t\t\t\tyield \"{\";\n+\t\t\t\t\tlet first = true;\n+\t\t\t\t\tfor (const key of Object.keys(value)) {\n+\t\t\t\t\t\tconst child = normalize((value as Record<string, unknown>)[key], key);\n+\t\t\t\t\t\tif (omitted(child)) continue;\n+\t\t\t\t\t\tif (!first) yield \",\";\n+\t\t\t\t\t\tfirst = false;\n+\t\t\t\t\t\tyield* string(key);\n+\t\t\t\t\t\tyield \":\";\n+\t\t\t\t\t\tyield* encode(child);\n+\t\t\t\t\t}\n+\t\t\t\t\tyield \"}\";\n+\t\t\t\t}\n+\t\t\t} finally {\n+\t\t\t\tactive.delete(value);\n+\t\t\t}\n+\t\t}\n+\t}\n+\tyield* encode(normalize(input, \"\"));\n+}\n+\n+/** Exact serialized-content equality, retaining only the current pair of chunks. */\n+export function equalJsonValues(left: unknown, right: unknown): boolean {\n+\tconst a = jsonValueChunks(left),\n+\t\tb = jsonValueChunks(right);\n+\tlet x = a.next(),\n+\t\ty = b.next(),\n+\t\ti = 0,\n+\t\tj = 0;\n+\ttry {\n+\t\tfor (;;) {\n+\t\t\twhile (!x.done && i === x.value.length) {\n+\t\t\t\tx = a.next();\n+\t\t\t\ti = 0;\n+\t\t\t}\n+\t\t\twhile (!y.done && j === y.value.length) {\n+\t\t\t\ty = b.next();\n+\t\t\t\tj = 0;\n+\t\t\t}\n+\t\t\tif (x.done || y.done) return x.done === y.done;\n+\t\t\tconst length = Math.min(x.value.length - i, y.value.length - j);\n+\t\t\tif (x.value.slice(i, i + length) !== y.value.slice(j, j + length)) return false;\n+\t\t\ti += length;\n+\t\t\tj += length;\n+\t\t}\n+\t} finally {\n+\t\ta.return?.();\n+\t\tb.return?.();\n+\t}\n+}"},{"path":"src/engine/test/json-value-chunks.test.ts","added":66,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/json-value-chunks.test.ts\n@@ -0,0 +1,66 @@\n+import assert from \"node:assert/strict\";\n+import { createHash } from \"node:crypto\";\n+import { test } from \"node:test\";\n+import { equalJsonValues, jsonValueChunks } from \"../json-value-chunks.ts\";\n+\n+test(\"canonical JSON chunks preserve scalar, container and toJSON encoding\", () => {\n+\tconst values = [\n+\t\tnull,\n+\t\ttrue,\n+\t\tfalse,\n+\t\t0,\n+\t\t-0,\n+\t\t1.25,\n+\t\tNaN,\n+\t\tInfinity,\n+\t\t{ z: undefined, a: [undefined, null, 'quoted\"\\n\\t\\\\', \"\\ud800\", \"\\udc00\", \"\\u2028\\u2029\"] },\n+\t\tnew Array(3),\n+\t\t{ 20: \"twenty\", 2: \"two\", before: 1, after: 2 },\n+\t\t{\n+\t\t\tnested: {\n+\t\t\t\ttoJSON(key: string) {\n+\t\t\t\t\treturn { key, value: \"converted\" };\n+\t\t\t\t},\n+\t\t\t},\n+\t\t},\n+\t\tJSON.parse('{\"__proto__\":\"data\",\"constructor\":\"also data\"}'),\n+\t];\n+\tfor (const value of values) assert.equal([...jsonValueChunks(value)].join(\"\"), JSON.stringify(value));\n+\tfor (const left of values)\n+\t\tfor (const right of values)\n+\t\t\tassert.equal(equalJsonValues(left, right), JSON.stringify(left) === JSON.stringify(right));\n+});\n+\n+test(\"canonical JSON string chunks preserve every surrogate split and bound escaped output\", () => {\n+\tfor (const offset of [16382, 16383, 16384, 16385]) {\n+\t\tconst value = { text: `${\"a\".repeat(offset)}\\ud83d\\ude80${\"\\u0000\".repeat(40000)}\\ud800` };\n+\t\tconst hash = createHash(\"sha256\");\n+\t\tfor (const chunk of jsonValueChunks(value)) {\n+\t\t\tassert.ok(chunk.length <= 16384 * 6);\n+\t\t\thash.update(chunk);\n+\t\t}\n+\t\tassert.equal(hash.digest(\"hex\"), createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\"));\n+\t}\n+});\n+\n+test(\"canonical JSON visits large arrays incrementally and rejects cycles\", () => {\n+\tlet reads = 0;\n+\tconst values = new Proxy(new Array(10000), {\n+\t\tget(target, key, receiver) {\n+\t\t\tif (typeof key === \"string\" && /^[0-9]+$/.test(key)) {\n+\t\t\t\treads++;\n+\t\t\t\treturn Number(key);\n+\t\t\t}\n+\t\t\treturn Reflect.get(target, key, receiver);\n+\t\t},\n+\t});\n+\tconst chunks = jsonValueChunks(values);\n+\tassert.equal(chunks.next().value, \"[\");\n+\tassert.equal(reads, 0);\n+\tassert.equal(chunks.next().value, \"0\");\n+\tassert.equal(reads, 1);\n+\tchunks.return?.();\n+\tconst cyclic: unknown[] = [];\n+\tcyclic.push(cyclic);\n+\tassert.throws(() => [...jsonValueChunks(cyclic)], /cyclic/);\n+});"},{"path":"src/engine/test/projection-atom-index.test.ts","added":15,"removed":0,"diff":"--- a/src/engine/test/projection-atom-index.test.ts\n+++ b/src/engine/test/projection-atom-index.test.ts\n@@ -11,6 +11,21 @@\n import { Repo } from \"./helpers.ts\";\n import { SqlState } from \"./storage-helper.ts\";\n \n+test(\"accepted atom indexing preserves the original digest without serializing the whole atom\", (t) => {\n+\tconst db = new SqlState();\n+\tt.after(() => db.db.close());\n+\tconst repo = Repo.init({ \"a.txt\": `${\"x\".repeat(16383)}\\ud83d\\ude80\\n${\"\\u0000\".repeat(20000)}\\n` });\n+\tconst atom = repo.graph.atom(\"a0\");\n+\tconst expected = createHash(\"sha256\").update(JSON.stringify(atom)).digest(\"hex\");\n+\tconst stringify = JSON.stringify;\n+\tt.mock.method(JSON, \"stringify\", (...args: Parameters<typeof JSON.stringify>) => {\n+\t\tassert.notEqual(args[0], atom, \"indexing must not rematerialize the full atom JSON\");\n+\t\treturn stringify(...args);\n+\t});\n+\tindexAcceptedProjectionAtom(atom, [\"a.txt\"], db);\n+\tassert.equal(new ProjectionAtomIndex(db).openAccepted(\"a0\").digest, expected);\n+});\n+\n test(\"projection atom descriptors exclude inserted text and read one indexed item\", () => {\n \tconst db = new SqlState();\n \ttry {"},{"path":"src/engine/test/projection-locator.test.ts","added":9,"removed":1,"diff":"--- a/src/engine/test/projection-locator.test.ts\n+++ b/src/engine/test/projection-locator.test.ts\n@@ -114,6 +114,7 @@\n \t\tlet seed = 12345;\n \t\tconst random = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0);\n \t\tconst keys = [0, 0xffffffff, 1, 16, 255, 256, ...Array.from({ length: 60 }, random)];\n+\t\tconst expected = new Map<number, number>();\n \t\tfor (let round = 0; round < 8; round++) {\n \t\t\tconst edits: [number, number][] = Array.from({ length: 64 }, (_, i) => [\n \t\t\t\tkeys[random() % keys.length]!,\n@@ -122,8 +123,15 @@\n \t\t\tconst prior: number | null = left;\n \t\t\tconst oldEntries: (readonly [number, number])[] = [...batched.entries(prior)];\n \t\t\tleft = batched.setMany(left, edits);\n-\t\t\tfor (const [key, value] of edits) right = sequential.set(right, key, value);\n+\t\t\tfor (const [key, value] of edits) {\n+\t\t\t\tright = sequential.set(right, key, value);\n+\t\t\t\texpected.set(key, value);\n+\t\t\t}\n \t\t\tassert.deepEqual([...batched.entries(left)], [...sequential.entries(right)]);\n+\t\t\tassert.deepEqual(\n+\t\t\t\t[...batched.entries(left)],\n+\t\t\t\t[...expected].sort(([a], [b]) => a - b),\n+\t\t\t);\n \t\t\tassert.deepEqual([...batched.entries(prior)], oldEntries);\n \t\t}\n \t} finally {"},{"path":"src/engine/test/projection-marker.test.ts","added":22,"removed":0,"diff":"--- a/src/engine/test/projection-marker.test.ts\n+++ b/src/engine/test/projection-marker.test.ts\n@@ -6,6 +6,28 @@\n import { Repo } from \"./helpers.ts\";\n import { SqlState } from \"./storage-helper.ts\";\n \n+test(\"projection apply and removal compare atom contents without whole-atom JSON\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst repo = Repo.init({ \"f.txt\": `${\"x\".repeat(40000)}\\n` });\n+\tconst atom = repo.graph.atom(\"a0\");\n+\tconst projection = new MarkerProjection(storage, repo.graph, \"f.txt\", \"streamed-comparison\");\n+\tconst stringify = JSON.stringify;\n+\tt.mock.method(JSON, \"stringify\", (...args: Parameters<typeof JSON.stringify>) => {\n+\t\tassert.notEqual(args[0], atom, \"projection validation must not serialize the full atom\");\n+\t\treturn stringify(...args);\n+\t});\n+\tconst state = projection.apply(projection.empty(), atom);\n+\tconst before = storage.writes;\n+\tconst altered = { ...atom, message: \"forged\" };\n+\tassert.throws(() => projection.apply(state, altered), /canonical atom mismatch/);\n+\tassert.throws(() => projection.removeAtom(state, altered), /canonical atom mismatch/);\n+\tassert.equal(storage.writes, before);\n+\tconst removed = projection.removeAtom(state, atom);\n+\tassert.deepEqual(projection.lines(removed, \"f.txt\"), []);\n+\tassert.equal(projection.lines(state, \"f.txt\").length, 1);\n+});\n+\n test(\"typed marker projection matches mixed multi-file edits and reverse removals\", () => {\n \tconst db = new SqlState();\n \ttry {"}],"ci":null}