@criogaid/pi-hashline-edit 0.6.1 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -12,9 +12,11 @@
12
12
  * Pi's key. It is always taken first and Pi's queue never waits on it, so
13
13
  * the nesting cannot deadlock.
14
14
  *
15
- * Writers outside these queues are not blocked; the freshness check against
16
- * `publishedRevision` detects them and the command is skipped or reported stale.
17
- * A failed command never rolls back the published file.
15
+ * Writers outside these queues are not blocked; the commit layer's freshness
16
+ * observation against `publishedRevision` detects them, and the command is
17
+ * skipped or the result reports the changed freshness. A failed command never
18
+ * rolls back the published file. Fusion states only the command: its status,
19
+ * output, and termination request; the file state belongs to the mutation result.
18
20
  *
19
21
  * @module pi-hashline-edit/pi
20
22
  */
@@ -24,68 +26,64 @@ import { basename, dirname, resolve } from "node:path";
24
26
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
25
27
  import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
26
28
  import { Type, type Static, type TObject, type TProperties } from "typebox";
27
- import { fileRevision, FileMutationError, type PublicationStatus } from "./file-commit.ts";
28
- import { commitFreshness, finalizeMutation, type MutationOutcome } from "./mutation-result.ts";
29
- import { errorMessage } from "../core/errors.ts";
30
- import { OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
29
+ import {
30
+ commitFreshness,
31
+ FileMutationError,
32
+ observeFreshness,
33
+ type FreshnessObservation,
34
+ } from "./file-commit.ts";
35
+ import {
36
+ finalizeMutation,
37
+ type CommandFacts,
38
+ type MutationOutcome,
39
+ type MutationResultDetails,
40
+ } from "./mutation-result.ts";
41
+ import { errnoCode, errorMessage } from "../core/errors.ts";
42
+ import { throwIfCancelled } from "./error-text.ts";
43
+ import { causeOf, CommandNotRun, type ReportDetails } from "./report.ts";
44
+ import { DEFAULT_OUTPUT_BUDGETS, type OutputBudgets } from "./budgets.ts";
45
+ import type {
46
+ ActionFusionProgress,
47
+ CommandStatus,
48
+ Freshness,
49
+ MutationToolName,
50
+ PublicationStatus,
51
+ SuccessReport,
52
+ } from "./report-schema.ts";
53
+ export type { ActionFusionProgress } from "./report-schema.ts";
31
54
 
32
55
  const MILLISECONDS_PER_SECOND = 1_000;
33
56
 
34
- export const THEN_RUN_SUCCEEDED = "[then_run:succeeded]";
35
- export const THEN_RUN_FAILED = "[then_run:failed]";
36
- export const THEN_RUN_SKIPPED = "[then_run:skipped]";
37
- export const THEN_RUN_STALE = "[then_run:stale]";
38
57
  // Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
39
58
  const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / 1_000;
40
59
 
60
+ // Pi's Bash runs on this host, and Pi's prompt does not name the OS; only Windows needs the path note.
61
+ const COMMAND_DESCRIPTION =
62
+ process.platform === "win32"
63
+ ? "Bash command to run. This host is Windows: avoid Unix-only paths such as /tmp."
64
+ : "Bash command to run.";
65
+
41
66
  export const ACTION_FUSION_GUIDELINES = [
42
67
  "Before each file mutation, identify its next command.",
43
- "Prefer then_run when the next command is known, authorized, and ready after the mutation succeeds.",
44
- "When several edits are prerequisites, attach then_run to the last one.",
45
- "Run the command separately if it depends on the mutation result, needs approval, or awaits a reload.",
46
- "Use platform-appropriate commands; avoid Unix-only paths like /tmp on Windows.",
68
+ "then_run is a parameter of edit, replace, and write, not a separate tool.",
47
69
  "Check the command outcome before claiming validation passed.",
48
70
  ];
49
71
 
50
- export type CommandStatus =
51
- | "not_requested"
52
- | "skipped"
53
- | "succeeded"
54
- | "failed"
55
- | "timeout"
56
- | "cancelled";
57
- export type Freshness = "unchanged" | "changed" | "missing" | "unknown";
58
72
  export interface ActionFusionDetails {
59
- publication: PublicationStatus;
60
- command: CommandStatus;
61
- freshness: Freshness;
62
- }
63
-
64
- export interface ActionFusionProgress extends Omit<ActionFusionDetails, "command"> {
65
- toolCallId: string;
66
- path: string;
67
- commandText: string;
68
- command: Exclude<CommandStatus, "not_requested"> | "waiting" | "running";
69
- /** Command output or command execution errors only. */
70
- output: string;
71
- /** A short explanation when the command was not started; never mutation diagnostics. */
72
- reason?: string;
73
- /** True only after mutation execution and result generation both succeed. */
74
- mutationCompleted: boolean;
75
- /** Present once a command with an explicit timeout starts; refreshed during silent execution. */
76
- timing?: { readonly timeoutSeconds: number; readonly remainingSeconds: number };
73
+ readonly publication: PublicationStatus;
74
+ readonly command: CommandStatus | "not_requested";
75
+ readonly freshness: Freshness;
77
76
  }
78
77
 
79
78
  type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionToolContext) => void;
80
79
 
81
80
  /** The tools that accept then_run. */
82
- export type MutationToolName = "edit" | "replace" | "write";
83
81
 
84
82
  export function createThenRunSchema(tool: MutationToolName) {
85
83
  return Type.Optional(
86
84
  Type.Object(
87
85
  {
88
- command: Type.String({ minLength: 1, pattern: "\\S", description: "Bash command to run" }),
86
+ command: Type.String({ minLength: 1, pattern: "\\S", description: COMMAND_DESCRIPTION }),
89
87
  timeout: Type.Optional(
90
88
  Type.Number({
91
89
  exclusiveMinimum: 0,
@@ -116,9 +114,16 @@ export function withThenRunSchema<P extends TProperties>(
116
114
  }
117
115
  export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
118
116
 
117
+ /** Name then_run in a mutation tool's description when Action Fusion is enabled. */
118
+ export function withThenRunDescription(description: string, actionFusion: boolean): string {
119
+ return actionFusion
120
+ ? `${description} If a command such as tests, a typecheck, or a build should run right after this change, set then_run instead of calling bash separately, unless the command needs the user's approval, depends on this call's result, must wait for a reload, or checks several changes sent in the same response; run that check once with bash after them.`
121
+ : description;
122
+ }
123
+
119
124
  /** Keep command state independent of its diagnostic text and of file publication. */
120
125
  export interface CommandOutcome {
121
- readonly status: Exclude<CommandStatus, "not_requested" | "skipped">;
126
+ readonly status: Exclude<CommandStatus, "skipped">;
122
127
  readonly output: string;
123
128
  /** Preserve the session tool's request to stop after this tool batch. */
124
129
  readonly terminate?: boolean;
@@ -132,90 +137,9 @@ type CommandRunner = (
132
137
  onUpdate?: AgentToolUpdateCallback<unknown>,
133
138
  ) => Promise<CommandOutcome>;
134
139
 
135
- type MutationResult<TDetails> = AgentToolResult<TDetails>;
136
- /** Attach the fused outcome to a finalized mutation result, plus optional command text. */
137
- function withFusionDetails<TDetails>(
138
- result: MutationResult<TDetails>,
139
- actionFusion: ActionFusionDetails,
140
- commandText?: string,
141
- ): MutationResult<TDetails> {
142
- return {
143
- ...result,
144
- details: { ...((result.details as object) ?? {}), actionFusion },
145
- content:
146
- commandText === undefined
147
- ? result.content
148
- : [...result.content, { type: "text", text: commandText }],
149
- } as MutationResult<TDetails>;
150
- }
151
-
152
- async function readFreshness(path: string, baseline: string): Promise<Freshness> {
153
- try {
154
- return (await fileRevision(path)) === baseline ? "unchanged" : "changed";
155
- } catch (error) {
156
- if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
157
- return "missing";
158
- return "unknown";
159
- }
160
- }
161
-
162
- async function assertUnchangedBeforeCommand(path: string, baseline: string): Promise<void> {
163
- try {
164
- const before = await fileRevision(path);
165
- await new Promise<void>((resolve) => setImmediate(resolve));
166
- const after = await fileRevision(path);
167
- if (before !== baseline || after !== baseline) {
168
- throw new Error("target content changed after the fused mutation");
169
- }
170
- } catch (error) {
171
- throw new Error(`${THEN_RUN_SKIPPED} ${errorMessage(error)}; the command was not run.`);
172
- }
173
- }
174
-
175
- export class ActionFusionError extends Error {
176
- readonly publication: PublicationStatus;
177
- readonly command: CommandStatus;
178
- readonly freshness: Freshness;
179
- readonly commandOutput: string;
180
- readonly commandReason: string | undefined;
181
-
182
- constructor(
183
- message: string,
184
- state: { publication: PublicationStatus; command: CommandStatus; freshness: Freshness },
185
- options?: {
186
- cause?: unknown;
187
- mutationFailure?: boolean;
188
- commandOutput?: string;
189
- commandReason?: string;
190
- rawMessage?: boolean;
191
- },
192
- ) {
193
- if (options?.rawMessage) {
194
- super(message, options);
195
- } else {
196
- const fileState =
197
- state.publication === "PUBLISHED"
198
- ? "File changes are saved."
199
- : state.publication === "NOT_PUBLISHED"
200
- ? "No file changes were published."
201
- : "File state is uncertain.";
202
- const outcome = `${message} ${state.command === "skipped" || state.command === "cancelled" ? THEN_RUN_SKIPPED : state.command === "succeeded" ? THEN_RUN_SUCCEEDED : THEN_RUN_FAILED}\n${fileState} Command ${state.command}.`;
203
- const diagnostic = options?.cause === undefined ? "" : errorMessage(options.cause);
204
- // Pi serializes only the message. Put the mutation's own error first for its card.
205
- super(
206
- (options?.mutationFailure ? [diagnostic, outcome] : [outcome, diagnostic])
207
- .filter(Boolean)
208
- .join("\n"),
209
- options,
210
- );
211
- }
212
- this.commandOutput = options?.commandOutput ?? "";
213
- this.commandReason = options?.commandReason;
214
- this.name = "ActionFusionError";
215
- this.publication = state.publication;
216
- this.command = state.command;
217
- this.freshness = state.freshness;
218
- }
140
+ /** Publication of a mutation failure, for progress reports; the failure report states it to the model. */
141
+ function publicationOf(error: unknown): PublicationStatus {
142
+ return error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED";
219
143
  }
220
144
 
221
145
  async function defaultCommandRunner(
@@ -262,15 +186,8 @@ async function canonicalQueueKey(path: string): Promise<string> {
262
186
  const canonical = resolve(await realpath(current), ...missing);
263
187
  return process.platform === "win32" ? canonical.toLowerCase() : canonical;
264
188
  } catch (error) {
265
- if (
266
- !(
267
- typeof error === "object" &&
268
- error !== null &&
269
- "code" in error &&
270
- (error.code === "ENOENT" || error.code === "ENOTDIR")
271
- )
272
- )
273
- throw error;
189
+ const code = errnoCode(error);
190
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
274
191
  const parent = dirname(current);
275
192
  if (parent === current)
276
193
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
@@ -304,33 +221,40 @@ export function createActionFusionExecutor(
304
221
  }
305
222
  }
306
223
 
307
- return async function execute<TDetails>({
224
+ return async function execute<TDetails extends object, TTool extends MutationToolName>({
308
225
  toolCallId,
226
+ tool,
227
+ displayPath,
309
228
  absolutePath,
310
229
  thenRun,
230
+ budget = DEFAULT_OUTPUT_BUDGETS,
311
231
  mutate,
312
232
  signal,
313
233
  ctx,
314
234
  onUpdate,
315
235
  }: {
316
236
  toolCallId: string;
237
+ tool: TTool;
238
+ /** The caller-supplied path, as the report states it. */
239
+ displayPath: string;
317
240
  absolutePath: string;
318
241
  thenRun: ThenRunInput | undefined;
319
- mutate: () => Promise<MutationOutcome<TDetails>>;
242
+ budget?: OutputBudgets;
243
+ mutate: () => Promise<MutationOutcome<TDetails, NoInfer<TTool>>>;
320
244
  signal: AbortSignal | undefined;
321
245
  ctx: ExtensionToolContext;
322
- onUpdate?: AgentToolUpdateCallback<TDetails>;
323
- }): Promise<MutationResult<TDetails>> {
324
- let completedMutation: MutationOutcome<TDetails> | undefined;
325
- let commandTermination: boolean | undefined;
326
- let progressFailure: string | undefined;
246
+ onUpdate?: AgentToolUpdateCallback<MutationResultDetails<TDetails>>;
247
+ }): Promise<
248
+ AgentToolResult<TDetails & ReportDetails<SuccessReport> & { actionFusion: ActionFusionDetails }>
249
+ > {
250
+ let completedMutation: MutationOutcome<TDetails, TTool> | undefined;
251
+ let progressFailure: unknown;
327
252
  let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
328
253
  const report = (
329
254
  command: ActionFusionProgress["command"],
330
255
  publication: PublicationStatus,
331
256
  freshness: Freshness,
332
257
  output = "",
333
- reason?: string,
334
258
  ) => {
335
259
  if (!thenRun) return;
336
260
  const progress: ActionFusionProgress = {
@@ -341,7 +265,6 @@ export function createActionFusionExecutor(
341
265
  publication,
342
266
  freshness,
343
267
  output,
344
- ...(reason ? { reason } : {}),
345
268
  mutationCompleted: completedMutation !== undefined,
346
269
  ...(commandTiming
347
270
  ? {
@@ -360,96 +283,69 @@ export function createActionFusionExecutor(
360
283
  () => onProgress?.(progress, ctx),
361
284
  () =>
362
285
  onUpdate?.({
363
- content: [
364
- ...(completedMutation?.result.content ?? []),
365
- {
366
- type: "text",
367
- text: `then_run ${command}: ${thenRun.command}\n${reason ?? output}`,
368
- },
369
- ],
370
- details: {
371
- ...((completedMutation?.result.details as object) ?? {}),
372
- actionFusion: progress,
373
- },
374
- } as MutationResult<TDetails>),
286
+ content: [],
287
+ details: { ...completedMutation?.details, actionFusion: progress },
288
+ }),
375
289
  ]) {
376
290
  try {
377
291
  notify();
378
292
  } catch (error) {
379
- progressFailure ??= errorMessage(error);
293
+ progressFailure ??= error;
380
294
  }
381
295
  }
382
296
  };
297
+ /** A mutation that did not complete keeps its own failure; Fusion adds only the command status. */
298
+ const notRun = (error: unknown, command: "skipped" | "cancelled") => {
299
+ report(command, publicationOf(error), "unknown");
300
+ return new CommandNotRun(error, command, causeOf(progressFailure, budget.fieldBytes));
301
+ };
383
302
  report("waiting", "NOT_PUBLISHED", "unknown");
384
- return withQueue(absolutePath, async () => {
303
+ let terminate: boolean | undefined;
304
+ const result = await withQueue(absolutePath, async () => {
385
305
  try {
386
306
  throwIfCancelled(signal);
387
307
  } catch (error) {
388
- if (thenRun !== undefined)
389
- throw new ActionFusionError(
390
- `${OPERATION_ABORTED} before the mutation started; the command was not run`,
391
- { publication: "NOT_PUBLISHED", command: "cancelled", freshness: "unknown" },
392
- {
393
- cause: error,
394
- mutationFailure: true,
395
- commandReason: "Not run because the mutation was cancelled.",
396
- },
397
- );
308
+ if (thenRun !== undefined) throw notRun(error, "cancelled");
398
309
  throw error;
399
310
  }
400
- let outcome: MutationOutcome<TDetails>;
311
+ let outcome: MutationOutcome<TDetails, TTool>;
401
312
  try {
402
313
  outcome = await mutate();
403
314
  completedMutation = outcome;
404
315
  } catch (error) {
405
- const publication =
406
- error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED";
407
- if (thenRun !== undefined) {
408
- throw new ActionFusionError(
409
- `mutation ${error instanceof FileMutationError ? error.stage : "failed"}; the command was not run`,
410
- { publication, command: "skipped", freshness: "unknown" },
411
- {
412
- cause: error,
413
- mutationFailure: true,
414
- commandReason: "Not run because the mutation did not complete.",
415
- },
416
- );
417
- }
316
+ if (thenRun !== undefined) throw notRun(error, "skipped");
418
317
  throw error;
419
318
  }
420
319
 
421
- const { publication, publishedRevision: baseline } = outcome.commit;
320
+ const { publication, publishedRevision } = outcome.commit;
422
321
  report("waiting", publication, "unknown");
423
- if (thenRun === undefined) {
424
- const freshness = commitFreshness(outcome.commit);
425
- return withFusionDetails(finalizeMutation(outcome, freshness === "unchanged"), {
426
- publication,
427
- command: "not_requested",
428
- freshness,
429
- });
430
- }
431
- try {
432
- throwIfCancelled(signal);
433
- await assertUnchangedBeforeCommand(absolutePath, baseline);
434
- throwIfCancelled(signal);
435
- } catch (error) {
436
- const freshness = await readFreshness(absolutePath, baseline);
437
- throw new ActionFusionError(
438
- "mutation completed; the command was not run",
439
- { publication, command: signal?.aborted ? "cancelled" : "skipped", freshness },
440
- {
441
- cause: error,
442
- commandReason: signal?.aborted
443
- ? "Not run because the operation was cancelled."
444
- : "Not run because the target revision could not be confirmed.",
445
- },
322
+ const settle = (observation: FreshnessObservation, command?: CommandFacts) => {
323
+ if (command) report(command.status, publication, observation.freshness, command.output);
324
+ const settled = finalizeMutation(
325
+ tool,
326
+ displayPath,
327
+ outcome,
328
+ observation,
329
+ command && { ...command, progressError: progressFailure },
330
+ budget,
446
331
  );
447
- }
332
+ const actionFusion: ActionFusionDetails = {
333
+ publication,
334
+ command: command?.status ?? "not_requested",
335
+ freshness: observation.freshness,
336
+ };
337
+ return { ...settled, details: { ...settled.details, actionFusion } };
338
+ };
339
+ if (thenRun === undefined) return settle(commitFreshness(outcome.commit));
340
+
341
+ // A completed mutation remains successful; the command is only started on a fresh target.
342
+ const before = await observeFreshness(absolutePath, publishedRevision, true);
343
+ if (signal?.aborted) return settle(before, { status: "cancelled" });
344
+ if (before.freshness !== "unchanged") return settle(before, { status: "skipped" });
448
345
 
449
346
  report("running", publication, "unchanged");
450
347
  let output = "";
451
348
  let command: CommandOutcome;
452
- let commandError: unknown;
453
349
  // The executor owns the heartbeat lifetime; Pi Bash owns timeout and process cleanup.
454
350
  let heartbeat: ReturnType<typeof setInterval> | undefined;
455
351
  try {
@@ -477,91 +373,21 @@ export function createActionFusionExecutor(
477
373
  });
478
374
  output = command.output;
479
375
  } catch (error) {
480
- commandError = error;
481
376
  output = errorMessage(error);
482
377
  command = { status: signal?.aborted ? "cancelled" : "failed", output };
483
378
  } finally {
484
379
  if (heartbeat) clearInterval(heartbeat);
485
380
  }
486
- commandTermination = command.terminate;
487
- const freshness = await readFreshness(absolutePath, baseline);
488
- if (command.status !== "succeeded") {
489
- throw new ActionFusionError(
490
- "mutation completed; then_run did not complete successfully",
491
- { publication, command: command.status, freshness },
492
- { cause: commandError ?? output, commandOutput: output },
493
- );
494
- }
495
-
496
- report("succeeded", publication, freshness, output);
497
- return withFusionDetails(
498
- finalizeMutation(outcome, freshness === "unchanged", THEN_RUN_STALE),
499
- { publication, command: "succeeded", freshness },
500
- `${THEN_RUN_SUCCEEDED}${output ? `\n${output}` : ""}`,
501
- );
502
- })
503
- .catch((error: unknown) => {
504
- report(
505
- error instanceof ActionFusionError
506
- ? (error.command as ActionFusionProgress["command"])
507
- : "skipped",
508
- error instanceof ActionFusionError || error instanceof FileMutationError
509
- ? error.publication
510
- : (completedMutation?.commit.publication ?? "NOT_PUBLISHED"),
511
- error instanceof ActionFusionError ? error.freshness : "unknown",
512
- error instanceof ActionFusionError ? error.commandOutput : "",
513
- error instanceof ActionFusionError
514
- ? error.commandReason
515
- : "Not run because the mutation did not complete.",
516
- );
517
- // A completed mutation remains successful; command failure belongs to its own card.
518
- if (completedMutation && error instanceof ActionFusionError) {
519
- return withFusionDetails(
520
- finalizeMutation(completedMutation, error.freshness === "unchanged", THEN_RUN_STALE),
521
- { publication: error.publication, command: error.command, freshness: error.freshness },
522
- error.message,
523
- );
524
- }
525
- {
526
- const parts: string[] = [errorMessage(error)];
527
- if (error instanceof ActionFusionError && error.publication !== "NOT_PUBLISHED")
528
- parts.push("Re-read before retrying.");
529
- if (progressFailure) parts.push(`Progress reporting failed: ${progressFailure}`);
530
- if (parts.length > 1 || !(error instanceof Error)) {
531
- const wrapped =
532
- error instanceof ActionFusionError
533
- ? new ActionFusionError(
534
- parts.join("\n"),
535
- {
536
- publication: error.publication,
537
- command: error.command,
538
- freshness: error.freshness,
539
- },
540
- {
541
- cause: error,
542
- commandOutput: error.commandOutput,
543
- commandReason: error.commandReason,
544
- rawMessage: true,
545
- },
546
- )
547
- : new Error(parts.join("\n"), { cause: error });
548
- throw wrapped;
549
- }
550
- throw error;
551
- }
552
- })
553
- .then((result) => {
554
- const finalResult =
555
- commandTermination === undefined ? result : { ...result, terminate: commandTermination };
556
- return progressFailure
557
- ? {
558
- ...finalResult,
559
- content: [
560
- ...finalResult.content,
561
- { type: "text" as const, text: `Progress reporting failed: ${progressFailure}` },
562
- ],
563
- }
564
- : finalResult;
381
+ terminate = command.terminate;
382
+ return settle(await observeFreshness(absolutePath, publishedRevision), {
383
+ status: command.status,
384
+ output,
565
385
  });
386
+ }).catch((error: unknown) => {
387
+ // Failures before the mutation started (such as resolving the queue key) also skip the command.
388
+ if (thenRun === undefined || error instanceof CommandNotRun) throw error;
389
+ throw notRun(error, "skipped");
390
+ });
391
+ return terminate === undefined ? result : { ...result, terminate };
566
392
  };
567
393
  }
@@ -1,3 +1,12 @@
1
+ /**
2
+ * Anchor parsing and row rendering: anchored rows for read, grep, and edit
3
+ * failure diagnostics, plain rows for invalid UTF-8 grep previews, display-row
4
+ * parsing for the grep card, and the carriage-return display shared with
5
+ * mutation diffs.
6
+ *
7
+ * @module pi-hashline-edit/pi
8
+ */
9
+
1
10
  import { computeLineHash, HASH_ALPHABET, HASH_LEN_MIN, HASH_LEN_MAX } from "../core/hash.ts";
2
11
 
3
12
  function anchorSource(hashQuantifier: string): string {