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