Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(large-pages): edit_page diff trims common lines and bounds the LCS table (diff_coarse past the budget; unifiedDiff unchanged)
garrytan50137e97d29c
diff --git a/src/core/persistence/page-edit.ts b/src/core/persistence/page-edit.tsindex dad467e7f9..9b803a55be 100644--- a/src/core/persistence/page-edit.ts+++ b/src/core/persistence/page-edit.ts@@ -19,12 +19,18 @@ import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { sanitizeText } from '../batch-rows.ts';import { serializePageToMarkdown } from '../markdown.ts';-import { unifiedDiff } from '../skillpack/diff-text.ts';+import { insertNoNewlineMarkers, splitLines, unifiedDiff } from '../skillpack/diff-text.ts';import { redactRetrievalOutput } from '../search/output-redaction.ts';import { scanCanonicalFences, targetFenceRefusal } from '../fence-repair/refusal.ts';export const EDIT_PAGE_MAX_EDITS = 50;export const EDIT_PAGE_DIFF_MAX_BYTES = 8 * 1024;+/**+ * Most LCS table cells (old lines + 1) x (new lines + 1) an edit_page diff+ * fills, about 32 MB of numbers. Past it only the changed region is diffed.+ */+export const EDIT_PAGE_DIFF_CELL_BUDGET = 4_000_000;+const EDIT_PAGE_DIFF_CONTEXT = 3;export const EDIT_PAGE_DOCS = 'docs/protocol/MEMORY_VERBS_v1.md#partial-page-edits-edit_page';export interface PageEdit { old_text: string; new_text: string; }@@ -176,21 +182,100 @@ export function applyPageEdits(page: Page, tags: string[], remote: boolean, editconst encodedBytes = (text: string) => Buffer.byteLength(JSON.stringify(text));+/**+ * unifiedDiff when its LCS table fits `cellBudget`. Otherwise the common+ * leading lines and (when both sides agree on the trailing newline) common+ * trailing lines are trimmed down to the diff context, the remaining window+ * is diffed, and its hunk headers are shifted back to page line numbers. A+ * window still over budget becomes one coarse hunk (context, every old line+ * removed, every new line added) with `coarse: true`. Every result applies+ * cleanly to `before` and yields the lines of `after`, and its no-newline+ * markers sit only at end-of-file (unifiedDiff can place them mid-file; a+ * change of the final newline alone is no line change to either). Before+ * this bound a one-line edit on a 50k-line page filled a 2.5-billion-cell+ * table.+ *+ * @internal exported for the differential test.+ */+export function boundedUnifiedDiff(+ before: string,+ after: string,+ oldPath: string,+ newPath: string,+ cellBudget = EDIT_PAGE_DIFF_CELL_BUDGET,+): { diff: string; coarse: boolean } {+ const a = splitLines(before);+ const b = splitLines(after);+ const n = a.lines.length;+ const m = b.lines.length;+ const opts = { oldPath, newPath, context: EDIT_PAGE_DIFF_CONTEXT };+ if ((n + 1) * (m + 1) <= cellBudget) return { diff: unifiedDiff(before, after, opts), coarse: false };++ let prefix = 0;+ while (prefix < n && prefix < m && a.lines[prefix] === b.lines[prefix]) prefix++;+ if (prefix === n && prefix === m) return { diff: '', coarse: false };+ let suffix = 0;+ if (a.trailingNewline === b.trailingNewline) {+ while (suffix < n - prefix && suffix < m - prefix && a.lines[n - 1 - suffix] === b.lines[m - 1 - suffix]) suffix++;+ }+ const from = Math.max(0, prefix - EDIT_PAGE_DIFF_CONTEXT);+ const tail = Math.max(0, suffix - EDIT_PAGE_DIFF_CONTEXT);+ const aWindow = a.lines.slice(from, n - tail);+ const bWindow = b.lines.slice(from, m - tail);+ const header = [`--- ${oldPath}`, `+++ ${newPath}`];++ if ((aWindow.length + 1) * (bWindow.length + 1) > cellBudget) {+ const lead = prefix - from;+ const trail = suffix - tail;+ const out = [...header, `@@ -${from + 1},${aWindow.length} +${from + 1},${bWindow.length} @@`];+ for (const line of aWindow.slice(0, lead)) out.push(' ' + line);+ for (const line of aWindow.slice(lead, aWindow.length - trail)) out.push('-' + line);+ for (const line of bWindow.slice(lead, bWindow.length - trail)) out.push('+' + line);+ for (const line of aWindow.slice(aWindow.length - trail)) out.push(' ' + line);+ insertNoNewlineMarkers(out, tail > 0 || a.trailingNewline, tail > 0 || b.trailingNewline);+ return { diff: out.join('\n') + '\n', coarse: true };+ }++ // The window is diffed as if both sides ended in a newline; the markers+ // go in afterwards, only on a side whose last hunk reaches end-of-file.+ const windowText = (lines: string[]) => (lines.length === 0 ? '' : lines.join('\n') + '\n');+ const out = [...header];+ let aEnd = 0;+ let bEnd = 0;+ for (const line of unifiedDiff(windowText(aWindow), windowText(bWindow), opts).split('\n').slice(2, -1)) {+ const hunk = /^@@ -(\d+),(\d+) \+(\d+),(\d+) @@$/.exec(line);+ if (!hunk) {+ out.push(line);+ continue;+ }+ const [aStart, aCount, bStart, bCount] = hunk.slice(1).map(Number) as [number, number, number, number];+ aEnd = aStart + from + aCount - 1;+ bEnd = bStart + from + bCount - 1;+ out.push(`@@ -${aStart + from},${aCount} +${bStart + from},${bCount} @@`);+ }+ insertNoNewlineMarkers(out, aEnd < n || a.trailingNewline, bEnd < m || b.trailingNewline);+ return { diff: out.join('\n') + '\n', coarse: false };+}+/*** The caller-view unified diff, secret-redacted like retrieval output (it is* retained in the receipt), cut on a line boundary so its JSON encoding fits* 8 KB: the receipt reserves exactly that much (EDIT_PAGE_RECEIPT_RESERVE).+ * `diff_coarse` marks a changed region too large to line-diff+ * (boundedUnifiedDiff).*/-export function editDiff(slug: string, before: string, after: string): { diff: string; diff_truncated?: true } {- const [{ diff: full }] = redactRetrievalOutput([{ diff: unifiedDiff(before, after, { oldPath: `a/${slug}.md`, newPath: `b/${slug}.md` }) }], {}).results;- if (encodedBytes(full) <= EDIT_PAGE_DIFF_MAX_BYTES) return { diff: full };+export function editDiff(slug: string, before: string, after: string): { diff: string; diff_truncated?: true; diff_coarse?: true } {+ const { diff, coarse } = boundedUnifiedDiff(before, after, `a/${slug}.md`, `b/${slug}.md`);+ const [{ diff: full }] = redactRetrievalOutput([{ diff }], {}).results;+ const marked = coarse ? { diff_coarse: true as const } : {};+ if (encodedBytes(full) <= EDIT_PAGE_DIFF_MAX_BYTES) return { diff: full, ...marked };const lines = full.split('\n');let kept = '';for (const line of lines) {if (encodedBytes(`${kept}${line}\n`) > EDIT_PAGE_DIFF_MAX_BYTES) break;kept += `${line}\n`;}- return { diff: kept, diff_truncated: true };+ return { diff: kept, diff_truncated: true, ...marked };}/** Extra terminal-receipt bytes an edit_page admission reserves for its diff. */diff --git a/src/core/skillpack/diff-text.ts b/src/core/skillpack/diff-text.tsindex 2316273a73..f1284b7458 100644--- a/src/core/skillpack/diff-text.ts+++ b/src/core/skillpack/diff-text.ts@@ -146,9 +146,18 @@ export function unifiedDiff(a: string, b: string, opts: UnifiedDiffOpts = {}): sfor (const ln of body) out.push(ln);}- // Trailing-newline markers.- if (!aSplit.trailingNewline) {- // Insert `\ No newline at end of file` after the last ' ' or '-' line.+ insertNoNewlineMarkers(out, aSplit.trailingNewline, bSplit.trailingNewline);++ return out.join('\n') + '\n';+}++/**+ * Insert `\ No newline at end of file` after the last old-side line (' ' or+ * '-') when `a` lacks a trailing newline, and after the last new-side line+ * (' ' or '+') when `b` does.+ */+export function insertNoNewlineMarkers(out: string[], aTrailingNewline: boolean, bTrailingNewline: boolean): void {+ if (!aTrailingNewline) {for (let i = out.length - 1; i >= 0; i--) {const c = out[i].charAt(0);if (c === ' ' || c === '-') {@@ -157,7 +166,7 @@ export function unifiedDiff(a: string, b: string, opts: UnifiedDiffOpts = {}): s}}}- if (!bSplit.trailingNewline) {+ if (!bTrailingNewline) {for (let i = out.length - 1; i >= 0; i--) {const c = out[i].charAt(0);if (c === ' ' || c === '+') {@@ -166,16 +175,14 @@ export function unifiedDiff(a: string, b: string, opts: UnifiedDiffOpts = {}): s}}}-- return out.join('\n') + '\n';}-interface LineSplit {+export interface LineSplit {lines: string[];trailingNewline: boolean;}-function splitLines(s: string): LineSplit {+export function splitLines(s: string): LineSplit {if (s.length === 0) return { lines: [], trailingNewline: true };const trailingNewline = s.endsWith('\n');const body = trailingNewline ? s.slice(0, -1) : s;diff --git a/test/edit-page.test.ts b/test/edit-page.test.tsindex c61721d12b..dcecebb0da 100644--- a/test/edit-page.test.ts+++ b/test/edit-page.test.ts@@ -162,6 +162,29 @@ describe('edit_page matching', () => {expect(poll.body.outcome.diff).toBe(result.body.diff);});+ test('a one-line edit on a 50k-line page commits with a windowed line diff', async () => {+ const lines = Array.from({ length: 50_000 }, (_, i) => `Row ${i} of the long page.`);+ await seed('notes/long', `${lines.join('\n')}\n`);+ const head = await call('get_page', { slug: 'notes/long', body: 'none' });+ const result = await edit('notes/long', [{ old_text: 'Row 25000 of the long page.', new_text: 'Row 25000 was edited.' }], { revision: head.body.revision });+ expect({ isError: result.isError, text: result.text.slice(0, 300) }).toMatchObject({ isError: false });+ const snapshot = (await engine.readPageSnapshot('notes/long', { sourceId: 'default' }))!;+ const line = editableView(snapshot.page as Page, snapshot.tags, true).split('\n').indexOf('Row 25000 was edited.') + 1;+ expect(line).toBeGreaterThan(25_000);+ expect(result.body.diff).toBe([+ '--- a/notes/long.md',+ '+++ b/notes/long.md',+ `@@ -${line - 3},7 +${line - 3},7 @@`,+ ...[24_997, 24_998, 24_999].map(i => ` Row ${i} of the long page.`),+ '-Row 25000 of the long page.',+ '+Row 25000 was edited.',+ ...[25_001, 25_002, 25_003].map(i => ` Row ${i} of the long page.`),+ '',+ ].join('\n'));+ expect(result.body.diff_truncated).toBeUndefined();+ expect(result.body.diff_coarse).toBeUndefined();+ }, 120_000);+test('a stale revision is a revision_conflict that carries the current revision', async () => {await seed('notes/d', 'Body.\n');const stale = (await read('notes/d')).revision;diff --git a/test/large-pages/edit-diff-bounded.test.ts b/test/large-pages/edit-diff-bounded.test.tsnew file mode 100644index 0000000000..5a9d2c4ea6--- /dev/null+++ b/test/large-pages/edit-diff-bounded.test.ts@@ -0,0 +1,256 @@+/**+ * edit_page's retained diff must stay bounded on large pages: past a cell+ * budget only the changed window is line-diffed, and a window that is+ * itself too large becomes one coarse hunk marked `diff_coarse`.+ *+ * 1. Protects: edit_page on large pages (a one-line edit on a 50k-line page+ * filled a 2.5-billion-cell LCS table before the fix) and the receipt+ * diff of every ordinary edit, which stays byte-identical.+ * 2. Fails when: editDiff output changes for pages under the budget+ * (differential vs the old editDiff), a bounded diff stops applying to+ * the old text to give the new text (strict applier over a seeded+ * corpus with small budgets), a no-newline marker appears away from+ * end-of-file, or the LCS table grows past the budget (fill probe).+ * 3. Existing coverage: test/edit-page.test.ts pins the 8 KB cut and the+ * 50k-line case end to end; test/skillpack-apply-hunks.test.ts pins+ * unifiedDiff itself against its applier.+ * 4. Seam: boundedUnifiedDiff is exported (@internal) so small budgets+ * reach the windowed and coarse arms without large inputs.+ */+import { describe, expect, test } from 'bun:test';+import {+ EDIT_PAGE_DIFF_CELL_BUDGET,+ EDIT_PAGE_DIFF_MAX_BYTES,+ boundedUnifiedDiff,+ editDiff,+} from '../../src/core/persistence/page-edit.ts';+import { splitLines, unifiedDiff } from '../../src/core/skillpack/diff-text.ts';+import { redactRetrievalOutput } from '../../src/core/search/output-redaction.ts';+import { mulberry32 } from '../helpers/seeded-random.ts';++const MARKER = '\\ No newline at end of file';++/** editDiff before the cell budget. */+function oracleEditDiff(slug: string, before: string, after: string): { diff: string; diff_truncated?: true } {+ const [{ diff: full }] = redactRetrievalOutput([{ diff: unifiedDiff(before, after, { oldPath: `a/${slug}.md`, newPath: `b/${slug}.md` }) }], {}).results;+ const encoded = (text: string) => Buffer.byteLength(JSON.stringify(text));+ if (encoded(full) <= EDIT_PAGE_DIFF_MAX_BYTES) return { diff: full };+ let kept = '';+ for (const line of full.split('\n')) {+ if (encoded(`${kept}${line}\n`) > EDIT_PAGE_DIFF_MAX_BYTES) break;+ kept += `${line}\n`;+ }+ return { diff: kept, diff_truncated: true };+}++/**+ * Apply a unified diff produced by this repo's writer to `before`, checking+ * every context and removed line, hunk counts, hunk order, and that each+ * no-newline marker sits at end-of-file. A hunk starting at `-s` consumes+ * old lines from index s - 1 (the writer's convention, also for empty+ * old ranges). Returns the new text.+ */+function applyStrict(before: string, diff: string): string {+ const a = splitLines(before);+ if (diff === '') return before;+ const lines = diff.split('\n');+ expect(lines.pop()).toBe('');+ expect(lines[0]!.startsWith('--- ')).toBe(true);+ expect(lines[1]!.startsWith('+++ ')).toBe(true);+ const out: string[] = [];+ let cursor = 0;+ let newLacksNewline = false;+ let k = 2;+ while (k < lines.length) {+ const h = /^@@ -(\d+),(\d+) \+(\d+),(\d+) @@$/.exec(lines[k]!);+ expect(h).not.toBeNull();+ const [aStart, aCount, bStart, bCount] = h!.slice(1).map(Number) as [number, number, number, number];+ const at = aStart - 1;+ expect(at).toBeGreaterThanOrEqual(cursor);+ out.push(...a.lines.slice(cursor, at));+ expect(bStart - 1).toBe(out.length);+ let pos = at;+ let added = 0;+ k++;+ while (k < lines.length && !lines[k]!.startsWith('@@ ')) {+ const line = lines[k]!;+ const kind = line[0];+ if (kind === '\\') {+ expect(line).toBe(MARKER);+ const prev = lines[k - 1]![0];+ const twice = lines[k + 1] === MARKER;+ // The marker closes the old side, the new side, or both (twice). A+ // single marker after a context line closes the old side only when+ // that line ended the old text.+ const oldSide = prev === '-' || (prev === ' ' && (twice || (pos === a.lines.length && !a.trailingNewline)));+ const newSide = prev === '+' || (prev === ' ' && (twice || !oldSide));+ if (oldSide) expect({ pos, n: a.lines.length, trailing: a.trailingNewline }).toEqual({ pos: a.lines.length, n: a.lines.length, trailing: false });+ if (newSide) newLacksNewline = true;+ k += twice ? 2 : 1;+ continue;+ }+ const text = line.slice(1);+ if (kind === ' ' || kind === '-') {+ expect(a.lines[pos]).toBe(text);+ pos++;+ }+ if (kind === ' ' || kind === '+') {+ out.push(text);+ added++;+ }+ expect(' -+'.includes(kind!)).toBe(true);+ k++;+ }+ expect(pos - at).toBe(aCount);+ expect(added).toBe(bCount);+ cursor = pos;+ }+ const atEnd = cursor === a.lines.length;+ out.push(...a.lines.slice(cursor));+ if (out.length === 0) return '';+ const trailing = atEnd ? !newLacksNewline : a.trailingNewline;+ return out.join('\n') + (trailing ? '\n' : '');+}++function randomPage(rand: () => number, alphabet: string[]): string[] {+ return Array.from({ length: Math.floor(rand() * 30) }, () => alphabet[Math.floor(rand() * alphabet.length)]!);+}++function mutate(rand: () => number, lines: string[], alphabet: string[]): string[] {+ const out = [...lines];+ const edits = 1 + Math.floor(rand() * 4);+ for (let e = 0; e < edits; e++) {+ const at = Math.floor(rand() * (out.length + 1));+ const del = Math.floor(rand() * 3);+ const ins = Array.from({ length: Math.floor(rand() * 3) }, () => alphabet[Math.floor(rand() * alphabet.length)]!);+ out.splice(at, del, ...ins);+ }+ return out;+}++describe('editDiff stays identical under the budget', () => {+ test('ordinary edits produce the old editDiff byte for byte', () => {+ const rand = mulberry32(0x0b16_d1ff);+ const alphabet = ['alpha', 'beta', 'gamma', '', 'alice-example met acme-example', 'x'.repeat(400)];+ for (let k = 0; k < 2_000; k++) {+ const before = randomPage(rand, alphabet);+ const after = mutate(rand, before, alphabet);+ const a = before.join('\n') + (rand() < 0.8 ? '\n' : '');+ const b = after.join('\n') + (rand() < 0.8 ? '\n' : '');+ expect(editDiff('notes/x', a, b)).toEqual(oracleEditDiff('notes/x', a, b));+ }+ });+});++describe('boundedUnifiedDiff over budget (seeded corpus, small budgets)', () => {+ test('every windowed or coarse diff applies strictly and reproduces the new text', () => {+ const rand = mulberry32(0x0b16_d1ff ^ 0x5eed);+ const alphabet = ['a', 'b', 'c', '', ' a', '-a', '+a'];+ let windowed = 0;+ let coarse = 0;+ for (let k = 0; k < 20_000; k++) {+ const beforeLines = randomPage(rand, alphabet);+ const afterLines = mutate(rand, beforeLines, alphabet);+ const aTrailing = rand() < 0.7;+ const bTrailing = rand() < 0.5 ? aTrailing : rand() < 0.7;+ const before = beforeLines.length ? beforeLines.join('\n') + (aTrailing ? '\n' : '') : '';+ const after = afterLines.length ? afterLines.join('\n') + (bTrailing ? '\n' : '') : '';+ const budget = [1, 4, 12, 30, 80, 200][k % 6]!;+ const { diff, coarse: isCoarse } = boundedUnifiedDiff(before, after, 'a/p.md', 'b/p.md', budget);+ const aSplit = splitLines(before);+ const bSplit = splitLines(after);+ const n = aSplit.lines.length;+ const m = bSplit.lines.length;+ if ((n + 1) * (m + 1) <= budget) {+ expect({ diff, isCoarse }).toEqual({ diff: unifiedDiff(before, after, { oldPath: 'a/p.md', newPath: 'b/p.md' }), isCoarse: false });+ continue;+ }+ if (isCoarse) coarse++;+ else windowed++;+ if (aSplit.trailingNewline === bSplit.trailingNewline || before === '' || after === '') {+ expect(applyStrict(before, diff)).toBe(after);+ } else {+ // A change of the final newline alone is no line change to+ // unifiedDiff, so only the lines are compared here.+ expect(splitLines(applyStrict(before.endsWith('\n') ? before : before + '\n', diff.split('\n').filter(l => l !== MARKER).join('\n'))).lines)+ .toEqual(splitLines(after).lines);+ }+ }+ // The corpus reaches both arms.+ expect(windowed).toBeGreaterThan(1_000);+ expect(coarse).toBeGreaterThan(1_000);+ });++ test('a far-from-end edit in files without a final newline carries no marker', () => {+ const lines = Array.from({ length: 40 }, (_, i) => `line ${i}`);+ const before = lines.join('\n');+ const after = lines.map((l, i) => (i === 5 ? 'edited' : l)).join('\n');+ const { diff, coarse } = boundedUnifiedDiff(before, after, 'a', 'b', 100);+ expect(coarse).toBe(false);+ expect(diff).toBe(['--- a', '+++ b', '@@ -3,7 +3,7 @@', ' line 2', ' line 3', ' line 4', '-line 5', '+edited', ' line 6', ' line 7', ' line 8', ''].join('\n'));+ expect(applyStrict(before, diff)).toBe(after);+ });++ test('a near-end edit keeps both markers at end-of-file', () => {+ const lines = Array.from({ length: 40 }, (_, i) => `line ${i}`);+ const before = lines.join('\n');+ const after = lines.map((l, i) => (i === 38 ? 'edited' : l)).join('\n');+ const { diff } = boundedUnifiedDiff(before, after, 'a', 'b', 100);+ expect(diff.endsWith(` line 39\n${MARKER}\n${MARKER}\n`)).toBe(true);+ expect(applyStrict(before, diff)).toBe(after);+ });++ test('identical lines return an empty diff, like unifiedDiff', () => {+ const page = Array.from({ length: 100 }, (_, i) => `l${i}`).join('\n');+ expect(boundedUnifiedDiff(page, page, 'a', 'b', 10)).toEqual({ diff: '', coarse: false });+ expect(boundedUnifiedDiff(`${page}\n`, page, 'a', 'b', 10)).toEqual({ diff: unifiedDiff(`${page}\n`, page), coarse: false });+ });+});++/** Cells written by Array.prototype.fill (the LCS table rows) while `fn` runs. */+function countFilledCells(fn: () => void): number {+ const fill = Array.prototype.fill;+ let cells = 0;+ Array.prototype.fill = function (this: unknown[], ...args: unknown[]) {+ cells += this.length;+ return (fill as (...a: unknown[]) => unknown[]).apply(this, args);+ } as typeof Array.prototype.fill;+ try {+ fn();+ } finally {+ Array.prototype.fill = fill;+ }+ return cells;+}++describe('editDiff cell-budget probe', () => {+ const page = (n: number, tag = '') => Array.from({ length: n }, (_, i) => `Row ${i}${tag} of the page.`);++ test('a one-line edit just past the budget fills a window-sized table; the old diff filled the full one', () => {+ const before = page(2_000);+ const after = before.map((l, i) => (i === 1_000 ? 'Row 1000 was edited.' : l));+ const a = before.join('\n') + '\n';+ const b = after.join('\n') + '\n';+ let result: ReturnType<typeof editDiff> = { diff: '' };+ const cells = countFilledCells(() => { result = editDiff('notes/p', a, b); });+ expect(cells).toBeLessThanOrEqual(100);+ expect(result.diff_coarse).toBeUndefined();+ expect(applyStrict(a, result.diff)).toBe(b);+ const oldCells = countFilledCells(() => { oracleEditDiff('notes/p', a, b); });+ expect(oldCells).toBeGreaterThan(EDIT_PAGE_DIFF_CELL_BUDGET);+ });++ test('a rewrite of every line past the budget is one coarse hunk with no table at all', () => {+ const a = Array.from({ length: 2_100 }, (_, i) => `r${i}`).join('\n') + '\n';+ const b = Array.from({ length: 2_100 }, (_, i) => `s${i}`).join('\n') + '\n';+ let result: ReturnType<typeof editDiff> = { diff: '' };+ const cells = countFilledCells(() => { result = editDiff('notes/p', a, b); });+ expect(cells).toBe(0);+ expect(result.diff_coarse).toBe(true);+ expect(result.diff_truncated).toBe(true);+ expect(result.diff.split('\n').slice(0, 4)).toEqual(['--- a/notes/p.md', '+++ b/notes/p.md', '@@ -1,2100 +1,2100 @@', '-r0']);+ const full = boundedUnifiedDiff(a, b, 'a/notes/p.md', 'b/notes/p.md');+ expect(full.coarse).toBe(true);+ expect(applyStrict(a, full.diff)).toBe(b);+ });+});