@criogaid/pi-hashline-edit 0.11.0 → 0.13.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 (94) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +73 -17
  3. package/README.zh-CN.md +74 -18
  4. package/package.json +8 -7
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +15 -2
  7. package/src/core/apply.ts +6 -10
  8. package/src/core/case-fold.test.ts +16 -25
  9. package/src/core/case-fold.ts +4 -4
  10. package/src/core/character-set.test.ts +1 -6
  11. package/src/core/character-set.ts +7 -61
  12. package/src/core/regex.ts +2 -32
  13. package/src/core/replace.test.ts +51 -0
  14. package/src/core/replace.ts +10 -4
  15. package/src/core/search-analysis.test.ts +66 -61
  16. package/src/core/search-analysis.ts +24 -39
  17. package/src/core/search-matrix.test.ts +2 -2
  18. package/src/core/search-matrix.testing.ts +6 -16
  19. package/src/core/search-schema.ts +0 -1
  20. package/src/core/search.test.ts +6 -19
  21. package/src/core/search.ts +10 -8
  22. package/src/index.ts +28 -3
  23. package/src/integration/config-registration.test.ts +77 -4
  24. package/src/integration/fusion-dispatch.test.ts +47 -2
  25. package/src/integration/grep-errors.test.ts +31 -0
  26. package/src/integration/grep-flags.test.ts +13 -196
  27. package/src/integration/grep-js-completeness.test.ts +41 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -33
  29. package/src/integration/grep-matrix.test.ts +1 -1
  30. package/src/integration/grep-path-matrix.test.ts +59 -65
  31. package/src/integration/grep-prefilter-coverage.test.ts +26 -8
  32. package/src/integration/grep-process-limits.test.ts +46 -0
  33. package/src/integration/grep-regex.test.ts +7 -2
  34. package/src/integration/grep-rg.test.ts +106 -12
  35. package/src/integration/grep-translation.test.ts +14 -7
  36. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  37. package/src/integration/npm-package.test.ts +12 -10
  38. package/src/integration/npm-package.testing.ts +147 -1
  39. package/src/integration/replace-package.testing.ts +2 -2
  40. package/src/integration/report-replay.test.ts +4 -0
  41. package/src/pi/AGENTS.md +23 -15
  42. package/src/pi/action-fusion.test.ts +38 -4
  43. package/src/pi/action-fusion.ts +23 -19
  44. package/src/pi/argument-diagnostics.ts +28 -48
  45. package/src/pi/argument-validation.test.ts +103 -6
  46. package/src/pi/argument-validation.ts +55 -31
  47. package/src/pi/budgets.ts +19 -10
  48. package/src/pi/config.test.ts +1 -1
  49. package/src/pi/diagnostic-buffer.test.ts +1 -0
  50. package/src/pi/edit-tool.ts +3 -3
  51. package/src/pi/execute.test.ts +4 -0
  52. package/src/pi/failure-context.test.ts +24 -3
  53. package/src/pi/failure-context.ts +36 -42
  54. package/src/pi/failure-path.test.ts +8 -3
  55. package/src/pi/file-commit.test.ts +109 -52
  56. package/src/pi/file-commit.ts +62 -56
  57. package/src/pi/fusion-card.ts +12 -7
  58. package/src/pi/grep-candidates.test.ts +5 -5
  59. package/src/pi/grep-candidates.ts +80 -48
  60. package/src/pi/grep-matrix.test.ts +14 -29
  61. package/src/pi/grep-order.test.ts +132 -9
  62. package/src/pi/grep-output.ts +173 -48
  63. package/src/pi/grep-render.ts +40 -34
  64. package/src/pi/grep-rg.testing.ts +9 -6
  65. package/src/pi/grep-scope.ts +51 -29
  66. package/src/pi/grep-search.ts +96 -71
  67. package/src/pi/grep-tool.ts +28 -34
  68. package/src/pi/grep.test.ts +348 -83
  69. package/src/pi/model-budgets.test.ts +56 -6
  70. package/src/pi/model-budgets.ts +7 -4
  71. package/src/pi/mutation-result.test.ts +25 -1
  72. package/src/pi/mutation-result.ts +7 -2
  73. package/src/pi/mutation-runner.ts +4 -5
  74. package/src/pi/output-budgets.test.ts +3 -1
  75. package/src/pi/path.ts +18 -4
  76. package/src/pi/pi.test.ts +22 -0
  77. package/src/pi/read-delegation.test.ts +119 -0
  78. package/src/pi/read-tool.ts +109 -61
  79. package/src/pi/read.test.ts +351 -17
  80. package/src/pi/regex-worker.test.ts +42 -0
  81. package/src/pi/regex-worker.ts +17 -11
  82. package/src/pi/registration.test.ts +157 -102
  83. package/src/pi/render.test.ts +97 -0
  84. package/src/pi/render.ts +9 -9
  85. package/src/pi/replace-tool.ts +5 -2
  86. package/src/pi/report-schema.ts +75 -37
  87. package/src/pi/report.test.ts +73 -31
  88. package/src/pi/report.ts +12 -5
  89. package/src/pi/rg-process.ts +41 -5
  90. package/src/pi/rg-regex.test.ts +12 -39
  91. package/src/pi/rg-regex.ts +31 -79
  92. package/src/pi/text-stream.test.ts +3 -0
  93. package/src/pi/text-stream.ts +1 -1
  94. package/src/testing/regex-translation-corpus.ts +39 -96
@@ -26,12 +26,12 @@ test("upstream regex witnesses × LF/CRLF/malformed bytes → sound candidates,
26
26
  t.after(() => rm(directory, { recursive: true, force: true }));
27
27
  for (const [index, example] of REGEX_TRANSLATION_CORPUS.entries()) {
28
28
  await t.test(
29
- `${example.pattern.slice(0, 90)} /${example.flags}`,
30
- { skip: unsupportedByHost([example.pattern], example.flags) },
29
+ `${example.pattern.slice(0, 90)} /${example.ignoreCase ? "mi" : "m"}`,
30
+ { skip: unsupportedByHost([example.pattern], example.ignoreCase ? "mi" : "m") },
31
31
  async () => {
32
32
  const query: GrepQuery = {
33
33
  patterns: [example.pattern],
34
- flags: example.flags,
34
+ ignoreCase: example.ignoreCase,
35
35
  literal: false,
36
36
  multiline: false,
37
37
  };
@@ -114,7 +114,9 @@ test("upstream regex witnesses × LF/CRLF/malformed bytes → sound candidates,
114
114
  }
115
115
  });
116
116
 
117
- test("real rg AND/OR file prefilter → broad candidates retain exact JS results", async (t) => {
117
+ test("real rg AND/OR file prefilter → broad candidates retain exact JS results", {
118
+ skip: unsupportedByHost(["(?s:foo.*bar|baz.*qux)"], "m"),
119
+ }, async (t) => {
118
120
  const directory = await mkdtemp(join(tmpdir(), "hl-regex-conjunction-"));
119
121
  t.after(() => rm(directory, { recursive: true, force: true }));
120
122
  const fixtures = ["foo\nbar", "baz\nqux", "foo\nqux", "baz\nbar", "foo", "bar", "unrelated"];
@@ -125,8 +127,8 @@ test("real rg AND/OR file prefilter → broad candidates retain exact JS results
125
127
  paths.push(path);
126
128
  }
127
129
  const query: GrepQuery = {
128
- patterns: ["(?:foo.*bar|baz.*qux)"],
129
- flags: "s",
130
+ patterns: ["(?s:foo.*bar|baz.*qux)"],
131
+ ignoreCase: false,
130
132
  literal: false,
131
133
  multiline: true,
132
134
  };
@@ -165,7 +167,12 @@ test("oversized line translation → file prefilter fallback preserves JS result
165
167
  const directory = await mkdtemp(join(tmpdir(), "hl-regex-budget-"));
166
168
  t.after(() => rm(directory, { recursive: true, force: true }));
167
169
  const pattern = "a".repeat(30_000);
168
- const query: GrepQuery = { patterns: [pattern], flags: "", literal: true, multiline: false };
170
+ const query: GrepQuery = {
171
+ patterns: [pattern],
172
+ ignoreCase: false,
173
+ literal: true,
174
+ multiline: false,
175
+ };
169
176
  assert.equal(lineCandidatePatterns(query), undefined);
170
177
  const path = join(directory, "long.txt");
171
178
  await writeFile(path, pattern);
@@ -7,7 +7,7 @@ import { callTool } from "../pi/tool-call.testing.ts";
7
7
  import { outputBudgetsFor } from "../pi/budgets.ts";
8
8
  import { reportOf } from "../pi/report.ts";
9
9
  import type { Report } from "../pi/report-schema.ts";
10
- import { openTestSession } from "../testing/session.testing.ts";
10
+ import { openTestSession, responseStream } from "../testing/session.testing.ts";
11
11
 
12
12
  // Budget invalidation relies on Pi publishing the new model before tool preparation.
13
13
  test("model selection → exposes the new limit and invalidates only on a selection change", async (t) => {
@@ -63,7 +63,11 @@ test("model capacity changes → read and grep grow and shrink without re-regist
63
63
  configure: (pi) => hashlineEdit(pi),
64
64
  });
65
65
  const path = join(cwd, "large-row.txt");
66
- const text = "中文🙂".repeat(30_000);
66
+ const smallBudget = outputBudgetsFor(65_536);
67
+ const largeBudget = outputBudgetsFor(1_048_576);
68
+ const text = "中文🙂".repeat(
69
+ Math.floor((smallBudget.readBytes + largeBudget.readBytes) / (2 * Buffer.byteLength("中文🙂"))),
70
+ );
67
71
  await writeFile(path, text);
68
72
  const tool = session.getToolDefinition("read");
69
73
  assert.ok(tool);
@@ -145,3 +149,38 @@ test("model switches before argument preparation → rejection uses the new budg
145
149
  assert.ok(reports[0].omittedIssues);
146
150
  assert.equal(reports[1].omittedIssues, undefined);
147
151
  });
152
+
153
+ test("headless SDK reload → tool results still use the selected model's budget", async (t) => {
154
+ const { session, cwd, model } = await openTestSession(t, {
155
+ tools: ["read"],
156
+ configure: (pi) => hashlineEdit(pi),
157
+ });
158
+ const capacity = 16_384;
159
+ const selected = { ...model, contextWindow: capacity };
160
+ await session.setModel(selected);
161
+ await session.reload();
162
+ const path = "long-line.txt";
163
+ await writeFile(join(cwd, path), "x".repeat(outputBudgetsFor(capacity).readBytes * 2));
164
+ let requests = 0;
165
+ session.agent.streamFunction = () => {
166
+ const first = requests++ === 0;
167
+ return responseStream(
168
+ selected,
169
+ first
170
+ ? {
171
+ stopReason: "toolUse",
172
+ content: [
173
+ { type: "toolCall", id: "read-after-reload", name: "read", arguments: { path } },
174
+ ],
175
+ }
176
+ : { stopReason: "stop", content: [{ type: "text", text: "Done." }] },
177
+ );
178
+ };
179
+ await session.prompt("Read the fixture after reload.");
180
+ const result = session.agent.state.messages.find(
181
+ (message) => message.role === "toolResult" && message.toolCallId === "read-after-reload",
182
+ );
183
+ assert.ok(result?.role === "toolResult");
184
+ assert.equal(result.isError, false);
185
+ assert.ok(reportOf(result, "read")?.lineTooLong);
186
+ });
@@ -5,13 +5,15 @@ import { test } from "node:test";
5
5
  import { installedExtension } from "../testing/installation.testing.ts";
6
6
  import { runTestProcess } from "../testing/process.testing.ts";
7
7
 
8
- test("npm archive without devDependencies → registered tools complete a real Pi workflow", async (t) => {
9
- const installation = await installedExtension(t, "packed");
10
- await access(join(installation.packageDir, "THIRD_PARTY_NOTICES.md"));
11
- await runTestProcess(
12
- process.execPath,
13
- [fileURLToPath(new URL("./npm-package.testing.ts", import.meta.url)), installation.entry],
14
- installation.root,
15
- installation.agentDir,
16
- );
17
- });
8
+ for (const source of ["source", "packed"] as const) {
9
+ test(`${source} installation without devDependencies → real Pi workflow and argument diagnostics`, async (t) => {
10
+ const installation = await installedExtension(t, source);
11
+ if (source === "packed") await access(join(installation.packageDir, "THIRD_PARTY_NOTICES.md"));
12
+ await runTestProcess(
13
+ process.execPath,
14
+ [fileURLToPath(new URL("./npm-package.testing.ts", import.meta.url)), installation.entry],
15
+ installation.root,
16
+ installation.agentDir,
17
+ );
18
+ });
19
+ }
@@ -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,149 @@ 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, outputMode: "rows", context: null },
135
+ fields: ["pattern[0]", "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
+ outputMode: "count",
173
+ },
174
+ fields: [],
175
+ },
176
+ {
177
+ name: "replace",
178
+ args: {
179
+ path: "diagnostic.txt",
180
+ replacements: { find: 42, replace: 43, literal: "true", flags: null },
181
+ },
182
+ fields: ["replacements[0].flags"],
183
+ },
184
+ {
185
+ name: "replace",
186
+ args: {
187
+ path: "diagnostic.txt",
188
+ replacements: [{ find: 42, replace: 42, literal: "true", flags: null }],
189
+ },
190
+ fields: [],
191
+ },
192
+ {
193
+ name: "replace",
194
+ args: {
195
+ path: "diagnostic.txt",
196
+ replacements: { find: 42, replace: 43, literal: "true" },
197
+ },
198
+ fields: [],
199
+ },
200
+ ] as const;
201
+ const original = structuredClone(cases);
202
+ let next = 0;
203
+ session.agent.streamFunction = () => {
204
+ const scenario = cases[next++];
205
+ return responseStream(
206
+ model,
207
+ scenario
208
+ ? {
209
+ content: [
210
+ {
211
+ type: "toolCall",
212
+ id: `diagnostic-${next}`,
213
+ name: scenario.name,
214
+ arguments: scenario.args,
215
+ },
216
+ ],
217
+ stopReason: "toolUse",
218
+ }
219
+ : { content: [{ type: "text", text: "Done." }], stopReason: "stop" },
220
+ );
221
+ };
222
+ await session.prompt("Exercise installed argument validation.");
223
+ assert.equal(session.agent.state.errorMessage, undefined);
224
+ assert.equal(next, cases.length + 1);
225
+ for (const [index, scenario] of cases.entries()) {
226
+ const result = session.agent.state.messages.find(
227
+ (message) =>
228
+ message.role === "toolResult" && message.toolCallId === `diagnostic-${index + 1}`,
229
+ );
230
+ assert.ok(result?.role === "toolResult");
231
+ assert.equal(result.isError, scenario.fields.length > 0, JSON.stringify(result));
232
+ if (scenario.fields.length) {
233
+ const report = reportOf(result, scenario.name);
234
+ assert.equal(report?.error, "INVALID_ARGUMENTS");
235
+ assert.deepEqual(
236
+ report?.issues?.map((issue) => issue.field).sort(),
237
+ [...scenario.fields].sort(),
238
+ );
239
+ }
240
+ }
241
+ assert.deepEqual(cases, original);
242
+ assert.equal(await readFile(join(cwd, "diagnostic.txt"), "utf8"), "43");
243
+ });
@@ -15,10 +15,10 @@ for (const { entry, input, expected } of [
15
15
  entry: "grep-worker.mjs",
16
16
  input: {
17
17
  source: "😀\r\na\n",
18
- query: { patterns: ["^..$"], literal: false, multiline: false, flags: "m" },
18
+ query: { patterns: ["^..$"], literal: false, multiline: false, ignoreCase: false },
19
19
  limit: 10,
20
20
  },
21
- expected: { lines: [{ lineNumber: 1, column: 0 }], totalLines: 2 },
21
+ expected: { lines: [{ lineNumber: 1, column: 0 }] },
22
22
  },
23
23
  ]) {
24
24
  const worker = new Worker(join(process.argv[2], "src", "pi", entry));
@@ -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,49 +4,57 @@ 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` obtains the workspace from the Pi loader's default `pi.exec()` cwd, then loads config once and registers nothing when `enabled` is false. Tools and entry renderers register in the factory because Pi can rebuild history before `session_start` on reload. Each tool factory receives 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. The Action Fusion cards register even when Action Fusion is off, so saved then_run cards render. One helper appends `NEXT_GUIDELINE` from `report-schema.ts` to every tool's `promptGuidelines` (Pi prints the shared guideline once). The `then_run` field and `ACTION_FUSION_GUIDELINES` exist only when `fusion` does; that guideline is the one place the model is told when to use then_run.
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
+ - Call order: a tool's `prepareArguments` (from `argument-validation.ts`), then Pi's own schema validation, then `execute`. Caller arguments are never rewritten. File-dependent checks stay in execution.
12
+ - Tool files define TypeBox schemas, and each mutation tool's description names its alternative (edit ↔ replace ↔ write). A tool supplies only the semantic checks its schema cannot express or name precisely: edit's per-action fields and ranges, text that cannot be written as UTF-8, and regex compilation through `checkRegexArguments` in `argument-validation.ts`, which reports flags V8 rejects and compiles regex-mode patterns under the flags each tool uses. Shared integer rules live in `schema.ts`.
13
+ - 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.
14
+ - 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.
15
+ - `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
16
  - `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
17
  - `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
18
 
16
19
  ## Mutations
17
20
 
18
- - `mutation-runner.ts` owns the definition the mutation tools share (`mutationToolBase`: name, then_run field, description and guideline, argument preparation, strict sampling, and `execute`); each tool supplies its schema, text, semantic checks, and `run`, and adds its own renderers. It also owns the call sequence shared by `edit`/`replace`/`write` after Pi has validated the arguments: separating `then_run`, path resolution, `withFileMutationQueue`, the hand-off to Action Fusion, and finalization. Each tool's `run` returns a tool-indexed `MutationOutcome` (commit facts, details, schema-derived outcome facts), Action Fusion returns `FusedMutation` facts, and the runner's single `finalizeMutation` call turns them into a result; nothing downstream reads publication or revisions back from result details. `runTextMutation` owns the read-modify-write for `edit`/`replace`, so each tool supplies only a `TextChange` (new text, outcome facts).
21
+ - `mutation-runner.ts` owns what the mutation tools share: their definition (`mutationToolBase`) and the call sequence after validation (separating `then_run`, path resolution, `withFileMutationQueue`, the hand-off to Action Fusion, and finalization). A tool supplies its schema, text, semantic checks, `run`, and renderers. `run` returns a tool-indexed `MutationOutcome`, Action Fusion returns `FusedMutation` facts, and one `finalizeMutation` call turns them into a result; nothing downstream reads publication or revisions back from result details. `runTextMutation` owns the read-modify-write for `edit`/`replace`, which supply only a `TextChange`.
19
22
  - `file-read.ts` provides guarded stream and whole-file reads; byte revision checks stay in the search and commit owners.
20
23
  - `file-revision.ts` defines a revision once: the SHA-256 hex of exact bytes, whole (`byteRevision`) or streamed. `text-stream.ts` returns the revision of the bytes each scan read, so callers never hash.
21
- - `file-commit.ts` is the only publication path: file revisions (`fileRevision`), no-op detection, a temp file in a sibling dir, then `link` (create) or `rename` (overwrite). It handles symlinks and hard links, preserves existing file modes (a new file follows the umask), and syncs the directory on POSIX. A failure with a publication status to state throws `FileMutationError`; every other failure stays a plain `HashlineError`, reported as `NOT_PUBLISHED`. A failed step is the `message`, its underlying error the `cause`. `edit`/`replace` commit with `baseRevision`, the revision of the bytes they read; `CommitOptions` admits it only with `overwrite`. Its target type distinguishes missing from existing files with required revision and mode facts; commit results distinguish creation, replacement, and no-op. It also owns freshness: `commitFreshness` from the commit result and `observeFreshness` for Fusion's later observations; only unknown freshness carries an observation error.
24
+ - `file-commit.ts` publishes: no-op detection, a temp file in a sibling directory, then `link` (create) or `rename` (overwrite). It stages overwrites beside the resolved target and rechecks the requested path and target admission before renaming. It preserves existing file modes (a new file follows the umask) and syncs the directory on POSIX. A failure with a publication status to state throws `FileMutationError`; every other failure stays a plain `HashlineError`, reported as `NOT_PUBLISHED`. `CommitOptions` admits `baseRevision` only with `overwrite`. It also owns freshness: `commitFreshness` from the commit result and `observeFreshness` for Fusion's later observations; only unknown freshness carries an observation error.
22
25
  - `mutation-result.ts` owns tool-indexed outcome facts, final success/failure details, and progress details. It builds diffs and finalizes one mutation report from commit, tool, freshness, and command facts. On failure, `describeMutationFailure` states what only a mutation knows (publication, and through `CommandNotRun` why a fused command never ran) and leaves classification to `describeFailure`. `failure-context.ts` turns anchor failures into a `HashlineError` with bounded facts (`failures`, `candidateNeighborhoods`); `anchor-format.ts` owns the `LINE#HASH` syntax, its schema pattern, and row parsing.
23
26
 
24
27
  ## grep
25
28
 
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.
29
+ - 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). Each candidate file is scanned once through `text-stream.ts` for NUL, UTF-8 validity, its revision, and the lossy LF view it matches. 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. The README documents grep's resource limits.
30
+ - 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 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
31
  - `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
- - `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
- - 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
+ - `grep-candidates.ts` decides which rg runs to make: line candidates through `rg-regex.ts`, then file candidates through `--files-with-matches` over necessary literals. A stage falls back only when its arguments exceed the command line, or when it exits with code 2 before listing any file and `rgRejectsPatterns` confirms rg rejects its patterns; a search that only hit unreadable paths stands. When the file filter is unavailable or falls back, `--files` lists every file in scope. Byte-level pattern flags are defined once there.
33
+ - 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, and replace it if a later NUL made its failure irrelevant. Propagate cancellation without waiting for earlier files.
31
34
  - `grep-scope.ts` classifies scope errors: only `ENOENT` means `PATH_NOT_FOUND`; preserve other filesystem errors.
32
35
 
33
36
  ## Regex workers
34
37
 
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.
38
+ `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`); that schema check is a reply's only check, and the host trusts the engine's semantics. Bound worker failures only in the receiving tool.
36
39
 
37
40
  ## Reports and rendering
38
41
 
42
+ - Give each model-facing rule one home, chosen by what it decides. Choosing a tool, or a parameter of the call being written, belongs in that tool's `description` or the field's description; an obligation spanning several calls belongs in `promptGuidelines`; what to do about one result belongs only in that report's `next` (`src/pi/report-schema.ts`). State a tool's or field's facts once, where they belong. Guidelines never restate a `next`; `NEXT_GUIDELINE`, appended at registration in `src/index.ts`, ranks a report's `next` above them. Word rules as instructions with a concrete trigger and listed exceptions, not as preferences. Include text that applies to one platform only on that platform, decided from `process.platform` where the text is defined.
43
+ - Every tool result states its facts in one report. A success report follows the content payload; a failure report is the whole `isError` result. Layers return structured facts and never append sentences or bracket notices; each fact has one owner, so it appears once. Throw sites classify failures as `HashlineError` with a code and the facts its schema requires; `message` describes only the throwing step, a failure beneath that step is `cause`; native diagnostics remain directly in `message`, without a synthetic wrapper, except that a missing path or a directory target gets one fixed message in every tool (`PATH_ERROR_MESSAGES`), with resolved paths in `missing`; `next` is derived from the code and publication (a throw site may only select one of the code's named alternatives). Text shared by success and failure (such as `REREAD`) is defined once in the schema module.
44
+ - Send the model a result field only when its value changes the model's next call. Do not send a field that is a function of the call's own arguments, or that the same result already states (a payload header, a row, another field). What only a person can act on (diffs, progress, display-callback failures) goes to the TUI through `details`; revisions, candidate strategy, and timing stay out of results. In review, delete a field when nobody can say what the model does differently for another value of it.
45
+ - A success report carries `next` only when the result is incomplete or the model would otherwise misread it. A failure's `next` names a tool or parameter whose values the same report supplies; a code with no such action has no `next`. Order `OUTCOME_NEXT` so that following an earlier rule makes a later one reappear on the following call.
46
+
39
47
  - `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.
48
+ - `report.ts` builds reports and owns their one model-facing serialization (`renderReport`: one JSON object, fields in schema order). Result text omits the call's own `tool`/`path` and TUI-only facts, which stay in `details.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.
49
+ - `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
50
  - `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.
51
+ - 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. To change an error code, edit `ERROR_DEFINITIONS` and follow the type errors to every throw site and the worker contract.
44
52
  - `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
53
 
46
54
  ## Budgets and config
47
55
 
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.
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.
56
+ - `budgets.ts` defines the model-facing byte budgets, and `model-budgets.ts` derives them from the live selected model on each request. Preparation shares the provider, and each execution captures its budgets before its asynchronous work; internal helpers require the resolved budget or an explicit byte limit. Model-derived budgets and the `read.maxKiB` range share the `MAX_CONTENT_KIB` ceiling.
57
+ - `config.ts` defines the `hashlineEdit` settings as one TypeBox schema: shared top-level settings and the `read`, `grep`, and `replace` groups. A missing or invalid `read.maxKiB` selects automatic model sizing.
50
58
 
51
59
  ## Action Fusion
52
60
 
@@ -32,16 +32,28 @@ const mutationFactories = [
32
32
  makeWriteOverride,
33
33
  ];
34
34
 
35
+ test("Fusion executor toggled → mutation descriptions stay identical without then_run instructions", () => {
36
+ const fusion = createActionFusionExecutor(() => {});
37
+ for (const makeTool of mutationFactories) {
38
+ const disabled = makeTool("/tmp");
39
+ const enabled = makeTool("/tmp", fusion);
40
+ assert.equal(enabled.description, disabled.description, enabled.name);
41
+ assert.doesNotMatch(enabled.description, /then_run|separate bash call/i);
42
+ }
43
+ });
44
+
35
45
  test("mutation tools expose Fusion schemas and guidance when supplied an executor", () => {
36
46
  const fusion = createActionFusionExecutor(() => {});
37
47
  for (const makeTool of mutationFactories) {
38
48
  const disabled = makeTool("/tmp");
39
49
  const enabled = makeTool("/tmp", fusion);
40
50
  assert.equal(Object.hasOwn(disabled.parameters.properties, "then_run"), false);
41
- assert.ok(
42
- "then_run" in enabled.parameters.properties && enabled.parameters.properties.then_run,
43
- );
44
- assert.match(enabled.description, /set the then_run parameter/i);
51
+ assert.ok("then_run" in enabled.parameters.properties);
52
+ const thenRun = enabled.parameters.properties.then_run;
53
+ assert.partialDeepStrictEqual(thenRun, {
54
+ description: `Command to run once after ${enabled.name} succeeds; failure does not roll back the file.`,
55
+ properties: { command: { description: "Bash command to run." } },
56
+ });
45
57
  assert.deepEqual(enabled.promptGuidelines, [
46
58
  ...(disabled.promptGuidelines ?? []),
47
59
  ...ACTION_FUSION_GUIDELINES,
@@ -54,6 +66,28 @@ test("mutation tools expose Fusion schemas and guidance when supplied an executo
54
66
  }
55
67
  });
56
68
 
69
+ test("Fusion platform guidance → only Windows gets the path note", async () => {
70
+ const original = Object.getOwnPropertyDescriptor(process, "platform");
71
+ assert.ok(original);
72
+ const base =
73
+ "Set then_run on edit, replace, or write for a check that can run right after that change. Use a separate bash call when the command requires approval, needs information from the tool's result, must wait for reload, or covers several changes; run that check once after all of them.";
74
+ const windowsNote =
75
+ " then_run commands run in Bash on Windows: avoid Unix-only paths such as /tmp.";
76
+ try {
77
+ for (const platform of ["win32", "linux"] as const) {
78
+ Object.defineProperty(process, "platform", { ...original, value: platform });
79
+ const fusion: typeof import("./action-fusion.ts") = await import(
80
+ new URL(`./action-fusion.ts?platform=${platform}`, import.meta.url).href
81
+ );
82
+ assert.deepEqual(fusion.ACTION_FUSION_GUIDELINES, [
83
+ base + (platform === "win32" ? windowsNote : ""),
84
+ ]);
85
+ }
86
+ } finally {
87
+ Object.defineProperty(process, "platform", original);
88
+ }
89
+ });
90
+
57
91
  test("then_run schemas reject invalid commands, unknown keys, and excessive timeouts", async (t) => {
58
92
  const dir = await tempDir();
59
93
  try {
@@ -9,8 +9,8 @@
9
9
  * a later fused call on the same file waits until this command finishes and
10
10
  * cannot change the revision the command started from. Its key resolves the nearest
11
11
  * existing ancestor and folds case on Windows, so it is never looser than
12
- * Pi's key. It is always taken first and Pi's queue never waits on it, so
13
- * the nesting cannot deadlock.
12
+ * Pi's key. Nested tool calls during the command cannot wait on an occupied
13
+ * Fusion queue: they might be waiting for their own command to finish.
14
14
  *
15
15
  * Writers outside these queues are not blocked; the commit layer's freshness
16
16
  * observation against `publishedRevision` detects them, and the command is
@@ -21,6 +21,7 @@
21
21
  * @module pi-hashline-edit/pi
22
22
  */
23
23
 
24
+ import { AsyncLocalStorage } from "node:async_hooks";
24
25
  import { realpath } from "node:fs/promises";
25
26
  import { basename, dirname, resolve } from "node:path";
26
27
  import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
@@ -49,14 +50,14 @@ const MILLISECONDS_PER_SECOND = 1_000;
49
50
  // Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
50
51
  const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / MILLISECONDS_PER_SECOND;
51
52
 
52
- // Pi's Bash runs on this host, and Pi's prompt does not name the OS; only Windows needs the path note.
53
- const COMMAND_DESCRIPTION =
54
- process.platform === "win32"
55
- ? "Bash command to run. This host is Windows: avoid Unix-only paths such as /tmp."
56
- : "Bash command to run.";
57
-
53
+ // The one place the model is told when to use then_run; the tools' descriptions stay their own.
58
54
  export const ACTION_FUSION_GUIDELINES = [
59
- "When a check covers several changes, run it once after all of those changes.",
55
+ `Set then_run on edit, replace, or write for a check that can run right after that change. Use a separate bash call when the command requires approval, needs information from the tool's result, must wait for reload, or covers several changes; run that check once after all of them.${
56
+ // Pi's Bash runs on this host, and Pi's prompt does not name the OS; only Windows needs the path note.
57
+ process.platform === "win32"
58
+ ? " then_run commands run in Bash on Windows: avoid Unix-only paths such as /tmp."
59
+ : ""
60
+ }`,
60
61
  ];
61
62
 
62
63
  type ProgressReporter = (progress: ActionFusionProgress) => void;
@@ -65,7 +66,7 @@ function createThenRunSchema(tool: MutationToolName) {
65
66
  return Type.Optional(
66
67
  Type.Object(
67
68
  {
68
- command: Type.String({ pattern: "\\S", description: COMMAND_DESCRIPTION }),
69
+ command: Type.String({ pattern: "\\S", description: "Bash command to run." }),
69
70
  timeout: Type.Optional(
70
71
  Type.Number({
71
72
  exclusiveMinimum: 0,
@@ -98,13 +99,6 @@ export function withThenRunSchema<P extends TProperties>(
98
99
 
99
100
  export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
100
101
 
101
- /** Name then_run in a mutation tool's description when Action Fusion is enabled. */
102
- export function withThenRunDescription(description: string, actionFusion: boolean): string {
103
- return actionFusion
104
- ? `${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.`
105
- : description;
106
- }
107
-
108
102
  /** What a fused call leaves for the mutation runner to report; Fusion builds no result itself. */
109
103
  export interface FusedMutation<TDetails, TTool extends MutationToolName> {
110
104
  readonly outcome: MutationOutcome<TDetails, TTool>;
@@ -145,7 +139,7 @@ async function runCommand(
145
139
  typeof structured === "object" &&
146
140
  "exit_code" in structured &&
147
141
  typeof structured.exit_code === "number";
148
- // Pi 0.99.1 supplies exit_code for ordinary exits, but serializes a thrown
142
+ // Pi's Bash supplies exit_code for ordinary exits, but serializes a thrown
149
143
  // timeout as text. Only recognize its final diagnostic for the requested
150
144
  // timeout; a failed command's output may itself mention or quote a timeout.
151
145
  const timeoutDiagnostic = `Command timed out after ${input.timeout} seconds`;
@@ -265,10 +259,16 @@ function createProgressTracker<TDetails extends object>({
265
259
 
266
260
  export function createActionFusionExecutor(onProgress: ProgressReporter) {
267
261
  const queueTails = new Map<string, Promise<void>>();
262
+ const commandScope = new AsyncLocalStorage<{ active: boolean }>();
268
263
 
269
264
  async function withQueue<T>(path: string, work: () => Promise<T>): Promise<T> {
270
265
  const key = await canonicalQueueKey(path);
271
266
  const previous = queueTails.get(key) ?? Promise.resolve();
267
+ if (queueTails.has(key) && commandScope.getStore()?.active) {
268
+ throw new Error(
269
+ "A then_run command cannot call a mutation tool for a target with a pending mutation.",
270
+ );
271
+ }
272
272
  let release!: () => void;
273
273
  const owned = new Promise<void>((resolve) => {
274
274
  release = resolve;
@@ -353,15 +353,19 @@ export function createActionFusionExecutor(onProgress: ProgressReporter) {
353
353
  if (before.freshness !== "unchanged") return settle(before, { status: "skipped" });
354
354
 
355
355
  progress.report("running", "unchanged");
356
+ const scope = { active: true };
356
357
  let command: CommandOutcome;
357
358
  try {
358
- command = await runCommand(thenRun, signal, ctx, progress.followCommand);
359
+ command = await commandScope.run(scope, () =>
360
+ runCommand(thenRun, signal, ctx, progress.followCommand),
361
+ );
359
362
  } catch (error) {
360
363
  command = {
361
364
  status: signal?.aborted ? "cancelled" : "failed",
362
365
  result: { content: [{ type: "text", text: errorMessage(error) }] },
363
366
  };
364
367
  } finally {
368
+ scope.active = false;
365
369
  progress.stopHeartbeat();
366
370
  }
367
371
  progress.commandSettled(command.result);