{"version":175,"agent":"codex-capacity-chair","message":"Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.","time":1791967673854,"timeIso":"2026-10-14T08:47:53.854Z","changes":27,"change":2738,"files":["server/test/definition-scratch-runtime.test.ts","server/test/long-text-history.test.ts","src/engine/build.ts","src/engine/experimental/projection-marker.ts","src/engine/experimental/projection-reader.ts","src/engine/graph.ts","src/engine/json-value-chunks.ts","src/engine/test/build-lazy-lines.test.ts","src/engine/test/graph-line-chunks.test.ts","src/engine/test/json-string-chunks.test.ts","src/engine/test/projection-read-scope.test.ts","src/engine/test/streamed-diff.test.ts","src/engine/text.ts","src/engine/view.ts","worker/project/add-draft.ts","worker/project/definition-code.ts","worker/project/definitions.ts","worker/project/express-moves.ts","worker/project/markers.ts","worker/project/move-line-text.ts","worker/project/names.ts","worker/project/record-file.ts","worker/project/test/definition-code.test.ts","worker/project/test/definitions.test.ts","worker/project/test/move-line-text.test.ts","worker/project/test/move-reconstruction.test.ts","worker/project/test/record-stream.test.ts"],"draft":null,"diff":[{"path":"server/test/definition-scratch-runtime.test.ts","added":55,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/definition-scratch-runtime.test.ts\n@@ -0,0 +1,55 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { answer } from \"../../worker/project/http.ts\";\n+import { Project } from \"../../worker/project/project.ts\";\n+import { DiskFirstRuntime } from \"../src/disk-first-runtime.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"scratch-backed definition scanning preserves code-file record and publish\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"text-bound\", \"text-bound\");\n+\tconst unchanged = \"stable\".repeat(10000);\n+\tconst old = `${\"old\".repeat(20000)}\\n${unchanged}\\n`;\n+\tconst current = `changed\\n${unchanged}\\n`;\n+\tassert.equal(\n+\t\truntime().initialize(\n+\t\t\t(c) => answer(c, \"init\", undefined, { files: { f: old } }),\n+\t\t\t() => {},\n+\t\t).status,\n+\t\t200,\n+\t);\n+\twhile (!runtime().preparePage(() => {}).ready) {}\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full history replay forbidden\");\n+\t});\n+\n+\tassert.equal(\n+\t\truntime().write(\n+\t\t\t(c) => answer(c, \"record\", \"writer\", { files: { f: current } }),\n+\t\t\t() => {},\n+\t\t).status,\n+\t\t200,\n+\t);\n+\tassert.equal(\n+\t\truntime().write(\n+\t\t\t(c) => answer(c, \"publish\", \"writer\", { message: \"replace\" }),\n+\t\t\t() => {},\n+\t\t).status,\n+\t\t200,\n+\t);\n+\tassert.equal(\n+\t\truntime().read(\n+\t\t\t(c) => c.filesAt(0)[\"f\"],\n+\t\t\t() => {},\n+\t\t),\n+\t\told,\n+\t);\n+\tassert.equal(\n+\t\truntime().read(\n+\t\t\t(c) => c.shared().files[\"f\"],\n+\t\t\t() => {},\n+\t\t),\n+\t\tcurrent,\n+\t);\n+});"},{"path":"server/test/long-text-history.test.ts","added":5,"removed":0,"diff":"--- a/server/test/long-text-history.test.ts\n+++ b/server/test/long-text-history.test.ts\n@@ -1,6 +1,7 @@\n import assert from \"node:assert/strict\";\n import { test } from \"node:test\";\n import { Graph } from \"../../src/engine/graph.ts\";\n+import { StoredText } from \"../../src/engine/stored-text.ts\";\n import { answer } from \"../../worker/project/http.ts\";\n import { Project } from \"../../worker/project/project.ts\";\n import { DiskFirstRuntime } from \"../src/disk-first-runtime.ts\";\n@@ -23,6 +24,9 @@\n \t\t(calls) => calls.fileAt(\"a.txt\", 0, null),\n \t\t() => {},\n \t);\n+\tconst wholeRead = t.mock.method(StoredText.prototype, \"read\", () => {\n+\t\tthrow Error(\"whole stored text read forbidden during record\");\n+\t});\n \tassert.equal(\n \t\truntime().write(\n \t\t\t(calls) => answer(calls, \"record\", \"alice\", { files: { \"a.txt\": current } }),\n@@ -30,6 +34,7 @@\n \t\t).status,\n \t\t200,\n \t);\n+\twholeRead.mock.restore();\n \tassert.equal(\n \t\truntime().write(\n \t\t\t(calls) => answer(calls, \"publish\", \"alice\", { message: \"Replace long line\" }),"},{"path":"src/engine/build.ts","added":46,"removed":14,"diff":"--- a/src/engine/build.ts\n+++ b/src/engine/build.ts\n@@ -4,7 +4,7 @@\n \n import { Graph } from \"./graph.ts\";\n import { attrKey, gapKey, isStartNode, lineKey, parseKey, posKey, startNode, writerOf } from \"./keys.ts\";\n-import { diffLines, joinLines, normalizeText, splitLines } from \"./text.ts\";\n+import { diffChunkedLines, joinLines, normalizeText, splitLines } from \"./text.ts\";\n import {\n \tATTR_NAMES,\n \ttype Atom,\n@@ -26,8 +26,33 @@\n /** Exact read surface used to build atoms; membership requires point lookup only. */\n export type AtomBuildView = Pick<View, \"graph\" | \"lines\" | \"sequence\" | \"sequenceIndex\" | \"parentOf\"> & {\n \treadonly set: Pick<ReadonlySet<AtomId>, \"has\">;\n+\tbuildLines?: View[\"buildLines\"];\n };\n \n+function buildingLines(view: AtomBuildView, path: string) {\n+\treturn view.buildLines ? view.buildLines(path) : view.lines(path);\n+}\n+\n+/** Cache only within one immutable build; never retain handles across writes. */\n+function cachedBuildView(view: AtomBuildView): AtomBuildView {\n+\tconst files = new Map<string, ReturnType<View[\"lines\"]>>();\n+\treturn {\n+\t\tgraph: view.graph,\n+\t\tset: view.set,\n+\t\tlines(path) {\n+\t\t\tlet lines = files.get(path);\n+\t\t\tif (!lines) {\n+\t\t\t\tlines = buildingLines(view, path);\n+\t\t\t\tfiles.set(path, lines);\n+\t\t\t}\n+\t\t\treturn lines;\n+\t\t},\n+\t\tsequence: (path) => view.sequence(path),\n+\t\tsequenceIndex: (path, line) => view.sequenceIndex(path, line),\n+\t\tparentOf: (line) => view.parentOf(line),\n+\t};\n+}\n+\n /** Replace the one exact occurrence of `old` in `file` with `new`. */\n export interface TextEdit {\n \treadonly file: string;\n@@ -132,6 +157,7 @@\n }\n \n function build(view: AtomBuildView, input: AtomInput, allowEmpty: boolean): Atom {\n+\tview = cachedBuildView(view);\n \tconst graph = view.graph;\n \tconst id = graph.nextId();\n \tif (typeof input.author !== \"string\" || typeof input.message !== \"string\") {\n@@ -152,9 +178,14 @@\n \tconst emptiedBy = new Set<AtomId>();\n \n \tfor (const region of regions) {\n-\t\tconst visible = view.lines(region.file);\n-\t\tconst oldLines = visible.slice(region.start, region.end).map((l) => l.text);\n-\t\tfor (const hunk of diffLines(oldLines, region.lines)) {\n+\t\tconst visible = buildingLines(view, region.file);\n+\t\tfunction* oldLines() {\n+\t\t\tfor (let i = region.start; i < region.end; i++) {\n+\t\t\t\tconst line = visible[i]!;\n+\t\t\t\tyield () => (line.textChunks ? line.textChunks() : [line.text]);\n+\t\t\t}\n+\t\t}\n+\t\tfor (const hunk of diffChunkedLines(oldLines(), region.lines)) {\n \t\t\tconst start = region.start + hunk.start;\n \t\t\tconst end = region.start + hunk.end;\n \t\t\tlet parent: NodeId;\n@@ -285,7 +316,7 @@\n \t\tif (typeof path !== \"string\" || path === \"\" || /[\\n\\r]/.test(path))\n \t\t\tthrow new EngineError(\"bad-edit\", `bad file path ${JSON.stringify(path)}`);\n \t}\n-\tconst visible = view.lines(move.file);\n+\tconst visible = buildingLines(view, move.file);\n \tconst { start, end, at } = move;\n \tif (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end > visible.length || start >= end) {\n \t\tthrow new EngineError(\n@@ -293,7 +324,7 @@\n \t\t\t`${move.file} lines [${start}, ${end}) are not a non-empty range of its ${visible.length} visible lines`,\n \t\t);\n \t}\n-\tconst dest = view.lines(move.to);\n+\tconst dest = buildingLines(view, move.to);\n \tif (!Number.isInteger(at) || at < 0 || at > dest.length) {\n \t\tthrow new EngineError(\"bad-range\", `${move.to} has no place ${at} (it has ${dest.length} visible lines)`);\n \t}\n@@ -396,7 +427,7 @@\n }\n \n function rangeLines(view: AtomBuildView, range: LineRange): LineId[] {\n-\tconst visible = view.lines(range.file);\n+\tconst visible = buildingLines(view, range.file);\n \tif (\n \t\t!Number.isInteger(range.start) ||\n \t\t!Number.isInteger(range.end) ||\n@@ -465,7 +496,7 @@\n \t\tthrow new EngineError(\"bad-edit\", \"a text edit needs old and new strings\");\n \t}\n \tconst file = edit.file;\n-\tconst visible = view.lines(file);\n+\tconst visible = buildingLines(view, file);\n \tconst oldText = normalizeText(edit.old);\n \tconst newText = normalizeText(edit.new);\n \tif (oldText === \"\") {\n@@ -477,7 +508,8 @@\n \t\t}\n \t\treturn { file, start: 0, end: 0, lines: splitLines(newText), mode, order };\n \t}\n-\tconst text = joinLines(visible.map((l) => l.text));\n+\tconst texts = visible.map((line) => line.text);\n+\tconst text = joinLines(texts);\n \tconst at = text.indexOf(oldText);\n \tif (at < 0) throw new EngineError(\"no-match\", `old text not found in ${file}`);\n \tif (text.indexOf(oldText, at + 1) >= 0) {\n@@ -488,9 +520,9 @@\n \t}\n \tconst starts: number[] = [];\n \tlet pos = 0;\n-\tfor (const line of visible) {\n+\tfor (const text of texts) {\n \t\tstarts.push(pos);\n-\t\tpos += line.text.length + 1;\n+\t\tpos += text.length + 1;\n \t}\n \tconst lineAt = (offset: number): number => {\n \t\tlet lo = 0;\n@@ -506,12 +538,12 @@\n \tconst startLine = lineAt(at);\n \tlet endLine = lineAt(end - 1);\n \tconst lineStart = starts[startLine]!;\n-\tconst lineEnd = starts[endLine]! + visible[endLine]!.text.length + 1;\n+\tconst lineEnd = starts[endLine]! + texts[endLine]!.length + 1;\n \tlet replacement = text.slice(lineStart, at) + newText + text.slice(end, lineEnd);\n \tif (replacement !== \"\" && !replacement.endsWith(\"\\n\")) {\n \t\tif (endLine + 1 < visible.length) {\n \t\t\tendLine++;\n-\t\t\treplacement += `${visible[endLine]!.text}\\n`;\n+\t\t\treplacement += `${texts[endLine]}\\n`;\n \t\t} else {\n \t\t\treplacement += \"\\n\";\n \t\t}\n@@ -520,7 +552,7 @@\n }\n \n function matchSplice(view: AtomBuildView, edit: SpliceEdit, mode: Mode, order: number): Region {\n-\tconst count = view.lines(edit.file).length;\n+\tconst count = buildingLines(view, edit.file).length;\n \tif (\n \t\t!Number.isInteger(edit.start) ||\n \t\t!Number.isInteger(edit.end) ||"},{"path":"src/engine/experimental/projection-marker.ts","added":6,"removed":9,"diff":"--- a/src/engine/experimental/projection-marker.ts\n+++ b/src/engine/experimental/projection-marker.ts\n@@ -121,8 +121,7 @@\n \t\t\tconst state = { ...previous };\n \t\t\tthis.ensureFile(state, this.path);\n \t\t\tfor (const run of atom.inserts) this.ensureFile(state, run.file);\n-\t\t\tlet k = 0;\n-\t\t\tfor (const run of atom.inserts) for (const _ of run.lines) this.insertLine(state, `${atom.id}.${k++}`);\n+\t\t\tfor (const line of this.graph.eachInsertedLine(atom.id)) this.insertLine(state, line);\n \t\t\tlet visibility: Array<{ kind: \"visibility\"; id: number; delta: number }> = [];\n \t\t\tfor (const line of atom.deletes) {\n \t\t\t\tconst marker = this.markers.get(state.locator, this.graph.lineN(line) + 1);\n@@ -194,13 +193,11 @@\n \t\t\tthrow Error(\"included dependent prevents removal\");\n \t\treturn this.storage.transaction(() => {\n \t\t\tconst state = { ...previous };\n-\t\t\tlet k = 0;\n-\t\t\tfor (const run of atom.inserts)\n-\t\t\t\tfor (const text of run.lines) {\n-\t\t\t\t\tconst marker = this.markers.get(state.locator, this.graph.lineN(`${atom.id}.${k++}`) + 1);\n-\t\t\t\t\tif (!marker) throw Error(\"missing inserted marker\");\n-\t\t\t\t\tstate.sequence = this.sequence.update(state.sequence, { kind: \"visibility\", id: marker.enter, delta: 1 });\n-\t\t\t\t}\n+\t\t\tfor (const line of this.graph.eachInsertedLine(atom.id)) {\n+\t\t\t\tconst marker = this.markers.get(state.locator, this.graph.lineN(line) + 1);\n+\t\t\t\tif (!marker) throw Error(\"missing inserted marker\");\n+\t\t\t\tstate.sequence = this.sequence.update(state.sequence, { kind: \"visibility\", id: marker.enter, delta: 1 });\n+\t\t\t}\n \t\t\tfor (const line of atom.deletes) {\n \t\t\t\tconst marker = this.markers.get(state.locator, this.graph.lineN(line) + 1);\n \t\t\t\tif (!marker) throw Error(\"missing deleted marker\");"},{"path":"src/engine/experimental/projection-reader.ts","added":52,"removed":0,"diff":"--- a/src/engine/experimental/projection-reader.ts\n+++ b/src/engine/experimental/projection-reader.ts\n@@ -110,6 +110,30 @@\n \t\tfor (const id of this.graph.movers()) if (this.set.has(id)) return true;\n \t\treturn false;\n \t}\n+\t*#textChunks(n: number): IterableIterator<string> {\n+\t\tthis.#assertLive();\n+\t\tconst iterator = this.graph.textChunks(n);\n+\t\twhile (true) {\n+\t\t\tthis.#assertLive();\n+\t\t\tconst next = iterator.next();\n+\t\t\tthis.#assertLive();\n+\t\t\tif (next.done) return;\n+\t\t\tyield next.value;\n+\t\t}\n+\t}\n+\t*lineChunks(path: string): IterableIterator<() => Iterable<string>> {\n+\t\tthis.#assertLive();\n+\t\tconst iterator = this.#adapter.lineIds(this.#state, path);\n+\t\twhile (true) {\n+\t\t\tthis.#assertLive();\n+\t\t\tconst next = iterator.next();\n+\t\t\tthis.#assertLive();\n+\t\t\tif (next.done) return;\n+\t\t\tconst n = this.graph.lineN(next.value);\n+\t\t\tyield () => this.#textChunks(n);\n+\t\t}\n+\t}\n+\n \t*visibleLines(path: string): IterableIterator<VisibleLine> {\n \t\tthis.#assertLive();\n \t\tconst graph = this.#adapter.graph;\n@@ -128,6 +152,34 @@\n \t\tthis.#assertLive();\n \t\treturn [...this.visibleLines(path)];\n \t}\n+\t*#buildingLines(path: string): IterableIterator<VisibleLine> {\n+\t\tthis.#assertLive();\n+\t\tconst graph = this.#adapter.graph;\n+\t\tconst iterator = this.#adapter.lineIds(this.#state, path);\n+\t\twhile (true) {\n+\t\t\tthis.#assertLive();\n+\t\t\tconst next = iterator.next();\n+\t\t\tthis.#assertLive();\n+\t\t\tif (next.done) return;\n+\t\t\tconst id = next.value;\n+\t\t\tconst n = graph.lineN(id);\n+\t\t\tconst assertLive = () => this.#assertLive();\n+\t\t\tyield {\n+\t\t\t\tid,\n+\t\t\t\ttextChunks: () => this.#textChunks(n),\n+\t\t\t\tget text() {\n+\t\t\t\t\tassertLive();\n+\t\t\t\t\treturn graph.textOf(n);\n+\t\t\t\t},\n+\t\t\t\tatom: graph.idOfSeq(graph.writerSeqOf(n)),\n+\t\t\t};\n+\t\t}\n+\t}\n+\tbuildLines(path: string): readonly VisibleLine[] {\n+\t\tthis.#assertLive();\n+\t\treturn [...this.#buildingLines(path)];\n+\t}\n+\n \tsequence(path: string): readonly SeqLine[] {\n \t\tthis.#assertLive();\n \t\tconst adapter = this.#adapter,"},{"path":"src/engine/graph.ts","added":75,"removed":10,"diff":"--- a/src/engine/graph.ts\n+++ b/src/engine/graph.ts\n@@ -3,6 +3,7 @@\n // atoms and keeps indexes so those questions are cheap.\n \n import { ChildCounts } from \"./child-counts.ts\";\n+import { JsonStringChunks, registerJsonChunkValue } from \"./json-value-chunks.ts\";\n import {\n \tatomId,\n \tattrKey,\n@@ -358,6 +359,8 @@\n \t\t\t\t\t\tencoded.textFormat === 1 || encoded.listFormat === 1 || encoded.insertionFormat === 1\n \t\t\t\t\t\t\t? encoded.atom!\n \t\t\t\t\t\t\t: value;\n+\t\t\t\t\tif (encoded.insertionFormat === 1 && (!Array.isArray(atom.inserts) || atom.inserts.length !== 0))\n+\t\t\t\t\t\tthrow Error(\"invalid stored insertion placeholder\");\n \t\t\t\t\tconst text =\n \t\t\t\t\t\tencoded.textFormat === 1\n \t\t\t\t\t\t\t? (start: number, length: number): readonly string[] => {\n@@ -368,7 +371,7 @@\n \t\t\t\t\t\t\t\t\t\t\tif (index >= start && index < start + length) {\n \t\t\t\t\t\t\t\t\t\t\t\tconst reference = raw as unknown as TextReference;\n \t\t\t\t\t\t\t\t\t\t\t\tif (typeof raw === \"string\") result.push(raw);\n-\t\t\t\t\t\t\t\t\t\t\t\telse if (reference && typeof reference.text === \"string\")\n+\t\t\t\t\t\t\t\t\t\t\t\telse if (reference && reference.text === JSON.stringify([String(atom.seq), index]))\n \t\t\t\t\t\t\t\t\t\t\t\t\tresult.push(atomText.read(reference.text));\n \t\t\t\t\t\t\t\t\t\t\t\telse throw Error(\"invalid stored atom text reference\");\n \t\t\t\t\t\t\t\t\t\t\t}\n@@ -377,13 +380,51 @@\n \t\t\t\t\t\t\t\t\tthrow Error(\"stored atom text range missing\");\n \t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t: undefined;\n+\t\t\t\t\tconst streamed = (target: Atom): Atom => {\n+\t\t\t\t\t\tregisterJsonChunkValue(target, () => {\n+\t\t\t\t\t\t\tconst line = (raw: unknown, index: number): unknown => {\n+\t\t\t\t\t\t\t\tif (typeof raw === \"string\") return raw;\n+\t\t\t\t\t\t\t\tconst reference = raw as TextReference;\n+\t\t\t\t\t\t\t\tif (!reference || reference.text !== JSON.stringify([String(atom.seq), index]))\n+\t\t\t\t\t\t\t\t\tthrow Error(\"invalid stored atom text reference\");\n+\t\t\t\t\t\t\t\treturn new JsonStringChunks(() => atomText.chunks(reference.text));\n+\t\t\t\t\t\t\t};\n+\t\t\t\t\t\t\tlet inserts: readonly unknown[];\n+\t\t\t\t\t\t\tif (encoded.insertionFormat === 1) {\n+\t\t\t\t\t\t\t\tconst collection = `atom-inserts:${atom.seq}`;\n+\t\t\t\t\t\t\t\tinserts = readonlyStoredArray(storage, collection, (raw, index) => {\n+\t\t\t\t\t\t\t\t\tconst run = raw as { file: string; parent: string; lines: string };\n+\t\t\t\t\t\t\t\t\tconst lines = `${collection}:lines:${index}`;\n+\t\t\t\t\t\t\t\t\tif (run.lines !== lines || typeof run.file !== \"string\" || typeof run.parent !== \"string\")\n+\t\t\t\t\t\t\t\t\t\tthrow Error(\"invalid stored insertion run\");\n+\t\t\t\t\t\t\t\t\tlet start = 0;\n+\t\t\t\t\t\t\t\t\tfor (let prior = 0; prior < index; prior++)\n+\t\t\t\t\t\t\t\t\t\tstart += readonlyStoredArray(storage, `${collection}:lines:${prior}`).length;\n+\t\t\t\t\t\t\t\t\treturn {\n+\t\t\t\t\t\t\t\t\t\tfile: run.file,\n+\t\t\t\t\t\t\t\t\t\tparent: run.parent,\n+\t\t\t\t\t\t\t\t\t\tlines: readonlyStoredArray(storage, lines, (raw, i) => line(raw, start + i)),\n+\t\t\t\t\t\t\t\t\t};\n+\t\t\t\t\t\t\t\t});\n+\t\t\t\t\t\t\t} else {\n+\t\t\t\t\t\t\t\tlet index = 0;\n+\t\t\t\t\t\t\t\tinserts = atom.inserts.map((run) => ({\n+\t\t\t\t\t\t\t\t\tfile: run.file,\n+\t\t\t\t\t\t\t\t\tparent: run.parent,\n+\t\t\t\t\t\t\t\t\tlines: run.lines.map((raw) => line(raw, index++)),\n+\t\t\t\t\t\t\t\t}));\n+\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\treturn { ...target, inserts };\n+\t\t\t\t\t\t});\n+\t\t\t\t\t\treturn target;\n+\t\t\t\t\t};\n \t\t\t\t\tconst frozen = freezeAtom(\n \t\t\t\t\t\tatom,\n \t\t\t\t\t\t(id) => id,\n \t\t\t\t\t\t(author) => author,\n \t\t\t\t\t\ttext,\n \t\t\t\t\t);\n-\t\t\t\t\tif (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return frozen;\n+\t\t\t\t\tif (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return streamed(frozen);\n \t\t\t\t\tconst result = { ...frozen };\n \t\t\t\t\tif (encoded.insertionFormat === 1) {\n \t\t\t\t\t\tconst collection = `atom-inserts:${atom.seq}`;\n@@ -396,10 +437,14 @@\n \t\t\t\t\t\t\treturn Object.freeze({\n \t\t\t\t\t\t\t\tfile: run.file,\n \t\t\t\t\t\t\t\tparent: run.parent,\n-\t\t\t\t\t\t\t\tlines: readonlyStoredArray<string>(storage, lines, (rawLine) => {\n+\t\t\t\t\t\t\t\tlines: readonlyStoredArray<string>(storage, lines, (rawLine, lineIndex) => {\n \t\t\t\t\t\t\t\t\tif (typeof rawLine === \"string\") return rawLine;\n \t\t\t\t\t\t\t\t\tconst ref = rawLine as TextReference;\n-\t\t\t\t\t\t\t\t\tif (!ref || typeof ref.text !== \"string\") throw Error(\"invalid stored insertion text\");\n+\t\t\t\t\t\t\t\t\tlet atomLine = lineIndex;\n+\t\t\t\t\t\t\t\t\tfor (let prior = 0; prior < index; prior++)\n+\t\t\t\t\t\t\t\t\t\tatomLine += readonlyStoredArray(storage, `${collection}:lines:${prior}`).length;\n+\t\t\t\t\t\t\t\t\tif (!ref || ref.text !== JSON.stringify([String(atom.seq), atomLine]))\n+\t\t\t\t\t\t\t\t\t\tthrow Error(\"invalid stored insertion text\");\n \t\t\t\t\t\t\t\t\treturn atomText.read(ref.text);\n \t\t\t\t\t\t\t\t}),\n \t\t\t\t\t\t\t});\n@@ -413,7 +458,7 @@\n \t\t\t\t\t\t\tthrow Error(\"invalid stored atom list reference\");\n \t\t\t\t\t\tObject.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true });\n \t\t\t\t\t}\n-\t\t\t\t\treturn Object.freeze(result);\n+\t\t\t\t\treturn streamed(Object.freeze(result));\n \t\t\t\t},\n \t\t\t\t(input, key) => {\n \t\t\t\t\tconst atom = { ...input };\n@@ -779,6 +824,25 @@\n \t\treturn this.#text(n);\n \t}\n \n+\t/** Historical text in bounded chunks, without decoding a whole stored line. */\n+\t*textChunks(n: number): IterableIterator<string> {\n+\t\tif (!this.#storage) {\n+\t\t\tconst text = this.#text(n);\n+\t\t\tfor (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters)\n+\t\t\t\tyield text.slice(offset, offset + StoredText.chunkCharacters);\n+\t\t\treturn;\n+\t\t}\n+\t\tif (!Number.isSafeInteger(n) || n < 0 || n >= this.#lineText!.length) throw Error(\"invalid line number\");\n+\t\tconst value = this.#storage.read(\"line-text\", String(n));\n+\t\tif (typeof value === \"string\") {\n+\t\t\tyield value;\n+\t\t\treturn;\n+\t\t}\n+\t\tconst reference = value as { format?: number; text?: string } | undefined;\n+\t\tif (reference?.format !== 1 || typeof reference.text !== \"string\") throw Error(\"invalid long line reference\");\n+\t\tyield* new StoredText(this.#storage, \"atom-text:long\").chunks(reference.text);\n+\t}\n+\n \t/** The seq of the atom that wrote line n. */\n \twriterSeqOf(n: number): number {\n \t\treturn this.#lineAtom.at(n);\n@@ -976,12 +1040,13 @@\n \n \t/** The line ids an atom inserted, in k order. */\n \tlinesOf(id: AtomId): LineId[] {\n-\t\tconst atom = this.atom(id);\n-\t\tconst out: LineId[] = [];\n-\t\tconst seq = atom.seq;\n+\t\treturn [...this.eachInsertedLine(id)];\n+\t}\n+\t/** Inserted identities without decoding or allocating the atom's text. */\n+\t*eachInsertedLine(id: AtomId): IterableIterator<LineId> {\n+\t\tconst seq = this.atom(id).seq;\n \t\tconst count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;\n-\t\tfor (let k = 0; k < count; k++) out.push(lineId(id, k));\n-\t\treturn out;\n+\t\tfor (let k = 0; k < count; k++) yield lineId(id, k);\n \t}\n \n \t/** Every atom that deletes this line (across the whole graph). */"},{"path":"src/engine/json-value-chunks.ts","added":35,"removed":1,"diff":"--- a/src/engine/json-value-chunks.ts\n+++ b/src/engine/json-value-chunks.ts\n@@ -1,3 +1,20 @@\n+/** Internal values may expose an exact streaming representation without changing public toJSON. */\n+const streamingValues = new WeakMap<object, () => unknown>();\n+export function registerJsonChunkValue(value: object, representation: () => unknown): void {\n+\tstreamingValues.set(value, representation);\n+}\n+\n+/** A JSON string backed by bounded, replayable UTF-16 chunks. */\n+export class JsonStringChunks {\n+\treadonly chunks: () => Iterable<string>;\n+\tconstructor(chunks: () => Iterable<string>) {\n+\t\tthis.chunks = chunks;\n+\t}\n+\ttoJSON(): string {\n+\t\treturn [...this.chunks()].join(\"\");\n+\t}\n+}\n+\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@@ -16,7 +33,10 @@\n \t\tyield '\"';\n \t}\n \tconst normalize = (value: unknown, key: string): unknown => {\n+\t\tif (value instanceof JsonStringChunks) return value;\n \t\tif (value !== null && typeof value === \"object\") {\n+\t\t\tconst streaming = streamingValues.get(value);\n+\t\t\tif (streaming) return streaming();\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@@ -24,7 +44,21 @@\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\tif (value instanceof JsonStringChunks) {\n+\t\t\tyield '\"';\n+\t\t\tlet pending = \"\";\n+\t\t\tfor (const chunk of value.chunks()) {\n+\t\t\t\tif (typeof chunk !== \"string\" || chunk.length > 16384) throw Error(\"JSON string chunk exceeds bound\");\n+\t\t\t\tconst text = pending + chunk;\n+\t\t\t\tlet end = text.length;\n+\t\t\t\tconst last = text.charCodeAt(end - 1);\n+\t\t\t\tif (last >= 0xd800 && last <= 0xdbff) end--;\n+\t\t\t\tpending = text.slice(end);\n+\t\t\t\tif (end) yield JSON.stringify(text.slice(0, end)).slice(1, -1);\n+\t\t\t}\n+\t\t\tif (pending) yield JSON.stringify(pending).slice(1, -1);\n+\t\t\tyield '\"';\n+\t\t} else if (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 {"},{"path":"src/engine/test/build-lazy-lines.test.ts","added":46,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/build-lazy-lines.test.ts\n@@ -0,0 +1,46 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildAtom } from \"../build.ts\";\n+import { Repo } from \"./helpers.ts\";\n+\n+test(\"splice atom construction reads only the replaced region's text\", (t) => {\n+\tconst repo = Repo.init({ \"f.txt\": `${\"unrelated\".repeat(10000)}\\nold\\nlast\\n` });\n+\tconst view = repo.view();\n+\tconst input = { author: \"writer\", message: \"replace\", edits: [{ file: \"f.txt\", start: 1, end: 2, lines: [\"new\"] }] };\n+\tconst expected = buildAtom(view, input);\n+\tconst original = repo.graph.textChunks.bind(repo.graph);\n+\tconst reads: number[] = [];\n+\tt.mock.method(repo.graph, \"textChunks\", (n: number) => {\n+\t\treads.push(n);\n+\t\tassert.equal(n, 1);\n+\t\treturn original(n);\n+\t});\n+\tassert.deepEqual(buildAtom(repo.view(), input), expected);\n+\tassert.deepEqual(reads, [1]);\n+\treads.length = 0;\n+\tbuildAtom(repo.view(), {\n+\t\tauthor: \"writer\",\n+\t\tmessage: \"insert\",\n+\t\tedits: [{ file: \"f.txt\", start: 1, end: 1, lines: [\"added\"] }],\n+\t});\n+\tassert.deepEqual(reads, []);\n+});\n+\n+test(\"many splice edits build line handles only once per file\", (t) => {\n+\tconst repo = Repo.init({ \"f.txt\": Array.from({ length: 2000 }, (_, i) => `line ${i}\\n`).join(\"\") });\n+\tconst view = repo.view();\n+\tconst read = view.buildLines.bind(view);\n+\tlet calls = 0;\n+\tt.mock.method(view, \"buildLines\", (path: string) => {\n+\t\tcalls++;\n+\t\treturn read(path);\n+\t});\n+\tconst edits = Array.from({ length: 400 }, (_, i) => ({\n+\t\tfile: \"f.txt\",\n+\t\tstart: i * 4,\n+\t\tend: i * 4 + 1,\n+\t\tlines: [`new ${i}`],\n+\t}));\n+\tassert.equal(buildAtom(view, { author: \"writer\", message: \"many edits\", edits }).deletes.length, 400);\n+\tassert.equal(calls, 1);\n+});"},{"path":"src/engine/test/graph-line-chunks.test.ts","added":41,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-line-chunks.test.ts\n@@ -0,0 +1,41 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildAtom } from \"../build.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { StoredText } from \"../stored-text.ts\";\n+import { diffChunkedLines } from \"../text.ts\";\n+import { View } from \"../view.ts\";\n+import { Repo } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"stored line comparison and atom construction never assemble historical long text\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst line = \"x\".repeat(100000) + \"\\ud800\\udc00\";\n+\tconst repo = Repo.init({ \"f.txt\": `${line}\\nkeep\\n` });\n+\tconst graph = new Graph({ storage });\n+\tgraph.add(repo.graph.atom(\"a0\"));\n+\tt.mock.method(StoredText.prototype, \"read\", () => {\n+\t\tthrow Error(\"whole stored text forbidden\");\n+\t});\n+\tt.mock.method(graph, \"textOf\", () => {\n+\t\tthrow Error(\"whole line forbidden\");\n+\t});\n+\tconst chunks = [...graph.textChunks(0)];\n+\tassert.equal(chunks.join(\"\"), line);\n+\tassert.ok(chunks.every((chunk) => chunk.length <= StoredText.chunkCharacters));\n+\tconst view = new View(graph, [\"a0\"]);\n+\tassert.deepEqual(diffChunkedLines(view.lineChunks(\"f.txt\"), [line, \"changed\"]), [\n+\t\t{ start: 1, end: 2, lines: [\"changed\"] },\n+\t]);\n+\tassert.equal(\n+\t\tbuildAtom(view, {\n+\t\t\tauthor: \"writer\",\n+\t\t\tmessage: \"change\",\n+\t\t\tedits: [{ file: \"f.txt\", start: 0, end: 1, lines: [\"replacement\"] }],\n+\t\t}).deletes.length,\n+\t\t1,\n+\t);\n+\tassert.throws(() => [...graph.textChunks(-1)], /invalid line/);\n+\tassert.throws(() => [...graph.textChunks(2)], /invalid line/);\n+});"},{"path":"src/engine/test/json-string-chunks.test.ts","added":58,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/json-string-chunks.test.ts\n@@ -0,0 +1,58 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase } from \"../build.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { JsonStringChunks, jsonValueChunks, registerJsonChunkValue } from \"../json-value-chunks.ts\";\n+import { StoredText } from \"../stored-text.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"chunk-backed JSON strings preserve escaping and split UTF-16 exactly\", () => {\n+\tconst values = [\n+\t\t\"\",\n+\t\t\"ordinary\",\n+\t\t'\"\\\\\\n\\r\\t\\u0000',\n+\t\t\"\\ud800\",\n+\t\t\"\\udc00\",\n+\t\t\"\\ud800\\udc00\",\n+\t\t\"a\\ud800b\\udc00c\",\n+\t\t\"x\".repeat(50000),\n+\t];\n+\tfor (const text of values)\n+\t\tfor (const size of [1, 2, 17, 16384]) {\n+\t\t\tconst value = new JsonStringChunks(function* () {\n+\t\t\t\tyield \"\";\n+\t\t\t\tfor (let offset = 0; offset < text.length; offset += size) {\n+\t\t\t\t\tyield text.slice(offset, offset + size);\n+\t\t\t\t\tyield \"\";\n+\t\t\t\t}\n+\t\t\t});\n+\t\t\tassert.equal([...jsonValueChunks({ value })].join(\"\"), JSON.stringify({ value: text }));\n+\t\t\tassert.equal(JSON.stringify(value), JSON.stringify(text));\n+\t\t}\n+});\n+\n+test(\"registered lazy values stream without invoking their whole-value toJSON\", () => {\n+\tconst value = {\n+\t\ttoJSON() {\n+\t\t\tthrow Error(\"whole value forbidden\");\n+\t\t},\n+\t};\n+\tregisterJsonChunkValue(value, () => ({ lines: [new JsonStringChunks(() => [\"abc\", \"def\"])] }));\n+\tassert.equal([...jsonValueChunks(value)].join(\"\"), '{\"lines\":[\"abcdef\"]}');\n+\tassert.throws(() => [...jsonValueChunks(new JsonStringChunks(() => [\"x\".repeat(16385)]))], /exceeds bound/);\n+});\n+\n+for (const length of [60000, 100000])\n+\ttest(`stored atom JSON streams a ${length}-character line without whole reads`, (t) => {\n+\t\tconst storage = new SqlState();\n+\t\tt.after(() => storage.db.close());\n+\t\tconst graph = new Graph({ storage });\n+\t\tconst atom = buildBase({ f: `${\"x\".repeat(length)}\\n` }, { author: \"writer\", message: \"init\" });\n+\t\tgraph.add(atom);\n+\t\tconst stored = graph.atom(\"a0\");\n+\t\tconst expected = JSON.stringify(stored);\n+\t\tt.mock.method(StoredText.prototype, \"read\", () => {\n+\t\t\tthrow Error(\"whole stored text forbidden\");\n+\t\t});\n+\t\tassert.equal([...jsonValueChunks(stored)].join(\"\"), expected);\n+\t});"},{"path":"src/engine/test/projection-read-scope.test.ts","added":7,"removed":0,"diff":"--- a/src/engine/test/projection-read-scope.test.ts\n+++ b/src/engine/test/projection-read-scope.test.ts\n@@ -21,6 +21,10 @@\n \t\t\tassert.throws(() => scope.guard(new Graph()), /mismatch/);\n \t\t\tconst reader = new ProjectionReader(adapter, state, scope.guard(graph));\n \t\t\tconst membership = reader.set;\n+\t\t\tconst heldLine = reader.buildLines(\"f.txt\")[0]!;\n+\t\t\tconst chunkSource = reader.lineChunks(\"f.txt\").next().value!;\n+\t\t\tconst chunks = chunkSource()[Symbol.iterator]();\n+\t\t\tassert.equal(chunks.next().value, \"one\");\n \t\t\tconst iterator = reader.visibleLines(\"f.txt\");\n \t\t\tassert.equal(iterator.next().value?.text, \"one\");\n \t\t\tif (end === \"source\") source = {};\n@@ -46,6 +50,9 @@\n \t\t\tt.mock.method(graph, \"lineN\", refuseAccess);\n \t\t\tt.mock.method(graph, \"textOf\", refuseAccess);\n \t\t\tassert.throws(() => reader.text(\"f.txt\"), /expired|stale/);\n+\t\t\tassert.throws(() => heldLine.text, /expired|stale/);\n+\t\t\tassert.throws(() => chunks.next(), /expired|stale/);\n+\t\t\tassert.throws(() => chunkSource()[Symbol.iterator]().next(), /expired|stale/);\n \t\t\tassert.throws(() => membership.has(\"a0\"), /expired|stale/);\n \t\t\tassert.throws(() => iterator.next(), /expired|stale/);\n \t\t\tassert.equal(touched, false);"},{"path":"src/engine/test/streamed-diff.test.ts","added":87,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/streamed-diff.test.ts\n@@ -0,0 +1,87 @@\n+import assert from \"node:assert/strict\";\n+import { it } from \"node:test\";\n+import { diffChunkedLines, diffLineStream, diffLines } from \"../text.ts\";\n+\n+it(\"reads aligned long lines once without accepting hash collisions\", () => {\n+\tconst before = [\"x\".repeat(100000), \"reqicjpk\", \"y\".repeat(80000)];\n+\tconst after = [before[0]!, \"ejfslztg\", before[2]!];\n+\tconst reads = [0, 0, 0];\n+\tconst sources = before.map(\n+\t\t(line, index) =>\n+\t\t\tfunction* () {\n+\t\t\t\treads[index]!++;\n+\t\t\t\tfor (let at = 0; at < line.length; at += 4) yield line.slice(at, at + 4);\n+\t\t\t},\n+\t);\n+\tassert.deepEqual(diffChunkedLines(sources, after), diffLines(before, after));\n+\tassert.equal(reads[0], 1);\n+\tassert.equal(reads[2], 1);\n+});\n+\n+it(\"preserves exact array-diff hunks for single-pass line sources\", () => {\n+\tlet seed = 918273;\n+\tconst random = (n: number) => {\n+\t\tseed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;\n+\t\treturn seed % n;\n+\t};\n+\tfor (let trial = 0; trial < 3000; trial++) {\n+\t\tconst before = Array.from({ length: random(90) }, () => `line ${random(19)}`);\n+\t\tconst after = Array.from({ length: random(90) }, () => `line ${random(19)}`);\n+\t\tlet reads = 0;\n+\t\tfunction* oldLines() {\n+\t\t\tfor (const line of before) {\n+\t\t\t\treads++;\n+\t\t\t\tyield line;\n+\t\t\t}\n+\t\t}\n+\t\tassert.deepEqual(diffLineStream(oldLines(), after), diffLines(before, after));\n+\t\tassert.deepEqual(\n+\t\t\tdiffChunkedLines(\n+\t\t\t\tbefore.map((line) => () => [line.slice(0, 3), line.slice(3)]),\n+\t\t\t\tafter,\n+\t\t\t),\n+\t\t\tdiffLines(before, after),\n+\t\t);\n+\t\tassert.equal(reads, before.length);\n+\t}\n+});\n+\n+it(\"preserves prefix, suffix and expensive-rewrite fallback choices\", () => {\n+\tfor (const count of [0, 1, 300, 900]) {\n+\t\tconst before = Array.from({ length: count }, (_, i) => `old ${i}`);\n+\t\tconst after = [...before].reverse();\n+\t\tbefore.unshift(\"prefix\");\n+\t\tafter.unshift(\"prefix\");\n+\t\tbefore.push(\"suffix\");\n+\t\tafter.push(\"suffix\");\n+\t\tassert.deepEqual(diffLineStream(before.values(), after), diffLines(before, after));\n+\t}\n+});\n+\n+it(\"compares chunked lines exactly, including a same-length hash collision\", () => {\n+\tconst before = [\"reqicjpk\", \"\", \"x\".repeat(100000), \"\\ud800\\udc00\"];\n+\tconst after = [\"ejfslztg\", \"\", \"x\".repeat(100000), \"\\ud800\\udc00\", \"end\"];\n+\tfor (const size of [1, 7, 16384]) {\n+\t\tconst sources = before.map(\n+\t\t\t(line) =>\n+\t\t\t\tfunction* () {\n+\t\t\t\t\tfor (let offset = 0; offset < line.length; offset += size) yield line.slice(offset, offset + size);\n+\t\t\t\t},\n+\t\t);\n+\t\tassert.deepEqual(diffChunkedLines(sources, after), diffLines(before, after));\n+\t}\n+});\n+\n+it(\"reads single-chunk old lines once while matching exactly\", () => {\n+\tlet reads = 0;\n+\tconst before = [\"keep\", \"replace\", \"\"];\n+\tconst sources = before.map(\n+\t\t(line) =>\n+\t\t\tfunction* () {\n+\t\t\t\treads++;\n+\t\t\t\tyield line;\n+\t\t\t},\n+\t);\n+\tassert.deepEqual(diffChunkedLines(sources, [\"keep\", \"new\", \"\"]), diffLines(before, [\"keep\", \"new\", \"\"]));\n+\tassert.equal(reads, before.length);\n+});"},{"path":"src/engine/text.ts","added":123,"removed":6,"diff":"--- a/src/engine/text.ts\n+++ b/src/engine/text.ts\n@@ -43,12 +43,129 @@\n  * file's length times MAX_COST instead of its length squared.\n  */\n export function diffLines(a: readonly string[], b: readonly string[]): Hunk[] {\n-\tconst matches = commonLines(a, b);\n-\tconst hunks: Hunk[] = [];\n+\treturn hunksFromMatches(a.length, b, commonLines(a, b));\n+}\n+\n+/** Diff a single-pass old-line source without retaining its strings. */\n+export function diffLineStream(a: Iterable<string>, b: readonly string[]): Hunk[] {\n+\tconst ids = new Map<string, number>();\n+\tconst next = b.map((line) => {\n+\t\tlet id = ids.get(line);\n+\t\tif (id === undefined) {\n+\t\t\tid = ids.size;\n+\t\t\tids.set(line, id);\n+\t\t}\n+\t\treturn id;\n+\t});\n+\tconst previous: number[] = [];\n+\tfor (const line of a) previous.push(ids.get(line) ?? -1);\n+\treturn hunksFromMatches(previous.length, b, commonLines(previous, next));\n+}\n+\n+/** Compare replayable old-line chunks without assembling historical strings. */\n+export function diffChunkedLines(a: Iterable<() => Iterable<string>>, b: readonly string[]): Hunk[] {\n+\tconst keys = new Map<string, number>();\n+\tconst buckets = new Map<string, number[]>();\n+\tconst next = b.map((line, index) => {\n+\t\tlet id = keys.get(line);\n+\t\tif (id === undefined) {\n+\t\t\tid = index;\n+\t\t\tkeys.set(line, id);\n+\t\t\tconst key = chunkKey([line]);\n+\t\t\tconst bucket = buckets.get(key) ?? [];\n+\t\t\tbucket.push(id);\n+\t\t\tbuckets.set(key, bucket);\n+\t\t}\n+\t\treturn id;\n+\t});\n+\tconst previous: number[] = [];\n+\tfor (const chunks of a) {\n+\t\tconst iterator = chunks()[Symbol.iterator]();\n+\t\tlet key: string;\n+\t\tconst aligned = b[previous.length];\n+\t\tlet alignedOffset = 0;\n+\t\tlet alignedEqual = aligned !== undefined;\n+\t\ttry {\n+\t\t\tconst first = iterator.next();\n+\t\t\tif (first.done) {\n+\t\t\t\tprevious.push(keys.get(\"\") ?? -1);\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\tconst second = iterator.next();\n+\t\t\tif (second.done) {\n+\t\t\t\tprevious.push(keys.get(first.value) ?? -1);\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\tkey = chunkKey(\n+\t\t\t\t(function* () {\n+\t\t\t\t\tfunction* remaining() {\n+\t\t\t\t\t\tyield first.value;\n+\t\t\t\t\t\tyield second.value;\n+\t\t\t\t\t\tfor (let next = iterator.next(); !next.done; next = iterator.next()) yield next.value;\n+\t\t\t\t\t}\n+\t\t\t\t\tfor (const chunk of remaining()) {\n+\t\t\t\t\t\tif (alignedEqual && !aligned!.startsWith(chunk, alignedOffset)) alignedEqual = false;\n+\t\t\t\t\t\talignedOffset += chunk.length;\n+\t\t\t\t\t\tyield chunk;\n+\t\t\t\t\t}\n+\t\t\t\t})(),\n+\t\t\t);\n+\t\t} finally {\n+\t\t\titerator.return?.();\n+\t\t}\n+\t\t// Same-position unchanged lines are common. Confirm them during hashing,\n+\t\t// retaining exact comparison and the collision-safe fallback for moved lines.\n+\t\tif (alignedEqual && alignedOffset === aligned!.length) {\n+\t\t\tprevious.push(next[previous.length]!);\n+\t\t\tcontinue;\n+\t\t}\n+\t\tconst candidates = buckets.get(key);\n+\t\tlet match = -1;\n+\t\tfor (const candidate of candidates ?? []) {\n+\t\t\tlet offset = 0;\n+\t\t\tlet equal = true;\n+\t\t\tfor (const chunk of chunks()) {\n+\t\t\t\tif (!b[candidate]!.startsWith(chunk, offset)) equal = false;\n+\t\t\t\toffset += chunk.length;\n+\t\t\t}\n+\t\t\tif (equal && offset === b[candidate]!.length) {\n+\t\t\t\tmatch = candidate;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n+\t\tprevious.push(match);\n+\t}\n+\treturn hunksFromMatches(previous.length, b, commonLines(previous, next));\n+}\n+\n+function chunkKey(chunks: Iterable<string>): string {\n+\tlet hash = 2166136261;\n+\tlet length = 0;\n+\tfor (const chunk of chunks) {\n+\t\tlength += chunk.length;\n+\t\tfor (let i = 0; i < chunk.length; i++) hash = Math.imul(hash ^ chunk.charCodeAt(i), 16777619) >>> 0;\n+\t}\n+\treturn `${length}:${hash}`;\n+}\n+\n+/** The existing diff algorithm over exact line symbols, without retaining text. */\n+export function diffLineSymbols(\n+\ta: readonly number[],\n+\tb: readonly number[],\n+): { start: number; end: number; lines: number[] }[] {\n+\treturn hunksFromMatches(a.length, b, commonLines(a, b));\n+}\n+\n+function hunksFromMatches<T>(\n+\tlength: number,\n+\tb: readonly T[],\n+\tmatches: readonly number[],\n+): { start: number; end: number; lines: T[] }[] {\n+\tconst hunks: { start: number; end: number; lines: T[] }[] = [];\n \tlet i = 0;\n \tlet j = 0;\n \tfor (let m = 0; m <= matches.length; m += 2) {\n-\t\tconst mi = m < matches.length ? matches[m]! : a.length;\n+\t\tconst mi = m < matches.length ? matches[m]! : length;\n \t\tconst mj = m < matches.length ? matches[m + 1]! : b.length;\n \t\tif (mi > i || mj > j) hunks.push({ start: i, end: mi, lines: b.slice(j, mj) });\n \t\ti = mi + 1;\n@@ -61,7 +178,7 @@\n  * The matched pairs of a longest common subsequence of `a` and `b`, flattened\n  * as [i0, j0, i1, j1, ...] in increasing order.\n  */\n-function commonLines(a: readonly string[], b: readonly string[]): number[] {\n+function commonLines<T>(a: readonly T[], b: readonly T[]): number[] {\n \t// Common prefix and suffix match directly.\n \tlet pre = 0;\n \twhile (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++;\n@@ -72,8 +189,8 @@\n \n \t// A line that occurs on only one side can never be matched; leave it out of\n \t// the search (this also makes wholly different texts instant).\n-\tconst ids = new Map<string, number>();\n-\tconst intern = (s: string): number => {\n+\tconst ids = new Map<T, number>();\n+\tconst intern = (s: T): number => {\n \t\tlet id = ids.get(s);\n \t\tif (id === undefined) {\n \t\t\tid = ids.size;"},{"path":"src/engine/view.ts","added":31,"removed":0,"diff":"--- a/src/engine/view.ts\n+++ b/src/engine/view.ts\n@@ -29,6 +29,7 @@\n \n /** A visible line of a projected file. */\n export interface VisibleLine {\n+\treadonly textChunks?: () => Iterable<string>;\n \treadonly id: LineId;\n \treadonly text: string;\n \treadonly atom: AtomId;\n@@ -542,6 +543,36 @@\n \t\treturn true;\n \t}\n \n+\t*lineChunks(path: string): IterableIterator<() => Iterable<string>> {\n+\t\tfor (const n of this.#file(path).vis) yield () => this.graph.textChunks(n);\n+\t}\n+\n+\t/** Visible lines without retaining their text in the view cache. */\n+\t*visibleLines(path: string): IterableIterator<VisibleLine> {\n+\t\tconst graph = this.graph;\n+\t\tfor (const n of this.#file(path).vis)\n+\t\t\tyield { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };\n+\t}\n+\n+\t/** Atom-building line handles; text is loaded only when requested. */\n+\tbuildLines(path: string): readonly VisibleLine[] {\n+\t\tconst graph = this.graph;\n+\t\tconst vis = this.#file(path).vis;\n+\t\tconst lines: VisibleLine[] = new Array(vis.length);\n+\t\tfor (let i = 0; i < vis.length; i++) {\n+\t\t\tconst n = vis[i]!;\n+\t\t\tlines[i] = {\n+\t\t\t\tid: graph.lineIdOf(n),\n+\t\t\t\ttextChunks: () => graph.textChunks(n),\n+\t\t\t\tget text() {\n+\t\t\t\t\treturn graph.textOf(n);\n+\t\t\t\t},\n+\t\t\t\tatom: graph.idOfSeq(graph.writerSeqOf(n)),\n+\t\t\t};\n+\t\t}\n+\t\treturn lines;\n+\t}\n+\n \t/** Visible lines with their ids. */\n \tlines(path: string): readonly VisibleLine[] {\n \t\tif (this.#linesCache?.path === path) return this.#linesCache.lines;"},{"path":"worker/project/add-draft.ts","added":1,"removed":1,"diff":"--- a/worker/project/add-draft.ts\n+++ b/worker/project/add-draft.ts\n@@ -50,7 +50,7 @@\n \tconst touched = new Set<AtomId>();\n \tfor (const key of claimsOf(atom)) {\n \t\tconst { kind, node } = parseKey(key);\n-\t\tif (kind === \"line\") touched.add(host.graph.line(node)!.atom);\n+\t\tif (kind === \"line\") touched.add(host.graph.idOfSeq(host.graph.writerSeqOf(host.graph.lineN(node))));\n \t\t// Setting an attribute again settles a collision over it.\n \t\tif (kind === \"attr\") for (const w of host.graph.writersOf(key)) touched.add(w);\n \t}"},{"path":"worker/project/definition-code.ts","added":70,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/definition-code.ts\n@@ -0,0 +1,70 @@\n+import type { ReadView, VisibleLine } from \"../../src/engine/index.ts\";\n+import { StoredText } from \"../../src/engine/stored-text.ts\";\n+import { eachCodeLine } from \"./names.ts\";\n+\n+/** Parsed code is temporary derived data, discarded with the scratch transaction. */\n+export function withDefinitionCode<T>(\n+\tview: ReadView,\n+\tvisible: readonly VisibleLine[],\n+\toperation: (code: readonly string[]) => T,\n+): T {\n+\tfunction* source() {\n+\t\tfor (const line of visible) yield line.text;\n+\t}\n+\tif (!view.graph.hasOrderedChildren) return operation([...eachCodeLine(source())]);\n+\tconst iterator = eachCodeLine(source());\n+\tlet prefix: string[] = [];\n+\tlet size = 0;\n+\tlet pending = iterator.next();\n+\twhile (!pending.done && size + pending.value.length + 1 <= 65536) {\n+\t\tprefix.push(pending.value);\n+\t\tsize += pending.value.length + 1;\n+\t\tpending = iterator.next();\n+\t}\n+\tif (pending.done) return operation(prefix);\n+\treturn view.graph.withProjectionScratch((storage) => {\n+\t\tconst text = new StoredText(storage, \"definition-code\");\n+\t\tlet count = 0;\n+\t\tfor (const line of prefix) text.write(String(count++), line);\n+\t\tprefix = [];\n+\t\ttext.write(String(count++), pending.value!);\n+\t\tfor (const line of iterator) text.write(String(count++), line);\n+\t\tconst cache = new Map<number, string>();\n+\t\tlet characters = 0;\n+\t\tconst read = (index: number) => {\n+\t\t\tif (index < 0 || index >= count) return undefined;\n+\t\t\tconst cached = cache.get(index);\n+\t\t\tif (cached !== undefined) return cached;\n+\t\t\tconst value = text.read(String(index));\n+\t\t\tif (value.length <= 65536) {\n+\t\t\t\twhile (cache.size >= 64 || characters + value.length > 65536) {\n+\t\t\t\t\tconst first = cache.keys().next().value!;\n+\t\t\t\t\tcharacters -= cache.get(first)!.length;\n+\t\t\t\t\tcache.delete(first);\n+\t\t\t\t}\n+\t\t\t\tcache.set(index, value);\n+\t\t\t\tcharacters += value.length;\n+\t\t\t}\n+\t\t\treturn value;\n+\t\t};\n+\t\tlet active = true;\n+\t\tconst code = new Proxy([] as string[], {\n+\t\t\thas(target, key) {\n+\t\t\t\tif (!active) throw Error(\"definition code scope has ended\");\n+\t\t\t\tif (typeof key === \"string\" && /^(0|[1-9][0-9]*)$/.test(key)) return Number(key) < count;\n+\t\t\t\treturn Reflect.has(target, key);\n+\t\t\t},\n+\t\t\tget(target, key, receiver) {\n+\t\t\t\tif (!active) throw Error(\"definition code scope has ended\");\n+\t\t\t\tif (key === \"length\") return count;\n+\t\t\t\tif (typeof key === \"string\" && /^(0|[1-9][0-9]*)$/.test(key)) return read(Number(key));\n+\t\t\t\treturn Reflect.get(target, key, receiver);\n+\t\t\t},\n+\t\t});\n+\t\ttry {\n+\t\t\treturn operation(code);\n+\t\t} finally {\n+\t\t\tactive = false;\n+\t\t}\n+\t});\n+}"},{"path":"worker/project/definitions.ts","added":44,"removed":41,"diff":"--- a/worker/project/definitions.ts\n+++ b/worker/project/definitions.ts\n@@ -20,7 +20,8 @@\n // that defines it (project.ts, #definitionCore).\n \n import type { LineId, ReadView } from \"../../src/engine/index.ts\";\n-import { codeOfLines, holdsNoCode, isCommonName } from \"./names.ts\";\n+import { withDefinitionCode } from \"./definition-code.ts\";\n+import { holdsNoCode, isCommonName } from \"./names.ts\";\n \n export interface Definition {\n \treadonly name: string;\n@@ -121,27 +122,28 @@\n function definitionsInFile(view: ReadView, file: string, keepCommon = false): Definition[] {\n \tif (holdsNoCode(file) || !view.hasFile(file)) return [];\n \tconst out: Definition[] = [];\n-\tconst visible = view.lines(file);\n-\tconst code = codeOfLines(visible.map((l) => l.text));\n-\tfor (let i = 0; i < code.length; i++) {\n-\t\t// Only top-level declarations: what another file can import. Locals,\n-\t\t// parameters and methods are indented.\n-\t\tif (/^\\s/.test(code[i]!)) continue;\n-\t\tconst found = defineAt(code, i);\n-\t\tif (!found || (!keepCommon && (found.name.length < 3 || isCommonName(found.name)))) continue;\n-\t\tout.push({\n-\t\t\tname: found.name,\n-\t\t\tfile,\n-\t\t\tstart: i,\n-\t\t\tend: found.end,\n-\t\t\tlines: visible.slice(i, found.end).map((l) => l.id),\n-\t\t\ttext: visible\n-\t\t\t\t.slice(i, found.end)\n-\t\t\t\t.map((l) => l.text)\n-\t\t\t\t.join(\"\\n\"),\n-\t\t});\n-\t}\n-\treturn out;\n+\tconst visible = view.buildLines(file);\n+\treturn withDefinitionCode(view, visible, (code) => {\n+\t\tfor (let i = 0; i < code.length; i++) {\n+\t\t\t// Only top-level declarations: what another file can import. Locals,\n+\t\t\t// parameters and methods are indented.\n+\t\t\tif (/^\\s/.test(code[i]!)) continue;\n+\t\t\tconst found = defineAt(code, i);\n+\t\t\tif (!found || (!keepCommon && (found.name.length < 3 || isCommonName(found.name)))) continue;\n+\t\t\tout.push({\n+\t\t\t\tname: found.name,\n+\t\t\t\tfile,\n+\t\t\t\tstart: i,\n+\t\t\t\tend: found.end,\n+\t\t\t\tlines: visible.slice(i, found.end).map((l) => l.id),\n+\t\t\t\ttext: visible\n+\t\t\t\t\t.slice(i, found.end)\n+\t\t\t\t\t.map((l) => l.text)\n+\t\t\t\t\t.join(\"\\n\"),\n+\t\t\t});\n+\t\t}\n+\t\treturn out;\n+\t});\n }\n \n /**\n@@ -155,25 +157,26 @@\n \tconst count = new Map<string, number>();\n \tfor (const d of all) count.set(d.name, (count.get(d.name) ?? 0) + 1);\n \tif (![...count.values()].some((n) => n > 1)) return out;\n-\tconst visible = view.lines(file);\n-\tconst code = codeOfLines(visible.map((l) => l.text));\n-\tfor (const d of all) {\n-\t\tif (count.get(d.name)! < 2) continue;\n-\t\tconst end = Math.max(d.end, wholeBlockEnd(code, d.start));\n-\t\tconst whole: Definition = {\n-\t\t\t...d,\n-\t\t\tend,\n-\t\t\tlines: visible.slice(d.start, end).map((l) => l.id),\n-\t\t\ttext: visible\n-\t\t\t\t.slice(d.start, end)\n-\t\t\t\t.map((l) => l.text)\n-\t\t\t\t.join(\"\\n\"),\n-\t\t};\n-\t\tconst list = out.get(d.name);\n-\t\tif (list) list.push(whole);\n-\t\telse out.set(d.name, [whole]);\n-\t}\n-\treturn out;\n+\tconst visible = view.buildLines(file);\n+\treturn withDefinitionCode(view, visible, (code) => {\n+\t\tfor (const d of all) {\n+\t\t\tif (count.get(d.name)! < 2) continue;\n+\t\t\tconst end = Math.max(d.end, wholeBlockEnd(code, d.start));\n+\t\t\tconst whole: Definition = {\n+\t\t\t\t...d,\n+\t\t\t\tend,\n+\t\t\t\tlines: visible.slice(d.start, end).map((l) => l.id),\n+\t\t\t\ttext: visible\n+\t\t\t\t\t.slice(d.start, end)\n+\t\t\t\t\t.map((l) => l.text)\n+\t\t\t\t\t.join(\"\\n\"),\n+\t\t\t};\n+\t\t\tconst list = out.get(d.name);\n+\t\t\tif (list) list.push(whole);\n+\t\t\telse out.set(d.name, [whole]);\n+\t\t}\n+\t\treturn out;\n+\t});\n }\n \n /**"},{"path":"worker/project/express-moves.ts","added":30,"removed":17,"diff":"--- a/worker/project/express-moves.ts\n+++ b/worker/project/express-moves.ts\n@@ -1,10 +1,12 @@\n+import { diffLineSymbols } from \"../../src/engine/text.ts\";\n+import { recordFileChanges } from \"./record-file.ts\";\n // Moves (#28): within one agent's unpublished draft, a line that leaves one place and the same\n // text that arrives somewhere else is the same line. Before a publish, those matches become move\n // atoms so the lines keep their ids. Writes go through ExpressMovesHost; today the host is Project.\n \n import type { AtomId, AttrSet, EditInput, Graph, LineId, MoveInput, ReadView } from \"../../src/engine/index.ts\";\n import { differenceSet, StableOverlaySet } from \"../../src/engine/state-source.ts\";\n-import { PLAIN_LINE } from \"./collisions.ts\";\n+import { MoveLineText } from \"./move-line-text.ts\";\n import type { AgentState, Entry, Meta, Mode } from \"./project-types.ts\";\n \n /** The most moved blocks one publish expresses: the longest ones, when there are more. */\n@@ -59,6 +61,7 @@\n \tif (draft.length === 0) return;\n \tconst g = host.graph;\n \tconst mine = new Set(draft);\n+\tconst text = new MoveLineText(g);\n \tconst after = host.agentView(agent);\n \tconst before = host.beforeDraft\n \t\t? host.beforeDraft(agent, draft)\n@@ -71,25 +74,25 @@\n \t\treadonly file: string;\n \t\treadonly start: number;\n \t\treadonly ids: LineId[];\n-\t\treadonly texts: string[];\n+\t\treadonly texts: number[];\n \t}\n \tconst gone: Block[] = [];\n \tconst written: Block[] = [];\n \tfor (const file of [...touched].toSorted()) {\n \t\tlet cur: Block | undefined;\n-\t\tbefore.lines(file).forEach((l, i) => {\n+\t\tbefore.buildLines(file).forEach((l, i) => {\n \t\t\tif (g.deletersOf(l.id).some((d) => mine.has(d))) {\n \t\t\t\tif (!cur) gone.push((cur = { file, start: i, ids: [], texts: [] }));\n \t\t\t\tcur.ids.push(l.id);\n-\t\t\t\tcur.texts.push(l.text);\n+\t\t\t\tcur.texts.push(text.intern(l.id));\n \t\t\t} else cur = undefined;\n \t\t});\n \t\tcur = undefined;\n-\t\tafter.lines(file).forEach((l, i) => {\n+\t\tafter.buildLines(file).forEach((l, i) => {\n \t\t\tif (mine.has(l.atom)) {\n \t\t\t\tif (!cur) written.push((cur = { file, start: i, ids: [], texts: [] }));\n \t\t\t\tcur.ids.push(l.id);\n-\t\t\t\tcur.texts.push(l.text);\n+\t\t\t\tcur.texts.push(text.intern(l.id));\n \t\t\t} else cur = undefined;\n \t\t});\n \t}\n@@ -108,7 +111,7 @@\n \t// Where each deleted text starts a candidate, in block and line order (abso issue 158): a stretch\n \t// can only start where the texts are equal, so each written line looks only there, not at\n \t// every deleted line. A text deleted more than MATCH_STARTS times keeps its first ones.\n-\tconst starts = new Map<string, { block: Block; q: number }[]>();\n+\tconst starts = new Map<number, { block: Block; q: number }[]>();\n \tfor (const block of gone)\n \t\tblock.texts.forEach((t, q) => {\n \t\t\tconst list = starts.get(t);\n@@ -131,7 +134,7 @@\n \t\t\t\t}\n \t\t\t\tif (len > 0 && (!best || len > best.len)) best = { block, q, len };\n \t\t\t}\n-\t\t\tif (best?.block.texts.slice(best.q, best.q + best.len).some((t) => !PLAIN_LINE.test(t))) {\n+\t\t\tif (best?.block.texts.slice(best.q, best.q + best.len).some((t) => !text.plain[t])) {\n \t\t\t\tconst ids = best.block.ids.slice(best.q, best.q + best.len);\n \t\t\t\tfor (const id of ids) used.add(id);\n \t\t\t\tmatches.push({ from: best.block.file, ids, to: run.file, at: run.start + p });\n@@ -145,7 +148,7 @@\n \t// passed Workers' CPU limit. So the longest blocks move first, up to MOVE_LIMIT of them and\n \t// MOVE_BUDGET lines laid out in all; the rest are a delete and a fresh write, as an unmatched block\n \t// always is.\n-\tconst length = (path: string) => (after.hasFile(path) ? after.lines(path).length : 0);\n+\tconst length = (path: string) => (after.hasFile(path) ? after.buildLines(path).length : 0);\n \tconst cost = (m: Match) => length(m.from) + (m.to === m.from ? 0 : length(m.to));\n \tconst keep = new Set<Match>();\n \tlet spent = 0;\n@@ -185,7 +188,7 @@\n \t\tconst start = view.lineNumber(m.from, m.ids[0]!);\n \t\tif (start < 0 || m.ids.some((id, k) => view.lineNumber(m.from, id) !== start + k)) continue;\n \t\t// Land after the nearest line above it in the final text that is already there.\n-\t\tconst finalLines = host.agentView(finalAgent).lines(m.to);\n+\t\tconst finalLines = host.agentView(finalAgent).buildLines(m.to);\n \t\tlet at = 0;\n \t\tfor (let i = m.at - 1; i >= 0; i--) {\n \t\t\tconst n = view.lineNumber(m.to, finalLines[i]!.id);\n@@ -207,18 +210,28 @@\n \tfor (const path of [...involved].toSorted()) {\n \t\tconst finalView = host.agentView(finalAgent);\n \t\tconst was = finalView.attrs(path);\n-\t\thost.recordFile(\n+\t\tconst view = host.agentView(agent);\n+\t\tconst target = finalView.buildLines(path);\n+\t\tconst symbols = new MoveLineText(g);\n+\t\tconst previous = view.buildLines(path).map((line) => symbols.intern(line.id));\n+\t\tconst next = target.map((line) => symbols.intern(line.id));\n+\t\tconst edits = diffLineSymbols(previous, next).map((hunk) => ({\n+\t\t\tfile: path,\n+\t\t\tstart: hunk.start,\n+\t\t\tend: hunk.end,\n+\t\t\tlines: hunk.lines.map((symbol) => symbols.text(symbol)),\n+\t\t}));\n+\t\trecordFileChanges(\n+\t\t\thost,\n \t\t\tagent,\n-\t\t\thost.agentView(agent),\n+\t\t\tview,\n \t\t\tpath,\n-\t\t\tfinalView.hasFile(path) ? finalView.text(path) : null,\n+\t\t\t!finalView.hasFile(path) ? \"missing\" : target.length === 0 ? \"empty\" : \"present\",\n+\t\t\tedits,\n \t\t\ttime,\n \t\t\t{},\n \t\t\tentries,\n-\t\t\t{\n-\t\t\t\texec: was.exec,\n-\t\t\t\tlink: was.link,\n-\t\t\t},\n+\t\t\t{ exec: was.exec, link: was.link },\n \t\t);\n \t}\n }"},{"path":"worker/project/markers.ts","added":1,"removed":1,"diff":"--- a/worker/project/markers.ts\n+++ b/worker/project/markers.ts\n@@ -352,7 +352,7 @@\n \tconst out: Collision[] = [];\n \tfor (const file of [...host.draftFiles(agent)].toSorted()) {\n \t\tif (!view.hasFile(file)) continue;\n-\t\tconst lines = view.lines(file);\n+\t\tconst lines = view.buildLines(file);\n \t\tconst added = lines.map((l, i) => (mine.has(l.atom) && isMarkerLine(l.text) ? i : -1)).filter((i) => i >= 0);\n \t\tif (added.length === 0) continue;\n \t\tconst blocks = blocksIn(lines.map((l) => l.text));"},{"path":"worker/project/move-line-text.ts","added":74,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/move-line-text.ts\n@@ -0,0 +1,74 @@\n+import type { Graph } from \"../../src/engine/graph.ts\";\n+import { PLAIN_LINE } from \"./collisions.ts\";\n+\n+/** Exact text symbols backed by graph line IDs, never retained whole strings. */\n+export class MoveLineText {\n+\treadonly graph: Graph;\n+\treadonly buckets = new Map<string, { symbol: number; line: number }[]>();\n+\treadonly plain: boolean[] = [];\n+\treadonly lines: number[] = [];\n+\treadonly symbolsByLine = new Map<number, number>();\n+\tconstructor(graph: Graph) {\n+\t\tthis.graph = graph;\n+\t}\n+\ttext(symbol: number): string {\n+\t\tconst line = this.lines[symbol];\n+\t\tif (line === undefined) throw Error(\"unknown move text symbol\");\n+\t\treturn this.graph.textOf(line);\n+\t}\n+\n+\tintern(id: string): number {\n+\t\tconst line = this.graph.lineN(id);\n+\t\tconst known = this.symbolsByLine.get(line);\n+\t\tif (known !== undefined) return known;\n+\t\tlet hash = 2166136261,\n+\t\t\tlength = 0,\n+\t\t\tplain = true;\n+\t\tfor (const chunk of this.graph.textChunks(line)) {\n+\t\t\tlength += chunk.length;\n+\t\t\tif (!PLAIN_LINE.test(chunk)) plain = false;\n+\t\t\tfor (let i = 0; i < chunk.length; i++) hash = Math.imul(hash ^ chunk.charCodeAt(i), 16777619) >>> 0;\n+\t\t}\n+\t\tconst key = `${length}:${hash}`;\n+\t\tconst bucket = this.buckets.get(key) ?? [];\n+\t\tfor (const candidate of bucket)\n+\t\t\tif (sameChunks(this.graph.textChunks(line), this.graph.textChunks(candidate.line))) {\n+\t\t\t\tthis.symbolsByLine.set(line, candidate.symbol);\n+\t\t\t\treturn candidate.symbol;\n+\t\t\t}\n+\t\tconst symbol = this.plain.length;\n+\t\tthis.plain.push(plain);\n+\t\tthis.lines.push(line);\n+\t\tbucket.push({ symbol, line });\n+\t\tthis.buckets.set(key, bucket);\n+\t\tthis.symbolsByLine.set(line, symbol);\n+\t\treturn symbol;\n+\t}\n+}\n+\n+function sameChunks(a: IterableIterator<string>, b: IterableIterator<string>): boolean {\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":"worker/project/names.ts","added":6,"removed":2,"diff":"--- a/worker/project/names.ts\n+++ b/worker/project/names.ts\n@@ -194,9 +194,13 @@\n  * without its string literals and comments. A string or comment opened on\n  * one line continues on the next.\n  */\n-export function codeOfLines(lines: readonly string[]): string[] {\n+export function codeOfLines(lines: Iterable<string>): string[] {\n+\treturn [...eachCodeLine(lines)];\n+}\n+\n+export function* eachCodeLine(lines: Iterable<string>): IterableIterator<string> {\n \tconst st: ScanState = { stack: [{ kind: \"code\", depth: 0 }], block: false, triple: undefined };\n-\treturn lines.map((line) => scanLine(line, st));\n+\tfor (const line of lines) yield scanLine(line, st);\n }\n \n /** Names in some code (from codeOfLines): identifiers of three or more characters that aren't common names. */"},{"path":"worker/project/record-file.ts","added":57,"removed":17,"diff":"--- a/worker/project/record-file.ts\n+++ b/worker/project/record-file.ts\n@@ -4,7 +4,7 @@\n import {\n \ttype AttrName,\n \ttype AttrSet,\n-\tdiffLines,\n+\tdiffChunkedLines,\n \ttype EditInput,\n \ttype Hunk,\n \ttype ReadView,\n@@ -44,39 +44,79 @@\n \tblob?: string,\n \thunks?: readonly Hunk[],\n ): boolean {\n-\tconst was = view.attrs(path);\n-\tconst exists = view.hasFile(path);\n \tconst lines = text === undefined ? undefined : text === null ? \"\" : text;\n \tconst edits: SpliceEdit[] =\n-\t\tlines === undefined || view.text(path) === lines\n+\t\tlines === undefined || (hunks !== undefined && sameProjectedText(view, path, lines))\n \t\t\t? []\n-\t\t\t: (\n-\t\t\t\t\thunks ??\n-\t\t\t\t\tdiffLines(\n-\t\t\t\t\t\tview.lines(path).map((l) => l.text),\n-\t\t\t\t\t\tsplitLines(lines),\n-\t\t\t\t\t)\n-\t\t\t\t).map((h) => ({ file: path, start: h.start, end: h.end, lines: h.lines }));\n+\t\t\t: (hunks ?? diffChunkedLines(view.lineChunks(path), splitLines(lines))).map((h) => ({\n+\t\t\t\t\tfile: path,\n+\t\t\t\t\tstart: h.start,\n+\t\t\t\t\tend: h.end,\n+\t\t\t\t\tlines: h.lines,\n+\t\t\t\t}));\n+\treturn recordFileChanges(\n+\t\thost,\n+\t\tagent,\n+\t\tview,\n+\t\tpath,\n+\t\ttext === undefined ? \"unchanged\" : text === null ? \"missing\" : text === \"\" ? \"empty\" : \"present\",\n+\t\tedits,\n+\t\ttime,\n+\t\tmeta,\n+\t\tentries,\n+\t\tmode,\n+\t\tblob,\n+\t);\n+}\n+\n+/** Apply a precomputed exact text diff and the normal file attribute rules. */\n+export function recordFileChanges(\n+\thost: RecordFileHost,\n+\tagent: AgentState,\n+\tview: ReadView,\n+\tpath: string,\n+\tstate: \"unchanged\" | \"missing\" | \"empty\" | \"present\",\n+\tedits: readonly SpliceEdit[],\n+\ttime: number,\n+\tmeta: Meta,\n+\tentries: Entry[],\n+\tmode: Mode = {},\n+\tblob?: string,\n+): boolean {\n+\tconst was = view.attrs(path);\n+\tconst exists = view.hasFile(path);\n+\n \tconst attrs: AttrSet[] = [];\n \tconst set = (name: AttrName, now: string | null, value: string | null): void => {\n \t\tif (now !== value) attrs.push({ file: path, name, value });\n \t};\n-\tconst link = mode.link !== undefined ? mode.link : text === null ? null : was.link;\n-\tif (text === null) {\n+\tconst link = mode.link !== undefined ? mode.link : state === \"missing\" ? null : was.link;\n+\tif (state === \"missing\") {\n \t\t// Gone: no lines, and nothing keeps it.\n \t\tset(\"exists\", was.exists ? \"1\" : null, null);\n \t\tset(\"exec\", was.exec ? \"1\" : null, null);\n-\t} else if (text === \"\" && link === null && blob === undefined) {\n+\t} else if (state === \"empty\" && link === null && blob === undefined) {\n \t\t// An empty file is kept by its exists attribute.\n \t\tset(\"exists\", was.exists ? \"1\" : null, \"1\");\n \t}\n \t// A binary file is its blob and no lines; text, or no file, clears the blob.\n \tif (blob !== undefined) set(\"blob\", was.blob, blob);\n-\telse if (text !== undefined) set(\"blob\", was.blob, null);\n-\tif (mode.exec !== undefined && text !== null) set(\"exec\", was.exec ? \"1\" : null, mode.exec ? \"1\" : null);\n+\telse if (state !== \"unchanged\") set(\"blob\", was.blob, null);\n+\tif (mode.exec !== undefined && state !== \"missing\") set(\"exec\", was.exec ? \"1\" : null, mode.exec ? \"1\" : null);\n \tset(\"link\", was.link, link);\n \tif (edits.length === 0 && attrs.length === 0) return false;\n-\tif (!exists && text === null && attrs.length === 0) return false;\n+\tif (!exists && state === \"missing\" && attrs.length === 0) return false;\n \thost.addDraft(agent, view, { edits, attrs }, time, meta, entries);\n \treturn true;\n }\n+\n+/** Compare canonical projected text without joining or caching old lines. */\n+function sameProjectedText(view: ReadView, path: string, text: string): boolean {\n+\tlet offset = 0;\n+\tfor (const line of view.visibleLines(path)) {\n+\t\tif (!text.startsWith(line.text, offset)) return false;\n+\t\toffset += line.text.length;\n+\t\tif (text[offset++] !== \"\\n\") return false;\n+\t}\n+\treturn offset === text.length;\n+}"},{"path":"worker/project/test/definition-code.test.ts","added":56,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/definition-code.test.ts\n@@ -0,0 +1,56 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph, View } from \"../../../src/engine/index.ts\";\n+import { SqlState } from \"../../../src/engine/test/storage-helper.ts\";\n+import { withDefinitionCode } from \"../definition-code.ts\";\n+import { definedTwice, definitionsIn } from \"../definitions.ts\";\n+import { codeOfLines } from \"../names.ts\";\n+\n+test(\"small parsed code stays in memory without scratch writes\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst graph = new Graph({ storage });\n+\tgraph.add(buildBase({ \"f.ts\": \"export const answer = 42;\\n\" }, { author: \"writer\", message: \"init\" }));\n+\tconst view = new View(graph, [\"a0\"]);\n+\tconst writes = storage.writes;\n+\twithDefinitionCode(view, view.buildLines(\"f.ts\"), (code) => {\n+\t\tassert.deepEqual(code, codeOfLines([\"export const answer = 42;\"]));\n+\t});\n+\tassert.equal(storage.writes, writes);\n+});\n+\n+test(\"disk definition code preserves random reads and always rolls scratch back\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst lines = [\n+\t\t\"/* comment\",\n+\t\t\"end */ export function parseOne(\",\n+\t\t\"arg: string\",\n+\t\t\") { return 1; }\",\n+\t\t...Array.from({ length: 4000 }, (_, i) => `const value${i} = ${i}; // trailing`),\n+\t];\n+\tconst atom = buildBase({ \"f.ts\": `${lines.join(\"\\n\")}\\n` }, { author: \"writer\", message: \"init\" });\n+\tconst memory = new Graph();\n+\tmemory.add(atom);\n+\tconst graph = new Graph({ storage });\n+\tgraph.add(atom);\n+\tconst view = new View(graph, [\"a0\"]);\n+\tconst expected = codeOfLines(lines);\n+\tconst rows = () => storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\tconst before = rows();\n+\tlet escaped: readonly string[] = [];\n+\twithDefinitionCode(view, view.buildLines(\"f.ts\"), (code) => {\n+\t\tescaped = code;\n+\t\tassert.deepEqual(code.slice(0, 4), expected.slice(0, 4));\n+\t\tfor (let i = code.length - 1; i >= 0; i--) assert.equal(code[i], expected[i]);\n+\t\tfor (let i = 0; i < code.length; i++) assert.equal(code[i], expected[i]);\n+\t});\n+\tassert.throws(() => escaped[0], /scope has ended/);\n+\tassert.deepEqual(rows(), before);\n+\tassert.deepEqual(definitionsIn(view), definitionsIn(new View(memory, [\"a0\"])));\n+\tassert.deepEqual(definedTwice(view, \"f.ts\"), definedTwice(new View(memory, [\"a0\"]), \"f.ts\"));\n+\tassert.deepEqual(rows(), before);\n+\tstorage.failWrite = storage.writes + 2;\n+\tassert.throws(() => withDefinitionCode(view, view.buildLines(\"f.ts\"), () => []), /injected storage failure/);\n+\tassert.deepEqual(rows(), before);\n+});"},{"path":"worker/project/test/definitions.test.ts","added":10,"removed":0,"diff":"--- a/worker/project/test/definitions.test.ts\n+++ b/worker/project/test/definitions.test.ts\n@@ -68,3 +68,13 @@\n \tassert.deepEqual(defs({ \"fixtures/a.json\": codeLike, \"data/b.csv\": codeLike, \"c.lock\": codeLike }), {});\n \tassert.deepEqual(Object.keys(defs({ \"src/a.ts\": codeLike })), [\"parsePattern\"]);\n });\n+\n+test(\"definition scanning does not retain the original file line array\", (t) => {\n+\tconst graph = new Graph();\n+\tgraph.add(buildBase({ \"a.ts\": \"export function parseThing() { return 1; }\\n\" }, { author: \"t\", message: \"t\" }));\n+\tconst view = new View(graph, [\"a0\"]);\n+\tt.mock.method(view, \"lines\", () => {\n+\t\tthrow Error(\"original file line array forbidden\");\n+\t});\n+\tassert.deepEqual([...definitionsIn(view).keys()], [\"parseThing\"]);\n+});"},{"path":"worker/project/test/move-line-text.test.ts","added":29,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/move-line-text.test.ts\n@@ -0,0 +1,29 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { Graph } from \"../../../src/engine/graph.ts\";\n+import { StoredText } from \"../../../src/engine/stored-text.ts\";\n+import { Repo } from \"../../../src/engine/test/helpers.ts\";\n+import { SqlState } from \"../../../src/engine/test/storage-helper.ts\";\n+import { MoveLineText } from \"../move-line-text.ts\";\n+\n+test(\"move text symbols compare stored chunks exactly and distinguish hash collisions\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst long = \"x\".repeat(100000);\n+\tconst repo = Repo.init({ f: `reqicjpk\\nejfslztg\\n${long}\\n${long}\\n  {};\\n` });\n+\tconst graph = new Graph({ storage });\n+\tgraph.add(repo.graph.atom(\"a0\"));\n+\tt.mock.method(StoredText.prototype, \"read\", () => {\n+\t\tthrow Error(\"whole text forbidden\");\n+\t});\n+\tconst texts = new MoveLineText(graph);\n+\tassert.notEqual(texts.intern(\"a0.0\"), texts.intern(\"a0.1\"));\n+\tassert.equal(texts.intern(\"a0.2\"), texts.intern(\"a0.3\"));\n+\tassert.equal(texts.plain[texts.intern(\"a0.2\")], false);\n+\tassert.equal(texts.plain[texts.intern(\"a0.4\")], true);\n+\tconst known = texts.intern(\"a0.2\");\n+\tt.mock.method(graph, \"textChunks\", () => {\n+\t\tthrow Error(\"known identity must not reread text\");\n+\t});\n+\tassert.equal(texts.intern(\"a0.2\"), known);\n+});"},{"path":"worker/project/test/move-reconstruction.test.ts","added":18,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/move-reconstruction.test.ts\n@@ -0,0 +1,18 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { View } from \"../../../src/engine/view.ts\";\n+import { MemoryStore, Project } from \"../project.ts\";\n+\n+test(\"move reconstruction does not join the intended whole file\", (t) => {\n+\tconst project = new Project(new MemoryStore());\n+\tproject.init({ \"a.txt\": \"header\\nmove this line\\nfooter\\n\", \"b.txt\": \"destination\\n\" }, 0);\n+\tproject.sync(\"writer\");\n+\tassert.equal(project.edit(\"writer\", { file: \"a.txt\", old: \"move this line\\n\", new: \"\" }, 1).ok, true);\n+\tassert.equal(project.edit(\"writer\", { file: \"b.txt\", content: \"destination\\nmove this line\\n\" }, 1).ok, true);\n+\tconst whole = t.mock.method(View.prototype, \"text\", () => {\n+\t\tthrow Error(\"whole file join forbidden\");\n+\t});\n+\tassert.equal(project.publish(\"writer\", \"move\", 2).ok, true);\n+\twhole.mock.restore();\n+\tassert.deepEqual(project.files(), { \"a.txt\": \"header\\nfooter\\n\", \"b.txt\": \"destination\\nmove this line\\n\" });\n+});"},{"path":"worker/project/test/record-stream.test.ts","added":44,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/record-stream.test.ts\n@@ -0,0 +1,44 @@\n+import assert from \"node:assert/strict\";\n+import { it } from \"node:test\";\n+import { Repo } from \"../../../src/engine/test/helpers.ts\";\n+import type { AgentState } from \"../project-types.ts\";\n+import { type RecordFileHost, recordFile } from \"../record-file.ts\";\n+\n+it(\"records replacements without materializing old file text or line arrays\", () => {\n+\tconst view = Repo.init({ \"large.txt\": `${\"x\".repeat(100000)}\\nkeep\\n` }).view();\n+\tview.text = () => {\n+\t\tthrow Error(\"whole old text is forbidden\");\n+\t};\n+\tview.lines = () => {\n+\t\tthrow Error(\"old line array is forbidden\");\n+\t};\n+\tconst calls: Parameters<RecordFileHost[\"addDraft\"]>[2][] = [];\n+\tconst host: RecordFileHost = {\n+\t\taddDraft(_agent, _view, input) {\n+\t\t\tcalls.push(input);\n+\t\t},\n+\t};\n+\tconst agent: AgentState = {\n+\t\tname: \"writer\",\n+\t\tspace: \"\",\n+\t\tbase: 0,\n+\t\tsynced: true,\n+\t\tmine: [],\n+\t\tnews: [],\n+\t\tnewsAt: [],\n+\t\ttold: new Set(),\n+\t\tparked: new Map(),\n+\t\tmarked: [],\n+\t};\n+\tassert.equal(recordFile(host, agent, view, \"large.txt\", \"changed\\nkeep\\n\", 1, {}, []), true);\n+\tassert.deepEqual(calls[0]!.edits, [{ file: \"large.txt\", start: 0, end: 1, lines: [\"changed\"] }]);\n+\tconst unchanged = `${\"x\".repeat(100000)}\\nkeep\\n`;\n+\tassert.equal(recordFile(host, agent, view, \"large.txt\", unchanged, 1, {}, []), false);\n+\tassert.equal(\n+\t\trecordFile(host, agent, view, \"large.txt\", unchanged, 1, {}, [], {}, undefined, [\n+\t\t\t{ start: 0, end: 1, lines: [\"ignored\"] },\n+\t\t]),\n+\t\tfalse,\n+\t);\n+\tassert.equal(calls.length, 1);\n+});"}],"ci":null}