@criogaid/pi-hashline-edit 0.6.0 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +56 -59
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,107 @@
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 { causeOf } from "../pi/report.ts";
7
+ import type { Cause } from "../pi/report-schema.ts";
8
+
9
+ const timeoutMs = 10_000;
10
+ const validRules = [{ find: "safe", replace: "changed", regex: true }];
11
+
12
+ test("worker boundary: malformed external reply → rejects its result and facts", async (t) => {
13
+ for (const reply of [
14
+ { result: { text: 123, count: 1 } },
15
+ { result: { text: "changed", count: 0 } },
16
+ {
17
+ result: { text: "changed", count: 1 },
18
+ error: { code: "NO_MATCH", message: "failure", facts: { rule: 0 } },
19
+ },
20
+ { error: { code: "NO_MATCH", message: "failure" } },
21
+ { error: { code: "foreign", message: "failure" } },
22
+ { error: { code: "NO_MATCH", message: "failure", facts: { rule: 0, foreign: true } } },
23
+ ]) {
24
+ await t.test(JSON.stringify(reply), { timeout: timeoutMs }, async (t) => {
25
+ const emit = Worker.prototype.emit;
26
+ t.mock.method(
27
+ Worker.prototype,
28
+ "emit",
29
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
30
+ return emit.call(this, event, ...(event === "message" ? [reply] : args));
31
+ },
32
+ );
33
+ await assert.rejects(
34
+ runRegexReplacements("safe", validRules, timeoutMs, undefined),
35
+ (error: unknown) =>
36
+ error instanceof HashlineError &&
37
+ error.errorCode === "REGEX_WORKER_FAILED" &&
38
+ /invalid result/i.test(error.message),
39
+ );
40
+ });
41
+ }
42
+ });
43
+
44
+ test("worker boundary: deep structured cause reply → preserves the terminal cause and every branch", {
45
+ timeout: timeoutMs,
46
+ }, async (t) => {
47
+ let nested: Cause = { code: "EACCES", message: "permission denied" };
48
+ for (let index = 0; index < 12; index++)
49
+ nested = { code: "EIO", message: `layer ${index}`, cause: nested };
50
+ const cause: Cause = {
51
+ message: "worker failure",
52
+ cause: nested,
53
+ errors: Array.from({ length: 24 }, (_, index) => ({
54
+ code: "EIO",
55
+ message: `branch ${index}`,
56
+ })),
57
+ };
58
+ const emit = Worker.prototype.emit;
59
+ t.mock.method(
60
+ Worker.prototype,
61
+ "emit",
62
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
63
+ return emit.call(
64
+ this,
65
+ event,
66
+ ...(event === "message"
67
+ ? [{ error: { code: "REGEX_WORKER_FAILED", message: "Regex evaluation failed.", cause } }]
68
+ : args),
69
+ );
70
+ },
71
+ );
72
+ await assert.rejects(
73
+ runRegexReplacements("safe", validRules, timeoutMs, undefined),
74
+ (error: unknown) => {
75
+ assert.ok(error instanceof HashlineError);
76
+ assert.equal(error.errorCode, "REGEX_WORKER_FAILED");
77
+ assert.deepEqual(causeOf(error.cause), cause);
78
+ return true;
79
+ },
80
+ );
81
+ });
82
+
83
+ test("worker boundary: cyclic argument facts in a reply → rejects nonserializable diagnostics", {
84
+ timeout: timeoutMs,
85
+ }, async (t) => {
86
+ const argumentsCopy: { self?: unknown } = {};
87
+ argumentsCopy.self = argumentsCopy;
88
+ const reply = {
89
+ error: {
90
+ code: "INVALID_ARGUMENTS",
91
+ message: "invalid arguments",
92
+ facts: { issues: [{ field: "path", reason: "missing" }], arguments: argumentsCopy },
93
+ },
94
+ };
95
+ const emit = Worker.prototype.emit;
96
+ t.mock.method(
97
+ Worker.prototype,
98
+ "emit",
99
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
100
+ return emit.call(this, event, ...(event === "message" ? [reply] : args));
101
+ },
102
+ );
103
+ await assert.rejects(
104
+ runRegexReplacements("safe", validRules, timeoutMs, undefined),
105
+ (error: unknown) => error instanceof HashlineError && error.errorCode === "REGEX_WORKER_FAILED",
106
+ );
107
+ });
@@ -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)?.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);
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-commit.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: [{ 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,55 @@
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), and calls `registerForgetTool` only when `forget` is enabled. When `actionFusion` is on, the three mutation tools also receive the Action Fusion executor and are wrapped with `withMutationStatus`; `withThenRunDescription` appends the one then_run selection sentence 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 and compiles regex rules; 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-commit.ts` is the only publication path: SHA-256 revisions (`byteRevision`/`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.
21
+ - `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.
22
+
23
+ ## grep
24
+
25
+ - 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.
26
+ - 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.
27
+ - `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.
28
+ - `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.
29
+ - 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.
30
+ - `grep-scope.ts` classifies scope errors: only `ENOENT` means `PATH_NOT_FOUND`; preserve other filesystem errors.
31
+
32
+ ## Regex workers
33
+
34
+ `regex-worker.ts` owns serialized requests, timeout, cancellation, and cleanup for grep and replace workers. 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 replacement request/result shapes. Bound worker failures only in the receiving tool.
35
+
36
+ ## Reports and rendering
37
+
38
+ - `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.
39
+ - `report.ts` builds reports and owns their one model-facing serialization (`renderReport`: one JSON object, fields in schema order) and omits `tool`/`path` from success text while retaining them in `details.report` and failures. `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.
40
+ - `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 and forget tags decode from the final content block with `decodeReport`. Supply the originating call's tool name when decoding success text. Invalid text-only reports remain raw.
41
+ - `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`.
42
+ - `error-text.ts` holds the Pi-layer error forms (cancellation, file changed during read or search). `diagnostic-buffer.ts` bounds stderr and search diagnostics.
43
+
44
+ ## Budgets and config
45
+
46
+ - `budgets.ts` derives model-facing byte budgets from the selected model's declared `contextWindow`, with bounded defaults for unknown limits. `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.
47
+ - `config.ts` defines the `hashlineEdit` settings as one TypeBox schema: top-level `enabled`, `actionFusion`, `forget`, `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.
48
+
49
+ ## Action Fusion
50
+
51
+ `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`; `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.
52
+
53
+ ## forget
54
+
55
+ `forget-tool.ts` implements `forget`, disabled by default through the `forget` setting. When enabled, read and grep tag large results with `withResultTag`, which adds the forget-owned `resultId` fact to their report; a `context` handler records the tagged results of the previous response, `forget` forgets the named ones among them and reports the rest in `notForgettable` (failing with `NOT_FORGETTABLE` only when none qualifies), since no later response can forget them, and its `turn_end` handler uses Pi's `context_edit` to replace each result's entire content with a forgotten receipt. It does not parse or classify the content; the original tool call and facts saved in `note` remain. Older results are never edited, so the next request changes only from the earliest replaced result on: later results of that batch, the response that asked, and its tool results. Tagged results also carry a display-only `forgetReceipt` in details (`readReceipt`/`grepReceipt`), which `forget` copies into its own details for the TUI card; nothing of it reaches the model.