@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
package/src/core/apply.ts CHANGED
@@ -17,13 +17,13 @@
17
17
  * ANY anchor fails, EVERY failure (with recovery) is collected and returned
18
18
  * together — nothing is written. This keeps the rescue report and the on-disk
19
19
  * file in sync: a partial write would shift lines and invalidate the very
20
- * recovery info we just returned. Range issues among the surviving ops are
21
- * deferred until anchors are corrected.
20
+ * recovery info we just returned. Overlaps among the surviving ops are deferred
21
+ * until anchors are corrected. The tool layer has already rejected reversed
22
+ * ranges.
22
23
  *
23
24
  * Other strict semantics:
24
- * - Operation ranges must not overlap, and each position takes at most one insertion,
25
- * copy/move destinations included. An insertion at the start of a replaced or deleted
26
- * range applies before that range.
25
+ * - Operation ranges must not overlap, and each position takes at most one insertion.
26
+ * An insertion at the start of a replaced or deleted range applies before that range.
27
27
  * - Byte-identical output is a success; the commit layer reports it as a no-op.
28
28
  *
29
29
  * @module pi-hashline-edit/core
@@ -38,28 +38,21 @@ import {
38
38
  replacementSeparator,
39
39
  splitLines,
40
40
  } from "./lines.ts";
41
- import type {
42
- Anchor,
43
- AnchorCheck,
44
- AnchorFailure,
45
- AnchorRecovery,
46
- ApplyFailure,
47
- ApplyResult,
48
- Edit,
49
- } from "./types.ts";
41
+ import type { Anchor, AnchorFailure, AnchorRecovery, ApplyResult, Edit } from "./types.ts";
42
+ import { HashlineError } from "./errors.ts";
50
43
  import { findSortedRangeConflict } from "./ranges.ts";
51
44
 
52
- /** Replace `[lo, hi)` with caller text or a range captured from the verified original lines. */
53
- type SpanOp = { readonly lo: number; readonly hi: number } & (
54
- | { readonly kind: "body"; readonly newLines: readonly string[] }
55
- | { readonly kind: "capture"; readonly sourceLo: number; readonly sourceHi: number }
56
- );
45
+ /** Replace `[lo, hi)` with caller text. */
46
+ interface SpanOp {
47
+ readonly lo: number;
48
+ readonly hi: number;
49
+ readonly newLines: readonly string[];
50
+ }
57
51
 
58
52
  /**
59
53
  * Verify an anchor against the live content; on mismatch, attempt shifted
60
54
  * recovery. Returns null when the anchor matches, otherwise an
61
- * {@link AnchorFailure} carrying the recovery outcome and the cited line's
62
- * current snapshot.
55
+ * {@link AnchorFailure} carrying the recovery outcome.
63
56
  *
64
57
  * Recovery holds the ORIGINAL line number fixed and re-hashes each candidate's
65
58
  * content. A matching checksum identifies a candidate, not proof of the
@@ -70,7 +63,7 @@ type SpanOp = { readonly lo: number; readonly hi: number } & (
70
63
  function verifyAnchor(
71
64
  lines: readonly string[],
72
65
  cited: Anchor,
73
- which: AnchorCheck["which"],
66
+ which: AnchorFailure["which"],
74
67
  opIndex: number,
75
68
  op: Edit["op"],
76
69
  hashLen: number,
@@ -86,7 +79,6 @@ function verifyAnchor(
86
79
  }
87
80
 
88
81
  const candidates: { line: number; hash: string }[] = [];
89
- let scope: "local" | "full-file" = "local";
90
82
  const scan = (start: number, end: number) => {
91
83
  for (let c = start; c <= end; c++) {
92
84
  if (c === line) continue;
@@ -101,7 +93,6 @@ function verifyAnchor(
101
93
  scan(lo, hi);
102
94
  // Preserve local candidates; scan both remaining regions before deciding uniqueness.
103
95
  if (candidates.length === 0) {
104
- scope = "full-file";
105
96
  scan(1, Math.min(lines.length, lo - 1));
106
97
  scan(Math.max(1, hi + 1), lines.length);
107
98
  }
@@ -109,34 +100,21 @@ function verifyAnchor(
109
100
 
110
101
  let recovery: AnchorRecovery;
111
102
  if (candidates.length === 1) {
112
- recovery = { kind: "found", scope, newLine: candidates[0].line, newHash: candidates[0].hash };
103
+ recovery = { kind: "found", newLine: candidates[0].line, newHash: candidates[0].hash };
113
104
  } else if (candidates.length > 1) {
114
- recovery = { kind: "ambiguous", scope, candidates };
105
+ recovery = { kind: "ambiguous", candidates };
115
106
  } else {
116
107
  recovery = { kind: "none" };
117
108
  }
118
109
 
119
- const current = line >= 1 && line <= lines.length ? { content: lines[line - 1] } : null;
120
-
121
- return { opIndex, which, op, cited, recovery, current };
110
+ return { opIndex, which, op, cited, recovery };
122
111
  }
123
112
 
124
113
  type TranslateResult =
125
- | { readonly ok: true; readonly ops: readonly SpanOp[]; readonly checks: AnchorCheck[] }
126
- | { readonly ok: false; readonly anchorFailures: AnchorFailure[]; readonly checks: AnchorCheck[] }
127
- | { readonly ok: false; readonly rangeError: RangeError; readonly checks: AnchorCheck[] };
114
+ | { readonly ok: true; readonly op: SpanOp }
115
+ | { readonly ok: false; readonly anchorFailures: AnchorFailure[] };
128
116
 
129
- type RangeError = Pick<Extract<ApplyFailure, { kind: "range" }>, "code" | "message">;
130
-
131
- function checkedAnchor(
132
- opIndex: number,
133
- which: AnchorCheck["which"],
134
- failure: AnchorFailure | null,
135
- ): AnchorCheck {
136
- return { opIndex, which, status: failure ? "mismatched" : "matched" };
137
- }
138
-
139
- /** Verify an Edit against the snapshot and plan its mutation spans and captured source. */
117
+ /** Verify an Edit against the snapshot and plan its mutation span. */
140
118
  function translateEdit(
141
119
  edit: Edit,
142
120
  opIndex: number,
@@ -144,120 +122,48 @@ function translateEdit(
144
122
  hashLen: number,
145
123
  radius: number,
146
124
  ): TranslateResult {
125
+ const verify = (cited: Anchor, which: AnchorFailure["which"]) =>
126
+ verifyAnchor(lines, cited, which, opIndex, edit.op, hashLen, radius);
147
127
  switch (edit.op) {
148
128
  case "replace":
149
- case "delete":
150
- case "copy":
151
- case "move": {
129
+ case "delete": {
152
130
  const failures: AnchorFailure[] = [];
153
- const checks: AnchorCheck[] = [];
154
- const anchorF = verifyAnchor(lines, edit.anchor, "anchor", opIndex, edit.op, hashLen, radius);
155
- checks.push(checkedAnchor(opIndex, "anchor", anchorF));
131
+ const anchorF = verify(edit.anchor, "anchor");
156
132
  if (anchorF) failures.push(anchorF);
157
133
  let endLine = edit.anchor.line;
158
134
  if (edit.end) {
159
- const endF = verifyAnchor(lines, edit.end, "end", opIndex, edit.op, hashLen, radius);
160
- checks.push(checkedAnchor(opIndex, "end", endF));
135
+ const endF = verify(edit.end, "end");
161
136
  if (endF) failures.push(endF);
162
137
  endLine = edit.end.line;
163
138
  }
164
- const destination =
165
- edit.op === "copy" || edit.op === "move"
166
- ? edit.before !== undefined
167
- ? { which: "before" as const, cited: edit.before }
168
- : { which: "after" as const, cited: edit.after }
169
- : undefined;
170
- if (destination) {
171
- const failure = verifyAnchor(
172
- lines,
173
- destination.cited,
174
- destination.which,
175
- opIndex,
176
- edit.op,
177
- hashLen,
178
- radius,
179
- );
180
- checks.push(checkedAnchor(opIndex, destination.which, failure));
181
- if (failure) failures.push(failure);
182
- }
183
- if (failures.length > 0) return { ok: false, anchorFailures: failures, checks };
184
- if (endLine < edit.anchor.line)
185
- return {
186
- ok: false,
187
- rangeError: {
188
- code: "INVALID_RANGE",
189
- message: `Range ${edit.anchor.line}..${endLine} ends before it starts.`,
190
- },
191
- checks,
192
- };
193
- if (destination) {
194
- const sourceLo = edit.anchor.line - 1;
195
- const gap = destination.cited.line - (destination.which === "before" ? 1 : 0);
196
- if (edit.op === "move" && sourceLo < gap && gap < endLine) {
197
- return {
198
- ok: false,
199
- rangeError: {
200
- code: "INVALID_RANGE",
201
- message: `Destination ${destination.which} line ${destination.cited.line} lies inside moved range ${edit.anchor.line}..${endLine}.`,
202
- },
203
- checks,
204
- };
205
- }
206
- if (edit.op === "move" && (gap === sourceLo || gap === endLine)) {
207
- return { ok: true, ops: [], checks };
208
- }
209
- const insertion: SpanOp = {
210
- lo: gap,
211
- hi: gap,
212
- kind: "capture",
213
- sourceLo,
214
- sourceHi: endLine,
215
- };
216
- return {
217
- ok: true,
218
- checks,
219
- ops:
220
- edit.op === "move"
221
- ? [insertion, { lo: sourceLo, hi: endLine, kind: "body", newLines: [] }]
222
- : [insertion],
223
- };
224
- }
139
+ if (failures.length > 0) return { ok: false, anchorFailures: failures };
225
140
  return {
226
141
  ok: true,
227
- checks,
228
- ops: [
229
- {
230
- lo: edit.anchor.line - 1,
231
- hi: endLine,
232
- kind: "body",
233
- newLines: edit.op === "replace" ? edit.body : [],
234
- },
235
- ],
142
+ op: {
143
+ lo: edit.anchor.line - 1,
144
+ hi: endLine,
145
+ newLines: edit.op === "replace" ? edit.body : [],
146
+ },
236
147
  };
237
148
  }
238
149
  case "insert_after":
239
150
  case "insert_before": {
240
- const failure = verifyAnchor(lines, edit.anchor, "anchor", opIndex, edit.op, hashLen, radius);
241
- const checks = [checkedAnchor(opIndex, "anchor", failure)];
242
- if (failure) return { ok: false, anchorFailures: [failure], checks };
151
+ const failure = verify(edit.anchor, "anchor");
152
+ if (failure) return { ok: false, anchorFailures: [failure] };
243
153
  const line = edit.anchor.line - (edit.op === "insert_before" ? 1 : 0);
244
- return { ok: true, checks, ops: [{ lo: line, hi: line, kind: "body", newLines: edit.body }] };
154
+ return { ok: true, op: { lo: line, hi: line, newLines: edit.body } };
245
155
  }
246
156
  case "append":
247
- return {
248
- ok: true,
249
- checks: [],
250
- ops: [{ lo: lines.length, hi: lines.length, kind: "body", newLines: edit.body }],
251
- };
157
+ return { ok: true, op: { lo: lines.length, hi: lines.length, newLines: edit.body } };
252
158
  case "prepend":
253
- return { ok: true, checks: [], ops: [{ lo: 0, hi: 0, kind: "body", newLines: edit.body }] };
159
+ return { ok: true, op: { lo: 0, hi: 0, newLines: edit.body } };
254
160
  }
255
161
  }
256
162
 
257
163
  /**
258
164
  * Apply edits to `text`. Anchors are verified against the current content.
259
165
  * On any anchor mismatch, all failures (with shifted recovery) are collected
260
- * and returned together. Every failure includes per-input anchor checks.
166
+ * and returned together.
261
167
  *
262
168
  * @param text current full file text
263
169
  * @param edits validated edit operations; each body element is one logical line
@@ -266,7 +172,7 @@ function translateEdit(
266
172
  */
267
173
  export function applyEdits(
268
174
  text: string,
269
- edits: Edit[],
175
+ edits: readonly Edit[],
270
176
  hashLen: number,
271
177
  shiftRadius: number,
272
178
  ): ApplyResult {
@@ -274,55 +180,47 @@ export function applyEdits(
274
180
  const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
275
181
  const ending = detectLineEnding(text);
276
182
 
277
- const ops: SpanOp[] = [];
183
+ const ops: (SpanOp & { readonly opIndex: number })[] = [];
278
184
  const anchorFailures: AnchorFailure[] = [];
279
- const anchorChecks: AnchorCheck[] = [];
280
- let rangeError: RangeError | null = null;
281
185
 
282
186
  for (let i = 0; i < edits.length; i++) {
283
187
  const t = translateEdit(edits[i], i, lines, hashLen, shiftRadius);
284
- anchorChecks.push(...t.checks);
285
188
  if (t.ok) {
286
- for (const op of t.ops) ops.push(op);
287
- } else if ("anchorFailures" in t) {
189
+ ops.push({ ...t.op, opIndex: i });
190
+ } else {
288
191
  anchorFailures.push(...t.anchorFailures);
289
- } else if (rangeError === null) {
290
- rangeError = t.rangeError;
291
192
  }
292
193
  }
293
194
 
294
- // Anchor failures take priority: the model must fix anchors first; range
295
- // issues among surviving ops are premature until anchors are corrected.
195
+ // Anchor failures take priority: the model must fix anchors first; overlaps
196
+ // among surviving ops are premature until anchors are corrected.
296
197
  if (anchorFailures.length > 0) {
297
- return {
298
- ok: false,
299
- failure: { kind: "anchor", failures: anchorFailures, checks: anchorChecks },
300
- };
301
- }
302
- if (rangeError !== null) {
303
- return { ok: false, failure: { kind: "range", ...rangeError, checks: anchorChecks } };
198
+ return { ok: false, failures: anchorFailures };
304
199
  }
305
200
 
306
- const sorted = [...ops].sort((a, b) => a.lo - b.lo || a.hi - b.hi);
201
+ const sorted = ops.sort((a, b) => a.lo - b.lo || a.hi - b.hi);
307
202
  const conflict = findSortedRangeConflict(
308
203
  sorted.map((op) => [op.lo, op.hi]),
309
204
  true,
310
205
  );
311
206
  if (conflict !== undefined) {
312
- const { lo, hi } = sorted[conflict];
207
+ const current = sorted[conflict];
313
208
  const previous = sorted[conflict - 1];
314
- const repeatedInsertion = lo === hi && previous.lo === lo && previous.hi === hi;
315
- return {
316
- ok: false,
317
- failure: {
318
- kind: "range",
319
- code: "OVERLAPPING_EDITS",
320
- message: repeatedInsertion
321
- ? `Edits insert more than once at one position near line ${lo + 1}.`
322
- : `Edits overlap near line ${lo + 1}.`,
323
- checks: anchorChecks,
209
+ const repeatedInsertion =
210
+ current.lo === current.hi && previous.lo === current.lo && previous.hi === current.hi;
211
+ throw new HashlineError(
212
+ "OVERLAPPING_EDITS",
213
+ repeatedInsertion ? "Two edits insert at one position." : "Two edits overlap.",
214
+ {
215
+ // The first conflicting pair found, ascending.
216
+ facts: {
217
+ conflict: [
218
+ `edits[${Math.min(previous.opIndex, current.opIndex)}]`,
219
+ `edits[${Math.max(previous.opIndex, current.opIndex)}]`,
220
+ ],
221
+ },
324
222
  },
325
- };
223
+ );
326
224
  }
327
225
 
328
226
  // Mixed line endings: each line carries the separator that FOLLOWED it in
@@ -341,7 +239,7 @@ export function applyEdits(
341
239
  const appendSource = (start: number, end: number) => {
342
240
  for (let index = start; index < end; index++) {
343
241
  const content = lines[index];
344
- // Keep the verified first-line BOM at byte zero, including for captured ranges.
242
+ // Keep the verified first-line BOM at byte zero.
345
243
  result.push({
346
244
  content: bom && index === 0 ? content.slice(1) : content,
347
245
  separator: separators?.[index] ?? "",
@@ -350,11 +248,6 @@ export function applyEdits(
350
248
  };
351
249
  for (const op of sorted) {
352
250
  appendSource(cursor, op.lo);
353
- if (op.kind === "capture") {
354
- appendSource(op.sourceLo, op.sourceHi);
355
- cursor = op.hi;
356
- continue;
357
- }
358
251
  // The trailing gap is outside the logical replacement, just as in substring replacement.
359
252
  const removedSeparators = separators?.slice(op.lo, Math.max(op.lo, op.hi - 1)) ?? [];
360
253
  for (let i = 0; i < op.newLines.length; i++) {
@@ -1,77 +1,18 @@
1
1
  /**
2
- * JavaScript ignoreCase equivalence, derived from the engine's own definitions:
3
- * without u/v, ECMA-262 Canonicalize through toUpperCase; with u/v, RegExp itself.
2
+ * JavaScript ignoreCase equivalence, derived from the engine itself.
4
3
  *
5
4
  * @module pi-hashline-edit/core
6
5
  */
7
6
 
8
- import { MAX_UNIT, MAX_SCALAR, nativeCharacterRanges } from "./character-set.ts";
9
- const MAX_ASCII = 0x7f;
7
+ import { MAX_UNIT, foldRanges } from "./character-set.ts";
10
8
 
11
- /** Code units that ignoreCase treats as equal: ECMA-262 Canonicalize without the u flag. */
12
- function equivalentCases(): readonly (readonly number[])[] {
13
- const groups = new Map<number, number[]>();
14
- for (let unit = 0; unit <= MAX_UNIT; unit++) {
15
- const upper = String.fromCharCode(unit).toUpperCase();
16
- const canonical =
17
- upper.length === 1 && !(unit >= 128 && upper.charCodeAt(0) < 128)
18
- ? upper.charCodeAt(0)
19
- : unit;
20
- const group = groups.get(canonical);
21
- if (group) group.push(unit);
22
- else groups.set(canonical, [unit]);
23
- }
24
- return [...groups.values()].filter((group) => group.length > 1);
25
- }
26
-
27
- let unitVariants: ReadonlyMap<number, readonly string[]> | undefined;
28
-
29
- function variantsWithoutUnicode(unit: number): readonly string[] | undefined {
30
- if (!unitVariants) {
31
- const variants = new Map<number, readonly string[]>();
32
- for (const group of equivalentCases()) {
33
- const chars = group.map((member) => String.fromCharCode(member));
34
- for (const member of group) variants.set(member, chars);
35
- }
36
- unitVariants = variants;
37
- }
38
- return unitVariants.get(unit);
39
- }
40
-
41
- let asciiVariants: readonly (readonly string[])[] | undefined;
42
-
43
- /** With u/v, every character that RegExp matches caselessly against each ASCII character. */
44
- function variantsOfAscii(code: number): readonly string[] {
45
- if (!asciiVariants) {
46
- const probe = /^[\0-\x7f]$/iu;
47
- const hits: string[] = [];
48
- for (let point = 0; point <= MAX_SCALAR; point++) {
49
- if (point === 0xd800) point = 0xe000;
50
- const char = String.fromCodePoint(point);
51
- if (probe.test(char)) hits.push(char);
52
- }
53
- asciiVariants = Array.from({ length: MAX_ASCII + 1 }, (_, ascii) => {
54
- const exact = new RegExp(`^\\x${ascii.toString(16).padStart(2, "0")}$`, "iu");
55
- return hits.filter((char) => exact.test(char));
56
- });
57
- }
58
- return asciiVariants[code];
59
- }
60
-
61
- /**
62
- * The characters JavaScript's ignoreCase matches for one character, itself included,
63
- * derived from V8 for Unicode and ECMAScript Canonicalize otherwise.
64
- */
9
+ /** The characters JavaScript's ignoreCase matches for one character, itself included. */
65
10
  export function caseVariants(char: string, unicode: boolean): readonly string[] {
66
11
  const point = char.codePointAt(0)!;
67
- if (unicode) {
68
- if (point <= MAX_ASCII) return variantsOfAscii(point);
69
- const result: string[] = [];
70
- for (const [low, high] of nativeCharacterRanges(`\\u{${point.toString(16)}}`, "iu"))
71
- for (let code = low; code <= high; code++) result.push(String.fromCodePoint(code));
72
- return result;
73
- }
74
12
  // Without u, ignoreCase never folds a supplementary character's surrogates.
75
- if (point > MAX_UNIT) return [char];
76
- return variantsWithoutUnicode(point) ?? [char];
13
+ if (!unicode && point > MAX_UNIT) return [char];
14
+ const result: string[] = [];
15
+ for (const [low, high] of foldRanges([[point, point]], unicode))
16
+ for (let code = low; code <= high; code++) result.push(String.fromCodePoint(code));
17
+ return result;
77
18
  }
@@ -59,14 +59,14 @@ export function normalize(ranges: Iterable<readonly [number, number]>): Ranges {
59
59
  return merged;
60
60
  }
61
61
 
62
- export function complement(ranges: Ranges, max: number): Ranges {
62
+ function complement(ranges: Ranges): Ranges {
63
63
  const result: [number, number][] = [];
64
64
  let next = 0;
65
65
  for (const [low, high] of ranges) {
66
66
  if (low > next) result.push([next, low - 1]);
67
67
  next = high + 1;
68
68
  }
69
- if (next <= max) result.push([next, max]);
69
+ if (next <= MAX_SCALAR) result.push([next, MAX_SCALAR]);
70
70
  return result;
71
71
  }
72
72
 
@@ -85,7 +85,7 @@ export function intersect(left: Ranges, right: Ranges): Ranges {
85
85
  }
86
86
 
87
87
  export function subtract(ranges: Ranges, removed: Ranges): Ranges {
88
- return intersect(ranges, complement(normalize(removed), MAX_SCALAR));
88
+ return intersect(ranges, complement(normalize(removed)));
89
89
  }
90
90
 
91
91
  export const total = (ranges: Ranges): number =>
@@ -154,7 +154,7 @@ export function acceptedClassStrings(
154
154
  }
155
155
 
156
156
  /** String representatives of a class; undefined means a string property is not enumerable here. */
157
- export function classStrings(node: ClassNode): readonly string[] | undefined {
157
+ function classStrings(node: ClassNode): readonly string[] | undefined {
158
158
  switch (node.type) {
159
159
  case "ExpressionCharacterClass":
160
160
  return node.negate ? [] : classStrings(node.expression);
@@ -1,23 +1,39 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
- import { HashlineError } from "./errors.ts";
3
+ import { filesystemErrorCode, HashlineError, PATH_ERROR_MESSAGES } from "./errors.ts";
4
4
 
5
5
  // npm run typecheck checks these invalid callers; they must never run.
6
6
  function invalidErrorConstruction() {
7
- // @ts-expect-error NO_MATCH requires its rule fact.
7
+ // @ts-expect-error NO_MATCH requires its unmatched fact.
8
8
  new HashlineError("NO_MATCH", "missing");
9
9
  // @ts-expect-error NO_MATCH facts cannot contain unrelated fields.
10
- new HashlineError("NO_MATCH", "missing", { facts: { rule: 0, ids: [] } });
10
+ new HashlineError("NO_MATCH", "missing", { facts: { unmatched: [], ids: [] } });
11
11
  // @ts-expect-error TARGET_EXISTS has no code facts.
12
- new HashlineError("TARGET_EXISTS", "exists", { facts: { rule: 0 } });
12
+ new HashlineError("TARGET_EXISTS", "exists", { facts: { unmatched: [] } });
13
13
  // @ts-expect-error Only PATH_NOT_FOUND permits useCreate recovery.
14
- new HashlineError("NO_MATCH", "missing", { facts: { rule: 0 }, next: "useCreate" });
14
+ new HashlineError("NO_MATCH", "missing", { facts: { unmatched: [] }, next: "useCreate" });
15
15
  }
16
16
 
17
17
  test("classified code with required facts → retains facts and native cause", () => {
18
18
  const cause = new Error("native failure");
19
- const failure = new HashlineError("NO_MATCH", "missing", { facts: { rule: 2 }, cause });
19
+ const failure = new HashlineError("NO_MATCH", "missing", {
20
+ facts: { unmatched: ["replacements[2]"] },
21
+ cause,
22
+ });
20
23
  assert.equal(failure.errorCode, "NO_MATCH");
21
- assert.deepEqual(failure.facts, { rule: 2 });
24
+ assert.deepEqual(failure.facts, { unmatched: ["replacements[2]"] });
22
25
  assert.equal(failure.cause, cause);
23
26
  });
27
+
28
+ test("filesystem errors → classify missing paths and directories consistently", () => {
29
+ assert.equal(PATH_ERROR_MESSAGES.PATH_NOT_FOUND, "Path not found.");
30
+ assert.equal(PATH_ERROR_MESSAGES.NOT_REGULAR_FILE, "Path is not a regular file.");
31
+ for (const [code, expected] of [
32
+ ["ENOENT", "PATH_NOT_FOUND"],
33
+ ["EISDIR", "NOT_REGULAR_FILE"],
34
+ ["EPERM", "FILESYSTEM_ERROR"],
35
+ ] as const) {
36
+ assert.equal(filesystemErrorCode({ code }), expected);
37
+ }
38
+ assert.equal(filesystemErrorCode(new Error()), undefined);
39
+ });
@@ -8,8 +8,6 @@
8
8
 
9
9
  import type { ErrorCode, ErrorFacts, NextVariant } from "../pi/report-schema.ts";
10
10
 
11
- export type { ErrorCode } from "../pi/report-schema.ts";
12
-
13
11
  /** Options of a failure of `C`: its facts are required exactly when the code has required facts. */
14
12
  export type HashlineErrorOptions<C extends ErrorCode> = {
15
13
  /** The failure beneath this step; reported as structured `cause`, never folded into `message`. */
@@ -50,6 +48,12 @@ export const TEXT_ERROR_MESSAGES = {
50
48
  INVALID_UNICODE: "Content cannot be encoded losslessly as UTF-8.",
51
49
  } as const satisfies Partial<Record<ErrorCode, string>>;
52
50
 
51
+ /** Messages for an unusable path, which every tool reports alike whichever step found it. */
52
+ export const PATH_ERROR_MESSAGES = {
53
+ PATH_NOT_FOUND: "Path not found.",
54
+ NOT_REGULAR_FILE: "Path is not a regular file.",
55
+ } as const satisfies Partial<Record<ErrorCode, string>>;
56
+
53
57
  /** Message text for a caught value; non-Error throws are stringified. */
54
58
  export function errorMessage(error: unknown): string {
55
59
  return error instanceof Error ? error.message : String(error);
@@ -65,11 +69,34 @@ export function errnoCode(error: unknown): string | undefined {
65
69
  : undefined;
66
70
  }
67
71
 
68
- /** Classify a filesystem error: only ENOENT means a missing path; other errno failures keep their cause. */
72
+ /**
73
+ * Classify a filesystem error: only ENOENT means a missing path and only EISDIR a directory
74
+ * target; other errno failures keep their cause.
75
+ */
69
76
  export function filesystemErrorCode(
70
77
  error: unknown,
71
- ): "PATH_NOT_FOUND" | "FILESYSTEM_ERROR" | undefined {
78
+ ): "PATH_NOT_FOUND" | "NOT_REGULAR_FILE" | "FILESYSTEM_ERROR" | undefined {
72
79
  const code = errnoCode(error);
73
80
  if (code === undefined) return undefined;
74
- return code === "ENOENT" ? "PATH_NOT_FOUND" : "FILESYSTEM_ERROR";
81
+ if (code === "ENOENT") return "PATH_NOT_FOUND";
82
+ return code === "EISDIR" ? "NOT_REGULAR_FILE" : "FILESYSTEM_ERROR";
83
+ }
84
+
85
+ /** A missing path or directory target as every tool reports it; undefined for any other failure. */
86
+ export function pathError(error: unknown): HashlineError | undefined {
87
+ if (error instanceof HashlineError)
88
+ return error.errorCode in PATH_ERROR_MESSAGES ? error : undefined;
89
+ const code = filesystemErrorCode(error);
90
+ const cause = error instanceof Error ? error.cause : undefined;
91
+ if (code === "PATH_NOT_FOUND") {
92
+ // Node's resolved path shows where a relative path led, such as under the wrong directory.
93
+ const path: unknown = Reflect.get(error as object, "path");
94
+ return new HashlineError(code, PATH_ERROR_MESSAGES[code], {
95
+ cause,
96
+ facts: typeof path === "string" ? { missing: [path] } : {},
97
+ });
98
+ }
99
+ return code === "NOT_REGULAR_FILE"
100
+ ? new HashlineError(code, PATH_ERROR_MESSAGES[code], { cause })
101
+ : undefined;
75
102
  }
@@ -4,12 +4,19 @@ import { computeLineHash } from "./hash.ts";
4
4
 
5
5
  const ALLOWED = new Set("0123456789ABCDEFGHJKMNPQRSTVWXYZ");
6
6
 
7
- test("computeLineHash is stable and base32", () => {
7
+ test("computeLineHash is stable and uses the configured base32 length", () => {
8
8
  const a = computeLineHash(3, "code", 4);
9
9
  const b = computeLineHash(3, "code", 4);
10
10
  assert.equal(a, b);
11
11
  assert.equal(a.length, 4);
12
12
  for (const ch of a) assert.ok(ALLOWED.has(ch), `bad char ${ch}`);
13
+ for (let i = 0; i < 2000; i++) {
14
+ const hash = computeLineHash(i + 1, `line ${i}`, 4);
15
+ for (const ch of hash) assert.ok(ALLOWED.has(ch), `bad char ${ch} in ${hash}`);
16
+ }
17
+ for (let i = 1; i <= 20; i++) {
18
+ assert.equal(computeLineHash(i, `content ${i}`, 8).length, 8);
19
+ }
13
20
  });
14
21
 
15
22
  test("different line number → different hash (even for identical content)", () => {
@@ -21,26 +28,11 @@ test("different content → different hash", () => {
21
28
  assert.notEqual(computeLineHash(1, "a", 4), computeLineHash(1, "b", 4));
22
29
  });
23
30
 
24
- test("base32 alphabet (without I/L/O/U) in bulk", () => {
25
- for (let i = 0; i < 2000; i++) {
26
- const h = computeLineHash(i + 1, `line ${i}`, 4);
27
- for (const ch of h) assert.ok(ALLOWED.has(ch), `bad char ${ch} in ${h}`);
28
- }
29
- });
30
-
31
31
  test("truncated checksums can collide", () => {
32
32
  assert.equal(computeLineHash(1, "const value = 558;", 4), "TM02");
33
33
  assert.equal(computeLineHash(1, "const value = 9344;", 4), "TM02");
34
34
  });
35
35
 
36
- test("hashLen 8 has a leading zero due to the 32-bit hash limit", () => {
37
- for (let i = 1; i <= 20; i++) {
38
- const h = computeLineHash(i, `content ${i}`, 8);
39
- assert.equal(h.length, 8);
40
- assert.equal(h[0], "0");
41
- }
42
- });
43
-
44
36
  test("computeLineHash produces output identical to hashing full interpolated string", () => {
45
37
  function referenceHash(line: number, content: string, len: number): string {
46
38
  let h = 0x811c9dc5;