@criogaid/pi-hashline-edit 0.9.0 → 0.11.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 (131) hide show
  1. package/README.md +12 -12
  2. package/README.zh-CN.md +12 -12
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +96 -271
  7. package/src/core/apply.ts +62 -169
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.test.ts +2 -3
  10. package/src/core/character-set.ts +5 -5
  11. package/src/core/errors.test.ts +23 -7
  12. package/src/core/errors.ts +32 -5
  13. package/src/core/hash.test.ts +8 -16
  14. package/src/core/hash.ts +3 -23
  15. package/src/core/lines.ts +2 -4
  16. package/src/core/ranges.test.ts +2 -1
  17. package/src/core/ranges.ts +1 -1
  18. package/src/core/regex.ts +3 -4
  19. package/src/core/replace.test.ts +47 -1
  20. package/src/core/replace.ts +19 -13
  21. package/src/core/search-analysis.test.ts +24 -27
  22. package/src/core/search-analysis.ts +34 -65
  23. package/src/core/search-matrix.testing.ts +0 -2
  24. package/src/core/search.ts +1 -1
  25. package/src/core/text.test.ts +5 -5
  26. package/src/core/text.ts +5 -12
  27. package/src/core/types.ts +8 -44
  28. package/src/index.ts +8 -8
  29. package/src/integration/config-registration.test.ts +8 -10
  30. package/src/integration/fusion-dispatch.test.ts +4 -7
  31. package/src/integration/grep-errors.test.ts +3 -3
  32. package/src/integration/grep-flags.test.ts +5 -19
  33. package/src/integration/grep-js-completeness.test.ts +45 -18
  34. package/src/integration/grep-line-candidates.test.ts +7 -10
  35. package/src/integration/grep-matrix.test.ts +6 -9
  36. package/src/integration/grep-order.test.ts +4 -4
  37. package/src/integration/grep-path-matrix.test.ts +10 -9
  38. package/src/integration/grep-prefilter-coverage.test.ts +5 -8
  39. package/src/integration/grep-process-limits.test.ts +76 -0
  40. package/src/integration/grep-regex.test.ts +10 -10
  41. package/src/integration/grep-rg.test.ts +166 -66
  42. package/src/integration/grep-scan-budget.test.ts +9 -9
  43. package/src/integration/grep-translation.test.ts +18 -32
  44. package/src/integration/large-text.test.ts +6 -52
  45. package/src/integration/model-budget-lifecycle.test.ts +10 -9
  46. package/src/integration/mutation-file-types.testing.ts +4 -4
  47. package/src/integration/npm-package.testing.ts +3 -3
  48. package/src/integration/publication-read-changes.test.ts +161 -83
  49. package/src/integration/read-changes.test.ts +4 -4
  50. package/src/integration/replace-worker-boundary.test.ts +22 -12
  51. package/src/integration/report-replay.test.ts +23 -26
  52. package/src/integration/utf8-errors.test.ts +4 -4
  53. package/src/pi/AGENTS.md +18 -17
  54. package/src/pi/action-fusion.test.ts +241 -353
  55. package/src/pi/action-fusion.testing.ts +38 -0
  56. package/src/pi/action-fusion.ts +150 -125
  57. package/src/pi/anchor-format.test.ts +9 -9
  58. package/src/pi/anchor-format.ts +6 -8
  59. package/src/pi/argument-diagnostics.ts +25 -28
  60. package/src/pi/argument-error.ts +2 -1
  61. package/src/pi/argument-format.test.ts +19 -18
  62. package/src/pi/argument-validation.test.ts +334 -283
  63. package/src/pi/argument-validation.ts +5 -8
  64. package/src/pi/budgets.ts +6 -8
  65. package/src/pi/codemode.test.ts +7 -2
  66. package/src/pi/config.test.ts +7 -3
  67. package/src/pi/config.ts +12 -9
  68. package/src/pi/diagnostic-buffer.test.ts +34 -13
  69. package/src/pi/diagnostic-buffer.ts +1 -2
  70. package/src/pi/directory-sync.test.ts +0 -1
  71. package/src/pi/edit-tool.ts +86 -211
  72. package/src/pi/error-text.ts +10 -9
  73. package/src/pi/execute.test.ts +249 -345
  74. package/src/pi/failure-context.test.ts +146 -127
  75. package/src/pi/failure-context.ts +45 -94
  76. package/src/pi/failure-path.test.ts +182 -155
  77. package/src/pi/file-commit.test.ts +156 -71
  78. package/src/pi/file-commit.ts +126 -146
  79. package/src/pi/file-snapshot.test.ts +3 -5
  80. package/src/pi/fusion-card.test.ts +26 -22
  81. package/src/pi/fusion-card.ts +16 -24
  82. package/src/pi/grep-candidates.test.ts +19 -120
  83. package/src/pi/grep-candidates.ts +25 -76
  84. package/src/pi/grep-matrix.test.ts +5 -5
  85. package/src/pi/grep-order.test.ts +16 -15
  86. package/src/pi/grep-output.ts +94 -107
  87. package/src/pi/grep-render.ts +1 -1
  88. package/src/pi/grep-reread.ts +97 -0
  89. package/src/pi/grep-rg.testing.ts +70 -0
  90. package/src/pi/grep-scope.ts +41 -43
  91. package/src/pi/grep-search.ts +27 -39
  92. package/src/pi/grep-tool.ts +63 -106
  93. package/src/pi/grep.test.ts +177 -156
  94. package/src/pi/model-budgets.test.ts +27 -24
  95. package/src/pi/model-budgets.ts +6 -38
  96. package/src/pi/mutation-outcome.testing.ts +0 -1
  97. package/src/pi/mutation-result.test.ts +44 -35
  98. package/src/pi/mutation-result.ts +52 -21
  99. package/src/pi/mutation-runner.ts +134 -74
  100. package/src/pi/output-budgets.test.ts +86 -42
  101. package/src/pi/path.ts +1 -1
  102. package/src/pi/pi.test.ts +18 -13
  103. package/src/pi/read-tool.ts +18 -23
  104. package/src/pi/read.test.ts +22 -41
  105. package/src/pi/regex-worker-contract.ts +3 -13
  106. package/src/pi/regex-worker.ts +1 -10
  107. package/src/pi/registration.test.ts +85 -51
  108. package/src/pi/render.test.ts +88 -59
  109. package/src/pi/render.ts +64 -65
  110. package/src/pi/replace-regex.ts +14 -2
  111. package/src/pi/replace-tool.ts +22 -94
  112. package/src/pi/replace-worker.ts +1 -1
  113. package/src/pi/replace.test.ts +53 -38
  114. package/src/pi/report-cause.ts +3 -8
  115. package/src/pi/report-failure.testing.ts +10 -3
  116. package/src/pi/report-schema.ts +251 -148
  117. package/src/pi/report.test.ts +215 -67
  118. package/src/pi/report.ts +50 -98
  119. package/src/pi/result-safety.test.ts +241 -247
  120. package/src/pi/rg-process.test.ts +77 -63
  121. package/src/pi/rg-process.ts +53 -75
  122. package/src/pi/rg-regex.ts +40 -400
  123. package/src/pi/schema.ts +35 -0
  124. package/src/pi/text-stream.test.ts +0 -21
  125. package/src/pi/text-stream.ts +14 -21
  126. package/src/pi/tool-factories.testing.ts +59 -0
  127. package/src/pi/write-tool.ts +36 -71
  128. package/src/pi/write.test.ts +31 -34
  129. package/src/testing/regex-translation-corpus.ts +12 -12
  130. package/src/testing/run-tests.ts +1 -1
  131. package/src/pi/replace-worker-contract.ts +0 -10
@@ -0,0 +1,38 @@
1
+ import type { AgentToolCallOutcome, AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
3
+ import type { TestContext } from "node:test";
4
+ import { createToolContext } from "./tool-call.testing.ts";
5
+
6
+ export type SessionCommand = ExtensionToolContext["executeTool"];
7
+
8
+ type CommandResult = Omit<AgentToolResult<unknown>, "details"> & {
9
+ readonly details?: unknown;
10
+ };
11
+
12
+ export function commandCompletion(
13
+ result: CommandResult,
14
+ isError = false,
15
+ terminate?: boolean,
16
+ structuredContent?: AgentToolResult<unknown>["structuredContent"],
17
+ ): AgentToolCallOutcome {
18
+ return {
19
+ toolCall: { type: "toolCall", id: "test/1", name: "bash", arguments: {} },
20
+ result: {
21
+ ...result,
22
+ details: result.details ?? {},
23
+ ...(terminate === undefined ? {} : { terminate }),
24
+ ...(structuredContent === undefined ? {} : { structuredContent }),
25
+ },
26
+ isError,
27
+ };
28
+ }
29
+
30
+ export async function createFusionContext(
31
+ cwd: string,
32
+ t: TestContext,
33
+ executeTool: ExtensionToolContext["executeTool"],
34
+ mode: ExtensionToolContext["mode"] = "json",
35
+ ) {
36
+ const context = await createToolContext(cwd, t, mode);
37
+ return { ...context, executeTool };
38
+ }
@@ -23,35 +23,31 @@
23
23
 
24
24
  import { realpath } from "node:fs/promises";
25
25
  import { basename, dirname, resolve } from "node:path";
26
- import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
26
+ import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
27
27
  import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
28
28
  import { Type, type Static, type TObject, type TProperties } from "typebox";
29
29
  import { commitFreshness, observeFreshness, type FreshnessObservation } from "./file-commit.ts";
30
30
  import {
31
+ CommandNotRun,
31
32
  commandText,
32
- finalizeMutation,
33
33
  type CommandFacts,
34
34
  type MutationOutcome,
35
35
  type MutationResultDetails,
36
36
  } from "./mutation-result.ts";
37
37
  import { errnoCode, errorMessage } from "../core/errors.ts";
38
38
  import { throwIfCancelled } from "./error-text.ts";
39
- import { causeOf, CommandNotRun, type ReportDetails } from "./report.ts";
40
- import type { OutputBudgets } from "./budgets.ts";
41
39
  import type {
42
40
  ActionFusionProgress,
43
41
  CommandResult,
44
42
  CommandStatus,
45
43
  Freshness,
46
44
  MutationToolName,
47
- SuccessReport,
48
45
  } from "./report-schema.ts";
49
- export type { ActionFusionProgress } from "./report-schema.ts";
50
46
 
51
47
  const MILLISECONDS_PER_SECOND = 1_000;
52
48
 
53
49
  // Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
54
- const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / 1_000;
50
+ const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / MILLISECONDS_PER_SECOND;
55
51
 
56
52
  // Pi's Bash runs on this host, and Pi's prompt does not name the OS; only Windows needs the path note.
57
53
  const COMMAND_DESCRIPTION =
@@ -63,13 +59,13 @@ export const ACTION_FUSION_GUIDELINES = [
63
59
  "When a check covers several changes, run it once after all of those changes.",
64
60
  ];
65
61
 
66
- type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionToolContext) => void;
62
+ type ProgressReporter = (progress: ActionFusionProgress) => void;
67
63
 
68
64
  function createThenRunSchema(tool: MutationToolName) {
69
65
  return Type.Optional(
70
66
  Type.Object(
71
67
  {
72
- command: Type.String({ minLength: 1, pattern: "\\S", description: COMMAND_DESCRIPTION }),
68
+ command: Type.String({ pattern: "\\S", description: COMMAND_DESCRIPTION }),
73
69
  timeout: Type.Optional(
74
70
  Type.Number({
75
71
  exclusiveMinimum: 0,
@@ -85,6 +81,7 @@ function createThenRunSchema(tool: MutationToolName) {
85
81
  ),
86
82
  );
87
83
  }
84
+
88
85
  /** Add the optional then_run field to a mutation schema when Action Fusion is enabled. */
89
86
  export function withThenRunSchema<P extends TProperties>(
90
87
  schema: TObject<P>,
@@ -98,6 +95,7 @@ export function withThenRunSchema<P extends TProperties>(
98
95
  )
99
96
  : schema;
100
97
  }
98
+
101
99
  export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
102
100
 
103
101
  /** Name then_run in a mutation tool's description when Action Fusion is enabled. */
@@ -107,28 +105,29 @@ export function withThenRunDescription(description: string, actionFusion: boolea
107
105
  : description;
108
106
  }
109
107
 
108
+ /** What a fused call leaves for the mutation runner to report; Fusion builds no result itself. */
109
+ export interface FusedMutation<TDetails, TTool extends MutationToolName> {
110
+ readonly outcome: MutationOutcome<TDetails, TTool>;
111
+ readonly observation: FreshnessObservation;
112
+ /** Absent when the call has no then_run. */
113
+ readonly command?: CommandFacts;
114
+ /** Preserve the session tool's request to stop after this tool batch. */
115
+ readonly terminate?: boolean;
116
+ }
117
+
110
118
  /** Keep command state independent of its diagnostic text and of file publication. */
111
- export interface CommandOutcome {
119
+ interface CommandOutcome {
112
120
  readonly status: Exclude<CommandStatus, "skipped">;
113
121
  readonly result: CommandResult;
114
122
  /** Preserve the session tool's request to stop after this tool batch. */
115
123
  readonly terminate?: boolean;
116
124
  }
117
125
 
118
- type CommandRunner = (
119
- toolCallId: string,
120
- input: ThenRunInput,
121
- signal: AbortSignal | undefined,
122
- ctx: ExtensionToolContext,
123
- onUpdate?: AgentToolUpdateCallback<unknown>,
124
- ) => Promise<CommandOutcome>;
125
-
126
- async function defaultCommandRunner(
127
- _toolCallId: string,
126
+ async function runCommand(
128
127
  input: ThenRunInput,
129
128
  signal: AbortSignal | undefined,
130
129
  ctx: ExtensionToolContext,
131
- onUpdate?: AgentToolUpdateCallback<unknown>,
130
+ onUpdate: AgentToolUpdateCallback<unknown>,
132
131
  ): Promise<CommandOutcome> {
133
132
  // Use the session's callable Bash, including overrides, validation, permission
134
133
  // hooks and tool_result hooks. Tool failures resolve with isError, not rejection.
@@ -159,29 +158,112 @@ async function defaultCommandRunner(
159
158
  }
160
159
 
161
160
  async function canonicalQueueKey(path: string): Promise<string> {
161
+ const folded = (key: string) => (process.platform === "win32" ? key.toLowerCase() : key);
162
162
  const resolved = resolve(path);
163
163
  let current = resolved;
164
164
  const missing: string[] = [];
165
165
  while (true) {
166
166
  try {
167
- const canonical = resolve(await realpath(current), ...missing);
168
- return process.platform === "win32" ? canonical.toLowerCase() : canonical;
167
+ return folded(resolve(await realpath(current), ...missing));
169
168
  } catch (error) {
170
169
  const code = errnoCode(error);
171
170
  if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
172
171
  const parent = dirname(current);
173
- if (parent === current)
174
- return process.platform === "win32" ? resolved.toLowerCase() : resolved;
172
+ if (parent === current) return folded(resolved);
175
173
  missing.unshift(basename(current));
176
174
  current = parent;
177
175
  }
178
176
  }
179
177
  }
180
178
 
181
- export function createActionFusionExecutor(
182
- commandRunner: CommandRunner = defaultCommandRunner,
183
- onProgress?: ProgressReporter,
184
- ) {
179
+ /**
180
+ * One then_run call's display state and the observers that follow it. Display callbacks are
181
+ * observers: their failures must not change publication or command execution, so the first is
182
+ * kept for the report. The tracker owns the heartbeat lifetime; Pi Bash owns timeout and
183
+ * process cleanup.
184
+ */
185
+ function createProgressTracker<TDetails extends object>({
186
+ toolCallId,
187
+ thenRun,
188
+ onProgress,
189
+ onUpdate,
190
+ }: {
191
+ toolCallId: string;
192
+ thenRun: ThenRunInput;
193
+ onProgress: ProgressReporter;
194
+ onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>> | undefined;
195
+ }) {
196
+ let mutationDetails: TDetails | undefined;
197
+ let failure: unknown;
198
+ let commandResult: CommandResult | undefined;
199
+ let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
200
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
201
+
202
+ const report = (command: ActionFusionProgress["command"], freshness: Freshness) => {
203
+ const progress: ActionFusionProgress = {
204
+ toolCallId,
205
+ commandText: thenRun.command,
206
+ command,
207
+ freshness,
208
+ ...(commandResult ? { result: commandResult } : {}),
209
+ mutationCompleted: mutationDetails !== undefined,
210
+ ...(commandTiming
211
+ ? {
212
+ timing: {
213
+ timeoutSeconds: commandTiming.timeoutSeconds,
214
+ remainingSeconds: Math.max(
215
+ 0,
216
+ Math.ceil((commandTiming.deadlineMs - Date.now()) / MILLISECONDS_PER_SECOND),
217
+ ),
218
+ },
219
+ }
220
+ : {}),
221
+ };
222
+ for (const notify of [
223
+ () => onProgress(progress),
224
+ () => onUpdate?.({ content: [], details: { ...mutationDetails, actionFusion: progress } }),
225
+ ]) {
226
+ try {
227
+ notify();
228
+ } catch (error) {
229
+ failure ??= error;
230
+ }
231
+ }
232
+ };
233
+
234
+ /** Follow the running command's partial results. */
235
+ const followCommand: AgentToolUpdateCallback<unknown> = (partial) => {
236
+ // Pi Bash emits an initial update even for silent commands. Start its
237
+ // countdown here, after session permission hooks have allowed execution.
238
+ if (!commandTiming && thenRun.timeout !== undefined) {
239
+ commandTiming = {
240
+ timeoutSeconds: thenRun.timeout,
241
+ deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
242
+ };
243
+ heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
244
+ heartbeat.unref();
245
+ }
246
+ commandResult = { content: partial.content, details: partial.details };
247
+ report("running", "unknown");
248
+ };
249
+
250
+ return {
251
+ report,
252
+ followCommand,
253
+ failure: () => failure,
254
+ mutationCompleted(details: TDetails) {
255
+ mutationDetails = details;
256
+ },
257
+ stopHeartbeat() {
258
+ if (heartbeat) clearInterval(heartbeat);
259
+ },
260
+ commandSettled(result: CommandResult) {
261
+ commandResult = result;
262
+ },
263
+ };
264
+ }
265
+
266
+ export function createActionFusionExecutor(onProgress: ProgressReporter) {
185
267
  const queueTails = new Map<string, Promise<void>>();
186
268
 
187
269
  async function withQueue<T>(path: string, work: () => Promise<T>): Promise<T> {
@@ -204,153 +286,96 @@ export function createActionFusionExecutor(
204
286
 
205
287
  return async function execute<TDetails extends object, TTool extends MutationToolName>({
206
288
  toolCallId,
207
- tool,
208
- displayPath,
209
289
  absolutePath,
210
290
  thenRun,
211
- budget,
212
291
  mutate,
213
292
  signal,
214
293
  ctx,
215
294
  onUpdate,
216
295
  }: {
217
296
  toolCallId: string;
218
- tool: TTool;
219
- /** The caller-supplied path, as the report states it. */
220
- displayPath: string;
221
297
  absolutePath: string;
222
298
  thenRun: ThenRunInput | undefined;
223
- budget: OutputBudgets;
224
- mutate: () => Promise<MutationOutcome<TDetails, NoInfer<TTool>>>;
299
+ mutate: () => Promise<MutationOutcome<TDetails, TTool>>;
225
300
  signal: AbortSignal | undefined;
226
301
  ctx: ExtensionToolContext;
227
302
  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;
232
- let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
233
- const report = (command: ActionFusionProgress["command"], freshness: Freshness) => {
234
- if (!thenRun) return;
235
- const progress: ActionFusionProgress = {
236
- toolCallId,
237
- commandText: thenRun.command,
238
- command,
239
- freshness,
240
- ...(commandResult ? { result: commandResult } : {}),
241
- mutationCompleted: completedMutation !== undefined,
242
- ...(commandTiming
243
- ? {
244
- timing: {
245
- timeoutSeconds: commandTiming.timeoutSeconds,
246
- remainingSeconds: Math.max(
247
- 0,
248
- Math.ceil((commandTiming.deadlineMs - Date.now()) / MILLISECONDS_PER_SECOND),
249
- ),
250
- },
251
- }
252
- : {}),
253
- };
254
- // Display callbacks are observers: their failures must not change publication or command execution.
255
- for (const notify of [
256
- () => onProgress?.(progress, ctx),
257
- () =>
258
- onUpdate?.({
259
- content: [],
260
- details: { ...completedMutation?.details, actionFusion: progress },
261
- }),
262
- ]) {
263
- try {
264
- notify();
265
- } catch (error) {
266
- progressFailure ??= error;
267
- }
268
- }
269
- };
303
+ }): Promise<FusedMutation<TDetails, TTool>> {
304
+ // Without a command, the mutation still waits for a fused call on the same file.
305
+ if (thenRun === undefined) {
306
+ return withQueue(absolutePath, async () => {
307
+ throwIfCancelled(signal);
308
+ const outcome = await mutate();
309
+ return { outcome, observation: commitFreshness(outcome.commit) };
310
+ });
311
+ }
312
+
313
+ const progress = createProgressTracker<TDetails>({
314
+ toolCallId,
315
+ thenRun,
316
+ onProgress,
317
+ onUpdate,
318
+ });
270
319
  /** A mutation that did not complete keeps its own failure; Fusion adds only the command status. */
271
320
  const notRun = (error: unknown, command: "skipped" | "cancelled") => {
272
- report(command, "unknown");
273
- return new CommandNotRun(error, command, causeOf(progressFailure, budget.fieldBytes));
321
+ progress.report(command, "unknown");
322
+ return new CommandNotRun(error, command, progress.failure());
274
323
  };
275
- report("waiting", "unknown");
276
- let terminate: boolean | undefined;
277
- const result = await withQueue(absolutePath, async () => {
324
+ progress.report("waiting", "unknown");
325
+ return withQueue(absolutePath, async () => {
278
326
  try {
279
327
  throwIfCancelled(signal);
280
328
  } catch (error) {
281
- if (thenRun !== undefined) throw notRun(error, "cancelled");
282
- throw error;
329
+ throw notRun(error, "cancelled");
283
330
  }
284
331
  let outcome: MutationOutcome<TDetails, TTool>;
285
332
  try {
286
333
  outcome = await mutate();
287
- completedMutation = outcome;
334
+ progress.mutationCompleted(outcome.details);
288
335
  } catch (error) {
289
- if (thenRun !== undefined) throw notRun(error, "skipped");
290
- throw error;
336
+ throw notRun(error, "skipped");
291
337
  }
292
338
 
293
339
  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,
340
+ progress.report("waiting", "unknown");
341
+ const settle = (observation: FreshnessObservation, command: CommandFacts) => {
342
+ progress.report(command.status, observation.freshness);
343
+ return {
301
344
  outcome,
302
345
  observation,
303
- command && { ...command, progressError: progressFailure },
304
- budget,
305
- );
346
+ command: { ...command, progressError: progress.failure() },
347
+ };
306
348
  };
307
- if (thenRun === undefined) return settle(commitFreshness(outcome.commit));
308
349
 
309
350
  // A completed mutation remains successful; the command is only started on a fresh target.
310
351
  const before = await observeFreshness(absolutePath, publishedRevision, true);
311
352
  if (signal?.aborted) return settle(before, { status: "cancelled" });
312
353
  if (before.freshness !== "unchanged") return settle(before, { status: "skipped" });
313
354
 
314
- report("running", "unchanged");
355
+ progress.report("running", "unchanged");
315
356
  let command: CommandOutcome;
316
- // The executor owns the heartbeat lifetime; Pi Bash owns timeout and process cleanup.
317
- let heartbeat: ReturnType<typeof setInterval> | undefined;
318
357
  try {
319
- command = await commandRunner(toolCallId, thenRun, signal, ctx, (partial) => {
320
- // Pi Bash emits an initial update even for silent commands. Start its
321
- // countdown here, after session permission hooks have allowed execution.
322
- if (!commandTiming && thenRun.timeout !== undefined) {
323
- commandTiming = {
324
- timeoutSeconds: thenRun.timeout,
325
- deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
326
- };
327
- if (onProgress || onUpdate) {
328
- heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
329
- heartbeat.unref();
330
- }
331
- }
332
- commandResult = { content: partial.content, details: partial.details };
333
- report("running", "unknown");
334
- });
358
+ command = await runCommand(thenRun, signal, ctx, progress.followCommand);
335
359
  } catch (error) {
336
360
  command = {
337
361
  status: signal?.aborted ? "cancelled" : "failed",
338
362
  result: { content: [{ type: "text", text: errorMessage(error) }] },
339
363
  };
340
364
  } finally {
341
- if (heartbeat) clearInterval(heartbeat);
365
+ progress.stopHeartbeat();
342
366
  }
343
- commandResult = command.result;
344
- terminate = command.terminate;
345
- return settle(await observeFreshness(absolutePath, publishedRevision), {
367
+ progress.commandSettled(command.result);
368
+ const settled = settle(await observeFreshness(absolutePath, publishedRevision), {
346
369
  status: command.status,
347
370
  result: command.result,
348
371
  });
372
+ return command.terminate === undefined
373
+ ? settled
374
+ : { ...settled, terminate: command.terminate };
349
375
  }).catch((error: unknown) => {
350
376
  // Failures before the mutation started (such as resolving the queue key) also skip the command.
351
- if (thenRun === undefined || error instanceof CommandNotRun) throw error;
377
+ if (error instanceof CommandNotRun) throw error;
352
378
  throw notRun(error, "skipped");
353
379
  });
354
- return terminate === undefined ? result : { ...result, terminate };
355
380
  };
356
381
  }
@@ -10,22 +10,22 @@ import {
10
10
  plainRow,
11
11
  } from "./anchor-format.ts";
12
12
 
13
+ function token(line: number, content: string, hashLen: number): string {
14
+ return createAnchorFormatter(hashLen).reference(line, computeLineHash(line, content, hashLen));
15
+ }
16
+
13
17
  test("anchor formatter binds the supplied hash length and hashes undisplayed content", () => {
14
18
  const formatter = createAnchorFormatter(6);
15
- const shortFormatter = createAnchorFormatter(4);
16
19
 
17
- assert.equal(formatter.token(3, "full content"), `3#${computeLineHash(3, "full content", 6)}`);
20
+ assert.equal(token(3, "full content", 6), `3#${computeLineHash(3, "full content", 6)}`);
18
21
  assert.equal(formatter.reference(3, "ABCDEF"), "3#ABCDEF");
19
- assert.match(formatter.token(3, "full content"), new RegExp(anchorPattern(6)));
20
- assert.doesNotMatch(formatter.token(3, "full content"), new RegExp(anchorPattern(4)));
22
+ assert.match(token(3, "full content", 6), new RegExp(anchorPattern(6)));
23
+ assert.doesNotMatch(token(3, "full content", 6), new RegExp(anchorPattern(4)));
21
24
  assert.equal(
22
25
  formatter.row(3, "full content", "full…"),
23
26
  `3#${computeLineHash(3, "full content", 6)}│full…`,
24
27
  );
25
- assert.equal(
26
- shortFormatter.token(3, "full content"),
27
- `3#${computeLineHash(3, "full content", 4)}`,
28
- );
28
+ assert.equal(token(3, "full content", 4), `3#${computeLineHash(3, "full content", 4)}`);
29
29
  });
30
30
 
31
31
  test("anchor tokens parse at any hash length so wrong lengths can be explained", () => {
@@ -38,7 +38,7 @@ test("anchor tokens parse at any hash length so wrong lengths can be explained",
38
38
  test("anchor rows expose carriage returns while checksums retain source content", () => {
39
39
  const formatter = createAnchorFormatter(4);
40
40
  assert.equal(formatter.row(1, "a\rb"), `1#${computeLineHash(1, "a\rb", 4)}│a␍b`);
41
- assert.notEqual(formatter.token(1, "a\rb"), formatter.token(1, "a␍b"));
41
+ assert.notEqual(token(1, "a\rb", 4), token(1, "a␍b", 4));
42
42
  });
43
43
 
44
44
  test("anchor syntax rejects characters absent from the checksum alphabet", () => {
@@ -9,8 +9,10 @@
9
9
 
10
10
  import { computeLineHash, HASH_ALPHABET, HASH_LEN_MIN, HASH_LEN_MAX } from "../core/hash.ts";
11
11
 
12
+ const LINE_NUMBER = "([1-9][0-9]*)";
13
+
12
14
  function anchorSource(hashQuantifier: string): string {
13
- return `([1-9][0-9]*)#([${HASH_ALPHABET}]${hashQuantifier})`;
15
+ return `${LINE_NUMBER}#([${HASH_ALPHABET}]${hashQuantifier})`;
14
16
  }
15
17
 
16
18
  /** Schema pattern for a `LINE#HASH` anchor whose hash has exactly `hashLen` characters. */
@@ -32,7 +34,7 @@ const HASHLINE_ROW = new RegExp(
32
34
  /** Split a `LINE#HASH` token of any hash length; undefined when the shape is wrong. */
33
35
  export function parseAnchorToken(value: string): { line: number; hash: string } | undefined {
34
36
  const match = ANCHOR_TOKEN.exec(value);
35
- return match ? { line: Number(match[1]), hash: match[2]! } : undefined;
37
+ return match ? { line: Number(match[1]), hash: match[2] } : undefined;
36
38
  }
37
39
 
38
40
  interface HashlineRow {
@@ -48,7 +50,7 @@ export function parseHashline(line: string): HashlineRow | null {
48
50
  return match ? { lineNo: match[1], content: match[3] } : null;
49
51
  }
50
52
 
51
- const PLAIN_ROW = new RegExp(`^([1-9][0-9]*)${ROW_SEPARATOR}(.*)$`, "s");
53
+ const PLAIN_ROW = new RegExp(`^${LINE_NUMBER}${ROW_SEPARATOR}(.*)$`, "s");
52
54
 
53
55
  /** Parse an anchored row or a non-editable `LINE│content` row; null for other text. */
54
56
  export function parseDisplayRow(line: string): HashlineRow | null {
@@ -61,7 +63,6 @@ export function parseDisplayRow(line: string): HashlineRow | null {
61
63
  /** Anchor serialization bound to a caller-supplied hash length. */
62
64
  export interface AnchorFormatter {
63
65
  reference(line: number, hash: string): string;
64
- token(line: number, content: string): string;
65
66
  row(line: number, content: string, displayContent?: string): string;
66
67
  }
67
68
 
@@ -77,12 +78,9 @@ export function plainRow(line: number, displayContent: string): string {
77
78
 
78
79
  export function createAnchorFormatter(hashLen: number): AnchorFormatter {
79
80
  const reference = (line: number, hash: string) => `${line}#${hash}`;
80
- const token = (line: number, content: string) =>
81
- reference(line, computeLineHash(line, content, hashLen));
82
81
  return {
83
- token,
84
82
  reference,
85
83
  row: (line, content, displayContent = content) =>
86
- `${token(line, content)}${ROW_SEPARATOR}${displayCarriageReturns(displayContent)}`,
84
+ `${reference(line, computeLineHash(line, content, hashLen))}${ROW_SEPARATOR}${displayCarriageReturns(displayContent)}`,
87
85
  };
88
86
  }
@@ -61,19 +61,6 @@ function projectValueSchema(
61
61
  projection.applicable.add(path);
62
62
  return Type.Unknown({ enum: [...new Set(choices)] });
63
63
  }
64
- const typed = schema.anyOf.filter((branch) => "type" in branch);
65
- if (typed.length === schema.anyOf.length) {
66
- const matches = typed.filter(
67
- (branch) => "type" in branch && Value.Check(Type.Unknown({ type: branch.type }), value),
68
- );
69
- if (matches.length === 1) return projectSchema(matches[0], value, path, projection);
70
- if (matches.length === 0) {
71
- const types = typed.flatMap((branch) =>
72
- "type" in branch ? (Array.isArray(branch.type) ? branch.type : [branch.type]) : [],
73
- );
74
- return Type.Unknown({ type: [...new Set(types)] });
75
- }
76
- }
77
64
  return schema;
78
65
  }
79
66
  if ("type" in schema && !Value.Check(Type.Unknown({ type: schema.type }), value)) return schema;
@@ -119,14 +106,15 @@ function pointerParts(pointer: string): readonly string[] {
119
106
  }
120
107
 
121
108
  /**
122
- * The projection path of the value at `pointer`; the root is "". Pi's TypeBox leaves `/` and
123
- * `~` in property names unescaped, so a name spans the fewest segments that form an own key,
124
- * read escaped or as is.
109
+ * The projection paths of the value at `pointer` and of its parent; the root is "". Pi's TypeBox
110
+ * leaves `/` and `~` in property names unescaped, so a name spans the fewest segments that form
111
+ * an own key, read escaped or as is.
125
112
  */
126
- function valuePath(pointer: string, prepared: unknown): string {
113
+ function valuePaths(pointer: string, prepared: unknown): { path: string; parent: string } {
127
114
  const segments = pointer.split("/").slice(1);
128
115
  let value = prepared;
129
116
  let path = "";
117
+ let parent = "";
130
118
  for (let index = 0; index < segments.length; index++) {
131
119
  let part = unescapePointer(segments[index]);
132
120
  if (typeof value === "object" && value !== null && !Array.isArray(value)) {
@@ -141,14 +129,15 @@ function valuePath(pointer: string, prepared: unknown): string {
141
129
  }
142
130
  }
143
131
  }
132
+ parent = path;
144
133
  path = Array.isArray(value) ? `${path}[${part}]` : propertyPath(path, part);
145
134
  value = typeof value === "object" && value !== null ? Reflect.get(value, part) : undefined;
146
135
  }
147
- return path;
136
+ return { path, parent };
148
137
  }
149
138
 
150
139
  function fieldPath(pointer: string, prepared: unknown, key?: string): string {
151
- const path = valuePath(pointer, prepared);
140
+ const { path } = valuePaths(pointer, prepared);
152
141
  return (key === undefined ? path : propertyPath(path, key)) || "$";
153
142
  }
154
143
 
@@ -181,8 +170,8 @@ function fieldExplanation(schema: TSchema, parts: readonly string[]): string | u
181
170
  }
182
171
 
183
172
  /** Why a field is not allowed: the fields its object declares. */
184
- function shapeExplanation(object: TObject): string {
185
- return `Accepted fields: ${Object.keys(object.properties).join(", ")}.`;
173
+ function shapeExplanation(object: TObject | undefined): string | undefined {
174
+ return object && `Accepted fields: ${Object.keys(object.properties).join(", ")}.`;
186
175
  }
187
176
 
188
177
  /** One issue per field: distinct reasons joined, and distinct fixes joined, each in report order. */
@@ -203,9 +192,9 @@ function combineIssues(issues: readonly ArgumentIssue[]): readonly ArgumentIssue
203
192
 
204
193
  /**
205
194
  * One issue per native error. Reasons that do not say how to correct the value
206
- * carry a fix derived from the declared schema: a missing field and a pattern
207
- * mismatch explain the field, and a field that is not allowed lists its
208
- * object's declared fields.
195
+ * carry a fix derived from the declared schema: a missing field, a pattern
196
+ * mismatch, and a value outside the field's choices explain the field, and a
197
+ * field that is not allowed lists its object's declared fields.
209
198
  */
210
199
  function aggregateErrors(
211
200
  errors: readonly TLocalizedValidationError[],
@@ -229,8 +218,8 @@ function aggregateErrors(
229
218
  break;
230
219
  }
231
220
  case "additionalProperties": {
232
- const shape = objects.get(valuePath(error.instancePath, prepared));
233
- const fix = shape && shapeExplanation(shape);
221
+ const { path } = valuePaths(error.instancePath, prepared);
222
+ const fix = shapeExplanation(objects.get(path));
234
223
  for (const key of error.params.additionalProperties)
235
224
  add(fieldPath(error.instancePath, prepared, key), "is not allowed", fix);
236
225
  break;
@@ -242,13 +231,21 @@ function aggregateErrors(
242
231
  fieldExplanation(parameters, pointerParts(error.instancePath)),
243
232
  );
244
233
  break;
245
- case "boolean":
246
- add(fieldPath(error.instancePath, prepared), "is not allowed");
234
+ case "boolean": {
235
+ // Once TypeBox's error capacity ends before `additionalProperties`, this is the only report.
236
+ const { parent } = valuePaths(error.instancePath, prepared);
237
+ add(
238
+ fieldPath(error.instancePath, prepared),
239
+ "is not allowed",
240
+ shapeExplanation(objects.get(parent)),
241
+ );
247
242
  break;
243
+ }
248
244
  case "enum":
249
245
  add(
250
246
  fieldPath(error.instancePath, prepared),
251
247
  `expected one of: ${error.params.allowedValues.map((value) => JSON.stringify(value)).join(", ")}`,
248
+ fieldExplanation(parameters, pointerParts(error.instancePath)),
252
249
  );
253
250
  break;
254
251
  default: