@criogaid/pi-hashline-edit 0.11.0 → 0.12.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.
@@ -7,7 +7,7 @@ import { loadInstalledExtension } from "../testing/extension-loader.testing.ts";
7
7
  import { openTestSession, responseStream, SESSION_TIMEOUT_MS } from "../testing/session.testing.ts";
8
8
  import { reportOf } from "../pi/report.ts";
9
9
 
10
- test("packed extension completes file, worker, and command operations", {
10
+ test("installed extension completes file, worker, and command operations", {
11
11
  timeout: SESSION_TIMEOUT_MS,
12
12
  }, async (t) => {
13
13
  const cwd = process.cwd();
@@ -95,3 +95,150 @@ test("packed extension completes file, worker, and command operations", {
95
95
  assert.match(command?.output ?? "", /PACKAGE_COMMAND_OK/);
96
96
  assert.equal(await readFile(join(cwd, "fixture.txt"), "utf8"), "edited after\nkeep\n");
97
97
  });
98
+
99
+ test("installed extension argument failures → precise independent issues and host coercion without input mutation", {
100
+ timeout: SESSION_TIMEOUT_MS,
101
+ }, async (t) => {
102
+ const cwd = process.cwd();
103
+ const factory = await loadInstalledExtension(process.argv[2]);
104
+ const { session, model } = await openTestSession(t, {
105
+ cwd,
106
+ tools: ["write", "read", "grep", "edit", "replace"],
107
+ configure: (pi) => factory(pi),
108
+ });
109
+ const cases = [
110
+ {
111
+ name: "grep",
112
+ args: { pattern: "text", literal: true, outputMode: "rows" },
113
+ fields: ["outputMode"],
114
+ },
115
+ {
116
+ name: "replace",
117
+ args: {
118
+ path: "diagnostic.txt",
119
+ mode: "regex",
120
+ replacements: [{ find: "text", replace: "value", literal: true }],
121
+ },
122
+ fields: ["mode"],
123
+ },
124
+ {
125
+ name: "replace",
126
+ args: {
127
+ path: "diagnostic.txt",
128
+ replacements: [{ find: "text", replace: "value", literal: true, mode: "regex" }],
129
+ },
130
+ fields: ["replacements[0].mode"],
131
+ },
132
+ {
133
+ name: "grep",
134
+ args: { pattern: "(", literal: false, flags: "x", outputMode: "rows", context: null },
135
+ fields: ["flags", "outputMode"],
136
+ },
137
+ {
138
+ name: "replace",
139
+ args: {
140
+ path: "diagnostic.txt",
141
+ replacements: [{ find: "(", replace: "value", literal: false, flags: "x", mode: "regex" }],
142
+ },
143
+ fields: ["replacements[0].flags", "replacements[0].mode"],
144
+ },
145
+ {
146
+ name: "read",
147
+ args: { path: "diagnostic.txt", offset: -1, limit: 0 },
148
+ fields: ["offset", "limit"],
149
+ },
150
+ {
151
+ name: "write",
152
+ args: { path: "diagnostic.txt", content: "text", mode: "invalid" },
153
+ fields: ["mode"],
154
+ },
155
+ {
156
+ name: "edit",
157
+ args: { path: "diagnostic.txt", steps: { action: "append", lines: [] } },
158
+ fields: ["steps[0].lines"],
159
+ },
160
+ {
161
+ name: "write",
162
+ args: { path: "diagnostic.txt", content: 42, mode: "create", then_run: null },
163
+ fields: [],
164
+ },
165
+ { name: "read", args: { path: "diagnostic.txt", offset: "1", limit: null }, fields: [] },
166
+ {
167
+ name: "grep",
168
+ args: {
169
+ path: "diagnostic.txt",
170
+ pattern: "42",
171
+ literal: "true",
172
+ flags: null,
173
+ outputMode: "count",
174
+ },
175
+ fields: [],
176
+ },
177
+ {
178
+ name: "replace",
179
+ args: {
180
+ path: "diagnostic.txt",
181
+ replacements: { find: 42, replace: 43, literal: "true", flags: null },
182
+ },
183
+ fields: ["replacements[0].flags"],
184
+ },
185
+ {
186
+ name: "replace",
187
+ args: {
188
+ path: "diagnostic.txt",
189
+ replacements: [{ find: 42, replace: 42, literal: "true", flags: null }],
190
+ },
191
+ fields: [],
192
+ },
193
+ {
194
+ name: "replace",
195
+ args: {
196
+ path: "diagnostic.txt",
197
+ replacements: { find: 42, replace: 43, literal: "true" },
198
+ },
199
+ fields: [],
200
+ },
201
+ ] as const;
202
+ const original = structuredClone(cases);
203
+ let next = 0;
204
+ session.agent.streamFunction = () => {
205
+ const scenario = cases[next++];
206
+ return responseStream(
207
+ model,
208
+ scenario
209
+ ? {
210
+ content: [
211
+ {
212
+ type: "toolCall",
213
+ id: `diagnostic-${next}`,
214
+ name: scenario.name,
215
+ arguments: scenario.args,
216
+ },
217
+ ],
218
+ stopReason: "toolUse",
219
+ }
220
+ : { content: [{ type: "text", text: "Done." }], stopReason: "stop" },
221
+ );
222
+ };
223
+ await session.prompt("Exercise installed argument validation.");
224
+ assert.equal(session.agent.state.errorMessage, undefined);
225
+ assert.equal(next, cases.length + 1);
226
+ for (const [index, scenario] of cases.entries()) {
227
+ const result = session.agent.state.messages.find(
228
+ (message) =>
229
+ message.role === "toolResult" && message.toolCallId === `diagnostic-${index + 1}`,
230
+ );
231
+ assert.ok(result?.role === "toolResult");
232
+ assert.equal(result.isError, scenario.fields.length > 0, JSON.stringify(result));
233
+ if (scenario.fields.length) {
234
+ const report = reportOf(result, scenario.name);
235
+ assert.equal(report?.error, "INVALID_ARGUMENTS");
236
+ assert.deepEqual(
237
+ report?.issues?.map((issue) => issue.field).sort(),
238
+ [...scenario.fields].sort(),
239
+ );
240
+ }
241
+ }
242
+ assert.deepEqual(cases, original);
243
+ assert.equal(await readFile(join(cwd, "diagnostic.txt"), "utf8"), "43");
244
+ });
@@ -72,6 +72,10 @@ test("live preparation failure → replays diagnostic after fresh registration",
72
72
  invalidate() {},
73
73
  lastComponent: undefined,
74
74
  executionStarted: true,
75
+ durationMs: undefined,
76
+ outputPad: 1,
77
+ keyText: () => "",
78
+ keyHint: (_key, description) => description,
75
79
  argsComplete: true,
76
80
  expanded,
77
81
  isPartial: false,
package/src/pi/AGENTS.md CHANGED
@@ -4,12 +4,12 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
4
4
 
5
5
  ## Registration
6
6
 
7
- `src/index.ts` loads the config once and passes it explicitly to each tool factory, which keeps that snapshot for its lifetime. When `enabled` is false it registers nothing. Otherwise it registers tools from their `make*Override` / `makeReplaceTool` factories through one helper that appends `NEXT_GUIDELINE` from `report-schema.ts` (Pi prints the shared guideline once). When `actionFusion` is on, the three mutation tools also receive the Action Fusion executor and are wrapped with `withMutationStatus`; their shared `mutationToolBase` (`mutation-runner.ts`) applies `withThenRunDescription`, which appends the then_run selection instructions, as `withThenRunSchema` adds the field, and the field's `command` description carries the Windows path note only when `process.platform` is `win32`.
7
+ `src/index.ts` loads the config once; each tool captures that snapshot for its lifetime, and a reload registers the tools again. When `enabled` is false it registers nothing. Otherwise it registers the model-budget provider (`registerModelBudgets`) and the Action Fusion cards (`registerFusionCards`, always, so saved then_run cards render while Action Fusion is off), builds the Action Fusion executor from the cards' progress reporter only when `actionFusion` is on, and passes each tool factory one environment: `ToolEnvironment` (`cwd`, `config`, and the `budgets` provider; `config.ts`) for `read` and `grep`, and `MutationToolEnvironment` (the same plus `fusion`, undefined when Action Fusion is off; `mutation-runner.ts`) for `write`, `edit`, and `replace`. Tools register in the order write, edit, replace, read, grep. One helper appends `NEXT_GUIDELINE` from `report-schema.ts` to every tool's `promptGuidelines` (Pi prints the shared guideline once); the mutation tools are also wrapped with `withMutationStatus` when the executor exists. Their shared `mutationToolBase` (`mutation-runner.ts`) adds the `then_run` field (`withThenRunSchema`), its selection instructions in the description (`withThenRunDescription`), and `ACTION_FUSION_GUIDELINES` only when `fusion` exists; the field's `command` description carries the Windows path note only when `process.platform` is `win32`.
8
8
 
9
9
  ## Argument funnel
10
10
 
11
- - Tool files (`read-tool.ts`, `grep-tool.ts`, `edit-tool.ts`, `replace-tool.ts`, `write-tool.ts`) define TypeBox schemas and each mutation tool's description names its alternative (edit ↔ replace ↔ write). Each tool's `prepareArguments` comes from `argument-validation.ts`, then Pi validates against the schema again, and only then calls `execute`. Caller arguments are never rewritten. Each tool supplies only the semantic checks the schema cannot express or name precisely: edit rejects fields an operation's `action` does not take or requires but lacks, empty bodies, body lines that cannot be written as UTF-8, line numbers beyond the safe-integer range, anchors of another hash length, and reversed ranges; replace rejects unwritable replacement text; replace and grep share `checkRegexArguments`, which reports flags V8 rejects and compiles regex-mode patterns; write rejects unwritable content. File-dependent checks stay in execution. Shared integer rules live in `schema.ts`. Every tool declares `STRICT_SAMPLING` from `schema.ts` (mutation tools through `mutationToolBase`) and keeps its parameters convertible by Pi's strict converter: no object or array unions, so grep's multi-valued fields are arrays only and each edit item is one flat object whose `EDIT_OPS` table, not the schema, fixes the fields per action. Constrained sampling and some gateways emit keys alphabetically, so the item's discriminator keeps the alphabetically first key.
12
- - `argument-validation.ts` owns every tool's `prepareArguments` hook, issue collection, bounded diagnostic output, and the Pi schema validation adapter. Tools report semantic field issues through its callback and do not throw during collection. Successful schema conversion informs those checks without changing caller arguments. Observe prepared failures without reimplementing coercion or optional-null rules.
11
+ - Tool files (`read-tool.ts`, `grep-tool.ts`, `edit-tool.ts`, `replace-tool.ts`, `write-tool.ts`) define TypeBox schemas and each mutation tool's description names its alternative (edit ↔ replace ↔ write). Each tool's `prepareArguments` comes from `argument-validation.ts`, then Pi validates against the schema again, and only then calls `execute`. Caller arguments are never rewritten. Each tool supplies only the semantic checks the schema cannot express or name precisely: edit rejects fields an operation's `action` does not take or requires but lacks, an empty `lines` array, `lines` entries that cannot be written as UTF-8, line numbers beyond the safe-integer range, anchors of another hash length, and reversed ranges; replace rejects unwritable replacement text; replace and grep share `checkRegexArguments`, which reports flags V8 rejects and compiles regex-mode patterns; write rejects unwritable content. File-dependent checks stay in execution. Shared integer rules live in `schema.ts`. Every tool declares `STRICT_SAMPLING` from `schema.ts` (mutation tools through `mutationToolBase`) and keeps its parameters convertible by Pi's strict converter: no object or array unions, so grep's multi-valued fields are arrays only and each edit item is one flat object whose `EDIT_OPS` table, not the schema, fixes the fields per action. Some providers emit keys in declaration order and others alphabetically, so the `edit` and `replace` keys are declared in alphabetical order (`path`, `steps`, `then_run`; `action`, `anchor`, `end`, `lines`; `path`, `replacements`, `then_run`): both orders stream the file and each operation's action and range before the payload.
12
+ - `argument-validation.ts` owns every tool's `prepareArguments` hook, issue collection, bounded diagnostic output, and the Pi schema validation adapter. Tools report semantic field issues through its callback and do not throw during collection. Successful schema conversion informs those checks without changing caller arguments. On schema failure, prepare diagnostic values with the public pi-schema coercer using Pi's formats and unresolved-reference policy; Pi alone decides acceptance. Do not reimplement coercion or optional-null rules.
13
13
  - `argument-diagnostics.ts` owns failure-only schema projection and structured aggregation. Top-level tool fields have independent schemas; failure diagnosis derives field schemas with TypeBox and keeps Pi's coercion and per-field error limits. Derive choices and the explanations of missing, undeclared, pattern-mismatched, and out-of-choice fields from the declared schema: when a schema reason does not say how to correct the value, the `fix` of a missing field, a pattern mismatch, or a value outside the field's choices is the field's description (each choice's value and description), and an undeclared field's `fix` lists its object's accepted fields. A declared field is applicable even when absent, so a tool check may require it. An issue on a whole object leaves its fields' diagnostics in place. Suppress only inapplicable or already explained issues, and retain independent fields with bounded native diagnostics.
14
14
  - `argument-error.ts` owns the JSON argument-error envelope and its byte budget: retain exact field paths, omit whole issues with explicit counts, and never truncate serialized JSON or repeat the call's arguments. Preparation failures use the same envelope.
15
15
 
@@ -24,7 +24,7 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
24
24
  ## grep
25
25
 
26
26
  - Split into `grep-tool` (schema and execution order), `grep-scope` (paths and glob admission), `grep-candidates` (candidate strategy, fallback, whole-scope scan budget, and the empty-scope guard), `grep-search` (queue backpressure, worker pool, per-file matches with their revisions), `grep-reread` (content mode's bounded second read of each matched file and its revision check), `grep-output` (payload rows, file-header format and its parser, and every grep report fact, including empty and incomplete searches), and `grep-render` (TUI rows). Grep scans each candidate file once through `text-stream.ts` (via `scanTextFile`) for NUL, UTF-8 validity, its revision, and the lossy LF view it matches; content mode reads each matched file again in `grep-reread`. Each stage returns ordered `SearchWarning` records (`{ path?, reason }`) in its result rather than composing sentences; `grep-tool` joins stages in order, and only `grep-output` formats diagnostics with cwd-relative paths, de-duplicates them, and applies the field budget. README defines resource limits and physical-line reporting; document file and worker budgets there.
27
- - Without `multiline`, `rg-regex.ts` translates each pattern into rg patterns that list every line the query matches: keep a construct only where both engines give it the same meaning over the original line bytes (CRLF, malformed UTF-8, surrogate halves included), and otherwise widen it; never narrow. Bound string expansion and emitted patterns. Preserve every alternative. A multiline query, unsupported or oversized translation, or pattern rg rejects before reporting a file uses the file prefilter.
27
+ - Without `multiline`, `rg-regex.ts` translates each pattern into rg patterns that list every line the query matches: keep a construct only where both engines give it the same meaning over the original line bytes (CRLF, malformed UTF-8, surrogate halves included), and otherwise widen it; never narrow. Bound string expansion and emitted patterns. Preserve every alternative. In a backreference's repeated text, membership keeps each node's original scoped case flags, and the reference's case widening is applied afterward through the existing byte translator (`scalarRanges`, `backreference`). A multiline query, unsupported or oversized translation, or pattern rg rejects before reporting a file uses the file prefilter.
28
28
  - `rg-process.ts` is the ripgrep process layer: spawning, bounded reading, and parsing rg's output protocols (`runRgPaths` reads NUL-delimited paths; `runRgLines` reads the per-file line numbers of `LINE_LISTING_ARGS`). It knows no candidate strategy. Completed-run diagnostics leave this layer as reason-only warning data; path formatting belongs to `grep-output`. Scope flags are produced only in `grep-scope.ts` and never parsed back.
29
29
  - `grep-candidates.ts` decides which rg runs to make: line candidates through `rg-regex.ts` (workers re-check only those lines through `searchLines`), else candidate files (`--files-with-matches` over the necessary literals, or `--files` when none is necessary or they exceed `MAX_RG_PATTERN_UNITS`). Byte-level pattern flags are defined once there.
30
30
  - Keep grep matching in the bounded, cancellable worker pool of `grep-search.ts`: a lazily started pool, each worker sending `core/search.ts` whole lines in bounded requests, or the whole file for a multiline query. Commit file results, warnings, and fatal failures in listing order; retire a worker after a fatal file result, but propagate cancellation without waiting for earlier files.
@@ -32,20 +32,20 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
32
32
 
33
33
  ## Regex workers
34
34
 
35
- `regex-worker.ts` owns timeout, cancellation, and cleanup for grep and replace workers; each caller awaits a request before sending another to the same worker. Their `.mjs` bootstraps load TypeScript through `jiti`, because workers do not inherit Pi's loader; workers never import the Pi runtime and trust inputs validated at tool entry. `replace-regex.ts` owns the replacement request and sends regex batches to `core/replace.ts`; literal-only batches remain in-process. `config.ts` owns both timeout settings. The host validates exactly-one-result replies with `regex-worker-contract.ts`, using code-specific facts from `report-schema.ts` and each engine's result schema (`core/replace-schema.ts`, `core/search-schema.ts`). Bound worker failures only in the receiving tool.
35
+ `regex-worker.ts` owns timeout, cancellation, and cleanup for grep and replace workers; each caller awaits a request before sending another to the same worker. Each worker (`grep-worker.ts` runs `core/search.ts`; `replace-worker.ts` runs `core/replace.ts`) is started through its `.mjs` bootstrap, which loads TypeScript through `jiti`, because workers do not inherit Pi's loader; workers never import the Pi runtime and trust inputs validated at tool entry. `replace-regex.ts` owns the replacement request and sends regex batches to `core/replace.ts`; literal-only batches remain in-process. `config.ts` owns both timeout settings. The host validates exactly-one-result replies with `regex-worker-contract.ts`, using code-specific facts from `report-schema.ts` and each engine's result schema (`core/replace-schema.ts`, `core/search-schema.ts`). Bound worker failures only in the receiving tool.
36
36
 
37
37
  ## Reports and rendering
38
38
 
39
39
  - `report-schema.ts` is the single definition of the result protocol: every report field in output order (each with one owning layer), its schema, audience, and model decision purpose, every error code with its facts schema and recovery (`next.default` plus named alternatives), and the success recovery order (`OUTCOME_NEXT`). `FACT_FIELDS` is the required declaration point; model omission is derived from its audience together with the call fields, so `report.ts` does not maintain a second field set. Checked report types retain their tool or error-code variant; absent fields remain readable as undefined. Types derive from it. Its closed wire schemas validate text-only reports, enforce legal tool names, and require code-specific facts.
40
- - `report.ts` builds reports and owns their one model-facing serialization (`renderReport`: one JSON object, fields in schema order). It filters the derived model omission set (`MODEL_OMITTED_FIELDS`) and omits the call's own `tool`/`path` plus TUI-only facts from result text while retaining them in `details.report`; renderers pass their tool name to decode text-only reports. `reportResult` appends a success report after the tool's payload; every tool's `execute` runs inside `runTool`, which classifies a failure (`describeFailure`, structured `cause`, `next` from code and publication) and returns it as an `isError` result whose `details.report` the TUI renders. This module receives a mutation's failure facts from `mutation-result.ts` and does not depend on the commit layer.
41
- - `render.ts` (`reportLines`) is the one TUI renderer of a report and holds the shared tool renderers. Render inputs admit partial details independently of the current execution result. Failure rendering uses `details.report`; Pi raises argument errors before execution, so text-only argument rejections decode from the final content block with `decodeReport`. Report text omits its tool, so every `decodeReport` call supplies the originating call's tool name. Invalid text-only reports remain raw.
40
+ - `report.ts` builds reports and owns their one model-facing serialization (`renderReport`: one JSON object, fields in schema order). It filters the derived model omission set (`MODEL_OMITTED_FIELDS`) and omits the call's own `tool`/`path` plus TUI-only facts from result text while retaining them in `details.report`; renderers pass their tool name to `reportOf`, which reads `details.report` (checked once by `detailsReport`) or else decodes a text-only report. `reportResult` appends a success report after the tool's payload only when the report states a model-visible fact or the result has no payload; every tool's `execute` runs inside `runTool`, which classifies a failure (`describeFailure`, structured `cause`, `next` from code and publication) and returns it as an `isError` result whose `details.report` the TUI renders. This module receives a mutation's failure facts from `mutation-result.ts` and does not depend on the commit layer.
41
+ - `render.ts` (`reportLines`) is the one TUI renderer of a report and holds the shared tool renderers. Render inputs admit partial details independently of the current execution result. Renderers read reports only through `splitReport` (a success: the checked report and the content before its trailing report block, stripped only when that block equals `renderReport(details.report)`) or `renderToolError` (a failure). Failure rendering uses `details.report`; Pi raises argument errors before execution, so a text-only argument rejection decodes from the final content block through `reportOf`. Report text omits its tool, so every decode supplies the originating call's tool name. Invalid text-only reports remain raw.
42
42
  - `report-cause.ts` transports structured causes without Pi runtime imports, preserving cause chains with cycle protection; reports and worker replies share it. Native failures state the original diagnostic and errno once in `message`, retaining only an actual underlying `Error.cause`.
43
- - To add or change a report field: (1) declare it in `FACT_FIELDS` under its owning layer's group, including its audience and, for model-visible facts, the non-empty decision it changes; (2) list it in each `SUCCESS_DEFINITIONS` tool or `ERROR_DEFINITIONS` code that carries it; (3) when it needs recovery, add one `OUTCOME_NEXT` rule or the code's `next`, never a sentence at the producing site; (4) produce it in that one layer, bounded by the call's budget, omitting whole items with a count; (5) leave `render.ts` alone unless a card presents the fact another way, and then name it in that card's shown set; (6) check the README passage for the tool. The model omission set is derived from the declarations; do not add a parallel list in `report.ts`. To change an error code, edit `ERROR_DEFINITIONS` and follow the type errors to every throw site and the worker contract.
43
+ - To add or change a report field: (1) declare it in `FACT_FIELDS` under its owning layer's group, including its audience and, for model-visible facts, the decision it changes: the concrete call the model makes differently for each value (`decide whether…` and `account for…` name no call); (2) list it in each `SUCCESS_DEFINITIONS` tool or `ERROR_DEFINITIONS` code that carries it; (3) when it needs recovery, add one `OUTCOME_NEXT` rule or the code's `next`, never a sentence at the producing site; when the recovery depends on the call's arguments, the rule names alternatives and the producing layer selects one (`OutcomeVariant`, passed to `reportResult`), so the text never asks the model to branch; (4) produce it in that one layer, bounded by the call's budget, omitting whole items with a count; (5) leave `render.ts` alone unless a card presents the fact another way, and then name it in that card's shown set; (6) check the README passage for the tool. The model omission set is derived from the declarations; do not add a parallel list in `report.ts`. To change an error code, edit `ERROR_DEFINITIONS` and follow the type errors to every throw site and the worker contract.
44
44
  - `error-text.ts` holds the Pi-layer error forms (cancellation, file changed during read or search). `diagnostic-buffer.ts` bounds stderr and search diagnostics.
45
45
 
46
46
  ## Budgets and config
47
47
 
48
- - `budgets.ts` derives model-facing byte budgets from the selected model's declared `contextWindow`, with bounded defaults for unknown limits. Standalone tool factories default to its provider; internal helpers require the resolved budget or explicit byte limit. `model-budgets.ts` derives the budgets from the live selected model on each request; preparation shares its provider, and each execution captures its budgets before its asynchronous work. Model-derived content budgets share the `MAX_CONTENT_KIB` ceiling that the explicit `read.maxKiB` range also uses.
48
+ - `budgets.ts` derives model-facing byte budgets from the selected model's declared `contextWindow`, with bounded defaults for unknown limits. Every tool factory receives the provider as `ToolEnvironment.budgets` (`config.ts`); internal helpers require the resolved budget or an explicit byte limit. `model-budgets.ts` derives the budgets from the live selected model on each request; preparation shares its provider, and each execution captures its budgets before its asynchronous work. Model-derived content budgets share the `MAX_CONTENT_KIB` ceiling that the explicit `read.maxKiB` range also uses.
49
49
  - `config.ts` defines the `hashlineEdit` settings as one TypeBox schema: top-level `enabled`, `actionFusion`, `hashLen`, `shiftRadius` control shared behavior; the `read`, `grep`, and `replace` groups hold tool-specific settings. Missing or invalid optional `read.maxKiB` selects automatic model sizing.
50
50
 
51
51
  ## Action Fusion
@@ -26,6 +26,29 @@ const {
26
26
  makeWriteOverride,
27
27
  } = await import("./tool-factories.testing.ts");
28
28
 
29
+ test("grep has invalid flags alongside invalid literal or pattern → reports independent fields", async (t) => {
30
+ const tool = makeGrepOverride(process.cwd(), DEFAULT_CONFIG);
31
+ for (const args of [
32
+ { pattern: ["text"], flags: "x" },
33
+ { pattern: ["text"], literal: {}, flags: "x" },
34
+ { pattern: {}, literal: true, flags: "x" },
35
+ ]) {
36
+ await t.test(JSON.stringify(args), async () => {
37
+ await assert.rejects(callTool(tool, args), (error: unknown) => {
38
+ const fields = argumentError(error).issues.map((issue) => issue.field);
39
+ assert.ok(fields.includes("flags"), JSON.stringify(fields));
40
+ assert.ok(
41
+ fields.some((field) =>
42
+ Array.isArray(args.pattern) ? field === "literal" : field.startsWith("pattern"),
43
+ ),
44
+ JSON.stringify(fields),
45
+ );
46
+ return true;
47
+ });
48
+ });
49
+ }
50
+ });
51
+
29
52
  const invalidCommand = { command: "", timeout: 0 };
30
53
  const anchorHash = "A".repeat(DEFAULT_CONFIG.hashLen);
31
54
  const cases = [
@@ -240,6 +263,46 @@ test("grep and replace flags → accept V8 modes and reject invalid flags before
240
263
  }
241
264
  });
242
265
 
266
+ test("invalid regex pattern → explains literal recovery without changing the requested mode", async (t) => {
267
+ const cwd = await mkdtemp(join(tmpdir(), "hashline-regex-recovery-"));
268
+ t.after(() => rm(cwd, { recursive: true, force: true }));
269
+ const path = join(cwd, "missing.txt");
270
+ const cases = [
271
+ {
272
+ tool: makeGrepOverride(cwd, DEFAULT_CONFIG),
273
+ args: (find: string, literal: boolean) => ({ pattern: [find], literal }),
274
+ field: "pattern[0]",
275
+ },
276
+ {
277
+ tool: makeReplaceTool(cwd, DEFAULT_CONFIG),
278
+ args: (find: string, literal: boolean) => ({
279
+ replacements: [{ find, literal, replace: "updated" }],
280
+ }),
281
+ field: "replacements[0].find",
282
+ },
283
+ ];
284
+ for (const { tool, args, field } of cases) {
285
+ await t.test(tool.name, async () => {
286
+ const input = { path, ...args("call(", false) };
287
+ const original = structuredClone(input);
288
+ await assert.rejects(callTool(tool, input), (error: unknown) => {
289
+ const { issues } = argumentError(error);
290
+ assert.equal(issues.length, 1);
291
+ assert.equal(issues[0].field, field);
292
+ assert.match(issues[0].reason, /Invalid regular expression/);
293
+ assert.match(issues[0].fix ?? "", /literal.*true.*otherwise.*regex/);
294
+ return true;
295
+ });
296
+ assert.deepEqual(input, original);
297
+ for (const corrected of [args("call(", true), args("call\\(", false)]) {
298
+ const result = await callTool(tool, { path, ...corrected });
299
+ assert.equal(reportOf(result, tool.name)?.error, "PATH_NOT_FOUND");
300
+ }
301
+ await assert.rejects(readFile(path), { code: "ENOENT" });
302
+ });
303
+ }
304
+ });
305
+
243
306
  const editFields = ["anchor", "end", "lines"] as const;
244
307
  type EditField = (typeof editFields)[number];
245
308
  const fieldValues = {
@@ -1,12 +1,14 @@
1
1
  /**
2
2
  * Shared tool argument boundary. Pi owns preparation and acceptance; tool checks
3
- * report semantic issues. Failure-only diagnostics observe Pi's prepared value,
3
+ * report semantic issues. Failure-only diagnostics use pi-schema's public coercer,
4
4
  * then project and aggregate the declared schema in argument-diagnostics.ts.
5
5
  * Pi still validates returned arguments in its mandatory tool-call pipeline.
6
6
  * Tool schemas have no cross-field constraints.
7
7
  */
8
8
  import { validateToolArguments, type ToolCall } from "@earendil-works/pi-ai";
9
- import { ObjectOptions, Type, type Static, type TObject, type TSchema } from "typebox";
9
+ import { compile } from "@earendil-works/pi-schema";
10
+ import { formats } from "@earendil-works/pi-schema/formats";
11
+ import type { Static, TObject } from "typebox";
10
12
  import { errorMessage } from "../core/errors.ts";
11
13
  import { diagnoseArguments } from "./argument-diagnostics.ts";
12
14
  import { formatArgumentError } from "./argument-error.ts";
@@ -28,45 +30,34 @@ export function createArgumentPreparer<T extends TObject>(
28
30
  check: CheckArguments | undefined,
29
31
  budgets: OutputBudgetProvider,
30
32
  ): (args: unknown) => Static<T> {
31
- const validate = (schema: TSchema, args: unknown): unknown =>
32
- validateToolArguments(
33
- { name, parameters: schema, description: "" },
34
- // Pi owns shape checking and coercion at this external boundary.
35
- {
36
- type: "toolCall",
37
- id: "argument-validation",
38
- name,
39
- arguments: args as ToolCall["arguments"],
40
- },
41
- );
33
+ const diagnosticValidator = compile(parameters, {
34
+ formats,
35
+ coerce: true,
36
+ unresolvedRefs: "reject",
37
+ });
42
38
 
43
39
  return (args) => {
44
40
  let checked: unknown = args;
45
41
  let schemaFailure: unknown;
46
42
  try {
47
- checked = validate(parameters, args);
43
+ checked = validateToolArguments(
44
+ { name, parameters, description: "" },
45
+ // Pi owns shape checking and coercion at this external boundary.
46
+ {
47
+ type: "toolCall",
48
+ id: "argument-validation",
49
+ name,
50
+ arguments: args as ToolCall["arguments"],
51
+ },
52
+ );
48
53
  } catch (error) {
49
54
  schemaFailure = error;
50
55
  }
51
56
  if (schemaFailure !== undefined) {
52
- let observation: { readonly value: unknown } | undefined;
53
- // Pi does not expose failed prepared values. A successful allOf refinement
54
- // observes its error pass without changing coercion, null handling or acceptance.
55
- const observer = Type.Object(parameters.properties, {
56
- ...ObjectOptions(parameters),
57
- allOf: [
58
- Type.Refine(Type.Unknown(), (value: unknown) => {
59
- observation = { value };
60
- return true;
61
- }),
62
- ],
63
- });
64
57
  try {
65
- validate(observer, args);
58
+ checked = diagnosticValidator.coerce(structuredClone(args));
66
59
  } catch {
67
- // The original schema already failed; this call only observes preparation.
68
- }
69
- if (!observation) {
60
+ // Preparation failures retain Pi's original cause in the shared error envelope.
70
61
  throw new Error(
71
62
  formatArgumentError(
72
63
  [{ field: "$", reason: errorMessage(schemaFailure) }],
@@ -76,7 +67,6 @@ export function createArgumentPreparer<T extends TObject>(
76
67
  { cause: schemaFailure },
77
68
  );
78
69
  }
79
- checked = observation.value;
80
70
  }
81
71
  const issues: ArgumentIssue[] = [];
82
72
  check?.(checked, (field, reason, fix) =>
@@ -108,7 +108,7 @@ function buildEditSchema(hashLen: number) {
108
108
  },
109
109
  {
110
110
  additionalProperties: false,
111
- description: "One operation. Omit, or set to null, each field its action does not take.",
111
+ description: "One step. Omit, or set to null, each field its action does not take.",
112
112
  },
113
113
  );
114
114
  return Type.Object(
@@ -117,7 +117,7 @@ function buildEditSchema(hashLen: number) {
117
117
  steps: Type.Array(editOpSchema, {
118
118
  minItems: 1,
119
119
  maxItems: MAX_EDIT_OPS,
120
- description: `Operations on one snapshot; ranges must not overlap. Each gap between lines takes at most one insertion; insert_after N and insert_before N+1 target the same gap, so put all new lines for a gap in one operation. An insertion at the start of a replaced or deleted range goes before it. Anchors are LINE#HASH with exactly ${hashLen} hash characters. Copy each anchor from read, grep, or edit failure diagnostics; never write a hash you have not seen there. Shell output such as sed, head, or cat has no anchors, so read or grep those lines first.`,
120
+ description: `Steps applied to one snapshot; ranges must not overlap. Each gap between lines takes at most one insertion; insert_after N and insert_before N+1 target the same gap, so put all new lines for a gap in one step. An insertion at the start of a replaced or deleted range goes before it. Anchors are LINE#HASH with exactly ${hashLen} hash characters. Copy each anchor from read, grep, or edit failure diagnostics; never write a hash you have not seen there. Shell output such as sed, head, or cat has no anchors, so read or grep those lines first.`,
121
121
  }),
122
122
  },
123
123
  { additionalProperties: false },
@@ -603,6 +603,10 @@ test("failed commands preserve mutation results and stay out of all main card re
603
603
  invalidate() {},
604
604
  lastComponent: undefined,
605
605
  executionStarted: true,
606
+ durationMs: undefined,
607
+ outputPad: 1,
608
+ keyText: () => "",
609
+ keyHint: (_key, description) => description,
606
610
  argsComplete: true,
607
611
  isPartial: false,
608
612
  expanded: true,
@@ -320,7 +320,7 @@ test("overlapping edits → ordered conflict and shared recovery", () => {
320
320
  assert.deepEqual(report.conflict, ["steps[0]", "steps[2]"]);
321
321
  assert.equal(report.message, error.message);
322
322
  assert.equal(report.publication, "NOT_PUBLISHED");
323
- assert.match(report.next ?? "", /one edit per range or position/);
323
+ assert.match(report.next ?? "", /one step per range or position/);
324
324
  return true;
325
325
  },
326
326
  );
@@ -9,6 +9,7 @@ import type {
9
9
  ExtensionAPI,
10
10
  ExtensionContext,
11
11
  ToolDefinition,
12
+ ToolRenderers,
12
13
  } from "@earendil-works/pi-coding-agent";
13
14
  import {
14
15
  createBashToolDefinition,
@@ -131,15 +132,16 @@ export function registerFusionCards(pi: ExtensionAPI) {
131
132
  });
132
133
  pi.on("session_tree", (_event, ctx) => restore(ctx));
133
134
 
134
- pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, function renderCard(entry, { expanded }):
135
+ pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, function renderCard(entry, options):
135
136
  | Component
136
137
  | undefined {
138
+ const { expanded } = options;
137
139
  const initial = entry.data;
138
140
  if (!Value.Check(COMMAND_CARD_SCHEMA, initial)) return undefined;
139
141
  if (!tui) {
140
142
  // Pi may rebuild history before session_start supplies its UI context.
141
143
  let component: Component | undefined;
142
- const ready = () => (component ??= tui ? renderCard(entry, { expanded }) : undefined);
144
+ const ready = () => (component ??= tui ? renderCard(entry, options) : undefined);
143
145
  return {
144
146
  render: (width) => ready()?.render(width) ?? [],
145
147
  invalidate: () => component?.invalidate(),
@@ -155,15 +157,16 @@ export function registerFusionCards(pi: ExtensionAPI) {
155
157
  let box = new Box(outputPadding, 1);
156
158
  let call: Component | undefined;
157
159
  let result: Component | undefined;
158
- const renderers: Pick<typeof bash, "renderShell" | "renderCall" | "renderResult"> = {
160
+ const renderers: ToolRenderers = {
159
161
  renderShell: "self",
160
- renderCall(args, theme, context) {
162
+ renderCall(_args, theme, context) {
161
163
  const padding = SettingsManager.inMemory(pi.getSettings()).getOutputPad();
162
164
  if (padding !== outputPadding) {
163
165
  outputPadding = padding;
164
166
  box = new Box(outputPadding, 1);
165
167
  }
166
168
  const value = current();
169
+ const args = { command: value.commandText, timeout: value.timing?.timeoutSeconds };
167
170
  const pending = commandPending(value);
168
171
  const interrupted = pending && !active.has(value.toolCallId);
169
172
  const status = interrupted ? "interrupted (final status unknown)" : value.command;
@@ -192,7 +195,7 @@ export function registerFusionCards(pi: ExtensionAPI) {
192
195
  statusText.setText(
193
196
  `${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status + countdown)}`,
194
197
  );
195
- call = bash.renderCall!(args, theme, { ...context, lastComponent: call });
198
+ call = bash.renderCall!(args, theme, { ...context, args, lastComponent: call });
196
199
  box.clear();
197
200
  box.addChild(statusText);
198
201
  box.addChild(call);
@@ -205,6 +208,7 @@ export function registerFusionCards(pi: ExtensionAPI) {
205
208
  if (current().result) {
206
209
  result = bash.renderResult!(value, options, theme, {
207
210
  ...context,
211
+ args: { command: current().commandText, timeout: current().timing?.timeoutSeconds },
208
212
  lastComponent: result,
209
213
  });
210
214
  box.addChild(result);
@@ -10,7 +10,7 @@ import { stat } from "node:fs/promises";
10
10
  import { resolve } from "node:path";
11
11
  import type { GrepQuery } from "../core/search.ts";
12
12
  import { extractPrefilter, type Literal, type Prefilter } from "../core/search-analysis.ts";
13
- import { scopeArgs, type SearchScope } from "./grep-scope.ts";
13
+ import { foldedPathKey, isListedFile, scopeArgs, type SearchScope } from "./grep-scope.ts";
14
14
  import {
15
15
  COMMON_RG_ARGS,
16
16
  LINE_LISTING_ARGS,
@@ -94,13 +94,14 @@ export async function listCandidates(options: {
94
94
  let listedAny = false;
95
95
  let scanned = 0;
96
96
  let scanLimitReached = false;
97
- const seen = new Set<string>();
97
+ const seen = new Map<string, string[]>();
98
98
  const offer = async (path: string, lines?: readonly number[]) => {
99
99
  listedAny = true;
100
100
  if (stopped()) return false;
101
101
  const filePath = resolve(path);
102
- if (seen.has(filePath)) return true;
103
- seen.add(filePath);
102
+ if (await isListedFile(filePath, seen)) return true;
103
+ const key = foldedPathKey(filePath);
104
+ seen.set(key, [...(seen.get(key) ?? []), filePath]);
104
105
  if (candidates === "all") {
105
106
  if (scanned >= MAX_UNNARROWED_SCAN_BYTES) {
106
107
  scanLimitReached = true;
@@ -14,7 +14,7 @@ import { rereadMatches, type LineCollector } from "./grep-reread.ts";
14
14
  import { formatByteSize, type OutputBudgets } from "./budgets.ts";
15
15
  import { HashlineError } from "../core/errors.ts";
16
16
  import { serializePath } from "./path.ts";
17
- import type { Report, SuccessFacts } from "./report-schema.ts";
17
+ import type { OutcomeVariant, Report, SuccessFacts } from "./report-schema.ts";
18
18
 
19
19
  /** How grep presents matches; the tool's schema offers these and this module formats each. */
20
20
  export const GREP_OUTPUT_MODES = ["content", "files", "count"] as const;
@@ -170,6 +170,7 @@ interface AssembleGrepOutputOptions {
170
170
  readonly cwd: string;
171
171
  readonly warnings: readonly SearchWarning[];
172
172
  readonly outputMode: GrepOutputMode;
173
+ readonly context: number;
173
174
  readonly matchLimitReached: boolean;
174
175
  readonly effectiveLimit: number;
175
176
  readonly searchFacts: SearchFacts;
@@ -180,12 +181,14 @@ interface AssembleGrepOutputOptions {
180
181
  function assembleGrepOutput(options: AssembleGrepOutputOptions): {
181
182
  payload: string;
182
183
  facts: SuccessFacts<"grep">;
184
+ next?: OutcomeVariant;
183
185
  } {
184
186
  const {
185
187
  formatted,
186
188
  cwd,
187
189
  warnings,
188
190
  outputMode,
191
+ context,
189
192
  matchLimitReached,
190
193
  effectiveLimit,
191
194
  searchFacts,
@@ -229,6 +232,8 @@ function assembleGrepOutput(options: AssembleGrepOutputOptions): {
229
232
  invalidUtf8: invalidUtf8.length ? invalidUtf8 : undefined,
230
233
  diagnostics: warnings.length ? searchDiagnostics(warnings, cwd, budget) : undefined,
231
234
  },
235
+ // Only content mode with a nonzero context spends the byte budget on context rows.
236
+ next: outputMode === "content" && context > 0 ? "contextRows" : undefined,
232
237
  };
233
238
  }
234
239
 
@@ -245,8 +250,9 @@ export async function grepOutput(
245
250
  /** A literal pattern contains `|`, which matches only that character. */
246
251
  readonly literalPipe: boolean;
247
252
  },
248
- ): Promise<{ payload?: string; facts: SuccessFacts<"grep"> }> {
249
- const { cwd, search, warnings, outputMode, effectiveLimit, literalPipe, budget } = options;
253
+ ): Promise<{ payload?: string; facts: SuccessFacts<"grep">; next?: OutcomeVariant }> {
254
+ const { cwd, search, warnings, outputMode, context, effectiveLimit, literalPipe, budget } =
255
+ options;
250
256
  const searchFacts: SearchFacts = {
251
257
  scanLimit: search.scanLimitReached ? formatByteSize(MAX_UNNARROWED_SCAN_BYTES) : undefined,
252
258
  };
@@ -267,6 +273,7 @@ export async function grepOutput(
267
273
  cwd,
268
274
  warnings: [...warnings, ...rereadWarnings],
269
275
  outputMode,
276
+ context,
270
277
  matchLimitReached: search.matchLimitReached,
271
278
  effectiveLimit,
272
279
  searchFacts,
@@ -55,11 +55,11 @@ export async function resolveSearchPaths(cwd: string, path: readonly string[] |
55
55
  }
56
56
 
57
57
  /** Groups spellings that a case-insensitive filesystem may treat as one file. */
58
- const foldedKey = (path: string): string => resolve(path).toLowerCase();
58
+ export const foldedPathKey = (path: string): string => resolve(path).toLowerCase();
59
59
 
60
- /** Whether rg listed the named file, possibly under its on-disk case spelling. */
61
- async function isListed(path: string, listed: ReadonlyMap<string, readonly string[]>) {
62
- const spellings = listed.get(foldedKey(path)) ?? [];
60
+ /** Whether the listed spellings include the same file, without folding distinct files together. */
61
+ export async function isListedFile(path: string, listed: ReadonlyMap<string, readonly string[]>) {
62
+ const spellings = listed.get(foldedPathKey(path)) ?? [];
63
63
  const absolute = resolve(path);
64
64
  if (spellings.some((spelling) => resolve(spelling) === absolute)) return true;
65
65
  if (!spellings.length) return false;
@@ -103,12 +103,12 @@ export async function filterExplicitFilesByGlob(
103
103
  ...parents,
104
104
  ];
105
105
  const listed = await runRgPaths(args, signal, async (path) => {
106
- const key = foldedKey(path);
106
+ const key = foldedPathKey(path);
107
107
  allowed.set(key, [...(allowed.get(key) ?? []), path]);
108
108
  return true;
109
109
  });
110
110
  const admitted = new Set<string>();
111
- for (const { path } of explicitFiles) if (await isListed(path, allowed)) admitted.add(path);
111
+ for (const { path } of explicitFiles) if (await isListedFile(path, allowed)) admitted.add(path);
112
112
  // Listing diagnostics about sibling entries matter only when they may explain an exclusion.
113
113
  const diagnostic = admitted.size < explicitFiles.length ? searchDiagnostic(listed) : undefined;
114
114
  return {