27 files, 1107 lines added, 119 removed.
--- /dev/null
+++ b/server/test/definition-scratch-runtime.test.ts
@@ -0,0 +1,55 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { answer } from "../../worker/project/http.ts"; 4+import { Project } from "../../worker/project/project.ts"; 5+import { DiskFirstRuntime } from "../src/disk-first-runtime.ts"; 6+import { memoryStorage } from "./helpers.ts"; 8+test("scratch-backed definition scanning preserves code-file record and publish", (t) => { 9+ const storage = memoryStorage(); 10+ t.after(() => storage.db.close()); 11+ const runtime = () => new DiskFirstRuntime(storage, "text-bound", "text-bound"); 12+ const unchanged = "stable".repeat(10000); 13+ const old = `${"old".repeat(20000)}\n${unchanged}\n`; 14+ const current = `changed\n${unchanged}\n`; 16+ runtime().initialize( 17+ (c) => answer(c, "init", undefined, { files: { f: old } }), 22+ while (!runtime().preparePage(() => {}).ready) {} 23+ t.mock.method(Project, "load", () => { 24+ throw Error("full history replay forbidden"); 29+ (c) => answer(c, "record", "writer", { files: { f: current } }), 36+ (c) => answer(c, "publish", "writer", { message: "replace" }), 43+ (c) => c.filesAt(0)["f"], 50+ (c) => c.shared().files["f"], --- a/server/test/long-text-history.test.ts
+++ b/server/test/long-text-history.test.ts
@@ -1,6 +1,7 @@
11import assert from "node:assert/strict"; 22import { test } from "node:test"; 33import { Graph } from "../../src/engine/graph.ts"; 4+import { StoredText } from "../../src/engine/stored-text.ts"; 45import { answer } from "../../worker/project/http.ts"; 56import { Project } from "../../worker/project/project.ts"; 67import { DiskFirstRuntime } from "../src/disk-first-runtime.ts"; @@ -23,6 +24,9 @@
2324 (calls) => calls.fileAt("a.txt", 0, null), 27+ const wholeRead = t.mock.method(StoredText.prototype, "read", () => { 28+ throw Error("whole stored text read forbidden during record"); 2832 (calls) => answer(calls, "record", "alice", { files: { "a.txt": current } }), @@ -30,6 +34,7 @@
37+ wholeRead.mock.restore(); 3540 (calls) => answer(calls, "publish", "alice", { message: "Replace long line" }), --- a/src/engine/build.ts
+++ b/src/engine/build.ts
@@ -4,7 +4,7 @@
55import { Graph } from "./graph.ts"; 66import { attrKey, gapKey, isStartNode, lineKey, parseKey, posKey, startNode, writerOf } from "./keys.ts"; 7−import { diffLines, joinLines, normalizeText, splitLines } from "./text.ts";
7+import { diffChunkedLines, joinLines, normalizeText, splitLines } from "./text.ts"; @@ -26,8 +26,33 @@
2626/** Exact read surface used to build atoms; membership requires point lookup only. */ 2727export type AtomBuildView = Pick<View, "graph" | "lines" | "sequence" | "sequenceIndex" | "parentOf"> & { 2828 readonly set: Pick<ReadonlySet<AtomId>, "has">; 29+ buildLines?: View["buildLines"]; 32+function buildingLines(view: AtomBuildView, path: string) { 33+ return view.buildLines ? view.buildLines(path) : view.lines(path); 36+/** Cache only within one immutable build; never retain handles across writes. */ 37+function cachedBuildView(view: AtomBuildView): AtomBuildView { 38+ const files = new Map<string, ReturnType<View["lines"]>>(); 43+ let lines = files.get(path); 45+ lines = buildingLines(view, path); 46+ files.set(path, lines); 50+ sequence: (path) => view.sequence(path), 51+ sequenceIndex: (path, line) => view.sequenceIndex(path, line), 52+ parentOf: (line) => view.parentOf(line), 3156/** Replace the one exact occurrence of `old` in `file` with `new`. */ 3257export interface TextEdit { 3358 readonly file: string; @@ -132,6 +157,7 @@
134159function build(view: AtomBuildView, input: AtomInput, allowEmpty: boolean): Atom { 160+ view = cachedBuildView(view); 135161 const graph = view.graph; 136162 const id = graph.nextId(); 137163 if (typeof input.author !== "string" || typeof input.message !== "string") { @@ -152,9 +178,14 @@
152178 const emptiedBy = new Set<AtomId>(); 154180 for (const region of regions) { 155− const visible = view.lines(region.file);
156− const oldLines = visible.slice(region.start, region.end).map((l) => l.text);
157− for (const hunk of diffLines(oldLines, region.lines)) {
181+ const visible = buildingLines(view, region.file); 182+ function* oldLines() { 183+ for (let i = region.start; i < region.end; i++) { 184+ const line = visible[i]!; 185+ yield () => (line.textChunks ? line.textChunks() : [line.text]); 188+ for (const hunk of diffChunkedLines(oldLines(), region.lines)) { 158189 const start = region.start + hunk.start; 159190 const end = region.start + hunk.end; 160191 let parent: NodeId; @@ -285,7 +316,7 @@
285316 if (typeof path !== "string" || path === "" || /[\n\r]/.test(path)) 286317 throw new EngineError("bad-edit", `bad file path ${JSON.stringify(path)}`); 288− const visible = view.lines(move.file);
319+ const visible = buildingLines(view, move.file); 289320 const { start, end, at } = move; 290321 if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end > visible.length || start >= end) { 291322 throw new EngineError( @@ -293,7 +324,7 @@
293324 `${move.file} lines [${start}, ${end}) are not a non-empty range of its ${visible.length} visible lines`, 296− const dest = view.lines(move.to);
327+ const dest = buildingLines(view, move.to); 297328 if (!Number.isInteger(at) || at < 0 || at > dest.length) { 298329 throw new EngineError("bad-range", `${move.to} has no place ${at} (it has ${dest.length} visible lines)`); @@ -396,7 +427,7 @@
398429function rangeLines(view: AtomBuildView, range: LineRange): LineId[] { 399− const visible = view.lines(range.file);
430+ const visible = buildingLines(view, range.file); 401432 !Number.isInteger(range.start) || 402433 !Number.isInteger(range.end) || @@ -465,7 +496,7 @@
465496 throw new EngineError("bad-edit", "a text edit needs old and new strings"); 467498 const file = edit.file; 468− const visible = view.lines(file);
499+ const visible = buildingLines(view, file); 469500 const oldText = normalizeText(edit.old); 470501 const newText = normalizeText(edit.new); 471502 if (oldText === "") { @@ -477,7 +508,8 @@
478509 return { file, start: 0, end: 0, lines: splitLines(newText), mode, order }; 480− const text = joinLines(visible.map((l) => l.text));
511+ const texts = visible.map((line) => line.text); 512+ const text = joinLines(texts); 481513 const at = text.indexOf(oldText); 482514 if (at < 0) throw new EngineError("no-match", `old text not found in ${file}`); 483515 if (text.indexOf(oldText, at + 1) >= 0) { @@ -488,9 +520,9 @@
489521 const starts: number[] = []; 491− for (const line of visible) {
523+ for (const text of texts) { 493− pos += line.text.length + 1;
525+ pos += text.length + 1; 495527 const lineAt = (offset: number): number => { @@ -506,12 +538,12 @@
506538 const startLine = lineAt(at); 507539 let endLine = lineAt(end - 1); 508540 const lineStart = starts[startLine]!; 509− const lineEnd = starts[endLine]! + visible[endLine]!.text.length + 1;
541+ const lineEnd = starts[endLine]! + texts[endLine]!.length + 1; 510542 let replacement = text.slice(lineStart, at) + newText + text.slice(end, lineEnd); 511543 if (replacement !== "" && !replacement.endsWith("\n")) { 512544 if (endLine + 1 < visible.length) { 514− replacement += `${visible[endLine]!.text}\n`;
546+ replacement += `${texts[endLine]}\n`; 516548 replacement += "\n"; @@ -520,7 +552,7 @@
522554function matchSplice(view: AtomBuildView, edit: SpliceEdit, mode: Mode, order: number): Region { 523− const count = view.lines(edit.file).length;
555+ const count = buildingLines(view, edit.file).length; 525557 !Number.isInteger(edit.start) || 526558 !Number.isInteger(edit.end) || --- a/src/engine/experimental/projection-marker.ts
+++ b/src/engine/experimental/projection-marker.ts
@@ -121,8 +121,7 @@
121121 const state = { ...previous }; 122122 this.ensureFile(state, this.path); 123123 for (const run of atom.inserts) this.ensureFile(state, run.file); 124− let k = 0;
125− for (const run of atom.inserts) for (const _ of run.lines) this.insertLine(state, `${atom.id}.${k++}`);
124+ for (const line of this.graph.eachInsertedLine(atom.id)) this.insertLine(state, line); 126125 let visibility: Array<{ kind: "visibility"; id: number; delta: number }> = []; 127126 for (const line of atom.deletes) { 128127 const marker = this.markers.get(state.locator, this.graph.lineN(line) + 1); @@ -194,13 +193,11 @@
194193 throw Error("included dependent prevents removal"); 195194 return this.storage.transaction(() => { 196195 const state = { ...previous }; 197− let k = 0;
198− for (const run of atom.inserts)
199− for (const text of run.lines) {
200− const marker = this.markers.get(state.locator, this.graph.lineN(`${atom.id}.${k++}`) + 1);
201− if (!marker) throw Error("missing inserted marker");
202− state.sequence = this.sequence.update(state.sequence, { kind: "visibility", id: marker.enter, delta: 1 });
203− }
196+ for (const line of this.graph.eachInsertedLine(atom.id)) { 197+ const marker = this.markers.get(state.locator, this.graph.lineN(line) + 1); 198+ if (!marker) throw Error("missing inserted marker"); 199+ state.sequence = this.sequence.update(state.sequence, { kind: "visibility", id: marker.enter, delta: 1 }); 204201 for (const line of atom.deletes) { 205202 const marker = this.markers.get(state.locator, this.graph.lineN(line) + 1); 206203 if (!marker) throw Error("missing deleted marker"); --- a/src/engine/experimental/projection-reader.ts
+++ b/src/engine/experimental/projection-reader.ts
@@ -110,6 +110,30 @@
110110 for (const id of this.graph.movers()) if (this.set.has(id)) return true; 113+ *#textChunks(n: number): IterableIterator<string> { 115+ const iterator = this.graph.textChunks(n); 118+ const next = iterator.next(); 120+ if (next.done) return; 124+ *lineChunks(path: string): IterableIterator<() => Iterable<string>> { 126+ const iterator = this.#adapter.lineIds(this.#state, path); 129+ const next = iterator.next(); 131+ if (next.done) return; 132+ const n = this.graph.lineN(next.value); 133+ yield () => this.#textChunks(n); 113137 *visibleLines(path: string): IterableIterator<VisibleLine> { 114138 this.#assertLive(); 115139 const graph = this.#adapter.graph; @@ -128,6 +152,34 @@
128152 this.#assertLive(); 129153 return [...this.visibleLines(path)]; 155+ *#buildingLines(path: string): IterableIterator<VisibleLine> { 157+ const graph = this.#adapter.graph; 158+ const iterator = this.#adapter.lineIds(this.#state, path); 161+ const next = iterator.next(); 163+ if (next.done) return; 164+ const id = next.value; 165+ const n = graph.lineN(id); 166+ const assertLive = () => this.#assertLive(); 169+ textChunks: () => this.#textChunks(n), 172+ return graph.textOf(n); 174+ atom: graph.idOfSeq(graph.writerSeqOf(n)), 178+ buildLines(path: string): readonly VisibleLine[] { 180+ return [...this.#buildingLines(path)]; 131183 sequence(path: string): readonly SeqLine[] { 132184 this.#assertLive(); 133185 const adapter = this.#adapter, --- a/src/engine/graph.ts
+++ b/src/engine/graph.ts
@@ -3,6 +3,7 @@
33// atoms and keeps indexes so those questions are cheap. 55import { ChildCounts } from "./child-counts.ts"; 6+import { JsonStringChunks, registerJsonChunkValue } from "./json-value-chunks.ts"; @@ -358,6 +359,8 @@
358359 encoded.textFormat === 1 || encoded.listFormat === 1 || encoded.insertionFormat === 1 362+ if (encoded.insertionFormat === 1 && (!Array.isArray(atom.inserts) || atom.inserts.length !== 0)) 363+ throw Error("invalid stored insertion placeholder"); 362365 encoded.textFormat === 1 363366 ? (start: number, length: number): readonly string[] => { @@ -368,7 +371,7 @@
368371 if (index >= start && index < start + length) { 369372 const reference = raw as unknown as TextReference; 370373 if (typeof raw === "string") result.push(raw); 371− else if (reference && typeof reference.text === "string")
374+ else if (reference && reference.text === JSON.stringify([String(atom.seq), index])) 372375 result.push(atomText.read(reference.text)); 373376 else throw Error("invalid stored atom text reference"); @@ -377,13 +380,51 @@
377380 throw Error("stored atom text range missing"); 383+ const streamed = (target: Atom): Atom => { 384+ registerJsonChunkValue(target, () => { 385+ const line = (raw: unknown, index: number): unknown => { 386+ if (typeof raw === "string") return raw; 387+ const reference = raw as TextReference; 388+ if (!reference || reference.text !== JSON.stringify([String(atom.seq), index])) 389+ throw Error("invalid stored atom text reference"); 390+ return new JsonStringChunks(() => atomText.chunks(reference.text)); 392+ let inserts: readonly unknown[]; 393+ if (encoded.insertionFormat === 1) { 394+ const collection = `atom-inserts:${atom.seq}`; 395+ inserts = readonlyStoredArray(storage, collection, (raw, index) => { 396+ const run = raw as { file: string; parent: string; lines: string }; 397+ const lines = `${collection}:lines:${index}`; 398+ if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string") 399+ throw Error("invalid stored insertion run"); 401+ for (let prior = 0; prior < index; prior++) 402+ start += readonlyStoredArray(storage, `${collection}:lines:${prior}`).length; 406+ lines: readonlyStoredArray(storage, lines, (raw, i) => line(raw, start + i)), 411+ inserts = atom.inserts.map((run) => ({ 414+ lines: run.lines.map((raw) => line(raw, index++)), 417+ return { ...target, inserts }; 380421 const frozen = freezeAtom( 383424 (author) => author, 386− if (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return frozen;
427+ if (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return streamed(frozen); 387428 const result = { ...frozen }; 388429 if (encoded.insertionFormat === 1) { 389430 const collection = `atom-inserts:${atom.seq}`; @@ -396,10 +437,14 @@
396437 return Object.freeze({ 398439 parent: run.parent, 399− lines: readonlyStoredArray<string>(storage, lines, (rawLine) => {
440+ lines: readonlyStoredArray<string>(storage, lines, (rawLine, lineIndex) => { 400441 if (typeof rawLine === "string") return rawLine; 401442 const ref = rawLine as TextReference; 402− if (!ref || typeof ref.text !== "string") throw Error("invalid stored insertion text");
443+ let atomLine = lineIndex; 444+ for (let prior = 0; prior < index; prior++) 445+ atomLine += readonlyStoredArray(storage, `${collection}:lines:${prior}`).length; 446+ if (!ref || ref.text !== JSON.stringify([String(atom.seq), atomLine])) 447+ throw Error("invalid stored insertion text"); 403448 return atomText.read(ref.text); @@ -413,7 +458,7 @@
413458 throw Error("invalid stored atom list reference"); 414459 Object.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true }); 416− return Object.freeze(result);
461+ return streamed(Object.freeze(result)); 419464 const atom = { ...input }; @@ -779,6 +824,25 @@
779824 return this.#text(n); 827+ /** Historical text in bounded chunks, without decoding a whole stored line. */ 828+ *textChunks(n: number): IterableIterator<string> { 829+ if (!this.#storage) { 830+ const text = this.#text(n); 831+ for (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters) 832+ yield text.slice(offset, offset + StoredText.chunkCharacters); 835+ if (!Number.isSafeInteger(n) || n < 0 || n >= this.#lineText!.length) throw Error("invalid line number"); 836+ const value = this.#storage.read("line-text", String(n)); 837+ if (typeof value === "string") { 841+ const reference = value as { format?: number; text?: string } | undefined; 842+ if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference"); 843+ yield* new StoredText(this.#storage, "atom-text:long").chunks(reference.text); 782846 /** The seq of the atom that wrote line n. */ 783847 writerSeqOf(n: number): number { 784848 return this.#lineAtom.at(n); @@ -976,12 +1040,13 @@
9771041 /** The line ids an atom inserted, in k order. */ 9781042 linesOf(id: AtomId): LineId[] { 979− const atom = this.atom(id);
980− const out: LineId[] = [];
981− const seq = atom.seq;
1043+ return [...this.eachInsertedLine(id)]; 1045+ /** Inserted identities without decoding or allocating the atom's text. */ 1046+ *eachInsertedLine(id: AtomId): IterableIterator<LineId> { 1047+ const seq = this.atom(id).seq; 9821048 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!; 983− for (let k = 0; k < count; k++) out.push(lineId(id, k));
984− return out;
1049+ for (let k = 0; k < count; k++) yield lineId(id, k); 9871052 /** Every atom that deletes this line (across the whole graph). */ --- a/src/engine/json-value-chunks.ts
+++ b/src/engine/json-value-chunks.ts
@@ -1,3 +1,20 @@
1+/** Internal values may expose an exact streaming representation without changing public toJSON. */ 2+const streamingValues = new WeakMap<object, () => unknown>(); 3+export function registerJsonChunkValue(value: object, representation: () => unknown): void { 4+ streamingValues.set(value, representation); 7+/** A JSON string backed by bounded, replayable UTF-16 chunks. */ 8+export class JsonStringChunks { 9+ readonly chunks: () => Iterable<string>; 10+ constructor(chunks: () => Iterable<string>) { 11+ this.chunks = chunks; 14+ return [...this.chunks()].join(""); 118/** JSON.stringify-compatible chunks for canonical data, without a whole-value string. 219 * Individual input strings and object key lists still belong to the caller. @@ -16,7 +33,10 @@
1835 const normalize = (value: unknown, key: string): unknown => { 36+ if (value instanceof JsonStringChunks) return value; 1937 if (value !== null && typeof value === "object") { 38+ const streaming = streamingValues.get(value); 39+ if (streaming) return streaming(); 2040 const toJSON = (value as { toJSON?: unknown }).toJSON; 2141 if (typeof toJSON === "function") return toJSON.call(value, key); @@ -24,7 +44,21 @@
2545 const omitted = (value: unknown) => value === undefined || typeof value === "function" || typeof value === "symbol"; 2646 function* encode(value: unknown): IterableIterator<string> { 27− if (typeof value === "string") yield* string(value);
47+ if (value instanceof JsonStringChunks) { 50+ for (const chunk of value.chunks()) { 51+ if (typeof chunk !== "string" || chunk.length > 16384) throw Error("JSON string chunk exceeds bound"); 52+ const text = pending + chunk; 53+ let end = text.length; 54+ const last = text.charCodeAt(end - 1); 55+ if (last >= 0xd800 && last <= 0xdbff) end--; 56+ pending = text.slice(end); 57+ if (end) yield JSON.stringify(text.slice(0, end)).slice(1, -1); 59+ if (pending) yield JSON.stringify(pending).slice(1, -1); 61+ } else if (typeof value === "string") yield* string(value); 2862 else if (value === null || typeof value === "boolean" || typeof value === "number") yield JSON.stringify(value); 2963 else if (typeof value !== "object" || value === null) throw Error("unsupported canonical JSON value"); --- /dev/null
+++ b/src/engine/test/build-lazy-lines.test.ts
@@ -0,0 +1,46 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildAtom } from "../build.ts"; 4+import { Repo } from "./helpers.ts"; 6+test("splice atom construction reads only the replaced region's text", (t) => { 7+ const repo = Repo.init({ "f.txt": `${"unrelated".repeat(10000)}\nold\nlast\n` }); 8+ const view = repo.view(); 9+ const input = { author: "writer", message: "replace", edits: [{ file: "f.txt", start: 1, end: 2, lines: ["new"] }] }; 10+ const expected = buildAtom(view, input); 11+ const original = repo.graph.textChunks.bind(repo.graph); 12+ const reads: number[] = []; 13+ t.mock.method(repo.graph, "textChunks", (n: number) => { 18+ assert.deepEqual(buildAtom(repo.view(), input), expected); 19+ assert.deepEqual(reads, [1]); 21+ buildAtom(repo.view(), { 24+ edits: [{ file: "f.txt", start: 1, end: 1, lines: ["added"] }], 26+ assert.deepEqual(reads, []); 29+test("many splice edits build line handles only once per file", (t) => { 30+ const repo = Repo.init({ "f.txt": Array.from({ length: 2000 }, (_, i) => `line ${i}\n`).join("") }); 31+ const view = repo.view(); 32+ const read = view.buildLines.bind(view); 34+ t.mock.method(view, "buildLines", (path: string) => { 38+ const edits = Array.from({ length: 400 }, (_, i) => ({ 44+ assert.equal(buildAtom(view, { author: "writer", message: "many edits", edits }).deletes.length, 400); 45+ assert.equal(calls, 1); --- /dev/null
+++ b/src/engine/test/graph-line-chunks.test.ts
@@ -0,0 +1,41 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildAtom } from "../build.ts"; 4+import { Graph } from "../graph.ts"; 5+import { StoredText } from "../stored-text.ts"; 6+import { diffChunkedLines } from "../text.ts"; 7+import { View } from "../view.ts"; 8+import { Repo } from "./helpers.ts"; 9+import { SqlState } from "./storage-helper.ts"; 11+test("stored line comparison and atom construction never assemble historical long text", (t) => { 12+ const storage = new SqlState(); 13+ t.after(() => storage.db.close()); 14+ const line = "x".repeat(100000) + "\ud800\udc00"; 15+ const repo = Repo.init({ "f.txt": `${line}\nkeep\n` }); 16+ const graph = new Graph({ storage }); 17+ graph.add(repo.graph.atom("a0")); 18+ t.mock.method(StoredText.prototype, "read", () => { 19+ throw Error("whole stored text forbidden"); 21+ t.mock.method(graph, "textOf", () => { 22+ throw Error("whole line forbidden"); 24+ const chunks = [...graph.textChunks(0)]; 25+ assert.equal(chunks.join(""), line); 26+ assert.ok(chunks.every((chunk) => chunk.length <= StoredText.chunkCharacters)); 27+ const view = new View(graph, ["a0"]); 28+ assert.deepEqual(diffChunkedLines(view.lineChunks("f.txt"), [line, "changed"]), [ 29+ { start: 1, end: 2, lines: ["changed"] }, 35+ edits: [{ file: "f.txt", start: 0, end: 1, lines: ["replacement"] }], 39+ assert.throws(() => [...graph.textChunks(-1)], /invalid line/); 40+ assert.throws(() => [...graph.textChunks(2)], /invalid line/); --- /dev/null
+++ b/src/engine/test/json-string-chunks.test.ts
@@ -0,0 +1,58 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase } from "../build.ts"; 4+import { Graph } from "../graph.ts"; 5+import { JsonStringChunks, jsonValueChunks, registerJsonChunkValue } from "../json-value-chunks.ts"; 6+import { StoredText } from "../stored-text.ts"; 7+import { SqlState } from "./storage-helper.ts"; 9+test("chunk-backed JSON strings preserve escaping and split UTF-16 exactly", () => { 20+ for (const text of values) 21+ for (const size of [1, 2, 17, 16384]) { 22+ const value = new JsonStringChunks(function* () { 24+ for (let offset = 0; offset < text.length; offset += size) { 25+ yield text.slice(offset, offset + size); 29+ assert.equal([...jsonValueChunks({ value })].join(""), JSON.stringify({ value: text })); 30+ assert.equal(JSON.stringify(value), JSON.stringify(text)); 34+test("registered lazy values stream without invoking their whole-value toJSON", () => { 37+ throw Error("whole value forbidden"); 40+ registerJsonChunkValue(value, () => ({ lines: [new JsonStringChunks(() => ["abc", "def"])] })); 41+ assert.equal([...jsonValueChunks(value)].join(""), '{"lines":["abcdef"]}'); 42+ assert.throws(() => [...jsonValueChunks(new JsonStringChunks(() => ["x".repeat(16385)]))], /exceeds bound/); 45+for (const length of [60000, 100000]) 46+ test(`stored atom JSON streams a ${length}-character line without whole reads`, (t) => { 47+ const storage = new SqlState(); 48+ t.after(() => storage.db.close()); 49+ const graph = new Graph({ storage }); 50+ const atom = buildBase({ f: `${"x".repeat(length)}\n` }, { author: "writer", message: "init" }); 52+ const stored = graph.atom("a0"); 53+ const expected = JSON.stringify(stored); 54+ t.mock.method(StoredText.prototype, "read", () => { 55+ throw Error("whole stored text forbidden"); 57+ assert.equal([...jsonValueChunks(stored)].join(""), expected); --- a/src/engine/test/projection-read-scope.test.ts
+++ b/src/engine/test/projection-read-scope.test.ts
@@ -21,6 +21,10 @@
2121 assert.throws(() => scope.guard(new Graph()), /mismatch/); 2222 const reader = new ProjectionReader(adapter, state, scope.guard(graph)); 2323 const membership = reader.set; 24+ const heldLine = reader.buildLines("f.txt")[0]!; 25+ const chunkSource = reader.lineChunks("f.txt").next().value!; 26+ const chunks = chunkSource()[Symbol.iterator](); 27+ assert.equal(chunks.next().value, "one"); 2428 const iterator = reader.visibleLines("f.txt"); 2529 assert.equal(iterator.next().value?.text, "one"); 2630 if (end === "source") source = {}; @@ -46,6 +50,9 @@
4650 t.mock.method(graph, "lineN", refuseAccess); 4751 t.mock.method(graph, "textOf", refuseAccess); 4852 assert.throws(() => reader.text("f.txt"), /expired|stale/); 53+ assert.throws(() => heldLine.text, /expired|stale/); 54+ assert.throws(() => chunks.next(), /expired|stale/); 55+ assert.throws(() => chunkSource()[Symbol.iterator]().next(), /expired|stale/); 4956 assert.throws(() => membership.has("a0"), /expired|stale/); 5057 assert.throws(() => iterator.next(), /expired|stale/); 5158 assert.equal(touched, false); --- /dev/null
+++ b/src/engine/test/streamed-diff.test.ts
@@ -0,0 +1,87 @@
1+import assert from "node:assert/strict"; 2+import { it } from "node:test"; 3+import { diffChunkedLines, diffLineStream, diffLines } from "../text.ts"; 5+it("reads aligned long lines once without accepting hash collisions", () => { 6+ const before = ["x".repeat(100000), "reqicjpk", "y".repeat(80000)]; 7+ const after = [before[0]!, "ejfslztg", before[2]!]; 8+ const reads = [0, 0, 0]; 9+ const sources = before.map( 13+ for (let at = 0; at < line.length; at += 4) yield line.slice(at, at + 4); 16+ assert.deepEqual(diffChunkedLines(sources, after), diffLines(before, after)); 17+ assert.equal(reads[0], 1); 18+ assert.equal(reads[2], 1); 21+it("preserves exact array-diff hunks for single-pass line sources", () => { 23+ const random = (n: number) => { 24+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; 27+ for (let trial = 0; trial < 3000; trial++) { 28+ const before = Array.from({ length: random(90) }, () => `line ${random(19)}`); 29+ const after = Array.from({ length: random(90) }, () => `line ${random(19)}`); 31+ function* oldLines() { 32+ for (const line of before) { 37+ assert.deepEqual(diffLineStream(oldLines(), after), diffLines(before, after)); 40+ before.map((line) => () => [line.slice(0, 3), line.slice(3)]), 43+ diffLines(before, after), 45+ assert.equal(reads, before.length); 49+it("preserves prefix, suffix and expensive-rewrite fallback choices", () => { 50+ for (const count of [0, 1, 300, 900]) { 51+ const before = Array.from({ length: count }, (_, i) => `old ${i}`); 52+ const after = [...before].reverse(); 53+ before.unshift("prefix"); 54+ after.unshift("prefix"); 55+ before.push("suffix"); 56+ after.push("suffix"); 57+ assert.deepEqual(diffLineStream(before.values(), after), diffLines(before, after)); 61+it("compares chunked lines exactly, including a same-length hash collision", () => { 62+ const before = ["reqicjpk", "", "x".repeat(100000), "\ud800\udc00"]; 63+ const after = ["ejfslztg", "", "x".repeat(100000), "\ud800\udc00", "end"]; 64+ for (const size of [1, 7, 16384]) { 65+ const sources = before.map( 68+ for (let offset = 0; offset < line.length; offset += size) yield line.slice(offset, offset + size); 71+ assert.deepEqual(diffChunkedLines(sources, after), diffLines(before, after)); 75+it("reads single-chunk old lines once while matching exactly", () => { 77+ const before = ["keep", "replace", ""]; 78+ const sources = before.map( 85+ assert.deepEqual(diffChunkedLines(sources, ["keep", "new", ""]), diffLines(before, ["keep", "new", ""])); 86+ assert.equal(reads, before.length); --- a/src/engine/text.ts
+++ b/src/engine/text.ts
@@ -43,12 +43,129 @@
4343 * file's length times MAX_COST instead of its length squared. 4545export function diffLines(a: readonly string[], b: readonly string[]): Hunk[] { 46− const matches = commonLines(a, b);
47− const hunks: Hunk[] = [];
46+ return hunksFromMatches(a.length, b, commonLines(a, b)); 49+/** Diff a single-pass old-line source without retaining its strings. */ 50+export function diffLineStream(a: Iterable<string>, b: readonly string[]): Hunk[] { 51+ const ids = new Map<string, number>(); 52+ const next = b.map((line) => { 53+ let id = ids.get(line); 54+ if (id === undefined) { 60+ const previous: number[] = []; 61+ for (const line of a) previous.push(ids.get(line) ?? -1); 62+ return hunksFromMatches(previous.length, b, commonLines(previous, next)); 65+/** Compare replayable old-line chunks without assembling historical strings. */ 66+export function diffChunkedLines(a: Iterable<() => Iterable<string>>, b: readonly string[]): Hunk[] { 67+ const keys = new Map<string, number>(); 68+ const buckets = new Map<string, number[]>(); 69+ const next = b.map((line, index) => { 70+ let id = keys.get(line); 71+ if (id === undefined) { 74+ const key = chunkKey([line]); 75+ const bucket = buckets.get(key) ?? []; 77+ buckets.set(key, bucket); 81+ const previous: number[] = []; 82+ for (const chunks of a) { 83+ const iterator = chunks()[Symbol.iterator](); 85+ const aligned = b[previous.length]; 86+ let alignedOffset = 0; 87+ let alignedEqual = aligned !== undefined; 89+ const first = iterator.next(); 91+ previous.push(keys.get("") ?? -1); 94+ const second = iterator.next(); 96+ previous.push(keys.get(first.value) ?? -1); 101+ function* remaining() { 104+ for (let next = iterator.next(); !next.done; next = iterator.next()) yield next.value; 106+ for (const chunk of remaining()) { 107+ if (alignedEqual && !aligned!.startsWith(chunk, alignedOffset)) alignedEqual = false; 108+ alignedOffset += chunk.length; 114+ iterator.return?.(); 116+ // Same-position unchanged lines are common. Confirm them during hashing, 117+ // retaining exact comparison and the collision-safe fallback for moved lines. 118+ if (alignedEqual && alignedOffset === aligned!.length) { 119+ previous.push(next[previous.length]!); 122+ const candidates = buckets.get(key); 124+ for (const candidate of candidates ?? []) { 127+ for (const chunk of chunks()) { 128+ if (!b[candidate]!.startsWith(chunk, offset)) equal = false; 129+ offset += chunk.length; 131+ if (equal && offset === b[candidate]!.length) { 136+ previous.push(match); 138+ return hunksFromMatches(previous.length, b, commonLines(previous, next)); 141+function chunkKey(chunks: Iterable<string>): string { 142+ let hash = 2166136261; 144+ for (const chunk of chunks) { 145+ length += chunk.length; 146+ for (let i = 0; i < chunk.length; i++) hash = Math.imul(hash ^ chunk.charCodeAt(i), 16777619) >>> 0; 148+ return `${length}:${hash}`; 151+/** The existing diff algorithm over exact line symbols, without retaining text. */ 152+export function diffLineSymbols( 153+ a: readonly number[], 154+ b: readonly number[], 155+): { start: number; end: number; lines: number[] }[] { 156+ return hunksFromMatches(a.length, b, commonLines(a, b)); 159+function hunksFromMatches<T>( 162+ matches: readonly number[], 163+): { start: number; end: number; lines: T[] }[] { 164+ const hunks: { start: number; end: number; lines: T[] }[] = []; 50167 for (let m = 0; m <= matches.length; m += 2) { 51− const mi = m < matches.length ? matches[m]! : a.length;
168+ const mi = m < matches.length ? matches[m]! : length; 52169 const mj = m < matches.length ? matches[m + 1]! : b.length; 53170 if (mi > i || mj > j) hunks.push({ start: i, end: mi, lines: b.slice(j, mj) }); @@ -61,7 +178,7 @@
61178 * The matched pairs of a longest common subsequence of `a` and `b`, flattened 62179 * as [i0, j0, i1, j1, ...] in increasing order. 64−function commonLines(a: readonly string[], b: readonly string[]): number[] {
181+function commonLines<T>(a: readonly T[], b: readonly T[]): number[] { 65182 // Common prefix and suffix match directly. 67184 while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++; @@ -72,8 +189,8 @@
73190 // A line that occurs on only one side can never be matched; leave it out of 74191 // the search (this also makes wholly different texts instant). 75− const ids = new Map<string, number>();
76− const intern = (s: string): number => {
192+ const ids = new Map<T, number>(); 193+ const intern = (s: T): number => { 77194 let id = ids.get(s); 78195 if (id === undefined) { --- a/src/engine/view.ts
+++ b/src/engine/view.ts
@@ -29,6 +29,7 @@
3030/** A visible line of a projected file. */ 3131export interface VisibleLine { 32+ readonly textChunks?: () => Iterable<string>; 3233 readonly id: LineId; 3334 readonly text: string; 3435 readonly atom: AtomId; @@ -542,6 +543,36 @@
546+ *lineChunks(path: string): IterableIterator<() => Iterable<string>> { 547+ for (const n of this.#file(path).vis) yield () => this.graph.textChunks(n); 550+ /** Visible lines without retaining their text in the view cache. */ 551+ *visibleLines(path: string): IterableIterator<VisibleLine> { 552+ const graph = this.graph; 553+ for (const n of this.#file(path).vis) 554+ yield { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) }; 557+ /** Atom-building line handles; text is loaded only when requested. */ 558+ buildLines(path: string): readonly VisibleLine[] { 559+ const graph = this.graph; 560+ const vis = this.#file(path).vis; 561+ const lines: VisibleLine[] = new Array(vis.length); 562+ for (let i = 0; i < vis.length; i++) { 565+ id: graph.lineIdOf(n), 566+ textChunks: () => graph.textChunks(n), 568+ return graph.textOf(n); 570+ atom: graph.idOfSeq(graph.writerSeqOf(n)), 545576 /** Visible lines with their ids. */ 546577 lines(path: string): readonly VisibleLine[] { 547578 if (this.#linesCache?.path === path) return this.#linesCache.lines; --- a/worker/project/add-draft.ts
+++ b/worker/project/add-draft.ts
@@ -50,7 +50,7 @@
5050 const touched = new Set<AtomId>(); 5151 for (const key of claimsOf(atom)) { 5252 const { kind, node } = parseKey(key); 53− if (kind === "line") touched.add(host.graph.line(node)!.atom);
53+ if (kind === "line") touched.add(host.graph.idOfSeq(host.graph.writerSeqOf(host.graph.lineN(node)))); 5454 // Setting an attribute again settles a collision over it. 5555 if (kind === "attr") for (const w of host.graph.writersOf(key)) touched.add(w); --- /dev/null
+++ b/worker/project/definition-code.ts
@@ -0,0 +1,70 @@
1+import type { ReadView, VisibleLine } from "../../src/engine/index.ts"; 2+import { StoredText } from "../../src/engine/stored-text.ts"; 3+import { eachCodeLine } from "./names.ts"; 5+/** Parsed code is temporary derived data, discarded with the scratch transaction. */ 6+export function withDefinitionCode<T>( 8+ visible: readonly VisibleLine[], 9+ operation: (code: readonly string[]) => T, 12+ for (const line of visible) yield line.text; 14+ if (!view.graph.hasOrderedChildren) return operation([...eachCodeLine(source())]); 15+ const iterator = eachCodeLine(source()); 16+ let prefix: string[] = []; 18+ let pending = iterator.next(); 19+ while (!pending.done && size + pending.value.length + 1 <= 65536) { 20+ prefix.push(pending.value); 21+ size += pending.value.length + 1; 22+ pending = iterator.next(); 24+ if (pending.done) return operation(prefix); 25+ return view.graph.withProjectionScratch((storage) => { 26+ const text = new StoredText(storage, "definition-code"); 28+ for (const line of prefix) text.write(String(count++), line); 30+ text.write(String(count++), pending.value!); 31+ for (const line of iterator) text.write(String(count++), line); 32+ const cache = new Map<number, string>(); 34+ const read = (index: number) => { 35+ if (index < 0 || index >= count) return undefined; 36+ const cached = cache.get(index); 37+ if (cached !== undefined) return cached; 38+ const value = text.read(String(index)); 39+ if (value.length <= 65536) { 40+ while (cache.size >= 64 || characters + value.length > 65536) { 41+ const first = cache.keys().next().value!; 42+ characters -= cache.get(first)!.length; 45+ cache.set(index, value); 46+ characters += value.length; 51+ const code = new Proxy([] as string[], { 53+ if (!active) throw Error("definition code scope has ended"); 54+ if (typeof key === "string" && /^(0|[1-9][0-9]*)$/.test(key)) return Number(key) < count; 55+ return Reflect.has(target, key); 57+ get(target, key, receiver) { 58+ if (!active) throw Error("definition code scope has ended"); 59+ if (key === "length") return count; 60+ if (typeof key === "string" && /^(0|[1-9][0-9]*)$/.test(key)) return read(Number(key)); 61+ return Reflect.get(target, key, receiver); 65+ return operation(code); --- a/worker/project/definitions.ts
+++ b/worker/project/definitions.ts
@@ -20,7 +20,8 @@
2020// that defines it (project.ts, #definitionCore). 2222import type { LineId, ReadView } from "../../src/engine/index.ts"; 23−import { codeOfLines, holdsNoCode, isCommonName } from "./names.ts";
23+import { withDefinitionCode } from "./definition-code.ts"; 24+import { holdsNoCode, isCommonName } from "./names.ts"; 2526export interface Definition { 2627 readonly name: string; @@ -121,27 +122,28 @@
121122function definitionsInFile(view: ReadView, file: string, keepCommon = false): Definition[] { 122123 if (holdsNoCode(file) || !view.hasFile(file)) return []; 123124 const out: Definition[] = []; 124− const visible = view.lines(file);
125− const code = codeOfLines(visible.map((l) => l.text));
126− for (let i = 0; i < code.length; i++) {
127− // Only top-level declarations: what another file can import. Locals,
128− // parameters and methods are indented.
129− if (/^\s/.test(code[i]!)) continue;
130− const found = defineAt(code, i);
131− if (!found || (!keepCommon && (found.name.length < 3 || isCommonName(found.name)))) continue;
132− out.push({
133− name: found.name,
134− file,
135− start: i,
136− end: found.end,
137− lines: visible.slice(i, found.end).map((l) => l.id),
138− text: visible
139− .slice(i, found.end)
140− .map((l) => l.text)
141− .join("\n"),
142− });
143− }
144− return out;
125+ const visible = view.buildLines(file); 126+ return withDefinitionCode(view, visible, (code) => { 127+ for (let i = 0; i < code.length; i++) { 128+ // Only top-level declarations: what another file can import. Locals, 129+ // parameters and methods are indented. 130+ if (/^\s/.test(code[i]!)) continue; 131+ const found = defineAt(code, i); 132+ if (!found || (!keepCommon && (found.name.length < 3 || isCommonName(found.name)))) continue; 138+ lines: visible.slice(i, found.end).map((l) => l.id), 140+ .slice(i, found.end) @@ -155,25 +157,26 @@
155157 const count = new Map<string, number>(); 156158 for (const d of all) count.set(d.name, (count.get(d.name) ?? 0) + 1); 157159 if (![...count.values()].some((n) => n > 1)) return out; 158− const visible = view.lines(file);
159− const code = codeOfLines(visible.map((l) => l.text));
160− for (const d of all) {
161− if (count.get(d.name)! < 2) continue;
162− const end = Math.max(d.end, wholeBlockEnd(code, d.start));
163− const whole: Definition = {
164− ...d,
165− end,
166− lines: visible.slice(d.start, end).map((l) => l.id),
167− text: visible
168− .slice(d.start, end)
169− .map((l) => l.text)
170− .join("\n"),
171− };
172− const list = out.get(d.name);
173− if (list) list.push(whole);
174− else out.set(d.name, [whole]);
175− }
176− return out;
160+ const visible = view.buildLines(file); 161+ return withDefinitionCode(view, visible, (code) => { 162+ for (const d of all) { 163+ if (count.get(d.name)! < 2) continue; 164+ const end = Math.max(d.end, wholeBlockEnd(code, d.start)); 165+ const whole: Definition = { 168+ lines: visible.slice(d.start, end).map((l) => l.id), 170+ .slice(d.start, end) 174+ const list = out.get(d.name); 175+ if (list) list.push(whole); 176+ else out.set(d.name, [whole]); --- a/worker/project/express-moves.ts
+++ b/worker/project/express-moves.ts
@@ -1,10 +1,12 @@
1+import { diffLineSymbols } from "../../src/engine/text.ts"; 2+import { recordFileChanges } from "./record-file.ts"; 13// Moves (#28): within one agent's unpublished draft, a line that leaves one place and the same 24// text that arrives somewhere else is the same line. Before a publish, those matches become move 35// atoms so the lines keep their ids. Writes go through ExpressMovesHost; today the host is Project. 57import type { AtomId, AttrSet, EditInput, Graph, LineId, MoveInput, ReadView } from "../../src/engine/index.ts"; 68import { differenceSet, StableOverlaySet } from "../../src/engine/state-source.ts"; 7−import { PLAIN_LINE } from "./collisions.ts";
9+import { MoveLineText } from "./move-line-text.ts"; 810import type { AgentState, Entry, Meta, Mode } from "./project-types.ts"; 1012/** The most moved blocks one publish expresses: the longest ones, when there are more. */ @@ -59,6 +61,7 @@
5961 if (draft.length === 0) return; 6062 const g = host.graph; 6163 const mine = new Set(draft); 64+ const text = new MoveLineText(g); 6265 const after = host.agentView(agent); 6366 const before = host.beforeDraft 6467 ? host.beforeDraft(agent, draft) @@ -71,25 +74,25 @@
7174 readonly file: string; 7275 readonly start: number; 7376 readonly ids: LineId[]; 74− readonly texts: string[];
77+ readonly texts: number[]; 7679 const gone: Block[] = []; 7780 const written: Block[] = []; 7881 for (const file of [...touched].toSorted()) { 7982 let cur: Block | undefined; 80− before.lines(file).forEach((l, i) => {
83+ before.buildLines(file).forEach((l, i) => { 8184 if (g.deletersOf(l.id).some((d) => mine.has(d))) { 8285 if (!cur) gone.push((cur = { file, start: i, ids: [], texts: [] })); 84− cur.texts.push(l.text);
87+ cur.texts.push(text.intern(l.id)); 8588 } else cur = undefined; 88− after.lines(file).forEach((l, i) => {
91+ after.buildLines(file).forEach((l, i) => { 8992 if (mine.has(l.atom)) { 9093 if (!cur) written.push((cur = { file, start: i, ids: [], texts: [] })); 92− cur.texts.push(l.text);
95+ cur.texts.push(text.intern(l.id)); 9396 } else cur = undefined; @@ -108,7 +111,7 @@
108111 // Where each deleted text starts a candidate, in block and line order (abso issue 158): a stretch 109112 // can only start where the texts are equal, so each written line looks only there, not at 110113 // every deleted line. A text deleted more than MATCH_STARTS times keeps its first ones. 111− const starts = new Map<string, { block: Block; q: number }[]>();
114+ const starts = new Map<number, { block: Block; q: number }[]>(); 112115 for (const block of gone) 113116 block.texts.forEach((t, q) => { 114117 const list = starts.get(t); @@ -131,7 +134,7 @@
132135 if (len > 0 && (!best || len > best.len)) best = { block, q, len }; 134− if (best?.block.texts.slice(best.q, best.q + best.len).some((t) => !PLAIN_LINE.test(t))) {
137+ if (best?.block.texts.slice(best.q, best.q + best.len).some((t) => !text.plain[t])) { 135138 const ids = best.block.ids.slice(best.q, best.q + best.len); 136139 for (const id of ids) used.add(id); 137140 matches.push({ from: best.block.file, ids, to: run.file, at: run.start + p }); @@ -145,7 +148,7 @@
145148 // passed Workers' CPU limit. So the longest blocks move first, up to MOVE_LIMIT of them and 146149 // MOVE_BUDGET lines laid out in all; the rest are a delete and a fresh write, as an unmatched block 148− const length = (path: string) => (after.hasFile(path) ? after.lines(path).length : 0);
151+ const length = (path: string) => (after.hasFile(path) ? after.buildLines(path).length : 0); 149152 const cost = (m: Match) => length(m.from) + (m.to === m.from ? 0 : length(m.to)); 150153 const keep = new Set<Match>(); @@ -185,7 +188,7 @@
185188 const start = view.lineNumber(m.from, m.ids[0]!); 186189 if (start < 0 || m.ids.some((id, k) => view.lineNumber(m.from, id) !== start + k)) continue; 187190 // Land after the nearest line above it in the final text that is already there. 188− const finalLines = host.agentView(finalAgent).lines(m.to);
191+ const finalLines = host.agentView(finalAgent).buildLines(m.to); 190193 for (let i = m.at - 1; i >= 0; i--) { 191194 const n = view.lineNumber(m.to, finalLines[i]!.id); @@ -207,18 +210,28 @@
207210 for (const path of [...involved].toSorted()) { 208211 const finalView = host.agentView(finalAgent); 209212 const was = finalView.attrs(path); 210− host.recordFile(
213+ const view = host.agentView(agent); 214+ const target = finalView.buildLines(path); 215+ const symbols = new MoveLineText(g); 216+ const previous = view.buildLines(path).map((line) => symbols.intern(line.id)); 217+ const next = target.map((line) => symbols.intern(line.id)); 218+ const edits = diffLineSymbols(previous, next).map((hunk) => ({ 222+ lines: hunk.lines.map((symbol) => symbols.text(symbol)), 212− host.agentView(agent),
214− finalView.hasFile(path) ? finalView.text(path) : null,
229+ !finalView.hasFile(path) ? "missing" : target.length === 0 ? "empty" : "present", 218− {
219− exec: was.exec,
220− link: was.link,
221− },
234+ { exec: was.exec, link: was.link }, --- a/worker/project/markers.ts
+++ b/worker/project/markers.ts
@@ -352,7 +352,7 @@
352352 const out: Collision[] = []; 353353 for (const file of [...host.draftFiles(agent)].toSorted()) { 354354 if (!view.hasFile(file)) continue; 355− const lines = view.lines(file);
355+ const lines = view.buildLines(file); 356356 const added = lines.map((l, i) => (mine.has(l.atom) && isMarkerLine(l.text) ? i : -1)).filter((i) => i >= 0); 357357 if (added.length === 0) continue; 358358 const blocks = blocksIn(lines.map((l) => l.text)); --- /dev/null
+++ b/worker/project/move-line-text.ts
@@ -0,0 +1,74 @@
1+import type { Graph } from "../../src/engine/graph.ts"; 2+import { PLAIN_LINE } from "./collisions.ts"; 4+/** Exact text symbols backed by graph line IDs, never retained whole strings. */ 5+export class MoveLineText { 6+ readonly graph: Graph; 7+ readonly buckets = new Map<string, { symbol: number; line: number }[]>(); 8+ readonly plain: boolean[] = []; 9+ readonly lines: number[] = []; 10+ readonly symbolsByLine = new Map<number, number>(); 11+ constructor(graph: Graph) { 14+ text(symbol: number): string { 15+ const line = this.lines[symbol]; 16+ if (line === undefined) throw Error("unknown move text symbol"); 17+ return this.graph.textOf(line); 20+ intern(id: string): number { 21+ const line = this.graph.lineN(id); 22+ const known = this.symbolsByLine.get(line); 23+ if (known !== undefined) return known; 24+ let hash = 2166136261, 27+ for (const chunk of this.graph.textChunks(line)) { 28+ length += chunk.length; 29+ if (!PLAIN_LINE.test(chunk)) plain = false; 30+ for (let i = 0; i < chunk.length; i++) hash = Math.imul(hash ^ chunk.charCodeAt(i), 16777619) >>> 0; 32+ const key = `${length}:${hash}`; 33+ const bucket = this.buckets.get(key) ?? []; 34+ for (const candidate of bucket) 35+ if (sameChunks(this.graph.textChunks(line), this.graph.textChunks(candidate.line))) { 36+ this.symbolsByLine.set(line, candidate.symbol); 37+ return candidate.symbol; 39+ const symbol = this.plain.length; 40+ this.plain.push(plain); 41+ this.lines.push(line); 42+ bucket.push({ symbol, line }); 43+ this.buckets.set(key, bucket); 44+ this.symbolsByLine.set(line, symbol); 49+function sameChunks(a: IterableIterator<string>, b: IterableIterator<string>): boolean { 56+ while (!x.done && i === x.value.length) { 60+ while (!y.done && j === y.value.length) { 64+ if (x.done || y.done) return x.done === y.done; 65+ const length = Math.min(x.value.length - i, y.value.length - j); 66+ if (x.value.slice(i, i + length) !== y.value.slice(j, j + length)) return false; --- a/worker/project/names.ts
+++ b/worker/project/names.ts
@@ -194,9 +194,13 @@
194194 * without its string literals and comments. A string or comment opened on 195195 * one line continues on the next. 197−export function codeOfLines(lines: readonly string[]): string[] {
197+export function codeOfLines(lines: Iterable<string>): string[] { 198+ return [...eachCodeLine(lines)]; 201+export function* eachCodeLine(lines: Iterable<string>): IterableIterator<string> { 198202 const st: ScanState = { stack: [{ kind: "code", depth: 0 }], block: false, triple: undefined }; 199− return lines.map((line) => scanLine(line, st));
203+ for (const line of lines) yield scanLine(line, st); 202206/** Names in some code (from codeOfLines): identifiers of three or more characters that aren't common names. */ --- a/worker/project/record-file.ts
+++ b/worker/project/record-file.ts
@@ -4,7 +4,7 @@
7− diffLines,
@@ -44,39 +44,79 @@
4545 hunks?: readonly Hunk[], 47− const was = view.attrs(path);
48− const exists = view.hasFile(path);
4947 const lines = text === undefined ? undefined : text === null ? "" : text; 5048 const edits: SpliceEdit[] = 51− lines === undefined || view.text(path) === lines
49+ lines === undefined || (hunks !== undefined && sameProjectedText(view, path, lines)) 53− : (
54− hunks ??
55− diffLines(
56− view.lines(path).map((l) => l.text),
57− splitLines(lines),
58− )
59− ).map((h) => ({ file: path, start: h.start, end: h.end, lines: h.lines }));
51+ : (hunks ?? diffChunkedLines(view.lineChunks(path), splitLines(lines))).map((h) => ({ 57+ return recordFileChanges( 62+ text === undefined ? "unchanged" : text === null ? "missing" : text === "" ? "empty" : "present", 72+/** Apply a precomputed exact text diff and the normal file attribute rules. */ 73+export function recordFileChanges( 74+ host: RecordFileHost, 78+ state: "unchanged" | "missing" | "empty" | "present", 79+ edits: readonly SpliceEdit[], 86+ const was = view.attrs(path); 87+ const exists = view.hasFile(path); 6089 const attrs: AttrSet[] = []; 6190 const set = (name: AttrName, now: string | null, value: string | null): void => { 6291 if (now !== value) attrs.push({ file: path, name, value }); 64− const link = mode.link !== undefined ? mode.link : text === null ? null : was.link;
65− if (text === null) {
93+ const link = mode.link !== undefined ? mode.link : state === "missing" ? null : was.link; 94+ if (state === "missing") { 6695 // Gone: no lines, and nothing keeps it. 6796 set("exists", was.exists ? "1" : null, null); 6897 set("exec", was.exec ? "1" : null, null); 69− } else if (text === "" && link === null && blob === undefined) {
98+ } else if (state === "empty" && link === null && blob === undefined) { 7099 // An empty file is kept by its exists attribute. 71100 set("exists", was.exists ? "1" : null, "1"); 73102 // A binary file is its blob and no lines; text, or no file, clears the blob. 74103 if (blob !== undefined) set("blob", was.blob, blob); 75− else if (text !== undefined) set("blob", was.blob, null);
76− if (mode.exec !== undefined && text !== null) set("exec", was.exec ? "1" : null, mode.exec ? "1" : null);
104+ else if (state !== "unchanged") set("blob", was.blob, null); 105+ if (mode.exec !== undefined && state !== "missing") set("exec", was.exec ? "1" : null, mode.exec ? "1" : null); 77106 set("link", was.link, link); 78107 if (edits.length === 0 && attrs.length === 0) return false; 79− if (!exists && text === null && attrs.length === 0) return false;
108+ if (!exists && state === "missing" && attrs.length === 0) return false; 80109 host.addDraft(agent, view, { edits, attrs }, time, meta, entries); 113+/** Compare canonical projected text without joining or caching old lines. */ 114+function sameProjectedText(view: ReadView, path: string, text: string): boolean { 116+ for (const line of view.visibleLines(path)) { 117+ if (!text.startsWith(line.text, offset)) return false; 118+ offset += line.text.length; 119+ if (text[offset++] !== "\n") return false; 121+ return offset === text.length; --- /dev/null
+++ b/worker/project/test/definition-code.test.ts
@@ -0,0 +1,56 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildBase, Graph, View } from "../../../src/engine/index.ts"; 4+import { SqlState } from "../../../src/engine/test/storage-helper.ts"; 5+import { withDefinitionCode } from "../definition-code.ts"; 6+import { definedTwice, definitionsIn } from "../definitions.ts"; 7+import { codeOfLines } from "../names.ts"; 9+test("small parsed code stays in memory without scratch writes", (t) => { 10+ const storage = new SqlState(); 11+ t.after(() => storage.db.close()); 12+ const graph = new Graph({ storage }); 13+ graph.add(buildBase({ "f.ts": "export const answer = 42;\n" }, { author: "writer", message: "init" })); 14+ const view = new View(graph, ["a0"]); 15+ const writes = storage.writes; 16+ withDefinitionCode(view, view.buildLines("f.ts"), (code) => { 17+ assert.deepEqual(code, codeOfLines(["export const answer = 42;"])); 19+ assert.equal(storage.writes, writes); 22+test("disk definition code preserves random reads and always rolls scratch back", (t) => { 23+ const storage = new SqlState(); 24+ t.after(() => storage.db.close()); 27+ "end */ export function parseOne(", 30+ ...Array.from({ length: 4000 }, (_, i) => `const value${i} = ${i}; // trailing`), 32+ const atom = buildBase({ "f.ts": `${lines.join("\n")}\n` }, { author: "writer", message: "init" }); 33+ const memory = new Graph(); 35+ const graph = new Graph({ storage }); 37+ const view = new View(graph, ["a0"]); 38+ const expected = codeOfLines(lines); 39+ const rows = () => storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all(); 40+ const before = rows(); 41+ let escaped: readonly string[] = []; 42+ withDefinitionCode(view, view.buildLines("f.ts"), (code) => { 44+ assert.deepEqual(code.slice(0, 4), expected.slice(0, 4)); 45+ for (let i = code.length - 1; i >= 0; i--) assert.equal(code[i], expected[i]); 46+ for (let i = 0; i < code.length; i++) assert.equal(code[i], expected[i]); 48+ assert.throws(() => escaped[0], /scope has ended/); 49+ assert.deepEqual(rows(), before); 50+ assert.deepEqual(definitionsIn(view), definitionsIn(new View(memory, ["a0"]))); 51+ assert.deepEqual(definedTwice(view, "f.ts"), definedTwice(new View(memory, ["a0"]), "f.ts")); 52+ assert.deepEqual(rows(), before); 53+ storage.failWrite = storage.writes + 2; 54+ assert.throws(() => withDefinitionCode(view, view.buildLines("f.ts"), () => []), /injected storage failure/); 55+ assert.deepEqual(rows(), before); --- a/worker/project/test/definitions.test.ts
+++ b/worker/project/test/definitions.test.ts
@@ -68,3 +68,13 @@
6868 assert.deepEqual(defs({ "fixtures/a.json": codeLike, "data/b.csv": codeLike, "c.lock": codeLike }), {}); 6969 assert.deepEqual(Object.keys(defs({ "src/a.ts": codeLike })), ["parsePattern"]); 72+test("definition scanning does not retain the original file line array", (t) => { 73+ const graph = new Graph(); 74+ graph.add(buildBase({ "a.ts": "export function parseThing() { return 1; }\n" }, { author: "t", message: "t" })); 75+ const view = new View(graph, ["a0"]); 76+ t.mock.method(view, "lines", () => { 77+ throw Error("original file line array forbidden"); 79+ assert.deepEqual([...definitionsIn(view).keys()], ["parseThing"]); --- /dev/null
+++ b/worker/project/test/move-line-text.test.ts
@@ -0,0 +1,29 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { Graph } from "../../../src/engine/graph.ts"; 4+import { StoredText } from "../../../src/engine/stored-text.ts"; 5+import { Repo } from "../../../src/engine/test/helpers.ts"; 6+import { SqlState } from "../../../src/engine/test/storage-helper.ts"; 7+import { MoveLineText } from "../move-line-text.ts"; 9+test("move text symbols compare stored chunks exactly and distinguish hash collisions", (t) => { 10+ const storage = new SqlState(); 11+ t.after(() => storage.db.close()); 12+ const long = "x".repeat(100000); 13+ const repo = Repo.init({ f: `reqicjpk\nejfslztg\n${long}\n${long}\n {};\n` }); 14+ const graph = new Graph({ storage }); 15+ graph.add(repo.graph.atom("a0")); 16+ t.mock.method(StoredText.prototype, "read", () => { 17+ throw Error("whole text forbidden"); 19+ const texts = new MoveLineText(graph); 20+ assert.notEqual(texts.intern("a0.0"), texts.intern("a0.1")); 21+ assert.equal(texts.intern("a0.2"), texts.intern("a0.3")); 22+ assert.equal(texts.plain[texts.intern("a0.2")], false); 23+ assert.equal(texts.plain[texts.intern("a0.4")], true); 24+ const known = texts.intern("a0.2"); 25+ t.mock.method(graph, "textChunks", () => { 26+ throw Error("known identity must not reread text"); 28+ assert.equal(texts.intern("a0.2"), known); --- /dev/null
+++ b/worker/project/test/move-reconstruction.test.ts
@@ -0,0 +1,18 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { View } from "../../../src/engine/view.ts"; 4+import { MemoryStore, Project } from "../project.ts"; 6+test("move reconstruction does not join the intended whole file", (t) => { 7+ const project = new Project(new MemoryStore()); 8+ project.init({ "a.txt": "header\nmove this line\nfooter\n", "b.txt": "destination\n" }, 0); 9+ project.sync("writer"); 10+ assert.equal(project.edit("writer", { file: "a.txt", old: "move this line\n", new: "" }, 1).ok, true); 11+ assert.equal(project.edit("writer", { file: "b.txt", content: "destination\nmove this line\n" }, 1).ok, true); 12+ const whole = t.mock.method(View.prototype, "text", () => { 13+ throw Error("whole file join forbidden"); 15+ assert.equal(project.publish("writer", "move", 2).ok, true); 16+ whole.mock.restore(); 17+ assert.deepEqual(project.files(), { "a.txt": "header\nfooter\n", "b.txt": "destination\nmove this line\n" }); --- /dev/null
+++ b/worker/project/test/record-stream.test.ts
@@ -0,0 +1,44 @@
1+import assert from "node:assert/strict"; 2+import { it } from "node:test"; 3+import { Repo } from "../../../src/engine/test/helpers.ts"; 4+import type { AgentState } from "../project-types.ts"; 5+import { type RecordFileHost, recordFile } from "../record-file.ts"; 7+it("records replacements without materializing old file text or line arrays", () => { 8+ const view = Repo.init({ "large.txt": `${"x".repeat(100000)}\nkeep\n` }).view(); 10+ throw Error("whole old text is forbidden"); 13+ throw Error("old line array is forbidden"); 15+ const calls: Parameters<RecordFileHost["addDraft"]>[2][] = []; 16+ const host: RecordFileHost = { 17+ addDraft(_agent, _view, input) { 21+ const agent: AgentState = { 33+ assert.equal(recordFile(host, agent, view, "large.txt", "changed\nkeep\n", 1, {}, []), true); 34+ assert.deepEqual(calls[0]!.edits, [{ file: "large.txt", start: 0, end: 1, lines: ["changed"] }]); 35+ const unchanged = `${"x".repeat(100000)}\nkeep\n`; 36+ assert.equal(recordFile(host, agent, view, "large.txt", unchanged, 1, {}, []), false); 38+ recordFile(host, agent, view, "large.txt", unchanged, 1, {}, [], {}, undefined, [ 39+ { start: 0, end: 1, lines: ["ignored"] }, 43+ assert.equal(calls.length, 1);