@criogaid/pi-hashline-edit 0.7.0 → 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 (118) hide show
  1. package/README.md +74 -222
  2. package/README.zh-CN.md +162 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +172 -134
  6. package/src/core/apply.ts +28 -30
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +41 -9
  14. package/src/core/ranges.ts +11 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +5 -7
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +16 -8
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +127 -87
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +3 -4
  34. package/src/integration/model-budget-lifecycle.test.ts +15 -6
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +1 -1
  37. package/src/integration/npm-package.testing.ts +6 -32
  38. package/src/integration/publication-read-changes.test.ts +58 -26
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +2 -2
  42. package/src/integration/utf8-errors.test.ts +2 -2
  43. package/src/pi/AGENTS.md +12 -13
  44. package/src/pi/action-fusion.test.ts +71 -216
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +1 -1
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +5 -16
  52. package/src/pi/argument-validation.test.ts +59 -25
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +9 -12
  60. package/src/pi/execute.test.ts +80 -149
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +12 -9
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +270 -169
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +25 -16
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +4 -5
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +54 -49
  92. package/src/pi/render.test.ts +196 -93
  93. package/src/pi/render.ts +32 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +27 -26
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +55 -43
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +157 -117
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -26,13 +26,9 @@ import { basename, dirname, resolve } from "node:path";
26
26
  import type { AgentToolResult, 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
+ import { commitFreshness, observeFreshness, type FreshnessObservation } from "./file-commit.ts";
29
30
  import {
30
- commitFreshness,
31
- FileMutationError,
32
- observeFreshness,
33
- type FreshnessObservation,
34
- } from "./file-commit.ts";
35
- import {
31
+ commandText,
36
32
  finalizeMutation,
37
33
  type CommandFacts,
38
34
  type MutationOutcome,
@@ -41,13 +37,13 @@ import {
41
37
  import { errnoCode, errorMessage } from "../core/errors.ts";
42
38
  import { throwIfCancelled } from "./error-text.ts";
43
39
  import { causeOf, CommandNotRun, type ReportDetails } from "./report.ts";
44
- import { DEFAULT_OUTPUT_BUDGETS, type OutputBudgets } from "./budgets.ts";
40
+ import type { OutputBudgets } from "./budgets.ts";
45
41
  import type {
46
42
  ActionFusionProgress,
43
+ CommandResult,
47
44
  CommandStatus,
48
45
  Freshness,
49
46
  MutationToolName,
50
- PublicationStatus,
51
47
  SuccessReport,
52
48
  } from "./report-schema.ts";
53
49
  export type { ActionFusionProgress } from "./report-schema.ts";
@@ -64,22 +60,12 @@ const COMMAND_DESCRIPTION =
64
60
  : "Bash command to run.";
65
61
 
66
62
  export const ACTION_FUSION_GUIDELINES = [
67
- "Before each file mutation, identify its next command.",
68
- "then_run is a parameter of edit, replace, and write, not a separate tool.",
69
- "Check the command outcome before claiming validation passed.",
63
+ "When a check covers several changes, run it once after all of those changes.",
70
64
  ];
71
65
 
72
- export interface ActionFusionDetails {
73
- readonly publication: PublicationStatus;
74
- readonly command: CommandStatus | "not_requested";
75
- readonly freshness: Freshness;
76
- }
77
-
78
66
  type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionToolContext) => void;
79
67
 
80
- /** The tools that accept then_run. */
81
-
82
- export function createThenRunSchema(tool: MutationToolName) {
68
+ function createThenRunSchema(tool: MutationToolName) {
83
69
  return Type.Optional(
84
70
  Type.Object(
85
71
  {
@@ -88,7 +74,7 @@ export function createThenRunSchema(tool: MutationToolName) {
88
74
  Type.Number({
89
75
  exclusiveMinimum: 0,
90
76
  maximum: MAX_BASH_TIMEOUT_SECONDS,
91
- description: "Timeout in seconds (optional, no default timeout)",
77
+ description: "Timeout in seconds; none when omitted.",
92
78
  }),
93
79
  ),
94
80
  },
@@ -117,14 +103,14 @@ export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSch
117
103
  /** Name then_run in a mutation tool's description when Action Fusion is enabled. */
118
104
  export function withThenRunDescription(description: string, actionFusion: boolean): string {
119
105
  return actionFusion
120
- ? `${description} If a command such as tests, a typecheck, or a build should run right after this change, set then_run instead of calling bash separately, unless the command needs the user's approval, depends on this call's result, must wait for a reload, or checks several changes sent in the same response; run that check once with bash after them.`
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.`
121
107
  : description;
122
108
  }
123
109
 
124
110
  /** Keep command state independent of its diagnostic text and of file publication. */
125
111
  export interface CommandOutcome {
126
112
  readonly status: Exclude<CommandStatus, "skipped">;
127
- readonly output: string;
113
+ readonly result: CommandResult;
128
114
  /** Preserve the session tool's request to stop after this tool batch. */
129
115
  readonly terminate?: boolean;
130
116
  }
@@ -137,11 +123,6 @@ type CommandRunner = (
137
123
  onUpdate?: AgentToolUpdateCallback<unknown>,
138
124
  ) => Promise<CommandOutcome>;
139
125
 
140
- /** Publication of a mutation failure, for progress reports; the failure report states it to the model. */
141
- function publicationOf(error: unknown): PublicationStatus {
142
- return error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED";
143
- }
144
-
145
126
  async function defaultCommandRunner(
146
127
  _toolCallId: string,
147
128
  input: ThenRunInput,
@@ -152,11 +133,10 @@ async function defaultCommandRunner(
152
133
  // Use the session's callable Bash, including overrides, validation, permission
153
134
  // hooks and tool_result hooks. Tool failures resolve with isError, not rejection.
154
135
  const { result, isError } = await ctx.executeTool("bash", input, { signal, onUpdate });
155
- const output = result.content
156
- .filter((block) => block.type === "text")
157
- .map((block) => block.text)
158
- .join("\n");
159
- const command = { output, terminate: result.terminate };
136
+ const command = {
137
+ terminate: result.terminate,
138
+ result: { content: result.content, details: result.details },
139
+ };
160
140
  if (!isError) return { status: "succeeded", ...command };
161
141
  if (signal?.aborted) return { status: "cancelled", ...command };
162
142
 
@@ -170,6 +150,7 @@ async function defaultCommandRunner(
170
150
  // timeout as text. Only recognize its final diagnostic for the requested
171
151
  // timeout; a failed command's output may itself mention or quote a timeout.
172
152
  const timeoutDiagnostic = `Command timed out after ${input.timeout} seconds`;
153
+ const output = commandText(result.content);
173
154
  const timedOut =
174
155
  !hasExitCode &&
175
156
  input.timeout !== undefined &&
@@ -227,7 +208,7 @@ export function createActionFusionExecutor(
227
208
  displayPath,
228
209
  absolutePath,
229
210
  thenRun,
230
- budget = DEFAULT_OUTPUT_BUDGETS,
211
+ budget,
231
212
  mutate,
232
213
  signal,
233
214
  ctx,
@@ -239,32 +220,24 @@ export function createActionFusionExecutor(
239
220
  displayPath: string;
240
221
  absolutePath: string;
241
222
  thenRun: ThenRunInput | undefined;
242
- budget?: OutputBudgets;
223
+ budget: OutputBudgets;
243
224
  mutate: () => Promise<MutationOutcome<TDetails, NoInfer<TTool>>>;
244
225
  signal: AbortSignal | undefined;
245
226
  ctx: ExtensionToolContext;
246
227
  onUpdate?: AgentToolUpdateCallback<MutationResultDetails<TDetails>>;
247
- }): Promise<
248
- AgentToolResult<TDetails & ReportDetails<SuccessReport> & { actionFusion: ActionFusionDetails }>
249
- > {
228
+ }): Promise<AgentToolResult<TDetails & ReportDetails<SuccessReport>>> {
250
229
  let completedMutation: MutationOutcome<TDetails, TTool> | undefined;
251
230
  let progressFailure: unknown;
231
+ let commandResult: CommandResult | undefined;
252
232
  let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
253
- const report = (
254
- command: ActionFusionProgress["command"],
255
- publication: PublicationStatus,
256
- freshness: Freshness,
257
- output = "",
258
- ) => {
233
+ const report = (command: ActionFusionProgress["command"], freshness: Freshness) => {
259
234
  if (!thenRun) return;
260
235
  const progress: ActionFusionProgress = {
261
236
  toolCallId,
262
- path: absolutePath,
263
237
  commandText: thenRun.command,
264
238
  command,
265
- publication,
266
239
  freshness,
267
- output,
240
+ ...(commandResult ? { result: commandResult } : {}),
268
241
  mutationCompleted: completedMutation !== undefined,
269
242
  ...(commandTiming
270
243
  ? {
@@ -296,10 +269,10 @@ export function createActionFusionExecutor(
296
269
  };
297
270
  /** A mutation that did not complete keeps its own failure; Fusion adds only the command status. */
298
271
  const notRun = (error: unknown, command: "skipped" | "cancelled") => {
299
- report(command, publicationOf(error), "unknown");
272
+ report(command, "unknown");
300
273
  return new CommandNotRun(error, command, causeOf(progressFailure, budget.fieldBytes));
301
274
  };
302
- report("waiting", "NOT_PUBLISHED", "unknown");
275
+ report("waiting", "unknown");
303
276
  let terminate: boolean | undefined;
304
277
  const result = await withQueue(absolutePath, async () => {
305
278
  try {
@@ -317,11 +290,12 @@ export function createActionFusionExecutor(
317
290
  throw error;
318
291
  }
319
292
 
320
- const { publication, publishedRevision } = outcome.commit;
321
- report("waiting", publication, "unknown");
293
+ const { publishedRevision } = outcome.commit;
294
+ report("waiting", "unknown");
322
295
  const settle = (observation: FreshnessObservation, command?: CommandFacts) => {
323
- if (command) report(command.status, publication, observation.freshness, command.output);
324
- const settled = finalizeMutation(
296
+ if (command) report(command.status, observation.freshness);
297
+ // The report states publication, freshness, and the command status once.
298
+ return finalizeMutation(
325
299
  tool,
326
300
  displayPath,
327
301
  outcome,
@@ -329,12 +303,6 @@ export function createActionFusionExecutor(
329
303
  command && { ...command, progressError: progressFailure },
330
304
  budget,
331
305
  );
332
- const actionFusion: ActionFusionDetails = {
333
- publication,
334
- command: command?.status ?? "not_requested",
335
- freshness: observation.freshness,
336
- };
337
- return { ...settled, details: { ...settled.details, actionFusion } };
338
306
  };
339
307
  if (thenRun === undefined) return settle(commitFreshness(outcome.commit));
340
308
 
@@ -343,8 +311,7 @@ export function createActionFusionExecutor(
343
311
  if (signal?.aborted) return settle(before, { status: "cancelled" });
344
312
  if (before.freshness !== "unchanged") return settle(before, { status: "skipped" });
345
313
 
346
- report("running", publication, "unchanged");
347
- let output = "";
314
+ report("running", "unchanged");
348
315
  let command: CommandOutcome;
349
316
  // The executor owns the heartbeat lifetime; Pi Bash owns timeout and process cleanup.
350
317
  let heartbeat: ReturnType<typeof setInterval> | undefined;
@@ -358,30 +325,26 @@ export function createActionFusionExecutor(
358
325
  deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
359
326
  };
360
327
  if (onProgress || onUpdate) {
361
- heartbeat = setInterval(
362
- () => report("running", publication, "unknown", output),
363
- MILLISECONDS_PER_SECOND,
364
- );
328
+ heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
365
329
  heartbeat.unref();
366
330
  }
367
331
  }
368
- output = partial.content
369
- .filter((block) => block.type === "text")
370
- .map((block) => block.text)
371
- .join("\n");
372
- report("running", publication, "unknown", output);
332
+ commandResult = { content: partial.content, details: partial.details };
333
+ report("running", "unknown");
373
334
  });
374
- output = command.output;
375
335
  } catch (error) {
376
- output = errorMessage(error);
377
- command = { status: signal?.aborted ? "cancelled" : "failed", output };
336
+ command = {
337
+ status: signal?.aborted ? "cancelled" : "failed",
338
+ result: { content: [{ type: "text", text: errorMessage(error) }] },
339
+ };
378
340
  } finally {
379
341
  if (heartbeat) clearInterval(heartbeat);
380
342
  }
343
+ commandResult = command.result;
381
344
  terminate = command.terminate;
382
345
  return settle(await observeFreshness(absolutePath, publishedRevision), {
383
346
  status: command.status,
384
- output,
347
+ result: command.result,
385
348
  });
386
349
  }).catch((error: unknown) => {
387
350
  // Failures before the mutation started (such as resolving the queue key) also skip the command.
@@ -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
+ });
@@ -18,11 +18,15 @@ export function anchorPattern(hashLen: number): string {
18
18
  return `^${anchorSource(`{${hashLen}}`)}$`;
19
19
  }
20
20
 
21
- /** 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
+ */
22
25
  const ROW_SEPARATOR = "│";
23
26
  const ANCHOR_TOKEN = new RegExp(`^${anchorSource("+")}$`);
24
27
  const HASHLINE_ROW = new RegExp(
25
28
  `^${anchorSource(`{${HASH_LEN_MIN},${HASH_LEN_MAX}}`)}${ROW_SEPARATOR}(.*)$`,
29
+ "s",
26
30
  );
27
31
 
28
32
  /** Split a `LINE#HASH` token of any hash length; undefined when the shape is wrong. */
@@ -31,7 +35,7 @@ export function parseAnchorToken(value: string): { line: number; hash: string }
31
35
  return match ? { line: Number(match[1]), hash: match[2]! } : undefined;
32
36
  }
33
37
 
34
- export interface HashlineRow {
38
+ interface HashlineRow {
35
39
  /** Line number as written in the anchor (string form). */
36
40
  lineNo: string;
37
41
  /** Line content with the `LINE#HASH│` prefix removed. */
@@ -44,7 +48,7 @@ export function parseHashline(line: string): HashlineRow | null {
44
48
  return match ? { lineNo: match[1], content: match[3] } : null;
45
49
  }
46
50
 
47
- const PLAIN_ROW = new RegExp(`^([1-9][0-9]*)${ROW_SEPARATOR}(.*)$`);
51
+ const PLAIN_ROW = new RegExp(`^([1-9][0-9]*)${ROW_SEPARATOR}(.*)$`, "s");
48
52
 
49
53
  /** Parse an anchored row or a non-editable `LINE│content` row; null for other text. */
50
54
  export function parseDisplayRow(line: string): HashlineRow | null {
@@ -17,7 +17,7 @@ import type { TLocalizedValidationError } from "typebox/error";
17
17
  import { Value } from "typebox/value";
18
18
  import type { ArgumentIssue } from "./report-schema.ts";
19
19
 
20
- export interface ArgumentDiagnostics {
20
+ interface ArgumentDiagnostics {
21
21
  readonly issues: readonly ArgumentIssue[];
22
22
  readonly limited: boolean;
23
23
  }
@@ -1,7 +1,10 @@
1
1
  import assert from "node:assert/strict";
2
2
  import type { ArgumentIssue, Report } from "./report-schema.ts";
3
3
 
4
- type ArgumentRejection = Report & { error: "INVALID_ARGUMENTS"; issues: ArgumentIssue[] };
4
+ type ArgumentRejection = Omit<Report, "tool" | "path"> & {
5
+ error: "INVALID_ARGUMENTS";
6
+ issues: ArgumentIssue[];
7
+ };
5
8
 
6
9
  /** Assert the model-facing JSON contract before inspecting an individual rejection. */
7
10
  export function argumentError(error: unknown): ArgumentRejection {
@@ -9,7 +12,8 @@ export function argumentError(error: unknown): ArgumentRejection {
9
12
  const value: unknown = JSON.parse(error.message);
10
13
  assert.ok(typeof value === "object" && value !== null);
11
14
  assert.equal(Reflect.get(value, "error"), "INVALID_ARGUMENTS");
12
- assert.equal(typeof Reflect.get(value, "tool"), "string");
15
+ assert.equal(Object.hasOwn(value, "tool"), false);
16
+ assert.equal(Object.hasOwn(value, "path"), false);
13
17
  const issues: unknown = Reflect.get(value, "issues");
14
18
  assert.ok(Array.isArray(issues));
15
19
  for (const issue of issues) {
@@ -33,10 +37,9 @@ export function rejectsArgument(field: string, reason: RegExp = /./) {
33
37
  };
34
38
  }
35
39
 
36
- export function rejectsArguments(tool: string) {
40
+ export function rejectsArguments() {
37
41
  return (error: unknown): boolean => {
38
42
  const result = argumentError(error);
39
- assert.equal(result.tool, tool);
40
43
  assert.ok(result.issues.length > 0);
41
44
  return true;
42
45
  };
@@ -3,11 +3,11 @@
3
3
  * with field issues within one byte budget. Pi raises it before execution,
4
4
  * so it travels as the thrown message only. Oversized issues are omitted whole.
5
5
  */
6
- import { DEFAULT_OUTPUT_BUDGETS, type OutputBudgets } from "./budgets.ts";
7
- import { boundedText, renderReport } from "./report.ts";
8
- import type { ArgumentIssue, FailureReport, ReportTool } from "./report-schema.ts";
6
+ import type { OutputBudgets } from "./budgets.ts";
7
+ import { boundedText, renderReport, type ReportText } from "./report.ts";
8
+ import type { ArgumentIssue, FailureReport } from "./report-schema.ts";
9
9
 
10
- type ArgumentRejection = Extract<FailureReport, { error: "INVALID_ARGUMENTS" }>;
10
+ type ArgumentRejection = ReportText<Extract<FailureReport, { error: "INVALID_ARGUMENTS" }>>;
11
11
 
12
12
  /**
13
13
  * State each distinct fix once, on the first reported issue that needs it:
@@ -29,10 +29,9 @@ function encode(report: ArgumentRejection): string {
29
29
 
30
30
  /** Encode actionable field diagnostics without repeating the call's arguments. */
31
31
  export function formatArgumentError(
32
- tool: ReportTool,
33
32
  issues: readonly ArgumentIssue[],
34
33
  schemaLimited: boolean,
35
- budget: OutputBudgets = DEFAULT_OUTPUT_BUDGETS,
34
+ budget: OutputBudgets,
36
35
  ): string {
37
36
  const boundedIssues = issues.map(({ field, reason, fix }) => ({
38
37
  field,
@@ -41,7 +40,6 @@ export function formatArgumentError(
41
40
  }));
42
41
  const base = {
43
42
  error: "INVALID_ARGUMENTS" as const,
44
- tool,
45
43
  ...(schemaLimited ? { schemaLimited: true as const } : {}),
46
44
  };
47
45
  const fits = (text: string) => Buffer.byteLength(text) <= budget.blockBytes;
@@ -1,7 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
- import { openTestSession } from "../testing/session.testing.ts";
4
- import { registerForgetTool } from "./forget-tool.ts";
5
3
  import { makeEditOverride } from "./edit-tool.ts";
6
4
  import { makeReadOverride } from "./read-tool.ts";
7
5
  import { makeGrepOverride } from "./grep-tool.ts";
@@ -14,15 +12,7 @@ import { argumentError } from "./argument-error.testing.ts";
14
12
 
15
13
  const cwd = process.cwd();
16
14
 
17
- test("all six tools receive invalid arguments → return field diagnostics without an argument copy or execution", async (t) => {
18
- const { session } = await openTestSession(t, {
19
- tools: ["forget"],
20
- configure(pi) {
21
- registerForgetTool(pi);
22
- },
23
- });
24
- const forget = session.getToolDefinition("forget");
25
- assert.ok(forget);
15
+ test("all tools receive invalid arguments → return field diagnostics without an argument copy or execution", async () => {
26
16
  const cases = [
27
17
  {
28
18
  tool: makeEditOverride(cwd, DEFAULT_CONFIG),
@@ -33,9 +23,8 @@ test("all six tools receive invalid arguments → return field diagnostics witho
33
23
  { tool: makeWriteOverride(cwd), args: { path: "unused", content: "bad\0", mode: "create" } },
34
24
  {
35
25
  tool: makeReplaceTool(cwd, DEFAULT_CONFIG),
36
- args: { path: "unused", replacements: [{ find: "a", replace: "bad\0" }] },
26
+ args: { path: "unused", replacements: [{ literal: true, find: "a", replace: "bad\0" }] },
37
27
  },
38
- { tool: forget, args: { ids: [] } },
39
28
  ];
40
29
  for (const { tool, args } of cases) {
41
30
  let executed = false;
@@ -52,10 +41,8 @@ test("all six tools receive invalid arguments → return field diagnostics witho
52
41
  ),
53
42
  (error: unknown) => {
54
43
  const result = argumentError(error);
55
- assert.equal(result.tool, tool.name);
56
44
  assert.ok(result.issues.length > 0);
57
45
  assert.equal(Object.hasOwn(result, "arguments"), false);
58
- assert.equal(Object.hasOwn(result, "argumentsOmitted"), false);
59
46
  return true;
60
47
  },
61
48
  );
@@ -79,10 +66,12 @@ test("Pi prepares a singleton operation → semantic and schema paths resolve to
79
66
  await assert.rejects(
80
67
  callTool(makeReadOverride(cwd, DEFAULT_CONFIG), { path: "unused", offset: "1", limit: 0 }),
81
68
  (error: unknown) => {
69
+ const result = argumentError(error);
82
70
  assert.deepEqual(
83
- argumentError(error).issues.map((issue) => issue.field),
71
+ result.issues.map((issue) => issue.field),
84
72
  ["limit"],
85
73
  );
74
+ assert.equal(result.schemaLimited, undefined);
86
75
  return true;
87
76
  },
88
77
  );
@@ -6,13 +6,14 @@ import { test } from "node:test";
6
6
  import { createActionFusionExecutor } from "./action-fusion.ts";
7
7
  import { DEFAULT_CONFIG } from "./config.ts";
8
8
  import { makeEditOverride } from "./edit-tool.ts";
9
- import { makeGrepOverride } from "./grep-tool.ts";
9
+ import { makeGrepOverride, makeGrepOverrideWithBackend } from "./grep-tool.ts";
10
10
  import { makeReadOverride } from "./read-tool.ts";
11
11
  import { makeReplaceTool } from "./replace-tool.ts";
12
12
  import { makeWriteOverride } from "./write-tool.ts";
13
13
  import { callTool } from "./tool-call.testing.ts";
14
14
  import { argumentError, rejectsArgument } from "./argument-error.testing.ts";
15
15
  import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
16
+ import { reportOf } from "./report.ts";
16
17
 
17
18
  const invalidCommand = { command: "", timeout: 0 };
18
19
  const anchorHash = "A".repeat(DEFAULT_CONFIG.hashLen);
@@ -61,8 +62,8 @@ const cases = [
61
62
  makeReplaceTool(cwd, DEFAULT_CONFIG, fusion),
62
63
  args: {
63
64
  replacements: [
64
- { find: "(", replace: "bad\0", regex: true },
65
- { find: "[", replace: "bad\ud800", regex: true },
65
+ { find: "(", replace: "bad\0", literal: false },
66
+ { find: "[", replace: "bad\ud800", literal: false },
66
67
  ],
67
68
  then_run: invalidCommand,
68
69
  },
@@ -94,7 +95,7 @@ for (const scenario of cases) {
94
95
  let commandRuns = 0;
95
96
  const fusion = createActionFusionExecutor(async () => {
96
97
  commandRuns++;
97
- return { status: "succeeded", output: "ran" };
98
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ran" }] } };
98
99
  });
99
100
  const tool = scenario.make(cwd, fusion);
100
101
  const args: unknown = JSON.parse(JSON.stringify({ path, ...scenario.args, unexpected: true }));
@@ -111,6 +112,50 @@ for (const scenario of cases) {
111
112
  });
112
113
  }
113
114
 
115
+ test("grep and replace flags → accept V8 modes and reject invalid flags before patterns or file reads", async (t) => {
116
+ const cwd = await mkdtemp(join(tmpdir(), "hashline-flags-"));
117
+ t.after(() => rm(cwd, { recursive: true, force: true }));
118
+ const path = join(cwd, "missing.txt");
119
+ const tools = [
120
+ {
121
+ tool: makeGrepOverride(cwd, DEFAULT_CONFIG),
122
+ args: (find: string, literal: boolean, flags: string) => ({ pattern: find, literal, flags }),
123
+ field: "flags",
124
+ },
125
+ {
126
+ tool: makeReplaceTool(cwd, DEFAULT_CONFIG),
127
+ args: (find: string, literal: boolean, flags: string) => ({
128
+ replacements: [
129
+ { literal: true, find: "valid", replace: "first" },
130
+ { find, replace: "second", literal, flags },
131
+ ],
132
+ }),
133
+ field: "replacements[1].flags",
134
+ },
135
+ ];
136
+ for (const { tool, args, field } of tools) {
137
+ for (const literal of [false, true]) {
138
+ for (const flags of ["v", "uv", "x"]) {
139
+ await t.test(`${tool.name}/${literal ? "literal" : "regex"}/${flags}`, async () => {
140
+ const input = { path, ...args(flags === "v" ? "a" : "(", literal, flags) };
141
+ if (flags === "v") {
142
+ const result = await callTool(tool, input);
143
+ assert.equal(reportOf(result, tool.name)?.error, "PATH_NOT_FOUND");
144
+ } else {
145
+ await assert.rejects(callTool(tool, input), (error: unknown) => {
146
+ const report = argumentError(error);
147
+ assert.equal(report.issues.length, 1);
148
+ assert.equal(report.issues[0].field, field);
149
+ assert.match(report.issues[0].reason, /Invalid flags supplied to RegExp constructor/);
150
+ return true;
151
+ });
152
+ }
153
+ });
154
+ }
155
+ }
156
+ }
157
+ });
158
+
114
159
  test("known edit operations with empty bodies → report the actionable issue once", async () => {
115
160
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
116
161
  for (const op of ["replace", "insert_after", "insert_before", "append", "prepend"]) {
@@ -307,25 +352,6 @@ test("operation shape does not permit a field → omit inapplicable semantic adv
307
352
  }
308
353
  });
309
354
 
310
- test("Pi coerces valid fields while another field fails → do not diagnose the original value", async () => {
311
- await assert.rejects(
312
- callTool(makeReadOverride(process.cwd(), DEFAULT_CONFIG), {
313
- path: "unused.txt",
314
- offset: "1",
315
- limit: 0,
316
- }),
317
- (error: unknown) => {
318
- const result = argumentError(error);
319
- assert.deepEqual(
320
- result.issues.map((issue) => issue.field),
321
- ["limit"],
322
- );
323
- assert.equal(result.schemaLimited, undefined);
324
- return true;
325
- },
326
- );
327
- });
328
-
329
355
  test("multiple required fields are missing → report every missing field", async () => {
330
356
  await assert.rejects(
331
357
  callTool(makeEditOverride(process.cwd(), DEFAULT_CONFIG), {
@@ -441,7 +467,6 @@ test("copy/move illegal argument shapes → reject before any file access", asyn
441
467
  callTool(tool, { path: "missing-copy-move.txt", edits: [{ op, anchor, ...fields }] }),
442
468
  (error: unknown) => {
443
469
  const result = argumentError(error);
444
- assert.equal(result.tool, "edit");
445
470
  assert(result.issues.length > 0);
446
471
  if ("body" in fields)
447
472
  assert(result.issues.some((issue) => issue.field === "edits[0].body"));
@@ -604,7 +629,15 @@ const inOrder = (fix: string, pieces: readonly string[]): void => {
604
629
  };
605
630
 
606
631
  test("missing required parameter → fix states the parameter's role from its schema description", async () => {
607
- const grep = makeGrepOverride(process.cwd(), DEFAULT_CONFIG);
632
+ let discoveries = 0;
633
+ const discover = async () => {
634
+ discoveries++;
635
+ return { code: 1, stderr: "", stopped: false };
636
+ };
637
+ const grep = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, {
638
+ runRgPaths: discover,
639
+ runRgLines: discover,
640
+ });
608
641
  const write = makeWriteOverride(process.cwd());
609
642
  const edit = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
610
643
  const cases = [
@@ -659,6 +692,7 @@ test("missing required parameter → fix states the parameter's role from its sc
659
692
  return true;
660
693
  });
661
694
  }
695
+ assert.equal(discoveries, 0);
662
696
  });
663
697
 
664
698
  test("two operations miss the same required field → the shared fix appears once", async () => {
@@ -10,7 +10,7 @@ import { ObjectOptions, Type, type Static, type TObject, type TSchema } from "ty
10
10
  import { errorMessage } from "../core/errors.ts";
11
11
  import { diagnoseArguments } from "./argument-diagnostics.ts";
12
12
  import { formatArgumentError } from "./argument-error.ts";
13
- import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
13
+ import type { OutputBudgetProvider } from "./budgets.ts";
14
14
  import type { ArgumentIssue, ReportTool } from "./report-schema.ts";
15
15
 
16
16
  /** Report one semantic issue: what is wrong (a fact), and how to correct it when the fact alone does not say. */
@@ -25,8 +25,8 @@ export function argumentItems(value: unknown): readonly unknown[] {
25
25
  export function createArgumentPreparer<T extends TObject>(
26
26
  name: ReportTool,
27
27
  parameters: T,
28
- check?: CheckArguments,
29
- budgets: OutputBudgetProvider = defaultOutputBudgets,
28
+ check: CheckArguments | undefined,
29
+ budgets: OutputBudgetProvider,
30
30
  ): (args: unknown) => Static<T> {
31
31
  const validate = (schema: TSchema, args: unknown): unknown =>
32
32
  validateToolArguments(
@@ -69,7 +69,6 @@ export function createArgumentPreparer<T extends TObject>(
69
69
  if (!observation) {
70
70
  throw new Error(
71
71
  formatArgumentError(
72
- name,
73
72
  [{ field: "$", reason: errorMessage(schemaFailure) }],
74
73
  false,
75
74
  budgets(),
@@ -90,7 +89,7 @@ export function createArgumentPreparer<T extends TObject>(
90
89
  ? result.issues
91
90
  : [{ field: "$", reason: errorMessage(schemaFailure) }];
92
91
  if (schemaFailure !== undefined || result.issues.length > 0) {
93
- throw new Error(formatArgumentError(name, reported, result.limited, budgets()), {
92
+ throw new Error(formatArgumentError(reported, result.limited, budgets()), {
94
93
  cause: schemaFailure,
95
94
  });
96
95
  }
package/src/pi/budgets.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  /**
2
2
  * Model-facing byte budgets. README "Output budgets" documents this policy.
3
3
  * The context window is a capacity hint, not a tokenizer or remaining-context counter.
4
- * This module also loads in the replacement worker; keep it free of Pi runtime imports.
5
4
  */
6
5
 
7
6
  const BYTES_PER_CONTEXT_TOKEN = 1;
@@ -48,10 +47,9 @@ export function outputBudgetsFor(contextWindow: number | undefined): OutputBudge
48
47
  /** Standalone tool factories have no session model until a provider is supplied. */
49
48
  export const defaultOutputBudgets: OutputBudgetProvider = () => DEFAULT_OUTPUT_BUDGETS;
50
49
 
51
- /** Size wording for notices, e.g. `16 KiB`. */
52
- export function formatKiB(bytes: number): string {
53
- return `${bytes / 1024} KiB`;
54
- }
50
+ const MIB = 1024 * 1024;
55
51
 
56
- /** Smallest read or grep text result tagged for forget; smaller ones save too little to be worth forgetting. */
57
- export const FORGET_MIN_BYTES = 2 * 1024;
52
+ /** Size wording for every model-facing limit: whole MiB as `256 MiB`, otherwise `16 KiB`. */
53
+ export function formatByteSize(bytes: number): string {
54
+ return bytes % MIB === 0 ? `${bytes / MIB} MiB` : `${bytes / 1024} KiB`;
55
+ }