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