@criogaid/pi-hashline-edit 0.2.0 → 0.3.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.
package/README.md CHANGED
@@ -66,7 +66,11 @@ Successful `edit` and `replace` results omit candidate rows whose full content a
66
66
  | `replace` | Replace every occurrence of a literal string or JavaScript regex across one file. |
67
67
  | `write` | Create a file or replace its complete contents. |
68
68
 
69
- All tools accept relative or absolute paths and expand a leading `~`. Mutation tools share the file-mutation queue and commit layer.
69
+ All tools accept relative and absolute paths, `file://` URLs, a leading `@` prefix, and a leading `~` (including `~\` on Windows). As in Pi's built-in file tools, supported Unicode spaces in paths become regular spaces, and Windows shell drive paths such as `/c/file`, `/mnt/c/file`, and `/cygdrive/c/file` resolve to native drive paths. Mutation tools share the file-mutation queue and commit layer.
70
+
71
+ All text inspection and matching uses one logical representation: CRLF boundaries become LF; standalone CR and source-code escape sequences such as the four characters `\r\n` remain content. `read` and `grep` hash the same logical lines that `edit` verifies; literal and regex `replace` both match this LF view. Mutation offsets map back to the original text. `edit` and `replace` share separator restoration: reuse internal separators positionally, repeat the last for extra gaps, or use the file style (CRLF if present, otherwise LF) when none exist. Boundaries outside the replacement stay unchanged.
72
+
73
+ `write` is the full-content boundary: its supplied bytes are authoritative, so it preserves their explicit LF/CRLF choices. Use it for intentional whole-file line-ending conversion. To inspect actual line-ending bytes, use a raw byte reader; anchored line displays intentionally do not distinguish LF from CRLF.
70
74
 
71
75
  ### Edit operations
72
76
 
@@ -101,7 +105,11 @@ For a rename across a file:
101
105
  { "path": "src/foo.ts", "find": "oldName", "replace": "newName" }
102
106
  ```
103
107
 
104
- Literal mode inserts replacement text verbatim. Set `regex: true` for JavaScript capture groups and replacement templates:
108
+ Literal mode keeps `$` text verbatim. Both literal and regex modes match the shared LF view: actual CRLF in the file and `find` normalizes to LF; standalone CR remains content. Match ranges map back to the original text before replacement, preserving bytes and separators outside each match, including an unmatched BOM or final newline.
109
+
110
+ Replacement text also normalizes CRLF to LF, then reuses matched separators in order. Additional lines use the last matched separator, or the file style when the match contains no separator (CRLF if present anywhere, otherwise LF).
111
+
112
+ Regex patterns run on LF text, so use `\n` for a line boundary. Captures and replacement templates also use the LF snapshot; the result then restores original separators. Use `write` for explicit line-ending conversion. Source-code escapes are ordinary text: JSON `"find": "\\r\\n"` finds the visible four-character sequence in literal mode, while `"find": "\r\n"` contains an actual CRLF boundary. Set `regex: true` for JavaScript capture groups and replacement templates:
105
113
 
106
114
  ```json
107
115
  { "path": "src/foo.ts", "find": "get([A-Z]\\w*)", "replace": "fetch$1", "regex": true }
@@ -136,7 +144,7 @@ Required: `path`. Optional: 1-based `offset` (default 1) and `limit` (default 20
136
144
  | `path` | Current directory | One path or an array of search roots. |
137
145
  | `matchMode` | `"any"` | OR across patterns; `"all"` requires every pattern on the same physical line, at most 16 patterns. |
138
146
  | `excludePattern` | None | String or array; remove lines matching any exclusion. |
139
- | `literal` | Automatic | `true`: literal strings. `false`: strict regex. Automatic mode detects regex metacharacters; parse failures fall back to literal text only for one inclusion pattern without exclusions. Invalid compound queries fail with guidance to fix the regex or explicitly set `literal: true`. |
147
+ | `literal` | Automatic | Set `true` for code text containing regex punctuation, such as `pi.on(`, `compact(`, or a visible `\0`; use a `pattern` array for literal alternatives. Set `false` only for intentional valid regex. The setting also applies to exclusions. Automatic mode tries regex when it sees metacharacters; an invalid single pattern without exclusions falls back to searching the **entire string** literally, not interpreting `|` as alternatives. Invalid compound queries fail rather than changing their meaning. |
140
148
  | `ignoreCase` | Smart-case | Explicit `true`/`false` overrides case handling; the query-level decision also applies to exclusions. |
141
149
  | `wordMatch` | `false` | Whole-word matches. |
142
150
  | `glob` | None | One glob or an ordered array; prefix exclusions with `!`. |
@@ -150,7 +158,7 @@ Required: `path`. Optional: 1-based `offset` (default 1) and `limit` (default 20
150
158
 
151
159
  Context is rebuilt from surviving matches. Multiline filtering, counting, and limits remain line-based. Wildcard-only regexes such as `.*` and `^.+$` are accepted; use `literal: true` to search those characters verbatim.
152
160
 
153
- All inclusion/exclusion matching uses bundled ripgrep, independent of system `rg` or `PATH`. Searches are CRLF-aware, include hidden files while respecting ignore rules, and pass `--no-config`. The default engine is Rust regex; PCRE2 never silently falls back to another engine or literal matching.
161
+ All inclusion/exclusion matching uses bundled ripgrep on the shared LF view, independent of system `rg` or `PATH`. File selection uses original paths, ignore rules, globs, and link settings. Search batches stage up to 64 normalized temporary files or 8 MiB of text (one large file can exceed that threshold); snapshots are removed after each batch and on failure/cancellation. This adds temporary disk I/O. Match paths refer to original files; line and column positions refer to logical text. Searches include hidden files and pass `--no-config`, `--no-crlf`, and `--encoding=none` for snapshot matching so standalone CR and BOM remain content. The default engine is Rust regex; PCRE2 never silently falls back to another engine or literal matching.
154
162
 
155
163
  Search diagnostics are preserved even when a result limit stops ripgrep. Readable, confirmed matches remain available with a `Search incomplete` notice and `details.incomplete: true`; counts then cover only confirmed matches. If no results can be returned, the tool reports an error rather than claiming there are no matches. Exclusion-scan failures still reject the query, because incomplete exclusions could admit incorrect results. Search diagnostics have a separate 4 KiB display budget.
156
164
 
@@ -160,13 +168,13 @@ Long lines show a labeled partial preview of up to 500 UTF-16 units around a rip
160
168
 
161
169
  Required: `path` and either top-level `find` / `replace`, or a non-empty `replacements` array. These forms are mutually exclusive: batch calls cannot include top-level `find`, `replace`, `regex`, `flags`, or `maxMatches`. Each rule requires `find` and `replace`, with these optional fields:
162
170
 
163
- - `regex`: defaults to `false`; regex mode supports capture groups, the full match, and prefix/suffix substitutions.
171
+ - `regex`: defaults to `false`; both modes match the shared LF view. Regex mode supports capture groups, the full match, and prefix/suffix substitutions.
164
172
  - `flags`: applies in both modes; `g` is always added. Supported flags: `g i m s u y d`.
165
173
  - `maxMatches`: defaults to 2000 per rule and must be finite and positive; rejects excess matches before writing. Raise it for intentional bulk changes. It does not bound regex execution time or result size.
166
174
 
167
- Zero matches in any rule, an invalid rule, or overlapping match ranges rejects the whole call without writing. Adjacent ranges are allowed. Zero-length matches conflict at the same position or at the start/interior of another match; a zero-length match at another match's end is allowed unless it conflicts with a following match. Error rule indices and string offsets are zero-based (offsets count UTF-16 code units).
175
+ Zero matches in any rule, an invalid rule, or overlapping match ranges rejects the whole call without writing. Adjacent ranges are allowed. Zero-length matches conflict at the same position or at the start/interior of another match; a zero-length match at another match's end is allowed unless it conflicts with a following match. Error rule indices and string offsets are zero-based (offsets count UTF-16 code units in the original text). Literal and regex rules share the same original ranges for conflict detection.
168
176
 
169
- Regex captures and prefix/suffix substitutions always refer to the original snapshot.
177
+ Regex captures and prefix/suffix substitutions always refer to the original LF-normalized snapshot.
170
178
 
171
179
  ### Write
172
180
 
@@ -225,7 +233,7 @@ Action Fusion is enabled by default. Set `"actionFusion": false` in `hashlineEdi
225
233
 
226
234
  `command` is required; `timeout` is optional, in positive seconds, with no default. Mutation failure skips the command. Command failure after mutation success **does not roll back the file**: it is returned separately in result text and `details.actionFusion`, rather than thrown as failure of the whole mutation.
227
235
 
228
- In the TUI, the mutation card turns successful when execution and result generation finish. The command gets its own waiting/running/success/failure card with expandable output. Command failure leaves the successful mutation card intact. RPC hosts receive the same progress and choose their own rendering.
236
+ In the TUI, the mutation card owns the mutation's result or error summary, publication status, and freshness warnings. It turns successful when mutation execution and result generation finish. The command card owns command output and execution status; skipped or cancelled commands are neutral and show a short reason when execution never started. Mutation diagnostics never become command output, and command failure leaves a successful mutation card intact. RPC hosts receive the same progress and choose their own rendering.
229
237
 
230
238
  Fusion serializes each mutation/command sequence for its target and checks the published revision before running the command. Commands invoke Pi's built-in Bash definition directly, without a separate Bash tool call; Bash-only approval/sandbox extensions must explicitly cover these tools' `then_run` inputs.
231
239
 
@@ -245,7 +253,7 @@ Fusion serializes each mutation/command sequence for its target and checks the p
245
253
 
246
254
  `read` computes line hashes only for its requested window; `grep` hashes selected matches/context. Both still read and decode whole files. Mutation revision checks cover actual bytes.
247
255
 
248
- Line boundaries are LF or CRLF; a standalone CR remains line content. Anchored rows display standalone CR as `␍` (U+240D), while hashes use the original content. Edit/replace diff previews also show CR as `␍`, including CR in CRLF endings; their unified patches retain the original characters and line endings. The marker is a display aid, not replacement text.
256
+ Line boundaries are LF or CRLF; a standalone CR remains line content. Anchored rows display standalone CR as `␍` (U+240D), while hashes use the original content. Edit/replace `details.diff` marks raw CR as `␍`; `details.displayDiff` renders the shared LF view for the TUI, so CRLF boundary markers stay hidden even in mixed-ending files or beside an unterminated last line. Standalone CR and literal `␍` characters remain visible. Unified patches retain the original characters and line endings. The marker is a display aid, not replacement text.
249
257
 
250
258
  An existing UTF-8 BOM stays at byte zero through first-line replacement/deletion or insertion; deleting all content leaves the BOM. First-line hashes include it. A copied leading BOM in the first replacement/insertion line denotes the existing header; interior `U+FEFF` remains content. BOM-only files retain one anchored line. `replace` can explicitly match the BOM; `write` uses supplied content.
251
259
 
@@ -291,6 +299,6 @@ The shared commit layer validates the target and skips publication when the requ
291
299
  | `actionFusion.freshness` | `unchanged`, `changed`, `missing`, or `unknown`, relative to the published revision. |
292
300
  | `actionFusion.mutationCompleted` | Progress flag set after mutation execution and result generation succeed; publication alone is not mutation success. |
293
301
 
294
- Streaming mutation summaries omit anchors. Result-generation failures preserve publication status; progress callback failures are reported separately from mutation/command outcomes. Command output appears on its own card with native Bash rendering. Final cards survive reloads without adding model-context messages; unfinished saved commands show an interrupted/unknown outcome.
302
+ Streaming mutation summaries omit anchors. Result-generation failures preserve publication status and any completed command outcome; progress callback failures are reported separately from mutation/command outcomes. Command progress `output` contains only command output or execution errors, with an optional `reason` for commands that never started. Command cards persist only their own state and use native Bash output rendering. Final cards survive reloads without adding model-context messages; unfinished saved commands show an interrupted/unknown outcome. Older mixed failure snapshots expose only recognized command diagnostics, leaving other details in the original tool result.
295
303
 
296
304
  </details>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@criogaid/pi-hashline-edit",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "Hashline-style file editing for pi — line-anchored edits verified by content hash, replacing oldText/newText matching",
6
6
  "homepage": "https://github.com/Criogaid/pi-hashline-edit#readme",
@@ -205,8 +205,8 @@ test("replacing one line with several keeps the block's trailing gap", () => {
205
205
  const result = applyEdits(before, [{ op: "replace", start: at(before, 2), body: ["X", "Y", "Z"] }]);
206
206
  assert.equal(result.ok, true);
207
207
  // b's gap (\n) moves to the last new line, so the boundary to c is unchanged;
208
- // the two new interior gaps borrow positionally, then fall back to crlf.
209
- if (result.ok) assert.equal(result.text, "a\r\nX\nY\r\nZ\nc\r\nd");
208
+ // b has no internal gap; both new internal gaps use the file style, like replace("b", "X\nY\nZ").
209
+ if (result.ok) assert.equal(result.text, "a\r\nX\r\nY\r\nZ\nc\r\nd");
210
210
  });
211
211
 
212
212
  test("a file without a final newline keeps not having one", () => {
package/src/core/apply.ts CHANGED
@@ -28,7 +28,7 @@
28
28
  */
29
29
 
30
30
  import { computeLineHash } from "./hash.ts";
31
- import { detectLineEnding, hasFinalNewline, splitLines } from "./lines.ts";
31
+ import { detectLineEnding, hasFinalNewline, lineSeparators, replacementSeparator, splitLines } from "./lines.ts";
32
32
  import type { Anchor, AnchorCheck, AnchorFailure, AnchorRecovery, ApplyResult, Edit } from "./types.ts";
33
33
  import { findSortedRangeConflict } from "./ranges.ts";
34
34
 
@@ -244,20 +244,22 @@ export function applyEdits(text: string, edits: Edit[], hashLen = 4, shiftRadius
244
244
  // the original (its gap), so surviving lines keep theirs byte for byte. New
245
245
  // gaps borrow the removed block's separators positionally — the last new
246
246
  // line inherits the block's trailing gap, leaving the boundary to the next
247
- // surviving line unchanged; gaps past the removed block's length (or in a
248
- // pure insertion) fall back to the file's customary ending.
249
- const separators = text.match(/\r?\n/g) ?? [];
247
+ // surviving line unchanged. Internal gaps use the same positional/last-gap
248
+ // rule as substring replacements, falling back to the file style for insertions.
249
+ const separators = lineSeparators(text);
250
250
  const separator = ending === "crlf" ? "\r\n" : "\n";
251
251
  // Verify legacy anchors above before separating the file BOM from movable line content.
252
252
  let result = lines.map((content, i) => ({ content: bom && i === 0 ? content.slice(1) : content, separator: separators[i] ?? "" }));
253
253
  for (const op of [...sorted].sort((a, b) => b.lo - a.lo)) {
254
254
  const removed = result.slice(op.lo, op.hi);
255
+ // The trailing gap is outside the logical replacement, just as in substring replacement.
256
+ const removedSeparators = removed.slice(0, -1).map((line) => line.separator);
255
257
  const inserted = op.newLines.map((content, i) => ({
256
258
  // A copied first-line BOM denotes the existing file header, not a second BOM.
257
259
  content: bom && op.lo === 0 && i === 0 && content.startsWith(bom) ? content.slice(1) : content,
258
260
  separator: i === op.newLines.length - 1 && removed.length > 0
259
261
  ? removed[removed.length - 1].separator
260
- : removed[i]?.separator || separator,
262
+ : replacementSeparator(removedSeparators, i, separator),
261
263
  }));
262
264
  result.splice(op.lo, op.hi - op.lo, ...inserted);
263
265
  }
@@ -1,6 +1,6 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { splitLines, detectLineEnding, hasFinalNewline } from "./lines.ts";
3
+ import { createLfTextView, normalizeLineEndings, splitLines, detectLineEnding, hasFinalNewline } from "./lines.ts";
4
4
 
5
5
  test("splitLines edge cases", () => {
6
6
  assert.deepEqual(splitLines(""), []);
@@ -31,3 +31,14 @@ test("detectLineEnding", () => {
31
31
  assert.equal(detectLineEnding("a\r\nb\r\n"), "crlf");
32
32
  assert.equal(detectLineEnding("a\nb\r\nc\n"), "crlf");
33
33
  });
34
+
35
+ test("LF views map every UTF-16 boundary back to original CRLF bytes", () => {
36
+ for (const source of ["", "a\nb", "\uFEFF😀\r\nb\nc\r\n", "\r\n\r\n", "a\rb\r\r\nc"]) {
37
+ const view = createLfTextView(source);
38
+ assert.equal(view.text, normalizeLineEndings(source));
39
+ assert.equal(view.sourceOffset(view.text.length), source.length);
40
+ for (let offset = 0; offset <= view.text.length; offset++) {
41
+ assert.equal(normalizeLineEndings(source.slice(0, view.sourceOffset(offset))), view.text.slice(0, offset));
42
+ }
43
+ }
44
+ });
package/src/core/lines.ts CHANGED
@@ -18,6 +18,48 @@
18
18
 
19
19
  import type { LineEnding } from "./types.ts";
20
20
 
21
+ /** Normalize CRLF boundaries to LF; standalone CR remains content. */
22
+ export function normalizeLineEndings(text: string): string {
23
+ return text.replace(/\r\n/g, "\n");
24
+ }
25
+
26
+ /** Raw separators in logical-line order, shared by both mutation applicators. */
27
+ export function lineSeparators(text: string): string[] {
28
+ return text.match(/\r?\n/g) ?? [];
29
+ }
30
+
31
+ /** New internal gaps reuse the corresponding old gap, then the last gap or file style. */
32
+ export function replacementSeparator(separators: readonly string[], index: number, fallback: string): string {
33
+ return separators[index] || separators[separators.length - 1] || fallback;
34
+ }
35
+
36
+ /** Restore a logical replacement without normalizing it a second time. */
37
+ export function restoreLineEndings(logical: string, original: string, fallback: string): string {
38
+ const separators = lineSeparators(original);
39
+ let index = 0;
40
+ return logical.replace(/\n/g, () => replacementSeparator(separators, index++, fallback));
41
+ }
42
+
43
+ /** Build an LF matching view with UTF-16 boundary offsets back into the original text. */
44
+ export function createLfTextView(source: string) {
45
+ const removed: number[] = [];
46
+ for (const match of source.matchAll(/\r\n/g)) removed.push(match.index! - removed.length);
47
+ return {
48
+ text: normalizeLineEndings(source),
49
+ sourceOffset(offset: number): number {
50
+ // Count removed CRs strictly before this boundary: a newline starts at its original CR.
51
+ let lo = 0;
52
+ let hi = removed.length;
53
+ while (lo < hi) {
54
+ const mid = Math.floor((lo + hi) / 2);
55
+ if (removed[mid] < offset) lo = mid + 1;
56
+ else hi = mid;
57
+ }
58
+ return offset + lo;
59
+ },
60
+ };
61
+ }
62
+
21
63
  /**
22
64
  * Split text into lines, normalizing CRLF boundaries and preserving standalone `\r`.
23
65
  *
@@ -30,7 +72,7 @@ import type { LineEnding } from "./types.ts";
30
72
  */
31
73
  export function splitLines(text: string): string[] {
32
74
  if (text === "") return [];
33
- const normalized = text.replace(/\r\n/g, "\n");
75
+ const normalized = normalizeLineEndings(text);
34
76
  return (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
35
77
  }
36
78
 
@@ -510,3 +510,115 @@ test("long-line previews expose real rg hits across engines and preserve full-li
510
510
  }
511
511
  } finally { await rm(directory, { recursive: true, force: true }); }
512
512
  });
513
+
514
+ test("all text tools share logical CRLF matching, anchors, and mutation separators", async () => {
515
+ const directory = await mkdtemp(join(tmpdir(), "hl-shared-text-"));
516
+ try {
517
+ const path = join(directory, "mixed.txt");
518
+ const before = "\uFEFFhead\r\nalpha\r\nbeta\nstand\rCR\r\r\nlast";
519
+ const write = makeWriteOverride(directory);
520
+ const read = makeReadOverride(directory);
521
+ const grep = makeGrepOverrideWithBackend(directory, {});
522
+ await write.execute("write", { path, content: before }, undefined, undefined);
523
+ assert.equal(await readFile(path, "utf8"), before);
524
+ const observed = await read.execute("read", { path }, undefined, undefined);
525
+ assert.ok(observed.content[0].type === "text");
526
+ const rows = observed.content[0].text.split("\n").filter((line: string) => /^\d+#[0-9A-Z]+│/.test(line));
527
+ for (const query of [
528
+ { pattern: "alpha\r\nbeta", literal: true },
529
+ { pattern: "alpha\\nbeta", literal: false },
530
+ { pattern: "alpha\\nbeta", literal: false, pcre2: true },
531
+ { pattern: ["alpha\\nbeta", "alpha|beta"], matchMode: "all", literal: false },
532
+ ]) {
533
+ const found = await grep.execute("grep", { path, multiline: true, ignoreCase: false, ...query }, undefined, undefined);
534
+ assert.ok(found.content[0].text.includes(rows[1]), JSON.stringify(query));
535
+ assert.ok(found.content[0].text.includes(rows[2]), JSON.stringify(query));
536
+ }
537
+ const excluded = await grep.execute("grep", { path, pattern: "alpha\\nbeta", excludePattern: "alpha", multiline: true, literal: false }, undefined, undefined);
538
+ assert.ok(!excluded.content[0].text.includes(rows[1]));
539
+ assert.ok(excluded.content[0].text.includes(rows[2]));
540
+ const carriage = await grep.execute("grep", { path, pattern: "\\r", literal: false }, undefined, undefined);
541
+ assert.ok(carriage.content[0].text.includes(rows[3]));
542
+ assert.ok(!carriage.content[0].text.includes(rows[1]));
543
+ const standaloneEnd = await grep.execute("grep", { path, pattern: "CR\\r$", literal: false }, undefined, undefined);
544
+ assert.ok(standaloneEnd.content[0].text.includes(rows[3]));
545
+
546
+ const expected = "\uFEFFhead\r\nA\r\nB\r\nC\nstand\rCR\r\r\nlast";
547
+ for (const mode of ["edit", "literal", "regex"]) {
548
+ await write.execute("reset", { path, content: before }, undefined, undefined);
549
+ if (mode === "edit") {
550
+ await makeEditOverride(directory).execute("edit", { path, edits: [{ op: "replace", anchor: rows[1].split("│")[0], end: rows[2].split("│")[0], body: ["A", "B", "C"] }] }, undefined, undefined);
551
+ } else {
552
+ await makeReplaceTool(directory).execute("replace", { path, find: mode === "regex" ? "alpha\\nbeta" : "alpha\r\nbeta", replace: "A\nB\nC", regex: mode === "regex" }, undefined, undefined);
553
+ }
554
+ assert.equal(await readFile(path, "utf8"), expected, mode);
555
+ }
556
+ // Whole-file write remains the explicit representation boundary, including EOL conversion.
557
+ await write.execute("convert", { path, content: "alpha\nbeta\n" }, undefined, undefined);
558
+ assert.equal(await readFile(path, "utf8"), "alpha\nbeta\n");
559
+ } finally {
560
+ await rm(directory, { recursive: true, force: true });
561
+ }
562
+ });
563
+
564
+ test("visible source escapes remain readable and searchable while real CRLF stays preserved", async () => {
565
+ const directory = await mkdtemp(join(tmpdir(), "hl-source-escapes-"));
566
+ try {
567
+ const path = join(directory, "escapes.ts");
568
+ const code = 'const eol = "\\r\\n";\r\n';
569
+ await makeWriteOverride(directory).execute("write", { path, content: code }, undefined, undefined);
570
+ const read = await makeReadOverride(directory).execute("read", { path }, undefined, undefined);
571
+ assert.ok(read.content[0].type === "text");
572
+ assert.ok(read.content[0].text.includes(String.raw`const eol = "\r\n";`));
573
+ const grep = makeGrepOverrideWithBackend(directory, {});
574
+ for (const query of [
575
+ { pattern: String.raw`\r\n`, literal: true },
576
+ { pattern: String.raw`\\r\\n`, literal: false },
577
+ { pattern: String.raw`\\r\\n`, literal: false, pcre2: true },
578
+ ]) {
579
+ const result = await grep.execute("grep", { path, ...query, ignoreCase: false }, undefined, undefined);
580
+ assert.ok(result.content[0].text.includes(String.raw`const eol = "\r\n";`));
581
+ }
582
+ const replace = makeReplaceTool(directory);
583
+ await replace.execute("literal", { path, find: String.raw`\r\n`, replace: String.raw`\n` }, undefined, undefined);
584
+ assert.equal(await readFile(path, "utf8"), 'const eol = "\\n";\r\n');
585
+ await replace.execute("regex", { path, find: String.raw`\\n`, replace: String.raw`\r\n`, regex: true }, undefined, undefined);
586
+ assert.equal(await readFile(path, "utf8"), code);
587
+ } finally {
588
+ await rm(directory, { recursive: true, force: true });
589
+ }
590
+ });
591
+
592
+ test("normalized grep batches retain original paths, literal option markers, and decode diagnostics", async () => {
593
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-snapshots-"));
594
+ try {
595
+ await Promise.all(Array.from({ length: 70 }, (_, i) => writeFile(join(directory, `file ${i}.txt`), "--\r\n")));
596
+ await writeFile(join(directory, "invalid.txt"), Buffer.from([0xc3, 0x28]));
597
+ const grep = makeGrepOverrideWithBackend(directory, {});
598
+ const result = await grep.execute("grep", { path: directory, pattern: "--", literal: true, outputMode: "count", limit: 100 }, undefined, undefined);
599
+ assert.equal((result.content[0].text.match(/file \d+\.txt: 1/g) ?? []).length, 70);
600
+ assert.match(result.content[0].text, /Search incomplete/);
601
+ assert.match(result.content[0].text, /invalid\.txt/);
602
+ assert.match(result.content[0].text, /UNSUPPORTED_ENCODING/);
603
+ assert.doesNotMatch(result.content[0].text, /hashline-grep-/);
604
+ } finally {
605
+ await rm(directory, { recursive: true, force: true });
606
+ }
607
+ });
608
+
609
+ test("NUL files are rejected on a confirmed hit, not reported as no match", async () => {
610
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-nul-"));
611
+ try {
612
+ const binary = join(directory, "binary.txt");
613
+ await writeFile(binary, Buffer.from("needle\r\nother\0needle\n"));
614
+ const grep = makeGrepOverrideWithBackend(directory, {});
615
+ await assert.rejects(grep.execute("grep", { path: binary, pattern: "needle", literal: true }, undefined, undefined), /UNSUPPORTED_TEXT/);
616
+ const absent = await grep.execute("grep", { path: binary, pattern: "absent", literal: true }, undefined, undefined);
617
+ assert.equal(absent.content[0].type, "text");
618
+ if (absent.content[0].type === "text") assert.equal(absent.content[0].text, "No matches found");
619
+ await writeFile(join(directory, "valid.txt"), "needle\n");
620
+ await assert.rejects(grep.execute("grep", { path: directory, pattern: "needle", literal: true }, undefined, undefined), /UNSUPPORTED_TEXT/);
621
+ } finally {
622
+ await rm(directory, { recursive: true, force: true });
623
+ }
624
+ });
@@ -228,6 +228,8 @@ test("progress reports skipped mutations and failed commands without rolling bac
228
228
  await assert.rejects(makeEditOverride(dir, fusion).execute("skip", { path: "missing.txt", edits: [{ op: "append", body: ["after"] }], then_run: { command: "check" } }, undefined, undefined, ctx(dir)));
229
229
  assert.equal(commands, 0);
230
230
  assert.deepEqual(events.map((event) => event.command), ["waiting", "skipped"]);
231
+ assert.equal(events.at(-1)!.output, "");
232
+ assert.equal(events.at(-1)!.reason, "Not run because the mutation did not complete.");
231
233
  events.length = 0;
232
234
  await writeFile(join(dir, "replace.txt"), "original\n");
233
235
  await assert.rejects(makeReplaceTool(dir, fusion).execute("replace-skip", { path: "replace.txt", find: "missing", replace: "changed", then_run: { command: "check" } }, undefined, undefined, ctx(dir)), /no matches/);
@@ -238,7 +240,7 @@ test("progress reports skipped mutations and failed commands without rolling bac
238
240
  const failed = await makeWriteOverride(dir, fusion).execute("fail", { path: "failed.txt", content: "published\n", then_run: { command: "check" } }, undefined, undefined, ctx(dir));
239
241
  assert.equal(failed.details.actionFusion.command, "failed");
240
242
  assert.deepEqual(events.map((event) => event.command), ["waiting", "waiting", "running", "failed"]);
241
- assert.match(events.at(-1)!.output, /diagnostic[\s\S]*code 7/);
243
+ assert.equal(events.at(-1)!.output, "diagnostic\nCommand exited with code 7");
242
244
  assert.equal(await readFile(join(dir, "failed.txt"), "utf8"), "published\n");
243
245
  } finally {
244
246
  await rm(dir, { recursive: true, force: true });
@@ -35,7 +35,10 @@ export interface ActionFusionProgress extends Omit<ActionFusionDetails, "command
35
35
  path: string;
36
36
  commandText: string;
37
37
  command: Exclude<CommandStatus, "not_requested"> | "waiting" | "running";
38
+ /** Command output or command execution errors only. */
38
39
  output: string;
40
+ /** A short explanation when the command was not started; never mutation diagnostics. */
41
+ reason?: string;
39
42
  /** True only after mutation execution and result generation both succeed. */
40
43
  mutationCompleted: boolean;
41
44
  }
@@ -88,13 +91,18 @@ export class ActionFusionError extends Error {
88
91
  readonly publication: PublicationStatus;
89
92
  readonly command: CommandStatus;
90
93
  readonly freshness: Freshness;
94
+ readonly commandOutput: string;
95
+ readonly commandReason: string | undefined;
91
96
 
92
- constructor(message: string, state: { publication: PublicationStatus; command: CommandStatus; freshness: Freshness }, options?: { cause?: unknown }) {
97
+ constructor(message: string, state: { publication: PublicationStatus; command: CommandStatus; freshness: Freshness }, options?: { cause?: unknown; mutationFailure?: boolean; commandOutput?: string; commandReason?: string }) {
93
98
  const fileState = state.publication === "PUBLISHED" ? "File changes are saved."
94
99
  : state.publication === "NOT_PUBLISHED" ? "No file changes were published." : "File state is uncertain.";
95
- super(`${message} ${state.command === "skipped" || state.command === "cancelled" ? THEN_RUN_SKIPPED : state.command === "succeeded" ? THEN_RUN_SUCCEEDED : THEN_RUN_FAILED}\n${fileState} Command ${state.command}.`, options);
96
- // Pi exposes error.message to the model, but does not serialize Error.cause.
97
- if (options?.cause !== undefined) this.message += `\n${errorText(options.cause)}`;
100
+ const outcome = `${message} ${state.command === "skipped" || state.command === "cancelled" ? THEN_RUN_SKIPPED : state.command === "succeeded" ? THEN_RUN_SUCCEEDED : THEN_RUN_FAILED}\n${fileState} Command ${state.command}.`;
101
+ const diagnostic = options?.cause === undefined ? "" : errorText(options.cause);
102
+ // Pi serializes only the message. Put the mutation's own error first for its card.
103
+ super((options?.mutationFailure ? [diagnostic, outcome] : [outcome, diagnostic]).filter(Boolean).join("\n"), options);
104
+ this.commandOutput = options?.commandOutput ?? "";
105
+ this.commandReason = options?.commandReason;
98
106
  this.name = "ActionFusionError";
99
107
  this.publication = state.publication;
100
108
  this.command = state.command;
@@ -187,14 +195,16 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
187
195
  if (thenRun !== undefined) validateThenRun(thenRun);
188
196
  let completedMutation: MutationResult<TDetails> | undefined;
189
197
  let progressFailure: string | undefined;
190
- const report = (command: ActionFusionProgress["command"], publication: PublicationStatus, freshness: Freshness, output = "") => {
198
+ let commandSucceeded = false;
199
+ const report = (command: ActionFusionProgress["command"], publication: PublicationStatus, freshness: Freshness, output = "", reason?: string) => {
200
+ if (command === "succeeded") commandSucceeded = true;
191
201
  if (!thenRun) return;
192
- const progress: ActionFusionProgress = { toolCallId, path: absolutePath, commandText: thenRun.command, command, publication, freshness, output, mutationCompleted: completedMutation !== undefined };
202
+ const progress: ActionFusionProgress = { toolCallId, path: absolutePath, commandText: thenRun.command, command, publication, freshness, output, ...(reason ? { reason } : {}), mutationCompleted: completedMutation !== undefined };
193
203
  // Display callbacks are observers: their failures must not change publication or command execution.
194
204
  for (const notify of [
195
205
  () => onProgress?.(progress, ctx),
196
206
  () => onUpdate?.({
197
- content: [...(completedMutation?.content ?? []), { type: "text", text: `then_run ${command}: ${thenRun.command}\n${output}` }],
207
+ content: [...(completedMutation?.content ?? []), { type: "text", text: `then_run ${command}: ${thenRun.command}\n${reason ?? output}` }],
198
208
  details: { ...(completedMutation?.details as object ?? {}), actionFusion: progress },
199
209
  } as MutationResult<TDetails>),
200
210
  ]) {
@@ -204,7 +214,7 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
204
214
  report("waiting", "NOT_PUBLISHED", "unknown");
205
215
  return withQueue(absolutePath, async () => {
206
216
  try { signal?.throwIfAborted(); } catch (error) {
207
- if (thenRun !== undefined) throw new ActionFusionError("mutation was cancelled before it started; the command was not run", { publication: "NOT_PUBLISHED", command: "cancelled", freshness: "unknown" }, { cause: error });
217
+ if (thenRun !== undefined) throw new ActionFusionError("mutation was cancelled before it started; the command was not run", { publication: "NOT_PUBLISHED", command: "cancelled", freshness: "unknown" }, { cause: error, mutationFailure: true, commandReason: "Not run because the mutation was cancelled." });
208
218
  throw error;
209
219
  }
210
220
  let mutationResult: MutationResult<TDetails>;
@@ -214,7 +224,7 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
214
224
  } catch (error) {
215
225
  const publication = error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED";
216
226
  if (thenRun !== undefined) {
217
- throw new ActionFusionError(`mutation ${error instanceof FileMutationError ? error.stage : "failed"}; the command was not run`, { publication, command: "skipped", freshness: "unknown" }, { cause: error });
227
+ throw new ActionFusionError(`mutation ${error instanceof FileMutationError ? error.stage : "failed"}; the command was not run`, { publication, command: "skipped", freshness: "unknown" }, { cause: error, mutationFailure: true, commandReason: "Not run because the mutation did not complete." });
218
228
  }
219
229
  throw error;
220
230
  }
@@ -231,7 +241,7 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
231
241
 
232
242
  const baseline = mutationPublishedRevision(mutationResult);
233
243
  if (baseline === undefined) {
234
- throw new ActionFusionError("Missing published revision; cannot validate fused command freshness.", { publication, command: "skipped", freshness: "unknown" });
244
+ throw new ActionFusionError("Missing published revision; cannot validate fused command freshness.", { publication, command: "skipped", freshness: "unknown" }, { commandReason: "Not run because the mutation revision is unavailable." });
235
245
  }
236
246
  try {
237
247
  signal?.throwIfAborted();
@@ -239,7 +249,7 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
239
249
  signal?.throwIfAborted();
240
250
  } catch (error) {
241
251
  const freshness = await readFreshness(absolutePath, baseline);
242
- throw new ActionFusionError("mutation completed; the command was not run", { publication, command: signal?.aborted ? "cancelled" : "skipped", freshness }, { cause: error });
252
+ throw new ActionFusionError("mutation completed; the command was not run", { publication, command: signal?.aborted ? "cancelled" : "skipped", freshness }, { cause: error, commandReason: signal?.aborted ? "Not run because the operation was cancelled." : "Not run because the target revision could not be confirmed." });
243
253
  }
244
254
 
245
255
  report("running", publication, "unchanged");
@@ -256,7 +266,7 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
256
266
  }
257
267
  const freshness = await readFreshness(absolutePath, baseline);
258
268
  if (commandError !== undefined) {
259
- throw new ActionFusionError("mutation completed; then_run did not complete successfully", { publication, command: commandStatus(commandError, signal), freshness }, { cause: commandError });
269
+ throw new ActionFusionError("mutation completed; then_run did not complete successfully", { publication, command: commandStatus(commandError, signal), freshness }, { cause: commandError, commandOutput: errorText(commandError) });
260
270
  }
261
271
 
262
272
  const actionFusion: ActionFusionDetails = { publication, command: "succeeded", freshness };
@@ -269,9 +279,14 @@ export function createActionFusionExecutor(commandRunner: CommandRunner = defaul
269
279
  content: [...finalized.content, { type: "text", text: commandText }],
270
280
  } as MutationResult<TDetails>;
271
281
  }).catch((error: unknown) => {
272
- report(error instanceof ActionFusionError ? error.command as ActionFusionProgress["command"] : "skipped",
273
- error instanceof ActionFusionError || error instanceof FileMutationError ? error.publication : completedMutation ? mutationPublication(completedMutation) : "NOT_PUBLISHED",
274
- error instanceof ActionFusionError ? error.freshness : "unknown", errorText(error));
282
+ // Result-generation errors after a successful command must not relabel it skipped.
283
+ if (!commandSucceeded) {
284
+ report(error instanceof ActionFusionError ? error.command as ActionFusionProgress["command"] : "skipped",
285
+ error instanceof ActionFusionError || error instanceof FileMutationError ? error.publication : completedMutation ? mutationPublication(completedMutation) : "NOT_PUBLISHED",
286
+ error instanceof ActionFusionError ? error.freshness : "unknown",
287
+ error instanceof ActionFusionError ? error.commandOutput : "",
288
+ error instanceof ActionFusionError ? error.commandReason : "Not run because the mutation did not complete.");
289
+ }
275
290
  // A completed mutation remains successful; command failure belongs to its own card.
276
291
  if (completedMutation && error instanceof ActionFusionError) {
277
292
  const finalized = finalizeMutation ? finalizeMutationResult(completedMutation, finalizeMutation, error.freshness === "unchanged", staleAnchorNotice()) : completedMutation;
@@ -26,7 +26,7 @@ import { readEditableSnapshot, commitReplacement } from "./file-commit.ts";
26
26
  import { applyEdits } from "../core/index.ts";
27
27
  import { splitLines } from "../core/lines.ts";
28
28
  import type { ApplyFailure, Edit } from "../core/types.ts";
29
- import { canonicalPath } from "./read-tool.ts";
29
+ import { canonicalPath } from "./path.ts";
30
30
  import { getState } from "./state.ts";
31
31
  import { ANCHOR_PATTERN, createAnchorFormatter, type AnchorFormatter } from "./anchor-format.ts";
32
32
  import { formatDiffCounts, renderMutationCall, renderMutationResult, type DiffCounts } from "./render.ts";
@@ -762,15 +762,14 @@ test("unique candidate content is independent of oversized neighboring rows", as
762
762
  assert.equal(await readFile(file, "utf8"), before.replace("target", "updated"));
763
763
  }));
764
764
 
765
- test("CR replacements remain visible in diffs and exact in patches", async () => withDir(async (dir) => {
765
+ test("standalone CR replacements remain visible in diffs and exact in patches", async () => withDir(async (dir) => {
766
766
  const file = join(dir, "cr.txt");
767
767
  for (const [before, find, replacement] of [
768
768
  ["a\rb\n", "\r", "\n"],
769
769
  ["a\rb\n", "\r", "␍"],
770
- ["a\r\nb\r\n", "\r\n", "\n"],
771
770
  ]) {
772
771
  await writeFile(file, before);
773
- const result = await call(makeReplaceTool(dir), { path: file, find, replace: replacement });
772
+ const result = await call(makeReplaceTool(dir), { path: file, find, replace: replacement, regex: true });
774
773
  assert.equal(await readFile(file, "utf8"), before.replaceAll(find, replacement));
775
774
  assert.equal(result.details.firstChangedLine, 1);
776
775
  assert.match(result.details.diff, /^-1 a␍/m);
@@ -62,3 +62,20 @@ test("queue is released after a failed command", async () => withTemp(async (dir
62
62
  assert.equal(calls, 2);
63
63
  assert.match(second.content[1].type === "text" ? second.content[1].text : "", /then_run:succeeded/);
64
64
  }));
65
+
66
+ test("result generation failure cannot overwrite an already successful command", async () => withTemp(async (dir) => {
67
+ const target = join(dir, "finalize.txt");
68
+ const progress: any[] = [];
69
+ const fusion = createActionFusionExecutor(async () => "command finished", (event) => progress.push(event));
70
+ await assert.rejects(fusion({
71
+ toolCallId: "finalize", absolutePath: target, thenRun: { command: "check" }, signal: undefined, ctx: context(dir),
72
+ mutate: async () => { await writeFile(target, "saved\n"); return result("saved\n"); },
73
+ finalizeMutation: () => { throw new Error("mutation result failure"); },
74
+ }), /mutation result failure/);
75
+ assert.equal(progress.filter((event) => event.command === "succeeded").length, 1);
76
+ assert.equal(progress.at(-1).publication, "PUBLISHED");
77
+ assert.equal(progress.at(-1).freshness, "unchanged");
78
+ assert.equal(progress.at(-1).command, "succeeded");
79
+ assert.equal(progress.at(-1).output, "command finished");
80
+ assert.equal(progress.at(-1).reason, undefined);
81
+ }));
@@ -49,7 +49,8 @@ test("one independent card updates live and only persists its endpoints", () =>
49
49
  assert.equal(h.entries.length, 2);
50
50
  assert.equal(h.entries[0].data.command, "waiting");
51
51
  const collapsed = card.render(100).join("\n");
52
- assert.match(collapsed, /succeeded[\s\S]*Anchors are stale/);
52
+ assert.match(collapsed, /succeeded/);
53
+ assert.doesNotMatch(collapsed, /publication=|freshness=|Anchors are stale|file\.ts/);
53
54
  assert.equal(h.backgrounds.at(-1), "toolSuccessBg");
54
55
  assert.match(collapsed, /output line 19/);
55
56
  assert.doesNotMatch(collapsed, /output line 0\b/);
@@ -67,3 +68,39 @@ test("session restore uses final snapshots and marks unfinished calls unknown",
67
68
  resumed.restore("session_tree", [h.entries[0]]);
68
69
  assert.match(resumed.card(h.entries[0]).render(100).join("\n"), /interrupted \(final status unknown\)/);
69
70
  });
71
+
72
+ test("skips and cancellations stay neutral and restore their own reason", () => {
73
+ for (const command of ["skipped", "cancelled"] as const) {
74
+ const h = harness();
75
+ h.report(waiting);
76
+ h.report({ ...waiting, command, reason: "Not run because the mutation did not complete." });
77
+ for (const restored of [false, true]) {
78
+ const view = restored ? harness(h.entries) : h;
79
+ if (restored) view.restore();
80
+ const output = view.card(h.entries[0], true).render(160).join("\n");
81
+ assert.match(output, /Not run because the mutation did not complete/);
82
+ assert.doesNotMatch(output, /publication=|freshness=|\(no output\)/);
83
+ assert.ok(!view.backgrounds.includes("toolErrorBg"));
84
+ assert.ok(!view.backgrounds.includes("toolSuccessBg"));
85
+ assert.equal(view.backgrounds.at(-1), "customMessageBg");
86
+ }
87
+ }
88
+ });
89
+
90
+ test("legacy snapshots separate known command failures and suppress mutation diagnostics", () => {
91
+ for (const command of ["skipped", "failed", "cancelled"] as const) {
92
+ const output = command === "skipped"
93
+ ? "mutation failed; the command was not run [then_run:skipped]\nNo file changes were published. Command skipped.\nAnchor mismatch: 1 shifted.\nInput-anchor checks"
94
+ : `mutation completed; then_run did not complete successfully [then_run:${command === "cancelled" ? "skipped" : "failed"}]\nFile changes are saved. Command ${command}.\nactual command diagnostic`;
95
+ const entries = [
96
+ { type: "custom", customType: "hashline-then-run", data: waiting },
97
+ { type: "custom", customType: "hashline-then-run-result", data: { ...waiting, command, publication: "PUBLISHED", output } },
98
+ ];
99
+ const h = harness(entries);
100
+ h.restore();
101
+ const text = h.card(entries[0], true).render(160).join("\n");
102
+ assert.doesNotMatch(text, /Anchor mismatch|Input-anchor|publication=|freshness=|File changes are saved|mutation completed/);
103
+ assert.match(text, command === "skipped" ? /Command was not run/ : /actual command diagnostic/);
104
+ assert.equal(entries[1].data.output, output, "restoring must not rewrite persisted evidence");
105
+ }
106
+ });