@criogaid/pi-hashline-edit 0.3.1 → 0.5.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 (75) hide show
  1. package/README.md +166 -61
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +459 -313
  4. package/src/core/apply.ts +251 -215
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +61 -23
  7. package/src/core/hash.ts +49 -20
  8. package/src/core/lines.test.ts +46 -27
  9. package/src/core/lines.ts +36 -28
  10. package/src/core/ranges.test.ts +73 -19
  11. package/src/core/ranges.ts +15 -15
  12. package/src/core/replace.ts +109 -0
  13. package/src/core/text.test.ts +3 -3
  14. package/src/core/text.ts +26 -9
  15. package/src/core/types.ts +56 -41
  16. package/src/index.ts +23 -19
  17. package/src/integration/config-registration.test.ts +206 -0
  18. package/src/integration/grep-rg.test.ts +879 -251
  19. package/src/integration/large-text.test.ts +63 -0
  20. package/src/integration/replace-package.test.ts +41 -0
  21. package/src/pi/action-fusion.test.ts +612 -207
  22. package/src/pi/action-fusion.ts +442 -254
  23. package/src/pi/anchor-format.test.ts +53 -21
  24. package/src/pi/anchor-format.ts +48 -20
  25. package/src/pi/budgets.ts +25 -0
  26. package/src/pi/config.test.ts +178 -35
  27. package/src/pi/config.ts +96 -37
  28. package/src/pi/directory-sync.test.ts +55 -0
  29. package/src/pi/e2e-scenarios.test.ts +360 -0
  30. package/src/pi/edit-tool.ts +307 -279
  31. package/src/pi/error-text.ts +26 -0
  32. package/src/pi/execute.test.ts +1718 -713
  33. package/src/pi/failure-context.test.ts +110 -83
  34. package/src/pi/failure-context.ts +232 -73
  35. package/src/pi/failure-path.test.ts +180 -66
  36. package/src/pi/file-commit.test.ts +446 -233
  37. package/src/pi/file-commit.ts +348 -203
  38. package/src/pi/fusion-card.test.ts +118 -83
  39. package/src/pi/fusion-card.ts +203 -87
  40. package/src/pi/grep-output.ts +225 -0
  41. package/src/pi/grep-render.ts +59 -0
  42. package/src/pi/grep-scope.ts +139 -0
  43. package/src/pi/grep-search.ts +231 -0
  44. package/src/pi/grep-tool.ts +215 -774
  45. package/src/pi/grep.test.ts +825 -376
  46. package/src/pi/mutation-outcome.testing.ts +22 -0
  47. package/src/pi/mutation-result.test.ts +86 -0
  48. package/src/pi/mutation-result.ts +118 -63
  49. package/src/pi/mutation-runner.ts +151 -0
  50. package/src/pi/path.ts +20 -12
  51. package/src/pi/pi.test.ts +100 -52
  52. package/src/pi/read-tool.ts +245 -134
  53. package/src/pi/registration.test.ts +271 -114
  54. package/src/pi/render.test.ts +227 -84
  55. package/src/pi/render.ts +86 -116
  56. package/src/pi/replace-regex.ts +54 -0
  57. package/src/pi/replace-tool.ts +247 -241
  58. package/src/pi/replace-worker.mjs +4 -0
  59. package/src/pi/replace-worker.ts +10 -0
  60. package/src/pi/replace.test.ts +778 -390
  61. package/src/pi/result-safety.test.ts +821 -344
  62. package/src/pi/rg-line-ranges.test.ts +57 -31
  63. package/src/pi/rg-line-ranges.ts +45 -82
  64. package/src/pi/rg-process.test.ts +113 -0
  65. package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
  66. package/src/pi/rg-text-view.ts +102 -48
  67. package/src/pi/schema.ts +19 -0
  68. package/src/pi/text-stream.test.ts +118 -0
  69. package/src/pi/text-stream.ts +136 -0
  70. package/src/pi/tool-call.testing.ts +37 -0
  71. package/src/pi/write-tool.ts +114 -52
  72. package/src/pi/write.test.ts +250 -97
  73. package/src/core/index.ts +0 -14
  74. package/src/pi/rg-line-filter.test.ts +0 -85
  75. package/src/pi/state.ts +0 -26
@@ -6,120 +6,147 @@ 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, 4)}│${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({
135
+ kind: "found",
136
+ scope: "local",
137
+ newLine: 2,
138
+ newHash: computeLineHash(2, lines[1], 4),
139
+ }),
140
+ ]).text;
141
+ assert.match(output, /truncated: candidate row limit/);
142
+ assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
116
143
  });
117
144
 
118
145
  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);
146
+ const lines = ["x".repeat(16 * 1024 - 100), "y".repeat(200), "target", "other"];
147
+ const output = format(lines.join("\n"), [ambiguous(lines, [3, 4])]);
148
+ assert.deepEqual([...output.shownLines], [1, 3, 4]);
149
+ assert.match(output.text, /Candidate-neighborhood rows: 3\/4; 1 omitted/);
150
+ const rows = output.text.match(/^\d+#[0-9A-Z]+│.*$/gm) ?? [];
151
+ assert.ok(Buffer.byteLength(rows.join("\n") + "\n") <= 16 * 1024);
125
152
  });
@@ -1,71 +1,87 @@
1
+ /**
2
+ * Bounded anchor-failure diagnostics for edit: failure details with recovery
3
+ * candidates, input-anchor checks, and ambiguous-candidate neighborhoods.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
7
+
8
+ import { truncateHead } from "@earendil-works/pi-coding-agent";
1
9
  import type { AnchorFormatter } from "./anchor-format.ts";
2
10
  import { splitLines } from "../core/lines.ts";
3
- import type { AnchorFailure } from "../core/types.ts";
11
+ import type { Anchor, AnchorFailure, ApplyFailure } from "../core/types.ts";
4
12
  import { mergeRanges } from "../core/ranges.ts";
13
+ import { formatKiB, MAX_BLOCK_BYTES, MAX_RECOVERY_CANDIDATE_BYTES } from "./budgets.ts";
5
14
 
6
15
  const CONTEXT_RADIUS = 3;
7
- const MAX_CONTEXT_BYTES = 16 * 1024;
8
- export const MAX_RECOVERY_CANDIDATE_BYTES = 4 * 1024;
9
- export const MAX_AMBIGUOUS_CANDIDATES = 8;
16
+ const MAX_AMBIGUOUS_CANDIDATES = 8;
17
+
18
+ /** Select the shared candidate prefix for detail lists and observation neighborhoods. */
19
+ export function selectAmbiguousCandidates(candidates: readonly Anchor[]): readonly Anchor[] {
20
+ return candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES);
21
+ }
10
22
 
11
23
  type Interval = { lo: number; hi: number };
12
24
  type ContextRow = { line: number; text: string };
13
25
 
14
-
15
26
  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;
27
+ const intervals: Interval[] = [];
28
+ for (const row of rows) {
29
+ const previous = intervals.at(-1);
30
+ if (previous && row.line === previous.hi + 1) previous.hi = row.line;
31
+ else intervals.push({ lo: row.line, hi: row.line });
32
+ }
33
+ return intervals;
23
34
  }
24
35
 
25
36
  function collectContextRows(
26
- lines: readonly string[],
27
- centers: readonly number[],
28
- anchors: AnchorFormatter,
29
- candidateLines: ReadonlySet<number>,
37
+ lines: readonly string[],
38
+ centers: readonly number[],
39
+ anchors: AnchorFormatter,
40
+ candidateLines: ReadonlySet<number>,
30
41
  ) {
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">();
42
+ const windows = mergeRanges(
43
+ centers.map((center) => {
44
+ const line = Math.min(lines.length, Math.max(1, center));
45
+ return [
46
+ Math.max(1, line - CONTEXT_RADIUS),
47
+ Math.min(lines.length, line + CONTEXT_RADIUS) + 1,
48
+ ];
49
+ }),
50
+ );
51
+ const total = windows.reduce((sum, [start, end]) => sum + end - start, 0);
52
+ const rows: ContextRow[] = [];
53
+ let bytes = 0;
54
+ const omissions = new Set<"byte limit" | "candidate row limit">();
39
55
 
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 };
56
+ for (const [start, end] of windows) {
57
+ for (let line = start; line < end; line++) {
58
+ const content = lines[line - 1];
59
+ const text = anchors.row(line, content);
60
+ const rowBytes = Buffer.byteLength(text, "utf8");
61
+ // Neighborhoods must not bypass the standalone candidate's complete-row limit.
62
+ if (candidateLines.has(line) && rowBytes > MAX_RECOVERY_CANDIDATE_BYTES) {
63
+ omissions.add("candidate row limit");
64
+ continue;
65
+ }
66
+ if (bytes + rowBytes + 1 > MAX_BLOCK_BYTES) {
67
+ omissions.add("byte limit");
68
+ continue;
69
+ }
70
+ rows.push({ line, text });
71
+ bytes += rowBytes + 1;
72
+ }
73
+ }
74
+ return { rows, total, truncatedBy: [...omissions].join(" and ") || undefined };
59
75
  }
60
76
 
61
77
  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;
78
+ const body: string[] = [];
79
+ let index = 0;
80
+ for (const interval of shownIntervals(rows)) {
81
+ body.push(`@@ candidate-neighborhood lines ${interval.lo}-${interval.hi} @@`);
82
+ while (index < rows.length && rows[index].line <= interval.hi) body.push(rows[index++].text);
83
+ }
84
+ return body;
69
85
  }
70
86
 
71
87
  /**
@@ -73,29 +89,172 @@ function formatContextRows(rows: readonly ContextRow[]): string[] {
73
89
  * @internal Performs no I/O; the edit diagnostic uses shownLines to avoid repeating content.
74
90
  */
75
91
  export function formatAmbiguousCandidateNeighborhoods(
76
- currentText: string,
77
- failures: readonly AnchorFailure[],
78
- anchors: AnchorFormatter,
92
+ currentText: string,
93
+ failures: readonly AnchorFailure[],
94
+ anchors: AnchorFormatter,
79
95
  ): { 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() };
96
+ const centers = failures.flatMap((failure) =>
97
+ failure.recovery.kind === "ambiguous"
98
+ ? selectAmbiguousCandidates(failure.recovery.candidates).map((candidate) => candidate.line)
99
+ : [],
100
+ );
101
+ if (centers.length === 0) return { text: "", shownLines: new Set() };
102
+
103
+ const lines = splitLines(currentText);
104
+ const candidateLines = new Set(centers);
105
+ for (const failure of failures) {
106
+ if (failure.recovery.kind === "found") candidateLines.add(failure.recovery.newLine);
107
+ }
108
+ const { rows, total, truncatedBy } = collectContextRows(lines, centers, anchors, candidateLines);
109
+ const body = [`Ambiguous-candidate neighborhoods (+/-${CONTEXT_RADIUS}; observation only):`];
110
+ if (rows.length === 0) {
111
+ body.push("No complete neighborhood row fits the limits.");
112
+ } else {
113
+ body.push(...formatContextRows(rows));
114
+ }
115
+ if (truncatedBy) {
116
+ body.push(
117
+ `Candidate-neighborhood rows: ${rows.length}/${total}; ${total - rows.length} omitted.`,
118
+ );
119
+ body.push(
120
+ `Candidate neighborhoods truncated: ${truncatedBy} (${formatKiB(MAX_BLOCK_BYTES)}; candidate row ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}; lowest lines first).`,
121
+ );
122
+ }
123
+ return { text: `\n${body.join("\n")}`, shownLines: new Set(rows.map((row) => row.line)) };
124
+ }
125
+
126
+ /** Keep independent byte budgets for failure details and input-anchor checks. */
127
+ function boundDiagnostic(message: string, notice: string): string {
128
+ const bounded = truncateHead(message, { maxBytes: MAX_BLOCK_BYTES - Buffer.byteLength(notice) });
129
+ return bounded.content + (bounded.truncated ? notice : "");
130
+ }
131
+ /** Format failure mappings and complete unique-candidate rows within the detail budget. */
132
+ function formatFailureDetails(
133
+ failure: ApplyFailure,
134
+ snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
135
+ candidateLines: ReadonlySet<number>,
136
+ ): string {
137
+ if (failure.kind !== "anchor") return failure.message;
138
+
139
+ const lines: string[] = [];
140
+ const currentLines = splitLines(snapshot.currentText);
141
+ const shownCandidates = new Set(candidateLines);
142
+ let found = 0;
143
+ let ambiguous = 0;
144
+ let none = 0;
145
+ for (const f of failure.failures) {
146
+ if (f.recovery.kind === "found") found++;
147
+ else if (f.recovery.kind === "ambiguous") ambiguous++;
148
+ else none++;
149
+ const where = `op #${f.opIndex} ${f.op} ${f.which} (line ${f.cited.line})`;
150
+ const search =
151
+ f.recovery.kind === "none"
152
+ ? ""
153
+ : f.recovery.scope === "local"
154
+ ? "Search: local; matches outside the window were not checked."
155
+ : "Search: full file.";
156
+ switch (f.recovery.kind) {
157
+ case "found": {
158
+ const content = currentLines[f.recovery.newLine - 1];
159
+ const candidate = snapshot.anchors.reference(f.recovery.newLine, f.recovery.newHash);
160
+ const row =
161
+ content === undefined ? candidate : snapshot.anchors.row(f.recovery.newLine, content);
162
+ let detail = `• ${where}: checksum-matching candidate ${candidate}. ${search}`;
163
+ if (!shownCandidates.has(f.recovery.newLine)) {
164
+ if (
165
+ content !== undefined &&
166
+ Buffer.byteLength(row, "utf8") <= MAX_RECOVERY_CANDIDATE_BYTES
167
+ ) {
168
+ detail += `\n${row}`;
169
+ shownCandidates.add(f.recovery.newLine);
170
+ } else {
171
+ detail += ` Candidate content exceeds ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}.`;
172
+ }
173
+ }
174
+ lines.push(detail);
175
+ break;
176
+ }
177
+ case "ambiguous": {
178
+ const candidates = selectAmbiguousCandidates(f.recovery.candidates);
179
+ const list = candidates
180
+ .map((candidate) => `"${snapshot.anchors.reference(candidate.line, candidate.hash)}"`)
181
+ .join(" / ");
182
+ const omitted = f.recovery.candidates.length - candidates.length;
183
+ const more = omitted ? ` (${omitted} more candidates omitted)` : "";
184
+ lines.push(`• ${where}: ambiguous checksum matches: ${list}${more}. ${search}`);
185
+ break;
186
+ }
187
+ case "none": {
188
+ const row =
189
+ f.current === null ? null : snapshot.anchors.row(f.cited.line, f.current.content);
190
+ if (row !== null && Buffer.byteLength(row, "utf8") <= MAX_RECOVERY_CANDIDATE_BYTES) {
191
+ lines.push(
192
+ `• ${where}: no checksum-matching candidate found. Current cited line (validation snapshot; observation only):\n${row}\nConfirm this is the intended target before reusing its anchor directly; retries revalidate.`,
193
+ );
194
+ } else {
195
+ lines.push(
196
+ `• ${where}: no checksum-matching candidate found. Use read or grep to inspect the current file before retrying.` +
197
+ (f.current === null
198
+ ? " Cited line is out of range."
199
+ : ` Current row exceeds ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}.`),
200
+ );
201
+ }
202
+ break;
203
+ }
204
+ }
205
+ }
206
+ const parts: string[] = [];
207
+ if (found) parts.push(`${found} shifted`);
208
+ if (ambiguous) parts.push(`${ambiguous} ambiguous`);
209
+ if (none) parts.push(`${none} unresolved`);
210
+ const message = [
211
+ `Anchor mismatch: ${parts.join(", ")}.`,
212
+ "No changes written by this edit batch.",
213
+ ...lines,
214
+ ].join("\n");
215
+ return boundDiagnostic(
216
+ message,
217
+ `\nDiagnostic output truncated at ${formatKiB(MAX_BLOCK_BYTES)}.`,
218
+ );
219
+ }
220
+
221
+ function formatAnchorChecks(failure: ApplyFailure, anchors: AnchorFormatter): string {
222
+ const rows = failure.checks.map(
223
+ (check) =>
224
+ `op ${check.opIndex} / ${check.which} / ${anchors.reference(check.cited.line, check.cited.hash)} / ${check.status}`,
225
+ );
226
+ const message = [
227
+ "Input-anchor checks (this snapshot):",
228
+ ...rows,
229
+ "Anchor checks only; retries revalidate.",
230
+ ].join("\n");
231
+ return boundDiagnostic(
232
+ message,
233
+ `\nAnchor-check output truncated at ${formatKiB(MAX_BLOCK_BYTES)}; omitted entries are not implied matched.`,
234
+ );
235
+ }
83
236
 
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)) };
237
+ /** Keep validation status and observation context visible even when failure details are truncated. */
238
+ export function formatFailure(
239
+ failure: ApplyFailure,
240
+ snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
241
+ isBatch: boolean,
242
+ ): string {
243
+ const candidateNeighborhoods =
244
+ failure.kind === "anchor"
245
+ ? formatAmbiguousCandidateNeighborhoods(
246
+ snapshot.currentText,
247
+ failure.failures,
248
+ snapshot.anchors,
249
+ )
250
+ : { text: "", shownLines: new Set<number>() };
251
+ const guidance =
252
+ failure.kind === "anchor"
253
+ ? "\nCheck the intended target before retrying; use read or grep for omitted or additional context."
254
+ : "";
255
+ const anchorChecks =
256
+ isBatch && failure.checks.length > 0
257
+ ? `\n${formatAnchorChecks(failure, snapshot.anchors)}`
258
+ : "";
259
+ return `${formatFailureDetails(failure, snapshot, candidateNeighborhoods.shownLines)}${anchorChecks}${candidateNeighborhoods.text}${guidance}`;
101
260
  }