@criogaid/pi-hashline-edit 0.6.1 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. 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 { formatKiB, 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,125 @@ 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(text, failures, createAnchorFormatter(hashLen));
34
+ }
35
+ function rows(result: ReturnType<typeof neighborhoods>) {
36
+ return result.facts.candidateNeighborhoods?.flatMap((group) => group.rows) ?? [];
33
37
  }
34
38
 
35
- test("unique and unresolved failures produce no neighborhoods", () => {
39
+ test("unique and unresolved failures → no ambiguous neighborhoods", () => {
36
40
  const failures = [
37
41
  failure({ kind: "found", scope: "local", newLine: 2, newHash: "NEW" }),
38
42
  failure({ kind: "none" }),
39
43
  ];
40
- assert.deepEqual(format("a\nb\nc\n", failures), { text: "", shownLines: new Set() });
41
- assert.deepEqual(format("", [failure({ kind: "none" })]), { text: "", shownLines: new Set() });
44
+ for (const text of ["a\nb\nc\n", ""]) {
45
+ assert.deepEqual(neighborhoods(text, failures), { facts: {}, shownLines: new Set() });
46
+ }
42
47
  });
43
48
 
44
- test("ambiguous context merges and sorts windows with CRLF and BOM-aware anchors", () => {
49
+ test("ambiguous CRLF and BOM context → merges sorted windows with copyable anchors", () => {
45
50
  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/);
51
+ const result = neighborhoods(lines.join("\r\n"), [ambiguous(lines, [6, 2], 6)], 6);
52
+ assert.deepEqual([...result.shownLines], [1, 2, 3, 4, 5, 6, 7, 8]);
53
+ assert.deepEqual(
54
+ result.facts.candidateNeighborhoods?.map((group) => group.lines),
55
+ ["1-8"],
56
+ );
57
+ assert.deepEqual(
58
+ rows(result),
59
+ lines.map(
60
+ (content, index) => `${index + 1}#${computeLineHash(index + 1, content, 6)}│${content}`,
61
+ ),
62
+ );
63
+ assert.doesNotMatch(rows(result).join("\n"), /\r/);
64
+ assert.equal(result.facts.omittedNeighborhoodRows, undefined);
55
65
  });
56
66
 
57
- test("ambiguous context clips windows at BOF and EOF without padding", () => {
67
+ test("ambiguous candidates at BOF and EOF → clipped windows without padding", () => {
58
68
  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/);
69
+ const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [1, 10])]);
70
+ assert.deepEqual(
71
+ result.facts.candidateNeighborhoods?.map((group) => group.lines),
72
+ ["1-4", "7-10"],
73
+ );
74
+ assert.equal(rows(result).length, 8);
75
+ assert.equal(result.facts.omittedNeighborhoodRows, undefined);
64
76
  });
65
77
 
66
- test("ambiguous context exceeds forty rows and merges repeated candidate windows", () => {
78
+ test("more than forty context rows and repeated windows → no row cap or duplication", () => {
67
79
  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(
80
+ const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [4, 14, 24, 34, 44, 54])]);
81
+ assert.equal(rows(result).length, 42);
82
+ assert.equal(result.facts.omittedNeighborhoodRows, undefined);
83
+ const repeated = neighborhoods(
72
84
  lines.join("\n"),
73
85
  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/);
86
+ );
87
+ assert.equal(rows(repeated).length, 8);
88
+ assert.equal(new Set(rows(repeated)).size, 8);
77
89
  });
78
90
 
79
- test("ambiguous context uses the same first eight candidates as the detail list", () => {
91
+ test("more than eight ambiguous candidates → context uses the same candidate prefix", () => {
80
92
  const lines = Array.from({ length: 90 }, (_, index) => `line-${index + 1}`);
81
- const result = format(lines.join("\n"), [
93
+ const result = neighborhoods(lines.join("\n"), [
82
94
  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);
95
+ ]);
96
+ assert.equal(rows(result).length, 56);
97
+ assert.ok(rows(result).some((row) => /^77#[0-9A-Z]+│line-77$/.test(row)));
98
+ assert.ok(rows(result).every((row) => !/^8[1-7]#/.test(row)));
87
99
  });
88
100
 
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/);
101
+ test("neighborhood exceeds byte budget → whole rows and explicit omission counts", () => {
102
+ const exact = "x".repeat(DEFAULT_OUTPUT_BUDGETS.blockBytes - Buffer.byteLength("1#XXXX│\n"));
103
+ const cases = [
104
+ { lines: [exact, "target", "last"], shown: [1], omitted: 2 },
105
+ { lines: ["界".repeat(6000), "target", "last"], shown: [2, 3], omitted: 1 },
106
+ { lines: ["short", "界".repeat(6000), "target", "last"], shown: [1, 3, 4], omitted: 1 },
107
+ {
108
+ lines: [
109
+ "x".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes),
110
+ "y".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes),
111
+ ],
112
+ shown: [],
113
+ omitted: 2,
114
+ },
115
+ ];
116
+ for (const { lines, shown, omitted } of cases) {
117
+ const result = neighborhoods(lines.join("\n"), [
118
+ ambiguous(lines, [lines.length - 1, lines.length]),
119
+ ]);
120
+ assert.deepEqual([...result.shownLines], shown);
121
+ assert.equal(result.facts.omittedNeighborhoodRows, omitted);
122
+ assert.ok(
123
+ Buffer.byteLength(rows(result).join("\n") + (rows(result).length ? "\n" : "")) <=
124
+ DEFAULT_OUTPUT_BUDGETS.blockBytes,
125
+ );
126
+ for (const position of shown)
127
+ assert.ok(
128
+ rows(result).includes(
129
+ `${position}#${computeLineHash(position, lines[position - 1], 4)}│${lines[position - 1]}`,
130
+ ),
131
+ );
132
+ }
113
133
  });
114
134
 
115
- test("ambiguous context enforces the complete candidate row byte limit", () => {
135
+ test("candidate complete row at its byte limit → kept exactly or omitted whole", () => {
116
136
  for (const extra of [0, 1]) {
117
- const candidate = "x".repeat(4096 - Buffer.byteLength("2#XXXXXX│") + extra);
137
+ const candidate = "x".repeat(
138
+ DEFAULT_OUTPUT_BUDGETS.fieldBytes - Buffer.byteLength("2#XXXXXX│") + extra,
139
+ );
118
140
  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
- }
141
+ const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [2, 4], 6)], 6);
142
+ assert.equal(result.shownLines.has(2), extra === 0);
143
+ assert.equal(result.facts.omittedNeighborhoodRows, extra === 0 ? undefined : 1);
144
+ assert.ok(result.shownLines.has(4));
128
145
  }
129
146
  });
130
147
 
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"), [
148
+ test("unique candidate inside ambiguous context exceeds limit → context cannot bypass its row limit", () => {
149
+ const lines = ["prefix", "x".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes), "match", "match"];
150
+ const result = neighborhoods(lines.join("\n"), [
134
151
  ambiguous(lines, [3, 4]),
135
152
  failure({
136
153
  kind: "found",
@@ -138,16 +155,131 @@ test("unique candidates inside ambiguous neighborhoods retain the candidate row
138
155
  newLine: 2,
139
156
  newHash: computeLineHash(2, lines[1], 4),
140
157
  }),
141
- ]).text;
142
- assert.match(output, /truncated: candidate row limit/);
143
- assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
158
+ ]);
159
+ assert.equal(result.shownLines.has(2), false);
160
+ assert.equal(result.facts.omittedNeighborhoodRows, 1);
144
161
  });
145
162
 
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);
163
+ test("remaining context budget cannot fit an intermediate row → retain shorter later rows", () => {
164
+ const lines = [
165
+ "x".repeat(DEFAULT_OUTPUT_BUDGETS.blockBytes - 100),
166
+ "y".repeat(200),
167
+ "target",
168
+ "other",
169
+ ];
170
+ const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [3, 4])]);
171
+ assert.deepEqual([...result.shownLines], [1, 3, 4]);
172
+ assert.equal(result.facts.omittedNeighborhoodRows, 1);
173
+ assert.ok(Buffer.byteLength(rows(result).join("\n") + "\n") <= DEFAULT_OUTPUT_BUDGETS.blockBytes);
174
+ });
175
+
176
+ function rejectedEdit(text: string, edits: Edit[], shiftRadius = 0) {
177
+ const result = applyEdits(text, edits, DEFAULT_CONFIG.hashLen, shiftRadius);
178
+ assert.ok(!result.ok, "the fixture must reach failure reporting");
179
+ const error = describeEditFailure(
180
+ result.failure,
181
+ { currentText: text, anchors: createAnchorFormatter(DEFAULT_CONFIG.hashLen) },
182
+ edits.length > 1,
183
+ );
184
+ return {
185
+ failure: result.failure,
186
+ report: describeFailure("edit", error, { path: "file.txt", mutation: true }),
187
+ };
188
+ }
189
+ const oldAnchor = { line: 1, hash: computeLineHash(1, "old", DEFAULT_CONFIG.hashLen) };
190
+
191
+ test("multiple unresolved anchors and candidate context → one recovery survives omitted facts", () => {
192
+ const cases = [
193
+ ...[2, DEFAULT_OUTPUT_BUDGETS.blockBytes].map((count) => ({
194
+ text: "current\n",
195
+ edits: Array.from({ length: count }, (): Edit => ({ op: "delete", start: oldAnchor })),
196
+ radius: 0,
197
+ omitted: count === DEFAULT_OUTPUT_BUDGETS.blockBytes,
198
+ })),
199
+ {
200
+ text: "current\nold\n",
201
+ edits: [{ op: "delete", start: oldAnchor } as Edit],
202
+ radius: 2,
203
+ omitted: false,
204
+ },
205
+ {
206
+ text: "current\nold\nold\n",
207
+ edits: [{ op: "delete", start: oldAnchor } as Edit],
208
+ radius: 2,
209
+ omitted: false,
210
+ },
211
+ ];
212
+ for (const fixture of cases) {
213
+ const { report } = rejectedEdit(fixture.text, fixture.edits, fixture.radius);
214
+ assert.equal(report.error, "ANCHOR_MISMATCH");
215
+ assert.match(report.next ?? "", /confirm.*intended target/);
216
+ assert.match(report.next ?? "", /read or grep.*omitted rows.*out-of-range lines.*context/);
217
+ const { next, ...facts } = report;
218
+ assert.equal(renderReport(report).split(next!).length - 1, 1);
219
+ assert.doesNotMatch(JSON.stringify(facts), /\b(?:confirm|read|grep|retries)\b/i);
220
+ if (fixture.radius === 0)
221
+ assert.match(report.failures?.[0].observed ?? "", /1#[0-9A-Z]+│current/);
222
+ assert.equal(Boolean(report.omittedFailures), fixture.omitted);
223
+ }
224
+ });
225
+
226
+ test("failure list exceeds budget → omitted anchors are never reported as matched", () => {
227
+ const { report } = rejectedEdit(
228
+ "current\n",
229
+ Array.from({ length: DEFAULT_OUTPUT_BUDGETS.blockBytes }, () => ({
230
+ op: "delete",
231
+ start: oldAnchor,
232
+ })),
233
+ );
234
+ assert.equal(report.error, "ANCHOR_MISMATCH");
235
+ assert.ok(report.failures && report.failures.length > 0);
236
+ assert.equal(
237
+ report.failures.length + (report.omittedFailures ?? 0),
238
+ DEFAULT_OUTPUT_BUDGETS.blockBytes,
239
+ );
240
+ assert.equal(report.matched, undefined);
241
+ assert.ok(report.failures.every((entry) => entry.result === "unresolved"));
242
+ });
243
+
244
+ test("reversed ranges and overlapping edits → original reason and unpublished status without anchor recovery", () => {
245
+ const text = "a\nb\nc\n";
246
+ const anchor = (line: number, content: string) => ({
247
+ line,
248
+ hash: computeLineHash(line, content, DEFAULT_CONFIG.hashLen),
249
+ });
250
+ const cases: Edit[][] = [
251
+ [{ op: "delete", start: anchor(3, "c"), end: anchor(1, "a") }],
252
+ [
253
+ { op: "delete", start: anchor(1, "a"), end: anchor(2, "b") },
254
+ { op: "replace", start: anchor(2, "b"), body: ["changed"] },
255
+ ],
256
+ ];
257
+ for (const edits of cases) {
258
+ const { failure, report } = rejectedEdit(text, edits);
259
+ assert.ok(failure.kind === "range");
260
+ assert.equal(report.message, failure.message);
261
+ assert.equal(report.publication, "NOT_PUBLISHED");
262
+ assert.doesNotMatch(report.next ?? "", /Before reusing|confirm|read or grep|Retries verify/);
263
+ }
264
+ });
265
+
266
+ test("unresolved row out of range or oversized → omission facts contain no recovery instructions", () => {
267
+ const text = "x".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes) + "\n";
268
+ const cases = [
269
+ {
270
+ start: oldAnchor,
271
+ reason: new RegExp(`row exceeds ${formatKiB(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`),
272
+ },
273
+ { start: { ...oldAnchor, line: 2 }, reason: /cited line is out of range/ },
274
+ ];
275
+ for (const { start, reason } of cases) {
276
+ const { report } = rejectedEdit(text, [{ op: "delete", start }]);
277
+ assert.equal(report.error, "ANCHOR_MISMATCH");
278
+ assert.match(report.failures?.[0].observedOmitted ?? "", reason);
279
+ assert.equal(report.failures?.[0].observed, undefined);
280
+ assert.doesNotMatch(
281
+ JSON.stringify(report.failures),
282
+ /\b(?:confirm|read|grep|retry|retries)\b/i,
283
+ );
284
+ }
153
285
  });