@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.
@@ -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
+ });
@@ -12,33 +12,15 @@
12
12
  import { createReadToolDefinition, getLanguageFromPath, highlightCode, truncateHead } from "@earendil-works/pi-coding-agent";
13
13
  import { Text } from "@earendil-works/pi-tui";
14
14
  import { readFile } from "node:fs/promises";
15
- import { join, resolve } from "node:path";
16
- import { homedir } from "node:os";
17
15
  import { decodeUtf8 } from "../core/index.ts";
18
16
  import { hasFinalNewline, splitLines } from "../core/lines.ts";
19
17
  import { createAnchorFormatter } from "./anchor-format.ts";
18
+ import { canonicalPath } from "./path.ts";
20
19
  import { parseHashline, renderToolError } from "./render.ts";
21
20
 
22
21
  const MAX_LINES = 2000;
23
22
  const MAX_BYTES = 256 * 1024;
24
23
 
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
24
  /**
43
25
  * Render the expanded read body for the TUI: color the header, strip the
44
26
  * `LINE#HASH│` prefix from every anchor line to ` N: content`, and
@@ -104,7 +86,7 @@ export function makeReadOverride(cwd: string) {
104
86
  name: "read" as const,
105
87
  label: "read",
106
88
  description:
107
- "Read file contents. Text files display per-line content hashes (LINE#HASH│content) for hashline-verified editing.",
89
+ "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
90
  promptSnippet: "Read files with editable line anchors",
109
91
  promptGuidelines: [
110
92
  "Prefer read over shell output for files you intend to edit.",
@@ -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
+ });
package/src/pi/render.ts CHANGED
@@ -128,7 +128,7 @@ export function renderMutationResult(
128
128
  if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED") return new Text(theme.fg("warning", pending), 0, 0);
129
129
  const content = result.content?.[0];
130
130
  if (context.isError) return renderToolError(result, theme);
131
- const diff: string | undefined = result.details?.diff;
131
+ const diff: string | undefined = result.details?.displayDiff ?? result.details?.diff;
132
132
  // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
133
133
  publishDiffCounts(diff, context, (counts) => {
134
134
  context.state?.callText?.setText(header(context.args, theme, counts));
@@ -157,9 +157,19 @@ export function withMutationStatus(tool: ToolDefinition<any, any, any>): ToolDef
157
157
  renderResult(result, options, theme, context) {
158
158
  const shell = context.state.mutationShell;
159
159
  const isPartial = options.isPartial && result.details?.actionFusion?.mutationCompleted !== true;
160
- shell.result = tool.renderResult!(result, { ...options, isPartial }, theme, { ...context, isPartial, lastComponent: shell.result });
160
+ // Fused errors retain combined details for the model; show the mutation's summary here.
161
+ const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
162
+ shell.result = fusedError ? renderToolError(result, theme)
163
+ : tool.renderResult!(result, { ...options, isPartial }, theme, { ...context, isPartial, lastComponent: shell.result });
161
164
  // Pi runs renderCall first; update its box in place without invalidating the tool row.
162
165
  shell.box.addChild(shell.result);
166
+ const file = result.details?.actionFusion ?? shell.fileState;
167
+ if (file) {
168
+ shell.fileState = { freshness: file.freshness };
169
+ if (file.freshness === "changed" || file.freshness === "missing") {
170
+ shell.box.addChild(new Text(theme.fg("warning", `Anchors are stale: target ${file.freshness}.`), 0, 0));
171
+ }
172
+ }
163
173
  shell.box.setBgFn((line: string) => theme.bg(isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg", line));
164
174
  return new Container();
165
175
  },