@criogaid/pi-hashline-edit 0.9.0 → 0.11.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 (131) hide show
  1. package/README.md +12 -12
  2. package/README.zh-CN.md +12 -12
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +96 -271
  7. package/src/core/apply.ts +62 -169
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.test.ts +2 -3
  10. package/src/core/character-set.ts +5 -5
  11. package/src/core/errors.test.ts +23 -7
  12. package/src/core/errors.ts +32 -5
  13. package/src/core/hash.test.ts +8 -16
  14. package/src/core/hash.ts +3 -23
  15. package/src/core/lines.ts +2 -4
  16. package/src/core/ranges.test.ts +2 -1
  17. package/src/core/ranges.ts +1 -1
  18. package/src/core/regex.ts +3 -4
  19. package/src/core/replace.test.ts +47 -1
  20. package/src/core/replace.ts +19 -13
  21. package/src/core/search-analysis.test.ts +24 -27
  22. package/src/core/search-analysis.ts +34 -65
  23. package/src/core/search-matrix.testing.ts +0 -2
  24. package/src/core/search.ts +1 -1
  25. package/src/core/text.test.ts +5 -5
  26. package/src/core/text.ts +5 -12
  27. package/src/core/types.ts +8 -44
  28. package/src/index.ts +8 -8
  29. package/src/integration/config-registration.test.ts +8 -10
  30. package/src/integration/fusion-dispatch.test.ts +4 -7
  31. package/src/integration/grep-errors.test.ts +3 -3
  32. package/src/integration/grep-flags.test.ts +5 -19
  33. package/src/integration/grep-js-completeness.test.ts +45 -18
  34. package/src/integration/grep-line-candidates.test.ts +7 -10
  35. package/src/integration/grep-matrix.test.ts +6 -9
  36. package/src/integration/grep-order.test.ts +4 -4
  37. package/src/integration/grep-path-matrix.test.ts +10 -9
  38. package/src/integration/grep-prefilter-coverage.test.ts +5 -8
  39. package/src/integration/grep-process-limits.test.ts +76 -0
  40. package/src/integration/grep-regex.test.ts +10 -10
  41. package/src/integration/grep-rg.test.ts +166 -66
  42. package/src/integration/grep-scan-budget.test.ts +9 -9
  43. package/src/integration/grep-translation.test.ts +18 -32
  44. package/src/integration/large-text.test.ts +6 -52
  45. package/src/integration/model-budget-lifecycle.test.ts +10 -9
  46. package/src/integration/mutation-file-types.testing.ts +4 -4
  47. package/src/integration/npm-package.testing.ts +3 -3
  48. package/src/integration/publication-read-changes.test.ts +161 -83
  49. package/src/integration/read-changes.test.ts +4 -4
  50. package/src/integration/replace-worker-boundary.test.ts +22 -12
  51. package/src/integration/report-replay.test.ts +23 -26
  52. package/src/integration/utf8-errors.test.ts +4 -4
  53. package/src/pi/AGENTS.md +18 -17
  54. package/src/pi/action-fusion.test.ts +241 -353
  55. package/src/pi/action-fusion.testing.ts +38 -0
  56. package/src/pi/action-fusion.ts +150 -125
  57. package/src/pi/anchor-format.test.ts +9 -9
  58. package/src/pi/anchor-format.ts +6 -8
  59. package/src/pi/argument-diagnostics.ts +25 -28
  60. package/src/pi/argument-error.ts +2 -1
  61. package/src/pi/argument-format.test.ts +19 -18
  62. package/src/pi/argument-validation.test.ts +334 -283
  63. package/src/pi/argument-validation.ts +5 -8
  64. package/src/pi/budgets.ts +6 -8
  65. package/src/pi/codemode.test.ts +7 -2
  66. package/src/pi/config.test.ts +7 -3
  67. package/src/pi/config.ts +12 -9
  68. package/src/pi/diagnostic-buffer.test.ts +34 -13
  69. package/src/pi/diagnostic-buffer.ts +1 -2
  70. package/src/pi/directory-sync.test.ts +0 -1
  71. package/src/pi/edit-tool.ts +86 -211
  72. package/src/pi/error-text.ts +10 -9
  73. package/src/pi/execute.test.ts +249 -345
  74. package/src/pi/failure-context.test.ts +146 -127
  75. package/src/pi/failure-context.ts +45 -94
  76. package/src/pi/failure-path.test.ts +182 -155
  77. package/src/pi/file-commit.test.ts +156 -71
  78. package/src/pi/file-commit.ts +126 -146
  79. package/src/pi/file-snapshot.test.ts +3 -5
  80. package/src/pi/fusion-card.test.ts +26 -22
  81. package/src/pi/fusion-card.ts +16 -24
  82. package/src/pi/grep-candidates.test.ts +19 -120
  83. package/src/pi/grep-candidates.ts +25 -76
  84. package/src/pi/grep-matrix.test.ts +5 -5
  85. package/src/pi/grep-order.test.ts +16 -15
  86. package/src/pi/grep-output.ts +94 -107
  87. package/src/pi/grep-render.ts +1 -1
  88. package/src/pi/grep-reread.ts +97 -0
  89. package/src/pi/grep-rg.testing.ts +70 -0
  90. package/src/pi/grep-scope.ts +41 -43
  91. package/src/pi/grep-search.ts +27 -39
  92. package/src/pi/grep-tool.ts +63 -106
  93. package/src/pi/grep.test.ts +177 -156
  94. package/src/pi/model-budgets.test.ts +27 -24
  95. package/src/pi/model-budgets.ts +6 -38
  96. package/src/pi/mutation-outcome.testing.ts +0 -1
  97. package/src/pi/mutation-result.test.ts +44 -35
  98. package/src/pi/mutation-result.ts +52 -21
  99. package/src/pi/mutation-runner.ts +134 -74
  100. package/src/pi/output-budgets.test.ts +86 -42
  101. package/src/pi/path.ts +1 -1
  102. package/src/pi/pi.test.ts +18 -13
  103. package/src/pi/read-tool.ts +18 -23
  104. package/src/pi/read.test.ts +22 -41
  105. package/src/pi/regex-worker-contract.ts +3 -13
  106. package/src/pi/regex-worker.ts +1 -10
  107. package/src/pi/registration.test.ts +85 -51
  108. package/src/pi/render.test.ts +88 -59
  109. package/src/pi/render.ts +64 -65
  110. package/src/pi/replace-regex.ts +14 -2
  111. package/src/pi/replace-tool.ts +22 -94
  112. package/src/pi/replace-worker.ts +1 -1
  113. package/src/pi/replace.test.ts +53 -38
  114. package/src/pi/report-cause.ts +3 -8
  115. package/src/pi/report-failure.testing.ts +10 -3
  116. package/src/pi/report-schema.ts +251 -148
  117. package/src/pi/report.test.ts +215 -67
  118. package/src/pi/report.ts +50 -98
  119. package/src/pi/result-safety.test.ts +241 -247
  120. package/src/pi/rg-process.test.ts +77 -63
  121. package/src/pi/rg-process.ts +53 -75
  122. package/src/pi/rg-regex.ts +40 -400
  123. package/src/pi/schema.ts +35 -0
  124. package/src/pi/text-stream.test.ts +0 -21
  125. package/src/pi/text-stream.ts +14 -21
  126. package/src/pi/tool-factories.testing.ts +59 -0
  127. package/src/pi/write-tool.ts +36 -71
  128. package/src/pi/write.test.ts +31 -34
  129. package/src/testing/regex-translation-corpus.ts +12 -12
  130. package/src/testing/run-tests.ts +1 -1
  131. package/src/pi/replace-worker-contract.ts +0 -10
@@ -2,12 +2,15 @@ import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
3
  import { computeLineHash } from "../core/hash.ts";
4
4
  import { applyEdits } from "../core/apply.ts";
5
+ import { HashlineError } from "../core/errors.ts";
5
6
  import type { AnchorFailure, Edit } from "../core/types.ts";
6
- import { formatByteSize, DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
7
- import { DEFAULT_CONFIG } from "./config.ts";
7
+ import { formatByteSize, outputBudgetsFor } from "./budgets.ts";
8
+ import { DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
9
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
8
10
  import { createAnchorFormatter } from "./anchor-format.ts";
9
- import { ambiguousCandidateNeighborhoods, describeEditFailure } from "./failure-context.ts";
10
- import { describeFailure, renderReport } from "./report.ts";
11
+ import { describeEditFailure } from "./failure-context.ts";
12
+ import { describeMutationFailure } from "./mutation-result.ts";
13
+ import { renderReport } from "./report.ts";
11
14
 
12
15
  function failure(recovery: AnchorFailure["recovery"]): AnchorFailure {
13
16
  return {
@@ -16,13 +19,11 @@ function failure(recovery: AnchorFailure["recovery"]): AnchorFailure {
16
19
  op: "replace",
17
20
  cited: { line: 1, hash: "OLD" },
18
21
  recovery,
19
- current: null,
20
22
  };
21
23
  }
22
24
  function ambiguous(lines: readonly string[], positions: number[], hashLen = 4): AnchorFailure {
23
25
  return failure({
24
26
  kind: "ambiguous",
25
- scope: "local",
26
27
  candidates: positions.map((line) => ({
27
28
  line,
28
29
  hash: computeLineHash(line, lines[line - 1], hashLen),
@@ -30,33 +31,41 @@ function ambiguous(lines: readonly string[], positions: number[], hashLen = 4):
30
31
  });
31
32
  }
32
33
  function neighborhoods(text: string, failures: readonly AnchorFailure[], hashLen = 4) {
33
- return ambiguousCandidateNeighborhoods(
34
+ const error = describeEditFailure(
34
35
  text,
35
36
  failures,
36
37
  createAnchorFormatter(hashLen),
37
38
  DEFAULT_OUTPUT_BUDGETS,
38
39
  );
40
+ assert.equal(error.errorCode, "ANCHOR_MISMATCH");
41
+ assert.ok(error.facts);
42
+ assert.equal(error.facts.failures.length, failures.length);
43
+ assert.equal(error.facts.omittedFailures, undefined);
44
+ return error.facts;
39
45
  }
40
46
  function rows(result: ReturnType<typeof neighborhoods>) {
41
- return result.facts.candidateNeighborhoods?.flatMap((group) => group.rows) ?? [];
47
+ return result.candidateNeighborhoods?.flatMap((group) => group.rows) ?? [];
42
48
  }
43
49
 
44
50
  test("unique and unresolved failures → no ambiguous neighborhoods", () => {
45
- const failures = [
46
- failure({ kind: "found", scope: "local", newLine: 2, newHash: "NEW" }),
47
- failure({ kind: "none" }),
48
- ];
49
- for (const text of ["a\nb\nc\n", ""]) {
50
- assert.deepEqual(neighborhoods(text, failures), { facts: {}, shownLines: new Set() });
51
+ for (const { text, failures } of [
52
+ {
53
+ text: "a\nb\nc\n",
54
+ failures: [failure({ kind: "found", newLine: 2, newHash: "NEW" }), failure({ kind: "none" })],
55
+ },
56
+ { text: "", failures: [failure({ kind: "none" })] },
57
+ ]) {
58
+ const facts = neighborhoods(text, failures);
59
+ assert.equal(facts.candidateNeighborhoods, undefined);
60
+ assert.equal(facts.omittedNeighborhoodRows, undefined);
51
61
  }
52
62
  });
53
63
 
54
64
  test("ambiguous CRLF and BOM context → merges sorted windows with copyable anchors", () => {
55
65
  const lines = ["\uFEFFfirst", "a", "", "c", "d", "e", "f", "last"];
56
66
  const result = neighborhoods(lines.join("\r\n"), [ambiguous(lines, [6, 2], 6)], 6);
57
- assert.deepEqual([...result.shownLines], [1, 2, 3, 4, 5, 6, 7, 8]);
58
67
  assert.deepEqual(
59
- result.facts.candidateNeighborhoods?.map((group) => group.lines),
68
+ result.candidateNeighborhoods?.map((group) => group.lines),
60
69
  ["1-8"],
61
70
  );
62
71
  assert.deepEqual(
@@ -66,25 +75,25 @@ test("ambiguous CRLF and BOM context → merges sorted windows with copyable anc
66
75
  ),
67
76
  );
68
77
  assert.doesNotMatch(rows(result).join("\n"), /\r/);
69
- assert.equal(result.facts.omittedNeighborhoodRows, undefined);
78
+ assert.equal(result.omittedNeighborhoodRows, undefined);
70
79
  });
71
80
 
72
81
  test("ambiguous candidates at BOF and EOF → clipped windows without padding", () => {
73
82
  const lines = Array.from({ length: 10 }, (_, index) => `${index + 1}`);
74
83
  const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [1, 10])]);
75
84
  assert.deepEqual(
76
- result.facts.candidateNeighborhoods?.map((group) => group.lines),
85
+ result.candidateNeighborhoods?.map((group) => group.lines),
77
86
  ["1-4", "7-10"],
78
87
  );
79
88
  assert.equal(rows(result).length, 8);
80
- assert.equal(result.facts.omittedNeighborhoodRows, undefined);
89
+ assert.equal(result.omittedNeighborhoodRows, undefined);
81
90
  });
82
91
 
83
92
  test("more than forty context rows and repeated windows → no row cap or duplication", () => {
84
93
  const lines = Array.from({ length: 60 }, (_, index) => `line-${index + 1}`);
85
94
  const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [4, 14, 24, 34, 44, 54])]);
86
95
  assert.equal(rows(result).length, 42);
87
- assert.equal(result.facts.omittedNeighborhoodRows, undefined);
96
+ assert.equal(result.omittedNeighborhoodRows, undefined);
88
97
  const repeated = neighborhoods(
89
98
  lines.join("\n"),
90
99
  Array.from({ length: 50 }, (_, opIndex) => ({ ...ambiguous(lines, [4, 5]), opIndex })),
@@ -122,18 +131,18 @@ test("neighborhood exceeds byte budget → whole rows and explicit omission coun
122
131
  const result = neighborhoods(lines.join("\n"), [
123
132
  ambiguous(lines, [lines.length - 1, lines.length]),
124
133
  ]);
125
- assert.deepEqual([...result.shownLines], shown);
126
- assert.equal(result.facts.omittedNeighborhoodRows, omitted);
134
+ assert.deepEqual(
135
+ rows(result),
136
+ shown.map(
137
+ (position) =>
138
+ `${position}#${computeLineHash(position, lines[position - 1], 4)}│${lines[position - 1]}`,
139
+ ),
140
+ );
141
+ assert.equal(result.omittedNeighborhoodRows, omitted);
127
142
  assert.ok(
128
143
  Buffer.byteLength(rows(result).join("\n") + (rows(result).length ? "\n" : "")) <=
129
144
  DEFAULT_OUTPUT_BUDGETS.blockBytes,
130
145
  );
131
- for (const position of shown)
132
- assert.ok(
133
- rows(result).includes(
134
- `${position}#${computeLineHash(position, lines[position - 1], 4)}│${lines[position - 1]}`,
135
- ),
136
- );
137
146
  }
138
147
  });
139
148
 
@@ -144,9 +153,12 @@ test("candidate complete row at its byte limit → kept exactly or omitted whole
144
153
  );
145
154
  const lines = ["prefix", candidate, "tail", "other"];
146
155
  const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [2, 4], 6)], 6);
147
- assert.equal(result.shownLines.has(2), extra === 0);
148
- assert.equal(result.facts.omittedNeighborhoodRows, extra === 0 ? undefined : 1);
149
- assert.ok(result.shownLines.has(4));
156
+ assert.equal(
157
+ rows(result).some((row) => row.startsWith("2#")),
158
+ extra === 0,
159
+ );
160
+ assert.equal(result.omittedNeighborhoodRows, extra === 0 ? undefined : 1);
161
+ assert.ok(rows(result).some((row) => row.startsWith("4#")));
150
162
  }
151
163
  });
152
164
 
@@ -156,13 +168,15 @@ test("unique candidate inside ambiguous context exceeds limit → context cannot
156
168
  ambiguous(lines, [3, 4]),
157
169
  failure({
158
170
  kind: "found",
159
- scope: "local",
160
171
  newLine: 2,
161
172
  newHash: computeLineHash(2, lines[1], 4),
162
173
  }),
163
174
  ]);
164
- assert.equal(result.shownLines.has(2), false);
165
- assert.equal(result.facts.omittedNeighborhoodRows, 1);
175
+ assert.equal(
176
+ rows(result).some((row) => row.startsWith("2#")),
177
+ false,
178
+ );
179
+ assert.equal(result.omittedNeighborhoodRows, 1);
166
180
  });
167
181
 
168
182
  test("remaining context budget cannot fit an intermediate row → retain shorter later rows", () => {
@@ -173,138 +187,143 @@ test("remaining context budget cannot fit an intermediate row → retain shorter
173
187
  "other",
174
188
  ];
175
189
  const result = neighborhoods(lines.join("\n"), [ambiguous(lines, [3, 4])]);
176
- assert.deepEqual([...result.shownLines], [1, 3, 4]);
177
- assert.equal(result.facts.omittedNeighborhoodRows, 1);
190
+ assert.deepEqual(
191
+ rows(result).map((row) => Number(row.split("#")[0])),
192
+ [1, 3, 4],
193
+ );
194
+ assert.equal(result.omittedNeighborhoodRows, 1);
178
195
  assert.ok(Buffer.byteLength(rows(result).join("\n") + "\n") <= DEFAULT_OUTPUT_BUDGETS.blockBytes);
179
196
  });
180
197
 
181
- function rejectedEdit(text: string, edits: Edit[], shiftRadius = 0) {
198
+ function rejectedEdit(
199
+ text: string,
200
+ edits: Edit[],
201
+ shiftRadius = 0,
202
+ budget = DEFAULT_OUTPUT_BUDGETS,
203
+ ) {
182
204
  const result = applyEdits(text, edits, DEFAULT_CONFIG.hashLen, shiftRadius);
183
205
  assert.ok(!result.ok, "the fixture must reach failure reporting");
184
206
  const error = describeEditFailure(
185
- result.failure,
186
- { currentText: text, anchors: createAnchorFormatter(DEFAULT_CONFIG.hashLen) },
187
- edits.length > 1,
188
- DEFAULT_OUTPUT_BUDGETS,
207
+ text,
208
+ result.failures,
209
+ createAnchorFormatter(DEFAULT_CONFIG.hashLen),
210
+ budget,
189
211
  );
190
- return {
191
- failure: result.failure,
192
- report: describeFailure("edit", error, { path: "file.txt", budget: DEFAULT_OUTPUT_BUDGETS }),
193
- };
212
+ return describeMutationFailure("edit", error, { path: "file.txt", budget });
194
213
  }
195
214
  const oldAnchor = { line: 1, hash: computeLineHash(1, "old", DEFAULT_CONFIG.hashLen) };
196
215
 
197
- test("unresolved observation already shown elsewhere → reports the row once", async (t) => {
198
- const cases = [
199
- {
200
- name: "ambiguous candidate neighborhood",
201
- text: "current\nneighbor\nold\nold\n",
202
- anchors: [oldAnchor, { line: 2, hash: computeLineHash(2, "gone", DEFAULT_CONFIG.hashLen) }],
203
- radius: DEFAULT_CONFIG.shiftRadius,
204
- line: 2,
205
- content: "neighbor",
206
- },
207
- {
208
- name: "earlier unresolved failure",
209
- text: "current\n",
210
- anchors: [oldAnchor, oldAnchor],
211
- radius: 0,
212
- line: 1,
213
- content: "current",
214
- },
215
- ];
216
- for (const fixture of cases) {
217
- await t.test(fixture.name, () => {
218
- const { report } = rejectedEdit(
219
- fixture.text,
220
- fixture.anchors.map((anchor) => ({ op: "delete", anchor })),
221
- fixture.radius,
222
- );
223
- const observed = createAnchorFormatter(DEFAULT_CONFIG.hashLen).row(
224
- fixture.line,
225
- fixture.content,
226
- );
227
- const displayedRows = [
228
- ...(report.failures?.flatMap((entry) => (entry.observed ? [entry.observed] : [])) ?? []),
229
- ...(report.candidateNeighborhoods?.flatMap((group) => group.rows) ?? []),
230
- ];
231
- assert.equal(displayedRows.filter((row) => row === observed).length, 1);
232
- });
233
- }
234
- });
235
-
236
216
  test("multiple unresolved anchors and candidate context → one recovery survives omitted facts", () => {
217
+ const budget = outputBudgetsFor(DEFAULT_OUTPUT_BUDGETS.fieldBytes);
218
+ const omittedFailureCount = 16;
237
219
  const cases = [
238
- ...[2, DEFAULT_OUTPUT_BUDGETS.blockBytes].map((count) => ({
220
+ ...[2, omittedFailureCount].map((count) => ({
239
221
  text: "current\n",
240
222
  edits: Array.from({ length: count }, (): Edit => ({ op: "delete", anchor: oldAnchor })),
241
223
  radius: 0,
242
- omitted: count === DEFAULT_OUTPUT_BUDGETS.blockBytes,
224
+ omitted: count === omittedFailureCount,
243
225
  })),
244
226
  {
245
227
  text: "current\nold\n",
246
- edits: [{ op: "delete", anchor: oldAnchor } as Edit],
228
+ edits: [{ op: "delete", anchor: oldAnchor }] satisfies Edit[],
247
229
  radius: 2,
248
230
  omitted: false,
249
231
  },
250
232
  {
251
233
  text: "current\nold\nold\n",
252
- edits: [{ op: "delete", anchor: oldAnchor } as Edit],
234
+ edits: [{ op: "delete", anchor: oldAnchor }] satisfies Edit[],
253
235
  radius: 2,
254
236
  omitted: false,
255
237
  },
238
+ ...["gone", "neighbor"].map((content) => ({
239
+ text: "current\nneighbor\nold\nold\n",
240
+ edits: [
241
+ { op: "delete", anchor: oldAnchor },
242
+ {
243
+ op: "delete",
244
+ anchor: {
245
+ line: content === "gone" ? 2 : 1,
246
+ hash: computeLineHash(content === "gone" ? 2 : 1, content, DEFAULT_CONFIG.hashLen),
247
+ },
248
+ },
249
+ ] satisfies Edit[],
250
+ radius: DEFAULT_CONFIG.shiftRadius,
251
+ omitted: false,
252
+ })),
256
253
  ];
257
254
  for (const fixture of cases) {
258
- const { report } = rejectedEdit(fixture.text, fixture.edits, fixture.radius);
255
+ const report = rejectedEdit(fixture.text, fixture.edits, fixture.radius, budget);
259
256
  assert.equal(report.error, "ANCHOR_MISMATCH");
260
- assert.match(report.next ?? "", /confirm.*intended target/);
261
- assert.match(report.next ?? "", /read or grep.*omitted rows.*out-of-range lines.*context/);
257
+ assert.equal(
258
+ report.next,
259
+ "Confirm a candidate or observed anchor is the intended target before reusing it; otherwise use read or grep.",
260
+ );
262
261
  const { next, ...facts } = report;
263
262
  assert.equal(renderReport(report).split(next!).length - 1, 1);
264
263
  assert.doesNotMatch(JSON.stringify(facts), /\b(?:confirm|read|grep|retries)\b/i);
265
- if (fixture.radius === 0)
266
- assert.match(report.failures?.[0].observed ?? "", /1#[0-9A-Z]+│current/);
264
+ if (fixture.radius === 0) {
265
+ assert.ok(
266
+ report.failures?.every((entry) => /1#[0-9A-Z]+│current/.test(entry.observed ?? "")),
267
+ );
268
+ assert.ok(report.failures && report.failures.length > 0);
269
+ assert.equal(report.failures.length + (report.omittedFailures ?? 0), fixture.edits.length);
270
+ assert.ok(report.failures.every((entry) => entry.result === "unresolved"));
271
+ }
272
+ if (fixture.text === "current\nneighbor\nold\nold\n") {
273
+ const row = createAnchorFormatter(DEFAULT_CONFIG.hashLen).row(2, "neighbor");
274
+ assert.ok(report.candidateNeighborhoods?.some((group) => group.rows.includes(row)));
275
+ const entry = report.failures?.[1];
276
+ assert.ok(entry);
277
+ assert.equal(entry.notShown, undefined);
278
+ if (entry.result === "unresolved") assert.equal(entry.observed, row);
279
+ else {
280
+ assert.equal(entry.result, "shifted");
281
+ assert.equal(entry.content, "neighbor");
282
+ }
283
+ }
267
284
  assert.equal(Boolean(report.omittedFailures), fixture.omitted);
268
285
  }
269
286
  });
270
287
 
271
- test("failure list exceeds budget → omitted anchors are never reported as matched", () => {
272
- const { report } = rejectedEdit(
273
- "current\n",
274
- Array.from({ length: DEFAULT_OUTPUT_BUDGETS.blockBytes }, () => ({
275
- op: "delete",
276
- anchor: oldAnchor,
277
- })),
278
- );
279
- assert.equal(report.error, "ANCHOR_MISMATCH");
280
- assert.ok(report.failures && report.failures.length > 0);
281
- assert.equal(
282
- report.failures.length + (report.omittedFailures ?? 0),
283
- DEFAULT_OUTPUT_BUDGETS.blockBytes,
284
- );
285
- assert.equal(report.matched, undefined);
286
- assert.ok(report.failures.every((entry) => entry.result === "unresolved"));
287
- });
288
-
289
- test("reversed ranges and overlapping edits → original reason and unpublished status without anchor recovery", () => {
290
- const text = "a\nb\nc\n";
288
+ test("overlapping edits → ordered conflict and shared recovery", () => {
289
+ const text = "a\nb\nc\nd\ne\n";
291
290
  const anchor = (line: number, content: string) => ({
292
291
  line,
293
292
  hash: computeLineHash(line, content, DEFAULT_CONFIG.hashLen),
294
293
  });
295
- const cases: Edit[][] = [
296
- [{ op: "delete", anchor: anchor(3, "c"), end: anchor(1, "a") }],
297
- [
298
- { op: "delete", anchor: anchor(1, "a"), end: anchor(2, "b") },
299
- { op: "replace", anchor: anchor(2, "b"), body: ["changed"] },
300
- ],
294
+ const cases: { edits: Edit[] }[] = [
295
+ {
296
+ edits: [
297
+ { op: "replace", anchor: anchor(2, "b"), body: ["changed"] },
298
+ { op: "delete", anchor: anchor(4, "d") },
299
+ { op: "delete", anchor: anchor(1, "a"), end: anchor(2, "b") },
300
+ ],
301
+ },
302
+ {
303
+ edits: [
304
+ { op: "insert_after", anchor: anchor(2, "b"), body: ["first"] },
305
+ { op: "delete", anchor: anchor(4, "d") },
306
+ { op: "insert_before", anchor: anchor(3, "c"), body: ["second"] },
307
+ ],
308
+ },
301
309
  ];
302
- for (const edits of cases) {
303
- const { failure, report } = rejectedEdit(text, edits);
304
- assert.ok(failure.kind === "range");
305
- assert.equal(report.message, failure.message);
306
- assert.equal(report.publication, "NOT_PUBLISHED");
307
- assert.doesNotMatch(report.next ?? "", /Before reusing|confirm|read or grep|Retries verify/);
310
+ for (const { edits } of cases) {
311
+ assert.throws(
312
+ () => applyEdits(text, edits, DEFAULT_CONFIG.hashLen, 0),
313
+ (error: unknown) => {
314
+ assert.ok(error instanceof HashlineError);
315
+ const report = describeMutationFailure("edit", error, {
316
+ path: "file.txt",
317
+ budget: DEFAULT_OUTPUT_BUDGETS,
318
+ });
319
+ assert.equal(report.error, "OVERLAPPING_EDITS");
320
+ assert.deepEqual(report.conflict, ["steps[0]", "steps[2]"]);
321
+ assert.equal(report.message, error.message);
322
+ assert.equal(report.publication, "NOT_PUBLISHED");
323
+ assert.match(report.next ?? "", /one edit per range or position/);
324
+ return true;
325
+ },
326
+ );
308
327
  }
309
328
  });
310
329
 
@@ -318,9 +337,9 @@ test("unresolved row out of range or oversized → omission facts contain no rec
318
337
  { anchor: { ...oldAnchor, line: 2 }, reason: /cited line is out of range/ },
319
338
  ];
320
339
  for (const { anchor, reason } of cases) {
321
- const { report } = rejectedEdit(text, [{ op: "delete", anchor }]);
340
+ const report = rejectedEdit(text, [{ op: "delete", anchor }]);
322
341
  assert.equal(report.error, "ANCHOR_MISMATCH");
323
- assert.match(report.failures?.[0].omitted ?? "", reason);
342
+ assert.match(report.failures?.[0].notShown ?? "", reason);
324
343
  assert.equal(report.failures?.[0].observed, undefined);
325
344
  assert.doesNotMatch(
326
345
  JSON.stringify(report.failures),
@@ -1,27 +1,22 @@
1
1
  /**
2
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.
3
+ * recovery candidates or observed rows, and ambiguous-candidate neighborhoods.
5
4
  *
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.
5
+ * A failure entry states what was cited and what the search found; a shifted
6
+ * candidate's anchor is stated once, beside its `content`. The `observed` and
7
+ * neighborhood rows are observations, not verified targets. Every list has its
8
+ * own byte budget and an explicit omission count. The recovery instruction is
9
+ * the report's `next`, derived from the code in report-schema.ts.
14
10
  *
15
11
  * @module pi-hashline-edit/pi
16
12
  */
17
13
 
18
14
  import { type AnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
19
15
  import { splitLines } from "../core/lines.ts";
20
- import type { Anchor, AnchorFailure, ApplyFailure } from "../core/types.ts";
16
+ import type { Anchor, AnchorFailure } from "../core/types.ts";
21
17
  import { mergeRanges } from "../core/ranges.ts";
22
18
  import { HashlineError } from "../core/errors.ts";
23
19
  import { formatByteSize, type OutputBudgets } from "./budgets.ts";
24
- import { boundedFacts } from "./report.ts";
25
20
  import type { AnchorFailureFact, ErrorFacts } from "./report-schema.ts";
26
21
 
27
22
  type MismatchFacts = ErrorFacts<"ANCHOR_MISMATCH">;
@@ -29,8 +24,6 @@ type MismatchFacts = ErrorFacts<"ANCHOR_MISMATCH">;
29
24
  const CONTEXT_RADIUS = 3;
30
25
  const MAX_AMBIGUOUS_CANDIDATES = 8;
31
26
 
32
- type Snapshot = Readonly<{ currentText: string; anchors: AnchorFormatter }>;
33
-
34
27
  /** Select the shared candidate prefix for detail lists and observation neighborhoods. */
35
28
  function selectAmbiguousCandidates(candidates: readonly Anchor[]): readonly Anchor[] {
36
29
  return candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES);
@@ -90,26 +83,19 @@ function groupContextRows(rows: readonly ContextRow[]) {
90
83
  return groups;
91
84
  }
92
85
 
93
- /**
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.
97
- */
98
- export function ambiguousCandidateNeighborhoods(
86
+ /** Observation rows around listed ambiguous candidates, lowest lines first. */
87
+ function ambiguousCandidateNeighborhoods(
99
88
  currentText: string,
100
89
  failures: readonly AnchorFailure[],
101
90
  anchors: AnchorFormatter,
102
91
  budget: OutputBudgets,
103
- ): {
104
- facts: Pick<MismatchFacts, "candidateNeighborhoods" | "omittedNeighborhoodRows">;
105
- shownLines: ReadonlySet<number>;
106
- } {
92
+ ): Pick<MismatchFacts, "candidateNeighborhoods" | "omittedNeighborhoodRows"> {
107
93
  const centers = failures.flatMap((failure) =>
108
94
  failure.recovery.kind === "ambiguous"
109
95
  ? selectAmbiguousCandidates(failure.recovery.candidates).map((candidate) => candidate.line)
110
96
  : [],
111
97
  );
112
- if (centers.length === 0) return { facts: {}, shownLines: new Set() };
98
+ if (centers.length === 0) return {};
113
99
 
114
100
  const candidateLines = new Set(centers);
115
101
  for (const failure of failures) {
@@ -123,11 +109,8 @@ export function ambiguousCandidateNeighborhoods(
123
109
  budget,
124
110
  );
125
111
  return {
126
- facts: {
127
- candidateNeighborhoods: groupContextRows(rows),
128
- ...(omitted ? { omittedNeighborhoodRows: omitted } : {}),
129
- },
130
- shownLines: new Set(rows.map((row) => row.line)),
112
+ candidateNeighborhoods: groupContextRows(rows),
113
+ ...(omitted ? { omittedNeighborhoodRows: omitted } : {}),
131
114
  };
132
115
  }
133
116
 
@@ -136,109 +119,77 @@ const RESULT = { found: "shifted", ambiguous: "ambiguous", none: "unresolved" }
136
119
  /** One failure entry: what was cited, then what the search found or what the cited line holds. */
137
120
  function failureEntry(
138
121
  f: AnchorFailure,
139
- snapshot: Snapshot,
122
+ anchors: AnchorFormatter,
140
123
  currentLines: readonly string[],
141
- shownLines: Set<number>,
142
124
  budget: OutputBudgets,
143
125
  ): AnchorFailureFact {
144
126
  const rowTooLarge = `row exceeds ${formatByteSize(budget.fieldBytes)}`;
145
127
  const entry: { -readonly [K in keyof AnchorFailureFact]: AnchorFailureFact[K] } = {
146
- field: `edits[${f.opIndex}].${f.which}`,
128
+ field: `steps[${f.opIndex}].${f.which}`,
147
129
  action: f.op,
148
- cited: snapshot.anchors.reference(f.cited.line, f.cited.hash),
130
+ cited: anchors.reference(f.cited.line, f.cited.hash),
149
131
  result: RESULT[f.recovery.kind],
150
132
  };
151
- if (f.recovery.kind !== "none")
152
- entry.search = f.recovery.scope === "local" ? "local window" : "full file";
153
133
  switch (f.recovery.kind) {
154
134
  case "found": {
155
135
  const { newLine, newHash } = f.recovery;
156
- entry.candidate = snapshot.anchors.reference(newLine, newHash);
157
- if (shownLines.has(newLine)) break;
136
+ entry.candidate = anchors.reference(newLine, newHash);
158
137
  const content = currentLines[newLine - 1];
159
138
  // 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
- ) {
139
+ if (Buffer.byteLength(anchors.row(newLine, content), "utf8") <= budget.fieldBytes) {
164
140
  entry.content = displayCarriageReturns(content);
165
- shownLines.add(newLine);
166
141
  } else {
167
- entry.omitted = rowTooLarge;
142
+ entry.notShown = rowTooLarge;
168
143
  }
169
144
  break;
170
145
  }
171
146
  case "ambiguous": {
172
147
  const candidates = selectAmbiguousCandidates(f.recovery.candidates);
173
148
  entry.candidates = candidates.map((candidate) =>
174
- snapshot.anchors.reference(candidate.line, candidate.hash),
149
+ anchors.reference(candidate.line, candidate.hash),
175
150
  );
176
151
  const omitted = f.recovery.candidates.length - candidates.length;
177
152
  if (omitted) entry.omittedCandidates = omitted;
178
153
  break;
179
154
  }
180
155
  case "none": {
181
- if (shownLines.has(f.cited.line)) break;
182
- const row = f.current === null ? null : snapshot.anchors.row(f.cited.line, f.current.content);
183
- if (row === null) entry.omitted = "cited line is out of range";
184
- else if (Buffer.byteLength(row, "utf8") <= budget.fieldBytes) {
185
- entry.observed = row;
186
- shownLines.add(f.cited.line);
187
- } else entry.omitted = rowTooLarge;
156
+ const content = currentLines[f.cited.line - 1];
157
+ if (content === undefined) {
158
+ entry.notShown = "cited line is out of range";
159
+ break;
160
+ }
161
+ const row = anchors.row(f.cited.line, content);
162
+ if (Buffer.byteLength(row, "utf8") <= budget.fieldBytes) entry.observed = row;
163
+ else entry.notShown = rowTooLarge;
188
164
  break;
189
165
  }
190
166
  }
191
167
  return entry;
192
168
  }
193
169
 
194
- /**
195
- * The batch's anchors whose checksum matched, by field. An anchor absent from
196
- * both `matched` and `failures` is counted as omitted, never implied matched.
197
- */
198
- function matchedAnchorFacts(
199
- failure: ApplyFailure,
200
- budget: OutputBudgets,
201
- ): Pick<MismatchFacts, "matched" | "omittedMatched"> {
202
- const { kept, omitted } = boundedFacts(
203
- failure.checks
204
- .filter((check) => check.status === "matched")
205
- .map((check) => `edits[${check.opIndex}].${check.which}`),
206
- budget.blockBytes,
207
- );
208
- return kept.length || omitted
209
- ? { matched: kept, ...(omitted ? { omittedMatched: omitted } : {}) }
210
- : {};
211
- }
212
-
213
- /** Classify a rejected edit batch with its bounded facts. */
170
+ /** Classify a batch's anchor failures with their bounded facts. */
214
171
  export function describeEditFailure(
215
- failure: ApplyFailure,
216
- snapshot: Snapshot,
217
- isBatch: boolean,
172
+ currentText: string,
173
+ failures: readonly AnchorFailure[],
174
+ anchors: AnchorFormatter,
218
175
  budget: OutputBudgets,
219
- ): HashlineError<"ANCHOR_MISMATCH" | "INVALID_RANGE" | "OVERLAPPING_EDITS"> {
220
- const matched = isBatch ? matchedAnchorFacts(failure, budget) : {};
221
- if (failure.kind === "range")
222
- return new HashlineError(failure.code, failure.message, { facts: matched });
223
-
224
- const neighborhoods = ambiguousCandidateNeighborhoods(
225
- snapshot.currentText,
226
- failure.failures,
227
- snapshot.anchors,
228
- budget,
229
- );
230
- const currentLines = splitLines(snapshot.currentText);
231
- const shownLines = new Set(neighborhoods.shownLines);
232
- const { kept, omitted } = boundedFacts(
233
- failure.failures.map((f) => failureEntry(f, snapshot, currentLines, shownLines, budget)),
234
- budget.blockBytes,
235
- );
176
+ ): HashlineError<"ANCHOR_MISMATCH"> {
177
+ const currentLines = splitLines(currentText);
178
+ // Leading entries whose compact JSON fits the block; whole entries are omitted, never cut.
179
+ const kept: AnchorFailureFact[] = [];
180
+ let bytes = 0;
181
+ for (const failure of failures) {
182
+ const entry = failureEntry(failure, anchors, currentLines, budget);
183
+ bytes += Buffer.byteLength(JSON.stringify(entry)) + 1;
184
+ if (bytes > budget.blockBytes) break;
185
+ kept.push(entry);
186
+ }
187
+ const omitted = failures.length - kept.length;
236
188
  return new HashlineError("ANCHOR_MISMATCH", "Anchors did not match the current file.", {
237
189
  facts: {
238
190
  failures: kept,
239
191
  ...(omitted ? { omittedFailures: omitted } : {}),
240
- ...matched,
241
- ...neighborhoods.facts,
192
+ ...ambiguousCandidateNeighborhoods(currentText, failures, anchors, budget),
242
193
  },
243
194
  });
244
195
  }