@criogaid/pi-hashline-edit 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -1,34 +1,14 @@
1
- import { execFile as execFileCallback } from "node:child_process";
2
- import { cp, mkdir, mkdtemp, rm, symlink } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { dirname, join } from "node:path";
5
1
  import { fileURLToPath } from "node:url";
6
2
  import { test } from "node:test";
7
- import manifest from "../../package.json" with { type: "json" };
8
- import { promisify } from "node:util";
9
-
10
- const execFile = promisify(execFileCallback);
11
- const LOAD_TIMEOUT_MS = 30_000;
3
+ import { installedExtension } from "../testing/installation.testing.ts";
4
+ import { runTestProcess } from "../testing/process.testing.ts";
12
5
 
13
6
  test("extension installed without devDependencies → loads through Pi's virtual modules", async (t) => {
14
- const root = await mkdtemp(join(tmpdir(), "hashline-extension-"));
15
- t.after(() => rm(root, { recursive: true, force: true }));
16
- const repository = fileURLToPath(new URL("../../", import.meta.url));
17
- await cp(join(repository, "src"), join(root, "src"), { recursive: true });
18
- await cp(join(repository, "package.json"), join(root, "package.json"));
19
- // Link only declared runtime packages; their own transitive dependencies stay resolvable.
20
- for (const dependency of Object.keys(manifest.dependencies)) {
21
- const destination = join(root, "node_modules", dependency);
22
- await mkdir(dirname(destination), { recursive: true });
23
- await symlink(join(repository, "node_modules", dependency), destination, "junction");
24
- }
25
- const entry = join(root, "src", "index.ts");
26
- await execFile(
7
+ const installation = await installedExtension(t);
8
+ await runTestProcess(
27
9
  process.execPath,
28
- [fileURLToPath(new URL("./extension-loading.testing.ts", import.meta.url)), entry],
29
- {
30
- env: { ...process.env, NODE_OPTIONS: "", NODE_PATH: "" },
31
- timeout: LOAD_TIMEOUT_MS,
32
- },
10
+ [fileURLToPath(new URL("./extension-loading.testing.ts", import.meta.url)), installation.entry],
11
+ installation.root,
12
+ installation.agentDir,
33
13
  );
34
14
  });
@@ -1,15 +1,3 @@
1
- // Run in a fresh Node process so global loaders and module caches cannot supply devDependencies.
2
- import assert from "node:assert/strict";
3
- import { createRequire } from "node:module";
4
- import { createJiti } from "../../node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/jiti-static-loader.js";
5
- import { VIRTUAL_MODULES } from "../../node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/virtual-modules.js";
1
+ import { loadInstalledExtension } from "../testing/extension-loader.testing.ts";
6
2
 
7
- const entry = process.argv[2];
8
- assert.throws(() => createRequire(entry).resolve("typebox/type"), { code: "MODULE_NOT_FOUND" });
9
- const jiti = createJiti(import.meta.url, {
10
- moduleCache: false,
11
- virtualModules: VIRTUAL_MODULES,
12
- tryNative: false,
13
- });
14
- const factory = await jiti.import<unknown>(entry, { default: true });
15
- assert.equal(typeof factory, "function");
3
+ await loadInstalledExtension(process.argv[2]);
@@ -1,10 +1,13 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
3
  import { computeLineHash } from "../core/hash.ts";
4
- import type { AnchorFailure } from "../core/types.ts";
5
- import { MAX_BLOCK_BYTES } from "./budgets.ts";
4
+ import { applyEdits } from "../core/apply.ts";
5
+ import type { AnchorFailure, Edit } from "../core/types.ts";
6
+ import { formatByteSize, DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
7
+ import { DEFAULT_CONFIG } from "./config.ts";
6
8
  import { createAnchorFormatter } from "./anchor-format.ts";
7
- import { formatAmbiguousCandidateNeighborhoods } from "./failure-context.ts";
9
+ import { ambiguousCandidateNeighborhoods, describeEditFailure } from "./failure-context.ts";
10
+ import { describeFailure, renderReport } from "./report.ts";
8
11
 
9
12
  function failure(recovery: AnchorFailure["recovery"]): AnchorFailure {
10
13
  return {
@@ -16,7 +19,6 @@ function failure(recovery: AnchorFailure["recovery"]): AnchorFailure {
16
19
  current: null,
17
20
  };
18
21
  }
19
-
20
22
  function ambiguous(lines: readonly string[], positions: number[], hashLen = 4): AnchorFailure {
21
23
  return failure({
22
24
  kind: "ambiguous",
@@ -27,110 +29,130 @@ function ambiguous(lines: readonly string[], positions: number[], hashLen = 4):
27
29
  })),
28
30
  });
29
31
  }
30
-
31
- function format(text: string, failures: readonly AnchorFailure[], hashLen = 4) {
32
- return formatAmbiguousCandidateNeighborhoods(text, failures, createAnchorFormatter(hashLen));
32
+ function neighborhoods(text: string, failures: readonly AnchorFailure[], hashLen = 4) {
33
+ return ambiguousCandidateNeighborhoods(
34
+ text,
35
+ failures,
36
+ createAnchorFormatter(hashLen),
37
+ DEFAULT_OUTPUT_BUDGETS,
38
+ );
39
+ }
40
+ function rows(result: ReturnType<typeof neighborhoods>) {
41
+ return result.facts.candidateNeighborhoods?.flatMap((group) => group.rows) ?? [];
33
42
  }
34
43
 
35
- test("unique and unresolved failures produce no neighborhoods", () => {
44
+ test("unique and unresolved failures → no ambiguous neighborhoods", () => {
36
45
  const failures = [
37
46
  failure({ kind: "found", scope: "local", newLine: 2, newHash: "NEW" }),
38
47
  failure({ kind: "none" }),
39
48
  ];
40
- assert.deepEqual(format("a\nb\nc\n", failures), { text: "", shownLines: new Set() });
41
- assert.deepEqual(format("", [failure({ kind: "none" })]), { text: "", shownLines: new Set() });
49
+ for (const text of ["a\nb\nc\n", ""]) {
50
+ assert.deepEqual(neighborhoods(text, failures), { facts: {}, shownLines: new Set() });
51
+ }
42
52
  });
43
53
 
44
- test("ambiguous context merges and sorts windows with CRLF and BOM-aware anchors", () => {
54
+ test("ambiguous CRLF and BOM context → merges sorted windows with copyable anchors", () => {
45
55
  const lines = ["\uFEFFfirst", "a", "", "c", "d", "e", "f", "last"];
46
- const { text: result, shownLines } = format(lines.join("\r\n"), [ambiguous(lines, [6, 2], 6)], 6);
47
- assert.deepEqual([...shownLines], [1, 2, 3, 4, 5, 6, 7, 8]);
48
- assert.match(result, /@@ candidate-neighborhood lines 1-8 @@/);
49
- assert.match(result, /Ambiguous-candidate neighborhoods.*observation only/);
50
- for (let line = 1; line <= lines.length; line++) {
51
- const row = `${line}#${computeLineHash(line, lines[line - 1], 6)}│${lines[line - 1]}`;
52
- assert.equal(result.split(row).length - 1, 1);
53
- }
54
- assert.doesNotMatch(result, /\r|omitted|truncated/);
56
+ const result = neighborhoods(lines.join("\r\n"), [ambiguous(lines, [6, 2], 6)], 6);
57
+ assert.deepEqual([...result.shownLines], [1, 2, 3, 4, 5, 6, 7, 8]);
58
+ assert.deepEqual(
59
+ result.facts.candidateNeighborhoods?.map((group) => group.lines),
60
+ ["1-8"],
61
+ );
62
+ assert.deepEqual(
63
+ rows(result),
64
+ lines.map(
65
+ (content, index) => `${index + 1}#${computeLineHash(index + 1, content, 6)}│${content}`,
66
+ ),
67
+ );
68
+ assert.doesNotMatch(rows(result).join("\n"), /\r/);
69
+ assert.equal(result.facts.omittedNeighborhoodRows, undefined);
55
70
  });
56
71
 
57
- test("ambiguous context clips windows at BOF and EOF without padding", () => {
72
+ test("ambiguous candidates at BOF and EOF → clipped windows without padding", () => {
58
73
  const lines = Array.from({ length: 10 }, (_, index) => `${index + 1}`);
59
- const result = format(lines.join("\n"), [ambiguous(lines, [1, 10])]).text;
60
- assert.match(result, /@@ candidate-neighborhood lines 1-4 @@/);
61
- assert.match(result, /@@ candidate-neighborhood lines 7-10 @@/);
62
- assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 8);
63
- assert.doesNotMatch(result, /omitted/);
74
+ const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [1, 10])]);
75
+ assert.deepEqual(
76
+ result.facts.candidateNeighborhoods?.map((group) => group.lines),
77
+ ["1-4", "7-10"],
78
+ );
79
+ assert.equal(rows(result).length, 8);
80
+ assert.equal(result.facts.omittedNeighborhoodRows, undefined);
64
81
  });
65
82
 
66
- test("ambiguous context exceeds forty rows and merges repeated candidate windows", () => {
83
+ test("more than forty context rows and repeated windows → no row cap or duplication", () => {
67
84
  const lines = Array.from({ length: 60 }, (_, index) => `line-${index + 1}`);
68
- const result = format(lines.join("\n"), [ambiguous(lines, [4, 14, 24, 34, 44, 54])]).text;
69
- assert.doesNotMatch(result, /omitted|truncated/);
70
- assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 42);
71
- const repeated = format(
85
+ const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [4, 14, 24, 34, 44, 54])]);
86
+ assert.equal(rows(result).length, 42);
87
+ assert.equal(result.facts.omittedNeighborhoodRows, undefined);
88
+ const repeated = neighborhoods(
72
89
  lines.join("\n"),
73
90
  Array.from({ length: 50 }, (_, opIndex) => ({ ...ambiguous(lines, [4, 5]), opIndex })),
74
- ).text;
75
- assert.equal((repeated.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 8);
76
- assert.doesNotMatch(repeated, /omitted|truncated/);
91
+ );
92
+ assert.equal(rows(repeated).length, 8);
93
+ assert.equal(new Set(rows(repeated)).size, 8);
77
94
  });
78
95
 
79
- test("ambiguous context uses the same first eight candidates as the detail list", () => {
96
+ test("more than eight ambiguous candidates → context uses the same candidate prefix", () => {
80
97
  const lines = Array.from({ length: 90 }, (_, index) => `line-${index + 1}`);
81
- const result = format(lines.join("\n"), [
98
+ const result = neighborhoods(lines.join("\n"), [
82
99
  ambiguous(lines, [4, 14, 24, 34, 44, 54, 64, 74, 84]),
83
- ]).text;
84
- assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 56);
85
- assert.match(result, /^77#[0-9A-Z]+│line-77$/m);
86
- assert.doesNotMatch(result, /^8[1-7]#[0-9A-Z]+│/m);
100
+ ]);
101
+ assert.equal(rows(result).length, 56);
102
+ assert.ok(rows(result).some((row) => /^77#[0-9A-Z]+│line-77$/.test(row)));
103
+ assert.ok(rows(result).every((row) => !/^8[1-7]#/.test(row)));
87
104
  });
88
105
 
89
- test("ambiguous context preserves complete rows at the byte budget", () => {
90
- const exact = "x".repeat(MAX_BLOCK_BYTES - Buffer.byteLength("1#XXXX│\n"));
91
- const lines = [exact, "target", "last"];
92
- const byteLimited = format(lines.join("\n"), [ambiguous(lines, [2, 3])]).text;
93
- assert.ok(byteLimited.includes(`1#${computeLineHash(1, exact, 4)}│${exact}\n`));
94
- assert.match(byteLimited, /Candidate-neighborhood rows: 1\/3; 2 omitted/);
95
- assert.match(byteLimited, /truncated: byte limit/);
96
- assert.doesNotMatch(byteLimited, /^2#[0-9A-Z]+│/m);
97
- const oversizedFirst = ["界".repeat(6000), "target", "last"];
98
- const skippedFirst = format(oversizedFirst.join("\n"), [ambiguous(oversizedFirst, [2, 3])]).text;
99
- assert.match(skippedFirst, /Candidate-neighborhood rows: 2\/3; 1 omitted/);
100
- assert.doesNotMatch(skippedFirst, /^1#[0-9A-Z]+│/m);
101
- assert.match(skippedFirst, /^2#[0-9A-Z]+│target$/m);
102
- assert.match(skippedFirst, /^3#[0-9A-Z]+│last$/m);
103
- const oversizedMiddle = ["short", "界".repeat(6000), "target", "last"];
104
- const partial = format(oversizedMiddle.join("\n"), [ambiguous(oversizedMiddle, [3, 4])]).text;
105
- assert.match(partial, /Candidate-neighborhood rows: 3\/4; 1 omitted/);
106
- assert.doesNotMatch(partial, /^2#[0-9A-Z]+│/m);
107
- assert.match(partial, /@@ candidate-neighborhood lines 1-1 @@/);
108
- assert.match(partial, /@@ candidate-neighborhood lines 3-4 @@/);
109
- const allOversized = ["x".repeat(4096), "y".repeat(4096)];
110
- const empty = format(allOversized.join("\n"), [ambiguous(allOversized, [1, 2])]).text;
111
- assert.match(empty, /No complete neighborhood row fits the limits/);
112
- assert.match(empty, /Candidate-neighborhood rows: 0\/2; 2 omitted/);
106
+ test("neighborhood exceeds byte budget → whole rows and explicit omission counts", () => {
107
+ const exact = "x".repeat(DEFAULT_OUTPUT_BUDGETS.blockBytes - Buffer.byteLength("1#XXXX│\n"));
108
+ const cases = [
109
+ { lines: [exact, "target", "last"], shown: [1], omitted: 2 },
110
+ { lines: ["界".repeat(6000), "target", "last"], shown: [2, 3], omitted: 1 },
111
+ { lines: ["short", "界".repeat(6000), "target", "last"], shown: [1, 3, 4], omitted: 1 },
112
+ {
113
+ lines: [
114
+ "x".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes),
115
+ "y".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes),
116
+ ],
117
+ shown: [],
118
+ omitted: 2,
119
+ },
120
+ ];
121
+ for (const { lines, shown, omitted } of cases) {
122
+ const result = neighborhoods(lines.join("\n"), [
123
+ ambiguous(lines, [lines.length - 1, lines.length]),
124
+ ]);
125
+ assert.deepEqual([...result.shownLines], shown);
126
+ assert.equal(result.facts.omittedNeighborhoodRows, omitted);
127
+ assert.ok(
128
+ Buffer.byteLength(rows(result).join("\n") + (rows(result).length ? "\n" : "")) <=
129
+ DEFAULT_OUTPUT_BUDGETS.blockBytes,
130
+ );
131
+ for (const position of shown)
132
+ assert.ok(
133
+ rows(result).includes(
134
+ `${position}#${computeLineHash(position, lines[position - 1], 4)}│${lines[position - 1]}`,
135
+ ),
136
+ );
137
+ }
113
138
  });
114
139
 
115
- test("ambiguous context enforces the complete candidate row byte limit", () => {
140
+ test("candidate complete row at its byte limit → kept exactly or omitted whole", () => {
116
141
  for (const extra of [0, 1]) {
117
- const candidate = "x".repeat(4096 - Buffer.byteLength("2#XXXXXX│") + extra);
142
+ const candidate = "x".repeat(
143
+ DEFAULT_OUTPUT_BUDGETS.fieldBytes - Buffer.byteLength("2#XXXXXX│") + extra,
144
+ );
118
145
  const lines = ["prefix", candidate, "tail", "other"];
119
- const output = format(lines.join("\n"), [ambiguous(lines, [2, 4], 6)], 6).text;
120
- if (extra === 0) {
121
- assert.ok(output.includes(`2#${computeLineHash(2, candidate, 6)}│${candidate}\n`));
122
- assert.doesNotMatch(output, /omitted/);
123
- } else {
124
- assert.match(output, /truncated: candidate row limit/);
125
- assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
126
- assert.match(output, /^4#[0-9A-Z]+│other$/m);
127
- }
146
+ const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [2, 4], 6)], 6);
147
+ assert.equal(result.shownLines.has(2), extra === 0);
148
+ assert.equal(result.facts.omittedNeighborhoodRows, extra === 0 ? undefined : 1);
149
+ assert.ok(result.shownLines.has(4));
128
150
  }
129
151
  });
130
152
 
131
- test("unique candidates inside ambiguous neighborhoods retain the candidate row limit", () => {
132
- const lines = ["prefix", "x".repeat(4096), "match", "match"];
133
- const output = format(lines.join("\n"), [
153
+ test("unique candidate inside ambiguous context exceeds limit → context cannot bypass its row limit", () => {
154
+ const lines = ["prefix", "x".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes), "match", "match"];
155
+ const result = neighborhoods(lines.join("\n"), [
134
156
  ambiguous(lines, [3, 4]),
135
157
  failure({
136
158
  kind: "found",
@@ -138,16 +160,171 @@ test("unique candidates inside ambiguous neighborhoods retain the candidate row
138
160
  newLine: 2,
139
161
  newHash: computeLineHash(2, lines[1], 4),
140
162
  }),
141
- ]).text;
142
- assert.match(output, /truncated: candidate row limit/);
143
- assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
163
+ ]);
164
+ assert.equal(result.shownLines.has(2), false);
165
+ assert.equal(result.facts.omittedNeighborhoodRows, 1);
144
166
  });
145
167
 
146
- test("neighborhoods keep shorter later rows when the remaining budget cannot fit a row", () => {
147
- const lines = ["x".repeat(MAX_BLOCK_BYTES - 100), "y".repeat(200), "target", "other"];
148
- const output = format(lines.join("\n"), [ambiguous(lines, [3, 4])]);
149
- assert.deepEqual([...output.shownLines], [1, 3, 4]);
150
- assert.match(output.text, /Candidate-neighborhood rows: 3\/4; 1 omitted/);
151
- const rows = output.text.match(/^\d+#[0-9A-Z]+│.*$/gm) ?? [];
152
- assert.ok(Buffer.byteLength(rows.join("\n") + "\n") <= MAX_BLOCK_BYTES);
168
+ test("remaining context budget cannot fit an intermediate row → retain shorter later rows", () => {
169
+ const lines = [
170
+ "x".repeat(DEFAULT_OUTPUT_BUDGETS.blockBytes - 100),
171
+ "y".repeat(200),
172
+ "target",
173
+ "other",
174
+ ];
175
+ const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [3, 4])]);
176
+ assert.deepEqual([...result.shownLines], [1, 3, 4]);
177
+ assert.equal(result.facts.omittedNeighborhoodRows, 1);
178
+ assert.ok(Buffer.byteLength(rows(result).join("\n") + "\n") <= DEFAULT_OUTPUT_BUDGETS.blockBytes);
179
+ });
180
+
181
+ function rejectedEdit(text: string, edits: Edit[], shiftRadius = 0) {
182
+ const result = applyEdits(text, edits, DEFAULT_CONFIG.hashLen, shiftRadius);
183
+ assert.ok(!result.ok, "the fixture must reach failure reporting");
184
+ const error = describeEditFailure(
185
+ result.failure,
186
+ { currentText: text, anchors: createAnchorFormatter(DEFAULT_CONFIG.hashLen) },
187
+ edits.length > 1,
188
+ DEFAULT_OUTPUT_BUDGETS,
189
+ );
190
+ return {
191
+ failure: result.failure,
192
+ report: describeFailure("edit", error, { path: "file.txt", budget: DEFAULT_OUTPUT_BUDGETS }),
193
+ };
194
+ }
195
+ const oldAnchor = { line: 1, hash: computeLineHash(1, "old", DEFAULT_CONFIG.hashLen) };
196
+
197
+ test("unresolved observation already shown elsewhere → reports the row once", async (t) => {
198
+ const cases = [
199
+ {
200
+ name: "ambiguous candidate neighborhood",
201
+ text: "current\nneighbor\nold\nold\n",
202
+ anchors: [oldAnchor, { line: 2, hash: computeLineHash(2, "gone", DEFAULT_CONFIG.hashLen) }],
203
+ radius: DEFAULT_CONFIG.shiftRadius,
204
+ line: 2,
205
+ content: "neighbor",
206
+ },
207
+ {
208
+ name: "earlier unresolved failure",
209
+ text: "current\n",
210
+ anchors: [oldAnchor, oldAnchor],
211
+ radius: 0,
212
+ line: 1,
213
+ content: "current",
214
+ },
215
+ ];
216
+ for (const fixture of cases) {
217
+ await t.test(fixture.name, () => {
218
+ const { report } = rejectedEdit(
219
+ fixture.text,
220
+ fixture.anchors.map((anchor) => ({ op: "delete", anchor })),
221
+ fixture.radius,
222
+ );
223
+ const observed = createAnchorFormatter(DEFAULT_CONFIG.hashLen).row(
224
+ fixture.line,
225
+ fixture.content,
226
+ );
227
+ const displayedRows = [
228
+ ...(report.failures?.flatMap((entry) => (entry.observed ? [entry.observed] : [])) ?? []),
229
+ ...(report.candidateNeighborhoods?.flatMap((group) => group.rows) ?? []),
230
+ ];
231
+ assert.equal(displayedRows.filter((row) => row === observed).length, 1);
232
+ });
233
+ }
234
+ });
235
+
236
+ test("multiple unresolved anchors and candidate context → one recovery survives omitted facts", () => {
237
+ const cases = [
238
+ ...[2, DEFAULT_OUTPUT_BUDGETS.blockBytes].map((count) => ({
239
+ text: "current\n",
240
+ edits: Array.from({ length: count }, (): Edit => ({ op: "delete", anchor: oldAnchor })),
241
+ radius: 0,
242
+ omitted: count === DEFAULT_OUTPUT_BUDGETS.blockBytes,
243
+ })),
244
+ {
245
+ text: "current\nold\n",
246
+ edits: [{ op: "delete", anchor: oldAnchor } as Edit],
247
+ radius: 2,
248
+ omitted: false,
249
+ },
250
+ {
251
+ text: "current\nold\nold\n",
252
+ edits: [{ op: "delete", anchor: oldAnchor } as Edit],
253
+ radius: 2,
254
+ omitted: false,
255
+ },
256
+ ];
257
+ for (const fixture of cases) {
258
+ const { report } = rejectedEdit(fixture.text, fixture.edits, fixture.radius);
259
+ assert.equal(report.error, "ANCHOR_MISMATCH");
260
+ assert.match(report.next ?? "", /confirm.*intended target/);
261
+ assert.match(report.next ?? "", /read or grep.*omitted rows.*out-of-range lines.*context/);
262
+ const { next, ...facts } = report;
263
+ assert.equal(renderReport(report).split(next!).length - 1, 1);
264
+ assert.doesNotMatch(JSON.stringify(facts), /\b(?:confirm|read|grep|retries)\b/i);
265
+ if (fixture.radius === 0)
266
+ assert.match(report.failures?.[0].observed ?? "", /1#[0-9A-Z]+│current/);
267
+ assert.equal(Boolean(report.omittedFailures), fixture.omitted);
268
+ }
269
+ });
270
+
271
+ test("failure list exceeds budget → omitted anchors are never reported as matched", () => {
272
+ const { report } = rejectedEdit(
273
+ "current\n",
274
+ Array.from({ length: DEFAULT_OUTPUT_BUDGETS.blockBytes }, () => ({
275
+ op: "delete",
276
+ anchor: oldAnchor,
277
+ })),
278
+ );
279
+ assert.equal(report.error, "ANCHOR_MISMATCH");
280
+ assert.ok(report.failures && report.failures.length > 0);
281
+ assert.equal(
282
+ report.failures.length + (report.omittedFailures ?? 0),
283
+ DEFAULT_OUTPUT_BUDGETS.blockBytes,
284
+ );
285
+ assert.equal(report.matched, undefined);
286
+ assert.ok(report.failures.every((entry) => entry.result === "unresolved"));
287
+ });
288
+
289
+ test("reversed ranges and overlapping edits → original reason and unpublished status without anchor recovery", () => {
290
+ const text = "a\nb\nc\n";
291
+ const anchor = (line: number, content: string) => ({
292
+ line,
293
+ hash: computeLineHash(line, content, DEFAULT_CONFIG.hashLen),
294
+ });
295
+ const cases: Edit[][] = [
296
+ [{ op: "delete", anchor: anchor(3, "c"), end: anchor(1, "a") }],
297
+ [
298
+ { op: "delete", anchor: anchor(1, "a"), end: anchor(2, "b") },
299
+ { op: "replace", anchor: anchor(2, "b"), body: ["changed"] },
300
+ ],
301
+ ];
302
+ for (const edits of cases) {
303
+ const { failure, report } = rejectedEdit(text, edits);
304
+ assert.ok(failure.kind === "range");
305
+ assert.equal(report.message, failure.message);
306
+ assert.equal(report.publication, "NOT_PUBLISHED");
307
+ assert.doesNotMatch(report.next ?? "", /Before reusing|confirm|read or grep|Retries verify/);
308
+ }
309
+ });
310
+
311
+ test("unresolved row out of range or oversized → omission facts contain no recovery instructions", () => {
312
+ const text = "x".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes) + "\n";
313
+ const cases = [
314
+ {
315
+ anchor: oldAnchor,
316
+ reason: new RegExp(`row exceeds ${formatByteSize(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`),
317
+ },
318
+ { anchor: { ...oldAnchor, line: 2 }, reason: /cited line is out of range/ },
319
+ ];
320
+ for (const { anchor, reason } of cases) {
321
+ const { report } = rejectedEdit(text, [{ op: "delete", anchor }]);
322
+ assert.equal(report.error, "ANCHOR_MISMATCH");
323
+ assert.match(report.failures?.[0].omitted ?? "", reason);
324
+ assert.equal(report.failures?.[0].observed, undefined);
325
+ assert.doesNotMatch(
326
+ JSON.stringify(report.failures),
327
+ /\b(?:confirm|read|grep|retry|retries)\b/i,
328
+ );
329
+ }
153
330
  });