@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,43 +1,49 @@
1
1
  /**
2
- * Bounded anchor-failure diagnostics for edit: failure details with recovery
3
- * candidates, input-anchor checks, and ambiguous-candidate neighborhoods.
2
+ * Bounded edit failure facts for the error record: anchor failures with their
3
+ * recovery candidates or observed rows, the batch's matched anchors, and
4
+ * ambiguous-candidate neighborhoods.
5
+ *
6
+ * Each fact has one owner. A failure entry states what was cited and what the
7
+ * search found; a shifted candidate's anchor is stated once, beside its
8
+ * `content`; `matched` lists only the anchors that passed, so a mismatch
9
+ * appears once, in `failures`; a row shown in a neighborhood is not repeated
10
+ * in a failure entry. The `observed` and neighborhood rows are observations,
11
+ * not verified targets. Every list has its own byte budget and an explicit
12
+ * omission count. The recovery instruction is the report's `next`, derived
13
+ * from the code in report-schema.ts.
4
14
  *
5
15
  * @module pi-hashline-edit/pi
6
16
  */
7
17
 
8
- import { truncateHead } from "@earendil-works/pi-coding-agent";
9
- import type { AnchorFormatter } from "./anchor-format.ts";
18
+ import { type AnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
10
19
  import { splitLines } from "../core/lines.ts";
11
20
  import type { Anchor, AnchorFailure, ApplyFailure } from "../core/types.ts";
12
21
  import { mergeRanges } from "../core/ranges.ts";
13
- import { formatKiB, MAX_BLOCK_BYTES, MAX_RECOVERY_CANDIDATE_BYTES } from "./budgets.ts";
22
+ import { HashlineError } from "../core/errors.ts";
23
+ import { DEFAULT_OUTPUT_BUDGETS, formatKiB, type OutputBudgets } from "./budgets.ts";
24
+ import { boundedFacts } from "./report.ts";
25
+ import type { AnchorFailureFact, ErrorFacts } from "./report-schema.ts";
26
+
27
+ type MismatchFacts = ErrorFacts<"ANCHOR_MISMATCH">;
14
28
 
15
29
  const CONTEXT_RADIUS = 3;
16
30
  const MAX_AMBIGUOUS_CANDIDATES = 8;
17
31
 
32
+ type Snapshot = Readonly<{ currentText: string; anchors: AnchorFormatter }>;
33
+
18
34
  /** Select the shared candidate prefix for detail lists and observation neighborhoods. */
19
35
  export function selectAmbiguousCandidates(candidates: readonly Anchor[]): readonly Anchor[] {
20
36
  return candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES);
21
37
  }
22
38
 
23
- type Interval = { lo: number; hi: number };
24
39
  type ContextRow = { line: number; text: string };
25
40
 
26
- function shownIntervals(rows: readonly ContextRow[]): Interval[] {
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;
34
- }
35
-
36
41
  function collectContextRows(
37
42
  lines: readonly string[],
38
43
  centers: readonly number[],
39
44
  anchors: AnchorFormatter,
40
45
  candidateLines: ReadonlySet<number>,
46
+ budget: OutputBudgets,
41
47
  ) {
42
48
  const windows = mergeRanges(
43
49
  centers.map((center) => {
@@ -51,210 +57,185 @@ function collectContextRows(
51
57
  const total = windows.reduce((sum, [start, end]) => sum + end - start, 0);
52
58
  const rows: ContextRow[] = [];
53
59
  let bytes = 0;
54
- const omissions = new Set<"byte limit" | "candidate row limit">();
55
60
 
56
61
  for (const [start, end] of windows) {
57
62
  for (let line = start; line < end; line++) {
58
- const content = lines[line - 1];
59
- const text = anchors.row(line, content);
63
+ const text = anchors.row(line, lines[line - 1]);
60
64
  const rowBytes = Buffer.byteLength(text, "utf8");
61
65
  // 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
- }
66
+ if (candidateLines.has(line) && rowBytes > budget.fieldBytes) continue;
67
+ if (bytes + rowBytes + 1 > budget.blockBytes) continue;
70
68
  rows.push({ line, text });
71
69
  bytes += rowBytes + 1;
72
70
  }
73
71
  }
74
- return { rows, total, truncatedBy: [...omissions].join(" and ") || undefined };
72
+ return { rows, omitted: total - rows.length };
75
73
  }
76
74
 
77
- function formatContextRows(rows: readonly ContextRow[]): string[] {
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);
75
+ /** Group shown rows into contiguous neighborhoods; gaps mark omitted rows. */
76
+ function groupContextRows(rows: readonly ContextRow[]) {
77
+ const groups: { lines: string; rows: string[] }[] = [];
78
+ let previous: ContextRow | undefined;
79
+ let first = 0;
80
+ for (const row of rows) {
81
+ if (!previous || row.line !== previous.line + 1) {
82
+ groups.push({ lines: "", rows: [] });
83
+ first = row.line;
84
+ }
85
+ const group = groups[groups.length - 1];
86
+ group.rows.push(row.text);
87
+ group.lines = `${first}-${row.line}`;
88
+ previous = row;
83
89
  }
84
- return body;
90
+ return groups;
85
91
  }
86
92
 
87
93
  /**
88
- * Format observation rows around listed ambiguous candidates and report rows actually shown.
89
- * @internal Performs no I/O; the edit diagnostic uses shownLines to avoid repeating content.
94
+ * Observation rows (±3) around listed ambiguous candidates, lowest lines first,
95
+ * and the lines actually shown so failure entries do not repeat them.
96
+ * @internal Performs no I/O.
90
97
  */
91
- export function formatAmbiguousCandidateNeighborhoods(
98
+ export function ambiguousCandidateNeighborhoods(
92
99
  currentText: string,
93
100
  failures: readonly AnchorFailure[],
94
101
  anchors: AnchorFormatter,
95
- ): { text: string; shownLines: ReadonlySet<number> } {
102
+ budget: OutputBudgets = DEFAULT_OUTPUT_BUDGETS,
103
+ ): {
104
+ facts: Pick<MismatchFacts, "candidateNeighborhoods" | "omittedNeighborhoodRows">;
105
+ shownLines: ReadonlySet<number>;
106
+ } {
96
107
  const centers = failures.flatMap((failure) =>
97
108
  failure.recovery.kind === "ambiguous"
98
109
  ? selectAmbiguousCandidates(failure.recovery.candidates).map((candidate) => candidate.line)
99
110
  : [],
100
111
  );
101
- if (centers.length === 0) return { text: "", shownLines: new Set() };
112
+ if (centers.length === 0) return { facts: {}, shownLines: new Set() };
102
113
 
103
- const lines = splitLines(currentText);
104
114
  const candidateLines = new Set(centers);
105
115
  for (const failure of failures) {
106
116
  if (failure.recovery.kind === "found") candidateLines.add(failure.recovery.newLine);
107
117
  }
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)) };
118
+ const { rows, omitted } = collectContextRows(
119
+ splitLines(currentText),
120
+ centers,
121
+ anchors,
122
+ candidateLines,
123
+ budget,
124
+ );
125
+ return {
126
+ facts: {
127
+ candidateNeighborhoods: groupContextRows(rows),
128
+ ...(omitted ? { omittedNeighborhoodRows: omitted } : {}),
129
+ },
130
+ shownLines: new Set(rows.map((row) => row.line)),
131
+ };
124
132
  }
125
133
 
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;
134
+ const RESULT = { found: "shifted", ambiguous: "ambiguous", none: "unresolved" } as const;
138
135
 
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;
136
+ /** One failure entry: what was cited, then what the search found or what the cited line holds. */
137
+ function failureEntry(
138
+ f: AnchorFailure,
139
+ snapshot: Snapshot,
140
+ currentLines: readonly string[],
141
+ shownLines: Set<number>,
142
+ budget: OutputBudgets,
143
+ ): AnchorFailureFact {
144
+ const rowTooLarge = `row exceeds ${formatKiB(budget.fieldBytes)}`;
145
+ const entry: { -readonly [K in keyof AnchorFailureFact]: AnchorFailureFact[K] } = {
146
+ field: `edits[${f.opIndex}].${f.which}`,
147
+ op: f.op,
148
+ cited: snapshot.anchors.reference(f.cited.line, f.cited.hash),
149
+ result: RESULT[f.recovery.kind],
150
+ };
151
+ if (f.recovery.kind !== "none")
152
+ entry.search = f.recovery.scope === "local" ? "local window" : "full file";
153
+ switch (f.recovery.kind) {
154
+ case "found": {
155
+ const { newLine, newHash } = f.recovery;
156
+ entry.candidate = snapshot.anchors.reference(newLine, newHash);
157
+ if (shownLines.has(newLine)) break;
158
+ const content = currentLines[newLine - 1];
159
+ // The row budget matches the neighborhoods'; the anchor itself is already `candidate`.
160
+ if (
161
+ content !== undefined &&
162
+ Buffer.byteLength(snapshot.anchors.row(newLine, content), "utf8") <= budget.fieldBytes
163
+ ) {
164
+ entry.content = displayCarriageReturns(content);
165
+ shownLines.add(newLine);
166
+ } else {
167
+ entry.contentOmitted = rowTooLarge;
203
168
  }
169
+ break;
170
+ }
171
+ case "ambiguous": {
172
+ const candidates = selectAmbiguousCandidates(f.recovery.candidates);
173
+ entry.candidates = candidates.map((candidate) =>
174
+ snapshot.anchors.reference(candidate.line, candidate.hash),
175
+ );
176
+ const omitted = f.recovery.candidates.length - candidates.length;
177
+ if (omitted) entry.omittedCandidates = omitted;
178
+ break;
179
+ }
180
+ case "none": {
181
+ const row = f.current === null ? null : snapshot.anchors.row(f.cited.line, f.current.content);
182
+ if (row === null) entry.observedOmitted = "cited line is out of range";
183
+ else if (Buffer.byteLength(row, "utf8") <= budget.fieldBytes) entry.observed = row;
184
+ else entry.observedOmitted = rowTooLarge;
185
+ break;
204
186
  }
205
187
  }
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
- );
188
+ return entry;
219
189
  }
220
190
 
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.`,
191
+ /**
192
+ * The batch's anchors whose checksum matched, by field. An anchor absent from
193
+ * both `matched` and `failures` is counted as omitted, never implied matched.
194
+ */
195
+ function matchedAnchorFacts(
196
+ failure: ApplyFailure,
197
+ budget: OutputBudgets,
198
+ ): Pick<MismatchFacts, "matched" | "omittedMatched"> {
199
+ const { kept, omitted } = boundedFacts(
200
+ failure.checks
201
+ .filter((check) => check.status === "matched")
202
+ .map((check) => `edits[${check.opIndex}].${check.which}`),
203
+ budget.blockBytes,
234
204
  );
205
+ return kept.length || omitted
206
+ ? { matched: kept, ...(omitted ? { omittedMatched: omitted } : {}) }
207
+ : {};
235
208
  }
236
209
 
237
- /** Keep validation status and observation context visible even when failure details are truncated. */
238
- export function formatFailure(
210
+ /** Classify a rejected edit batch with its bounded facts. */
211
+ export function describeEditFailure(
239
212
  failure: ApplyFailure,
240
- snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
213
+ snapshot: Snapshot,
241
214
  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}`;
215
+ budget: OutputBudgets = DEFAULT_OUTPUT_BUDGETS,
216
+ ): HashlineError<"ANCHOR_MISMATCH" | "INVALID_RANGE" | "OVERLAPPING_EDITS"> {
217
+ const matched = isBatch ? matchedAnchorFacts(failure, budget) : {};
218
+ if (failure.kind === "range")
219
+ return new HashlineError(failure.code, failure.message, { facts: matched });
220
+
221
+ const neighborhoods = ambiguousCandidateNeighborhoods(
222
+ snapshot.currentText,
223
+ failure.failures,
224
+ snapshot.anchors,
225
+ budget,
226
+ );
227
+ const currentLines = splitLines(snapshot.currentText);
228
+ const shownLines = new Set(neighborhoods.shownLines);
229
+ const { kept, omitted } = boundedFacts(
230
+ failure.failures.map((f) => failureEntry(f, snapshot, currentLines, shownLines, budget)),
231
+ budget.blockBytes,
232
+ );
233
+ return new HashlineError("ANCHOR_MISMATCH", "Anchors did not match the current file.", {
234
+ facts: {
235
+ failures: kept,
236
+ ...(omitted ? { omittedFailures: omitted } : {}),
237
+ ...matched,
238
+ ...neighborhoods.facts,
239
+ },
240
+ });
260
241
  }