A desktop coding agent with free access to frontier models.
TypeScript
feat(collector): turn.diff trace event pairing each turn with what it changed
ogsamrat133f07807dd9
diff --git a/apps/server/src/turn-diff.test.ts b/apps/server/src/turn-diff.test.tsnew file mode 100644index 00000000..d047918a--- /dev/null+++ b/apps/server/src/turn-diff.test.ts@@ -0,0 +1,227 @@+import { afterEach, describe, expect, test } from "bun:test";+import { createHash } from "node:crypto";+import { mkdtemp, readdir, rm, unlink, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { zstdDecompressSync } from "node:zlib";++import { MAX_TURN_DIFF_FILE_BYTES, TurnDiffBuilder, unifiedDiff, type TurnDiffEvent } from "./turn-diff.js";+import { WorkspaceCollector } from "./workspace-collector.js";++type Envelope = { snapshot_type: string; trace?: Array<{ type: string; data?: unknown }> };++const roots: string[] = [];+/** A snapshot cap that leaves no room for content once the envelope's own margin is set aside. */+const NO_CONTENT = 2 * 1024 * 1024;++afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});++async function tempDir(prefix: string): Promise<string> {+ const dir = await mkdtemp(join(tmpdir(), prefix));+ roots.push(dir);+ return dir;+}++function sha256(text: string): string {+ return createHash("sha256").update(text).digest("hex");+}++/** Runs one turn (prompt, `edit`, turn end) on a collector over `root` and returns the turn's "turn.diff" event. */+async function turnDiff(root: string, edit: () => Promise<void>, options: { stateDir?: string; snapshotMaxBytes?: number } = {}): Promise<TurnDiffEvent> {+ const uploads: Envelope[] = [];+ const collector = new WorkspaceCollector({+ upload: async (_sessionId, compressed) => {+ uploads.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Envelope);+ return Response.json({ ok: true }, { status: 201 });+ },+ changeDebounceMs: 60_000,+ fallbackScanMs: 60_000,+ ...options,+ });+ const sessionId = `session-turn-diff-${Math.random().toString(36).slice(2, 10)}`;+ collector.startSession(sessionId, "workspace-turn-diff", root);+ collector.captureSnapshot(sessionId, "prompt");+ await collector.idle(sessionId);+ await edit();+ collector.captureSnapshot(sessionId, "turn_completed");+ collector.flushTrace(sessionId, { messages: [] });+ await collector.idle(sessionId);+ await collector.stop();+ const events = uploads.filter((item) => item.snapshot_type === "trace").flatMap((item) => item.trace ?? []).filter((event) => event.type === "turn.diff");+ expect(events).toHaveLength(1);+ return events[0]!.data as TurnDiffEvent;+}++describe("unified diff", () => {+ test("writes hunks with context, counts and the missing-newline marker", () => {+ const before = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"].join("\n") + "\n";+ const after = ["one", "two", "THREE", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven"].join("\n");+ const result = unifiedDiff("notes.txt", before, after);+ expect(result).toMatchObject({ additions: 2, deletions: 1, truncated: false });+ expect(result.diff).toBe([+ "--- a/notes.txt",+ "+++ b/notes.txt",+ "@@ -1,6 +1,6 @@",+ " one",+ " two",+ "-three",+ "+THREE",+ " four",+ " five",+ " six",+ "@@ -8,3 +8,4 @@",+ " eight",+ " nine",+ " ten",+ "+eleven",+ "\\ No newline at end of file",+ "",+ ].join("\n"));+ expect(unifiedDiff("new.txt", null, "a\nb\n").diff).toBe("--- /dev/null\n+++ b/new.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n");+ expect(unifiedDiff("old.txt", "a\n", null).diff).toBe("--- a/old.txt\n+++ /dev/null\n@@ -1 +0,0 @@\n-a\n");+ });++ test("finds the minimal edit inside a long file and stays close to it past the exact bound", () => {+ const lines = Array.from({ length: 5_000 }, (_, index) => `line ${index}`);+ const edited = lines.map((line, index) => (index % 1_000 === 500 ? `${line} edited` : line));+ const small = unifiedDiff("long.txt", `${lines.join("\n")}\n`, `${edited.join("\n")}\n`);+ expect(small).toMatchObject({ additions: 5, deletions: 5, truncated: false });+ const rewritten = lines.map((line, index) => (index % 2 === 0 ? `${line} edited` : line));+ const large = unifiedDiff("long.txt", `${lines.join("\n")}\n`, `${rewritten.join("\n")}\n`);+ // 2,500 edits are past the exact search; the greedy pass still pairs each edited line with its original.+ expect(large).toMatchObject({ additions: 2_500, deletions: 2_500 });+ expect(large.diff).toContain("-line 0\n+line 0 edited\n line 1\n-line 2\n+line 2 edited\n");+ });+});++describe("turn.diff events", () => {+ test("pairs a turn with its added, modified and deleted files", async () => {+ const root = await tempDir("omnirush-turn-diff-");+ await writeFile(join(root, "keep.txt"), "unchanged\n");+ await writeFile(join(root, "app.ts"), "export const answer = 41;\nexport const name = \"omnirush\";\n");+ await writeFile(join(root, "old.md"), "retired\n");+ const event = await turnDiff(root, async () => {+ await writeFile(join(root, "app.ts"), "export const answer = 42;\nexport const name = \"omnirush\";\n");+ await writeFile(join(root, "new.md"), "fresh\nnotes\n");+ await unlink(join(root, "old.md"));+ });+ expect(event).toMatchObject({ schema_version: 1, file_count: 3, omitted_file_count: 0, truncated: false });+ expect(event.files).toEqual([+ {+ path: "app.ts",+ status: "modified",+ before_sha256: sha256("export const answer = 41;\nexport const name = \"omnirush\";\n"),+ after_sha256: sha256("export const answer = 42;\nexport const name = \"omnirush\";\n"),+ additions: 1,+ deletions: 1,+ diff: "--- a/app.ts\n+++ b/app.ts\n@@ -1,2 +1,2 @@\n-export const answer = 41;\n+export const answer = 42;\n export const name = \"omnirush\";\n",+ truncated: false,+ },+ {+ path: "new.md",+ status: "added",+ before_sha256: null,+ after_sha256: sha256("fresh\nnotes\n"),+ additions: 2,+ deletions: 0,+ diff: "--- /dev/null\n+++ b/new.md\n@@ -0,0 +1,2 @@\n+fresh\n+notes\n",+ truncated: false,+ },+ {+ path: "old.md",+ status: "deleted",+ before_sha256: sha256("retired\n"),+ after_sha256: null,+ additions: 0,+ deletions: 1,+ diff: "--- a/old.md\n+++ /dev/null\n@@ -1 +0,0 @@\n-retired\n",+ truncated: false,+ },+ ]);+ });++ test("marks a binary file the turn wrote as skipped, without content", async () => {+ const root = await tempDir("omnirush-turn-diff-binary-");+ await writeFile(join(root, "readme.txt"), "hello\n");+ const event = await turnDiff(root, async () => {+ await writeFile(join(root, "chart.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0, 0, 0, 13, 0xff]));+ });+ expect(event.files).toEqual([+ { path: "chart.png", status: "skipped", before_sha256: null, after_sha256: null, additions: null, deletions: null, diff: null, truncated: false },+ ]);+ });++ test("keeps a redacted secret redacted on both sides of the diff", async () => {+ const root = await tempDir("omnirush-turn-diff-secret-");+ await writeFile(join(root, "config.txt"), "OPENAI_API_KEY=sk-1234567890abcdefghijklmnop\nmode=dev\n");+ const event = await turnDiff(root, async () => {+ await writeFile(join(root, "config.txt"), "OPENAI_API_KEY=sk-abcdefghijklmnop1234567890\nmode=prod\n");+ });+ const serialized = JSON.stringify(event);+ expect(serialized).not.toContain("sk-1234567890abcdefghijklmnop");+ expect(serialized).not.toContain("sk-abcdefghijklmnop1234567890");+ const [file] = event.files;+ expect(file).toMatchObject({ path: "config.txt", status: "modified", additions: 1, deletions: 1 });+ // The key changed but both sides scrub to the same line: only the real edit shows.+ expect(file!.diff).toContain(" OPENAI_API_KEY=[REDACTED]\n-mode=dev\n+mode=prod\n");+ });++ test("marks a file whose base is no longer held as no_base and an unseen one as added", async () => {+ const root = await tempDir("omnirush-turn-diff-no-base-");+ await writeFile(join(root, "big.txt"), "before\n");+ // A snapshot with no room for content sends no text, so nothing is stored as a base.+ const event = await turnDiff(root, async () => {+ await writeFile(join(root, "big.txt"), "after\n");+ await writeFile(join(root, "added.txt"), "brand new\n");+ }, { snapshotMaxBytes: NO_CONTENT });+ expect(event.files).toEqual([+ { path: "added.txt", status: "added", before_sha256: null, after_sha256: sha256("brand new\n"), additions: 1, deletions: 0, diff: "--- /dev/null\n+++ b/added.txt\n@@ -0,0 +1 @@\n+brand new\n", truncated: false },+ { path: "big.txt", status: "no_base", before_sha256: sha256("before\n"), after_sha256: sha256("after\n"), additions: null, deletions: null, diff: null, truncated: false },+ ]);+ });++ test("keeps bases in the state dir across a restart", async () => {+ const root = await tempDir("omnirush-turn-diff-restart-");+ const stateDir = await tempDir("omnirush-turn-diff-state-");+ await writeFile(join(root, "app.txt"), "first\n");+ await turnDiff(root, async () => undefined, { stateDir });+ expect((await readdir(join(stateDir, "omnirush-collector-bases"))).sort()).toEqual([sha256("first\n"), "index.json"].sort());+ // The next process sends no content at all: the base can only come from disk.+ const event = await turnDiff(root, async () => {+ await writeFile(join(root, "app.txt"), "second\n");+ }, { stateDir, snapshotMaxBytes: NO_CONTENT });+ expect(event.files).toMatchObject([{ path: "app.txt", status: "modified", diff: "--- a/app.txt\n+++ b/app.txt\n@@ -1 +1 @@\n-first\n+second\n" }]);++ // A sign-out deletes the bases with the spool.+ const signedOut = new WorkspaceCollector({ upload: async () => Response.json({ ok: true }, { status: 201 }), stateDir });+ await signedOut.clearSpool();+ await signedOut.stop();+ expect(await readdir(stateDir)).not.toContain("omnirush-collector-bases");+ });++ test("cuts a file diff at 256 KiB and the event at its cap, marked truncated", async () => {+ const root = await tempDir("omnirush-turn-diff-cap-");+ await writeFile(join(root, "huge.txt"), "");+ const event = await turnDiff(root, async () => {+ await writeFile(join(root, "huge.txt"), Array.from({ length: 40_000 }, (_, index) => `generated line ${index}`).join("\n"));+ });+ const [file] = event.files;+ expect(file).toMatchObject({ path: "huge.txt", status: "modified", additions: 40_000, deletions: 0, truncated: true });+ expect(Buffer.byteLength(JSON.stringify(file!.diff))).toBeLessThanOrEqual(MAX_TURN_DIFF_FILE_BYTES + 2);+ expect(file!.diff!.endsWith("\n")).toBe(true);+ expect(event.truncated).toBe(true);++ const builder = new TurnDiffBuilder(4 * 1024, 1024);+ for (let index = 0; index < 10; index += 1) {+ builder.add({ path: `f${index}.txt`, status: "added", before_sha256: null, after_sha256: null, before: null, after: "line\n".repeat(1_000) });+ }+ const capped = builder.finish();+ expect(capped).toMatchObject({ file_count: 10, omitted_file_count: 7 });+ expect(capped.files).toHaveLength(3);+ expect(capped.files.every((entry) => entry.truncated)).toBe(true);+ expect(Buffer.byteLength(JSON.stringify(capped.files))).toBeLessThanOrEqual(4 * 1024);+ expect(capped.truncated).toBe(true);+ });+});diff --git a/apps/server/src/turn-diff.ts b/apps/server/src/turn-diff.tsnew file mode 100644index 00000000..a4f40282--- /dev/null+++ b/apps/server/src/turn-diff.ts@@ -0,0 +1,573 @@+/**+ * The "turn.diff" trace event: at the end of each turn, a unified diff per+ * workspace file the turn changed, of the scrubbed text the collector last+ * sent for it before the turn against the scrubbed text it sent after, so the+ * trace pairs the turn with exactly what it changed. The texts come from+ * TurnBaseStore, a bounded content-addressed store of the scrubbed texts the+ * collector sent (keyed by their redacted sha256, the digest the manifest+ * names), kept under the collector state dir so bases survive a restart.+ * Everything here runs on the capture worker (see capture-host.ts).+ */+import { createHash } from "node:crypto";+import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";++/** A file diff is cut at this many bytes (as JSON-encoded in the event). */+export const MAX_TURN_DIFF_FILE_BYTES = 256 * 1024;+/** One "turn.diff" event carries at most this many bytes of file entries. */+export const MAX_TURN_DIFF_EVENT_BYTES = 2 * 1024 * 1024;+/** Budget of the base store, least recently used out first. */+export const TURN_BASE_STORE_BYTES = 64 * 1024 * 1024;+/** Texts over the collector's per-file cap are never stored. */+const MAX_BASE_TEXT_BYTES = 4 * 1024 * 1024;+const DIFF_CONTEXT_LINES = 3;+/** A diff gets a place in the event only while at least this much of the budget is left. */+const MIN_DIFF_ROOM_BYTES = 1024;+/** Past this edit distance, or this much work, the exact diff gives way to a greedy one. */+const MAX_EDIT_DISTANCE = 1_500;+const MAX_DIFF_WORK = 10_000_000;+/** How far ahead the greedy diff looks, on each side, for the lines to line up again. */+const GREEDY_WINDOW = 32;+const BASE_WRITE_CONCURRENCY = 8;+/** Texts waiting to be written beyond this make writable() wait, so a start snapshot never holds more. */+const BASE_PENDING_HIGH_WATER = 8 * 1024 * 1024;+const BASE_INDEX_FILE = "index.json";+const BASE_INDEX_SAVE_MS = 2_000;+const SHA256_NAME = /^[0-9a-f]{64}$/;++export type TurnDiffStatus = "added" | "modified" | "deleted" | "skipped" | "no_base";++/** One file of a "turn.diff" event. */+export type TurnDiffFile = {+ /** Workspace-relative, redacted as upload paths are. */+ path: string;+ status: TurnDiffStatus;+ /** Redacted sha256 of the text before the turn (null for an added or skipped file). */+ before_sha256: string | null;+ /** Redacted sha256 of the text after the turn (null for a deleted or skipped file). */+ after_sha256: string | null;+ additions: number | null;+ deletions: number | null;+ /** Unified diff of the scrubbed texts; null when a side is unavailable (no_base) or the file was skipped. */+ diff: string | null;+ /** The diff was cut at MAX_TURN_DIFF_FILE_BYTES or at the event's remaining budget. */+ truncated: boolean;+};++export type TurnDiffEvent = {+ schema_version: 1;+ files: TurnDiffFile[];+ /** Files the turn changed, including any the event cap left out of `files`. */+ file_count: number;+ omitted_file_count: number;+ /** A diff was cut or a file left out. */+ truncated: boolean;+};++/** A changed file with its texts resolved: null where that side has no text (added, deleted, skipped, no base). */+export type TurnDiffInput = {+ path: string;+ status: TurnDiffStatus;+ before_sha256: string | null;+ after_sha256: string | null;+ before: string | null;+ after: string | null;+};++type Lines = { lines: string[]; eofNewline: boolean };++function splitLines(text: string): Lines {+ if (text === "") return { lines: [], eofNewline: true };+ const lines = text.split("\n");+ const eofNewline = lines.at(-1) === "";+ if (eofNewline) lines.pop();+ return { lines, eofNewline };+}++/**+ * Marks the lines outside a longest common subsequence of `a` and `b`+ * (Myers' O(ND) algorithm), or, once the edit distance or the work passes its+ * bound, outside a greedy matching: a correct diff either way, only not+ * always a minimal one.+ */+function markChanges(a: Int32Array, b: Int32Array, removed: Uint8Array, added: Uint8Array, aOffset: number, bOffset: number): void {+ const n = a.length;+ const m = b.length;+ const replaceAll = () => {+ removed.fill(1, aOffset, aOffset + n);+ added.fill(1, bOffset, bOffset + m);+ };+ if (n === 0 || m === 0) return replaceAll();+ const limit = Math.min(n + m, MAX_EDIT_DISTANCE);+ const offset = limit + 1;+ const v = new Int32Array(2 * limit + 3);+ const trace: Int32Array[] = [];+ let work = 0;+ for (let d = 0; d <= limit; d += 1) {+ // What round d reads of round d-1: v[k-1] and v[k+1] for k in [-d, d].+ trace.push(v.slice(offset - d - 1, offset + d + 2));+ for (let k = -d; k <= d; k += 2) {+ let x = k === -d || (k !== d && v[offset + k - 1]! < v[offset + k + 1]!) ? v[offset + k + 1]! : v[offset + k - 1]! + 1;+ let y = x - k;+ const start = x;+ while (x < n && y < m && a[x] === b[y]) {+ x += 1;+ y += 1;+ }+ work += 1 + x - start;+ v[offset + k] = x;+ if (x >= n && y >= m) return backtrack(trace, n, m, removed, added, aOffset, bOffset);+ }+ if (work > MAX_DIFF_WORK) break;+ }+ greedy(a, b, removed, added, aOffset, bOffset);+}++/**+ * Walks both sides together; at a mismatch, the nearest point within the+ * window where they line up again ends the edit. Linear in the lines times+ * the window squared, whatever the edit distance.+ */+function greedy(a: Int32Array, b: Int32Array, removed: Uint8Array, added: Uint8Array, aOffset: number, bOffset: number): void {+ const n = a.length;+ const m = b.length;+ let i = 0;+ let j = 0;+ while (i < n && j < m) {+ if (a[i] === b[j]) {+ i += 1;+ j += 1;+ continue;+ }+ let skipA = 1;+ let skipB = 1;+ search: for (let distance = 1; distance <= 2 * GREEDY_WINDOW; distance += 1) {+ for (let x = Math.max(0, distance - GREEDY_WINDOW); x <= Math.min(distance, GREEDY_WINDOW); x += 1) {+ if (i + x < n && j + distance - x < m && a[i + x] === b[j + distance - x]) {+ skipA = x;+ skipB = distance - x;+ break search;+ }+ }+ }+ removed.fill(1, aOffset + i, aOffset + i + skipA);+ added.fill(1, bOffset + j, bOffset + j + skipB);+ i += skipA;+ j += skipB;+ }+ removed.fill(1, aOffset + i, aOffset + n);+ added.fill(1, bOffset + j, bOffset + m);+}++/** Walks the recorded rounds back from the end, marking the one edit each round made. */+function backtrack(trace: Int32Array[], n: number, m: number, removed: Uint8Array, added: Uint8Array, aOffset: number, bOffset: number): void {+ let x = n;+ let y = m;+ for (let d = trace.length - 1; d > 0; d -= 1) {+ const v = trace[d]!;+ const at = (k: number) => v[k + d + 1]!;+ const k = x - y;+ const down = k === -d || (k !== d && at(k - 1) < at(k + 1));+ const previousX = at(down ? k + 1 : k - 1);+ const previousY = previousX - (down ? k + 1 : k - 1);+ if (down) added[bOffset + previousY] = 1;+ else removed[aOffset + previousX] = 1;+ x = previousX;+ y = previousY;+ }+}++/** Bytes a line costs in the event: JSON-escaped, with its escaped newline in place of the quotes. */+function lineCost(line: string): number {+ return Buffer.byteLength(JSON.stringify(line));+}++/**+ * A unified diff (3 lines of context) of `before` into `after`, a null side+ * standing for /dev/null. The counts cover the whole change; the text stops+ * at the last whole line within `maxBytes` (measured JSON-encoded), marked+ * truncated.+ */+export function unifiedDiff(path: string, before: string | null, after: string | null, maxBytes = MAX_TURN_DIFF_FILE_BYTES): { diff: string; additions: number; deletions: number; truncated: boolean; bytes: number } {+ const a = splitLines(before ?? "");+ const b = splitLines(after ?? "");+ // A last line without a newline differs from the same line with one.+ const key = (side: Lines, index: number) => (index === side.lines.length - 1 && !side.eofNewline ? `${side.lines[index]}\u0000` : side.lines[index]!);+ const nA = a.lines.length;+ const nB = b.lines.length;+ let prefix = 0;+ while (prefix < nA && prefix < nB && key(a, prefix) === key(b, prefix)) prefix += 1;+ let suffix = 0;+ while (suffix < nA - prefix && suffix < nB - prefix && key(a, nA - 1 - suffix) === key(b, nB - 1 - suffix)) suffix += 1;+ const ids = new Map<string, number>();+ const idsOf = (side: Lines, count: number) => {+ const out = new Int32Array(count);+ for (let index = 0; index < count; index += 1) {+ const text = key(side, prefix + index);+ let id = ids.get(text);+ if (id === undefined) {+ id = ids.size;+ ids.set(text, id);+ }+ out[index] = id;+ }+ return out;+ };+ const removed = new Uint8Array(nA);+ const added = new Uint8Array(nB);+ markChanges(idsOf(a, nA - prefix - suffix), idsOf(b, nB - prefix - suffix), removed, added, prefix, prefix);++ type Block = { aStart: number; aEnd: number; bStart: number; bEnd: number };+ const blocks: Block[] = [];+ let additions = 0;+ let deletions = 0;+ for (let i = prefix, j = prefix; i < nA - suffix || j < nB - suffix;) {+ if (i < nA && j < nB && !removed[i] && !added[j]) {+ i += 1;+ j += 1;+ continue;+ }+ const block = { aStart: i, aEnd: i, bStart: j, bEnd: j };+ while (i < nA && removed[i]) i += 1;+ while (j < nB && added[j]) j += 1;+ block.aEnd = i;+ block.bEnd = j;+ deletions += i - block.aStart;+ additions += j - block.bStart;+ blocks.push(block);+ }++ const out: string[] = [];+ let bytes = 0;+ let truncated = false;+ const push = (line: string): boolean => {+ const cost = lineCost(line);+ if (bytes + cost > maxBytes) {+ truncated = true;+ return false;+ }+ out.push(line);+ bytes += cost;+ return true;+ };+ const noNewline = "\\ No newline at end of file";+ const emit = (prefixChar: string, side: Lines, index: number): boolean => {+ if (!push(`${prefixChar}${side.lines[index]}`)) return false;+ return index === side.lines.length - 1 && !side.eofNewline ? push(noNewline) : true;+ };+ const range = (start: number, length: number) => (length === 1 ? `${start + 1}` : `${length === 0 ? start : start + 1},${length}`);+ if (blocks.length > 0 && push(`--- ${before === null ? "/dev/null" : `a/${path}`}`) && push(`+++ ${after === null ? "/dev/null" : `b/${path}`}`)) {+ hunks: for (let index = 0; index < blocks.length;) {+ // A hunk runs over every block within twice the context of the one before.+ let last = index;+ while (last + 1 < blocks.length && blocks[last + 1]!.aStart - blocks[last]!.aEnd <= 2 * DIFF_CONTEXT_LINES) last += 1;+ const first = blocks[index]!;+ const end = blocks[last]!;+ const lead = Math.min(DIFF_CONTEXT_LINES, first.aStart);+ const trail = Math.min(DIFF_CONTEXT_LINES, nA - end.aEnd);+ const aStart = first.aStart - lead;+ const bStart = first.bStart - lead;+ const aLength = end.aEnd + trail - aStart;+ const bLength = end.bEnd + trail - bStart;+ if (!push(`@@ -${range(aStart, aLength)} +${range(bStart, bLength)} @@`)) break;+ let i = aStart;+ let j = bStart;+ for (let at = index; at <= last; at += 1) {+ const block = blocks[at]!;+ for (; i < block.aStart; i += 1, j += 1) if (!emit(" ", b, j)) break hunks;+ for (; i < block.aEnd; i += 1) if (!emit("-", a, i)) break hunks;+ for (; j < block.bEnd; j += 1) if (!emit("+", b, j)) break hunks;+ }+ for (let count = 0; count < trail; count += 1, i += 1, j += 1) if (!emit(" ", b, j)) break hunks;+ index = last + 1;+ }+ }+ return { diff: out.length > 0 ? `${out.join("\n")}\n` : "", additions, deletions, truncated, bytes };+}++/**+ * Assembles one "turn.diff" event under the event cap: each file's diff gets+ * at most MAX_TURN_DIFF_FILE_BYTES and what is left of the event's budget;+ * once the budget is spent, further files are only counted.+ */+export class TurnDiffBuilder {+ private readonly files: TurnDiffFile[] = [];+ private used = 0;+ private omitted = 0;+ private truncated = false;++ constructor(private readonly maxEventBytes = MAX_TURN_DIFF_EVENT_BYTES, private readonly maxFileBytes = MAX_TURN_DIFF_FILE_BYTES) {}++ /** No further diff fits: the caller need not resolve its texts. */+ get full(): boolean {+ return this.used + MIN_DIFF_ROOM_BYTES > this.maxEventBytes;+ }++ omit(): void {+ this.omitted += 1;+ this.truncated = true;+ }++ add(input: TurnDiffInput): void {+ const file: TurnDiffFile = {+ path: input.path,+ status: input.status,+ before_sha256: input.before_sha256,+ after_sha256: input.after_sha256,+ additions: null,+ deletions: null,+ diff: null,+ truncated: false,+ };+ // The entry without its diff, plus the comma between entries.+ const overhead = Buffer.byteLength(JSON.stringify(file)) + 1;+ const room = this.maxEventBytes - this.used - overhead;+ const hasText = (input.status === "added" || input.status === "modified" || input.status === "deleted") && (input.before !== null || input.after !== null);+ if (room < (hasText ? MIN_DIFF_ROOM_BYTES : 0)) return this.omit();+ let diffBytes = 0;+ if (hasText) {+ const result = unifiedDiff(input.path, input.status === "added" ? null : input.before, input.status === "deleted" ? null : input.after, Math.min(this.maxFileBytes, room));+ file.additions = result.additions;+ file.deletions = result.deletions;+ file.diff = result.diff;+ file.truncated = result.truncated;+ diffBytes = result.bytes;+ if (result.truncated) this.truncated = true;+ }+ this.files.push(file);+ this.used += overhead + (file.diff === null ? 0 : diffBytes + 2 - 4);+ }++ finish(): TurnDiffEvent {+ return {+ schema_version: 1,+ files: this.files,+ file_count: this.files.length + this.omitted,+ omitted_file_count: this.omitted,+ truncated: this.truncated,+ };+ }+}++function sha256Hex(text: string): string {+ return createHash("sha256").update(text).digest("hex");+}++/**+ * The scrubbed texts the collector sent, by redacted sha256, least recently+ * used out first once `budget` bytes are held. The texts are files under+ * `dir` (one per digest, owner-only) and an index keeps their order across+ * restarts; a text is read back only while its digest still matches. Writes+ * happen in the background with bounded concurrency, and a text still being+ * written is served from memory.+ */+export class TurnBaseStore {+ /** Digest -> bytes, least recently used first. */+ private readonly index = new Map<string, number>();+ private readonly pending = new Map<string, { text: string; bytes: number }>();+ private readonly queue: string[] = [];+ private pendingBytes = 0;+ private used = 0;+ private active = 0;+ private generation = 0;+ /** The index changed since it was last saved. */+ private dirty = false;+ private saveTimer: ReturnType<typeof setTimeout> | null = null;+ private saveTail: Promise<void> = Promise.resolve();+ private readonly ready: Promise<void>;+ private waiters: Array<{ limit: number; resolve: () => void }> = [];++ constructor(private readonly dir: string, private readonly budget = TURN_BASE_STORE_BYTES) {+ this.ready = this.load(dir);+ }++ private async load(dir: string): Promise<void> {+ try {+ const parsed: unknown = JSON.parse(await readFile(join(dir, BASE_INDEX_FILE), "utf8"));+ const entries = typeof parsed === "object" && parsed !== null && "entries" in parsed && Array.isArray(parsed.entries) ? parsed.entries : [];+ for (const entry of entries) {+ if (!Array.isArray(entry) || typeof entry[0] !== "string" || !SHA256_NAME.test(entry[0]) || typeof entry[1] !== "number") continue;+ if (entry[1] < 0 || entry[1] > MAX_BASE_TEXT_BYTES || this.index.has(entry[0])) continue;+ this.index.set(entry[0], entry[1]);+ this.used += entry[1];+ }+ } catch {+ // No index yet, or an unreadable one: start empty.+ }+ try {+ // Texts no index names (written just before a crash) are never read: remove them.+ for (const name of await readdir(dir)) {+ if (name !== BASE_INDEX_FILE && !this.index.has(name)) await rm(join(dir, name), { force: true });+ }+ } catch {+ // No directory yet.+ }+ this.evict();+ }++ private touch(sha256: string, bytes: number): void {+ this.index.delete(sha256);+ this.index.set(sha256, bytes);+ this.dirty = true;+ }++ private evict(): void {+ for (const [sha256, bytes] of this.index) {+ if (this.used <= this.budget) break;+ this.index.delete(sha256);+ this.used -= bytes;+ void rm(join(this.dir, sha256), { force: true }).catch(() => undefined);+ }+ }++ /** Remembers `text` (the scrubbed text whose redacted sha256 is `sha256`, `bytes` long). */+ put(sha256: string, text: string, bytes: number): void {+ if (bytes > MAX_BASE_TEXT_BYTES) return;+ if (this.index.has(sha256)) return this.touch(sha256, bytes);+ // Writes that cannot keep up are dropped rather than held: a missing base only costs a no_base entry.+ if (this.pending.has(sha256) || this.pendingBytes + bytes > this.budget) return;+ this.pending.set(sha256, { text, bytes });+ this.pendingBytes += bytes;+ this.queue.push(sha256);+ this.pump();+ }++ private pump(): void {+ while (this.active < BASE_WRITE_CONCURRENCY && this.queue.length > 0) {+ const sha256 = this.queue.shift()!;+ this.active += 1;+ void this.write(sha256).finally(() => {+ this.active -= 1;+ const held = this.pending.get(sha256);+ if (held) {+ this.pending.delete(sha256);+ this.pendingBytes -= held.bytes;+ }+ this.pump();+ this.wake();+ });+ }+ }++ private wake(): void {+ const outstanding = this.active > 0 || this.queue.length > 0 ? this.pendingBytes + 1 : 0;+ this.waiters = this.waiters.filter((waiter) => {+ if (outstanding > waiter.limit) return true;+ waiter.resolve();+ return false;+ });+ }++ /** Resolves once queued writes hold at most `limit` bytes (0: once none are left). */+ private below(limit: number): Promise<void> {+ return new Promise((resolve) => {+ this.waiters.push({ limit, resolve });+ this.wake();+ });+ }++ /** Resolves once the write queue has room again: a caller putting many texts awaits it between puts. */+ writable(): Promise<void> {+ return this.pendingBytes <= BASE_PENDING_HIGH_WATER ? Promise.resolve() : this.below(BASE_PENDING_HIGH_WATER);+ }++ private async write(sha256: string): Promise<void> {+ const generation = this.generation;+ const held = this.pending.get(sha256);+ const dir = this.dir;+ try {+ await this.ready;+ if (!held || generation !== this.generation) return;+ const { text, bytes } = held;+ if (this.index.has(sha256)) return this.touch(sha256, bytes);+ await mkdir(dir, { recursive: true, mode: 0o700 });+ await writeFile(join(dir, sha256), text, { mode: 0o600 });+ if (generation !== this.generation) {+ await rm(join(dir, sha256), { force: true });+ return;+ }+ this.index.set(sha256, bytes);+ this.used += bytes;+ this.dirty = true;+ this.evict();+ this.scheduleSave();+ } catch {+ // A text that could not be written is simply not a base.+ }+ }++ /** The text stored under `sha256`, or null. */+ async get(sha256: string): Promise<string | null> {+ const pending = this.pending.get(sha256);+ if (pending) return pending.text;+ await this.ready;+ const bytes = this.index.get(sha256);+ if (bytes === undefined) return null;+ try {+ const text = await readFile(join(this.dir, sha256), "utf8");+ if (sha256Hex(text) !== sha256) throw new Error("base text changed on disk");+ if (this.index.has(sha256)) this.touch(sha256, bytes);+ return text;+ } catch {+ if (this.index.get(sha256) === bytes) {+ this.index.delete(sha256);+ this.used -= bytes;+ }+ return null;+ }+ }++ private scheduleSave(): void {+ if (this.saveTimer) return;+ this.saveTimer = setTimeout(() => {+ this.saveTimer = null;+ void this.save();+ }, BASE_INDEX_SAVE_MS);+ this.saveTimer.unref?.();+ }++ private save(): Promise<void> {+ const dir = this.dir;+ const generation = this.generation;+ this.dirty = false;+ const index = JSON.stringify({ version: 1, entries: [...this.index] });+ this.saveTail = this.saveTail.then(async () => {+ if (generation !== this.generation) return;+ await mkdir(dir, { recursive: true, mode: 0o700 });+ await writeFile(join(dir, `${BASE_INDEX_FILE}.tmp`), index, { mode: 0o600 });+ await rename(join(dir, `${BASE_INDEX_FILE}.tmp`), join(dir, BASE_INDEX_FILE));+ }).catch(() => undefined);+ return this.saveTail;+ }++ /** Waits for queued writes and saves the index (shutdown). */+ async flush(): Promise<void> {+ await this.below(0);+ if (this.saveTimer) {+ clearTimeout(this.saveTimer);+ this.saveTimer = null;+ }+ await this.ready;+ if (this.dirty) await this.save();+ }++ /** Forgets every text and removes the directory (sign-out). */+ async clear(): Promise<void> {+ this.generation += 1;+ if (this.saveTimer) {+ clearTimeout(this.saveTimer);+ this.saveTimer = null;+ }+ // After the load, which would otherwise fill the index again.+ await this.ready;+ this.index.clear();+ this.queue.length = 0;+ this.pending.clear();+ this.pendingBytes = 0;+ this.used = 0;+ this.dirty = false;+ this.wake();+ await this.saveTail;+ await rm(this.dir, { recursive: true, force: true });+ }+}diff --git a/apps/server/src/workspace-collector.ts b/apps/server/src/workspace-collector.tsindex 3fb19824..a0a7e054 100644--- a/apps/server/src/workspace-collector.ts+++ b/apps/server/src/workspace-collector.ts@@ -9,6 +9,7 @@ import { createZstdCompress } from "node:zlib";import { minimatch } from "minimatch";import { externalFetch } from "./server-fetch.js";+import { TurnBaseStore, TurnDiffBuilder, type TurnDiffInput } from "./turn-diff.js";const execFileAsync = promisify(execFile);@@ -107,6 +108,8 @@ const SESSION_LEDGER_FILE = "omnirush-collector-sessions.json";// the same bytes (a new chat on the same workspace) skips the regex pipeline.const REDACTED_TEXT_CACHE_BYTES = 32 * 1024 * 1024;const SPOOL_DIRECTORY = "omnirush-collector-spool";+/** The scrubbed texts "turn.diff" events are measured against (turn-diff.ts). */+const BASE_DIRECTORY = "omnirush-collector-bases";const MAX_SPOOL_BYTES = 128 * 1024 * 1024;const MAX_SPOOL_ENTRIES = 200;const MAX_SPOOL_ATTEMPTS = 24;@@ -313,6 +316,10 @@ type SessionState = {ignoredCache: Map<string, boolean>;/** The last accepted manifest: what the next change snapshot is measured against. */manifest: Manifest | null;+ /** The accepted manifest as the current turn began: what its "turn.diff" is measured against. */+ turnManifest: Manifest | null;+ /** Files the journal saw this turn write that may be binary or over the size cap: "skipped" in its "turn.diff". */+ turnSkipped: Set<string>;/** The per-root hash cache, shared with every other session open on the same root. */cache: Map<string, HashCacheEntry>;listing: { denied: number; truncated: boolean };@@ -2423,6 +2430,19 @@ type SnapshotCandidate = {priority: boolean;};+/** A file whose digest moved over a turn: null where it is not in that manifest. */+type TurnChange = { path: string; before: HashCacheEntry | null; after: HashCacheEntry | null };++/** Whether the first 8 KiB of a file read as binary (false when it cannot be read). */+async function startsBinary(absolute: string): Promise<boolean> {+ const head = Buffer.alloc(8_192);+ try {+ return isBinary(head.subarray(0, await readInto(absolute, head)));+ } catch {+ return false;+ }+}+/** The manifest entry as the envelope carries it: path (redacted), sha256, size. */function manifestEntryJson(entry: HashCacheEntry): string {return `{"path":${JSON.stringify(entry.uploadPath)},"sha256":"${entry.sha256}","size":${entry.bytes}}`;@@ -2828,6 +2848,8 @@ export class WorkspaceCollector {private readonly caches = new Map<string, { refs: number; entries: Map<string, HashCacheEntry>; reconciling: boolean; reconciledAt: number }>();/** Redacted text of the files the scrubber changed, shared by every root. */private readonly texts: RedactedTextCache;+ /** The scrubbed texts sent, by redacted digest: the bases of "turn.diff" events. */+ private readonly bases: TurnBaseStore;private readonly onSessionClosed?: (sessionId: string) => void;/** Work counters for tests and profiling. */readonly metrics: CollectorMetrics = freshMetrics();@@ -2858,6 +2880,7 @@ export class WorkspaceCollector {this.texts = new RedactedTextCache(options.redactedTextCacheBytes ?? REDACTED_TEXT_CACHE_BYTES);this.onSessionClosed = options.onSessionClosed;this.tempDir = stateDir ? join(stateDir, TEMP_DIRECTORY) : join(tmpdir(), `omnirush-collector-${process.pid}`);+ this.bases = new TurnBaseStore(stateDir ? join(stateDir, BASE_DIRECTORY) : join(this.tempDir, BASE_DIRECTORY));void this.cleanTempDir(60 * 60_000).catch(() => undefined);if (this.spoolDir) {if (this.enabled) {@@ -3037,6 +3060,8 @@ export class WorkspaceCollector {ignoreTimer: null,ignoredCache: new Map(),manifest: null,+ turnManifest: null,+ turnSkipped: new Set(),cache: this.acquireCache(root),listing: { denied: 0, truncated: false },dirty: new Set(),@@ -3619,7 +3644,87 @@ export class WorkspaceCollector {state.changeTimer = null;state.changeTrigger = null;}- this.enqueue(state, () => this.captureChange(state, trigger));+ this.enqueue(state, async () => {+ await this.captureChange(state, trigger);+ if (trigger === "turn_completed") return this.recordTurnDiff(state);+ // The turn is measured from the workspace as its prompt found it.+ state.turnManifest = state.manifest;+ state.turnSkipped = new Set();+ });+ }++ /**+ * Appends the "turn.diff" event of the turn that just completed: a unified+ * diff of the scrubbed texts of every file whose redacted digest moved+ * between the manifest the turn began on and the last accepted one (added,+ * modified, deleted, or no_base when the text sent before the turn is no+ * longer held), and each binary or oversized file the turn wrote as+ * skipped, without content. The next turn is measured from here.+ */+ private async recordTurnDiff(state: SessionState): Promise<void> {+ const before = state.turnManifest;+ const after = state.manifest;+ const skipped = state.turnSkipped;+ state.turnManifest = after;+ state.turnSkipped = new Set();+ if (state.finished || !before || !after) return;+ const changes: TurnChange[] = [];+ if (before !== after) {+ for (const [path, entry] of after) {+ const previous = before.get(path);+ if (previous?.sha256 !== entry.sha256) changes.push({ path, before: previous ?? null, after: entry });+ }+ for (const [path, entry] of before) if (!after.has(path)) changes.push({ path, before: entry, after: null });+ }+ for (const path of skipped) if (!after.has(path) && !before.has(path)) changes.push({ path, before: null, after: null });+ changes.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));+ const builder = new TurnDiffBuilder();+ const pool = new ReadPool(1);+ const ancestors: AncestorCache = new Map();+ const yielder = new LoopYielder();+ for (const change of changes) {+ if (builder.full) {+ builder.omit();+ continue;+ }+ const input = await this.turnDiffInput(state, change, pool, ancestors);+ if (input) builder.add(input);+ await yielder.pause();+ }+ this.appendTrace(state, "turn.diff", builder.finish());+ }++ private async turnDiffInput(state: SessionState, change: TurnChange, pool: ReadPool, ancestors: AncestorCache): Promise<TurnDiffInput | null> {+ const { path, before, after } = change;+ const input = {+ path: (after ?? before)?.uploadPath ?? collectorPathForUpload(path),+ before_sha256: before?.sha256 ?? null,+ after_sha256: after?.sha256 ?? null,+ before: null,+ after: null,+ };+ if (after) {+ const base = before ? await this.bases.get(before.sha256) : null;+ if (before && base === null) return { ...input, status: "no_base" };+ const text = await this.bases.get(after.sha256) ?? await this.rereadSentText(state, path, after, pool, ancestors);+ // Without the text after the turn (the file moved on since) there is nothing to diff.+ return { ...input, status: before ? "modified" : "added", before: text === null ? null : base, after: text };+ }+ // Gone from the manifest (or never in it): deleted, or a binary or oversized file now.+ const absolute = resolve(state.root, path);+ const file = await hasRealAncestors(state.root, path, ancestors) ? await lstat(absolute).catch(() => null) : null;+ if (!file) return before ? { ...input, status: "deleted", before: await this.bases.get(before.sha256) } : null;+ if (!file.isFile() || file.isSymbolicLink()) return null;+ if (file.size <= MAX_COLLECTOR_FILE_BYTES && !state.cache.get(path)?.binary && !(await startsBinary(absolute))) return null;+ return { ...input, after_sha256: null, status: "skipped" };+ }++ /** The text a manifest entry describes when the base store no longer holds it: read again, if the file still hashes to it. */+ private async rereadSentText(state: SessionState, path: string, entry: HashCacheEntry, pool: ReadPool, ancestors: AncestorCache): Promise<string | null> {+ const read = await readUploadContent(state.root, path, state.cache, this.texts, this.metrics, pool, ancestors);+ if (!read || read.entry.sha256 !== entry.sha256) return null;+ this.bases.put(entry.sha256, read.content, entry.bytes);+ return read.content;}finishSession(sessionId: string, finalTrace?: unknown): void {@@ -3694,6 +3799,7 @@ export class WorkspaceCollector {await Promise.allSettled([...this.sessions.values()].map((state) => state.tail));await this.spoolTail.catch(() => undefined);await this.ledgerWriteTail.catch(() => undefined);+ await this.bases.flush().catch(() => undefined);this.texts.clear();if (!this.ledgerPath) await rm(this.tempDir, { recursive: true, force: true }).catch(() => undefined);}@@ -3829,6 +3935,7 @@ export class WorkspaceCollector {let entry: ChangeJournalEntry;try {const file = await lstat(absolute);+ if (file.isFile() && !file.isSymbolicLink() && file.size > MAX_CHANGE_JOURNAL_BYTES) state.turnSkipped.add(path);if (!file.isFile() || file.isSymbolicLink() || file.size > MAX_COLLECTOR_FILE_BYTES) {entry = { path, at: new Date().toISOString(), status: "skipped" };} else if (file.size > MAX_CHANGE_JOURNAL_BYTES) {@@ -3840,6 +3947,7 @@ export class WorkspaceCollector {const buffer = await readFile(absolute);this.metrics.fileReads += 1;if (buffer.length > MAX_COLLECTOR_FILE_BYTES || isBinary(buffer)) {+ state.turnSkipped.add(path);entry = { path, at: new Date().toISOString(), status: "skipped" };} else {// The journal's read doubles as the snapshot's: the cache learns the@@ -4010,6 +4118,8 @@ export class WorkspaceCollector {if (read.entry.sha256 !== manifest.get(candidate.path)?.sha256) manifest.set(candidate.path, read.entry);await emit({ path: candidate.uploadPath, content: read.content, sha256: read.entry.sha256 });used += cost;+ this.bases.put(read.entry.sha256, read.content, read.entry.bytes);+ await this.bases.writable();}},manifest: () => manifest.values(),@@ -4045,6 +4155,7 @@ export class WorkspaceCollector {// next change snapshot reports exactly what moved since this one.accepted = true;state.manifest = manifest;+ state.turnManifest ??= manifest;state.listing = { denied: scan.deniedCount, truncated: scan.manifestTruncated };state.lastHead = git?.commit ?? null;if (journal.length > 0) this.acknowledgeJournal(state, journal);@@ -4444,8 +4555,9 @@ export class WorkspaceCollector {}/**- * Discards every spooled upload. Wire this to sign-out and consent- * withdrawal: once the account is gone nothing may stay queued on disk.+ * Discards every spooled upload and the stored turn-diff bases. Wire this+ * to sign-out and consent withdrawal: once the account is gone nothing may+ * stay queued on disk.*/clearSpool(): Promise<void> {if (this.retryTimer) {@@ -4454,6 +4566,8 @@ export class WorkspaceCollector {}this.retryFailures = 0;return this.spoolLocked(async () => {+ // The turn diffs' bases are workspace content on disk too.+ await this.bases.clear();if (!this.spoolDir) return;await rm(this.spoolDir, { recursive: true, force: true });});diff --git a/docs/workspace-collector-privacy.md b/docs/workspace-collector-privacy.mdindex 0374722a..e508d7c9 100644--- a/docs/workspace-collector-privacy.md+++ b/docs/workspace-collector-privacy.md@@ -18,3 +18,7 @@ Neither field changes what may leave the machine: `files[]`, `changed_paths` andThere is no per-session storage limit: a session keeps uploading snapshots and traces for as long as it runs, however much it has already sent, and the privacy block carries no `max_session_bytes`. Every remaining limit applies to one file or one request and matches what the backend accepts per request: 4 MiB per file, 64 MiB per snapshot envelope (uncompressed, and again once compressed), 16 MiB per trace document, 2 MiB of git diff and 50,000 manifest entries. These bound the collector's memory and never stop a session: a snapshot that would not fit still goes out with the files it has room for (touched and git-changed files first, smallest first within each tier), the full manifest, and the rest counted in `snapshot_cap_omitted_count` and `snapshot_cap_omitted_bytes`. The collector still counts the bytes each session has sent, in its local session ledger, for diagnostics only.The desktop collector keeps its footprint bounded while producing these snapshots. It runs on a worker thread of the app's local server, together with the turn observer and the project archive (`apps/server/src/capture-host.ts`), so reading, hashing and scrubbing files, building and compressing envelopes, and parsing long transcripts never hold the event loop that serves the app (the Electron main process in the desktop app); the main thread only forwards calls and makes the uploads the worker hands it. Envelopes are streamed as JSON through zstd into a temp file under the app state directory (`omnirush-collector-tmp`) and uploaded from that file, so no envelope string or buffer is ever held whole; a failed upload moves the file into the retry spool (same filesystem, a rename) and a delivered one is deleted at once. Files are read with bounded concurrency and the scan yields to the event loop between files. A per-root digest cache keyed by path, size and mtime, shared by every chat open on the same workspace, means unchanged files are neither re-read nor re-hashed, and a file the scrubber left byte-identical is uploaded as read (verified by digest) without a second pass through the redaction rules; the redacted text of files the scrubber did change is kept too (32 MiB at most, least recently used out first) and sent again only for the exact bytes it came from (verified by the digest of the bytes read), so a new chat on a workspace another chat already captured runs no file through the scrubber a second time. The scrubber runs the assignment and e-mail rules only over lines holding their keyword or an "@" and skips a rule whose literal the text lacks; neither shortcut changes a single output byte. Change snapshots come from watcher-driven dirty tracking: a prompt or completed turn with nothing dirty, journaled or committed since the last accepted snapshot records only its `collector.trigger` event; a change is scanned by dirty path, and before anything is read git is asked afresh, in one batched `git check-ignore`, about every reported path and every journal entry (or the workspace's own `.gitignore` files are applied where git cannot answer), so a file the user has just ignored through `.gitignore`, `.git/info/exclude` or `core.excludesFile` leaves the manifest and the journal at once; a path git refuses to answer for (one beyond a symlinked directory) is isolated by splitting the batch, so it cannot change the answer for the others, and counts as ignored. No path outside the workspace root (a parent folder, another Windows drive or a network share), and none reached through a symlinked directory, is ever read or listed. The whole tree is rescanned only when the dirty set overflowed, a directory appeared, a `.gitignore` changed, or the workspace is polled. The watchers go up from the start snapshot's listing before any file is read and cover the root, the top-level directories that hold listed files and then every other top-level directory git does not ignore and the denylist does not name (an empty `scripts/`, a `config/` holding only a denied `.env`), so `.git/`, `node_modules/`, gitignored build output and denied directories never reach them, and a gitignored directory that appears later (a rebuilt `dist/`) is neither watched nor rescanned; at the end of a turn every untracked file the turn created or changed is marked dirty too, so the turn's own snapshot carries it even where no watcher reaches; a workspace with more than 20,000 eligible files, or more than 64 top-level directories holding listed files, is polled on snapshots instead of watched (past 64 watched directories in all, the rest are left to the reconcile pass and the end-of-turn scan), and one reconcile pass (listing and stat only) per workspace every 60 seconds covers every chat watching it. A file larger than the change journal's budget is not journaled on every write; the next snapshot carries it. Filesystem- and reconcile-driven change snapshots are spaced at least 30 seconds apart, with the triggers in between merged into one; prompt and turn milestones capture at once.++## Per-turn diffs: the `turn.diff` trace event++At the end of each turn the trace gets one `turn.diff` event (`apps/server/src/turn-diff.ts`), pairing the turn with what it changed in the workspace: every file whose redacted sha256 moved between the accepted manifest the turn began on (as its prompt found the workspace) and the last accepted one. Each entry carries the workspace-relative redacted path, a `status` (`added`, `modified`, `deleted`, `skipped` for a binary or over-4-MiB file the turn wrote, sent without content, or `no_base` when the text sent before the turn is no longer held), both redacted digests, the `+`/`-` line counts and a unified diff of the scrubbed text sent before the turn against the scrubbed text sent after it. A file diff is cut at 256 KiB and the event at 2 MiB (JSON-encoded), both marked `truncated`; files past the event cap are only counted in `omitted_file_count`. The diff is built from text the collector already sent, so the denylist and scrubber apply unchanged, and the trace is scrubbed again as a whole like every other event. To have the "before" side, the collector keeps the scrubbed texts it sent (start snapshots seed it) in a content-addressed store under the app state directory (`omnirush-collector-bases`, owner-only files, 64 MiB at most, least recently used out first), so bases survive a restart; a sign-out deletes it with the spool.