@criogaid/pi-hashline-edit 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,117 @@
1
+ import assert from "node:assert/strict";
2
+ import { Worker } from "node:worker_threads";
3
+ import { test } from "node:test";
4
+ import { HashlineError } from "../core/errors.ts";
5
+ import { runRegexReplacements } from "../pi/replace-regex.ts";
6
+ import { DEFAULT_OUTPUT_BUDGETS } from "../pi/budgets.ts";
7
+ import { causeOf } from "../pi/report.ts";
8
+ import type { Cause } from "../pi/report-schema.ts";
9
+
10
+ const timeoutMs = 10_000;
11
+ const validRules = [{ find: "safe", replace: "changed", literal: false }];
12
+
13
+ test("worker boundary: malformed external reply → rejects its result and facts", async (t) => {
14
+ for (const reply of [
15
+ { result: { text: 123, count: 1 } },
16
+ { result: { text: "changed", count: 0 } },
17
+ {
18
+ result: { text: "changed", count: 1 },
19
+ error: { code: "NO_MATCH", message: "failure", facts: { rule: 0 } },
20
+ },
21
+ { error: { code: "NO_MATCH", message: "failure" } },
22
+ { error: { code: "foreign", message: "failure" } },
23
+ { error: { code: "NO_MATCH", message: "failure", facts: { rule: 0, foreign: true } } },
24
+ ]) {
25
+ await t.test(JSON.stringify(reply), { timeout: timeoutMs }, async (t) => {
26
+ const emit = Worker.prototype.emit;
27
+ t.mock.method(
28
+ Worker.prototype,
29
+ "emit",
30
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
31
+ return emit.call(this, event, ...(event === "message" ? [reply] : args));
32
+ },
33
+ );
34
+ await assert.rejects(
35
+ runRegexReplacements("safe", validRules, timeoutMs, undefined),
36
+ (error: unknown) =>
37
+ error instanceof HashlineError &&
38
+ error.errorCode === "REGEX_WORKER_FAILED" &&
39
+ /invalid result/i.test(error.message),
40
+ );
41
+ });
42
+ }
43
+ });
44
+
45
+ test("worker boundary: deep structured cause reply → preserves the terminal cause and every branch", {
46
+ timeout: timeoutMs,
47
+ }, async (t) => {
48
+ let nested: Cause = { code: "EACCES", message: "permission denied" };
49
+ for (let index = 0; index < 12; index++)
50
+ nested = { code: "EIO", message: `layer ${index}`, cause: nested };
51
+ const cause: Cause = {
52
+ message: "worker failure",
53
+ cause: nested,
54
+ errors: Array.from({ length: 24 }, (_, index) => ({
55
+ code: "EIO",
56
+ message: `branch ${index}`,
57
+ })),
58
+ };
59
+ const emit = Worker.prototype.emit;
60
+ t.mock.method(
61
+ Worker.prototype,
62
+ "emit",
63
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
64
+ return emit.call(
65
+ this,
66
+ event,
67
+ ...(event === "message"
68
+ ? [{ error: { code: "REGEX_WORKER_FAILED", message: "Regex evaluation failed.", cause } }]
69
+ : args),
70
+ );
71
+ },
72
+ );
73
+ await assert.rejects(
74
+ runRegexReplacements("safe", validRules, timeoutMs, undefined),
75
+ (error: unknown) => {
76
+ assert.ok(error instanceof HashlineError);
77
+ assert.equal(error.errorCode, "REGEX_WORKER_FAILED");
78
+ assert.deepEqual(causeOf(error.cause, DEFAULT_OUTPUT_BUDGETS.fieldBytes), cause);
79
+ return true;
80
+ },
81
+ );
82
+ });
83
+
84
+ test("worker boundary: cyclic structured cause → rejects a reply accepted with an acyclic cause", {
85
+ timeout: timeoutMs,
86
+ }, async (t) => {
87
+ for (const cyclic of [false, true]) {
88
+ await t.test(`cyclic=${cyclic}`, async (t) => {
89
+ const cause: Cause = { code: "EIO", message: "worker failure" };
90
+ if (cyclic) cause.cause = cause;
91
+ const reply = { error: { code: "NO_MATCH", message: "no match", facts: { rule: 0 }, cause } };
92
+ const emit = Worker.prototype.emit;
93
+ t.mock.method(
94
+ Worker.prototype,
95
+ "emit",
96
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
97
+ return emit.call(this, event, ...(event === "message" ? [reply] : args));
98
+ },
99
+ );
100
+ await assert.rejects(
101
+ runRegexReplacements("safe", validRules, timeoutMs, undefined),
102
+ (error: unknown) => {
103
+ assert.ok(error instanceof HashlineError);
104
+ if (cyclic) {
105
+ assert.equal(error.errorCode, "REGEX_WORKER_FAILED");
106
+ assert.match(error.message, /invalid result/i);
107
+ } else {
108
+ assert.equal(error.errorCode, "NO_MATCH");
109
+ assert.deepEqual(error.facts, { rule: 0 });
110
+ assert.deepEqual(causeOf(error.cause, DEFAULT_OUTPUT_BUDGETS.fieldBytes), cause);
111
+ }
112
+ return true;
113
+ },
114
+ );
115
+ });
116
+ }
117
+ });
@@ -0,0 +1,90 @@
1
+ /** Preparation errors transported by Pi and replayed with a fresh tool registration. */
2
+ import assert from "node:assert/strict";
3
+ import { readFile, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { stripVTControlCharacters } from "node:util";
7
+ import { initTheme } from "@earendil-works/pi-coding-agent";
8
+ import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
9
+ import { DEFAULT_CONFIG } from "../pi/config.ts";
10
+ import { makeEditOverride } from "../pi/edit-tool.ts";
11
+ import { reportOf } from "../pi/report.ts";
12
+ import { openTestSession, responseStream } from "../testing/session.testing.ts";
13
+
14
+ const args = { path: "target.txt", edits: [{ op: "append", body: [] }] };
15
+
16
+ test("live preparation failure → replays diagnostic after fresh registration", async (t) => {
17
+ initTheme("dark");
18
+ const first = await openTestSession(t, {
19
+ tools: ["edit"],
20
+ configure(pi, cwd) {
21
+ pi.registerTool(makeEditOverride(cwd, DEFAULT_CONFIG));
22
+ },
23
+ });
24
+ await writeFile(join(first.cwd, args.path), "unchanged\n");
25
+ let requests = 0;
26
+ first.session.agent.streamFunction = (_model, context) => {
27
+ if (requests++ === 0) {
28
+ return responseStream(first.model, {
29
+ content: [{ type: "toolCall", id: "invalid-edit", name: "edit", arguments: args }],
30
+ stopReason: "toolUse",
31
+ });
32
+ }
33
+ const result = context.messages.find(
34
+ (message) => message.role === "toolResult" && message.toolCallId === "invalid-edit",
35
+ );
36
+ assert.ok(result?.role === "toolResult");
37
+ assert.equal(result.isError, true);
38
+ assert.equal(reportOf(result, "edit")?.error, "INVALID_ARGUMENTS");
39
+ return responseStream(first.model, {
40
+ content: [{ type: "text", text: "Done." }],
41
+ stopReason: "stop",
42
+ });
43
+ };
44
+ await first.session.prompt("Exercise a rejected edit in an isolated fixture.");
45
+ assert.equal(first.session.agent.state.errorMessage, undefined);
46
+ assert.equal(requests, 2);
47
+ assert.equal(await readFile(join(first.cwd, args.path), "utf8"), "unchanged\n");
48
+ const live = first.session.agent.state.messages.find(
49
+ (message) => message.role === "toolResult" && message.toolCallId === "invalid-edit",
50
+ );
51
+ assert.ok(live?.role === "toolResult");
52
+ const replay = { content: structuredClone(live.content), details: undefined };
53
+ const serialized = JSON.stringify(replay);
54
+ const report = reportOf(replay, "edit");
55
+ assert.equal(report?.issues?.[0].field, "edits[0].body");
56
+ assert.equal(report?.issues?.[0].reason, "is empty");
57
+
58
+ const second = await openTestSession(t, {
59
+ tools: ["edit"],
60
+ configure(pi, cwd) {
61
+ pi.registerTool(makeEditOverride(cwd, DEFAULT_CONFIG));
62
+ },
63
+ });
64
+ const tool = second.session.getToolDefinition("edit");
65
+ assert.ok(tool?.renderResult);
66
+ for (const expanded of [false, true]) {
67
+ for (let rendering = 0; rendering < 2; rendering++) {
68
+ const decoded = JSON.parse(serialized);
69
+ const component = tool.renderResult(decoded, { expanded, isPartial: false }, theme, {
70
+ args,
71
+ toolCallId: "invalid-edit",
72
+ cwd: second.cwd,
73
+ state: {},
74
+ invalidate() {},
75
+ lastComponent: undefined,
76
+ executionStarted: true,
77
+ argsComplete: true,
78
+ expanded,
79
+ isPartial: false,
80
+ showImages: false,
81
+ isError: true,
82
+ });
83
+ const shown = stripVTControlCharacters(component.render(240).join("\n"));
84
+ assert.match(shown, /edits\[0\]\.body: is empty/);
85
+ assert.equal(shown.split("edits[0].body: is empty").length - 1, 1);
86
+ assert.doesNotMatch(shown, /"issues":/);
87
+ assert.equal(JSON.stringify(decoded), serialized);
88
+ }
89
+ }
90
+ });
@@ -0,0 +1,46 @@
1
+ import assert from "node:assert/strict";
2
+ import { constants, isUtf8 } from "node:buffer";
3
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { test } from "node:test";
7
+ import { DEFAULT_CONFIG } from "../pi/config.ts";
8
+ import { makeEditOverride } from "../pi/edit-tool.ts";
9
+ import { makeReplaceTool } from "../pi/replace-tool.ts";
10
+ import { byteRevision } from "../pi/file-revision.ts";
11
+ import { callTool } from "../pi/tool-call.testing.ts";
12
+ import { expectToolFailure } from "../pi/report-failure.testing.ts";
13
+
14
+ const SIZE_TEST_TIMEOUT_MS = 60_000;
15
+
16
+ test("valid UTF-8 exceeding the runtime string limit → mutations retain the size failure without publishing", {
17
+ timeout: SIZE_TEST_TIMEOUT_MS,
18
+ }, async (t) => {
19
+ const directory = await mkdtemp(join(tmpdir(), "hashline-utf8-size-"));
20
+ t.after(() => rm(directory, { recursive: true, force: true }));
21
+ const path = join(directory, "large.txt");
22
+ const source = Buffer.alloc(constants.MAX_STRING_LENGTH + Buffer.byteLength("中文"), 97);
23
+ source.write("中文", 0, "utf8");
24
+ assert.equal(isUtf8(source), true);
25
+ const originalRevision = byteRevision(source);
26
+ await writeFile(path, source);
27
+ const tools = [
28
+ makeEditOverride(directory, DEFAULT_CONFIG),
29
+ makeReplaceTool(directory, DEFAULT_CONFIG),
30
+ ];
31
+ for (const tool of tools) {
32
+ await t.test(tool.name, async () => {
33
+ const args =
34
+ tool.name === "edit"
35
+ ? { path, edits: [{ op: "append", body: ["tail"] }] }
36
+ : { path, replacements: [{ literal: true, find: "中文", replace: "汉字" }] };
37
+ await expectToolFailure(callTool(tool, args), "FILESYSTEM_ERROR", (report) => {
38
+ assert.doesNotMatch(JSON.stringify(report), /UNSUPPORTED_ENCODING/);
39
+ assert.match(report.message ?? "", /ERR_STRING_TOO_LONG/);
40
+ assert.equal(report.cause, undefined);
41
+ assert.equal(report.publication, "NOT_PUBLISHED");
42
+ });
43
+ assert.equal(byteRevision(await readFile(path)), originalRevision);
44
+ });
45
+ }
46
+ });
@@ -0,0 +1,54 @@
1
+ # src/pi
2
+
3
+ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file maps the modules and holds constraints specific to them.
4
+
5
+ ## Registration
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`; `withThenRunDescription` 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`.
8
+
9
+ ## Argument funnel
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 empty bodies, body lines that cannot be written as UTF-8, line numbers beyond the safe-integer range, and anchors of another hash length; 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`.
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.
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 branches, choices, and the explanations of missing, forbidden, and pattern-mismatched fields from the declared schema: when a schema reason does not say how to correct the value, a missing or pattern-mismatched field's `fix` is its description (each choice's value and description), and a forbidden field's `fix` lists the selected shape's accepted fields after the meaning of the operation that selected it. Suppress only inapplicable or already explained issues, and retain independent fields with bounded native diagnostics.
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
+
16
+ ## Mutations
17
+
18
+ - `mutation-runner.ts` owns the call sequence shared by `edit`/`replace`/`write` after Pi has validated the arguments: separating `then_run`, path resolution, `withFileMutationQueue`, and the hand-off to Action Fusion or plain finalization. Each tool's `run` returns a tool-indexed `MutationOutcome` (commit facts, details, schema-derived outcome facts), and only `finalizeMutation` turns it 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).
19
+ - `file-read.ts` provides guarded stream and whole-file reads; byte revision checks stay in the search and commit owners.
20
+ - `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 file modes, and syncs the directory on POSIX. It throws `FileMutationError` with a `stage` and a publication status; 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.
22
+ - `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. `failure-context.ts` turns anchor failures into a `HashlineError` with bounded facts (`failures`, `matched`, `candidateNeighborhoods`); `anchor-format.ts` owns the `LINE#HASH` syntax, its schema pattern, and row parsing.
23
+
24
+ ## grep
25
+
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-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 reads each candidate file once through `text-stream.ts` (via `scanTextFile`) for NUL, UTF-8 validity, its revision, and the lossy LF view it matches. 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 fixed-width assertion constraints, finite capture bindings, string expansion, and emitted patterns. Preserve every alternative, including branches outside an impossible capture. A multiline query, unsupported or oversized translation, or pattern rg rejects before reporting a file uses the file prefilter.
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. Keep the injectable `GrepBackend` and completed-run diagnostics here. Scope flags are produced only by `scopeArgs` 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). `runCandidatePaths` owns clause intersection and bounded retained paths; overflowing retention falls back to one necessary clause. 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.
31
+ - `grep-scope.ts` classifies scope errors: only `ENOENT` means `PATH_NOT_FOUND`; preserve other filesystem errors.
32
+
33
+ ## Regex workers
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` 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 result schemas and code-specific facts from `report-schema.ts`; `replace-worker-contract.ts` owns the replacement request; the result schema lives with the engine in `core/replace-schema.ts`. Bound worker failures only in the receiving tool.
36
+
37
+ ## Reports and rendering
38
+
39
+ - `report-schema.ts` is the single definition of the result protocol: every report field in output order (each with one owning layer), every error code with its facts schema and recovery (`next.default` plus named alternatives), and the success recovery order (`OUTCOME_NEXT`). 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) and omits the call's own `tool`/`path` from every 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.
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; `withMutationStatus` preserves both types. 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.
42
+ - `report-cause.ts` transports structured causes without Pi runtime imports, preserving cause chains and aggregate branches with cycle and repeated-reference 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
+ - `error-text.ts` holds the Pi-layer error forms (cancellation, file changed during read or search). `diagnostic-buffer.ts` bounds stderr and search diagnostics.
44
+
45
+ ## Budgets and config
46
+
47
+ - `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` caches one immutable snapshot per extension, calculated lazily and replaced when selection or capacity changes; preparation shares its provider, and each execution captures the snapshot before its asynchronous work. Model-derived content budgets share the `MAX_CONTENT_KIB` ceiling that the explicit `read.maxKiB` range also uses.
48
+ - `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.
49
+
50
+ ## Action Fusion
51
+
52
+ `action-fusion.ts` implements `then_run`. After a successful mutation it checks freshness against `publishedRevision`, then runs the command through the session Bash tool. Its own per-file queue wraps mutation and command around Pi's `withFileMutationQueue`; the module header explains the nesting. Fusion states only the command (`then_run` status and output, `terminate`); freshness and publication come from the mutation report. Fusion progress derives from `ACTION_FUSION_PROGRESS_SCHEMA` and retains the session command's original display content and details; `fusion-card.ts` validates saved command cards against its closed projection before restoring them. It renders the separate mutation and command TUI cards (`withMutationStatus`, `registerFusionCards`) and derives a not-run reason from the same facts.
53
+
54
+ Command cards reuse Pi's public `ToolExecutionComponent`, with the real TUI supplied by a temporary empty widget factory. History may be rebuilt before `session_start`, so retain a deferred component until the UI is bound. Cache each native component by call ID and apply global expansion only when that setting changes, so custom-entry rebuilds preserve mouse expansion. Keep spacing adaptation separate from native mouse handling and retain the built-in Bash presentation; the supported Pi API does not expose another tool's renderer.