edit-diff-fuzzy-span.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import {
  6. applyEditsToNormalizedContent,
  7. fuzzyFindText,
  8. isDisproportionateMatch,
  9. normalizeForFuzzyMatch,
  10. } from "../src/core/tools/edit-diff.ts";
  11. import { createEditToolDefinition } from "../src/core/tools/edit.ts";
  12. const tempDirs: string[] = [];
  13. async function createTempDir(): Promise<string> {
  14. const dir = await mkdtemp(join(tmpdir(), "pi-edit-fuzzy-span-"));
  15. tempDirs.push(dir);
  16. return dir;
  17. }
  18. afterEach(async () => {
  19. await Promise.all(tempDirs.splice(0, tempDirs.length).map((dir) => rm(dir, { recursive: true, force: true })));
  20. });
  21. // Unicode building blocks (kept as escapes so the test file itself stays ASCII-safe).
  22. const LSQ = "‘"; // left single smart quote
  23. const RSQ = "’"; // right single smart quote
  24. const LDQ = "“"; // left double smart quote
  25. const RDQ = "”"; // right double smart quote
  26. const EMDASH = "—";
  27. const ENDASH = "–";
  28. const IDEOSPACE = " "; // full-width ideographic space
  29. const FW_A = "a"; // full-width 'a'
  30. const FW_FOO = "foo"; // full-width 'foo'
  31. const FW_BAR = "bar"; // full-width 'bar'
  32. const COMBINING_ACUTE = "́";
  33. const BOM = "";
  34. describe("fuzzy matching stays scoped to the matched span", () => {
  35. it("keeps exact-match behavior unchanged", () => {
  36. const content = "line one\nline two\nline three\n";
  37. const result = applyEditsToNormalizedContent(content, [{ oldText: "line two", newText: "LINE TWO" }], "f.txt");
  38. expect(result.baseContent).toBe(content);
  39. expect(result.newContent).toBe("line one\nLINE TWO\nline three\n");
  40. });
  41. it("fails closed instead of swallowing a compat ligature the oldText only partly names", () => {
  42. // "fi" (U+FB01) NFKC-normalizes to "fi", so a model oldText of "ix"
  43. // matches in normalized space ("fix") starting INSIDE the ligature.
  44. // The back-map widens outward and would map onto the whole "fix",
  45. // silently destroying the ligature the model never named. The fidelity
  46. // guard must reject the ambiguous match rather than clobber those bytes.
  47. const content = "fix = 1\n";
  48. const match = fuzzyFindText(content, "ix");
  49. expect(match.found).toBe(false);
  50. expect(() =>
  51. applyEditsToNormalizedContent(content, [{ oldText: "ix", newText: "IX" }], "f.txt"),
  52. ).toThrow();
  53. });
  54. it("still applies a fuzzy edit that names a full-width run cleanly (guard is not over-strict)", () => {
  55. // oldText fully covers the full-width token in normalized space, so the
  56. // mapped span re-normalizes to exactly the located text — must succeed.
  57. const content = `x = ${FW_FOO}\n`;
  58. const result = applyEditsToNormalizedContent(content, [{ oldText: "x = foo", newText: "x = bar" }], "f.txt");
  59. expect(result.newContent).toBe("x = bar\n");
  60. });
  61. it("does not rewrite unrelated smart quotes / dashes / trailing whitespace when one edit matches fuzzily", () => {
  62. // Target line uses smart quotes; the model supplies ASCII quotes -> fuzzy match.
  63. // Every other line carries Unicode / whitespace quirks that must survive byte-for-byte.
  64. const lines = [
  65. `const a = "keep ${LDQ}these${RDQ} quotes";`, // smart double quotes, must survive
  66. `const target = ${LSQ}hello${RSQ};`, // smart single quotes, edit target
  67. `const dash = ${EMDASH}em${EMDASH};`, // em dashes, must survive
  68. "const pad = 1; ", // trailing spaces, must survive
  69. `const wide = ${IDEOSPACE}indent;`, // ideographic space, must survive
  70. ];
  71. const content = `${lines.join("\n")}\n`;
  72. const result = applyEditsToNormalizedContent(
  73. content,
  74. [{ oldText: "const target = 'hello';", newText: "const target = 'world';" }],
  75. "f.ts",
  76. );
  77. expect(result.baseContent).toBe(content);
  78. const newLines = result.newContent.split("\n");
  79. expect(newLines[0]).toBe(lines[0]);
  80. expect(newLines[1]).toBe("const target = 'world';");
  81. expect(newLines[2]).toBe(lines[2]);
  82. expect(newLines[3]).toBe(lines[3]);
  83. expect(newLines[4]).toBe(lines[4]);
  84. });
  85. it("preserves trailing whitespace on untouched lines when the match needed trailing-whitespace tolerance", () => {
  86. const content = "alpha = 1; \nbeta = 2;\t\ngamma = 3;\n";
  87. // oldText spans the newline but omits the trailing spaces present in the file -> fuzzy path.
  88. const result = applyEditsToNormalizedContent(
  89. content,
  90. [{ oldText: "alpha = 1;\nbeta", newText: "alpha = 10;\nbeta" }],
  91. "f.ts",
  92. );
  93. expect(result.newContent).toBe("alpha = 10;\nbeta = 2;\t\ngamma = 3;\n");
  94. });
  95. it("replaces a multi-line fuzzy span without touching surrounding lines", () => {
  96. const content = `before \nfoo(${LDQ}x${RDQ});\nbar(); \nafter${EMDASH}line\n`;
  97. const result = applyEditsToNormalizedContent(
  98. content,
  99. [{ oldText: 'foo("x");\nbar();', newText: "baz();" }],
  100. "f.ts",
  101. );
  102. // The matched span excludes bar()'s trailing spaces, so they survive after newText.
  103. expect(result.newContent).toBe(`before \nbaz(); \nafter${EMDASH}line\n`);
  104. });
  105. it("applies mixed exact and fuzzy edits at their original locations", () => {
  106. const content = `keep ${LDQ}quote${RDQ}\nexact target\nfuzzy ${LSQ}target${RSQ}\ntail \n`;
  107. const result = applyEditsToNormalizedContent(
  108. content,
  109. [
  110. { oldText: "exact target", newText: "exact done" },
  111. { oldText: "fuzzy 'target'", newText: "fuzzy done" },
  112. ],
  113. "f.txt",
  114. );
  115. expect(result.newContent).toBe(`keep ${LDQ}quote${RDQ}\nexact done\nfuzzy done\ntail \n`);
  116. });
  117. it("maps spans correctly on lines with full-width (NFKC-expanding) characters", () => {
  118. // Full-width latin letters normalize to ASCII under NFKC; untouched lines must survive.
  119. const content = `${FW_FOO} = 1\nvalue = ${LSQ}2${RSQ}\n${FW_BAR} = 3\n`;
  120. const result = applyEditsToNormalizedContent(
  121. content,
  122. [{ oldText: "value = '2'", newText: "value = '20'" }],
  123. "f.txt",
  124. );
  125. expect(result.newContent).toBe(`${FW_FOO} = 1\nvalue = '20'\n${FW_BAR} = 3\n`);
  126. });
  127. it("edits a fuzzy span on the same line as combining marks without corrupting them", () => {
  128. // "cafe" + combining acute precedes the target on the same line.
  129. const content = `cafe${COMBINING_ACUTE} price = ${LDQ}1${RDQ}\nother\n`;
  130. const result = applyEditsToNormalizedContent(
  131. content,
  132. [{ oldText: 'price = "1"', newText: 'price = "2"' }],
  133. "f.txt",
  134. );
  135. expect(result.newContent).toBe(`cafe${COMBINING_ACUTE} price = "2"\nother\n`);
  136. });
  137. it("returns original-space coordinates from fuzzyFindText for fuzzy matches", () => {
  138. const content = `pad \nsay ${LDQ}hi${RDQ} now\n`;
  139. const match = fuzzyFindText(content, 'say "hi" now');
  140. expect(match.found).toBe(true);
  141. expect(match.usedFuzzyMatch).toBe(true);
  142. expect(content.slice(match.index, match.index + match.matchLength)).toBe(`say ${LDQ}hi${RDQ} now`);
  143. });
  144. it("normalizes quotes, dashes, spaces, NFKC and trailing whitespace exactly as before", () => {
  145. const sample = `a${RSQ}b \n${LDQ}c${RDQ}${EMDASH}d\u00A0e\n${FW_A} line${IDEOSPACE}\nplain\n`;
  146. expect(normalizeForFuzzyMatch(sample)).toBe(`a'b\n"c"-d e\na line\nplain\n`);
  147. });
  148. });
  149. describe("error reporting", () => {
  150. it("suggests re-reading the file when the text is not found", () => {
  151. expect(() =>
  152. applyEditsToNormalizedContent("some content\n", [{ oldText: "missing", newText: "x" }], "f.txt"),
  153. ).toThrow(/read/i);
  154. });
  155. it("reports match line numbers on duplicate matches", () => {
  156. const content = "dup\nunique\ndup\ntail\n";
  157. expect(() => applyEditsToNormalizedContent(content, [{ oldText: "dup", newText: "x" }], "f.txt")).toThrow(
  158. /lines 1, 3/,
  159. );
  160. });
  161. it("still rejects empty oldText", () => {
  162. expect(() => applyEditsToNormalizedContent("abc\n", [{ oldText: "", newText: "x" }], "f.txt")).toThrow(
  163. /must not be empty/,
  164. );
  165. });
  166. it("still rejects overlapping edits", () => {
  167. const content = "one two three\n";
  168. expect(() =>
  169. applyEditsToNormalizedContent(
  170. content,
  171. [
  172. { oldText: "one two", newText: "a" },
  173. { oldText: "two three", newText: "b" },
  174. ],
  175. "f.txt",
  176. ),
  177. ).toThrow(/overlap/);
  178. });
  179. it("still rejects no-op replacements", () => {
  180. expect(() => applyEditsToNormalizedContent("abc\n", [{ oldText: "abc", newText: "abc" }], "f.txt")).toThrow(
  181. /No changes made/,
  182. );
  183. });
  184. });
  185. describe("isDisproportionateMatch", () => {
  186. it("accepts a match of similar size", () => {
  187. expect(isDisproportionateMatch("const a = 1;", "const a = 1; ")).toBe(false);
  188. });
  189. it("rejects a match spanning far more lines than oldText", () => {
  190. const oldText = "a";
  191. const matched = "a\nb\nc\nd";
  192. expect(isDisproportionateMatch(matched, oldText)).toBe(true);
  193. });
  194. it("rejects a multi-line match with disproportionate character count", () => {
  195. const oldText = "ab\ncd";
  196. const matched = `ab${"x".repeat(600)}\ncd`;
  197. expect(isDisproportionateMatch(matched, oldText)).toBe(true);
  198. });
  199. it("accepts a multi-line match within the character budget", () => {
  200. const oldText = "ab\ncd";
  201. const matched = "ab \ncd";
  202. expect(isDisproportionateMatch(matched, oldText)).toBe(false);
  203. });
  204. });
  205. describe("end-to-end through the edit tool", () => {
  206. async function runEdit(dir: string, fileName: string, raw: string, edits: unknown): Promise<string> {
  207. const filePath = join(dir, fileName);
  208. await writeFile(filePath, raw);
  209. const tool = createEditToolDefinition(dir);
  210. await tool.execute("call-1", { path: fileName, edits } as never, undefined);
  211. return readFile(filePath, "utf-8");
  212. }
  213. it("preserves CRLF line endings and unrelated bytes on a fuzzy edit", async () => {
  214. const dir = await createTempDir();
  215. const raw = `keep ${LDQ}q${RDQ}\r\ntarget = ${LSQ}a${RSQ}\r\ntrail \r\n`;
  216. const result = await runEdit(dir, "crlf.txt", raw, [{ oldText: "target = 'a'", newText: "target = 'b'" }]);
  217. expect(result).toBe(`keep ${LDQ}q${RDQ}\r\ntarget = 'b'\r\ntrail \r\n`);
  218. });
  219. it("preserves the BOM and untouched full-width characters", async () => {
  220. const dir = await createTempDir();
  221. const raw = `${BOM}${FW_A} = 1\ntarget ${EMDASH} x\n`;
  222. const result = await runEdit(dir, "bom.txt", raw, [{ oldText: "target - x", newText: "target - y" }]);
  223. expect(result).toBe(`${BOM}${FW_A} = 1\ntarget - y\n`);
  224. });
  225. it("produces a byte-exact file when only one line is edited fuzzily", async () => {
  226. const dir = await createTempDir();
  227. const lines = [
  228. "alpha ",
  229. `${LDQ}beta${RDQ}`,
  230. `gamma = ${LSQ}1${RSQ}`,
  231. `${IDEOSPACE}delta`,
  232. `epsilon${ENDASH}zeta`,
  233. ];
  234. const raw = `${lines.join("\n")}\n`;
  235. const result = await runEdit(dir, "mixed.txt", raw, [{ oldText: "gamma = '1'", newText: "gamma = '2'" }]);
  236. expect(result).toBe(`${lines[0]}\n${lines[1]}\ngamma = '2'\n${lines[3]}\n${lines[4]}\n`);
  237. });
  238. });