@criogaid/pi-hashline-edit 0.8.0 → 0.10.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 +13 -10
  2. package/README.zh-CN.md +12 -9
  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 +118 -293
  7. package/src/core/apply.ts +63 -165
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.ts +4 -4
  10. package/src/core/errors.test.ts +23 -7
  11. package/src/core/errors.ts +32 -5
  12. package/src/core/hash.test.ts +8 -16
  13. package/src/core/hash.ts +3 -23
  14. package/src/core/lines.ts +2 -4
  15. package/src/core/ranges.test.ts +16 -8
  16. package/src/core/ranges.ts +10 -6
  17. package/src/core/regex.ts +3 -4
  18. package/src/core/replace.test.ts +47 -1
  19. package/src/core/replace.ts +19 -13
  20. package/src/core/search-analysis.test.ts +24 -27
  21. package/src/core/search-analysis.ts +34 -65
  22. package/src/core/search-matrix.testing.ts +0 -2
  23. package/src/core/search.ts +1 -1
  24. package/src/core/text.test.ts +5 -5
  25. package/src/core/text.ts +5 -12
  26. package/src/core/types.ts +7 -43
  27. package/src/integration/config-registration.test.ts +2 -2
  28. package/src/integration/fusion-dispatch.test.ts +2 -5
  29. package/src/integration/grep-flags.test.ts +0 -14
  30. package/src/integration/grep-js-completeness.test.ts +34 -8
  31. package/src/integration/grep-line-candidates.test.ts +4 -8
  32. package/src/integration/grep-matrix.test.ts +3 -7
  33. package/src/integration/grep-path-matrix.test.ts +5 -5
  34. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  35. package/src/integration/grep-process-limits.test.ts +78 -0
  36. package/src/integration/grep-rg.test.ts +123 -25
  37. package/src/integration/grep-scan-budget.test.ts +2 -2
  38. package/src/integration/grep-translation.test.ts +12 -27
  39. package/src/integration/large-text.test.ts +1 -47
  40. package/src/integration/model-budget-lifecycle.test.ts +13 -3
  41. package/src/integration/mutation-file-types.testing.ts +1 -1
  42. package/src/integration/npm-package.testing.ts +1 -1
  43. package/src/integration/publication-read-changes.test.ts +125 -47
  44. package/src/integration/replace-worker-boundary.test.ts +21 -11
  45. package/src/integration/report-replay.test.ts +21 -23
  46. package/src/integration/utf8-errors.test.ts +1 -1
  47. package/src/pi/AGENTS.md +16 -16
  48. package/src/pi/action-fusion.test.ts +168 -300
  49. package/src/pi/action-fusion.ts +148 -111
  50. package/src/pi/anchor-format.test.ts +9 -9
  51. package/src/pi/anchor-format.ts +6 -8
  52. package/src/pi/argument-diagnostics.ts +52 -207
  53. package/src/pi/argument-error.ts +2 -1
  54. package/src/pi/argument-format.test.ts +20 -22
  55. package/src/pi/argument-validation.test.ts +382 -418
  56. package/src/pi/argument-validation.ts +5 -8
  57. package/src/pi/budgets.ts +5 -4
  58. package/src/pi/config.test.ts +5 -2
  59. package/src/pi/config.ts +4 -6
  60. package/src/pi/diagnostic-buffer.test.ts +12 -1
  61. package/src/pi/diagnostic-buffer.ts +1 -2
  62. package/src/pi/directory-sync.test.ts +0 -1
  63. package/src/pi/edit-tool.ts +173 -226
  64. package/src/pi/error-text.ts +4 -8
  65. package/src/pi/execute.test.ts +165 -266
  66. package/src/pi/failure-context.test.ts +144 -126
  67. package/src/pi/failure-context.ts +45 -94
  68. package/src/pi/failure-path.test.ts +168 -141
  69. package/src/pi/file-commit.test.ts +110 -53
  70. package/src/pi/file-commit.ts +90 -137
  71. package/src/pi/file-snapshot.test.ts +3 -5
  72. package/src/pi/fusion-card.test.ts +4 -1
  73. package/src/pi/fusion-card.ts +16 -24
  74. package/src/pi/grep-candidates.test.ts +2 -101
  75. package/src/pi/grep-candidates.ts +23 -69
  76. package/src/pi/grep-matrix.test.ts +2 -2
  77. package/src/pi/grep-order.test.ts +4 -4
  78. package/src/pi/grep-output.ts +62 -96
  79. package/src/pi/grep-render.ts +1 -1
  80. package/src/pi/grep-reread.ts +92 -0
  81. package/src/pi/grep-scope.ts +40 -42
  82. package/src/pi/grep-search.ts +22 -31
  83. package/src/pi/grep-tool.ts +55 -82
  84. package/src/pi/grep.test.ts +81 -46
  85. package/src/pi/model-budgets.test.ts +25 -23
  86. package/src/pi/model-budgets.ts +6 -38
  87. package/src/pi/mutation-result.test.ts +44 -35
  88. package/src/pi/mutation-result.ts +51 -20
  89. package/src/pi/mutation-runner.ts +126 -70
  90. package/src/pi/output-budgets.test.ts +38 -16
  91. package/src/pi/path.ts +1 -1
  92. package/src/pi/pi.test.ts +3 -1
  93. package/src/pi/read-tool.ts +5 -5
  94. package/src/pi/regex-worker-contract.ts +3 -13
  95. package/src/pi/regex-worker.ts +1 -10
  96. package/src/pi/registration.test.ts +82 -20
  97. package/src/pi/render.test.ts +79 -42
  98. package/src/pi/render.ts +69 -63
  99. package/src/pi/replace-regex.ts +14 -2
  100. package/src/pi/replace-tool.ts +22 -83
  101. package/src/pi/replace-worker.ts +1 -1
  102. package/src/pi/replace.test.ts +9 -5
  103. package/src/pi/report-cause.ts +3 -8
  104. package/src/pi/report-failure.testing.ts +1 -2
  105. package/src/pi/report-schema.ts +65 -81
  106. package/src/pi/report.test.ts +171 -25
  107. package/src/pi/report.ts +33 -87
  108. package/src/pi/result-safety.test.ts +177 -189
  109. package/src/pi/rg-process.test.ts +77 -63
  110. package/src/pi/rg-process.ts +48 -64
  111. package/src/pi/rg-regex.ts +40 -400
  112. package/src/pi/schema.ts +12 -0
  113. package/src/pi/text-stream.test.ts +0 -21
  114. package/src/pi/text-stream.ts +14 -21
  115. package/src/pi/write-tool.ts +33 -62
  116. package/src/pi/write.test.ts +1 -3
  117. package/src/testing/regex-translation-corpus.ts +12 -12
  118. package/src/pi/replace-worker-contract.ts +0 -10
@@ -8,64 +8,44 @@
8
8
  */
9
9
 
10
10
  import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
11
- import { rgPath as bundledRgPath } from "@vscode/ripgrep";
12
- import { Type, type Static } from "typebox";
11
+ import { Type, type Static, type TLiteral } from "typebox";
13
12
  import { Text } from "@earendil-works/pi-tui";
14
13
  import { renderOutputPreview, renderToolError, reportLines, splitReport } from "./render.ts";
15
14
  import { createAnchorFormatter } from "./anchor-format.ts";
16
- import { grepOutput } from "./grep-output.ts";
17
- import {
18
- filterExplicitFilesByGlob,
19
- toArray,
20
- resolveSearchPaths,
21
- type SearchScope,
22
- } from "./grep-scope.ts";
15
+ import { GREP_OUTPUT_MODES, grepOutput, type GrepOutputMode } from "./grep-output.ts";
16
+ import { filterExplicitFilesByGlob, resolveSearchPaths } from "./grep-scope.ts";
23
17
  import { searchFiles } from "./grep-search.ts";
24
18
  import { toDisplayLines } from "./grep-render.ts";
25
19
  import { runRgLines, runRgPaths, type GrepBackend } from "./rg-process.ts";
26
20
  import { smartIgnoreCase } from "../core/search-analysis.ts";
27
21
  import { checkRegexArguments } from "../core/regex.ts";
28
22
  import { DEFAULT_GREP_FLAGS } from "../core/search.ts";
29
- import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER } from "./schema.ts";
23
+ import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER, STRICT_SAMPLING } from "./schema.ts";
30
24
  import { throwIfCancelled } from "./error-text.ts";
31
25
  import { reportResult, runTool, type ReportDetails } from "./report.ts";
32
26
  import type { HashlineEditConfig } from "./config.ts";
33
27
  import { createArgumentPreparer, type ReportArgumentIssue } from "./argument-validation.ts";
34
28
  import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
35
29
 
30
+ /** A list field: arrays only, because strict sampling cannot take a string-or-array union. */
31
+ const nonEmptyStrings = (description: string) =>
32
+ Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description });
33
+
36
34
  /** Grep parameters; descriptions state the configured defaults. */
37
35
  function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["grep"]) {
38
36
  return Type.Object(
39
37
  {
40
- pattern: Type.Union(
41
- [Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
42
- {
43
- description:
44
- "String or array of strings; an array matches any of them, so use it for alternatives instead of joining them with |. Regex syntax is JavaScript, as in replace.",
45
- },
38
+ pattern: nonEmptyStrings(
39
+ "Patterns; a line matches if any of them matches. With literal true, | is an ordinary character, so give alternatives as separate items. Regex syntax is JavaScript, as in replace.",
46
40
  ),
47
41
  path: Type.Optional(
48
- Type.Union(
49
- [
50
- Type.String({ minLength: 1 }),
51
- Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
52
- ],
53
- {
54
- description:
55
- "Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded.",
56
- },
42
+ nonEmptyStrings(
43
+ "Existing files or directories; omit to search the working directory. Wildcards are not expanded.",
57
44
  ),
58
45
  ),
59
46
  glob: Type.Optional(
60
- Type.Union(
61
- [
62
- Type.String({ minLength: 1 }),
63
- Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
64
- ],
65
- {
66
- description:
67
- "Filename wildcards go here, not in path: a glob or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
68
- },
47
+ nonEmptyStrings(
48
+ "Filename wildcards go here, not in path: ordered globs; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
69
49
  ),
70
50
  ),
71
51
  literal: Type.Boolean({
@@ -102,26 +82,39 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
102
82
  }),
103
83
  ),
104
84
  outputMode: Type.Optional(
105
- Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
106
- description:
107
- '"content" (default): matches/context with anchors for valid UTF-8 or plain previews otherwise; "files": paths; "count": matching lines per file and total. Use files or count when only paths or counts are needed. limit counts matching lines in every mode, so files and count stop at the same cutoff as content.',
108
- }),
85
+ // TypeBox infers a union's static type only from a tuple.
86
+ Type.Union(
87
+ GREP_OUTPUT_MODES.map((mode) => Type.Literal(mode)) as [
88
+ TLiteral<GrepOutputMode>,
89
+ ...TLiteral<GrepOutputMode>[],
90
+ ],
91
+ {
92
+ description:
93
+ '"content" (default): matches/context with anchors for valid UTF-8 or plain previews otherwise; "files": paths; "count": matching lines per file and total. Use files or count when only paths or counts are needed. limit counts matching lines in every mode, so files and count stop at the same cutoff as content.',
94
+ },
95
+ ),
109
96
  ),
110
97
  },
111
98
  { additionalProperties: false },
112
99
  );
113
100
  }
114
101
  type GrepSchema = ReturnType<typeof createGrepSchema>;
115
- /** How grep presents matches; grep-output formats each mode. */
116
- export type GrepOutputMode = NonNullable<Static<GrepSchema>["outputMode"]>;
117
102
  type GrepTool = ToolDefinition<GrepSchema, Partial<ReportDetails> | undefined>;
103
+ /** A list field as the call header sees it: streamed before Pi wraps a lone string. */
104
+ function streamedList(value: string | readonly string[] | null | undefined): readonly string[] {
105
+ return value == null ? [] : typeof value === "string" ? [value] : value;
106
+ }
107
+
118
108
  /** Validate JavaScript syntax once; the search never rejects a pattern V8 accepts. */
119
109
  function checkGrepArguments(args: unknown, report: ReportArgumentIssue): void {
120
110
  const { pattern, literal, flags } = (args ?? {}) as Record<string, unknown>;
121
- if (typeof literal !== "boolean" || (flags !== undefined && typeof flags !== "string")) return;
122
- const fields = Array.isArray(pattern)
123
- ? pattern.map((value, index) => [`pattern[${index}]`, value] as const)
124
- : [["pattern", pattern] as const];
111
+ if (
112
+ !Array.isArray(pattern) ||
113
+ typeof literal !== "boolean" ||
114
+ (flags !== undefined && typeof flags !== "string")
115
+ )
116
+ return;
117
+ const fields = pattern.map((value, index) => [`pattern[${index}]`, value] as const);
125
118
  checkRegexArguments("flags", flags ?? DEFAULT_GREP_FLAGS, literal, fields, report);
126
119
  }
127
120
 
@@ -149,7 +142,7 @@ export function makeGrepOverrideWithBackend(
149
142
  name: "grep" as const,
150
143
  label: "grep",
151
144
  description:
152
- "Search file contents. Content mode returns LINE#HASH edit anchors for valid UTF-8 and plain line numbers without anchors otherwise; files/count modes return paths or matching-line counts. NUL-containing files are skipped. Directory searches respect ignore rules and skip .git and linked directories. Use grep instead of rg or grep in a shell to search files; use the shell only for ignored, .git, or linked directories, or to filter another command's output.",
145
+ "Search file contents. Content mode returns LINE#HASH edit anchors for valid UTF-8 and plain line numbers without anchors otherwise; files/count modes return paths or matching-line counts. NUL-containing files are skipped. Directory searches respect ignore rules and skip .git and linked directories, even beneath a directory named in path; to search an ignored file or one of those directories, name it itself in path. Use grep instead of rg or grep in a shell to search files; use the shell only to filter another command's output.",
153
146
  promptSnippet: "Search file contents",
154
147
  promptGuidelines: [
155
148
  "When you need several independent searches, send them as separate grep calls in one response; they run in parallel.",
@@ -157,6 +150,7 @@ export function makeGrepOverrideWithBackend(
157
150
  ],
158
151
  parameters: grepSchema,
159
152
  prepareArguments: createArgumentPreparer("grep", grepSchema, checkGrepArguments, budgets),
153
+ constrainedSampling: STRICT_SAMPLING,
160
154
 
161
155
  renderShell: "default" as const,
162
156
 
@@ -164,20 +158,17 @@ export function makeGrepOverrideWithBackend(
164
158
  args: Static<GrepSchema>,
165
159
  theme: Parameters<NonNullable<GrepTool["renderCall"]>>[1],
166
160
  ) {
167
- const rawPattern = args?.pattern;
168
- const patternText = Array.isArray(rawPattern)
169
- ? rawPattern.join(" | ")
170
- : String(rawPattern ?? "");
171
- const rawPath = args?.path;
172
- const pathText = Array.isArray(rawPath) ? rawPath.join(" ") : String(rawPath ?? ".");
161
+ const paths = streamedList(args?.path);
162
+ const globs = streamedList(args?.glob);
173
163
  let text =
174
164
  theme.fg("toolTitle", theme.bold("grep ")) +
175
- theme.fg("accent", `/${patternText}/${args?.flags ?? ""}`) +
176
- theme.fg("toolOutput", ` in ${pathText}`);
177
- if (args?.glob) text += theme.fg("toolOutput", ` (${toArray(args.glob).join(", ")})`);
165
+ theme.fg("accent", `/${streamedList(args?.pattern).join(" | ")}/${args?.flags ?? ""}`) +
166
+ theme.fg("toolOutput", ` in ${paths.length ? paths.join(" ") : "."}`);
167
+ if (globs.length) text += theme.fg("toolOutput", ` (${globs.join(", ")})`);
178
168
  if (args?.outputMode && args.outputMode !== "content")
179
169
  text += theme.fg("success", ` → ${args.outputMode}`);
180
- if (args?.limit !== undefined) text += theme.fg("toolOutput", ` limit ${args.limit}`);
170
+ // Strict sampling streams unused optional fields as null.
171
+ if (args?.limit != null) text += theme.fg("toolOutput", ` limit ${args.limit}`);
181
172
  return new Text(text, 0, 0);
182
173
  },
183
174
 
@@ -188,7 +179,7 @@ export function makeGrepOverrideWithBackend(
188
179
  context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
189
180
  ) {
190
181
  if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
191
- if (context?.isError) return renderToolError(result, "grep", theme, expanded);
182
+ if (context.isError) return renderToolError(result, "grep", theme, expanded);
192
183
  const { content, report } = splitReport(result);
193
184
  const payload = content[0];
194
185
  return renderOutputPreview(
@@ -205,13 +196,11 @@ export function makeGrepOverrideWithBackend(
205
196
  _toolCallId: string,
206
197
  params: Static<GrepSchema>,
207
198
  signal: AbortSignal | undefined,
208
- _onUpdate: Parameters<GrepTool["execute"]>[3],
209
199
  ) {
210
200
  const budget = budgets();
211
201
  return runTool("grep", { path: params.path, signal, budget }, async () => {
212
202
  throwIfCancelled(signal);
213
- const warnings: string[] = [];
214
- const patterns = toArray(params.pattern);
203
+ const patterns = params.pattern;
215
204
  const effectiveLimit = params.limit ?? config.grep.defaultLimit;
216
205
  const outputMode = params.outputMode ?? "content";
217
206
  const { literal } = params;
@@ -227,33 +216,16 @@ export function makeGrepOverrideWithBackend(
227
216
  flags: [...flags].join(""),
228
217
  multiline: params.multiline ?? false,
229
218
  };
230
- const { searchPaths, pathInfo } = await resolveSearchPaths(cwd, params.path);
231
- const unfiltered: SearchScope = {
232
- globs: toArray(params.glob),
233
- noIgnore: false,
234
- follow: false,
235
- searchPaths,
236
- };
237
- const scope: SearchScope = {
238
- ...unfiltered,
239
- searchPaths: await filterExplicitFilesByGlob(
240
- backend,
241
- bundledRgPath,
242
- unfiltered,
243
- pathInfo,
244
- signal,
245
- warnings,
246
- ),
247
- };
248
- const search = await searchFiles({
219
+ const globs = params.glob ?? [];
220
+ const paths = await resolveSearchPaths(cwd, params.path);
221
+ const admitted = await filterExplicitFilesByGlob(backend, globs, paths, signal);
222
+ const { warnings: searchWarnings, ...search } = await searchFiles({
249
223
  backend,
250
- rgPath: bundledRgPath,
251
- scope,
224
+ scope: { globs, searchPaths: admitted.searchPaths },
252
225
  query,
253
226
  limit: effectiveLimit,
254
227
  timeoutMs: config.grep.regexTimeoutMs,
255
228
  signal,
256
- warnings,
257
229
  });
258
230
  const { payload, facts } = await grepOutput({
259
231
  cwd,
@@ -262,7 +234,8 @@ export function makeGrepOverrideWithBackend(
262
234
  context: params.context ?? config.grep.defaultContext,
263
235
  anchors: createAnchorFormatter(hashLen),
264
236
  signal,
265
- warnings,
237
+ // Each stage returns its warnings in order; the report states them in stage order.
238
+ warnings: [...admitted.warnings, ...searchWarnings],
266
239
  effectiveLimit,
267
240
  literalPipe: literal && patterns.some((pattern) => pattern.includes("|")),
268
241
  budget,
@@ -11,7 +11,6 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
11
11
  import fsPromises from "node:fs/promises";
12
12
  import { tmpdir } from "node:os";
13
13
  import { join } from "node:path";
14
- import { rgPath } from "@vscode/ripgrep";
15
14
  import { initTheme } from "@earendil-works/pi-coding-agent";
16
15
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
17
16
  import { computeLineHash } from "../core/hash.ts";
@@ -51,14 +50,13 @@ async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
51
50
  }
52
51
 
53
52
  function fakeBackend(options: FakeOptions = {}) {
54
- const calls: { kind: "paths" | "lines"; path: string; args: readonly string[] }[] = [];
53
+ const calls: { kind: "paths" | "lines"; args: readonly string[] }[] = [];
55
54
  const run = async (
56
55
  kind: "paths" | "lines",
57
- path: string,
58
56
  args: readonly string[],
59
57
  onPath: (file: string) => boolean | Promise<boolean>,
60
58
  ) => {
61
- calls.push({ kind, path, args });
59
+ calls.push({ kind, args });
62
60
  await options.onRun?.();
63
61
  if (options.error) throw options.error;
64
62
  for (const file of options.paths ?? []) {
@@ -71,9 +69,9 @@ function fakeBackend(options: FakeOptions = {}) {
71
69
  };
72
70
  };
73
71
  const backend: GrepBackend = {
74
- runRgPaths: (path, args, _signal, onPath) => run("paths", path, args, onPath),
75
- runRgLines: (path, args, _signal, _maxLines, onFile) =>
76
- run("lines", path, args, (file) => onFile(file, options.lines)),
72
+ runRgPaths: (args, _signal, onPath) => run("paths", args, onPath),
73
+ runRgLines: (args, _signal, _maxLines, onFile) =>
74
+ run("lines", args, (file) => onFile(file, options.lines)),
77
75
  };
78
76
  return { backend, calls };
79
77
  }
@@ -86,13 +84,33 @@ test("explicit JavaScript flags → call rendering shows them", () => {
86
84
  initTheme("dark");
87
85
  const { backend } = fakeBackend();
88
86
  const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, backend);
89
- const rendered = tool.renderCall!({ pattern: "\\p{Letter}+", literal: false, flags: "u" }, theme)
87
+ const rendered = tool.renderCall!(
88
+ { pattern: ["\\p{Letter}+"], literal: false, flags: "u" },
89
+ theme,
90
+ )
90
91
  .render(120)
91
92
  .join("\n");
92
93
  assert.ok(rendered.includes("/\\p{Letter}+/u"));
93
94
  });
94
95
 
95
- test("configured defaults → descriptions, limits, and context use the registered values", async () =>
96
+ test("streamed grep strings and null fields → render the pattern and default path without a limit", () => {
97
+ initTheme("dark");
98
+ const { backend } = fakeBackend();
99
+ const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, backend);
100
+ for (const pattern of ["needle", null]) {
101
+ const args: unknown = { pattern, literal: true, path: null, limit: null };
102
+ const rendered = tool
103
+ // Streaming arguments reach the renderer before Pi validates and coerces them.
104
+ .renderCall(args as Parameters<typeof tool.renderCall>[0], theme)
105
+ .render(120)
106
+ .join("\n");
107
+ assert.ok(rendered.includes(`/${pattern ?? ""}/`));
108
+ assert.ok(rendered.includes("in ."));
109
+ assert.doesNotMatch(rendered, /limit/);
110
+ }
111
+ });
112
+
113
+ test("configured defaults → descriptions, limits, and context use registered values", async () =>
96
114
  withDir(async (dir) => {
97
115
  const file = join(dir, "configured.txt");
98
116
  const lines = [
@@ -192,7 +210,7 @@ test("grep points wildcard paths to glob without changing ordinary missing-path
192
210
  call(tool, { literal: true, pattern: "value", path: "src/fusion-card*" }),
193
211
  "PATH_NOT_FOUND",
194
212
  (report) => {
195
- assert.equal(report.path, "src/fusion-card*");
213
+ assert.deepEqual(report.path, ["src/fusion-card*"]);
196
214
  assert.match(report.next ?? "", /directory.*path.*wildcard.*glob/);
197
215
  },
198
216
  );
@@ -200,33 +218,43 @@ test("grep points wildcard paths to glob without changing ordinary missing-path
200
218
  call(tool, { literal: true, pattern: "value", path: "src/missing" }),
201
219
  "PATH_NOT_FOUND",
202
220
  (report) => {
203
- assert.equal(report.path, "src/missing");
221
+ assert.deepEqual(report.path, ["src/missing"]);
204
222
  assert.equal(report.next, "Check the path.");
205
223
  },
206
224
  );
207
225
  });
208
226
  });
209
227
 
210
- test("one of multiple grep paths is missing → text identifies it without repeating call fields", async () =>
228
+ test("multiple grep paths are missing → reports all resolved paths and selects wildcard recovery", async () =>
211
229
  withDir(async (dir) => {
212
230
  await writeFile(join(dir, "present.txt"), "value\n");
213
- const path = ["present.txt", "missing.txt"];
214
- const fake = fakeBackend();
215
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
216
- const result = await call(tool, { literal: true, pattern: "value", path });
217
- assert.equal(result.isError, true);
218
- const block = result.content[0];
219
- assert.ok(block.type === "text");
220
- const facts = JSON.parse(block.text);
221
- assert.equal(facts.error, "PATH_NOT_FOUND");
222
- assert.equal(facts.missing, join(dir, "missing.txt"));
223
- assert.equal(Object.hasOwn(facts, "tool"), false);
224
- assert.equal(Object.hasOwn(facts, "path"), false);
225
- const report = reportOf(result, "grep");
226
- assert.equal(report?.tool, "grep");
227
- assert.deepEqual(report?.path, path);
228
- assert.equal(report?.missing, facts.missing);
229
- assert.equal(fake.calls.length, 0);
231
+ for (const [path, missing, wildcard] of [
232
+ [["missing.txt", "present.txt", "other.txt"], ["missing.txt", "other.txt"], false],
233
+ [["missing.txt", "present.txt", "other*.txt"], ["missing.txt", "other*.txt"], true],
234
+ [["missing?.txt", "present.txt", "other.txt"], ["missing?.txt", "other.txt"], true],
235
+ ] as const) {
236
+ const fake = fakeBackend();
237
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
238
+ const result = await call(tool, { literal: true, pattern: "value", path });
239
+ assert.equal(result.isError, true);
240
+ const block = result.content[0];
241
+ assert.ok(block.type === "text");
242
+ const facts = JSON.parse(block.text);
243
+ assert.equal(facts.error, "PATH_NOT_FOUND");
244
+ assert.deepEqual(
245
+ facts.missing,
246
+ missing.map((item) => join(dir, item)),
247
+ );
248
+ if (wildcard) assert.match(facts.next, /directory.*path.*wildcard.*glob/);
249
+ else assert.equal(facts.next, "Check the path.");
250
+ assert.equal(Object.hasOwn(facts, "tool"), false);
251
+ assert.equal(Object.hasOwn(facts, "path"), false);
252
+ const report = reportOf(result, "grep");
253
+ assert.equal(report?.tool, "grep");
254
+ assert.deepEqual(report?.path, path);
255
+ assert.deepEqual(report?.missing, facts.missing);
256
+ assert.equal(fake.calls.length, 0);
257
+ }
230
258
  }));
231
259
 
232
260
  test("matched files → full-line hash anchors", async () => {
@@ -245,7 +273,6 @@ test("matched files → full-line hash anchors", async () => {
245
273
  assert.match(output, /b\.ts · 1 match/);
246
274
  assert.match(output, new RegExp(`1#${computeLineHash(1, "alpha beta", 4)}│alpha beta`));
247
275
  assert.match(output, /3#[0-9A-Z]+│alpha only/);
248
- assert.equal(fake.calls[0].path, rgPath);
249
276
  });
250
277
  });
251
278
 
@@ -494,7 +521,7 @@ test("candidate selection → reports only whole-file candidate facts", async ()
494
521
  withDir(async (dir) => {
495
522
  const file = join(dir, "input.txt");
496
523
  await writeFile(file, "abc \nneedle");
497
- for (const [pattern, multiline, candidates] of [
524
+ for (const [pattern, multiline, scanned] of [
498
525
  ["needle", false, undefined],
499
526
  ["needle", true, "files"],
500
527
  ["[^x\\s]{3}\\s", true, "all"],
@@ -511,7 +538,7 @@ test("candidate selection → reports only whole-file candidate facts", async ()
511
538
  );
512
539
  assert.equal(result.isError, undefined);
513
540
  assert.equal(grepCounts(result).matches, 1);
514
- assert.equal(reportOf(result, "grep")?.candidates, candidates);
541
+ assert.equal(reportOf(result, "grep")?.scanned, scanned);
515
542
  assert.equal(reportOf(result, "grep")?.scanLimit, undefined);
516
543
  assert.equal(fake.calls[0].kind, multiline ? "paths" : "lines");
517
544
  }
@@ -541,7 +568,7 @@ test("grep in a subdirectory returns a path that edits the matching file", async
541
568
  path: displayPath,
542
569
  edits: [
543
570
  {
544
- op: "replace",
571
+ action: "replace",
545
572
  anchor: contextAnchor,
546
573
  body: ["export const context = 2;"],
547
574
  },
@@ -625,7 +652,7 @@ for (const diagnosticLineCount of [0, 80]) {
625
652
  ].join("\n");
626
653
  const fake = fakeBackend({ code: 2, stderr: diagnostic });
627
654
  const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, fake.backend);
628
- const args = { pattern: "(?<=a+)b", literal: false };
655
+ const args = { pattern: ["(?<=a+)b"], literal: false };
629
656
  const failure: Awaited<ReturnType<typeof tool.execute>> = await callTool(tool, args);
630
657
  assert.equal(failure.isError, true);
631
658
  const errorText = failure.content
@@ -766,7 +793,7 @@ test("literal pipe patterns find no match → alternatives recovery preserves li
766
793
  if (literalPipe) {
767
794
  assert.match(
768
795
  report.next ?? "",
769
- /if you meant alternatives.*pattern array.*otherwise.*literal matching/i,
796
+ /if you meant alternatives.*each as its own pattern item.*otherwise.*literal matching/i,
770
797
  context,
771
798
  );
772
799
  } else {
@@ -777,17 +804,25 @@ test("literal pipe patterns find no match → alternatives recovery preserves li
777
804
 
778
805
  test("invalid JavaScript → its field rejects before file discovery", async () =>
779
806
  withDir(async (dir) => {
780
- for (const value of ["(", "(?m)^foo", "(?i)abc"]) {
781
- for (const pattern of [value, ["plain", value]]) {
782
- const fake = fakeBackend();
783
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
784
- const field = typeof pattern === "string" ? "pattern" : "pattern[1]";
785
- await assert.rejects(
786
- call(tool, { pattern, literal: false }),
787
- rejectsArgument(field, /Invalid regular expression/),
788
- );
789
- assert.equal(fake.calls.length, 0);
790
- }
807
+ for (const [pattern, flags, field] of [
808
+ ["(", undefined, "pattern[0]"],
809
+ [["plain", "("], undefined, "pattern[1]"],
810
+ ["(?m)^foo", undefined, "pattern[0]"],
811
+ [["plain", "(?m)^foo"], undefined, "pattern[1]"],
812
+ ["(?i)abc", undefined, "pattern[0]"],
813
+ [["plain", "(?i)abc"], undefined, "pattern[1]"],
814
+ ["\\p{NotAProperty}", "u", "pattern[0]"],
815
+ ["queueTool(", undefined, "pattern[0]"],
816
+ [["queueTool(", "\\bfoo\\b"], undefined, "pattern[0]"],
817
+ ["*", undefined, "pattern[0]"],
818
+ ] as const) {
819
+ const fake = fakeBackend();
820
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
821
+ await assert.rejects(
822
+ call(tool, { path: "missing.txt", pattern, literal: false, flags }),
823
+ rejectsArgument(field, /Invalid regular expression/),
824
+ );
825
+ assert.equal(fake.calls.length, 0);
791
826
  }
792
827
  }));
793
828
 
@@ -1,32 +1,34 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
3
  import { DEFAULT_OUTPUT_BUDGETS, MAX_CONTENT_KIB, outputBudgetsFor } from "./budgets.ts";
4
- import { createOutputBudgetProvider } from "./model-budgets.ts";
4
+ import { openTestSession } from "../testing/session.testing.ts";
5
+ import { registerModelBudgets } from "./model-budgets.ts";
5
6
 
6
- test("unchanged model → budget calculation is lazy and reuses the immutable snapshot", () => {
7
- let reads = 0;
8
- let model = { provider: "local", id: "small", contextWindow: 65_536 };
9
- const get = createOutputBudgetProvider(() => {
10
- reads++;
11
- return model;
7
+ test("session start and model selection → budgets follow the live model", async (t) => {
8
+ let get: ReturnType<typeof registerModelBudgets> | undefined;
9
+ const { session, model } = await openTestSession(t, {
10
+ tools: [],
11
+ configure(pi) {
12
+ get = registerModelBudgets(pi);
13
+ assert.deepEqual(get(), DEFAULT_OUTPUT_BUDGETS);
14
+ },
12
15
  });
13
- assert.equal(reads, 0);
14
- const first = get();
15
- assert.ok(Object.isFrozen(first));
16
- assert.equal(get(), first);
17
- model = { ...model };
18
- assert.equal(get(), first);
19
- model = { ...model, id: "large", contextWindow: 1_048_576 };
16
+ assert.ok(get);
17
+ assert.deepEqual(get(), outputBudgetsFor(model.contextWindow));
18
+ const selected = { ...model, id: "small", contextWindow: 65_536 };
19
+ await session.setModel(selected);
20
+ const small = get();
21
+ assert.ok(Object.isFrozen(small));
22
+ assert.deepEqual(small, outputBudgetsFor(selected.contextWindow));
23
+ selected.contextWindow = 1_048_576;
20
24
  const large = get();
21
- assert.notEqual(large, first);
22
- assert.ok(large.readBytes > first.readBytes);
23
- assert.ok(large.blockBytes > first.blockBytes);
24
- assert.ok(large.fieldBytes > first.fieldBytes);
25
- assert.ok(large.grepPreviewUnits > first.grepPreviewUnits);
26
- assert.equal(get(), large);
27
- assert.ok(first.readBytes < large.readBytes);
28
- model = { ...model, contextWindow: 65_536 };
29
- assert.equal(get().readBytes, first.readBytes);
25
+ assert.deepEqual(large, outputBudgetsFor(selected.contextWindow));
26
+ assert.ok(large.readBytes > small.readBytes);
27
+ assert.ok(large.blockBytes > small.blockBytes);
28
+ assert.ok(large.fieldBytes > small.fieldBytes);
29
+ assert.ok(large.grepPreviewUnits > small.grepPreviewUnits);
30
+ await session.setModel({ ...model, id: "small-again", contextWindow: 65_536 });
31
+ assert.deepEqual(get(), small);
30
32
  });
31
33
 
32
34
  test("unknown or invalid model capacity → bounded defaults are used", () => {
@@ -1,44 +1,12 @@
1
- /** Per-extension lazy budgets. Tool preparation and execution share the same provider. */
1
+ /** Per-extension budgets. Tool preparation and execution share the same provider. */
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { outputBudgetsFor, type OutputBudgetProvider, type OutputBudgets } from "./budgets.ts";
3
+ import { outputBudgetsFor, type OutputBudgetProvider } from "./budgets.ts";
4
4
 
5
- type BudgetModel = Pick<
6
- NonNullable<ExtensionContext["model"]>,
7
- "provider" | "id" | "contextWindow"
8
- >;
9
-
10
- /** Reuse the snapshot until selection or its declared capacity changes. No provider request is made. */
11
- export function createOutputBudgetProvider(
12
- readModel: () => BudgetModel | undefined,
13
- ): OutputBudgetProvider {
14
- let provider: string | undefined;
15
- let id: string | undefined;
16
- let contextWindow: number | undefined;
17
- let cached: OutputBudgets | undefined;
18
- return () => {
19
- const model = readModel();
20
- if (
21
- cached === undefined ||
22
- provider !== model?.provider ||
23
- id !== model?.id ||
24
- !Object.is(contextWindow, model?.contextWindow)
25
- ) {
26
- provider = model?.provider;
27
- id = model?.id;
28
- contextWindow = model?.contextWindow;
29
- cached = outputBudgetsFor(contextWindow);
30
- }
31
- return cached;
32
- };
33
- }
34
-
35
- /** Retain Pi's live context getter, including after session restore, without calculating on events. */
5
+ /** Retain Pi's context once per session: its model getter stays live, so no event recalculates. */
36
6
  export function registerModelBudgets(pi: ExtensionAPI): OutputBudgetProvider {
37
7
  let context: ExtensionContext | undefined;
38
- const bind = (_event: unknown, ctx: ExtensionContext) => {
8
+ pi.on("session_start", (_event, ctx) => {
39
9
  context = ctx;
40
- };
41
- pi.on("session_start", bind);
42
- pi.on("model_select", bind);
43
- return createOutputBudgetProvider(() => context?.model);
10
+ });
11
+ return () => outputBudgetsFor(context?.model?.contextWindow);
44
12
  }