@criogaid/pi-hashline-edit 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -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,73 +26,55 @@ 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 { commitFreshness, observeFreshness, type FreshnessObservation } from "./file-commit.ts";
30
+ import {
31
+ commandText,
32
+ finalizeMutation,
33
+ type CommandFacts,
34
+ type MutationOutcome,
35
+ type MutationResultDetails,
36
+ } from "./mutation-result.ts";
37
+ import { errnoCode, errorMessage } from "../core/errors.ts";
38
+ import { throwIfCancelled } from "./error-text.ts";
39
+ import { causeOf, CommandNotRun, type ReportDetails } from "./report.ts";
40
+ import type { OutputBudgets } from "./budgets.ts";
41
+ import type {
42
+ ActionFusionProgress,
43
+ CommandResult,
44
+ CommandStatus,
45
+ Freshness,
46
+ MutationToolName,
47
+ SuccessReport,
48
+ } from "./report-schema.ts";
49
+ export type { ActionFusionProgress } from "./report-schema.ts";
31
50
 
32
51
  const MILLISECONDS_PER_SECOND = 1_000;
33
52
 
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
53
  // Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
39
54
  const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / 1_000;
40
55
 
56
+ // Pi's Bash runs on this host, and Pi's prompt does not name the OS; only Windows needs the path note.
57
+ const COMMAND_DESCRIPTION =
58
+ process.platform === "win32"
59
+ ? "Bash command to run. This host is Windows: avoid Unix-only paths such as /tmp."
60
+ : "Bash command to run.";
61
+
41
62
  export const ACTION_FUSION_GUIDELINES = [
42
- "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.",
47
- "Check the command outcome before claiming validation passed.",
63
+ "When a check covers several changes, run it once after all of those changes.",
48
64
  ];
49
65
 
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
- 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 };
77
- }
78
-
79
66
  type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionToolContext) => void;
80
67
 
81
- /** The tools that accept then_run. */
82
- export type MutationToolName = "edit" | "replace" | "write";
83
-
84
- export function createThenRunSchema(tool: MutationToolName) {
68
+ function createThenRunSchema(tool: MutationToolName) {
85
69
  return Type.Optional(
86
70
  Type.Object(
87
71
  {
88
- command: Type.String({ minLength: 1, pattern: "\\S", description: "Bash command to run" }),
72
+ command: Type.String({ minLength: 1, pattern: "\\S", description: COMMAND_DESCRIPTION }),
89
73
  timeout: Type.Optional(
90
74
  Type.Number({
91
75
  exclusiveMinimum: 0,
92
76
  maximum: MAX_BASH_TIMEOUT_SECONDS,
93
- description: "Timeout in seconds (optional, no default timeout)",
77
+ description: "Timeout in seconds; none when omitted.",
94
78
  }),
95
79
  ),
96
80
  },
@@ -116,10 +100,17 @@ export function withThenRunSchema<P extends TProperties>(
116
100
  }
117
101
  export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
118
102
 
103
+ /** Name then_run in a mutation tool's description when Action Fusion is enabled. */
104
+ export function withThenRunDescription(description: string, actionFusion: boolean): string {
105
+ return actionFusion
106
+ ? `${description} Set the then_run parameter for checks that can run immediately after this change. Use a separate bash call when the command requires approval, needs information from this tool's result, must wait for reload, or checks several changes from one response.`
107
+ : description;
108
+ }
109
+
119
110
  /** Keep command state independent of its diagnostic text and of file publication. */
120
111
  export interface CommandOutcome {
121
- readonly status: Exclude<CommandStatus, "not_requested" | "skipped">;
122
- readonly output: string;
112
+ readonly status: Exclude<CommandStatus, "skipped">;
113
+ readonly result: CommandResult;
123
114
  /** Preserve the session tool's request to stop after this tool batch. */
124
115
  readonly terminate?: boolean;
125
116
  }
@@ -132,92 +123,6 @@ type CommandRunner = (
132
123
  onUpdate?: AgentToolUpdateCallback<unknown>,
133
124
  ) => Promise<CommandOutcome>;
134
125
 
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
- }
219
- }
220
-
221
126
  async function defaultCommandRunner(
222
127
  _toolCallId: string,
223
128
  input: ThenRunInput,
@@ -228,11 +133,10 @@ async function defaultCommandRunner(
228
133
  // Use the session's callable Bash, including overrides, validation, permission
229
134
  // hooks and tool_result hooks. Tool failures resolve with isError, not rejection.
230
135
  const { result, isError } = await ctx.executeTool("bash", input, { signal, onUpdate });
231
- const output = result.content
232
- .filter((block) => block.type === "text")
233
- .map((block) => block.text)
234
- .join("\n");
235
- const command = { output, terminate: result.terminate };
136
+ const command = {
137
+ terminate: result.terminate,
138
+ result: { content: result.content, details: result.details },
139
+ };
236
140
  if (!isError) return { status: "succeeded", ...command };
237
141
  if (signal?.aborted) return { status: "cancelled", ...command };
238
142
 
@@ -246,6 +150,7 @@ async function defaultCommandRunner(
246
150
  // timeout as text. Only recognize its final diagnostic for the requested
247
151
  // timeout; a failed command's output may itself mention or quote a timeout.
248
152
  const timeoutDiagnostic = `Command timed out after ${input.timeout} seconds`;
153
+ const output = commandText(result.content);
249
154
  const timedOut =
250
155
  !hasExitCode &&
251
156
  input.timeout !== undefined &&
@@ -262,15 +167,8 @@ async function canonicalQueueKey(path: string): Promise<string> {
262
167
  const canonical = resolve(await realpath(current), ...missing);
263
168
  return process.platform === "win32" ? canonical.toLowerCase() : canonical;
264
169
  } 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;
170
+ const code = errnoCode(error);
171
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
274
172
  const parent = dirname(current);
275
173
  if (parent === current)
276
174
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
@@ -304,44 +202,42 @@ export function createActionFusionExecutor(
304
202
  }
305
203
  }
306
204
 
307
- return async function execute<TDetails>({
205
+ return async function execute<TDetails extends object, TTool extends MutationToolName>({
308
206
  toolCallId,
207
+ tool,
208
+ displayPath,
309
209
  absolutePath,
310
210
  thenRun,
211
+ budget,
311
212
  mutate,
312
213
  signal,
313
214
  ctx,
314
215
  onUpdate,
315
216
  }: {
316
217
  toolCallId: string;
218
+ tool: TTool;
219
+ /** The caller-supplied path, as the report states it. */
220
+ displayPath: string;
317
221
  absolutePath: string;
318
222
  thenRun: ThenRunInput | undefined;
319
- mutate: () => Promise<MutationOutcome<TDetails>>;
223
+ budget: OutputBudgets;
224
+ mutate: () => Promise<MutationOutcome<TDetails, NoInfer<TTool>>>;
320
225
  signal: AbortSignal | undefined;
321
226
  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;
227
+ onUpdate?: AgentToolUpdateCallback<MutationResultDetails<TDetails>>;
228
+ }): Promise<AgentToolResult<TDetails & ReportDetails<SuccessReport>>> {
229
+ let completedMutation: MutationOutcome<TDetails, TTool> | undefined;
230
+ let progressFailure: unknown;
231
+ let commandResult: CommandResult | undefined;
327
232
  let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
328
- const report = (
329
- command: ActionFusionProgress["command"],
330
- publication: PublicationStatus,
331
- freshness: Freshness,
332
- output = "",
333
- reason?: string,
334
- ) => {
233
+ const report = (command: ActionFusionProgress["command"], freshness: Freshness) => {
335
234
  if (!thenRun) return;
336
235
  const progress: ActionFusionProgress = {
337
236
  toolCallId,
338
- path: absolutePath,
339
237
  commandText: thenRun.command,
340
238
  command,
341
- publication,
342
239
  freshness,
343
- output,
344
- ...(reason ? { reason } : {}),
240
+ ...(commandResult ? { result: commandResult } : {}),
345
241
  mutationCompleted: completedMutation !== undefined,
346
242
  ...(commandTiming
347
243
  ? {
@@ -360,96 +256,63 @@ export function createActionFusionExecutor(
360
256
  () => onProgress?.(progress, ctx),
361
257
  () =>
362
258
  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>),
259
+ content: [],
260
+ details: { ...completedMutation?.details, actionFusion: progress },
261
+ }),
375
262
  ]) {
376
263
  try {
377
264
  notify();
378
265
  } catch (error) {
379
- progressFailure ??= errorMessage(error);
266
+ progressFailure ??= error;
380
267
  }
381
268
  }
382
269
  };
383
- report("waiting", "NOT_PUBLISHED", "unknown");
384
- return withQueue(absolutePath, async () => {
270
+ /** A mutation that did not complete keeps its own failure; Fusion adds only the command status. */
271
+ const notRun = (error: unknown, command: "skipped" | "cancelled") => {
272
+ report(command, "unknown");
273
+ return new CommandNotRun(error, command, causeOf(progressFailure, budget.fieldBytes));
274
+ };
275
+ report("waiting", "unknown");
276
+ let terminate: boolean | undefined;
277
+ const result = await withQueue(absolutePath, async () => {
385
278
  try {
386
279
  throwIfCancelled(signal);
387
280
  } 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
- );
281
+ if (thenRun !== undefined) throw notRun(error, "cancelled");
398
282
  throw error;
399
283
  }
400
- let outcome: MutationOutcome<TDetails>;
284
+ let outcome: MutationOutcome<TDetails, TTool>;
401
285
  try {
402
286
  outcome = await mutate();
403
287
  completedMutation = outcome;
404
288
  } 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
- }
289
+ if (thenRun !== undefined) throw notRun(error, "skipped");
418
290
  throw error;
419
291
  }
420
292
 
421
- const { publication, publishedRevision: baseline } = outcome.commit;
422
- 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
- },
293
+ const { publishedRevision } = outcome.commit;
294
+ report("waiting", "unknown");
295
+ const settle = (observation: FreshnessObservation, command?: CommandFacts) => {
296
+ if (command) report(command.status, observation.freshness);
297
+ // The report states publication, freshness, and the command status once.
298
+ return finalizeMutation(
299
+ tool,
300
+ displayPath,
301
+ outcome,
302
+ observation,
303
+ command && { ...command, progressError: progressFailure },
304
+ budget,
446
305
  );
447
- }
306
+ };
307
+ if (thenRun === undefined) return settle(commitFreshness(outcome.commit));
308
+
309
+ // A completed mutation remains successful; the command is only started on a fresh target.
310
+ const before = await observeFreshness(absolutePath, publishedRevision, true);
311
+ if (signal?.aborted) return settle(before, { status: "cancelled" });
312
+ if (before.freshness !== "unchanged") return settle(before, { status: "skipped" });
448
313
 
449
- report("running", publication, "unchanged");
450
- let output = "";
314
+ report("running", "unchanged");
451
315
  let command: CommandOutcome;
452
- let commandError: unknown;
453
316
  // The executor owns the heartbeat lifetime; Pi Bash owns timeout and process cleanup.
454
317
  let heartbeat: ReturnType<typeof setInterval> | undefined;
455
318
  try {
@@ -462,106 +325,32 @@ export function createActionFusionExecutor(
462
325
  deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
463
326
  };
464
327
  if (onProgress || onUpdate) {
465
- heartbeat = setInterval(
466
- () => report("running", publication, "unknown", output),
467
- MILLISECONDS_PER_SECOND,
468
- );
328
+ heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
469
329
  heartbeat.unref();
470
330
  }
471
331
  }
472
- output = partial.content
473
- .filter((block) => block.type === "text")
474
- .map((block) => block.text)
475
- .join("\n");
476
- report("running", publication, "unknown", output);
332
+ commandResult = { content: partial.content, details: partial.details };
333
+ report("running", "unknown");
477
334
  });
478
- output = command.output;
479
335
  } catch (error) {
480
- commandError = error;
481
- output = errorMessage(error);
482
- command = { status: signal?.aborted ? "cancelled" : "failed", output };
336
+ command = {
337
+ status: signal?.aborted ? "cancelled" : "failed",
338
+ result: { content: [{ type: "text", text: errorMessage(error) }] },
339
+ };
483
340
  } finally {
484
341
  if (heartbeat) clearInterval(heartbeat);
485
342
  }
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;
343
+ commandResult = command.result;
344
+ terminate = command.terminate;
345
+ return settle(await observeFreshness(absolutePath, publishedRevision), {
346
+ status: command.status,
347
+ result: command.result,
565
348
  });
349
+ }).catch((error: unknown) => {
350
+ // Failures before the mutation started (such as resolving the queue key) also skip the command.
351
+ if (thenRun === undefined || error instanceof CommandNotRun) throw error;
352
+ throw notRun(error, "skipped");
353
+ });
354
+ return terminate === undefined ? result : { ...result, terminate };
566
355
  };
567
356
  }
@@ -106,3 +106,19 @@ test("display row parsing rejects headers, notices, and invalid line references"
106
106
  assert.equal(parseDisplayRow(row), null, row);
107
107
  }
108
108
  });
109
+
110
+ test("Unicode line separators in display rows → preserves the complete content", async (t) => {
111
+ const formatter = createAnchorFormatter(4);
112
+ for (const separator of ["\u2028", "\u2029"]) {
113
+ const content = `before${separator}after`;
114
+ for (const [name, row, parse] of [
115
+ ["anchored", formatter.row(12, content), parseHashline],
116
+ ["anchored display", formatter.row(12, content), parseDisplayRow],
117
+ ["plain display", plainRow(12, content), parseDisplayRow],
118
+ ] as const) {
119
+ await t.test(`${name} ${JSON.stringify(separator)}`, () => {
120
+ assert.deepEqual(parse(row), { lineNo: "12", content });
121
+ });
122
+ }
123
+ }
124
+ });
@@ -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 {
@@ -9,11 +18,15 @@ export function anchorPattern(hashLen: number): string {
9
18
  return `^${anchorSource(`{${hashLen}}`)}$`;
10
19
  }
11
20
 
12
- /** Separates a row's line reference from its displayed content. */
21
+ /**
22
+ * Separates a row's line reference from its displayed content. Rows are split on LF only, so
23
+ * row and header patterns use `s`: content may hold U+2028 or U+2029, which `.` skips otherwise.
24
+ */
13
25
  const ROW_SEPARATOR = "│";
14
26
  const ANCHOR_TOKEN = new RegExp(`^${anchorSource("+")}$`);
15
27
  const HASHLINE_ROW = new RegExp(
16
28
  `^${anchorSource(`{${HASH_LEN_MIN},${HASH_LEN_MAX}}`)}${ROW_SEPARATOR}(.*)$`,
29
+ "s",
17
30
  );
18
31
 
19
32
  /** Split a `LINE#HASH` token of any hash length; undefined when the shape is wrong. */
@@ -22,7 +35,7 @@ export function parseAnchorToken(value: string): { line: number; hash: string }
22
35
  return match ? { line: Number(match[1]), hash: match[2]! } : undefined;
23
36
  }
24
37
 
25
- export interface HashlineRow {
38
+ interface HashlineRow {
26
39
  /** Line number as written in the anchor (string form). */
27
40
  lineNo: string;
28
41
  /** Line content with the `LINE#HASH│` prefix removed. */
@@ -35,7 +48,7 @@ export function parseHashline(line: string): HashlineRow | null {
35
48
  return match ? { lineNo: match[1], content: match[3] } : null;
36
49
  }
37
50
 
38
- const PLAIN_ROW = new RegExp(`^([1-9][0-9]*)${ROW_SEPARATOR}(.*)$`);
51
+ const PLAIN_ROW = new RegExp(`^([1-9][0-9]*)${ROW_SEPARATOR}(.*)$`, "s");
39
52
 
40
53
  /** Parse an anchored row or a non-editable `LINE│content` row; null for other text. */
41
54
  export function parseDisplayRow(line: string): HashlineRow | null {