@criogaid/pi-hashline-edit 0.1.0 → 0.1.2

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.
@@ -34,9 +34,10 @@ import { rgPath as bundledRgPath } from "@vscode/ripgrep";
34
34
  import { Type } from "typebox";
35
35
  import { Text } from "@earendil-works/pi-tui";
36
36
  import { readFile, realpath, stat } from "node:fs/promises";
37
- import { isAbsolute, join, relative, resolve, sep } from "node:path";
38
- import { hashFileLines } from "../core/hash.ts";
37
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
38
+ import { computeLineHash } from "../core/hash.ts";
39
39
  import { splitLines } from "../core/lines.ts";
40
+ import { decodeEditableText } from "../core/text.ts";
40
41
  import { getState } from "./state.ts";
41
42
  import { canonicalPath } from "./read-tool.ts";
42
43
  import { parseHashline } from "./render.ts";
@@ -59,7 +60,6 @@ const DEFAULT_LIMIT = 100;
59
60
  /** Max chars per result line for display (mirrors pi's truncate.ts; not exported there). */
60
61
  const GREP_MAX_LINE_LENGTH = 500;
61
62
  const GREP_CONTEXT_MAX = 20;
62
- const WILDCARD_ONLY_REGEX = /^(?:\^?\.(?:[*+?][+?]?)?\$?|[*+?])$/;
63
63
  const MAX_ALL_PATTERNS = 16;
64
64
  // ponytail: finite batches bound candidate buffers but still spawn per batch; revisit streaming for sustained large scans.
65
65
  const FILTER_BATCH_SIZE = 4096;
@@ -120,7 +120,7 @@ function clampContext(context: number | undefined): number {
120
120
  const grepOverrideSchema = Type.Object({
121
121
  pattern: Type.Union([Type.String(), Type.Array(Type.String())], {
122
122
  description:
123
- "Non-empty pattern(s). Arrays use matchMode. Wildcard-only searches require literal:true.",
123
+ "Non-empty pattern(s). Arrays use matchMode.",
124
124
  }),
125
125
  matchMode: Type.Optional(
126
126
  Type.Union([Type.Literal("any"), Type.Literal("all")], {
@@ -219,6 +219,50 @@ function scopeArgs(scope: SearchScope): string[] {
219
219
  ];
220
220
  }
221
221
 
222
+ interface SearchPathInfo {
223
+ path: string;
224
+ isFile: boolean;
225
+ }
226
+
227
+ function fileKey(path: string): string {
228
+ const absolute = resolve(path);
229
+ return process.platform === "win32" ? absolute.toLowerCase() : absolute;
230
+ }
231
+
232
+ async function filterExplicitFilesByGlob(
233
+ backend: GrepBackend,
234
+ rgPath: string,
235
+ scope: SearchScope,
236
+ paths: readonly SearchPathInfo[],
237
+ signal: AbortSignal | undefined,
238
+ ): Promise<string[]> {
239
+ const explicitFiles = paths.filter(({ isFile }) => isFile);
240
+ if (scope.globs.length === 0 || explicitFiles.length === 0) return paths.map(({ path }) => path);
241
+
242
+ const parents = [...new Set(explicitFiles.map(({ path }) => dirname(path)))];
243
+ const allowed = new Set<string>();
244
+ // Direct file arguments bypass ignore and symlink traversal; let only the ordered globs decide admission.
245
+ const args = [
246
+ ...COMMON_RG_ARGS,
247
+ ...scopeArgs({ ...scope, noIgnore: true, follow: true }),
248
+ "--files",
249
+ "--null",
250
+ "--max-depth=1",
251
+ "--",
252
+ ...parents,
253
+ ];
254
+ const listed = await backend.runRgPaths(rgPath, args, signal, async (path) => {
255
+ allowed.add(fileKey(path));
256
+ return true;
257
+ });
258
+ if (!listed.stopped && listed.code !== 0 && listed.code !== 1) {
259
+ throw new Error(listed.stderr.trim() || `ripgrep exited with code ${listed.code}`);
260
+ }
261
+ return paths
262
+ .filter(({ path, isFile }) => !isFile || allowed.has(fileKey(path)))
263
+ .map(({ path }) => path);
264
+ }
265
+
222
266
  async function fileIdentity(path: string): Promise<FileIdentity> {
223
267
  const value = await stat(path);
224
268
  if (!value.isFile()) throw new Error(`Search target is not a regular file: ${path}`);
@@ -287,7 +331,7 @@ async function scanPatternRanges(
287
331
  if (!files.includes(filePath)) throw new Error("ripgrep returned an unexpected search path");
288
332
  let lineCount = lineCounts.get(filePath);
289
333
  if (lineCount === undefined) {
290
- lineCount = splitLines((await readFile(filePath)).toString("utf8")).length;
334
+ lineCount = splitLines(decodeEditableText(await readFile(filePath))).length;
291
335
  lineCounts.set(filePath, lineCount);
292
336
  }
293
337
  const bytes = rgBytes(data.lines);
@@ -414,6 +458,10 @@ function countLeading(s: string): number {
414
458
  function toDisplayLines(raw: string, theme: any): string[] {
415
459
  const out: string[] = [];
416
460
  const lines = raw.split("\n");
461
+ const lineNoWidth = lines.reduce(
462
+ (width, line) => Math.max(width, parseHashline(line)?.lineNo.length ?? 0),
463
+ 0,
464
+ );
417
465
  let i = 0;
418
466
  while (i < lines.length) {
419
467
  const line = lines[i];
@@ -434,7 +482,7 @@ function toDisplayLines(raw: string, theme: any): string[] {
434
482
  const marker = base > 0 ? theme.fg("dim", "›") + " " : "";
435
483
  for (const g of group) {
436
484
  const body = g.content.slice(base);
437
- out.push(theme.fg("dim", ` ${g.lineNo}: `) + marker + theme.fg("toolOutput", body));
485
+ out.push(theme.fg("dim", ` ${g.lineNo.padStart(lineNoWidth)}: `) + marker + theme.fg("toolOutput", body));
438
486
  }
439
487
  i = j;
440
488
  continue;
@@ -539,14 +587,6 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
539
587
  if (patterns.some((pattern) => pattern.trim() === "")) {
540
588
  throw new Error("pattern must not be empty");
541
589
  }
542
- if (params.literal !== true) {
543
- const wildcard = patterns.find((pattern) => WILDCARD_ONLY_REGEX.test(pattern.trim()));
544
- if (wildcard !== undefined) {
545
- throw new Error(
546
- `Pattern ${JSON.stringify(wildcard)} is wildcard-only; use read for a known file or provide a concrete substring or identifier`,
547
- );
548
- }
549
- }
550
590
 
551
591
  const rgPath = bundledRgPath;
552
592
  const excludes = toArray(params.excludePattern);
@@ -574,7 +614,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
574
614
  const values = toArray(params.path);
575
615
  return (values.length ? values : ["."]).map((path) => canonicalPath(cwd, path));
576
616
  })();
577
- const scope: SearchScope = {
617
+ let scope: SearchScope = {
578
618
  globs,
579
619
  noIgnore: params.noIgnore === true,
580
620
  follow: params.follow === true,
@@ -582,10 +622,15 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
582
622
  };
583
623
  const hashLen = state.config.hashLen;
584
624
 
625
+ const pathInfo: SearchPathInfo[] = [];
585
626
  for (const searchPath of searchPaths) {
586
- try { await stat(searchPath); }
627
+ try { pathInfo.push({ path: searchPath, isFile: (await stat(searchPath)).isFile() }); }
587
628
  catch { throw new Error(`Path not found: ${searchPath}`); }
588
629
  }
630
+ scope = {
631
+ ...scope,
632
+ searchPaths: await filterExplicitFilesByGlob(backend, rgPath, scope, pathInfo, signal),
633
+ };
589
634
  if (matchMode === "all" && patterns.length > MAX_ALL_PATTERNS) {
590
635
  throw new Error(`matchMode:"all" supports at most ${MAX_ALL_PATTERNS} patterns`);
591
636
  }
@@ -597,7 +642,10 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
597
642
  let strictIdentities: Map<string, FileIdentity> | undefined;
598
643
  let linesTruncated = false;
599
644
 
600
- if (complex) {
645
+ if (scope.searchPaths.length === 0) {
646
+ raw = [];
647
+ matchLimitReached = false;
648
+ } else if (complex) {
601
649
  await backend.validatePatterns(rgPath, patterns, modes, !!wordMatch, signal);
602
650
  await backend.validatePatterns(rgPath, excludes, modes, false, signal);
603
651
  const result = await complexSearch({
@@ -618,7 +666,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
618
666
  ...scopeArgs(scope),
619
667
  ];
620
668
  for (const pattern of matchMode === "all" ? patterns.slice(0, 1) : patterns) args.push("-e", pattern);
621
- args.push("--", ...searchPaths);
669
+ args.push("--", ...scope.searchPaths);
622
670
 
623
671
  const andPredicates = matchMode === "all"
624
672
  ? patterns.slice(1).map((pattern) => backend.createLinePredicate(rgPath, [pattern], modes, !!wordMatch, signal))
@@ -697,29 +745,23 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
697
745
  }
698
746
  for (const lines of byFile.values()) lines.sort((a, b) => a - b);
699
747
 
700
- // Read each file once and hash all its lines; hash is computed from the FULL line.
701
- const fileCache = new Map<string, { lines: string[]; hashes: string[] }>();
748
+ // Read each file once; only hash the selected match/context rows below.
702
749
  const getFile = async (filePath: string) => {
703
- let entry = fileCache.get(filePath);
704
- if (!entry) {
705
- let content: string;
706
- try {
707
- content = (await readFile(filePath)).toString("utf-8");
708
- } catch (error) {
709
- if (strictIdentities) throw error;
710
- content = "";
711
- }
712
- if (strictIdentities) {
713
- const baseline = strictIdentities.get(filePath);
714
- if (!baseline || !sameIdentity(baseline, await fileIdentity(filePath))) {
715
- throw new Error("File changed during search; rerun the query.");
716
- }
750
+ let bytes: Buffer;
751
+ try {
752
+ bytes = await readFile(filePath);
753
+ } catch (error) {
754
+ if (strictIdentities) throw error;
755
+ bytes = Buffer.alloc(0);
756
+ }
757
+ const content = decodeEditableText(bytes);
758
+ if (strictIdentities) {
759
+ const baseline = strictIdentities.get(filePath);
760
+ if (!baseline || !sameIdentity(baseline, await fileIdentity(filePath))) {
761
+ throw new Error("File changed during search; rerun the query.");
717
762
  }
718
- const lines = splitLines(content);
719
- entry = { lines, hashes: hashFileLines(lines, hashLen) };
720
- fileCache.set(filePath, entry);
721
763
  }
722
- return entry;
764
+ return splitLines(content);
723
765
  };
724
766
 
725
767
  const formatPath = (filePath: string): string => {
@@ -733,7 +775,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
733
775
  const blocks: string[] = [];
734
776
  if (outputMode === "content") {
735
777
  for (const [filePath, matchLines] of byFile) {
736
- const { lines, hashes } = await getFile(filePath);
778
+ const lines = await getFile(filePath);
737
779
  // Context windows are rebuilt from surviving matches so context
738
780
  // lines of a filtered-out match never leak.
739
781
  const windowSet = new Set<number>();
@@ -748,7 +790,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
748
790
  const rows: string[] = [];
749
791
  for (const n of [...windowSet].sort((a, b) => a - b)) {
750
792
  const content = lines[n - 1] ?? "";
751
- const hash = hashes[n - 1] ?? "";
793
+ const hash = n <= lines.length ? computeLineHash(n, content, hashLen) : "";
752
794
  const { text: display, wasTruncated } = truncateLine(content.replace(/\r/g, ""));
753
795
  if (wasTruncated) linesTruncated = true;
754
796
  rows.push(`${n}#${hash}│${display}`);
@@ -22,6 +22,7 @@ type FakeOptions = {
22
22
  error?: Error;
23
23
  onRun?: () => void;
24
24
  smartCase?: boolean;
25
+ paths?: string[];
25
26
  };
26
27
 
27
28
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
@@ -82,8 +83,11 @@ function fakeBackend(options: FakeOptions = {}) {
82
83
  stopped: false,
83
84
  };
84
85
  },
85
- async runRgPaths() {
86
- return { code: 1, stderr: "", stopped: false };
86
+ async runRgPaths(_path, _args, _signal, onPath) {
87
+ for (const path of options.paths ?? []) {
88
+ if (!await onPath(path)) return { code: null, stderr: "", stopped: true };
89
+ }
90
+ return { code: options.paths?.length ? 0 : 1, stderr: "", stopped: false };
87
91
  },
88
92
  async resolveIgnoreCase(_path, patterns, modes, explicit) {
89
93
  modeCalls.push({ patterns, literal: modes.literal, explicit });
@@ -230,7 +234,10 @@ test("passes output flags and formats files and counts", async () => {
230
234
  const b = join(dir, "b.ts");
231
235
  await writeFile(a, "Foo a.b\n");
232
236
  await writeFile(b, "foo a.b\n");
233
- const fake = fakeBackend({ lines: [rgMatch(a, 1, "Foo a.b\n"), rgMatch(b, 1, "foo a.b\n")] });
237
+ const fake = fakeBackend({
238
+ lines: [rgMatch(a, 1, "Foo a.b\n"), rgMatch(b, 1, "foo a.b\n")],
239
+ paths: [a, b],
240
+ });
234
241
 
235
242
  const files = await call(makeGrepOverrideWithBackend(dir, fake.backend), {
236
243
  pattern: ["Foo", "a.b"],
@@ -276,6 +283,26 @@ test("passes output flags and formats files and counts", async () => {
276
283
  );
277
284
  });
278
285
 
286
+ test("aligns TUI line numbers across files to the widest result", () => {
287
+ const tool = makeGrepOverrideWithBackend(process.cwd(), fakeBackend().backend);
288
+ const raw = [
289
+ "a.ts · 2 matches",
290
+ "99#ABCD│ alpha",
291
+ "100#ABCD│ beta",
292
+ "b.ts · 1 match",
293
+ "7#ABCD│gamma",
294
+ ].join("\n");
295
+ const theme = { fg: (_color: string, value: string) => value };
296
+ const rendered = tool.renderResult!(
297
+ { content: [{ type: "text", text: raw }] },
298
+ { isPartial: false, expanded: true },
299
+ theme,
300
+ {},
301
+ ).render(80).map((line: string) => line.trimEnd());
302
+ const rows = rendered.filter((line: string) => /^\s+\d+:/.test(line));
303
+ assert.deepEqual(rows.map((line: string) => line.indexOf(":")), [6, 6, 6]);
304
+ });
305
+
279
306
  test("counts only surviving matches toward the limit and stops the fake runner", async () => {
280
307
  await withDir(async (dir) =>
281
308
  withEnabled(true, async () => {
@@ -387,7 +414,7 @@ test("bounds rg predicate fanout for matchMode all", async () => {
387
414
  });
388
415
  });
389
416
 
390
- test("rejects empty and wildcard-only regexes without blocking literal or empty-line searches", async () => {
417
+ test("rejects empty patterns while allowing wildcard, literal, and empty-line searches", async () => {
391
418
  await withDir(async (dir) => {
392
419
  const fake = fakeBackend();
393
420
  const tool = makeGrepOverrideWithBackend(dir, fake.backend);
@@ -395,15 +422,15 @@ test("rejects empty and wildcard-only regexes without blocking literal or empty-
395
422
  for (const pattern of ["", " ", []]) {
396
423
  await assert.rejects(call(tool, { pattern }), /pattern (?:is required|must not be empty)/);
397
424
  }
398
- for (const pattern of [".*", "^.+$", ".?", "*"]) {
399
- await assert.rejects(call(tool, { pattern }), /is wildcard-only/);
400
- }
401
425
  assert.equal(fake.calls.length, 0);
426
+ for (const pattern of [".*", "^.+$", ".?"]) {
427
+ assert.equal(text(await call(tool, { pattern })), "No matches found");
428
+ }
402
429
 
403
430
  assert.equal(text(await call(tool, { pattern: ".*", literal: true })), "No matches found");
404
431
  assert.equal(text(await call(tool, { pattern: "^$" })), "No matches found");
405
- assert.equal(fake.calls.filter(({ args }) => !args.includes("--quiet")).length, 2);
406
- assert.equal(fake.calls.filter(({ args }) => args.includes("--quiet")).length, 1);
432
+ assert.equal(fake.calls.filter(({ args }) => !args.includes("--quiet")).length, 5);
433
+ assert.equal(fake.calls.filter(({ args }) => args.includes("--quiet")).length, 4);
407
434
  });
408
435
  });
409
436
 
@@ -513,3 +540,21 @@ test("large candidate lines flush before the batch line-count limit", async () =
513
540
  assert.deepEqual(sizes, [2, 1]);
514
541
  });
515
542
  });
543
+
544
+ test("grep rejects malformed UTF-8 and NUL bytes instead of hashing binary text", async () => {
545
+ await withDir(async (dir) =>
546
+ withEnabled(true, async () => {
547
+ const cases = [
548
+ { name: "invalid.txt", bytes: Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]), error: /UNSUPPORTED_ENCODING/ },
549
+ { name: "nul.txt", bytes: Buffer.from([0x61, 0x00, 0x62]), error: /UNSUPPORTED_TEXT/ },
550
+ ];
551
+ for (const fixture of cases) {
552
+ const file = join(dir, fixture.name);
553
+ await writeFile(file, fixture.bytes);
554
+ const fake = fakeBackend({ lines: [rgMatch(file, 1, "a\n")], paths: [file] });
555
+ await assert.rejects(call(makeGrepOverrideWithBackend(dir, fake.backend), { pattern: "a", path: file }), fixture.error);
556
+ assert.deepEqual(await readFile(file), fixture.bytes);
557
+ }
558
+ }),
559
+ );
560
+ });
@@ -0,0 +1,46 @@
1
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import { FileMutationError, type MutationVersions, type PublicationStatus } from "./file-commit.ts";
3
+ import { computeLineHash } from "../core/hash.ts";
4
+
5
+ export function observedFreshness(result: AgentToolResult<unknown>): "unchanged" | "changed" | "unknown" {
6
+ const versions = result.details as Partial<MutationVersions> | undefined;
7
+ if (!versions?.publishedRevision || !versions.observedRevision) return "unknown";
8
+ return versions.publishedRevision === versions.observedRevision ? "unchanged" : "changed";
9
+ }
10
+
11
+ /** Finalize from the observed commit revision unless a later freshness check supplies the decision. */
12
+ export function finalizeMutationResult<T>(
13
+ result: AgentToolResult<T>,
14
+ finalize: (result: AgentToolResult<T>, publishAnchors: boolean) => AgentToolResult<T>,
15
+ publishAnchors = observedFreshness(result) === "unchanged",
16
+ ): AgentToolResult<T> {
17
+ try {
18
+ const finalized = finalize(result, publishAnchors);
19
+ return publishAnchors ? finalized : {
20
+ ...finalized,
21
+ content: [...finalized.content, { type: "text", text: "Anchors omitted: target revision was not confirmed unchanged. Re-read before further edits." }],
22
+ };
23
+ } catch (error) {
24
+ const publication = (result.details as { publication?: PublicationStatus } | undefined)?.publication ?? "UNKNOWN";
25
+ throw new FileMutationError("post_process", publication, `Result generation failed; publication=${publication}. Re-read before retrying: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
26
+ }
27
+ }
28
+
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)";
32
+ const rows: string[] = [];
33
+ let bytes = Buffer.byteLength(`\n${heading}\n`) + Buffer.byteLength(notice);
34
+ let omitted = false;
35
+ for (const index of indices) {
36
+ 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) {
39
+ omitted = true;
40
+ break;
41
+ }
42
+ rows.push(`${index + 1}#${computeLineHash(index + 1, content, hashLen)}│${content}`);
43
+ bytes += rowBytes;
44
+ }
45
+ return rows.length || omitted ? `\n${heading}\n${rows.join("\n")}${omitted ? notice : ""}` : "";
46
+ }
@@ -14,7 +14,7 @@ import { Text } from "@earendil-works/pi-tui";
14
14
  import { readFile } from "node:fs/promises";
15
15
  import { join, resolve } from "node:path";
16
16
  import { homedir } from "node:os";
17
- import { hashFileLines } from "../core/hash.ts";
17
+ import { decodeUtf8, computeLineHash } from "../core/index.ts";
18
18
  import { hasFinalNewline, splitLines } from "../core/lines.ts";
19
19
  import { getState } from "./state.ts";
20
20
  import { parseHashline } from "./render.ts";
@@ -144,10 +144,10 @@ export function makeReadOverride(cwd: string) {
144
144
  // binary/image detection (null byte) → delegate to the built-in (it uses file-type for images)
145
145
  if (buf.includes(0)) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
146
146
 
147
- const text = buf.toString("utf-8");
147
+ const text = decodeUtf8(buf);
148
148
  const allLines = splitLines(text);
149
149
  const totalLines = allLines.length;
150
- const hashes = hashFileLines(allLines, getState().config.hashLen);
150
+ const hashLen = getState().config.hashLen;
151
151
 
152
152
  // offset/limit
153
153
  const offset = (params.offset as number | undefined) ?? 1;
@@ -155,7 +155,7 @@ export function makeReadOverride(cwd: string) {
155
155
  const startIdx = Math.max(0, offset - 1);
156
156
  const endIdx = Math.min(totalLines, startIdx + limit);
157
157
 
158
- const rows = allLines.slice(startIdx, endIdx).map((line, index) => `${startIdx + index + 1}#${hashes[startIdx + index]}│${line}`);
158
+ const rows = allLines.slice(startIdx, endIdx).map((line, index) => `${startIdx + index + 1}#${computeLineHash(startIdx + index + 1, line, hashLen)}│${line}`);
159
159
  const truncation = truncateHead(rows.join("\n"), { maxBytes: MAX_BYTES, maxLines: rows.length });
160
160
 
161
161
  const shownFrom = offset > 1 ? ` (from line ${offset})` : "";
@@ -5,8 +5,11 @@ import assert from "node:assert/strict";
5
5
  import { test } from "node:test";
6
6
  import registerHashline from "../index.ts";
7
7
  import { getState } from "./state.ts";
8
+ import { initTheme } from "@earendil-works/pi-coding-agent";
9
+ import { ToolExecutionComponent } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tool-execution.js";
10
+ import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
8
11
 
9
- test("enabled registration installs the Hashline write and shared Fusion schemas", async () => {
12
+ test("registered mutation cards finish independently of fused command cards", async () => {
10
13
  const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
11
14
  const previousCwd = process.cwd();
12
15
  const state = getState();
@@ -17,9 +20,10 @@ test("enabled registration installs the Hashline write and shared Fusion schemas
17
20
  process.chdir(dir);
18
21
  const tools: any[] = [];
19
22
  const entries: any[] = [];
23
+ const renderers = new Map<string, any>();
20
24
  registerHashline({
21
25
  on() {},
22
- registerEntryRenderer() {},
26
+ registerEntryRenderer(type: string, renderer: any) { renderers.set(type, renderer); },
23
27
  appendEntry(customType: string, data: unknown) { entries.push({ customType, data }); },
24
28
  registerTool(tool: any) { tools.push(tool); },
25
29
  } as any);
@@ -27,12 +31,55 @@ test("enabled registration installs the Hashline write and shared Fusion schemas
27
31
  for (const tool of tools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
28
32
  assert.ok(tool.parameters.properties.then_run, `${tool.name} should expose then_run when actionFusion is enabled`);
29
33
  }
30
- const writeTool = tools.find((tool) => tool.name === "write");
31
- const result = await writeTool.execute("write-error", { path: "published.txt", content: "published\n", then_run: { command: "node -e \\\"process.exit(1)\\\"" } }, undefined, undefined, { cwd: dir });
32
- assert.equal(result.details.actionFusion.command, "failed");
33
- assert.match(result.content[1].text, /File changes are saved[\s\S]*Command failed/);
34
- assert.deepEqual(entries.map((entry) => entry.data.command), ["waiting", "failed"]);
35
- assert.equal(entries[1].data.publication, "PUBLISHED");
34
+ initTheme("dark");
35
+ const cases = [
36
+ { name: "write", args: { content: "published\n" } },
37
+ { name: "edit", args: { edits: [{ op: "append", body: ["appended"] }] } },
38
+ { name: "replace", args: { find: "published", replace: "published" } },
39
+ ];
40
+ for (const { name, args } of cases) {
41
+ const tool = tools.find((tool) => tool.name === name);
42
+ const params = { path: "published.txt", ...args, then_run: { command: "exit 7" } };
43
+ const card = new ToolExecutionComponent(name, name, params, {}, tool, { requestRender() {} } as any, dir);
44
+ card.setArgsComplete();
45
+ card.markExecutionStarted();
46
+ const frames: { command: string; publication: string; mutationCompleted: boolean; output: string; commandOutput: string }[] = [];
47
+ const result = await tool.execute(name, params, undefined, (update: any) => {
48
+ card.updateResult({ ...update, isError: false }, true);
49
+ const entry = entries.find((entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === name);
50
+ const commandCard = renderers.get(entry.customType)(entry, { expanded: false }, theme);
51
+ frames.push({ ...update.details.actionFusion, output: card.render(100).join("\n"), commandOutput: commandCard.render(100).join("\n") });
52
+ }, { cwd: dir });
53
+ assert.equal(result.details.actionFusion.command, "failed");
54
+ assert.match(result.content[1].text, /File changes are saved|No file changes were published/);
55
+ assert.ok(frames[0].output.includes(theme.getBgAnsi("toolPendingBg")));
56
+ const running = frames.find((frame) => frame.command === "running")!;
57
+ assert.ok(running, `${name} should emit running progress`);
58
+ assert.ok(running.output.includes(theme.getBgAnsi("toolSuccessBg")), `${name} should turn green before then_run ends`);
59
+ assert.ok(!running.output.includes(theme.getBgAnsi("toolPendingBg")));
60
+ assert.ok(running.commandOutput.includes(theme.getBgAnsi("toolPendingBg")));
61
+ assert.ok(frames.at(-1)!.commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
62
+ const completed = frames.find((frame) => frame.command === "waiting" && frame.mutationCompleted)!;
63
+ assert.ok(completed?.output.includes(theme.getBgAnsi("toolSuccessBg")), "mutation completion must repaint before command checks");
64
+ if (name === "replace") assert.equal(running.publication, "NOT_PUBLISHED");
65
+ card.updateResult({ ...result, isError: false });
66
+ assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
67
+ card.setExpanded(true);
68
+ assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
69
+
70
+ const invalid = { ...params, path: "missing.txt", ...(name === "write" ? { mode: "overwrite" } : {}) };
71
+ const failedCard = new ToolExecutionComponent(name, `${name}-bad`, invalid, {}, tool, { requestRender() {} } as any, dir);
72
+ await assert.rejects(tool.execute(`${name}-bad`, invalid, undefined, (update: any) => {
73
+ failedCard.updateResult({ ...update, isError: false }, true);
74
+ }, { cwd: dir }), (error: Error) => {
75
+ failedCard.updateResult({ content: [{ type: "text", text: error.message }], isError: true });
76
+ const output = failedCard.render(100).join("\n");
77
+ assert.ok(output.includes(theme.getBgAnsi("toolErrorBg")), `${name} mutation failure should turn red`);
78
+ assert.ok(!output.includes(theme.getBgAnsi("toolPendingBg")));
79
+ return true;
80
+ });
81
+ }
82
+ assert.deepEqual(entries.map((entry) => entry.data.command), cases.flatMap(() => ["waiting", "failed", "waiting", "skipped"]));
36
83
  } finally {
37
84
  process.chdir(previousCwd);
38
85
  state.config = previousConfig;
package/src/pi/render.ts CHANGED
@@ -9,7 +9,8 @@
9
9
  * @module pi-hashline-edit/pi
10
10
  */
11
11
 
12
- import { renderDiff } from "@earendil-works/pi-coding-agent";
12
+ import { renderDiff, type ToolDefinition } from "@earendil-works/pi-coding-agent";
13
+ import { Box, Container, Text } from "@earendil-works/pi-tui";
13
14
 
14
15
  const HASHLINE_RE = /^(\d+)#[A-Za-z0-9]+│(.*)$/;
15
16
 
@@ -101,3 +102,52 @@ export function publishDiffCounts(
101
102
  context.state.diffCounts = counts;
102
103
  if (!prev || prev.added !== counts.added || prev.removed !== counts.removed) refreshHeader(counts);
103
104
  }
105
+
106
+ /** Render mutation status or a diff, refreshing the call header's counts in place. */
107
+ export function renderMutationResult(
108
+ result: any, { isPartial, expanded }: any, theme: any, context: any,
109
+ pending: string, fallback: string, header: (args: any, theme: any, counts?: DiffCounts) => string,
110
+ ): Text {
111
+ if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED") return new Text(theme.fg("warning", pending), 0, 0);
112
+ 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;
118
+ // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
119
+ publishDiffCounts(diff, context, (counts) => {
120
+ context.state?.callText?.setText(header(context.args, theme, counts));
121
+ });
122
+ if (!diff) {
123
+ // Only the summary is displayed; subsequent anchor rows are for the model.
124
+ const summary = content?.type === "text" ? content.text.split("\n")[0] : fallback;
125
+ return new Text(theme.fg("success", summary), 0, 0);
126
+ }
127
+ return new Text(renderDiffPreview(diff, expanded, theme), 0, 0);
128
+ }
129
+
130
+ /** Keep the mutation card's background independent of the fused command's lifetime. */
131
+ export function withMutationStatus(tool: ToolDefinition<any, any, any>): ToolDefinition<any, any, any> {
132
+ return {
133
+ ...tool,
134
+ renderShell: "self",
135
+ renderCall(args, theme, context) {
136
+ const shell = context.state.mutationShell ??= { box: new Box(1, 1) };
137
+ shell.call = tool.renderCall!(args, theme, { ...context, lastComponent: shell.call });
138
+ shell.box.clear();
139
+ shell.box.addChild(shell.call);
140
+ shell.box.setBgFn((line: string) => theme.bg(context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg", line));
141
+ return shell.box;
142
+ },
143
+ renderResult(result, options, theme, context) {
144
+ const shell = context.state.mutationShell;
145
+ const isPartial = options.isPartial && result.details?.actionFusion?.mutationCompleted !== true;
146
+ shell.result = tool.renderResult!(result, { ...options, isPartial }, theme, { ...context, isPartial, lastComponent: shell.result });
147
+ // Pi runs renderCall first; update its box in place without invalidating the tool row.
148
+ shell.box.addChild(shell.result);
149
+ shell.box.setBgFn((line: string) => theme.bg(isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg", line));
150
+ return new Container();
151
+ },
152
+ };
153
+ }