@criogaid/pi-hashline-edit 0.1.3 → 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.
Files changed (44) hide show
  1. package/README.md +77 -23
  2. package/package.json +1 -1
  3. package/src/core/apply.test.ts +87 -10
  4. package/src/core/apply.ts +106 -84
  5. package/src/core/lines.test.ts +12 -1
  6. package/src/core/lines.ts +43 -1
  7. package/src/core/ranges.test.ts +28 -0
  8. package/src/core/ranges.ts +25 -0
  9. package/src/core/text.ts +5 -0
  10. package/src/core/types.ts +37 -20
  11. package/src/integration/grep-rg.test.ts +188 -1
  12. package/src/pi/action-fusion.test.ts +3 -1
  13. package/src/pi/action-fusion.ts +38 -35
  14. package/src/pi/anchor-format.test.ts +30 -0
  15. package/src/pi/anchor-format.ts +28 -0
  16. package/src/pi/config.ts +1 -1
  17. package/src/pi/edit-tool.ts +91 -100
  18. package/src/pi/execute.test.ts +239 -14
  19. package/src/pi/failure-context.test.ts +99 -62
  20. package/src/pi/failure-context.ts +67 -64
  21. package/src/pi/failure-path.test.ts +20 -2
  22. package/src/pi/file-commit.test.ts +21 -0
  23. package/src/pi/file-commit.ts +35 -3
  24. package/src/pi/fusion-card.test.ts +38 -1
  25. package/src/pi/fusion-card.ts +41 -17
  26. package/src/pi/grep-tool.ts +84 -55
  27. package/src/pi/grep.test.ts +77 -6
  28. package/src/pi/mutation-result.ts +48 -9
  29. package/src/pi/path.ts +22 -0
  30. package/src/pi/pi.test.ts +64 -2
  31. package/src/pi/read-tool.ts +9 -30
  32. package/src/pi/registration.test.ts +28 -1
  33. package/src/pi/render.test.ts +111 -0
  34. package/src/pi/render.ts +30 -6
  35. package/src/pi/replace-tool.ts +144 -140
  36. package/src/pi/replace.test.ts +193 -1
  37. package/src/pi/result-safety.test.ts +241 -8
  38. package/src/pi/rg-line-filter.test.ts +7 -1
  39. package/src/pi/rg-line-filter.ts +10 -12
  40. package/src/pi/rg-line-ranges.test.ts +10 -0
  41. package/src/pi/rg-line-ranges.ts +21 -15
  42. package/src/pi/rg-text-view.ts +88 -0
  43. package/src/pi/write-tool.ts +13 -47
  44. package/src/pi/write.test.ts +25 -36
@@ -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",
@@ -338,8 +345,14 @@ test("auto-detects modes with rg validation while preserving explicit overrides"
338
345
  const fallback = makeGrepOverrideWithBackend(dir, invalid.backend);
339
346
 
340
347
  const result = await call(fallback, { pattern: "queueTool(" });
341
- assert.match(text(result), /Invalid regex; searched all patterns as literal text/);
342
- await call(fallback, { pattern: ["plain", "broken("] });
348
+ assert.match(text(result), /Invalid regex; searched the pattern as literal text/);
349
+ for (const params of [
350
+ { pattern: ["plain", "broken("] },
351
+ { pattern: "broken(", excludePattern: "^\\s*//" },
352
+ { pattern: "plain", excludePattern: "broken(" },
353
+ ]) {
354
+ await assert.rejects(call(fallback, params), /Invalid regex in compound query; automatic literal fallback is disabled/);
355
+ }
343
356
  await call(tool, { pattern: "value.*" });
344
357
  await call(tool, { pattern: "plain", literal: false });
345
358
  await call(tool, { pattern: "value.*", literal: true });
@@ -347,11 +360,11 @@ test("auto-detects modes with rg validation while preserving explicit overrides"
347
360
  assert.deepEqual(
348
361
  [...invalid.calls, ...valid.calls].filter(({ args }) => !args.includes("--quiet"))
349
362
  .map(({ args }) => args.includes("--fixed-strings")),
350
- [true, true, false, false, true],
363
+ [true, false, false, true],
351
364
  );
352
365
  assert.equal(valid.calls.filter(({ args }) => args.includes("--quiet")).length, 2);
353
366
  assert.deepEqual(invalid.calls[0].args, [
354
- "--no-config", "--color=never", "--crlf", "--engine=default", "--no-multiline",
367
+ "--no-config", "--color=never", "--no-crlf", "--engine=default", "--no-multiline",
355
368
  "--quiet", "-e", "queueTool(", "--", "-",
356
369
  ]);
357
370
 
@@ -558,3 +571,61 @@ test("grep rejects malformed UTF-8 and NUL bytes instead of hashing binary text"
558
571
  }),
559
572
  );
560
573
  });
574
+
575
+ test("partial searches retain matches and surface stderr across output modes", async () => {
576
+ await withDir(async dir => {
577
+ const file = join(dir, "found.txt");
578
+ await writeFile(file, "needle\n");
579
+ for (const outputMode of ["content", "files", "count"]) {
580
+ for (const limit of [1, 10]) {
581
+ const fake = fakeBackend({ lines: [rgMatch(file, 1, "needle\n")], code: 2, stderr: "unreadable.txt: Permission denied" });
582
+ const result = await call(makeGrepOverrideWithBackend(dir, fake.backend), { pattern: "needle", outputMode, limit });
583
+ assert.match(text(result), /found\.txt/);
584
+ assert.match(text(result), /Search incomplete; results and counts cover only confirmed matches/);
585
+ assert.match(text(result), /unreadable\.txt: Permission denied/);
586
+ assert.equal(result.details.incomplete, true);
587
+ }
588
+ }
589
+ const fake = fakeBackend({ code: 2, stderr: "Permission denied" });
590
+ await assert.rejects(call(makeGrepOverrideWithBackend(dir, fake.backend), { pattern: "needle" }), /No matches confirmed.*Search incomplete/s);
591
+ });
592
+ });
593
+
594
+ test("failed result reads report incomplete coverage while retaining readable files", async () => {
595
+ await withDir(async dir => {
596
+ const good = join(dir, "good.txt");
597
+ const gone = join(dir, "gone.txt");
598
+ await writeFile(good, "needle\n");
599
+ await writeFile(gone, "needle\n");
600
+ const fake = fakeBackend({ lines: [rgMatch(gone, 1, "needle\n"), rgMatch(good, 1, "needle\n")] });
601
+ const result = await call(makeGrepOverrideWithBackend(dir, { ...fake.backend, runRg: async (...args) => {
602
+ const result = await fake.backend.runRg(...args);
603
+ await rm(gone);
604
+ return result;
605
+ } }), { pattern: "needle" });
606
+ assert.match(text(result), /good\.txt · 1 match/);
607
+ assert.doesNotMatch(text(result), /gone\.txt · 1 match/);
608
+ assert.match(text(result), /Search incomplete/);
609
+ assert.match(text(result), /Could not read.*gone\.txt/);
610
+ });
611
+ });
612
+
613
+ test("complex searches report listing errors but reject incomplete exclusion scans", async () => {
614
+ await withDir(async dir => {
615
+ const file = join(dir, "fixture.txt");
616
+ await writeFile(file, "needle\n");
617
+ const event = JSON.stringify({ type: "match", data: { path: { text: file }, line_number: 1, lines: { text: "needle\n" }, submatches: [{ start: 0, end: 6 }] } });
618
+ const fake = fakeBackend({ paths: [file], lines: [event] });
619
+ const listing = await call(makeGrepOverrideWithBackend(dir, { ...fake.backend, runRgPaths: async (...args) => {
620
+ const result = await fake.backend.runRgPaths(...args);
621
+ return { ...result, code: 2, stderr: "directory: Permission denied" };
622
+ } }), { pattern: "needle", multiline: true });
623
+ assert.match(text(listing), /1#[0-9A-Z]+│needle/);
624
+ assert.match(text(listing), /Search incomplete/);
625
+ const tool = makeGrepOverrideWithBackend(dir, { ...fake.backend, runRg: async (...args) => {
626
+ const result = await fake.backend.runRg(...args);
627
+ return args[1].includes("exclude") ? { ...result, code: 2, stderr: "exclusion scan failed" } : result;
628
+ } });
629
+ await assert.rejects(call(tool, { pattern: "needle", excludePattern: "exclude", multiline: true }), /exclusion scan failed/);
630
+ });
631
+ });
@@ -1,6 +1,38 @@
1
1
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
2
  import { FileMutationError, type MutationVersions, type PublicationStatus } from "./file-commit.ts";
3
- import { computeLineHash } from "../core/hash.ts";
3
+ import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
4
+ import { displayCarriageReturns, type AnchorFormatter } from "./anchor-format.ts";
5
+ import { normalizeLineEndings } from "../core/lines.ts";
6
+
7
+ /** Keep byte-faithful diff/patch data and a separate preview of the shared logical text. */
8
+ export function generateMutationDetails(path: string, before: string, after: string, versions: MutationVersions, publication: PublicationStatus) {
9
+ const { diff, firstChangedLine } = generateDiffString(before, after);
10
+ return {
11
+ diff: displayCarriageReturns(diff),
12
+ displayDiff: displayCarriageReturns(generateDiffString(normalizeLineEndings(before), normalizeLineEndings(after)).diff),
13
+ firstChangedLine,
14
+ patch: generateUnifiedPatch(path, before, after),
15
+ publication,
16
+ ...versions,
17
+ revision: versions.publishedRevision,
18
+ };
19
+ }
20
+
21
+ /** Keep result-building failures distinct from file publication failures. */
22
+ export function postProcessMutation<T>(tool: string, publication: PublicationStatus, build: () => T): T {
23
+ try { return build(); } catch (error) {
24
+ throw new FileMutationError("post_process", publication, `${tool} result generation failed; publication=${publication}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
25
+ }
26
+ }
27
+
28
+ /** Append only to the summary block after the caller confirms anchor freshness. */
29
+ export function appendMutationAnchors<T>(result: AgentToolResult<T>, anchors: string, publish: boolean): AgentToolResult<T> {
30
+ return {
31
+ ...result,
32
+ content: result.content.map((block, index) => index === 0 && block.type === "text"
33
+ ? { ...block, text: `${block.text}${publish ? anchors : ""}` } : block),
34
+ };
35
+ }
4
36
 
5
37
  export function observedFreshness(result: AgentToolResult<unknown>): "unchanged" | "changed" | "unknown" {
6
38
  const versions = result.details as Partial<MutationVersions> | undefined;
@@ -13,12 +45,13 @@ export function finalizeMutationResult<T>(
13
45
  result: AgentToolResult<T>,
14
46
  finalize: (result: AgentToolResult<T>, publishAnchors: boolean) => AgentToolResult<T>,
15
47
  publishAnchors = observedFreshness(result) === "unchanged",
48
+ staleNotice = "Anchors omitted: target revision was not confirmed unchanged. Re-read before further edits.",
16
49
  ): AgentToolResult<T> {
17
50
  try {
18
51
  const finalized = finalize(result, publishAnchors);
19
52
  return publishAnchors ? finalized : {
20
53
  ...finalized,
21
- content: [...finalized.content, { type: "text", text: "Anchors omitted: target revision was not confirmed unchanged. Re-read before further edits." }],
54
+ content: [...finalized.content, { type: "text", text: staleNotice }],
22
55
  };
23
56
  } catch (error) {
24
57
  const publication = (result.details as { publication?: PublicationStatus } | undefined)?.publication ?? "UNKNOWN";
@@ -26,20 +59,26 @@ export function finalizeMutationResult<T>(
26
59
  }
27
60
  }
28
61
 
29
- /** Bound complete anchor rows before hashing or constructing their output strings. */
30
- export function formatMutationAnchors(lines: readonly string[], indices: Iterable<number>, hashLen: number, heading: string): string {
31
- const notice = "\n… (additional anchors omitted: 40-row/16 KiB limit; use read for full content)";
62
+ /** Return compact changed-position anchors; selected context rows retain full content within the byte budget. */
63
+ export function formatMutationAnchors(
64
+ beforeLines: readonly string[], lines: readonly string[], indices: Iterable<number>, anchors: AnchorFormatter, heading: string,
65
+ contentIndices?: ReadonlySet<number>,
66
+ ): string {
67
+ const notice = "\n… (additional anchors omitted: 16 KiB limit; use read for omitted positions)";
32
68
  const rows: string[] = [];
33
69
  let bytes = Buffer.byteLength(`\n${heading}\n`) + Buffer.byteLength(notice);
34
70
  let omitted = false;
35
71
  for (const index of indices) {
36
72
  const content = lines[index];
37
- const rowBytes = Buffer.byteLength(`${index + 1}#${"X".repeat(hashLen)}│`) + Buffer.byteLength(content) + 1;
38
- if (rows.length >= 40 || bytes + rowBytes > 16 * 1024) {
73
+ // Compare source content, not short hashes: a collision must not suppress a changed row.
74
+ if (beforeLines[index] === content) continue;
75
+ const row = contentIndices?.has(index) ? anchors.row(index + 1, content) : anchors.token(index + 1, content);
76
+ const rowBytes = Buffer.byteLength(row) + 1;
77
+ if (bytes + rowBytes > 16 * 1024) {
39
78
  omitted = true;
40
- break;
79
+ continue;
41
80
  }
42
- rows.push(`${index + 1}#${computeLineHash(index + 1, content, hashLen)}│${content}`);
81
+ rows.push(row);
43
82
  bytes += rowBytes;
44
83
  }
45
84
  return rows.length || omitted ? `\n${heading}\n${rows.join("\n")}${omitted ? notice : ""}` : "";
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
- import { decodeUtf8, computeLineHash } from "../core/index.ts";
15
+ import { decodeUtf8 } from "../core/index.ts";
18
16
  import { hasFinalNewline, splitLines } from "../core/lines.ts";
19
- import { getState } from "./state.ts";
20
- import { parseHashline } from "./render.ts";
17
+ import { createAnchorFormatter } from "./anchor-format.ts";
18
+ import { canonicalPath } from "./path.ts";
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.",
@@ -117,10 +99,7 @@ export function makeReadOverride(cwd: string) {
117
99
  renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
118
100
  if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
119
101
  const content = result.content?.[0];
120
- if (context?.isError) {
121
- const t = content?.type === "text" ? content.text.split("\n")[0] : "Error";
122
- return new Text(theme.fg("error", t), 0, 0);
123
- }
102
+ if (context?.isError) return renderToolError(result, theme);
124
103
  // Collapsed (not expanded): show nothing — the call line carries the
125
104
  // title, matching the built-in read's fold behavior.
126
105
  if (!expanded) return new Text("", 0, 0);
@@ -131,6 +110,7 @@ export function makeReadOverride(cwd: string) {
131
110
  async execute(toolCallId: string, params: any, signal: AbortSignal | undefined, onUpdate: any, ctx?: any) {
132
111
  // User cancelled → delegate to the built-in (builtin handles abort itself)
133
112
  if (signal?.aborted) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
113
+ const anchors = createAnchorFormatter();
134
114
 
135
115
  const absPath = canonicalPath(cwd, params.path as string);
136
116
  let buf: Buffer;
@@ -147,7 +127,6 @@ export function makeReadOverride(cwd: string) {
147
127
  const text = decodeUtf8(buf);
148
128
  const allLines = splitLines(text);
149
129
  const totalLines = allLines.length;
150
- const hashLen = getState().config.hashLen;
151
130
 
152
131
  // offset/limit
153
132
  const offset = (params.offset as number | undefined) ?? 1;
@@ -155,7 +134,7 @@ export function makeReadOverride(cwd: string) {
155
134
  const startIdx = Math.max(0, offset - 1);
156
135
  const endIdx = Math.min(totalLines, startIdx + limit);
157
136
 
158
- const rows = allLines.slice(startIdx, endIdx).map((line, index) => `${startIdx + index + 1}#${computeLineHash(startIdx + index + 1, line, hashLen)}│${line}`);
137
+ const rows = allLines.slice(startIdx, endIdx).map((line, index) => anchors.row(startIdx + index + 1, line));
159
138
  const truncation = truncateHead(rows.join("\n"), { maxBytes: MAX_BYTES, maxLines: rows.length });
160
139
 
161
140
  const shownFrom = offset > 1 ? ` (from line ${offset})` : "";
@@ -164,7 +143,7 @@ export function makeReadOverride(cwd: string) {
164
143
  // never copies into an edit `body`.
165
144
  const noFinalNewline = hasFinalNewline(text) ? "" : " · no trailing newline";
166
145
  const tail = truncation.firstLineExceedsLimit
167
- ? `\n… (line ${offset} exceeds ${MAX_BYTES >> 10}KB; cannot return a complete anchor row)`
146
+ ? `\n… (line ${offset} exceeds ${MAX_BYTES >> 10}KB; cannot return a complete anchor row. Reducing limit cannot split a physical line; use bash to inspect it in chunks, or replace for a known literal/regex change)`
168
147
  : truncation.truncated ? `\n… (truncated at ${MAX_BYTES >> 10}KB; use offset/limit to read more)` : "";
169
148
  const header = `${params.path} · ${totalLines} lines${shownFrom}${noFinalNewline}\n`;
170
149
  const body = truncation.content;
@@ -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({
@@ -0,0 +1,111 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generateDiffString, initTheme } from "@earendil-works/pi-coding-agent";
4
+ import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
5
+ import { displayCarriageReturns } from "./anchor-format.ts";
6
+ import { makeEditOverride } from "./edit-tool.ts";
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";
11
+
12
+ test("mutation headers refresh in place and retain isolated per-call counts", () => {
13
+ initTheme("dark");
14
+ for (const tool of [makeEditOverride(process.cwd()), makeReplaceTool(process.cwd())]) {
15
+ const args = { path: "a.txt", edits: [{ op: "append", body: ["new"] }], find: "old", replace: "new" };
16
+ const context: any = { args, state: {}, invalidate() { assert.fail("rendering must not invalidate the row"); } };
17
+ const header = tool.renderCall(args, theme, context);
18
+ const other = tool.renderCall({ ...args, path: "b.txt" }, theme, { state: {} });
19
+ assert.equal(context.state.callText, header);
20
+ tool.renderResult({ content: [{ type: "text", text: "Done" }], details: { diff: "-1 old\n+1 new" } }, { isPartial: false, expanded: false }, theme, context);
21
+ assert.match(header.render(100).join("\n"), /\+1/);
22
+ assert.match(header.render(100).join("\n"), /-1/);
23
+ assert.doesNotMatch(other.render(100).join("\n"), /\+1|-1/);
24
+ context.lastComponent = header;
25
+ assert.equal(tool.renderCall(args, theme, context), header);
26
+ assert.match(header.render(100).join("\n"), /\+1/);
27
+ }
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
@@ -103,6 +103,23 @@ export function publishDiffCounts(
103
103
  if (!prev || prev.added !== counts.added || prev.removed !== counts.removed) refreshHeader(counts);
104
104
  }
105
105
 
106
+ /** Reuse the call component and retain it for the result's in-place count refresh. */
107
+ export function renderMutationCall(
108
+ args: any, theme: any, context: any, header: (args: any, theme: any, counts?: DiffCounts) => string,
109
+ ): Text {
110
+ const text = (context?.lastComponent as Text | undefined) ?? new Text("", 0, 0);
111
+ if (context?.state) context.state.callText = text;
112
+ text.setText(header(args, theme, context?.state?.diffCounts));
113
+ return text;
114
+ }
115
+
116
+ /** Keep model-facing diagnostic details out of the compact error row. */
117
+ export function renderToolError(result: any, theme: any): Text {
118
+ const content = result.content?.[0];
119
+ const text = content?.type === "text" ? content.text.split("\n")[0] : "Error";
120
+ return new Text(theme.fg("error", text), 0, 0);
121
+ }
122
+
106
123
  /** Render mutation status or a diff, refreshing the call header's counts in place. */
107
124
  export function renderMutationResult(
108
125
  result: any, { isPartial, expanded }: any, theme: any, context: any,
@@ -110,11 +127,8 @@ export function renderMutationResult(
110
127
  ): Text {
111
128
  if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED") return new Text(theme.fg("warning", pending), 0, 0);
112
129
  const content = result.content?.[0];
113
- if (context.isError) {
114
- const text = content?.type === "text" ? content.text.split("\n")[0] : "Error";
115
- return new Text(theme.fg("error", text), 0, 0);
116
- }
117
- const diff: string | undefined = result.details?.diff;
130
+ if (context.isError) return renderToolError(result, theme);
131
+ const diff: string | undefined = result.details?.displayDiff ?? result.details?.diff;
118
132
  // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
119
133
  publishDiffCounts(diff, context, (counts) => {
120
134
  context.state?.callText?.setText(header(context.args, theme, counts));
@@ -143,9 +157,19 @@ export function withMutationStatus(tool: ToolDefinition<any, any, any>): ToolDef
143
157
  renderResult(result, options, theme, context) {
144
158
  const shell = context.state.mutationShell;
145
159
  const isPartial = options.isPartial && result.details?.actionFusion?.mutationCompleted !== true;
146
- 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 });
147
164
  // Pi runs renderCall first; update its box in place without invalidating the tool row.
148
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
+ }
149
173
  shell.box.setBgFn((line: string) => theme.bg(isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg", line));
150
174
  return new Container();
151
175
  },