@@ -13,67 +13,154 @@ export function generateDiff(
1313 return `--- ${filePath}\n+++ ${filePath}\n${diff}`;
1414 }
1515
16-function computeUnifiedDiff(before: string[], after: string[]): string {
17- const CONTEXT = 3;
18-
19- // Find the first differing index and the last differing index in each array
20- // independently, so hunk sizes are correct when the two arrays differ in length.
21- let firstDiff = -1;
22- let lastDiffBefore = -1;
23- let lastDiffAfter = -1;
16+// ---------------------------------------------------------------------------
17+// LCS-based unified diff
18+// ---------------------------------------------------------------------------
2419
25- for (let i = 0; i < before.length; i++) {
26- if (before[i] !== after[i]) {
27- if (firstDiff === -1) firstDiff = i;
28- lastDiffBefore = i;
29- }
30- }
31- for (let i = 0; i < after.length; i++) {
32- if (after[i] !== before[i]) {
33- if (firstDiff === -1) firstDiff = i;
34- lastDiffAfter = i;
20+/**
21+ * Compute the longest common subsequence lengths table for two string arrays.
22+ * Returns a flat (m+1)*(n+1) array where index i*(n+1)+j holds the LCS length
23+ * of before[0..i-1] and after[0..j-1].
24+ */
25+function lcsTable(before: string[], after: string[]): number[] {
26+ const m = before.length;
27+ const n = after.length;
28+ const w = n + 1;
29+ const dp: number[] = new Array<number>((m + 1) * w).fill(0);
30+ for (let i = 1; i <= m; i++) {
31+ for (let j = 1; j <= n; j++) {
32+ if (before[i - 1] === after[j - 1]) {
33+ dp[i * w + j] = (dp[(i - 1) * w + (j - 1)] ?? 0) + 1;
34+ } else {
35+ dp[i * w + j] = Math.max(
36+ dp[(i - 1) * w + j] ?? 0,
37+ dp[i * w + (j - 1)] ?? 0,
38+ );
39+ }
3540 }
3641 }
42+ return dp;
43+}
44+
45+type EditKind = "eq" | "del" | "ins";
46+type EditOp = { kind: EditKind; line: string };
3747
38- if (firstDiff === -1) return "";
48+/**
49+ * Backtrack through the LCS table to produce a sequence of edit operations:
50+ * - "eq" : line present in both (context)
51+ * - "del" : line only in before (removed)
52+ * - "ins" : line only in after (added)
53+ */
54+function editScript(before: string[], after: string[]): EditOp[] {
55+ const n = after.length;
56+ const w = n + 1;
57+ const dp = lcsTable(before, after);
3958
40- // Clamp: if one side has no differing lines past firstDiff, end at firstDiff
41- if (lastDiffBefore === -1) lastDiffBefore = firstDiff;
42- if (lastDiffAfter === -1) lastDiffAfter = firstDiff;
59+ const ops: EditOp[] = [];
60+ let i = before.length;
61+ let j = after.length;
62+ while (i > 0 || j > 0) {
63+ const bLine = before[i - 1] ?? "";
64+ const aLine = after[j - 1] ?? "";
65+ if (i > 0 && j > 0 && bLine === aLine) {
66+ ops.push({ kind: "eq", line: bLine });
67+ i--;
68+ j--;
69+ } else if (
70+ j > 0 &&
71+ (i === 0 || (dp[i * w + (j - 1)] ?? 0) >= (dp[(i - 1) * w + j] ?? 0))
72+ ) {
73+ ops.push({ kind: "ins", line: aLine });
74+ j--;
75+ } else {
76+ ops.push({ kind: "del", line: bLine });
77+ i--;
78+ }
79+ }
80+ ops.reverse();
81+ return ops;
82+}
4383
44- const hunkStart = Math.max(0, firstDiff - CONTEXT);
45- const hunkEndBefore = Math.min(before.length, lastDiffBefore + 1 + CONTEXT);
46- const hunkEndAfter = Math.min(after.length, lastDiffAfter + 1 + CONTEXT);
84+type IndexedOp = EditOp & { bi: number; ai: number };
4785
48- const lines: string[] = [];
49- lines.push(
50- `@@ -${hunkStart + 1},${hunkEndBefore - hunkStart} ` +
51- `+${hunkStart + 1},${hunkEndAfter - hunkStart} @@`,
52- );
86+function computeUnifiedDiff(before: string[], after: string[]): string {
87+ const CONTEXT = 3;
88+ const ops = editScript(before, after);
5389
54- // Context before
55- for (let i = hunkStart; i < firstDiff; i++) {
56- lines.push(` ${before[i] ?? ""}`);
90+ // Attach before/after line numbers to every op
91+ const indexed: IndexedOp[] = [];
92+ let bi = 0;
93+ let ai = 0;
94+ for (const op of ops) {
95+ indexed.push({ ...op, bi, ai });
96+ if (op.kind === "eq" || op.kind === "del") bi++;
97+ if (op.kind === "eq" || op.kind === "ins") ai++;
5798 }
5899
59- // Removed lines
60- for (let i = firstDiff; i <= lastDiffBefore && i < before.length; i++) {
61- lines.push(`-${before[i] ?? ""}`);
100+ // Collect positions of changed ops
101+ const changedIdx: number[] = [];
102+ for (let k = 0; k < indexed.length; k++) {
103+ if (indexed[k]?.kind !== "eq") changedIdx.push(k);
62104 }
63105
64- // Added lines
65- for (let i = firstDiff; i <= lastDiffAfter && i < after.length; i++) {
66- lines.push(`+${after[i] ?? ""}`);
106+ if (changedIdx.length === 0) return "";
107+
108+ // Group changed ops into hunks. Two changes belong to the same hunk when
109+ // the number of equal (context) lines separating them is <= 2*CONTEXT.
110+ const groups: Array<[number, number]> = [];
111+ let groupStart = changedIdx[0] ?? 0;
112+ let groupEnd = changedIdx[0] ?? 0;
113+
114+ for (let k = 1; k < changedIdx.length; k++) {
115+ const prev = changedIdx[k - 1] ?? 0;
116+ const cur = changedIdx[k] ?? 0;
117+ let equalCount = 0;
118+ for (let x = prev + 1; x < cur; x++) {
119+ if (indexed[x]?.kind === "eq") equalCount++;
120+ }
121+ if (equalCount > 2 * CONTEXT) {
122+ groups.push([groupStart, groupEnd]);
123+ groupStart = cur;
124+ }
125+ groupEnd = cur;
67126 }
127+ groups.push([groupStart, groupEnd]);
128+
129+ // Render each group as a unified-diff hunk
130+ const hunks: string[] = [];
131+ for (const [gStart, gEnd] of groups) {
132+ const opStart = Math.max(0, gStart - CONTEXT);
133+ const opEnd = Math.min(indexed.length - 1, gEnd + CONTEXT);
134+
135+ const lines: string[] = [];
136+ let beforeCount = 0;
137+ let afterCount = 0;
138+ for (let x = opStart; x <= opEnd; x++) {
139+ const op = indexed[x];
140+ if (!op) continue;
141+ if (op.kind === "eq") {
142+ lines.push(` ${op.line}`);
143+ beforeCount++;
144+ afterCount++;
145+ } else if (op.kind === "del") {
146+ lines.push(`-${op.line}`);
147+ beforeCount++;
148+ } else {
149+ lines.push(`+${op.line}`);
150+ afterCount++;
151+ }
152+ }
153+
154+ const firstOp = indexed[opStart];
155+ // When a side has no lines (e.g. new file or cleared file), the unified
156+ // diff convention is to use start=0 rather than start=1.
157+ const beforeStart = beforeCount === 0 ? 0 : (firstOp?.bi ?? 0) + 1;
158+ const afterStart = afterCount === 0 ? 0 : (firstOp?.ai ?? 0) + 1;
68159
69- // Context after
70- for (
71- let i = lastDiffBefore + 1;
72- i < hunkEndBefore && i < before.length;
73- i++
74- ) {
75- lines.push(` ${before[i] ?? ""}`);
160+ hunks.push(
161+ `@@ -${beforeStart},${beforeCount} +${afterStart},${afterCount} @@\n${lines.join("\n")}`,
162+ );
76163 }
77164
78- return lines.join("\n");
165+ return hunks.join("\n");
79166 }