@criogaid/pi-hashline-edit 0.2.0 → 0.3.1

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.
@@ -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
+ });
@@ -6,10 +6,16 @@ import type { ActionFusionProgress } from "./action-fusion.ts";
6
6
  const CARD_TYPE = "hashline-then-run";
7
7
  const RESULT_TYPE = "hashline-then-run-result";
8
8
 
9
+ type CommandCardData = Pick<ActionFusionProgress, "toolCallId" | "commandText" | "command" | "output" | "reason"> & { version: 1 };
10
+
11
+ function commandCardData({ toolCallId, commandText, command, output, reason }: ActionFusionProgress): CommandCardData {
12
+ return { version: 1, toolCallId, commandText, command, output, ...(reason ? { reason } : {}) };
13
+ }
14
+
9
15
  /** Render one durable transcript card per fused command without adding model context. */
10
16
  export function registerFusionCards(pi: ExtensionAPI) {
11
17
  const bash = createBashToolDefinition(process.cwd());
12
- const states = new Map<string, ActionFusionProgress>();
18
+ const states = new Map<string, CommandCardData>();
13
19
  const active = new Set<string>();
14
20
 
15
21
  const restore = (ctx: ExtensionContext) => {
@@ -17,16 +23,29 @@ export function registerFusionCards(pi: ExtensionAPI) {
17
23
  active.clear();
18
24
  for (const entry of ctx.sessionManager.getBranch()) {
19
25
  if (entry.type !== "custom" || (entry.customType !== CARD_TYPE && entry.customType !== RESULT_TYPE)) continue;
20
- const data = entry.data as ActionFusionProgress | undefined;
26
+ const data = entry.data as (ActionFusionProgress & { version?: number }) | undefined;
21
27
  if (data && typeof data.toolCallId === "string" && typeof data.commandText === "string" && typeof data.output === "string") {
22
- states.set(data.toolCallId, data);
28
+ const restored = commandCardData(data);
29
+ // Older snapshots stored the compound error in output. Recover only a known command wrapper.
30
+ if (data.version !== 1 && ["skipped", "cancelled", "failed", "timeout"].includes(data.command)) {
31
+ const marker = data.command === "cancelled" ? "[then_run:skipped]" : "[then_run:failed]";
32
+ const fileState = data.publication === "PUBLISHED" ? "File changes are saved."
33
+ : data.publication === "NOT_PUBLISHED" ? "No file changes were published." : "File state is uncertain.";
34
+ const prefix = `mutation completed; then_run did not complete successfully ${marker}\n${fileState} Command ${data.command}.\n`;
35
+ if (data.command !== "skipped" && data.output.startsWith(prefix)) restored.output = data.output.slice(prefix.length);
36
+ else {
37
+ restored.output = "";
38
+ restored.reason = data.command === "skipped" ? "Command was not run." : "Legacy failure details are available in the original tool result.";
39
+ }
40
+ }
41
+ states.set(data.toolCallId, restored);
23
42
  }
24
43
  }
25
44
  };
26
45
  pi.on("session_start", (_event, ctx) => restore(ctx));
27
46
  pi.on("session_tree", (_event, ctx) => restore(ctx));
28
47
 
29
- pi.registerEntryRenderer<ActionFusionProgress>(CARD_TYPE, (entry, { expanded }, theme) => {
48
+ pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, (entry, { expanded }, theme) => {
30
49
  const initial = entry.data;
31
50
  if (!initial) return undefined;
32
51
  const statusText = new Text("", 0, 0);
@@ -40,26 +59,30 @@ export function registerFusionCards(pi: ExtensionAPI) {
40
59
  // Read live state during rendering; native tool updates schedule the repaint.
41
60
  const current = states.get(initial.toolCallId) ?? initial;
42
61
  const pending = current.command === "waiting" || current.command === "running";
43
- const status = pending && !active.has(current.toolCallId) ? "interrupted (final status unknown)" : current.command;
44
- const color = pending ? "warning" : current.command === "succeeded" ? "success" : "error";
45
- const background = pending ? "toolPendingBg" : current.command === "succeeded" ? "toolSuccessBg" : "toolErrorBg";
62
+ const interrupted = pending && !active.has(current.toolCallId);
63
+ const status = interrupted ? "interrupted (final status unknown)" : current.command;
64
+ const failed = current.command === "failed" || current.command === "timeout";
65
+ const color = pending || current.command === "cancelled" ? "warning" : failed ? "error" : current.command === "succeeded" ? "success" : "dim";
66
+ const background = pending && !interrupted ? "toolPendingBg" : failed ? "toolErrorBg" : current.command === "succeeded" ? "toolSuccessBg" : "customMessageBg";
46
67
  box.setBgFn((line) => theme.bg(background, line));
47
- const stale = current.freshness === "changed" || current.freshness === "missing" ? `\nAnchors are stale: target ${current.freshness}.` : "";
48
- statusText.setText(`${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status)}\n${current.path}\npublication=${current.publication} freshness=${current.freshness}${stale}`);
68
+ statusText.setText(`${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status)}`);
49
69
  const context = {
50
70
  args: { command: current.commandText }, toolCallId: current.toolCallId, cwd: process.cwd(),
51
71
  state: rendererState, invalidate: () => box.invalidate(),
52
72
  // Parent tool updates drive entry rendering; leave the native elapsed-time timer off.
53
- executionStarted: false, argsComplete: true, isPartial: pending, expanded, showImages: false,
54
- isError: !pending && current.command !== "succeeded",
73
+ executionStarted: false, argsComplete: true, isPartial: pending && !interrupted, expanded, showImages: false,
74
+ isError: failed,
55
75
  };
56
76
  call = bash.renderCall!(context.args, theme, { ...context, lastComponent: call });
57
- result = bash.renderResult!({ content: [{ type: "text", text: current.output }], details: undefined },
58
- { expanded, isPartial: pending }, theme, { ...context, lastComponent: result });
59
77
  box.clear();
60
78
  box.addChild(statusText);
61
79
  box.addChild(call);
62
- box.addChild(result);
80
+ if (current.reason) box.addChild(new Text(theme.fg("dim", current.reason), 0, 0));
81
+ if (current.output || current.command === "succeeded" || failed) {
82
+ result = bash.renderResult!({ content: [{ type: "text", text: current.output }], details: undefined },
83
+ { expanded, isPartial: context.isPartial }, theme, { ...context, lastComponent: result });
84
+ box.addChild(result);
85
+ }
63
86
  return box.render(width);
64
87
  },
65
88
  };
@@ -67,12 +90,13 @@ export function registerFusionCards(pi: ExtensionAPI) {
67
90
 
68
91
  return (progress: ActionFusionProgress) => {
69
92
  const first = !states.has(progress.toolCallId);
70
- states.set(progress.toolCallId, progress);
93
+ const data = commandCardData(progress);
94
+ states.set(progress.toolCallId, data);
71
95
  const pending = progress.command === "waiting" || progress.command === "running";
72
96
  if (pending) active.add(progress.toolCallId);
73
97
  else active.delete(progress.toolCallId);
74
98
  // Only endpoints are persisted; streaming snapshots reuse Bash's bounded output.
75
- if (first) pi.appendEntry(CARD_TYPE, progress);
76
- if (!pending) pi.appendEntry(RESULT_TYPE, progress);
99
+ if (first) pi.appendEntry(CARD_TYPE, data);
100
+ if (!pending) pi.appendEntry(RESULT_TYPE, data);
77
101
  };
78
102
  }
@@ -34,10 +34,10 @@ import { Type } from "typebox";
34
34
  import { Text } from "@earendil-works/pi-tui";
35
35
  import { readFile, realpath, stat } from "node:fs/promises";
36
36
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
37
- import { splitLines } from "../core/lines.ts";
37
+ import { normalizeLineEndings, splitLines } from "../core/lines.ts";
38
38
  import { decodeEditableText } from "../core/text.ts";
39
39
  import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
40
- import { canonicalPath } from "./read-tool.ts";
40
+ import { canonicalPath } from "./path.ts";
41
41
  import { parseHashline, renderToolError } from "./render.ts";
42
42
  import {
43
43
  COMMON_RG_ARGS,
@@ -53,6 +53,7 @@ import {
53
53
  type LinePredicate,
54
54
  type SearchModes,
55
55
  } from "./rg-line-filter.ts";
56
+ import { runRgTextView } from "./rg-text-view.ts";
56
57
  import { intersectRanges, normalizeRanges, subtractRanges, unionRanges, submatchesToLineRanges, type LineRange, type RgSubmatch } from "./rg-line-ranges.ts";
57
58
 
58
59
  const DEFAULT_LIMIT = 100;
@@ -146,7 +147,7 @@ function clampContext(context: number | undefined): number {
146
147
  const grepOverrideSchema = Type.Object({
147
148
  pattern: Type.Union([Type.String(), Type.Array(Type.String())], {
148
149
  description:
149
- "Non-empty pattern(s). Arrays use matchMode.",
150
+ "Non-empty string or array (OR by default). For code snippets with regex punctuation, set literal:true; use an array for alternatives instead of joining literals with |.",
150
151
  }),
151
152
  matchMode: Type.Optional(
152
153
  Type.Union([Type.Literal("any"), Type.Literal("all")], {
@@ -181,7 +182,7 @@ const grepOverrideSchema = Type.Object({
181
182
  ),
182
183
  literal: Type.Optional(
183
184
  Type.Boolean({
184
- description: "true: literal; false: regex, no fallback. Shared by pattern/excludePattern. Default: literal unless any pattern has regex syntax; invalid regex falls back only for one inclusion pattern without exclusions.",
185
+ description: "Set true for literal code text, especially calls, brackets, pipes, and backslashes. Set false only for intentional valid regex. Applies to pattern and excludePattern. Automatic mode tries regex for metacharacters; only one pattern without exclusions can fall back, searching the entire input literally.",
185
186
  }),
186
187
  ),
187
188
  noIgnore: Type.Optional(Type.Boolean({
@@ -530,7 +531,7 @@ export function makeGrepOverride(cwd: string) {
530
531
  /** @internal — build a grep override with deterministic process backends for tests. */
531
532
  export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<GrepBackend>) {
532
533
  const backend: GrepBackend = {
533
- runRg,
534
+ runRg: runRgTextView,
534
535
  runRgPaths,
535
536
  resolveIgnoreCase,
536
537
  validatePatterns,
@@ -542,10 +543,11 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
542
543
  name: "grep" as const,
543
544
  label: "grep",
544
545
  description:
545
- "Search file contents with ripgrep and return LINE#HASH anchors for physical lines. Supports standard or PCRE2 regexes, multiline matching, ignore overrides, and linked directories.",
546
+ "Search LF-normalized file contents with ripgrep and return LINE#HASH anchors for logical lines. CRLF queries normalize to LF; standalone CR stays content. Supports standard or PCRE2 regexes, multiline matching, ignore overrides, and linked directories.",
546
547
  promptSnippet: "Search file contents with ripgrep",
547
548
  promptGuidelines: [
548
549
  "Prefer the grep tool for file-content searches.",
550
+ "Set literal:true when searching code text containing regex punctuation (for example pi.on(, compact(, or \\0); use a pattern array for literal alternatives. Use literal:false only for intentional valid regex.",
549
551
  "Use returned grep anchors directly for edits; no re-read needed.",
550
552
  "Use files/count when only paths or counts are needed; use matchMode all and excludePattern instead of shell pipelines.",
551
553
  ],
@@ -607,14 +609,14 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
607
609
  const anchors = createAnchorFormatter();
608
610
  const warnings: string[] = [];
609
611
 
610
- const patterns = toArray(params.pattern);
612
+ const patterns = toArray(params.pattern).map(normalizeLineEndings);
611
613
  if (patterns.length === 0) throw new Error("pattern is required (got an empty array)");
612
614
  if (patterns.some((pattern) => pattern.trim() === "")) {
613
615
  throw new Error("pattern must not be empty");
614
616
  }
615
617
 
616
618
  const rgPath = bundledRgPath;
617
- const excludes = toArray(params.excludePattern);
619
+ const excludes = toArray(params.excludePattern).map(normalizeLineEndings);
618
620
  const matchMode: "any" | "all" = params.matchMode ?? "any";
619
621
  const outputMode: "content" | "files" | "count" = params.outputMode ?? "content";
620
622
  const globs = toArray(params.glob);
@@ -105,6 +105,13 @@ const text = (result: any): string => result.content[0].text;
105
105
  const call = (tool: any, params: any, signal?: AbortSignal) =>
106
106
  tool.execute("0", params, signal, undefined);
107
107
 
108
+ test("grep guidance distinguishes literal code searches from regex and array alternatives", () => {
109
+ const tool = makeGrepOverrideWithBackend(process.cwd(), {});
110
+ assert.match(tool.promptGuidelines.join("\n"), /literal:true.*pi\.on\(.*pattern array.*literal alternatives/);
111
+ assert.match(JSON.stringify(tool.parameters.properties.pattern), /use an array for alternatives/);
112
+ assert.match(JSON.stringify(tool.parameters.properties.literal), /entire input literally/);
113
+ });
114
+
108
115
  async function withEnabled<T>(enabled: boolean, fn: () => Promise<T>): Promise<T> {
109
116
  const state = getState();
110
117
  const previous = state.config.enabled;
@@ -148,7 +155,7 @@ test("formats parsed rg matches with full-line hash anchors", async () => {
148
155
  assert.match(output, /3#[0-9A-Z]+│alpha only/);
149
156
  assert.deepEqual(fake.calls[0], {
150
157
  path: rgPath,
151
- args: ["--no-config", "--color=never", "--crlf", "--engine=default", "--no-multiline", "--ignore-case", "--fixed-strings", "--json", "--line-number", "--hidden", "-e", "alpha", "--", dir],
158
+ args: ["--no-config", "--color=never", "--no-crlf", "--engine=default", "--no-multiline", "--ignore-case", "--fixed-strings", "--json", "--line-number", "--hidden", "-e", "alpha", "--", dir],
152
159
  });
153
160
  }),
154
161
  );
@@ -252,7 +259,7 @@ test("passes output flags and formats files and counts", async () => {
252
259
  assert.deepEqual(fake.calls[0].args, [
253
260
  "--no-config",
254
261
  "--color=never",
255
- "--crlf",
262
+ "--no-crlf",
256
263
  "--engine=default",
257
264
  "--no-multiline",
258
265
  "--ignore-case",
@@ -357,7 +364,7 @@ test("auto-detects modes with rg validation while preserving explicit overrides"
357
364
  );
358
365
  assert.equal(valid.calls.filter(({ args }) => args.includes("--quiet")).length, 2);
359
366
  assert.deepEqual(invalid.calls[0].args, [
360
- "--no-config", "--color=never", "--crlf", "--engine=default", "--no-multiline",
367
+ "--no-config", "--color=never", "--no-crlf", "--engine=default", "--no-multiline",
361
368
  "--quiet", "-e", "queueTool(", "--", "-",
362
369
  ]);
363
370
 
@@ -2,12 +2,14 @@ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
2
  import { FileMutationError, type MutationVersions, type PublicationStatus } from "./file-commit.ts";
3
3
  import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
4
4
  import { displayCarriageReturns, type AnchorFormatter } from "./anchor-format.ts";
5
+ import { normalizeLineEndings } from "../core/lines.ts";
5
6
 
6
- /** Diff raw text so line numbers and patches retain LF boundaries and all source bytes. */
7
+ /** Keep byte-faithful diff/patch data and a separate preview of the shared logical text. */
7
8
  export function generateMutationDetails(path: string, before: string, after: string, versions: MutationVersions, publication: PublicationStatus) {
8
9
  const { diff, firstChangedLine } = generateDiffString(before, after);
9
10
  return {
10
11
  diff: displayCarriageReturns(diff),
12
+ displayDiff: displayCarriageReturns(generateDiffString(normalizeLineEndings(before), normalizeLineEndings(after)).diff),
11
13
  firstChangedLine,
12
14
  patch: generateUnifiedPatch(path, before, after),
13
15
  publication,
package/src/pi/path.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { homedir } from "node:os";
2
+ import { isAbsolute, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
6
+ const WINDOWS_SHELL_DRIVE = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i;
7
+
8
+ /** Resolve model-supplied paths with the same input conventions as Pi's built-in file tools. */
9
+ export function canonicalPath(cwd: string, path: string): string {
10
+ let normalized = path.replace(UNICODE_SPACES, " ");
11
+ if (normalized.startsWith("@")) normalized = normalized.slice(1);
12
+ if (process.platform === "win32" && normalized.startsWith("/") && !normalized.startsWith("//") && !normalized.includes("\\")) {
13
+ const match = WINDOWS_SHELL_DRIVE.exec(normalized);
14
+ if (match) normalized = `${match[1]!.toUpperCase()}:\\${match[2]?.replaceAll("/", "\\") ?? ""}`;
15
+ }
16
+ if (normalized === "~") normalized = homedir();
17
+ else if (normalized.startsWith("~/") || (process.platform === "win32" && normalized.startsWith("~\\"))) {
18
+ normalized = join(homedir(), normalized.slice(2));
19
+ }
20
+ if (normalized.startsWith("file://")) normalized = fileURLToPath(normalized);
21
+ return isAbsolute(normalized) ? resolve(normalized) : resolve(cwd, normalized);
22
+ }
package/src/pi/pi.test.ts CHANGED
@@ -1,8 +1,17 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { canonicalPath } from "./read-tool.ts";
4
- import { homedir } from "node:os";
3
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
4
+ import { tmpdir, homedir } from "node:os";
5
+ import { computeLineHash } from "../core/hash.ts";
6
+ import { createActionFusionExecutor } from "./action-fusion.ts";
7
+ import { makeEditOverride } from "./edit-tool.ts";
8
+ import { makeGrepOverride } from "./grep-tool.ts";
9
+ import { makeReadOverride } from "./read-tool.ts";
10
+ import { makeReplaceTool } from "./replace-tool.ts";
11
+ import { makeWriteOverride } from "./write-tool.ts";
12
+ import { canonicalPath } from "./path.ts";
5
13
  import { join, resolve } from "node:path";
14
+ import { pathToFileURL } from "node:url";
6
15
 
7
16
  test("canonicalPath resolves relative and absolute", () => {
8
17
  const cwd = resolve("/cwd");
@@ -17,3 +26,56 @@ test("canonicalPath expands ~ to home directory", () => {
17
26
  assert.equal(canonicalPath("/cwd", "~"), home);
18
27
  assert.equal(canonicalPath("/cwd", "~/foo.ts"), join(home, "foo.ts"));
19
28
  });
29
+
30
+ test("canonicalPath matches Pi's file URL, @ prefix, and Unicode space handling", () => {
31
+ const cwd = resolve("/cwd");
32
+ const target = join(cwd, "space name.txt");
33
+ const fileUrl = pathToFileURL(target).href;
34
+ for (const input of ["space name.txt", "space\u00a0name.txt", "space\u2009name.txt", "@space name.txt", fileUrl, `@${fileUrl}`]) {
35
+ assert.equal(canonicalPath(cwd, input), target, input);
36
+ }
37
+ assert.throws(() => canonicalPath(cwd, "file:///bad%ZZ"));
38
+ });
39
+
40
+ test("canonicalPath follows Pi's Windows shell-path conventions", () => {
41
+ const cwd = resolve("/cwd");
42
+ if (process.platform === "win32") {
43
+ const target = "C:\\src\\file.txt";
44
+ for (const input of ["/c/src/file.txt", "/mnt/c/src/file.txt", "/cygdrive/c/src/file.txt", "@/c/src/file.txt"]) {
45
+ assert.equal(canonicalPath(cwd, input), target, input);
46
+ }
47
+ assert.equal(canonicalPath(cwd, "~\\file.txt"), join(homedir(), "file.txt"));
48
+ assert.equal(canonicalPath(cwd, "@~\\file.txt"), join(homedir(), "file.txt"));
49
+ } else {
50
+ assert.equal(canonicalPath(cwd, "/c/src/file.txt"), "/c/src/file.txt");
51
+ }
52
+ });
53
+
54
+ test("file tools share Pi-style URL and @ path resolution", async () => {
55
+ const dir = await mkdtemp(join(tmpdir(), "hashline-path-"));
56
+ try {
57
+ const file = join(dir, "target.txt");
58
+ const url = pathToFileURL(file).href;
59
+ const ctx = { cwd: dir };
60
+ await makeWriteOverride(dir).execute("write", { path: `@${url}`, content: "before\n" }, undefined, undefined, ctx);
61
+ const read = await makeReadOverride(dir).execute("read", { path: url }, undefined, undefined, ctx);
62
+ if (read.content[0]?.type !== "text") throw new Error("Expected a text read result");
63
+ assert.match(read.content[0].text, /before/);
64
+ await makeReplaceTool(dir).execute("replace", { path: url, find: "before", replace: "after" }, undefined, undefined, ctx);
65
+ await makeEditOverride(dir).execute("edit", { path: `@${url}`, edits: [
66
+ { op: "replace", anchor: `1#${computeLineHash(1, "after")}`, body: ["edited"] },
67
+ ] }, undefined, undefined, ctx);
68
+ const matches = await makeGrepOverride(dir).execute("grep", { path: `@${url}`, pattern: "edited" }, undefined, undefined);
69
+ assert.match(matches.content[0].text, /edited/);
70
+ assert.equal(await readFile(file, "utf8"), "edited\n");
71
+ let commands = 0;
72
+ const fusion = createActionFusionExecutor(async () => { commands++; return "checked"; });
73
+ const fused = await makeWriteOverride(dir, fusion).execute("fused", {
74
+ path: `@${url}`, content: "edited\n", then_run: { command: "check" },
75
+ }, undefined, undefined, ctx);
76
+ assert.equal(fused.details.actionFusion.command, "succeeded");
77
+ assert.equal(commands, 1);
78
+ } finally {
79
+ await rm(dir, { recursive: true, force: true });
80
+ }
81
+ });
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Override read: text files output "lineNo#hash│content"; non-text (images /
3
- * binary) and read errors delegate to the built-in read.
2
+ * Override read: recognized images and NUL-containing files delegate to Pi's
3
+ * built-in read; valid UTF-8 text outputs "lineNo#hash│content".
4
4
  *
5
5
  * Hashes are computed from the current content on the fly — nothing is stored.
6
6
  * The hash is `(line number, content)`, recomputed and checked at edit time, so
@@ -9,36 +9,21 @@
9
9
  * @module pi-hashline-edit/pi
10
10
  */
11
11
 
12
- import { createReadToolDefinition, getLanguageFromPath, highlightCode, truncateHead } from "@earendil-works/pi-coding-agent";
12
+ import {
13
+ createReadToolDefinition, detectSupportedImageMimeTypeFromFile,
14
+ getLanguageFromPath, highlightCode, truncateHead,
15
+ } from "@earendil-works/pi-coding-agent";
13
16
  import { Text } from "@earendil-works/pi-tui";
14
17
  import { readFile } from "node:fs/promises";
15
- import { join, resolve } from "node:path";
16
- import { homedir } from "node:os";
17
18
  import { decodeUtf8 } from "../core/index.ts";
18
19
  import { hasFinalNewline, splitLines } from "../core/lines.ts";
19
20
  import { createAnchorFormatter } from "./anchor-format.ts";
21
+ import { canonicalPath } from "./path.ts";
20
22
  import { parseHashline, renderToolError } from "./render.ts";
21
23
 
22
24
  const MAX_LINES = 2000;
23
25
  const MAX_BYTES = 256 * 1024;
24
26
 
25
- /**
26
- * Canonical absolute path: shared by read/edit/grep to resolve a file consistently.
27
- * Expands a leading `~` / `~/` to the user's home directory. (`~user` is not supported.)
28
- */
29
- export function canonicalPath(cwd: string, p: string): string {
30
- return resolve(cwd, expandTilde(p));
31
- }
32
-
33
- /** Mirrors pi core's `normalizePath` tilde handling: expands `~` / `~/` (and `~\` on Windows), leaves `~user` untouched. */
34
- function expandTilde(p: string): string {
35
- if (p === "~") return homedir();
36
- if (p.startsWith("~/") || (process.platform === "win32" && p.startsWith("~\\"))) {
37
- return join(homedir(), p.slice(2));
38
- }
39
- return p;
40
- }
41
-
42
27
  /**
43
28
  * Render the expanded read body for the TUI: color the header, strip the
44
29
  * `LINE#HASH│` prefix from every anchor line to ` N: content`, and
@@ -104,7 +89,7 @@ export function makeReadOverride(cwd: string) {
104
89
  name: "read" as const,
105
90
  label: "read",
106
91
  description:
107
- "Read file contents. Text files display per-line content hashes (LINE#HASH│content) for hashline-verified editing.",
92
+ "Read file contents. Text files display per-line content hashes (LINE#HASH│content) in the shared LF view for hashline-verified editing. CRLF line boundaries display as LF; source-code escape sequences remain literal text.",
108
93
  promptSnippet: "Read files with editable line anchors",
109
94
  promptGuidelines: [
110
95
  "Prefer read over shell output for files you intend to edit.",
@@ -133,13 +118,16 @@ export function makeReadOverride(cwd: string) {
133
118
  const absPath = canonicalPath(cwd, params.path as string);
134
119
  let buf: Buffer;
135
120
  try {
121
+ if (await detectSupportedImageMimeTypeFromFile(absPath)) {
122
+ return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
123
+ }
136
124
  buf = await readFile(absPath);
137
125
  } catch {
138
126
  // read error → delegate to the built-in (it has polished error messages)
139
127
  return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
140
128
  }
141
129
 
142
- // binary/image detection (null byte) → delegate to the built-in (it uses file-type for images)
130
+ // NUL is a text-safety signal, not an exhaustive binary classifier.
143
131
  if (buf.includes(0)) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
144
132
 
145
133
  const text = decodeUtf8(buf);
@@ -1,4 +1,4 @@
1
- import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
1
+ import { mkdir, mkdtemp, rm, writeFile, readFile } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import assert from "node:assert/strict";
@@ -8,6 +8,7 @@ import { getState } from "./state.ts";
8
8
  import { initTheme } from "@earendil-works/pi-coding-agent";
9
9
  import { ToolExecutionComponent } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tool-execution.js";
10
10
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
11
+ import { computeLineHash } from "../core/hash.ts";
11
12
 
12
13
  test("mutation cards use Fusion by default and explicit false removes command support", async () => {
13
14
  const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
@@ -65,6 +66,9 @@ test("mutation cards use Fusion by default and explicit false removes command su
65
66
  card.updateResult({ ...result, isError: false });
66
67
  assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
67
68
  card.setExpanded(true);
69
+ assert.doesNotMatch(card.render(100).join("\n"), /publication=|freshness=/);
70
+ assert.doesNotMatch(card.render(100).join("\n"), /Command exited|then_run:failed/);
71
+ assert.doesNotMatch(frames.at(-1)!.commandOutput, /publication=|freshness=|File changes are saved|No file changes were published|mutation completed/);
68
72
  assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
69
73
 
70
74
  const invalid = { ...params, path: "missing.txt", ...(name === "write" ? { mode: "overwrite" } : {}) };
@@ -76,10 +80,33 @@ test("mutation cards use Fusion by default and explicit false removes command su
76
80
  const output = failedCard.render(100).join("\n");
77
81
  assert.ok(output.includes(theme.getBgAnsi("toolErrorBg")), `${name} mutation failure should turn red`);
78
82
  assert.ok(!output.includes(theme.getBgAnsi("toolPendingBg")));
83
+ assert.doesNotMatch(output, /the command was not run|then_run:skipped/);
84
+ assert.match(output, name === "write" ? /does not exist/ : /Error reading/);
85
+ const entry = entries.find((entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === `${name}-bad`);
86
+ const commandOutput = renderers.get(entry.customType)(entry, { expanded: true }, theme).render(160).join("\n");
87
+ assert.match(commandOutput, /skipped[\s\S]*Not run because the mutation did not complete/);
88
+ assert.doesNotMatch(commandOutput, /Error reading|does not exist|publication=|freshness=/);
89
+ assert.ok(!commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
79
90
  return true;
80
91
  });
81
92
  }
82
93
  assert.deepEqual(entries.map((entry) => entry.data.command), cases.flatMap(() => ["waiting", "failed", "waiting", "skipped"]));
94
+ assert.ok(entries.every((entry) => !("publication" in entry.data) && !("freshness" in entry.data) && !("path" in entry.data)));
95
+ await writeFile(join(dir, "stale.txt"), "header\ntarget\n");
96
+ const edit = tools.find((tool) => tool.name === "edit");
97
+ const stale = { path: "stale.txt", edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "target")}`, body: ["changed"] }], then_run: { command: "exit 99" } };
98
+ const staleCard = new ToolExecutionComponent("edit", "stale", stale, {}, edit, { requestRender() {} } as any, dir);
99
+ await assert.rejects(edit.execute("stale", stale, undefined, (update: any) => staleCard.updateResult({ ...update, isError: false }, true), { cwd: dir }), (error: Error) => {
100
+ assert.match(error.message, /checksum-matching candidate[\s\S]*Input-anchor checks/);
101
+ staleCard.updateResult({ content: [{ type: "text", text: error.message }], isError: true });
102
+ assert.match(staleCard.render(160).join("\n"), /Anchor mismatch/);
103
+ const entry = entries.find((entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === "stale");
104
+ const commandOutput = renderers.get(entry.customType)(entry, { expanded: true }, theme).render(160).join("\n");
105
+ assert.match(commandOutput, /skipped/);
106
+ assert.doesNotMatch(commandOutput, /Anchor mismatch|candidate|Input-anchor|publication=|freshness=/);
107
+ return true;
108
+ });
109
+ assert.equal(await readFile(join(dir, "stale.txt"), "utf8"), "header\ntarget\n");
83
110
  await writeFile(join(dir, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { actionFusion: false } }));
84
111
  const disabledTools: any[] = [];
85
112
  registerHashline({
@@ -1,9 +1,13 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { initTheme } from "@earendil-works/pi-coding-agent";
3
+ import { generateDiffString, initTheme } from "@earendil-works/pi-coding-agent";
4
4
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
5
+ import { displayCarriageReturns } from "./anchor-format.ts";
5
6
  import { makeEditOverride } from "./edit-tool.ts";
6
7
  import { makeReplaceTool } from "./replace-tool.ts";
8
+ import { renderDiffPreview, withMutationStatus } from "./render.ts";
9
+ import { makeWriteOverride } from "./write-tool.ts";
10
+ import { generateMutationDetails } from "./mutation-result.ts";
7
11
 
8
12
  test("mutation headers refresh in place and retain isolated per-call counts", () => {
9
13
  initTheme("dark");
@@ -22,3 +26,86 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
22
26
  assert.match(header.render(100).join("\n"), /\+1/);
23
27
  }
24
28
  });
29
+
30
+ test("mutation card owns stale-anchor notices without internal status", () => {
31
+ initTheme("dark");
32
+ const tool = withMutationStatus(makeEditOverride(process.cwd()));
33
+ const args = { path: "a.txt", edits: [{ op: "append", body: ["new"] }] };
34
+ const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
35
+ const card = tool.renderCall!(args, theme, context);
36
+ tool.renderResult!({
37
+ content: [{ type: "text", text: "Edit saved." }, { type: "text", text: "command diagnostic" }],
38
+ details: { actionFusion: { publication: "PUBLISHED", freshness: "changed", command: "failed" } },
39
+ }, { isPartial: false, expanded: false }, theme, context);
40
+ const output = card.render(160).join("\n");
41
+ assert.match(output, /Edit saved/);
42
+ assert.doesNotMatch(output, /publication=|freshness=/);
43
+ assert.match(output, /Anchors are stale: target changed/);
44
+ assert.doesNotMatch(output, /command diagnostic/);
45
+ assert.ok(output.includes(theme.getBgAnsi("toolSuccessBg")));
46
+ });
47
+
48
+ test("mutation card omits status when then_run was not requested", () => {
49
+ initTheme("dark");
50
+ const tool = withMutationStatus(makeEditOverride(process.cwd()));
51
+ const args = { path: "a.txt", edits: [{ op: "append", body: ["new"] }] };
52
+ const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
53
+ const card = tool.renderCall!(args, theme, context);
54
+ tool.renderResult!({
55
+ content: [{ type: "text", text: "Edited a.txt." }],
56
+ details: { actionFusion: { publication: "PUBLISHED", freshness: "unchanged", command: "not_requested" } },
57
+ }, { isPartial: false, expanded: false }, theme, context);
58
+ const output = card.render(160).join("\n");
59
+ assert.match(output, /Edited a\.txt/);
60
+ assert.doesNotMatch(output, /publication=|freshness=/);
61
+ tool.renderCall!(args, theme, context);
62
+ tool.renderResult!({
63
+ content: [{ type: "text", text: "Edited a.txt." }],
64
+ details: { actionFusion: { publication: "PUBLISHED", freshness: "changed", command: "not_requested" } },
65
+ }, { isPartial: false, expanded: false }, theme, context);
66
+ const staleOutput = card.render(160).join("\n");
67
+ assert.match(staleOutput, /Anchors are stale: target changed/);
68
+ assert.doesNotMatch(staleOutput, /publication=|freshness=/);
69
+ });
70
+
71
+ test("unfused write errors retain the native full diagnostic", () => {
72
+ initTheme("dark");
73
+ const tool = withMutationStatus(makeWriteOverride(process.cwd()));
74
+ const args = { path: "a.txt", content: "new" };
75
+ const context: any = { args, state: {}, isPartial: false, isError: true, invalidate() {} };
76
+ const card = tool.renderCall!(args, theme, context);
77
+ tool.renderResult!({ content: [{ type: "text", text: "write failed\nimportant detail" }], details: {} },
78
+ { isPartial: false, expanded: false }, theme, context);
79
+ assert.match(card.render(160).join("\n"), /write failed[\s\S]*important detail/);
80
+ });
81
+
82
+ test("mutation previews hide CRLF boundaries even with mixed endings or an unterminated last line", () => {
83
+ initTheme("dark");
84
+ for (const before of ["old\r\ncontext\r\n", "old\r\ncontext\nlast", "old\r\ncontext\r\nlast"]) {
85
+ const after = before.replace("old", "new");
86
+ const details = generateMutationDetails("a.txt", before, after, { publishedRevision: "r", observedRevision: "r" }, "PUBLISHED");
87
+ assert.equal(details.diff, displayCarriageReturns(generateDiffString(before, after).diff));
88
+ assert.match(details.diff, /␍/);
89
+ assert.ok(details.patch.includes("-old\r\n"));
90
+ for (const tool of [makeEditOverride(process.cwd()), makeReplaceTool(process.cwd())]) {
91
+ for (const expanded of [false, true]) {
92
+ const context: any = { args: { path: "a.txt" }, state: {}, isError: false };
93
+ const rendered = tool.renderResult({ content: [{ type: "text", text: "Done" }], details }, { isPartial: false, expanded }, theme, context);
94
+ const output = rendered.render(160).join("\n");
95
+ assert.doesNotMatch(output, /␍/);
96
+ assert.match(output, /old[\s\S]*new[\s\S]*context/);
97
+ }
98
+ }
99
+ }
100
+ });
101
+
102
+ test("diff previews retain standalone CR and literal control-picture characters", () => {
103
+ initTheme("dark");
104
+ for (const before of ["old\r", "old␍", "old\rcontent\r\n"]) {
105
+ const details = generateMutationDetails("a.txt", before, before.replace("old", "new"), { publishedRevision: "r", observedRevision: "r" }, "PUBLISHED");
106
+ const tool = makeEditOverride(process.cwd());
107
+ const result = tool.renderResult({ content: [], details }, { expanded: true }, theme, { args: { path: "a.txt" }, state: {}, isError: false });
108
+ assert.match(result.render(160).join("\n"), /␍/);
109
+ }
110
+ assert.match(renderDiffPreview("-1 old␍\n+1 new␍", true, theme), /␍/);
111
+ });