@criogaid/pi-hashline-edit 0.7.0 → 0.9.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 (118) hide show
  1. package/README.md +76 -220
  2. package/README.zh-CN.md +166 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +171 -133
  6. package/src/core/apply.ts +34 -31
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +49 -9
  14. package/src/core/ranges.ts +15 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +6 -8
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +18 -10
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +132 -92
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +4 -5
  34. package/src/integration/model-budget-lifecycle.test.ts +26 -8
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +2 -2
  37. package/src/integration/npm-package.testing.ts +7 -33
  38. package/src/integration/publication-read-changes.test.ts +60 -28
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +3 -3
  42. package/src/integration/utf8-errors.test.ts +3 -3
  43. package/src/pi/AGENTS.md +13 -14
  44. package/src/pi/action-fusion.test.ts +75 -220
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +35 -186
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +25 -38
  52. package/src/pi/argument-validation.test.ts +446 -420
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +175 -121
  60. package/src/pi/execute.test.ts +170 -227
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +13 -10
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +271 -170
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +27 -18
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +7 -6
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +106 -67
  92. package/src/pi/render.test.ts +239 -109
  93. package/src/pi/render.ts +42 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +29 -27
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +60 -45
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +186 -131
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -19,7 +19,7 @@ import {
19
19
  } from "node:fs/promises";
20
20
  import type { BigIntStats, Stats } from "node:fs";
21
21
  import { dirname, join } from "node:path";
22
- import { createHash } from "node:crypto";
22
+ import { byteRevision } from "./file-revision.ts";
23
23
  import { decodeEditableText, unwritableTextError } from "../core/text.ts";
24
24
  import {
25
25
  errnoCode,
@@ -42,21 +42,19 @@ export type CommitOptions = { readonly signal?: AbortSignal } & (
42
42
  | { readonly mode: "overwrite"; readonly baseRevision?: string }
43
43
  );
44
44
 
45
- export interface MutationVersions {
46
- baseRevision?: string;
47
- publishedRevision: string;
45
+ /** The published bytes' revision and, when stable, the revision observed right after. */
46
+ interface CommitRevisions {
47
+ readonly publishedRevision: string;
48
48
  /** Absent when a concurrent change prevented a stable observation after publication. */
49
- observedRevision?: string;
49
+ readonly observedRevision?: string;
50
50
  }
51
51
 
52
- export type CommitResult = MutationVersions &
52
+ export type CommitResult = CommitRevisions &
53
53
  (
54
- | { readonly created: true; readonly publication: "PUBLISHED"; readonly baseRevision?: never }
55
- | { readonly created: false; readonly publication: "PUBLISHED"; readonly baseRevision: string }
54
+ | { readonly created: boolean; readonly publication: "PUBLISHED" }
56
55
  | {
57
56
  readonly created: false;
58
57
  readonly publication: "NOT_PUBLISHED";
59
- readonly baseRevision: string;
60
58
  readonly observedRevision: string;
61
59
  }
62
60
  );
@@ -83,10 +81,6 @@ export class FileMutationError<C extends ErrorCode = ErrorCode> extends Hashline
83
81
  }
84
82
  }
85
83
 
86
- export function byteRevision(content: string | Uint8Array): string {
87
- return createHash("sha256").update(content).digest("hex");
88
- }
89
-
90
84
  function requireRegularFile(target: Stats | BigIntStats): void {
91
85
  if (!target.isFile()) throw prepareError("NOT_REGULAR_FILE", "Target is not a regular file.");
92
86
  }
@@ -338,7 +332,6 @@ export async function commitFile(
338
332
  }
339
333
  return {
340
334
  created: false,
341
- baseRevision: target.beforeRevision,
342
335
  publishedRevision,
343
336
  observedRevision: publishedRevision,
344
337
  publication: "NOT_PUBLISHED",
@@ -362,7 +355,6 @@ export async function commitFile(
362
355
  }
363
356
  const tempPath = join(tempDir, "content");
364
357
  let published = false;
365
- let failure: unknown;
366
358
  try {
367
359
  await writeAndSyncTemp(tempPath, bytes, target.modeBits, options.signal);
368
360
  if (baseRevision !== undefined) {
@@ -380,9 +372,7 @@ export async function commitFile(
380
372
  published = true;
381
373
  await syncDirectory(publishDirectory);
382
374
  const committed: CommitResult = {
383
- ...(target.existed
384
- ? { created: false, baseRevision: target.beforeRevision }
385
- : { created: true, baseRevision: target.beforeRevision }),
375
+ created: !target.existed,
386
376
  publishedRevision,
387
377
  publication: "PUBLISHED",
388
378
  };
@@ -401,7 +391,6 @@ export async function commitFile(
401
391
  );
402
392
  }
403
393
  } catch (error) {
404
- failure = error;
405
394
  if (error instanceof FileMutationError) throw error;
406
395
  if (published)
407
396
  throw new FileMutationError(
@@ -422,26 +411,8 @@ export async function commitFile(
422
411
  { cause: error },
423
412
  );
424
413
  } finally {
425
- try {
426
- await rm(tempDir, { recursive: true, force: true });
427
- } catch (error) {
428
- if (!published) {
429
- if (failure !== undefined) throw failure;
430
- throw error;
431
- }
432
- throw new FileMutationError(
433
- "POST_PROCESS_FAILED",
434
- "post_process",
435
- "PUBLISHED",
436
- "Temporary cleanup failed.",
437
- {
438
- cause:
439
- failure === undefined
440
- ? error
441
- : new AggregateError([failure, error], "post-publication cleanup also failed"),
442
- },
443
- );
444
- }
414
+ // Best effort: a leftover temporary directory changes neither the publication nor the recovery.
415
+ await rm(tempDir, { recursive: true, force: true }).catch(() => undefined);
445
416
  }
446
417
  }
447
418
 
@@ -455,7 +426,7 @@ export type FreshnessObservation =
455
426
  };
456
427
 
457
428
  /** Freshness known from the commit result alone, before any later observation. */
458
- export function commitFreshness(commit: MutationVersions): FreshnessObservation {
429
+ export function commitFreshness(commit: CommitRevisions): FreshnessObservation {
459
430
  return {
460
431
  freshness: commit.publishedRevision === commit.observedRevision ? "unchanged" : "changed",
461
432
  };
@@ -0,0 +1,25 @@
1
+ /**
2
+ * A file revision is the SHA-256 hex digest of its exact bytes, computed whole or streamed;
3
+ * equal bytes always give equal revisions. Commits and streaming scans share this one rule.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
7
+ import { createHash } from "node:crypto";
8
+
9
+ export function createRevisionHasher() {
10
+ const hash = createHash("sha256");
11
+ return {
12
+ update(bytes: Uint8Array): void {
13
+ hash.update(bytes);
14
+ },
15
+ digest(): string {
16
+ return hash.digest("hex");
17
+ },
18
+ };
19
+ }
20
+
21
+ export function byteRevision(bytes: Uint8Array): string {
22
+ const hasher = createRevisionHasher();
23
+ hasher.update(bytes);
24
+ return hasher.digest();
25
+ }
@@ -0,0 +1,143 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { initTheme, type AgentSession } from "@earendil-works/pi-coding-agent";
4
+ import { ProcessTerminal, TuiMainScreen, type TuiMouseEvent } from "@earendil-works/pi-tui";
5
+ import { CustomEntryComponent } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/custom-entry.js";
6
+ import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
7
+ import { openTestSession } from "../testing/session.testing.ts";
8
+ import { registerFusionCards } from "./fusion-card.ts";
9
+
10
+ const output = Array.from({ length: 20 }, (_, i) => `command output ${i}`).join("\n");
11
+
12
+ async function bindTui(session: AgentSession) {
13
+ const tui = new TuiMainScreen(new ProcessTerminal());
14
+ tui.requestRender = () => {};
15
+ await session.bindExtensions({
16
+ mode: "tui",
17
+ uiContext: {
18
+ ...session.extensionRunner.createContext().ui,
19
+ setWidget: ((_, content) => {
20
+ if (typeof content === "function") assert.deepEqual(content(tui, theme).render(100), []);
21
+ }) satisfies ReturnType<typeof session.extensionRunner.createContext>["ui"]["setWidget"],
22
+ },
23
+ });
24
+ }
25
+
26
+ test("command cards share native mouse behavior and preserve independent expansion through updates and redraws", async (t) => {
27
+ initTheme("dark");
28
+ let report: ReturnType<typeof registerFusionCards> | undefined;
29
+ const { session, sessionManager } = await openTestSession(t, {
30
+ tools: [],
31
+ configure(pi) {
32
+ report = registerFusionCards(pi);
33
+ },
34
+ });
35
+ await bindTui(session);
36
+ assert.ok(report);
37
+ const progress = {
38
+ toolCallId: "first",
39
+ commandText: "check",
40
+ command: "running" as const,
41
+ freshness: "unchanged" as const,
42
+ result: { content: [{ type: "text" as const, text: output }] },
43
+ mutationCompleted: true,
44
+ };
45
+ report(progress);
46
+ report({ ...progress, toolCallId: "second" });
47
+ const renderer = session.extensionRunner.getEntryRenderer("hashline-then-run");
48
+ assert.ok(renderer);
49
+ const hosts = sessionManager
50
+ .getBranch()
51
+ .filter((entry) => entry.type === "custom" && entry.customType === "hashline-then-run")
52
+ .map((entry) => {
53
+ assert.ok(entry.type === "custom");
54
+ return new CustomEntryComponent(entry, renderer);
55
+ });
56
+ const [first, second] = hosts;
57
+ assert.ok(first && second);
58
+ const rows = first.render(100);
59
+ const event: TuiMouseEvent = {
60
+ type: "click",
61
+ button: "left",
62
+ x: 4,
63
+ y: 2,
64
+ screenX: 4,
65
+ screenY: 2,
66
+ width: 100,
67
+ height: rows.length,
68
+ shift: false,
69
+ alt: false,
70
+ ctrl: false,
71
+ };
72
+ assert.doesNotMatch(rows.join("\n"), /command output 0\b/);
73
+ for (const ignored of [
74
+ { ...event, button: "right" as const },
75
+ ...(["press", "release", "drag", "wheel"] as const).map((type) => ({ ...event, type })),
76
+ ]) {
77
+ assert.equal(first.handleMouse(ignored), undefined);
78
+ assert.deepEqual(first.render(100), rows);
79
+ }
80
+ assert.equal(first.handleMouse(event)?.handled, true);
81
+ assert.match(first.render(100).join("\n"), /command output 0\b/);
82
+ assert.doesNotMatch(second.render(100).join("\n"), /command output 0\b/);
83
+ report({
84
+ ...progress,
85
+ command: "succeeded",
86
+ result: { content: [{ type: "text", text: `${output}\nfinished` }] },
87
+ });
88
+ first.invalidate();
89
+ assert.match(first.render(40).join("\n"), /command output 0\b/);
90
+ assert.match(first.render(100).join("\n"), /finished/);
91
+ first.setExpanded(true);
92
+ first.setExpanded(false);
93
+ assert.doesNotMatch(first.render(100).join("\n"), /command output 0\b/);
94
+ first.setExpanded(true);
95
+ assert.match(first.render(100).join("\n"), /command output 0\b/);
96
+ });
97
+
98
+ test("command entries rebuilt before session_start → remain visible and become interactive after UI binding", async (t) => {
99
+ initTheme("dark");
100
+ let report: ReturnType<typeof registerFusionCards> | undefined;
101
+ const { session, sessionManager } = await openTestSession(t, {
102
+ tools: [],
103
+ configure(pi) {
104
+ report = registerFusionCards(pi);
105
+ },
106
+ });
107
+ assert.ok(report);
108
+ report({
109
+ toolCallId: "restored",
110
+ commandText: "check",
111
+ command: "succeeded",
112
+ freshness: "unchanged",
113
+ result: { content: [{ type: "text", text: output }] },
114
+ mutationCompleted: true,
115
+ });
116
+ const entry = sessionManager
117
+ .getBranch()
118
+ .find((entry) => entry.type === "custom" && entry.customType === "hashline-then-run");
119
+ const renderer = session.extensionRunner.getEntryRenderer("hashline-then-run");
120
+ assert.ok(entry?.type === "custom" && renderer);
121
+ const host = new CustomEntryComponent(entry, renderer);
122
+ assert.equal(host.hasContent(), true, "Pi discards entries without a component during reload");
123
+ await bindTui(session);
124
+ const rows = host.render(100);
125
+ assert.match(rows.join("\n"), /succeeded[\s\S]*command output 19/);
126
+ assert.equal(
127
+ host.handleMouse({
128
+ type: "click",
129
+ button: "left",
130
+ x: 4,
131
+ y: 2,
132
+ screenX: 4,
133
+ screenY: 2,
134
+ width: 100,
135
+ height: rows.length,
136
+ shift: false,
137
+ alt: false,
138
+ ctrl: false,
139
+ })?.handled,
140
+ true,
141
+ );
142
+ assert.match(host.render(100).join("\n"), /command output 0\b/);
143
+ });
@@ -1,14 +1,20 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { after, before, test } from "node:test";
3
+ import { mkdtemp, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
3
6
  import { initTheme } from "@earendil-works/pi-coding-agent";
4
7
  import { registerFusionCards } from "./fusion-card.ts";
5
- import type { ActionFusionProgress } from "./action-fusion.ts";
8
+ import { createActionFusionExecutor, type ActionFusionProgress } from "./action-fusion.ts";
9
+ import type { CommandResult } from "./report-schema.ts";
10
+ import { commandText } from "./mutation-result.ts";
11
+ import { decodeReport } from "./report.ts";
12
+ import { makeWriteOverride } from "./write-tool.ts";
13
+ import { callTool, createToolContext } from "./tool-call.testing.ts";
14
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
15
+ import { ProcessTerminal, TuiMainScreen } from "@earendil-works/pi-tui";
16
+ import { theme as activeTheme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
6
17
 
7
- const theme = {
8
- fg: (_color: string, text: string) => text,
9
- bg: (_color: string, text: string) => text,
10
- bold: (text: string) => text,
11
- };
12
18
  const themeKey = Symbol.for("@earendil-works/pi-coding-agent:theme");
13
19
  const originalTheme = Object.getOwnPropertyDescriptor(globalThis, themeKey);
14
20
  before(() => initTheme("dark"));
@@ -20,8 +26,12 @@ after(() => {
20
26
  function harness(entries: any[] = []) {
21
27
  const renderers = new Map<string, any>();
22
28
  const handlers = new Map<string, any>();
23
- const backgrounds: string[] = [];
29
+ const tui = new TuiMainScreen(new ProcessTerminal());
30
+ tui.requestRender = () => {};
24
31
  const report = registerFusionCards({
32
+ getSettings() {
33
+ return {};
34
+ },
25
35
  on(event: string, handler: any) {
26
36
  handlers.set(event, handler);
27
37
  },
@@ -33,30 +43,30 @@ function harness(entries: any[] = []) {
33
43
  },
34
44
  } as any);
35
45
  const restore = (event = "session_start", branch = entries, extra = {}) =>
36
- handlers.get(event)({}, { sessionManager: { getBranch: () => branch }, ...extra });
37
- const card = (entry: any, expanded = false) =>
38
- renderers.get(entry.customType)(
39
- entry,
40
- { expanded },
46
+ handlers.get(event)(
47
+ {},
41
48
  {
42
- ...theme,
43
- bg: (color: string, text: string) => {
44
- backgrounds.push(color);
45
- return text;
49
+ mode: "tui",
50
+ ui: {
51
+ setWidget(_key: string, content: Parameters<ExtensionContext["ui"]["setWidget"]>[1]) {
52
+ if (typeof content === "function") content(tui, activeTheme);
53
+ },
46
54
  },
55
+ sessionManager: { getBranch: () => branch },
56
+ ...extra,
47
57
  },
48
58
  );
49
- return { entries, report, restore, card, backgrounds };
59
+ const card = (entry: any, expanded = false) =>
60
+ renderers.get(entry.customType)(entry, { expanded }, activeTheme);
61
+ restore();
62
+ return { entries, report, restore, card };
50
63
  }
51
64
 
52
65
  const waiting: ActionFusionProgress = {
53
66
  toolCallId: "call-1",
54
- path: "file.ts",
55
67
  commandText: "npm test",
56
68
  command: "waiting",
57
- publication: "NOT_PUBLISHED",
58
69
  freshness: "unknown",
59
- output: "",
60
70
  mutationCompleted: false,
61
71
  };
62
72
 
@@ -65,12 +75,11 @@ test("one independent card updates live and only persists its endpoints", () =>
65
75
  h.report(waiting);
66
76
  const card = h.card(h.entries[0]);
67
77
  assert.match(card.render(100).join("\n"), /waiting/);
68
- assert.equal(h.backgrounds.at(-1), "toolPendingBg");
78
+ assert.ok(card.render(100).join("\n").includes(activeTheme.getBgAnsi("toolPendingBg")));
69
79
  h.report({
70
80
  ...waiting,
71
81
  command: "running",
72
- publication: "PUBLISHED",
73
- output: "first test passed",
82
+ result: { content: [{ type: "text", text: "first test passed" }] },
74
83
  });
75
84
  assert.match(card.render(100).join("\n"), /running[\s\S]*first test passed/);
76
85
  assert.equal(h.entries.length, 1);
@@ -78,37 +87,135 @@ test("one independent card updates live and only persists its endpoints", () =>
78
87
  h.report({
79
88
  ...waiting,
80
89
  command: "succeeded",
81
- publication: "PUBLISHED",
82
90
  freshness: "changed",
83
- output,
91
+ result: { content: [{ type: "text", text: output }] },
84
92
  });
85
93
  assert.equal(h.entries.length, 2);
86
94
  assert.equal(h.entries[0].data.command, "waiting");
87
95
  const collapsed = card.render(100).join("\n");
88
96
  assert.match(collapsed, /succeeded/);
89
- assert.doesNotMatch(collapsed, /publication=|freshness=|Anchors are stale|file\.ts/);
90
- assert.equal(h.backgrounds.at(-1), "toolSuccessBg");
97
+ assert.ok(collapsed.includes(activeTheme.getBgAnsi("toolSuccessBg")));
91
98
  assert.match(collapsed, /output line 19/);
92
99
  assert.doesNotMatch(collapsed, /output line 0\b/);
93
100
  assert.match(h.card(h.entries[0], true).render(100).join("\n"), /output line 0\b/);
94
101
  });
95
102
 
103
+ test("Fusion command outcomes → progress, cards, and reports preserve command results", async (t) => {
104
+ const success: CommandResult = {
105
+ content: [
106
+ { type: "text", text: "first" },
107
+ { type: "text", text: "second" },
108
+ ],
109
+ };
110
+ const failure: CommandResult = { content: [{ type: "text", text: "boom" }] };
111
+ const cases: readonly {
112
+ scenario:
113
+ | "succeeded"
114
+ | "failed"
115
+ | "cancelled-error"
116
+ | "cancelled-empty"
117
+ | "skipped"
118
+ | "cancelled";
119
+ command: ActionFusionProgress["command"];
120
+ result?: CommandResult;
121
+ text: RegExp;
122
+ }[] = [
123
+ { scenario: "succeeded", command: "succeeded", result: success, text: /first[\s\S]*second/ },
124
+ { scenario: "failed", command: "failed", result: failure, text: /boom/ },
125
+ { scenario: "cancelled-error", command: "cancelled", result: failure, text: /boom/ },
126
+ {
127
+ scenario: "cancelled-empty",
128
+ command: "cancelled",
129
+ result: { content: [] },
130
+ text: /Not run: cancelled\./,
131
+ },
132
+ { scenario: "skipped", command: "skipped", text: /Not run: the mutation did not complete/ },
133
+ { scenario: "cancelled", command: "cancelled", text: /Not run: cancelled\./ },
134
+ ];
135
+ for (const { scenario, command, result: expected, text } of cases) {
136
+ await t.test(scenario, async (t) => {
137
+ const dir = await mkdtemp(join(tmpdir(), "hashline-fusion-card-"));
138
+ t.after(() => rm(dir, { recursive: true, force: true }));
139
+ const h = harness();
140
+ const events: ActionFusionProgress[] = [];
141
+ const controller = new AbortController();
142
+ if (scenario === "cancelled") controller.abort();
143
+ let commands = 0;
144
+ const fusion = createActionFusionExecutor(
145
+ async () => {
146
+ commands++;
147
+ if (scenario === "cancelled-error") controller.abort();
148
+ if (scenario === "failed" || scenario === "cancelled-error") throw new Error("boom");
149
+ return scenario === "cancelled-empty"
150
+ ? { status: "cancelled", result: { content: [] } }
151
+ : { status: "succeeded", result: success };
152
+ },
153
+ (progress) => {
154
+ events.push(progress);
155
+ h.report(progress);
156
+ },
157
+ );
158
+ const result = await callTool(
159
+ makeWriteOverride(dir, fusion),
160
+ {
161
+ path: "file.txt",
162
+ mode: scenario === "skipped" ? "overwrite" : "create",
163
+ content: "saved\n",
164
+ then_run: { command: "check" },
165
+ },
166
+ { ctx: await createToolContext(dir, t), signal: controller.signal },
167
+ );
168
+ assert.equal(commands, expected ? 1 : 0);
169
+ const final = events.at(-1);
170
+ assert.ok(final);
171
+ assert.equal(final.command, command);
172
+ assert.equal(Object.hasOwn(final, "result"), expected !== undefined);
173
+ assert.deepEqual(final.result, expected);
174
+ for (const progress of events) {
175
+ if (progress.command === "waiting") assert.equal(Object.hasOwn(progress, "result"), false);
176
+ }
177
+ const saved = h.entries.find((entry) => entry.customType === "hashline-then-run-result");
178
+ assert.ok(saved);
179
+ assert.equal(Object.hasOwn(saved.data, "result"), expected !== undefined);
180
+ assert.deepEqual(saved.data.result, expected);
181
+ assert.equal(Object.hasOwn(h.entries[0].data, "result"), false);
182
+ const block = result.content.at(-1);
183
+ assert.ok(block?.type === "text");
184
+ const report = decodeReport(block.text, "write");
185
+ assert.ok(report);
186
+ const output = expected ? commandText(expected.content) : "";
187
+ assert.deepEqual(report.then_run, { status: command, ...(output ? { output } : {}) });
188
+ const rendered = h.card(h.entries[0], true).render(160).join("\n");
189
+ assert.match(rendered, text);
190
+ if (command === "cancelled") assert.equal(rendered.includes("Not run: cancelled."), !output);
191
+ });
192
+ }
193
+ });
194
+
96
195
  test("session restore uses final snapshots and marks unfinished calls unknown", () => {
97
196
  const h = harness();
98
197
  h.report(waiting);
99
198
  h.report({
100
199
  ...waiting,
101
200
  command: "failed",
102
- publication: "PUBLISHED",
103
- output: "Command exited with code 7",
201
+ result: {
202
+ content: [{ type: "text", text: "Command exited with code 7" }],
203
+ details: { fullOutputPath: "/tmp/command-output.log" },
204
+ },
104
205
  });
105
206
  const resumed = harness(h.entries);
106
207
  resumed.restore();
107
208
  assert.match(
108
209
  resumed.card(h.entries[0]).render(100).join("\n"),
109
- /failed[\s\S]*Command exited with code 7/,
210
+ /failed[\s\S]*Command exited with code 7[\s\S]*command-output\.log/,
211
+ );
212
+ assert.ok(
213
+ resumed
214
+ .card(h.entries[0])
215
+ .render(100)
216
+ .join("\n")
217
+ .includes(activeTheme.getBgAnsi("toolErrorBg")),
110
218
  );
111
- assert.equal(resumed.backgrounds.at(-1), "toolErrorBg");
112
219
  resumed.restore("session_tree", [h.entries[0]]);
113
220
  assert.match(
114
221
  resumed.card(h.entries[0]).render(100).join("\n"),
@@ -116,6 +223,52 @@ test("session restore uses final snapshots and marks unfinished calls unknown",
116
223
  );
117
224
  });
118
225
 
226
+ test("session restore accepts optional command results", async (t) => {
227
+ const cases: readonly {
228
+ name: string;
229
+ fields: { result?: CommandResult };
230
+ command: ActionFusionProgress["command"];
231
+ text: RegExp;
232
+ }[] = [
233
+ {
234
+ name: "result is present → restore result text",
235
+ fields: { result: { content: [{ type: "text", text: "result text" }] } },
236
+ command: "succeeded",
237
+ text: /result text/,
238
+ },
239
+ {
240
+ name: "result is absent → restore the command status",
241
+ fields: {},
242
+ command: "cancelled",
243
+ text: /Not run: cancelled\./,
244
+ },
245
+ ];
246
+ for (const { name, fields, command, text } of cases) {
247
+ await t.test(name, () => {
248
+ for (const event of ["session_start", "session_tree"]) {
249
+ const original = harness();
250
+ original.report(waiting);
251
+ const initial = original.entries[0];
252
+ const snapshot = {
253
+ ...initial,
254
+ data: {
255
+ toolCallId: waiting.toolCallId,
256
+ commandText: waiting.commandText,
257
+ command,
258
+ mutationCompleted: true,
259
+ freshness: "unchanged",
260
+ ...fields,
261
+ },
262
+ };
263
+ const resumed = harness();
264
+ resumed.restore(event, [initial, { ...snapshot, customType: "hashline-then-run-result" }]);
265
+ const shown = resumed.card(initial, true).render(160).join("\n");
266
+ assert.match(shown, text, event);
267
+ }
268
+ });
269
+ }
270
+ });
271
+
119
272
  test("skips and cancellations stay neutral and restore their own reason", () => {
120
273
  for (const command of ["skipped", "cancelled"] as const) {
121
274
  const h = harness();
@@ -129,10 +282,10 @@ test("skips and cancellations stay neutral and restore their own reason", () =>
129
282
  output,
130
283
  command === "skipped" ? /Not run: the mutation did not complete/ : /Not run: cancelled/,
131
284
  );
132
- assert.doesNotMatch(output, /publication=|freshness=|\(no output\)/);
133
- assert.ok(!view.backgrounds.includes("toolErrorBg"));
134
- assert.ok(!view.backgrounds.includes("toolSuccessBg"));
135
- assert.equal(view.backgrounds.at(-1), "customMessageBg");
285
+ assert.doesNotMatch(output, /\(no output\)/);
286
+ assert.ok(!output.includes(activeTheme.getBgAnsi("toolErrorBg")));
287
+ assert.ok(!output.includes(activeTheme.getBgAnsi("toolSuccessBg")));
288
+ assert.ok(output.includes(activeTheme.getBgAnsi("customMessageBg")));
136
289
  }
137
290
  }
138
291
  });
@@ -145,7 +298,6 @@ test("timed command cards show remaining seconds only while actively running", (
145
298
  const running: ActionFusionProgress = {
146
299
  ...waiting,
147
300
  command: "running",
148
- publication: "PUBLISHED",
149
301
  mutationCompleted: true,
150
302
  timing: { timeoutSeconds: 10, remainingSeconds: 10 },
151
303
  };
@@ -156,7 +308,11 @@ test("timed command cards show remaining seconds only while actively running", (
156
308
  assert.equal(h.entries.length, 1);
157
309
  h.report({ ...running, timing: { timeoutSeconds: 10, remainingSeconds: 0 } });
158
310
  assert.match(card.render(160).join("\n"), /0s remaining/);
159
- h.report({ ...running, command: "timeout", output: "Command timed out after 10 seconds" });
311
+ h.report({
312
+ ...running,
313
+ command: "timeout",
314
+ result: { content: [{ type: "text", text: "Command timed out after 10 seconds" }] },
315
+ });
160
316
  assert.doesNotMatch(card.render(160).join("\n"), /remaining/);
161
317
  const restored = harness(h.entries);
162
318
  restored.restore();