@criogaid/pi-hashline-edit 0.6.1 → 0.8.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 (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -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
+ }
@@ -11,7 +11,7 @@ test("snapshot cancelled while opening → rejects as an unpublished cancellatio
11
11
  const path = join(directory, "file.txt");
12
12
  await writeFile(path, "before\n");
13
13
  const controller = new AbortController();
14
- const reading = readEditableSnapshot(path, "file.txt", controller.signal);
14
+ const reading = readEditableSnapshot(path, controller.signal);
15
15
  controller.abort();
16
16
  await assert.rejects(
17
17
  reading,
@@ -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,33 +1,37 @@
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
- const themeKeys = [
13
- Symbol.for("@earendil-works/pi-coding-agent:theme"),
14
- Symbol.for("@mariozechner/pi-coding-agent:theme"),
15
- ];
16
- const originalThemes = themeKeys.map((key) => Object.getOwnPropertyDescriptor(globalThis, key));
18
+ const themeKey = Symbol.for("@earendil-works/pi-coding-agent:theme");
19
+ const originalTheme = Object.getOwnPropertyDescriptor(globalThis, themeKey);
17
20
  before(() => initTheme("dark"));
18
- after(() =>
19
- themeKeys.forEach((key, index) => {
20
- const original = originalThemes[index];
21
- if (original) Object.defineProperty(globalThis, key, original);
22
- else Reflect.deleteProperty(globalThis, key);
23
- }),
24
- );
21
+ after(() => {
22
+ if (originalTheme) Object.defineProperty(globalThis, themeKey, originalTheme);
23
+ else Reflect.deleteProperty(globalThis, themeKey);
24
+ });
25
25
 
26
26
  function harness(entries: any[] = []) {
27
27
  const renderers = new Map<string, any>();
28
28
  const handlers = new Map<string, any>();
29
- const backgrounds: string[] = [];
29
+ const tui = new TuiMainScreen(new ProcessTerminal());
30
+ tui.requestRender = () => {};
30
31
  const report = registerFusionCards({
32
+ getSettings() {
33
+ return {};
34
+ },
31
35
  on(event: string, handler: any) {
32
36
  handlers.set(event, handler);
33
37
  },
@@ -39,30 +43,30 @@ function harness(entries: any[] = []) {
39
43
  },
40
44
  } as any);
41
45
  const restore = (event = "session_start", branch = entries, extra = {}) =>
42
- handlers.get(event)({}, { sessionManager: { getBranch: () => branch }, ...extra });
43
- const card = (entry: any, expanded = false) =>
44
- renderers.get(entry.customType)(
45
- entry,
46
- { expanded },
46
+ handlers.get(event)(
47
+ {},
47
48
  {
48
- ...theme,
49
- bg: (color: string, text: string) => {
50
- backgrounds.push(color);
51
- 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
+ },
52
54
  },
55
+ sessionManager: { getBranch: () => branch },
56
+ ...extra,
53
57
  },
54
58
  );
55
- 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 };
56
63
  }
57
64
 
58
65
  const waiting: ActionFusionProgress = {
59
66
  toolCallId: "call-1",
60
- path: "file.ts",
61
67
  commandText: "npm test",
62
68
  command: "waiting",
63
- publication: "NOT_PUBLISHED",
64
69
  freshness: "unknown",
65
- output: "",
66
70
  mutationCompleted: false,
67
71
  };
68
72
 
@@ -71,12 +75,11 @@ test("one independent card updates live and only persists its endpoints", () =>
71
75
  h.report(waiting);
72
76
  const card = h.card(h.entries[0]);
73
77
  assert.match(card.render(100).join("\n"), /waiting/);
74
- assert.equal(h.backgrounds.at(-1), "toolPendingBg");
78
+ assert.ok(card.render(100).join("\n").includes(activeTheme.getBgAnsi("toolPendingBg")));
75
79
  h.report({
76
80
  ...waiting,
77
81
  command: "running",
78
- publication: "PUBLISHED",
79
- output: "first test passed",
82
+ result: { content: [{ type: "text", text: "first test passed" }] },
80
83
  });
81
84
  assert.match(card.render(100).join("\n"), /running[\s\S]*first test passed/);
82
85
  assert.equal(h.entries.length, 1);
@@ -84,37 +87,135 @@ test("one independent card updates live and only persists its endpoints", () =>
84
87
  h.report({
85
88
  ...waiting,
86
89
  command: "succeeded",
87
- publication: "PUBLISHED",
88
90
  freshness: "changed",
89
- output,
91
+ result: { content: [{ type: "text", text: output }] },
90
92
  });
91
93
  assert.equal(h.entries.length, 2);
92
94
  assert.equal(h.entries[0].data.command, "waiting");
93
95
  const collapsed = card.render(100).join("\n");
94
96
  assert.match(collapsed, /succeeded/);
95
- assert.doesNotMatch(collapsed, /publication=|freshness=|Anchors are stale|file\.ts/);
96
- assert.equal(h.backgrounds.at(-1), "toolSuccessBg");
97
+ assert.ok(collapsed.includes(activeTheme.getBgAnsi("toolSuccessBg")));
97
98
  assert.match(collapsed, /output line 19/);
98
99
  assert.doesNotMatch(collapsed, /output line 0\b/);
99
100
  assert.match(h.card(h.entries[0], true).render(100).join("\n"), /output line 0\b/);
100
101
  });
101
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
+
102
195
  test("session restore uses final snapshots and marks unfinished calls unknown", () => {
103
196
  const h = harness();
104
197
  h.report(waiting);
105
198
  h.report({
106
199
  ...waiting,
107
200
  command: "failed",
108
- publication: "PUBLISHED",
109
- 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
+ },
110
205
  });
111
206
  const resumed = harness(h.entries);
112
207
  resumed.restore();
113
208
  assert.match(
114
209
  resumed.card(h.entries[0]).render(100).join("\n"),
115
- /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")),
116
218
  );
117
- assert.equal(resumed.backgrounds.at(-1), "toolErrorBg");
118
219
  resumed.restore("session_tree", [h.entries[0]]);
119
220
  assert.match(
120
221
  resumed.card(h.entries[0]).render(100).join("\n"),
@@ -122,20 +223,69 @@ test("session restore uses final snapshots and marks unfinished calls unknown",
122
223
  );
123
224
  });
124
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
+
125
272
  test("skips and cancellations stay neutral and restore their own reason", () => {
126
273
  for (const command of ["skipped", "cancelled"] as const) {
127
274
  const h = harness();
128
275
  h.report(waiting);
129
- h.report({ ...waiting, command, reason: "Not run because the mutation did not complete." });
276
+ h.report({ ...waiting, command, mutationCompleted: false });
130
277
  for (const restored of [false, true]) {
131
278
  const view = restored ? harness(h.entries) : h;
132
279
  if (restored) view.restore();
133
280
  const output = view.card(h.entries[0], true).render(160).join("\n");
134
- assert.match(output, /Not run because the mutation did not complete/);
135
- assert.doesNotMatch(output, /publication=|freshness=|\(no output\)/);
136
- assert.ok(!view.backgrounds.includes("toolErrorBg"));
137
- assert.ok(!view.backgrounds.includes("toolSuccessBg"));
138
- assert.equal(view.backgrounds.at(-1), "customMessageBg");
281
+ assert.match(
282
+ output,
283
+ command === "skipped" ? /Not run: the mutation did not complete/ : /Not run: cancelled/,
284
+ );
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")));
139
289
  }
140
290
  }
141
291
  });
@@ -148,7 +298,6 @@ test("timed command cards show remaining seconds only while actively running", (
148
298
  const running: ActionFusionProgress = {
149
299
  ...waiting,
150
300
  command: "running",
151
- publication: "PUBLISHED",
152
301
  mutationCompleted: true,
153
302
  timing: { timeoutSeconds: 10, remainingSeconds: 10 },
154
303
  };
@@ -159,9 +308,42 @@ test("timed command cards show remaining seconds only while actively running", (
159
308
  assert.equal(h.entries.length, 1);
160
309
  h.report({ ...running, timing: { timeoutSeconds: 10, remainingSeconds: 0 } });
161
310
  assert.match(card.render(160).join("\n"), /0s remaining/);
162
- 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
+ });
163
316
  assert.doesNotMatch(card.render(160).join("\n"), /remaining/);
164
317
  const restored = harness(h.entries);
165
318
  restored.restore();
166
319
  assert.doesNotMatch(restored.card(h.entries[0]).render(160).join("\n"), /remaining/);
167
320
  });
321
+
322
+ test("invalid persisted command snapshots → do not replace valid progress or become executable cards", () => {
323
+ const original = harness();
324
+ original.report(waiting);
325
+ const initial = original.entries[0];
326
+ for (const invalid of [
327
+ ...["mutationCompleted", "freshness"].map((missing) =>
328
+ Object.fromEntries(
329
+ Object.entries({ ...initial.data, command: "succeeded" }).filter(
330
+ ([key]) => key !== missing,
331
+ ),
332
+ ),
333
+ ),
334
+ { ...initial.data, command: "not-a-command-status" },
335
+ { ...initial.data, freshness: "fresh" },
336
+ { ...initial.data, mutationCompleted: "yes" },
337
+ { ...initial.data, timing: { timeoutSeconds: -1, remainingSeconds: 2 } },
338
+ { ...initial.data, timing: { timeoutSeconds: 3, remainingSeconds: "2" } },
339
+ { ...initial.data, foreign: true },
340
+ ]) {
341
+ const malformed = { ...initial, data: invalid };
342
+ const resumed = harness([initial, { ...malformed, customType: "hashline-then-run-result" }]);
343
+ resumed.restore();
344
+ assert.equal(resumed.card(malformed), undefined);
345
+ const shown = resumed.card(initial).render(160).join("\n");
346
+ assert.match(shown, /interrupted \(final status unknown\)/);
347
+ assert.doesNotMatch(shown, /not-a-command-status|remaining/);
348
+ }
349
+ });