@criogaid/pi-hashline-edit 0.3.1 → 0.4.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 (69) hide show
  1. package/README.md +58 -49
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1593 -712
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +215 -132
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -2,307 +2,532 @@ import { realpath } from "node:fs/promises";
2
2
  import { basename, dirname, resolve } from "node:path";
3
3
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
4
4
  import { createBashToolDefinition, type ExtensionContext } from "@earendil-works/pi-coding-agent";
5
- import { Type } from "typebox";
5
+ import { Type, type Static, type TObject, type TProperties } from "typebox";
6
6
  import { fileRevision, FileMutationError, type PublicationStatus } from "./file-commit.ts";
7
7
  import { finalizeMutationResult, observedFreshness } from "./mutation-result.ts";
8
+ import { errorMessage, OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
8
9
 
9
10
  export const THEN_RUN_SUCCEEDED = "[then_run:succeeded]";
10
11
  export const THEN_RUN_FAILED = "[then_run:failed]";
11
12
  export const THEN_RUN_SKIPPED = "[then_run:skipped]";
12
13
  export const THEN_RUN_STALE = "[then_run:stale]";
14
+ // Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
15
+ const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / 1_000;
13
16
 
14
17
  export const ACTION_FUSION_GUIDELINES = [
15
- "Before each file mutation, identify its next command. If that command is known, authorized, and ready once the mutation succeeds, you MUST include it in then_run instead of making a separate command call (for example, write a script and execute it, or finish edits and run a typecheck).",
16
- "When several edits are prerequisites, attach then_run to the last one. Separate the command only when its choice or arguments depend on inspecting the mutation result, or a required approval or user reload is still pending.",
17
- "Check the command outcome before claiming validation passed.",
18
+ "Before each file mutation, identify its next command.",
19
+ "Prefer then_run when the next command is known, authorized, and ready after the mutation succeeds.",
20
+ "When several edits are prerequisites, attach then_run to the last one.",
21
+ "Run the command separately if it depends on the mutation result, needs approval, or awaits a reload.",
22
+ "Use platform-appropriate commands; avoid Unix-only paths like /tmp on Windows.",
23
+ "Check the command outcome before claiming validation passed.",
18
24
  ];
19
25
 
20
- export interface ThenRunInput {
21
- command: string;
22
- timeout?: number;
23
- }
24
-
25
- export type CommandStatus = "not_requested" | "skipped" | "succeeded" | "failed" | "timeout" | "cancelled";
26
+ export type CommandStatus =
27
+ | "not_requested"
28
+ | "skipped"
29
+ | "succeeded"
30
+ | "failed"
31
+ | "timeout"
32
+ | "cancelled";
26
33
  export type Freshness = "unchanged" | "changed" | "missing" | "unknown";
27
34
  export interface ActionFusionDetails {
28
- publication: PublicationStatus;
29
- command: CommandStatus;
30
- freshness: Freshness;
35
+ publication: PublicationStatus;
36
+ command: CommandStatus;
37
+ freshness: Freshness;
31
38
  }
32
39
 
33
40
  export interface ActionFusionProgress extends Omit<ActionFusionDetails, "command"> {
34
- toolCallId: string;
35
- path: string;
36
- commandText: string;
37
- command: Exclude<CommandStatus, "not_requested"> | "waiting" | "running";
38
- /** Command output or command execution errors only. */
39
- output: string;
40
- /** A short explanation when the command was not started; never mutation diagnostics. */
41
- reason?: string;
42
- /** True only after mutation execution and result generation both succeed. */
43
- mutationCompleted: boolean;
41
+ toolCallId: string;
42
+ path: string;
43
+ commandText: string;
44
+ command: Exclude<CommandStatus, "not_requested"> | "waiting" | "running";
45
+ /** Command output or command execution errors only. */
46
+ output: string;
47
+ /** A short explanation when the command was not started; never mutation diagnostics. */
48
+ reason?: string;
49
+ /** True only after mutation execution and result generation both succeed. */
50
+ mutationCompleted: boolean;
44
51
  }
45
52
 
46
53
  type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionContext) => void;
47
54
 
48
55
  export function createThenRunSchema(description: string) {
49
- return Type.Optional(Type.Object({
50
- command: Type.String({ minLength: 1, description: "Bash command to run" }),
51
- timeout: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: "Timeout in seconds (optional, no default timeout)" })),
52
- }, { description }));
56
+ return Type.Optional(
57
+ Type.Object(
58
+ {
59
+ command: Type.String({ minLength: 1, pattern: "\\S", description: "Bash command to run" }),
60
+ timeout: Type.Optional(
61
+ Type.Number({
62
+ exclusiveMinimum: 0,
63
+ maximum: MAX_BASH_TIMEOUT_SECONDS,
64
+ description: "Timeout in seconds (optional, no default timeout)",
65
+ }),
66
+ ),
67
+ },
68
+ { description, additionalProperties: false },
69
+ ),
70
+ );
53
71
  }
72
+ /** Add the optional then_run field to a mutation schema when Action Fusion is enabled. */
73
+ export function withThenRunSchema<P extends TProperties>(
74
+ schema: TObject<P>,
75
+ description: string,
76
+ actionFusion: boolean,
77
+ ): TObject<P> | TObject<P & { then_run: ReturnType<typeof createThenRunSchema> }> {
78
+ return actionFusion
79
+ ? Type.Object(
80
+ { ...schema.properties, then_run: createThenRunSchema(description) },
81
+ { additionalProperties: false },
82
+ )
83
+ : schema;
84
+ }
85
+ export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
54
86
 
55
- type CommandRunner = (toolCallId: string, input: ThenRunInput, signal: AbortSignal | undefined, ctx: ExtensionContext, onUpdate?: AgentToolUpdateCallback<unknown>) => Promise<string>;
87
+ type CommandRunner = (
88
+ toolCallId: string,
89
+ input: ThenRunInput,
90
+ signal: AbortSignal | undefined,
91
+ ctx: ExtensionContext,
92
+ onUpdate?: AgentToolUpdateCallback<unknown>,
93
+ ) => Promise<string>;
56
94
 
57
95
  type MutationResult<TDetails> = AgentToolResult<TDetails>;
58
- type MutationFinalizer<TDetails> = (result: MutationResult<TDetails>, publishAnchors: boolean) => MutationResult<TDetails>;
96
+ type MutationFinalizer<TDetails> = (
97
+ result: MutationResult<TDetails>,
98
+ publishAnchors: boolean,
99
+ ) => MutationResult<TDetails>;
59
100
 
60
101
  function staleAnchorNotice(): string {
61
- return `${THEN_RUN_STALE} Pre-command anchors are omitted: target freshness is unconfirmed. Re-read before further edits.`;
62
- }
63
-
64
- function errorText(error: unknown): string {
65
- return error instanceof Error ? error.message : String(error);
102
+ return `${THEN_RUN_STALE} Pre-command anchors are omitted: target freshness is unconfirmed. Re-read before further edits.`;
66
103
  }
67
104
 
68
105
  async function readFreshness(path: string, baseline: string): Promise<Freshness> {
69
- try {
70
- return (await fileRevision(path)) === baseline ? "unchanged" : "changed";
71
- } catch (error) {
72
- if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return "missing";
73
- return "unknown";
74
- }
106
+ try {
107
+ return (await fileRevision(path)) === baseline ? "unchanged" : "changed";
108
+ } catch (error) {
109
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
110
+ return "missing";
111
+ return "unknown";
112
+ }
75
113
  }
76
114
 
77
115
  async function assertUnchangedBeforeCommand(path: string, baseline: string): Promise<void> {
78
- try {
79
- const before = await fileRevision(path);
80
- await new Promise<void>((resolve) => setImmediate(resolve));
81
- const after = await fileRevision(path);
82
- if (before !== baseline || after !== baseline) {
83
- throw new Error("target content changed after the fused mutation");
84
- }
85
- } catch (error) {
86
- throw new Error(`${THEN_RUN_SKIPPED} ${errorText(error)}; the command was not run.`);
87
- }
116
+ try {
117
+ const before = await fileRevision(path);
118
+ await new Promise<void>((resolve) => setImmediate(resolve));
119
+ const after = await fileRevision(path);
120
+ if (before !== baseline || after !== baseline) {
121
+ throw new Error("target content changed after the fused mutation");
122
+ }
123
+ } catch (error) {
124
+ throw new Error(`${THEN_RUN_SKIPPED} ${errorMessage(error)}; the command was not run.`);
125
+ }
88
126
  }
89
127
 
90
128
  export class ActionFusionError extends Error {
91
- readonly publication: PublicationStatus;
92
- readonly command: CommandStatus;
93
- readonly freshness: Freshness;
94
- readonly commandOutput: string;
95
- readonly commandReason: string | undefined;
129
+ readonly publication: PublicationStatus;
130
+ readonly command: CommandStatus;
131
+ readonly freshness: Freshness;
132
+ readonly commandOutput: string;
133
+ readonly commandReason: string | undefined;
96
134
 
97
- constructor(message: string, state: { publication: PublicationStatus; command: CommandStatus; freshness: Freshness }, options?: { cause?: unknown; mutationFailure?: boolean; commandOutput?: string; commandReason?: string }) {
98
- const fileState = state.publication === "PUBLISHED" ? "File changes are saved."
99
- : state.publication === "NOT_PUBLISHED" ? "No file changes were published." : "File state is uncertain.";
100
- 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}.`;
101
- const diagnostic = options?.cause === undefined ? "" : errorText(options.cause);
102
- // Pi serializes only the message. Put the mutation's own error first for its card.
103
- super((options?.mutationFailure ? [diagnostic, outcome] : [outcome, diagnostic]).filter(Boolean).join("\n"), options);
104
- this.commandOutput = options?.commandOutput ?? "";
105
- this.commandReason = options?.commandReason;
106
- this.name = "ActionFusionError";
107
- this.publication = state.publication;
108
- this.command = state.command;
109
- this.freshness = state.freshness;
110
- }
135
+ constructor(
136
+ message: string,
137
+ state: { publication: PublicationStatus; command: CommandStatus; freshness: Freshness },
138
+ options?: {
139
+ cause?: unknown;
140
+ mutationFailure?: boolean;
141
+ commandOutput?: string;
142
+ commandReason?: string;
143
+ rawMessage?: boolean;
144
+ },
145
+ ) {
146
+ if (options?.rawMessage) {
147
+ super(message, options);
148
+ } else {
149
+ const fileState =
150
+ state.publication === "PUBLISHED"
151
+ ? "File changes are saved."
152
+ : state.publication === "NOT_PUBLISHED"
153
+ ? "No file changes were published."
154
+ : "File state is uncertain.";
155
+ 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}.`;
156
+ const diagnostic = options?.cause === undefined ? "" : errorMessage(options.cause);
157
+ // Pi serializes only the message. Put the mutation's own error first for its card.
158
+ super(
159
+ (options?.mutationFailure ? [diagnostic, outcome] : [outcome, diagnostic])
160
+ .filter(Boolean)
161
+ .join("\n"),
162
+ options,
163
+ );
164
+ }
165
+ this.commandOutput = options?.commandOutput ?? "";
166
+ this.commandReason = options?.commandReason;
167
+ this.name = "ActionFusionError";
168
+ this.publication = state.publication;
169
+ this.command = state.command;
170
+ this.freshness = state.freshness;
171
+ }
111
172
  }
112
173
 
113
174
  function mutationPublication<TDetails>(result: MutationResult<TDetails>): PublicationStatus {
114
- const details = result.details as { publication?: PublicationStatus } | undefined;
115
- return details?.publication ?? "PUBLISHED";
175
+ const details = result.details as { publication?: PublicationStatus } | undefined;
176
+ return details?.publication ?? "PUBLISHED";
116
177
  }
117
178
 
118
179
  function mutationPublishedRevision<TDetails>(result: MutationResult<TDetails>): string | undefined {
119
- const revision = (result.details as { publishedRevision?: unknown } | undefined)?.publishedRevision;
120
- return typeof revision === "string" && revision.length > 0 ? revision : undefined;
180
+ const revision = (result.details as { publishedRevision?: unknown } | undefined)
181
+ ?.publishedRevision;
182
+ return typeof revision === "string" && revision.length > 0 ? revision : undefined;
121
183
  }
122
184
 
123
185
  function commandStatus(error: unknown, signal: AbortSignal | undefined): CommandStatus {
124
- if (signal?.aborted) return "cancelled";
125
- return /timeout|timed out/i.test(errorText(error)) ? "timeout" : "failed";
126
- }
127
-
128
- function validateThenRun(input: ThenRunInput): void {
129
- if (!input.command.trim()) throw new Error("then_run command must not be empty");
130
- if (input.timeout !== undefined && (!Number.isFinite(input.timeout) || input.timeout <= 0)) {
131
- throw new Error("then_run timeout must be a finite positive number of seconds");
132
- }
186
+ if (signal?.aborted) return "cancelled";
187
+ return /timeout|timed out/i.test(errorMessage(error)) ? "timeout" : "failed";
133
188
  }
134
189
 
135
- async function defaultCommandRunner(toolCallId: string, input: ThenRunInput, signal: AbortSignal | undefined, ctx: ExtensionContext, onUpdate?: AgentToolUpdateCallback<unknown>): Promise<string> {
136
- const bash = createBashToolDefinition(ctx.cwd);
137
- const result = await bash.execute(`${toolCallId}:then_run`, input, signal, onUpdate, ctx);
138
- return result.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
190
+ async function defaultCommandRunner(
191
+ toolCallId: string,
192
+ input: ThenRunInput,
193
+ signal: AbortSignal | undefined,
194
+ ctx: ExtensionContext,
195
+ onUpdate?: AgentToolUpdateCallback<unknown>,
196
+ ): Promise<string> {
197
+ const bash = createBashToolDefinition(ctx.cwd);
198
+ const result = await bash.execute(`${toolCallId}:then_run`, input, signal, onUpdate, ctx);
199
+ return result.content
200
+ .filter((block) => block.type === "text")
201
+ .map((block) => block.text)
202
+ .join("\n");
139
203
  }
140
204
 
141
205
  async function canonicalQueueKey(path: string): Promise<string> {
142
- const resolved = resolve(path);
143
- let current = resolved;
144
- const missing: string[] = [];
145
- while (true) {
146
- try { return resolve(await realpath(current), ...missing); }
147
- catch (error) {
148
- if (!(typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))) throw error;
149
- const parent = dirname(current);
150
- if (parent === current) return resolved;
151
- missing.unshift(basename(current));
152
- current = parent;
153
- }
154
- }
206
+ const resolved = resolve(path);
207
+ let current = resolved;
208
+ const missing: string[] = [];
209
+ while (true) {
210
+ try {
211
+ const canonical = resolve(await realpath(current), ...missing);
212
+ return process.platform === "win32" ? canonical.toLowerCase() : canonical;
213
+ } catch (error) {
214
+ if (
215
+ !(
216
+ typeof error === "object" &&
217
+ error !== null &&
218
+ "code" in error &&
219
+ (error.code === "ENOENT" || error.code === "ENOTDIR")
220
+ )
221
+ )
222
+ throw error;
223
+ const parent = dirname(current);
224
+ if (parent === current)
225
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
226
+ missing.unshift(basename(current));
227
+ current = parent;
228
+ }
229
+ }
155
230
  }
156
231
 
157
- export function createActionFusionExecutor(commandRunner: CommandRunner = defaultCommandRunner, onProgress?: ProgressReporter) {
158
- const queueTails = new Map<string, Promise<void>>();
232
+ export function createActionFusionExecutor(
233
+ commandRunner: CommandRunner = defaultCommandRunner,
234
+ onProgress?: ProgressReporter,
235
+ ) {
236
+ const queueTails = new Map<string, Promise<void>>();
159
237
 
160
- async function withQueue<T>(path: string, work: () => Promise<T>): Promise<T> {
161
- const key = await canonicalQueueKey(path);
162
- const previous = queueTails.get(key) ?? Promise.resolve();
163
- let release!: () => void;
164
- const owned = new Promise<void>((resolve) => { release = resolve; });
165
- const tail = previous.then(() => owned);
166
- queueTails.set(key, tail);
167
- await previous;
168
- try {
169
- return await work();
170
- } finally {
171
- release();
172
- if (queueTails.get(key) === tail) queueTails.delete(key);
173
- }
174
- }
238
+ async function withQueue<T>(path: string, work: () => Promise<T>): Promise<T> {
239
+ const key = await canonicalQueueKey(path);
240
+ const previous = queueTails.get(key) ?? Promise.resolve();
241
+ let release!: () => void;
242
+ const owned = new Promise<void>((resolve) => {
243
+ release = resolve;
244
+ });
245
+ const tail = previous.then(() => owned);
246
+ queueTails.set(key, tail);
247
+ await previous;
248
+ try {
249
+ return await work();
250
+ } finally {
251
+ release();
252
+ if (queueTails.get(key) === tail) queueTails.delete(key);
253
+ }
254
+ }
175
255
 
176
- return async function execute<TDetails>({
177
- toolCallId,
178
- absolutePath,
179
- thenRun,
180
- mutate,
181
- signal,
182
- ctx,
183
- onUpdate,
184
- finalizeMutation,
185
- }: {
186
- toolCallId: string;
187
- absolutePath: string;
188
- thenRun: ThenRunInput | undefined;
189
- mutate: () => Promise<MutationResult<TDetails>>;
190
- signal: AbortSignal | undefined;
191
- ctx: ExtensionContext;
192
- onUpdate?: AgentToolUpdateCallback<TDetails>;
193
- finalizeMutation?: MutationFinalizer<TDetails>;
194
- }): Promise<MutationResult<TDetails>> {
195
- if (thenRun !== undefined) validateThenRun(thenRun);
196
- let completedMutation: MutationResult<TDetails> | undefined;
197
- let progressFailure: string | undefined;
198
- let commandSucceeded = false;
199
- const report = (command: ActionFusionProgress["command"], publication: PublicationStatus, freshness: Freshness, output = "", reason?: string) => {
200
- if (command === "succeeded") commandSucceeded = true;
201
- if (!thenRun) return;
202
- const progress: ActionFusionProgress = { toolCallId, path: absolutePath, commandText: thenRun.command, command, publication, freshness, output, ...(reason ? { reason } : {}), mutationCompleted: completedMutation !== undefined };
203
- // Display callbacks are observers: their failures must not change publication or command execution.
204
- for (const notify of [
205
- () => onProgress?.(progress, ctx),
206
- () => onUpdate?.({
207
- content: [...(completedMutation?.content ?? []), { type: "text", text: `then_run ${command}: ${thenRun.command}\n${reason ?? output}` }],
208
- details: { ...(completedMutation?.details as object ?? {}), actionFusion: progress },
209
- } as MutationResult<TDetails>),
210
- ]) {
211
- try { notify(); } catch (error) { progressFailure ??= errorText(error); }
212
- }
213
- };
214
- report("waiting", "NOT_PUBLISHED", "unknown");
215
- return withQueue(absolutePath, async () => {
216
- try { signal?.throwIfAborted(); } catch (error) {
217
- if (thenRun !== undefined) throw new ActionFusionError("mutation was cancelled before it started; the command was not run", { publication: "NOT_PUBLISHED", command: "cancelled", freshness: "unknown" }, { cause: error, mutationFailure: true, commandReason: "Not run because the mutation was cancelled." });
218
- throw error;
219
- }
220
- let mutationResult: MutationResult<TDetails>;
221
- try {
222
- mutationResult = await mutate();
223
- completedMutation = mutationResult;
224
- } catch (error) {
225
- const publication = error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED";
226
- if (thenRun !== undefined) {
227
- throw new ActionFusionError(`mutation ${error instanceof FileMutationError ? error.stage : "failed"}; the command was not run`, { publication, command: "skipped", freshness: "unknown" }, { cause: error, mutationFailure: true, commandReason: "Not run because the mutation did not complete." });
228
- }
229
- throw error;
230
- }
256
+ return async function execute<TDetails>({
257
+ toolCallId,
258
+ absolutePath,
259
+ thenRun,
260
+ mutate,
261
+ signal,
262
+ ctx,
263
+ onUpdate,
264
+ finalizeMutation,
265
+ }: {
266
+ toolCallId: string;
267
+ absolutePath: string;
268
+ thenRun: ThenRunInput | undefined;
269
+ mutate: () => Promise<MutationResult<TDetails>>;
270
+ signal: AbortSignal | undefined;
271
+ ctx: ExtensionContext;
272
+ onUpdate?: AgentToolUpdateCallback<TDetails>;
273
+ finalizeMutation?: MutationFinalizer<TDetails>;
274
+ }): Promise<MutationResult<TDetails>> {
275
+ let completedMutation: MutationResult<TDetails> | undefined;
276
+ let progressFailure: string | undefined;
277
+ let commandSucceeded = false;
278
+ const report = (
279
+ command: ActionFusionProgress["command"],
280
+ publication: PublicationStatus,
281
+ freshness: Freshness,
282
+ output = "",
283
+ reason?: string,
284
+ ) => {
285
+ if (command === "succeeded") commandSucceeded = true;
286
+ if (!thenRun) return;
287
+ const progress: ActionFusionProgress = {
288
+ toolCallId,
289
+ path: absolutePath,
290
+ commandText: thenRun.command,
291
+ command,
292
+ publication,
293
+ freshness,
294
+ output,
295
+ ...(reason ? { reason } : {}),
296
+ mutationCompleted: completedMutation !== undefined,
297
+ };
298
+ // Display callbacks are observers: their failures must not change publication or command execution.
299
+ for (const notify of [
300
+ () => onProgress?.(progress, ctx),
301
+ () =>
302
+ onUpdate?.({
303
+ content: [
304
+ ...(completedMutation?.content ?? []),
305
+ {
306
+ type: "text",
307
+ text: `then_run ${command}: ${thenRun.command}\n${reason ?? output}`,
308
+ },
309
+ ],
310
+ details: { ...((completedMutation?.details as object) ?? {}), actionFusion: progress },
311
+ } as MutationResult<TDetails>),
312
+ ]) {
313
+ try {
314
+ notify();
315
+ } catch (error) {
316
+ progressFailure ??= errorMessage(error);
317
+ }
318
+ }
319
+ };
320
+ report("waiting", "NOT_PUBLISHED", "unknown");
321
+ return withQueue(absolutePath, async () => {
322
+ try {
323
+ throwIfCancelled(signal);
324
+ } catch (error) {
325
+ if (thenRun !== undefined)
326
+ throw new ActionFusionError(
327
+ `${OPERATION_ABORTED} before the mutation started; the command was not run`,
328
+ { publication: "NOT_PUBLISHED", command: "cancelled", freshness: "unknown" },
329
+ {
330
+ cause: error,
331
+ mutationFailure: true,
332
+ commandReason: "Not run because the mutation was cancelled.",
333
+ },
334
+ );
335
+ throw error;
336
+ }
337
+ let mutationResult: MutationResult<TDetails>;
338
+ try {
339
+ mutationResult = await mutate();
340
+ completedMutation = mutationResult;
341
+ } catch (error) {
342
+ const publication =
343
+ error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED";
344
+ if (thenRun !== undefined) {
345
+ throw new ActionFusionError(
346
+ `mutation ${error instanceof FileMutationError ? error.stage : "failed"}; the command was not run`,
347
+ { publication, command: "skipped", freshness: "unknown" },
348
+ {
349
+ cause: error,
350
+ mutationFailure: true,
351
+ commandReason: "Not run because the mutation did not complete.",
352
+ },
353
+ );
354
+ }
355
+ throw error;
356
+ }
231
357
 
232
- const publication = mutationPublication(mutationResult);
233
- report("waiting", publication, "unknown");
234
- if (thenRun === undefined) {
235
- const finalized = finalizeMutation ? finalizeMutationResult(mutationResult, finalizeMutation) : mutationResult;
236
- return {
237
- ...finalized,
238
- details: { ...(finalized.details as object ?? {}), actionFusion: { publication, command: "not_requested", freshness: observedFreshness(mutationResult) } satisfies ActionFusionDetails },
239
- } as MutationResult<TDetails>;
240
- }
358
+ const publication = mutationPublication(mutationResult);
359
+ report("waiting", publication, "unknown");
360
+ if (thenRun === undefined) {
361
+ const finalized = finalizeMutation
362
+ ? finalizeMutationResult(mutationResult, finalizeMutation)
363
+ : mutationResult;
364
+ return {
365
+ ...finalized,
366
+ details: {
367
+ ...((finalized.details as object) ?? {}),
368
+ actionFusion: {
369
+ publication,
370
+ command: "not_requested",
371
+ freshness: observedFreshness(mutationResult),
372
+ } satisfies ActionFusionDetails,
373
+ },
374
+ } as MutationResult<TDetails>;
375
+ }
241
376
 
242
- const baseline = mutationPublishedRevision(mutationResult);
243
- if (baseline === undefined) {
244
- throw new ActionFusionError("Missing published revision; cannot validate fused command freshness.", { publication, command: "skipped", freshness: "unknown" }, { commandReason: "Not run because the mutation revision is unavailable." });
245
- }
246
- try {
247
- signal?.throwIfAborted();
248
- await assertUnchangedBeforeCommand(absolutePath, baseline);
249
- signal?.throwIfAborted();
250
- } catch (error) {
251
- const freshness = await readFreshness(absolutePath, baseline);
252
- throw new ActionFusionError("mutation completed; the command was not run", { publication, command: signal?.aborted ? "cancelled" : "skipped", freshness }, { cause: error, commandReason: signal?.aborted ? "Not run because the operation was cancelled." : "Not run because the target revision could not be confirmed." });
253
- }
377
+ const baseline = mutationPublishedRevision(mutationResult);
378
+ if (baseline === undefined) {
379
+ throw new ActionFusionError(
380
+ "Missing published revision; cannot validate fused command freshness.",
381
+ { publication, command: "skipped", freshness: "unknown" },
382
+ { commandReason: "Not run because the mutation revision is unavailable." },
383
+ );
384
+ }
385
+ try {
386
+ throwIfCancelled(signal);
387
+ await assertUnchangedBeforeCommand(absolutePath, baseline);
388
+ throwIfCancelled(signal);
389
+ } catch (error) {
390
+ const freshness = await readFreshness(absolutePath, baseline);
391
+ throw new ActionFusionError(
392
+ "mutation completed; the command was not run",
393
+ { publication, command: signal?.aborted ? "cancelled" : "skipped", freshness },
394
+ {
395
+ cause: error,
396
+ commandReason: signal?.aborted
397
+ ? "Not run because the operation was cancelled."
398
+ : "Not run because the target revision could not be confirmed.",
399
+ },
400
+ );
401
+ }
254
402
 
255
- report("running", publication, "unchanged");
256
- let output: string;
257
- let commandError: unknown;
258
- try {
259
- output = await commandRunner(toolCallId, thenRun, signal, ctx, (partial) => {
260
- const text = partial.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
261
- report("running", publication, "unknown", text);
262
- });
263
- } catch (error) {
264
- commandError = error;
265
- output = "";
266
- }
267
- const freshness = await readFreshness(absolutePath, baseline);
268
- if (commandError !== undefined) {
269
- throw new ActionFusionError("mutation completed; then_run did not complete successfully", { publication, command: commandStatus(commandError, signal), freshness }, { cause: commandError, commandOutput: errorText(commandError) });
270
- }
403
+ report("running", publication, "unchanged");
404
+ let output: string;
405
+ let commandError: unknown;
406
+ try {
407
+ output = await commandRunner(toolCallId, thenRun, signal, ctx, (partial) => {
408
+ const text = partial.content
409
+ .filter((block) => block.type === "text")
410
+ .map((block) => block.text)
411
+ .join("\n");
412
+ report("running", publication, "unknown", text);
413
+ });
414
+ } catch (error) {
415
+ commandError = error;
416
+ output = "";
417
+ }
418
+ const freshness = await readFreshness(absolutePath, baseline);
419
+ if (commandError !== undefined) {
420
+ throw new ActionFusionError(
421
+ "mutation completed; then_run did not complete successfully",
422
+ { publication, command: commandStatus(commandError, signal), freshness },
423
+ { cause: commandError, commandOutput: errorMessage(commandError) },
424
+ );
425
+ }
271
426
 
272
- const actionFusion: ActionFusionDetails = { publication, command: "succeeded", freshness };
273
- report("succeeded", publication, freshness, output);
274
- const finalized = finalizeMutation ? finalizeMutationResult(mutationResult, finalizeMutation, freshness === "unchanged", staleAnchorNotice()) : mutationResult;
275
- const commandText = `${THEN_RUN_SUCCEEDED}${!finalizeMutation && freshness !== "unchanged" ? `\n${THEN_RUN_STALE} Re-read the file before further edits; previous anchors may no longer match.` : ""}${output ? `\n${output}` : ""}`;
276
- return {
277
- ...finalized,
278
- details: { ...(finalized.details as object ?? {}), actionFusion },
279
- content: [...finalized.content, { type: "text", text: commandText }],
280
- } as MutationResult<TDetails>;
281
- }).catch((error: unknown) => {
282
- // Result-generation errors after a successful command must not relabel it skipped.
283
- if (!commandSucceeded) {
284
- report(error instanceof ActionFusionError ? error.command as ActionFusionProgress["command"] : "skipped",
285
- error instanceof ActionFusionError || error instanceof FileMutationError ? error.publication : completedMutation ? mutationPublication(completedMutation) : "NOT_PUBLISHED",
286
- error instanceof ActionFusionError ? error.freshness : "unknown",
287
- error instanceof ActionFusionError ? error.commandOutput : "",
288
- error instanceof ActionFusionError ? error.commandReason : "Not run because the mutation did not complete.");
289
- }
290
- // A completed mutation remains successful; command failure belongs to its own card.
291
- if (completedMutation && error instanceof ActionFusionError) {
292
- const finalized = finalizeMutation ? finalizeMutationResult(completedMutation, finalizeMutation, error.freshness === "unchanged", staleAnchorNotice()) : completedMutation;
293
- const anchorNotice = !finalizeMutation && error.freshness !== "unchanged" ? `\n${THEN_RUN_STALE} Re-read before further edits; previous anchors may no longer match.` : "";
294
- return {
295
- ...finalized,
296
- details: { ...(finalized.details as object ?? {}), actionFusion: { publication: error.publication, command: error.command, freshness: error.freshness } satisfies ActionFusionDetails },
297
- content: [...finalized.content, { type: "text", text: `${error.message}${anchorNotice}` }],
298
- } as MutationResult<TDetails>;
299
- }
300
- if (error instanceof ActionFusionError && error.publication !== "NOT_PUBLISHED") error.message += "\nRe-read before retrying.";
301
- if (progressFailure && error instanceof Error) error.message += `\nProgress reporting failed: ${progressFailure}`;
302
- throw error;
303
- }).then((result) => progressFailure ? {
304
- ...result,
305
- content: [...result.content, { type: "text" as const, text: `Progress reporting failed: ${progressFailure}` }],
306
- } : result);
307
- };
427
+ const actionFusion: ActionFusionDetails = { publication, command: "succeeded", freshness };
428
+ report("succeeded", publication, freshness, output);
429
+ const finalized = finalizeMutation
430
+ ? finalizeMutationResult(
431
+ mutationResult,
432
+ finalizeMutation,
433
+ freshness === "unchanged",
434
+ staleAnchorNotice(),
435
+ )
436
+ : mutationResult;
437
+ const commandText = `${THEN_RUN_SUCCEEDED}${!finalizeMutation && freshness !== "unchanged" ? `\n${THEN_RUN_STALE} Re-read the file before further edits; previous anchors may no longer match.` : ""}${output ? `\n${output}` : ""}`;
438
+ return {
439
+ ...finalized,
440
+ details: { ...((finalized.details as object) ?? {}), actionFusion },
441
+ content: [...finalized.content, { type: "text", text: commandText }],
442
+ } as MutationResult<TDetails>;
443
+ })
444
+ .catch((error: unknown) => {
445
+ // Result-generation errors after a successful command must not relabel it skipped.
446
+ if (!commandSucceeded) {
447
+ report(
448
+ error instanceof ActionFusionError
449
+ ? (error.command as ActionFusionProgress["command"])
450
+ : "skipped",
451
+ error instanceof ActionFusionError || error instanceof FileMutationError
452
+ ? error.publication
453
+ : completedMutation
454
+ ? mutationPublication(completedMutation)
455
+ : "NOT_PUBLISHED",
456
+ error instanceof ActionFusionError ? error.freshness : "unknown",
457
+ error instanceof ActionFusionError ? error.commandOutput : "",
458
+ error instanceof ActionFusionError
459
+ ? error.commandReason
460
+ : "Not run because the mutation did not complete.",
461
+ );
462
+ }
463
+ // A completed mutation remains successful; command failure belongs to its own card.
464
+ if (completedMutation && error instanceof ActionFusionError) {
465
+ const finalized = finalizeMutation
466
+ ? finalizeMutationResult(
467
+ completedMutation,
468
+ finalizeMutation,
469
+ error.freshness === "unchanged",
470
+ staleAnchorNotice(),
471
+ )
472
+ : completedMutation;
473
+ const anchorNotice =
474
+ !finalizeMutation && error.freshness !== "unchanged"
475
+ ? `\n${THEN_RUN_STALE} Re-read before further edits; previous anchors may no longer match.`
476
+ : "";
477
+ return {
478
+ ...finalized,
479
+ details: {
480
+ ...((finalized.details as object) ?? {}),
481
+ actionFusion: {
482
+ publication: error.publication,
483
+ command: error.command,
484
+ freshness: error.freshness,
485
+ } satisfies ActionFusionDetails,
486
+ },
487
+ content: [
488
+ ...finalized.content,
489
+ { type: "text", text: `${error.message}${anchorNotice}` },
490
+ ],
491
+ } as MutationResult<TDetails>;
492
+ }
493
+ {
494
+ const parts: string[] = [errorMessage(error)];
495
+ if (error instanceof ActionFusionError && error.publication !== "NOT_PUBLISHED")
496
+ parts.push("Re-read before retrying.");
497
+ if (progressFailure) parts.push(`Progress reporting failed: ${progressFailure}`);
498
+ if (parts.length > 1 || !(error instanceof Error)) {
499
+ const wrapped =
500
+ error instanceof ActionFusionError
501
+ ? new ActionFusionError(
502
+ parts.join("\n"),
503
+ {
504
+ publication: error.publication,
505
+ command: error.command,
506
+ freshness: error.freshness,
507
+ },
508
+ {
509
+ cause: error,
510
+ commandOutput: error.commandOutput,
511
+ commandReason: error.commandReason,
512
+ rawMessage: true,
513
+ },
514
+ )
515
+ : new Error(parts.join("\n"), { cause: error });
516
+ throw wrapped;
517
+ }
518
+ throw error;
519
+ }
520
+ })
521
+ .then((result) =>
522
+ progressFailure
523
+ ? {
524
+ ...result,
525
+ content: [
526
+ ...result.content,
527
+ { type: "text" as const, text: `Progress reporting failed: ${progressFailure}` },
528
+ ],
529
+ }
530
+ : result,
531
+ );
532
+ };
308
533
  }