@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
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Action Fusion presentation: the mutation card shell that keeps the file
3
- * result's status independent of the fused command, and the separate
4
- * transcript card for each then_run command.
2
+ * Action Fusion presentation: the mutation card follows file mutation completion;
3
+ * a separate transcript card follows each then_run command's output and outcome.
5
4
  *
6
5
  * @module pi-hashline-edit/pi
7
6
  */
@@ -11,36 +10,79 @@ import type {
11
10
  ExtensionContext,
12
11
  ToolDefinition,
13
12
  } from "@earendil-works/pi-coding-agent";
14
- import { createBashToolDefinition } from "@earendil-works/pi-coding-agent";
15
- import { Box, Container, Text, type Component } from "@earendil-works/pi-tui";
13
+ import {
14
+ createBashToolDefinition,
15
+ SettingsManager,
16
+ ToolExecutionComponent,
17
+ } from "@earendil-works/pi-coding-agent";
18
+ import {
19
+ Box,
20
+ Container,
21
+ Text,
22
+ type Component,
23
+ type TUI,
24
+ type TuiMouseEvent,
25
+ } from "@earendil-works/pi-tui";
16
26
  import type { TSchema } from "typebox";
27
+ import { Value } from "typebox/value";
28
+ import { ACTION_FUSION_PROGRESS_SCHEMA } from "./report-schema.ts";
17
29
  import type { ActionFusionProgress } from "./action-fusion.ts";
18
- import { renderToolError, type MutationRenderState } from "./render.ts";
30
+ import { commandText } from "./mutation-result.ts";
31
+ import type { MutationRenderState } from "./render.ts";
19
32
 
20
33
  const CARD_TYPE = "hashline-then-run";
21
34
  const RESULT_TYPE = "hashline-then-run-result";
22
35
 
23
- type CommandCardData = Pick<
24
- ActionFusionProgress,
25
- "toolCallId" | "commandText" | "command" | "output" | "reason" | "timing"
26
- >;
27
-
28
- function commandCardData({
29
- toolCallId,
30
- commandText,
31
- command,
32
- output,
33
- reason,
34
- timing,
35
- }: ActionFusionProgress): CommandCardData {
36
- return {
37
- toolCallId,
38
- commandText,
39
- command,
40
- output,
41
- ...(reason ? { reason } : {}),
42
- ...(timing ? { timing } : {}),
43
- };
36
+ /** A command card persists its progress as is; restored entries are checked against the same schema. */
37
+ const COMMAND_CARD_SCHEMA = ACTION_FUSION_PROGRESS_SCHEMA;
38
+ type CommandCardData = ActionFusionProgress;
39
+
40
+ const TARGET_STATE = {
41
+ changed: "the target changed after the mutation",
42
+ missing: "the target is missing after the mutation",
43
+ unknown: "the target revision could not be read",
44
+ } as const;
45
+
46
+ /**
47
+ * Why a command never started, derived from the same facts the mutation result
48
+ * states: whether the mutation completed and the target's freshness.
49
+ */
50
+ function notRunReason(card: CommandCardData): string | undefined {
51
+ if (card.command === "cancelled" && !(card.result && commandText(card.result.content)))
52
+ return "Not run: cancelled.";
53
+ if (card.command !== "skipped") return undefined;
54
+ const { mutationCompleted, freshness } = card;
55
+ if (!mutationCompleted) return "Not run: the mutation did not complete.";
56
+ return freshness === "unchanged" ? undefined : `Not run: ${TARGET_STATE[freshness]}.`;
57
+ }
58
+
59
+ /** Adapt Pi's tool row spacing to the spacer already owned by a custom entry. */
60
+ class CommandEntryComponent extends ToolExecutionComponent {
61
+ private globalExpanded?: boolean;
62
+ private readonly refresh: () => void;
63
+
64
+ constructor(
65
+ refresh: (card: ToolExecutionComponent) => void,
66
+ ...args: ConstructorParameters<typeof ToolExecutionComponent>
67
+ ) {
68
+ super(...args);
69
+ this.refresh = () => refresh(this);
70
+ }
71
+
72
+ setGlobalExpanded(expanded: boolean) {
73
+ if (this.globalExpanded === expanded) return;
74
+ this.globalExpanded = expanded;
75
+ this.setExpanded(expanded);
76
+ }
77
+
78
+ override render(width: number) {
79
+ this.refresh();
80
+ return super.render(width).slice(1);
81
+ }
82
+
83
+ override handleMouse(event: TuiMouseEvent) {
84
+ return super.handleMouse({ ...event, y: event.y + 1, height: event.height + 1 });
85
+ }
44
86
  }
45
87
 
46
88
  /** Render one durable transcript card per fused command without adding model context. */
@@ -49,136 +91,205 @@ export function registerFusionCards(pi: ExtensionAPI) {
49
91
  const bash = createBashToolDefinition(process.cwd());
50
92
  const states = new Map<string, CommandCardData>();
51
93
  const active = new Set<string>();
94
+ const cards = new Map<string, CommandEntryComponent>();
95
+ let tui: TUI | undefined;
52
96
 
53
97
  const restore = (ctx: ExtensionContext) => {
54
98
  if (ctx.cwd) currentCwd = ctx.cwd;
55
99
  states.clear();
56
100
  active.clear();
101
+ cards.clear();
57
102
  for (const entry of ctx.sessionManager.getBranch()) {
58
103
  if (
59
104
  entry.type !== "custom" ||
60
105
  (entry.customType !== CARD_TYPE && entry.customType !== RESULT_TYPE)
61
106
  )
62
107
  continue;
63
- const data = entry.data as ActionFusionProgress | undefined;
64
- if (
65
- data &&
66
- typeof data.toolCallId === "string" &&
67
- typeof data.commandText === "string" &&
68
- typeof data.output === "string"
69
- ) {
70
- states.set(data.toolCallId, commandCardData(data));
71
- }
108
+ const data = entry.data;
109
+ if (Value.Check(COMMAND_CARD_SCHEMA, data)) states.set(data.toolCallId, data);
72
110
  }
73
111
  };
74
- pi.on("session_start", (_event, ctx) => restore(ctx));
112
+ pi.on("session_start", (_event, ctx) => {
113
+ restore(ctx);
114
+ tui = undefined;
115
+ if (ctx.mode !== "tui") return;
116
+ // The public widget factory supplies the session TUI without changing its header or editor.
117
+ const bridge = "hashline-then-run-ui";
118
+ ctx.ui.setWidget(
119
+ bridge,
120
+ (sessionTui) => {
121
+ tui = sessionTui;
122
+ return new Container();
123
+ },
124
+ { placement: "belowEditor" },
125
+ );
126
+ ctx.ui.setWidget(bridge, undefined);
127
+ });
75
128
  pi.on("session_tree", (_event, ctx) => restore(ctx));
76
129
 
77
- pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, (entry, { expanded }, theme) => {
130
+ pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, function renderCard(entry, { expanded }):
131
+ | Component
132
+ | undefined {
78
133
  const initial = entry.data;
79
- if (!initial) return undefined;
80
- const statusText = new Text("", 0, 0);
81
- const box = new Box(1, 1);
82
- let call: Component | undefined;
83
- let result: Component | undefined;
84
- const rendererState = { startedAt: undefined, endedAt: undefined, interval: undefined };
85
- return {
86
- invalidate: () => box.invalidate(),
87
- render(width) {
88
- // Read live state during rendering; native tool updates schedule the repaint.
89
- const current = states.get(initial.toolCallId) ?? initial;
90
- const pending = current.command === "waiting" || current.command === "running";
91
- const interrupted = pending && !active.has(current.toolCallId);
92
- const status = interrupted ? "interrupted (final status unknown)" : current.command;
93
- const countdown =
94
- current.command === "running" && !interrupted && current.timing
95
- ? ` · ${current.timing.remainingSeconds}s remaining`
96
- : "";
97
- const failed = current.command === "failed" || current.command === "timeout";
98
- const color =
99
- pending || current.command === "cancelled"
100
- ? "warning"
101
- : failed
102
- ? "error"
103
- : current.command === "succeeded"
104
- ? "success"
105
- : "dim";
106
- const background =
107
- pending && !interrupted
108
- ? "toolPendingBg"
109
- : failed
110
- ? "toolErrorBg"
111
- : current.command === "succeeded"
112
- ? "toolSuccessBg"
113
- : "customMessageBg";
114
- box.setBgFn((line) => theme.bg(background, line));
115
- statusText.setText(
116
- `${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status + countdown)}`,
117
- );
118
- const context = {
119
- args: {
120
- command: current.commandText,
121
- ...(current.timing ? { timeout: current.timing.timeoutSeconds } : {}),
122
- },
123
- toolCallId: current.toolCallId,
124
- cwd: currentCwd,
125
- state: rendererState,
126
- invalidate: () => box.invalidate(),
127
- // Parent tool updates drive entry rendering; leave the native elapsed-time timer off.
128
- executionStarted: false,
129
- argsComplete: true,
130
- isPartial: pending && !interrupted,
131
- expanded,
132
- showImages: false,
133
- isError: failed,
134
- };
135
- call = bash.renderCall!(context.args, theme, { ...context, lastComponent: call });
136
- box.clear();
137
- box.addChild(statusText);
138
- box.addChild(call);
139
- if (current.reason) box.addChild(new Text(theme.fg("dim", current.reason), 0, 0));
140
- if (current.output || current.command === "succeeded" || failed) {
141
- result = bash.renderResult!(
142
- { content: [{ type: "text", text: current.output }], details: undefined },
143
- { expanded, isPartial: context.isPartial },
144
- theme,
145
- { ...context, lastComponent: result },
134
+ if (!Value.Check(COMMAND_CARD_SCHEMA, initial)) return undefined;
135
+ if (!tui) {
136
+ // Pi may rebuild history before session_start supplies its UI context.
137
+ let component: Component | undefined;
138
+ const ready = () => (component ??= tui ? renderCard(entry, { expanded }) : undefined);
139
+ return {
140
+ render: (width) => ready()?.render(width) ?? [],
141
+ invalidate: () => component?.invalidate(),
142
+ handleMouse: (event) => ready()?.handleMouse?.(event),
143
+ };
144
+ }
145
+ let card = cards.get(initial.toolCallId);
146
+ const settings = SettingsManager.inMemory(pi.getSettings());
147
+ if (!card) {
148
+ const current = () => states.get(initial.toolCallId) ?? initial;
149
+ const statusText = new Text("", 0, 0);
150
+ let outputPadding = settings.getOutputPad();
151
+ let box = new Box(outputPadding, 1);
152
+ let call: Component | undefined;
153
+ let result: Component | undefined;
154
+ const renderers: Pick<typeof bash, "renderShell" | "renderCall" | "renderResult"> = {
155
+ renderShell: "self",
156
+ renderCall(args, theme, context) {
157
+ const padding = SettingsManager.inMemory(pi.getSettings()).getOutputPad();
158
+ if (padding !== outputPadding) {
159
+ outputPadding = padding;
160
+ box = new Box(outputPadding, 1);
161
+ }
162
+ const value = current();
163
+ const pending = value.command === "waiting" || value.command === "running";
164
+ const interrupted = pending && !active.has(value.toolCallId);
165
+ const status = interrupted ? "interrupted (final status unknown)" : value.command;
166
+ const countdown =
167
+ value.command === "running" && !interrupted && value.timing
168
+ ? ` · ${value.timing.remainingSeconds}s remaining`
169
+ : "";
170
+ const failed = value.command === "failed" || value.command === "timeout";
171
+ const color =
172
+ pending || value.command === "cancelled"
173
+ ? "warning"
174
+ : failed
175
+ ? "error"
176
+ : value.command === "succeeded"
177
+ ? "success"
178
+ : "dim";
179
+ const background =
180
+ pending && !interrupted
181
+ ? "toolPendingBg"
182
+ : failed
183
+ ? "toolErrorBg"
184
+ : value.command === "succeeded"
185
+ ? "toolSuccessBg"
186
+ : "customMessageBg";
187
+ box.setBgFn((line) => theme.bg(background, line));
188
+ statusText.setText(
189
+ `${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status + countdown)}`,
146
190
  );
147
- box.addChild(result);
148
- }
149
- return box.render(width);
150
- },
151
- };
191
+ call = bash.renderCall!(args, theme, { ...context, lastComponent: call });
192
+ box.clear();
193
+ box.addChild(statusText);
194
+ box.addChild(call);
195
+ const reason = notRunReason(value);
196
+ if (reason) box.addChild(new Text(theme.fg("dim", reason), 0, 0));
197
+ return box;
198
+ },
199
+ renderResult(value, options, theme, context) {
200
+ // Every command that ran or failed to start has a result; waiting and skipped ones do not.
201
+ if (current().result) {
202
+ result = bash.renderResult!(value, options, theme, {
203
+ ...context,
204
+ lastComponent: result,
205
+ });
206
+ box.addChild(result);
207
+ }
208
+ return new Container();
209
+ },
210
+ };
211
+ let rendered: CommandCardData | undefined;
212
+ card = new CommandEntryComponent(
213
+ (native) => {
214
+ const value = current();
215
+ if (rendered === value) return;
216
+ rendered = value;
217
+ native.updateArgs({
218
+ command: value.commandText,
219
+ ...(value.timing ? { timeout: value.timing.timeoutSeconds } : {}),
220
+ });
221
+ native.updateResult(
222
+ {
223
+ ...(value.result ?? { content: [] }),
224
+ isError: value.command === "failed" || value.command === "timeout",
225
+ },
226
+ (value.command === "waiting" || value.command === "running") &&
227
+ active.has(value.toolCallId),
228
+ );
229
+ },
230
+ "bash",
231
+ initial.toolCallId,
232
+ { command: initial.commandText },
233
+ {
234
+ showImages: settings.getShowImages(),
235
+ imageWidthCells: settings.getImageWidthCells(),
236
+ },
237
+ renderers,
238
+ tui,
239
+ currentCwd,
240
+ );
241
+ card.setArgsComplete();
242
+ cards.set(initial.toolCallId, card);
243
+ }
244
+ card.setShowImages(settings.getShowImages());
245
+ card.setImageWidthCells(settings.getImageWidthCells());
246
+ card.setGlobalExpanded(expanded);
247
+ return card;
152
248
  });
153
249
 
154
250
  return (progress: ActionFusionProgress, ctx?: ExtensionContext) => {
155
251
  if (ctx?.cwd) currentCwd = ctx.cwd;
156
252
  const first = !states.has(progress.toolCallId);
157
- const data = commandCardData(progress);
158
- states.set(progress.toolCallId, data);
253
+ states.set(progress.toolCallId, progress);
159
254
  const pending = progress.command === "waiting" || progress.command === "running";
160
255
  if (pending) active.add(progress.toolCallId);
161
256
  else active.delete(progress.toolCallId);
162
257
  // Only endpoints are persisted; streaming snapshots reuse Bash's bounded output.
163
- if (first) pi.appendEntry(CARD_TYPE, data);
164
- if (!pending) pi.appendEntry(RESULT_TYPE, data);
258
+ if (first) pi.appendEntry(CARD_TYPE, progress);
259
+ if (!pending) pi.appendEntry(RESULT_TYPE, progress);
165
260
  };
166
261
  }
167
262
 
263
+ type MutationCardProgress = Partial<Pick<ActionFusionProgress, "mutationCompleted">>;
264
+
265
+ function mutationPending(isPartial: boolean, progress?: MutationCardProgress): boolean {
266
+ return isPartial && progress?.mutationCompleted !== true;
267
+ }
268
+
168
269
  /** Mutation render state plus the shell that keeps the card status independent of then_run. */
169
270
  interface FusedMutationRenderState extends MutationRenderState {
170
271
  mutationShell?: {
171
272
  box: Box;
172
273
  call?: Component;
173
274
  result?: Component;
174
- fileState?: { freshness?: string };
275
+ fileState?: MutationCardProgress;
175
276
  };
176
277
  }
177
278
 
178
- /** Keep the mutation card's background independent of the fused command's lifetime. */
179
- export function withMutationStatus<TParams extends TSchema, TDetails>(
180
- tool: ToolDefinition<TParams, TDetails, FusedMutationRenderState>,
181
- ): ToolDefinition<TParams, TDetails, FusedMutationRenderState> {
279
+ type MutationCardTool<TParams extends TSchema, TDetails, TRenderDetails> = Omit<
280
+ ToolDefinition<TParams, TDetails, FusedMutationRenderState>,
281
+ "renderResult"
282
+ > &
283
+ Pick<ToolDefinition<TParams, TRenderDetails, FusedMutationRenderState>, "renderResult">;
284
+
285
+ /** Finish the mutation card independently while the fused command remains active. */
286
+ export function withMutationStatus<
287
+ TParams extends TSchema,
288
+ TDetails extends TRenderDetails,
289
+ TRenderDetails,
290
+ >(
291
+ tool: MutationCardTool<TParams, TDetails, TRenderDetails>,
292
+ ): MutationCardTool<TParams, TDetails, TRenderDetails> {
182
293
  return {
183
294
  ...tool,
184
295
  renderShell: "self",
@@ -189,7 +300,11 @@ export function withMutationStatus<TParams extends TSchema, TDetails>(
189
300
  shell.box.addChild(shell.call);
190
301
  shell.box.setBgFn((line: string) =>
191
302
  theme.bg(
192
- context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
303
+ mutationPending(context.isPartial, shell.fileState)
304
+ ? "toolPendingBg"
305
+ : context.isError
306
+ ? "toolErrorBg"
307
+ : "toolSuccessBg",
193
308
  line,
194
309
  ),
195
310
  );
@@ -197,30 +312,19 @@ export function withMutationStatus<TParams extends TSchema, TDetails>(
197
312
  },
198
313
  renderResult(result, options, theme, context) {
199
314
  const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
200
- const details = result.details as
201
- | { actionFusion?: { mutationCompleted?: boolean; freshness?: string } }
202
- | undefined;
203
- const isPartial = options.isPartial && details?.actionFusion?.mutationCompleted !== true;
204
- // Pi serializes fused failures into one diagnostic; retain it when the card expands.
205
- const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
206
- shell.result = fusedError
207
- ? renderToolError(result, theme, options.expanded)
208
- : tool.renderResult!(result, { ...options, isPartial }, theme, {
209
- ...context,
210
- isPartial,
211
- lastComponent: shell.result,
212
- });
315
+ // Fusion updates carry progress alongside TDetails; final results carry only the outcome.
316
+ const details = result.details as { actionFusion?: MutationCardProgress } | undefined;
317
+ const file = details?.actionFusion ?? shell.fileState;
318
+ const isPartial = mutationPending(options.isPartial, file);
319
+ // The tool's renderer shows failures and the report's freshness facts.
320
+ shell.result = tool.renderResult!(result, { ...options, isPartial }, theme, {
321
+ ...context,
322
+ isPartial,
323
+ lastComponent: shell.result,
324
+ });
213
325
  // Pi runs renderCall first; update its box in place without invalidating the tool row.
214
326
  shell.box.addChild(shell.result);
215
- const file = details?.actionFusion ?? shell.fileState;
216
- if (file) {
217
- shell.fileState = { freshness: file.freshness };
218
- if (file.freshness === "changed" || file.freshness === "missing") {
219
- shell.box.addChild(
220
- new Text(theme.fg("warning", `Anchors are stale: target ${file.freshness}.`), 0, 0),
221
- );
222
- }
223
- }
327
+ if (file) shell.fileState = { mutationCompleted: file.mutationCompleted };
224
328
  shell.box.setBgFn((line: string) =>
225
329
  theme.bg(
226
330
  isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
@@ -0,0 +1,127 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { candidateArgs, runCandidatePaths, MAX_PREFILTER_PATH_BYTES } from "./grep-candidates.ts";
4
+ import { COMMON_RG_ARGS, type GrepBackend } from "./rg-process.ts";
5
+ import type { Prefilter } from "../core/search-analysis.ts";
6
+
7
+ test("candidate literals → rg lists files with escaped byte-preserving alternatives", () => {
8
+ assert.deepEqual(candidateArgs({ kind: "all" }), [...COMMON_RG_ARGS, "--files"]);
9
+ for (const [literals, pattern] of [
10
+ [
11
+ [
12
+ [["a"], ["."], ["b"]],
13
+ [["-"], ["é"]],
14
+ ],
15
+ "a\\x{2e}b|\\x{2d}\\x{e9}",
16
+ ],
17
+ [[[["K", "k", "K"], ["_"], ["9"]]], "[Kk\\x{212a}]_9"],
18
+ ] as const) {
19
+ assert.deepEqual(candidateArgs({ kind: "literals", literals }), [
20
+ ...COMMON_RG_ARGS,
21
+ "--files-with-matches",
22
+ "--engine=default",
23
+ "--case-sensitive",
24
+ "--encoding=none",
25
+ "-e",
26
+ pattern,
27
+ ]);
28
+ }
29
+ });
30
+
31
+ const conjunction: Prefilter = {
32
+ kind: "and",
33
+ filters: [
34
+ { kind: "literals", literals: [[["a"]]] },
35
+ { kind: "literals", literals: [[["b"]]] },
36
+ ],
37
+ };
38
+
39
+ test("AND file passes → intersect paths before emitting and preserve final callback stop", async () => {
40
+ let pass = 0;
41
+ const calls: string[][] = [];
42
+ const run: GrepBackend["runRgPaths"] = async (_rg, args, _signal, onPath) => {
43
+ calls.push([...args]);
44
+ for (const path of [
45
+ ["a-only", "both"],
46
+ ["b-only", "both", "later"],
47
+ ][pass++])
48
+ if (!(await onPath(path))) return { code: null, stderr: "", stopped: true };
49
+ return { code: 0, stderr: "", stopped: false };
50
+ };
51
+ const paths: string[] = [];
52
+ const result = await runCandidatePaths(
53
+ run,
54
+ "rg",
55
+ conjunction,
56
+ ["--", "root"],
57
+ undefined,
58
+ (path) => {
59
+ paths.push(path);
60
+ return false;
61
+ },
62
+ );
63
+ assert.deepEqual(paths, ["both"]);
64
+ assert.equal(result.stopped, true);
65
+ assert.equal(calls.length, 2);
66
+ for (const args of calls) assert.deepEqual(args.slice(-2), ["--", "root"]);
67
+ });
68
+
69
+ test("AND path retention fills → rerun one necessary clause without excluding its candidates", async () => {
70
+ let pass = 0;
71
+ const run: GrepBackend["runRgPaths"] = async (_rg, _args, _signal, onPath) => {
72
+ const keepGoing = await onPath(
73
+ pass++ === 0 ? "x".repeat(MAX_PREFILTER_PATH_BYTES + 1) : "candidate",
74
+ );
75
+ return { code: keepGoing ? 0 : null, stderr: "", stopped: !keepGoing };
76
+ };
77
+ const paths: string[] = [];
78
+ const result = await runCandidatePaths(
79
+ run,
80
+ "rg",
81
+ conjunction,
82
+ ["--", "root"],
83
+ undefined,
84
+ (path) => {
85
+ paths.push(path);
86
+ return true;
87
+ },
88
+ );
89
+ assert.deepEqual(paths, ["candidate"]);
90
+ assert.equal(pass, 2);
91
+ assert.equal(result.stopped, false);
92
+ });
93
+
94
+ test("incomplete intermediate pass → retain reported candidates and the failure diagnostics", async () => {
95
+ const run: GrepBackend["runRgPaths"] = async (_rg, _args, _signal, onPath) => {
96
+ await onPath("reported");
97
+ return { code: 2, stderr: "unreadable path", stopped: false };
98
+ };
99
+ const paths: string[] = [];
100
+ const result = await runCandidatePaths(run, "rg", conjunction, [], undefined, (path) => {
101
+ paths.push(path);
102
+ return true;
103
+ });
104
+ assert.deepEqual(paths, ["reported"]);
105
+ assert.equal(result.code, 2);
106
+ assert.match(result.stderr, /unreadable path/);
107
+ });
108
+
109
+ test("cancel between AND passes → propagate cancellation before emitting candidates", async () => {
110
+ const controller = new AbortController();
111
+ let pass = 0;
112
+ const run: GrepBackend["runRgPaths"] = async (_rg, _args, signal, onPath) => {
113
+ assert.equal(signal, controller.signal);
114
+ if (pass++) {
115
+ controller.abort(new Error("cancelled"));
116
+ signal?.throwIfAborted();
117
+ }
118
+ await onPath("candidate");
119
+ return { code: 0, stderr: "", stopped: false };
120
+ };
121
+ await assert.rejects(
122
+ runCandidatePaths(run, "rg", conjunction, [], controller.signal, () =>
123
+ assert.fail("cancelled candidate"),
124
+ ),
125
+ /cancelled/,
126
+ );
127
+ });