@criogaid/pi-hashline-edit 0.3.1 → 0.4.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 (69) hide show
  1. package/README.md +58 -49
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1593 -712
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +215 -132
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -6,120 +6,142 @@ import { createAnchorFormatter } from "./anchor-format.ts";
6
6
  import { formatAmbiguousCandidateNeighborhoods } from "./failure-context.ts";
7
7
 
8
8
  function failure(recovery: AnchorFailure["recovery"]): AnchorFailure {
9
- return { opIndex: 0, which: "anchor", op: "replace", cited: { line: 1, hash: "OLD" }, recovery, current: null };
9
+ return {
10
+ opIndex: 0,
11
+ which: "anchor",
12
+ op: "replace",
13
+ cited: { line: 1, hash: "OLD" },
14
+ recovery,
15
+ current: null,
16
+ };
10
17
  }
11
18
 
12
19
  function ambiguous(lines: readonly string[], positions: number[], hashLen = 4): AnchorFailure {
13
- return failure({ kind: "ambiguous", scope: "local", candidates: positions.map(line => ({ line, hash: computeLineHash(line, lines[line - 1], hashLen) })) });
20
+ return failure({
21
+ kind: "ambiguous",
22
+ scope: "local",
23
+ candidates: positions.map((line) => ({
24
+ line,
25
+ hash: computeLineHash(line, lines[line - 1], hashLen),
26
+ })),
27
+ });
14
28
  }
15
29
 
16
30
  function format(text: string, failures: readonly AnchorFailure[], hashLen = 4) {
17
- return formatAmbiguousCandidateNeighborhoods(text, failures, createAnchorFormatter(hashLen));
31
+ return formatAmbiguousCandidateNeighborhoods(text, failures, createAnchorFormatter(hashLen));
18
32
  }
19
33
 
20
34
  test("unique and unresolved failures produce no neighborhoods", () => {
21
- const failures = [failure({ kind: "found", scope: "local", newLine: 2, newHash: "NEW" }), failure({ kind: "none" })];
22
- assert.deepEqual(format("a\nb\nc\n", failures), { text: "", shownLines: new Set() });
23
- assert.deepEqual(format("", [failure({ kind: "none" })]), { text: "", shownLines: new Set() });
35
+ const failures = [
36
+ failure({ kind: "found", scope: "local", newLine: 2, newHash: "NEW" }),
37
+ failure({ kind: "none" }),
38
+ ];
39
+ assert.deepEqual(format("a\nb\nc\n", failures), { text: "", shownLines: new Set() });
40
+ assert.deepEqual(format("", [failure({ kind: "none" })]), { text: "", shownLines: new Set() });
24
41
  });
25
42
 
26
43
  test("ambiguous context merges and sorts windows with CRLF and BOM-aware anchors", () => {
27
- const lines = ["\uFEFFfirst", "a", "", "c", "d", "e", "f", "last"];
28
- const { text: result, shownLines } = format(lines.join("\r\n"), [ambiguous(lines, [6, 2], 6)], 6);
29
- assert.deepEqual([...shownLines], [1, 2, 3, 4, 5, 6, 7, 8]);
30
- assert.match(result, /@@ candidate-neighborhood lines 1-8 @@/);
31
- assert.match(result, /Ambiguous-candidate neighborhoods.*observation only/);
32
- for (let line = 1; line <= lines.length; line++) {
33
- const row = `${line}#${computeLineHash(line, lines[line - 1], 6)}│${lines[line - 1]}`;
34
- assert.equal(result.split(row).length - 1, 1);
35
- }
36
- assert.doesNotMatch(result, /\r|omitted|truncated/);
44
+ const lines = ["\uFEFFfirst", "a", "", "c", "d", "e", "f", "last"];
45
+ const { text: result, shownLines } = format(lines.join("\r\n"), [ambiguous(lines, [6, 2], 6)], 6);
46
+ assert.deepEqual([...shownLines], [1, 2, 3, 4, 5, 6, 7, 8]);
47
+ assert.match(result, /@@ candidate-neighborhood lines 1-8 @@/);
48
+ assert.match(result, /Ambiguous-candidate neighborhoods.*observation only/);
49
+ for (let line = 1; line <= lines.length; line++) {
50
+ const row = `${line}#${computeLineHash(line, lines[line - 1], 6)}│${lines[line - 1]}`;
51
+ assert.equal(result.split(row).length - 1, 1);
52
+ }
53
+ assert.doesNotMatch(result, /\r|omitted|truncated/);
37
54
  });
38
55
 
39
56
  test("ambiguous context clips windows at BOF and EOF without padding", () => {
40
- const lines = Array.from({ length: 10 }, (_, index) => `${index + 1}`);
41
- const result = format(lines.join("\n"), [ambiguous(lines, [1, 10])]).text;
42
- assert.match(result, /@@ candidate-neighborhood lines 1-4 @@/);
43
- assert.match(result, /@@ candidate-neighborhood lines 7-10 @@/);
44
- assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 8);
45
- assert.doesNotMatch(result, /omitted/);
57
+ const lines = Array.from({ length: 10 }, (_, index) => `${index + 1}`);
58
+ const result = format(lines.join("\n"), [ambiguous(lines, [1, 10])]).text;
59
+ assert.match(result, /@@ candidate-neighborhood lines 1-4 @@/);
60
+ assert.match(result, /@@ candidate-neighborhood lines 7-10 @@/);
61
+ assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 8);
62
+ assert.doesNotMatch(result, /omitted/);
46
63
  });
47
64
 
48
65
  test("ambiguous context exceeds forty rows and merges repeated candidate windows", () => {
49
- const lines = Array.from({ length: 60 }, (_, index) => `line-${index + 1}`);
50
- const result = format(lines.join("\n"), [ambiguous(lines, [4, 14, 24, 34, 44, 54])]).text;
51
- assert.doesNotMatch(result, /omitted|truncated/);
52
- assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 42);
53
- const repeated = format(lines.join("\n"), Array.from({ length: 50 }, (_, opIndex) => ({ ...ambiguous(lines, [4, 5]), opIndex }))).text;
54
- assert.equal((repeated.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 8);
55
- assert.doesNotMatch(repeated, /omitted|truncated/);
66
+ const lines = Array.from({ length: 60 }, (_, index) => `line-${index + 1}`);
67
+ const result = format(lines.join("\n"), [ambiguous(lines, [4, 14, 24, 34, 44, 54])]).text;
68
+ assert.doesNotMatch(result, /omitted|truncated/);
69
+ assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 42);
70
+ const repeated = format(
71
+ lines.join("\n"),
72
+ Array.from({ length: 50 }, (_, opIndex) => ({ ...ambiguous(lines, [4, 5]), opIndex })),
73
+ ).text;
74
+ assert.equal((repeated.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 8);
75
+ assert.doesNotMatch(repeated, /omitted|truncated/);
56
76
  });
57
77
 
58
78
  test("ambiguous context uses the same first eight candidates as the detail list", () => {
59
- const lines = Array.from({ length: 90 }, (_, index) => `line-${index + 1}`);
60
- const result = format(lines.join("\n"), [ambiguous(lines, [4, 14, 24, 34, 44, 54, 64, 74, 84])]).text;
61
- assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 56);
62
- assert.match(result, /^77#[0-9A-Z]+│line-77$/m);
63
- assert.doesNotMatch(result, /^8[1-7]#[0-9A-Z]+│/m);
79
+ const lines = Array.from({ length: 90 }, (_, index) => `line-${index + 1}`);
80
+ const result = format(lines.join("\n"), [
81
+ ambiguous(lines, [4, 14, 24, 34, 44, 54, 64, 74, 84]),
82
+ ]).text;
83
+ assert.equal((result.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 56);
84
+ assert.match(result, /^77#[0-9A-Z]+│line-77$/m);
85
+ assert.doesNotMatch(result, /^8[1-7]#[0-9A-Z]+│/m);
64
86
  });
65
87
 
66
88
  test("ambiguous context preserves complete rows at the byte budget", () => {
67
- const exact = "x".repeat(16 * 1024 - Buffer.byteLength("1#XXXX│\n"));
68
- const lines = [exact, "target", "last"];
69
- const byteLimited = format(lines.join("\n"), [ambiguous(lines, [2, 3])]).text;
70
- assert.ok(byteLimited.includes(`1#${computeLineHash(1, exact)}│${exact}\n`));
71
- assert.match(byteLimited, /Candidate-neighborhood rows: 1\/3; 2 omitted/);
72
- assert.match(byteLimited, /truncated: byte limit/);
73
- assert.doesNotMatch(byteLimited, /^2#[0-9A-Z]+│/m);
74
- const oversizedFirst = ["界".repeat(6000), "target", "last"];
75
- const skippedFirst = format(oversizedFirst.join("\n"), [ambiguous(oversizedFirst, [2, 3])]).text;
76
- assert.match(skippedFirst, /Candidate-neighborhood rows: 2\/3; 1 omitted/);
77
- assert.doesNotMatch(skippedFirst, /^1#[0-9A-Z]+│/m);
78
- assert.match(skippedFirst, /^2#[0-9A-Z]+│target$/m);
79
- assert.match(skippedFirst, /^3#[0-9A-Z]+│last$/m);
80
- const oversizedMiddle = ["short", "界".repeat(6000), "target", "last"];
81
- const partial = format(oversizedMiddle.join("\n"), [ambiguous(oversizedMiddle, [3, 4])]).text;
82
- assert.match(partial, /Candidate-neighborhood rows: 3\/4; 1 omitted/);
83
- assert.doesNotMatch(partial, /^2#[0-9A-Z]+│/m);
84
- assert.match(partial, /@@ candidate-neighborhood lines 1-1 @@/);
85
- assert.match(partial, /@@ candidate-neighborhood lines 3-4 @@/);
86
- const allOversized = ["x".repeat(4096), "y".repeat(4096)];
87
- const empty = format(allOversized.join("\n"), [ambiguous(allOversized, [1, 2])]).text;
88
- assert.match(empty, /No complete neighborhood row fits the limits/);
89
- assert.match(empty, /Candidate-neighborhood rows: 0\/2; 2 omitted/);
89
+ const exact = "x".repeat(16 * 1024 - Buffer.byteLength("1#XXXX│\n"));
90
+ const lines = [exact, "target", "last"];
91
+ const byteLimited = format(lines.join("\n"), [ambiguous(lines, [2, 3])]).text;
92
+ assert.ok(byteLimited.includes(`1#${computeLineHash(1, exact)}│${exact}\n`));
93
+ assert.match(byteLimited, /Candidate-neighborhood rows: 1\/3; 2 omitted/);
94
+ assert.match(byteLimited, /truncated: byte limit/);
95
+ assert.doesNotMatch(byteLimited, /^2#[0-9A-Z]+│/m);
96
+ const oversizedFirst = ["界".repeat(6000), "target", "last"];
97
+ const skippedFirst = format(oversizedFirst.join("\n"), [ambiguous(oversizedFirst, [2, 3])]).text;
98
+ assert.match(skippedFirst, /Candidate-neighborhood rows: 2\/3; 1 omitted/);
99
+ assert.doesNotMatch(skippedFirst, /^1#[0-9A-Z]+│/m);
100
+ assert.match(skippedFirst, /^2#[0-9A-Z]+│target$/m);
101
+ assert.match(skippedFirst, /^3#[0-9A-Z]+│last$/m);
102
+ const oversizedMiddle = ["short", "界".repeat(6000), "target", "last"];
103
+ const partial = format(oversizedMiddle.join("\n"), [ambiguous(oversizedMiddle, [3, 4])]).text;
104
+ assert.match(partial, /Candidate-neighborhood rows: 3\/4; 1 omitted/);
105
+ assert.doesNotMatch(partial, /^2#[0-9A-Z]+│/m);
106
+ assert.match(partial, /@@ candidate-neighborhood lines 1-1 @@/);
107
+ assert.match(partial, /@@ candidate-neighborhood lines 3-4 @@/);
108
+ const allOversized = ["x".repeat(4096), "y".repeat(4096)];
109
+ const empty = format(allOversized.join("\n"), [ambiguous(allOversized, [1, 2])]).text;
110
+ assert.match(empty, /No complete neighborhood row fits the limits/);
111
+ assert.match(empty, /Candidate-neighborhood rows: 0\/2; 2 omitted/);
90
112
  });
91
113
 
92
114
  test("ambiguous context enforces the complete candidate row byte limit", () => {
93
- for (const extra of [0, 1]) {
94
- const candidate = "x".repeat(4096 - Buffer.byteLength("2#XXXXXX│") + extra);
95
- const lines = ["prefix", candidate, "tail", "other"];
96
- const output = format(lines.join("\n"), [ambiguous(lines, [2, 4], 6)], 6).text;
97
- if (extra === 0) {
98
- assert.ok(output.includes(`2#${computeLineHash(2, candidate, 6)}│${candidate}\n`));
99
- assert.doesNotMatch(output, /omitted/);
100
- } else {
101
- assert.match(output, /truncated: candidate row limit/);
102
- assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
103
- assert.match(output, /^4#[0-9A-Z]+│other$/m);
104
- }
105
- }
115
+ for (const extra of [0, 1]) {
116
+ const candidate = "x".repeat(4096 - Buffer.byteLength("2#XXXXXX│") + extra);
117
+ const lines = ["prefix", candidate, "tail", "other"];
118
+ const output = format(lines.join("\n"), [ambiguous(lines, [2, 4], 6)], 6).text;
119
+ if (extra === 0) {
120
+ assert.ok(output.includes(`2#${computeLineHash(2, candidate, 6)}│${candidate}\n`));
121
+ assert.doesNotMatch(output, /omitted/);
122
+ } else {
123
+ assert.match(output, /truncated: candidate row limit/);
124
+ assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
125
+ assert.match(output, /^4#[0-9A-Z]+│other$/m);
126
+ }
127
+ }
106
128
  });
107
129
 
108
130
  test("unique candidates inside ambiguous neighborhoods retain the candidate row limit", () => {
109
- const lines = ["prefix", "x".repeat(4096), "match", "match"];
110
- const output = format(lines.join("\n"), [
111
- ambiguous(lines, [3, 4]),
112
- failure({ kind: "found", scope: "local", newLine: 2, newHash: computeLineHash(2, lines[1]) }),
113
- ]).text;
114
- assert.match(output, /truncated: candidate row limit/);
115
- assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
131
+ const lines = ["prefix", "x".repeat(4096), "match", "match"];
132
+ const output = format(lines.join("\n"), [
133
+ ambiguous(lines, [3, 4]),
134
+ failure({ kind: "found", scope: "local", newLine: 2, newHash: computeLineHash(2, lines[1]) }),
135
+ ]).text;
136
+ assert.match(output, /truncated: candidate row limit/);
137
+ assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
116
138
  });
117
139
 
118
140
  test("neighborhoods keep shorter later rows when the remaining budget cannot fit a row", () => {
119
- const lines = ["x".repeat(16 * 1024 - 100), "y".repeat(200), "target", "other"];
120
- const output = format(lines.join("\n"), [ambiguous(lines, [3, 4])]);
121
- assert.deepEqual([...output.shownLines], [1, 3, 4]);
122
- assert.match(output.text, /Candidate-neighborhood rows: 3\/4; 1 omitted/);
123
- const rows = output.text.match(/^\d+#[0-9A-Z]+│.*$/gm) ?? [];
124
- assert.ok(Buffer.byteLength(rows.join("\n") + "\n") <= 16 * 1024);
141
+ const lines = ["x".repeat(16 * 1024 - 100), "y".repeat(200), "target", "other"];
142
+ const output = format(lines.join("\n"), [ambiguous(lines, [3, 4])]);
143
+ assert.deepEqual([...output.shownLines], [1, 3, 4]);
144
+ assert.match(output.text, /Candidate-neighborhood rows: 3\/4; 1 omitted/);
145
+ const rows = output.text.match(/^\d+#[0-9A-Z]+│.*$/gm) ?? [];
146
+ assert.ok(Buffer.byteLength(rows.join("\n") + "\n") <= 16 * 1024);
125
147
  });
@@ -2,70 +2,73 @@ import type { AnchorFormatter } from "./anchor-format.ts";
2
2
  import { splitLines } from "../core/lines.ts";
3
3
  import type { AnchorFailure } from "../core/types.ts";
4
4
  import { mergeRanges } from "../core/ranges.ts";
5
+ import { MAX_BLOCK_BYTES, MAX_RECOVERY_CANDIDATE_BYTES } from "./budgets.ts";
5
6
 
6
7
  const CONTEXT_RADIUS = 3;
7
- const MAX_CONTEXT_BYTES = 16 * 1024;
8
- export const MAX_RECOVERY_CANDIDATE_BYTES = 4 * 1024;
9
8
  export const MAX_AMBIGUOUS_CANDIDATES = 8;
10
9
 
11
10
  type Interval = { lo: number; hi: number };
12
11
  type ContextRow = { line: number; text: string };
13
12
 
14
-
15
13
  function shownIntervals(rows: readonly ContextRow[]): Interval[] {
16
- const intervals: Interval[] = [];
17
- for (const row of rows) {
18
- const previous = intervals.at(-1);
19
- if (previous && row.line === previous.hi + 1) previous.hi = row.line;
20
- else intervals.push({ lo: row.line, hi: row.line });
21
- }
22
- return intervals;
14
+ const intervals: Interval[] = [];
15
+ for (const row of rows) {
16
+ const previous = intervals.at(-1);
17
+ if (previous && row.line === previous.hi + 1) previous.hi = row.line;
18
+ else intervals.push({ lo: row.line, hi: row.line });
19
+ }
20
+ return intervals;
23
21
  }
24
22
 
25
23
  function collectContextRows(
26
- lines: readonly string[],
27
- centers: readonly number[],
28
- anchors: AnchorFormatter,
29
- candidateLines: ReadonlySet<number>,
24
+ lines: readonly string[],
25
+ centers: readonly number[],
26
+ anchors: AnchorFormatter,
27
+ candidateLines: ReadonlySet<number>,
30
28
  ) {
31
- const windows = mergeRanges(centers.map((center) => {
32
- const line = Math.min(lines.length, Math.max(1, center));
33
- return [Math.max(1, line - CONTEXT_RADIUS), Math.min(lines.length, line + CONTEXT_RADIUS) + 1];
34
- }));
35
- const total = windows.reduce((sum, [start, end]) => sum + end - start, 0);
36
- const rows: ContextRow[] = [];
37
- let bytes = 0;
38
- const omissions = new Set<"byte limit" | "candidate row limit">();
29
+ const windows = mergeRanges(
30
+ centers.map((center) => {
31
+ const line = Math.min(lines.length, Math.max(1, center));
32
+ return [
33
+ Math.max(1, line - CONTEXT_RADIUS),
34
+ Math.min(lines.length, line + CONTEXT_RADIUS) + 1,
35
+ ];
36
+ }),
37
+ );
38
+ const total = windows.reduce((sum, [start, end]) => sum + end - start, 0);
39
+ const rows: ContextRow[] = [];
40
+ let bytes = 0;
41
+ const omissions = new Set<"byte limit" | "candidate row limit">();
39
42
 
40
- for (const [start, end] of windows) {
41
- for (let line = start; line < end; line++) {
42
- const content = lines[line - 1];
43
- const text = anchors.row(line, content);
44
- const rowBytes = Buffer.byteLength(text, "utf8");
45
- // Neighborhoods must not bypass the standalone candidate's complete-row limit.
46
- if (candidateLines.has(line) && rowBytes > MAX_RECOVERY_CANDIDATE_BYTES) {
47
- omissions.add("candidate row limit");
48
- continue;
49
- }
50
- if (bytes + rowBytes + 1 > MAX_CONTEXT_BYTES) {
51
- omissions.add("byte limit");
52
- continue;
53
- }
54
- rows.push({ line, text });
55
- bytes += rowBytes + 1;
56
- }
57
- }
58
- return { rows, total, truncatedBy: [...omissions].join(" and ") || undefined };
43
+ for (const [start, end] of windows) {
44
+ for (let line = start; line < end; line++) {
45
+ const content = lines[line - 1];
46
+ const text = anchors.row(line, content);
47
+ const rowBytes = Buffer.byteLength(text, "utf8");
48
+ // Neighborhoods must not bypass the standalone candidate's complete-row limit.
49
+ if (candidateLines.has(line) && rowBytes > MAX_RECOVERY_CANDIDATE_BYTES) {
50
+ omissions.add("candidate row limit");
51
+ continue;
52
+ }
53
+ if (bytes + rowBytes + 1 > MAX_BLOCK_BYTES) {
54
+ omissions.add("byte limit");
55
+ continue;
56
+ }
57
+ rows.push({ line, text });
58
+ bytes += rowBytes + 1;
59
+ }
60
+ }
61
+ return { rows, total, truncatedBy: [...omissions].join(" and ") || undefined };
59
62
  }
60
63
 
61
64
  function formatContextRows(rows: readonly ContextRow[]): string[] {
62
- const body: string[] = [];
63
- let index = 0;
64
- for (const interval of shownIntervals(rows)) {
65
- body.push(`@@ candidate-neighborhood lines ${interval.lo}-${interval.hi} @@`);
66
- while (index < rows.length && rows[index].line <= interval.hi) body.push(rows[index++].text);
67
- }
68
- return body;
65
+ const body: string[] = [];
66
+ let index = 0;
67
+ for (const interval of shownIntervals(rows)) {
68
+ body.push(`@@ candidate-neighborhood lines ${interval.lo}-${interval.hi} @@`);
69
+ while (index < rows.length && rows[index].line <= interval.hi) body.push(rows[index++].text);
70
+ }
71
+ return body;
69
72
  }
70
73
 
71
74
  /**
@@ -73,29 +76,38 @@ function formatContextRows(rows: readonly ContextRow[]): string[] {
73
76
  * @internal Performs no I/O; the edit diagnostic uses shownLines to avoid repeating content.
74
77
  */
75
78
  export function formatAmbiguousCandidateNeighborhoods(
76
- currentText: string,
77
- failures: readonly AnchorFailure[],
78
- anchors: AnchorFormatter,
79
+ currentText: string,
80
+ failures: readonly AnchorFailure[],
81
+ anchors: AnchorFormatter,
79
82
  ): { text: string; shownLines: ReadonlySet<number> } {
80
- const centers = failures.flatMap((failure) => failure.recovery.kind === "ambiguous"
81
- ? failure.recovery.candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES).map(candidate => candidate.line) : []);
82
- if (centers.length === 0) return { text: "", shownLines: new Set() };
83
+ const centers = failures.flatMap((failure) =>
84
+ failure.recovery.kind === "ambiguous"
85
+ ? failure.recovery.candidates
86
+ .slice(0, MAX_AMBIGUOUS_CANDIDATES)
87
+ .map((candidate) => candidate.line)
88
+ : [],
89
+ );
90
+ if (centers.length === 0) return { text: "", shownLines: new Set() };
83
91
 
84
- const lines = splitLines(currentText);
85
- const candidateLines = new Set(centers);
86
- for (const failure of failures) {
87
- if (failure.recovery.kind === "found") candidateLines.add(failure.recovery.newLine);
88
- }
89
- const { rows, total, truncatedBy } = collectContextRows(lines, centers, anchors, candidateLines);
90
- const body = ["Ambiguous-candidate neighborhoods (+/-3; observation only):"];
91
- if (rows.length === 0) {
92
- body.push("No complete neighborhood row fits the limits.");
93
- } else {
94
- body.push(...formatContextRows(rows));
95
- }
96
- if (truncatedBy) {
97
- body.push(`Candidate-neighborhood rows: ${rows.length}/${total}; ${total - rows.length} omitted.`);
98
- body.push(`Candidate neighborhoods truncated: ${truncatedBy} (16384 bytes; candidate row 4096 bytes; lowest lines first).`);
99
- }
100
- return { text: `\n${body.join("\n")}`, shownLines: new Set(rows.map((row) => row.line)) };
92
+ const lines = splitLines(currentText);
93
+ const candidateLines = new Set(centers);
94
+ for (const failure of failures) {
95
+ if (failure.recovery.kind === "found") candidateLines.add(failure.recovery.newLine);
96
+ }
97
+ const { rows, total, truncatedBy } = collectContextRows(lines, centers, anchors, candidateLines);
98
+ const body = ["Ambiguous-candidate neighborhoods (+/-3; observation only):"];
99
+ if (rows.length === 0) {
100
+ body.push("No complete neighborhood row fits the limits.");
101
+ } else {
102
+ body.push(...formatContextRows(rows));
103
+ }
104
+ if (truncatedBy) {
105
+ body.push(
106
+ `Candidate-neighborhood rows: ${rows.length}/${total}; ${total - rows.length} omitted.`,
107
+ );
108
+ body.push(
109
+ `Candidate neighborhoods truncated: ${truncatedBy} (16384 bytes; candidate row 4096 bytes; lowest lines first).`,
110
+ );
111
+ }
112
+ return { text: `\n${body.join("\n")}`, shownLines: new Set(rows.map((row) => row.line)) };
101
113
  }