@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
package/README.md CHANGED
@@ -2,16 +2,11 @@
2
2
 
3
3
  [![CI](https://github.com/Criogaid/pi-hashline-edit/actions/workflows/ci.yml/badge.svg)](https://github.com/Criogaid/pi-hashline-edit/actions/workflows/ci.yml) [![npm version](https://img.shields.io/npm/v/@criogaid/pi-hashline-edit)](https://www.npmjs.com/package/@criogaid/pi-hashline-edit) [![npm downloads](https://img.shields.io/npm/dm/@criogaid/pi-hashline-edit)](https://www.npmjs.com/package/@criogaid/pi-hashline-edit) [![license](https://img.shields.io/npm/l/@criogaid/pi-hashline-edit)](https://www.npmjs.com/package/@criogaid/pi-hashline-edit)
4
4
 
5
- Hash-anchored file editing for [Pi](https://github.com/earendil-works/pi-coding-agent). The model references lines it has read and supplies their new content; the tool checks each anchor against the current file before editing.
5
+ Hash-anchored file editing for [Pi](https://github.com/earendil-works/pi-coding-agent). The model cites lines from `read` or `grep`; `edit` checks those anchors against the current file before changing it. A rejected edit provides recovery information for the model to inspect and resubmit.
6
6
 
7
- Overrides `read`, `grep`, `edit`, and `write`, and adds `replace` for bulk transformations. Optional `forget` drops read/grep result content from model context.
7
+ Overrides `read`, `grep`, `edit`, and `write`, adds `replace` for file-wide substitutions, and optionally adds `forget` to remove inspection results from model context. Mutations can include a follow-up command through [Action Fusion](#action-fusion).
8
8
 
9
- - **Search → edit:** `read` and `grep` return the same `LINE#HASH` anchors, so search results can feed directly into edits.
10
- - **Batch and chain edits:** submit structured JSON operations together, then use the returned fresh anchors for the next change.
11
- - **Recover from stale anchors:** rejected edits show a unique checksum-matching candidate's line, or neighborhoods around ambiguous candidates for comparison. With no candidate, they ask the model to re-read the file. Recovery never applies automatically.
12
- - **Edit → test:** Action Fusion lets a mutation include an optional follow-up command, with separate file and command outcomes and separate TUI cards.
13
-
14
- [Quick start](#quick-start) · [Tools](#tools) · [Configuration](#configuration) · [Action Fusion](#action-fusion) · [Safety and design](#safety-and-design)
9
+ [Quick start](#quick-start) · [Tools](#tools) · [Configuration](#configuration) · [Reports](#reports) · [Safety and design](#safety-and-design)
15
10
 
16
11
  ## Install
17
12
 
@@ -19,13 +14,11 @@ Overrides `read`, `grep`, `edit`, and `write`, and adds `replace` for bulk trans
19
14
  pi install npm:@criogaid/pi-hashline-edit
20
15
  ```
21
16
 
22
- This extension works on **local files**. For remote/custom-storage operations, disable it in [configuration](#configuration) and reload Pi to use the built-in tools.
17
+ Requires Pi 0.99.1 or later. The extension works on local files. For remote or custom storage, set `hashlineEdit.enabled` to `false` and reload Pi to restore its built-in tools.
23
18
 
24
19
  ## Quick start
25
20
 
26
- Once installed, Pi's model uses these tool calls automatically. The examples below show the read → edit protocol.
27
-
28
- A `read` of `greet.ts` returns:
21
+ Pi's model uses these tools automatically. A `read` of `greet.ts` returns lines with `LINE#HASH` anchors:
29
22
 
30
23
  ```text
31
24
  greet.ts · 3 lines
@@ -34,7 +27,7 @@ greet.ts · 3 lines
34
27
  3#FNSZ│}
35
28
  ```
36
29
 
37
- To change the return value, copy the second line's anchor into `edit` and supply only the new content:
30
+ Copy an anchor into `edit` and supply the new line content:
38
31
 
39
32
  ```json
40
33
  {
@@ -45,216 +38,126 @@ To change the return value, copy the second line's anchor into `edit` and supply
45
38
  }
46
39
  ```
47
40
 
48
- The result includes a diff and the updated anchor:
49
-
50
- ```text
51
- Updated anchors:
52
- 2#V8AT
53
- ```
54
-
55
- Use returned anchors for changed lines in subsequent edits. Previously observed anchors remain usable when their line number, full content, and hash-length configuration are unchanged. Content-mode `grep` provides the same references, grouped by file. Always copy actual tool output; the examples use the default four-character hash.
56
-
57
- Successful `edit` and `replace` results omit candidate rows whose full content at the same line number is unchanged, then return compact `LINE#HASH` tokens by default. `edit` retains complete content for a deletion successor unless the batch also supplies that row; `replace` retains it for the first surviving line after a pure deletion. Anchor reports have a 16 KiB byte limit, including heading/omission notice, with no fixed entry-count limit. Neither tool reports every shifted line in the remaining file; read shifted positions when needed and no fresh anchor was returned. `write` returns no anchors. Explicit `read`/`grep` results and edit failure context continue to include the requested or diagnostic rows.
41
+ A successful mutation returns a JSON report; the TUI shows the diff. It does not return new anchors. Read or grep changed or shifted lines before editing them again. Existing anchors remain usable while their line number, full content, and hash-length setting are unchanged. Always copy actual tool output; the examples illustrate the default four-character hash.
58
42
 
59
43
  ## Tools
60
44
 
61
45
  | Tool | Use it for |
62
46
  | --- | --- |
63
- | `read` | Inspect UTF-8 text with line anchors; Pi-supported images and NUL-containing files use Pi's built-in read. Other invalid UTF-8 is rejected. |
64
- | `grep` | Search with bundled ripgrep and return anchored UTF-8 matches/context, plain previews for invalid UTF-8, file paths, or counts. NUL-containing files are skipped. |
65
- | `edit` | Change specific lines or ranges using verified anchors. |
66
- | `replace` | Replace every occurrence of a literal string or JavaScript regex across one file. |
67
- | `write` | Create a file or replace its complete contents. |
68
- | `forget` | When enabled in configuration, drop read or grep result content from model context right after reading it. |
69
-
70
- File tools accept relative and absolute paths, `file://` URLs, a leading `@` prefix, and a leading `~` (including `~\` on Windows). As in Pi's built-in file tools, supported Unicode spaces in paths become regular spaces, and Windows shell drive paths using only forward slashes, such as `/c/file`, `/mnt/c/file`, and `/cygdrive/c/file`, resolve to native drive paths. Mixed-separator forms such as `/c/dir\file` do not undergo this drive conversion, matching Pi's built-in tools. Mutation tools share the file-mutation queue and commit layer.
71
-
72
- Grep returns paths that can be copied back into these tools unchanged. It preserves literal backslashes in POSIX filenames and adds `./` when a relative name would otherwise be interpreted as an input prefix. Names requiring escaping, including supported Unicode spaces or line breaks, use encoded `file://` URLs.
47
+ | `read` | Inspect UTF-8 text with anchors; delegate supported images and NUL-containing files to Pi's built-in read, and reject other invalid UTF-8. |
48
+ | `grep` | Search files with JavaScript regex or literal text; return anchored matches, file paths, or counts. |
49
+ | `edit` | Replace, insert, delete, copy, or move whole lines using anchors. |
50
+ | `replace` | Apply literal or regex substitutions across one file. |
51
+ | `write` | Create a file or overwrite its complete contents. |
52
+ | `forget` | Remove eligible inspection results from model context when enabled. |
73
53
 
74
- Valid UTF-8 text inspection and matching uses one logical representation: CRLF boundaries become LF; standalone CR and source-code escape sequences such as the four characters `\r\n` remain content. `read` and `grep` hash the same logical lines that `edit` verifies; literal and regex `replace` both match this LF view. Mutation offsets map back to the original text. `edit` and `replace` share separator restoration: reuse internal separators positionally, repeat the last for extra gaps, or use the file style (CRLF if present, otherwise LF) when none exist. Boundaries outside the replacement stay unchanged. Invalid UTF-8 grep previews use raw-byte matching as described below.
75
-
76
- `write` is the full-content boundary: its supplied bytes are authoritative, so it preserves their explicit LF/CRLF choices. Use it for intentional whole-file line-ending conversion. To inspect actual line-ending bytes, use a raw byte reader; anchored line displays intentionally do not distinguish LF from CRLF.
77
-
78
- ### Argument errors
54
+ `read`, `edit`, `replace`, and `write` each take one `path`; `grep` can take several search roots. Paths accept relative and absolute names, `file://` URLs, leading `@`, and leading `~`. Windows forward-slash drive forms such as `/c/file`, `/mnt/c/file`, and `/cygdrive/c/file` resolve to native paths; mixed-separator forms do not. Supported Unicode spaces normalize as in Pi's built-in tools.
79
55
 
80
- All six tools use one argument-validation entry point. Tool-specific checks collect independent issues instead of stopping at the first one; the response also includes Pi's schema diagnostics. For example, an edit batch can report empty bodies, unwritable text, invalid anchor lengths, and invalid `then_run` fields in one rejection. Schema failures are diagnosed per top-level field, so one field cannot consume another field's diagnostic allowance. Received arguments use compact JSON in both model-facing errors and the TUI. Pi still limits schema errors within each field; the response states that more may remain.
56
+ Grep returns paths that can be reused unchanged, preserving POSIX backslashes and escaping ambiguous names with `./` or encoded `file://` URLs. Unknown tool fields are rejected. All mutation tools share the same file queue and [publication rules](#publication).
81
57
 
82
- Argument diagnostics share the 16 KiB block budget in [`budgets.ts`](src/pi/budgets.ts), retain opening and closing text, and label omitted text. Invalid arguments prevent execution. Filesystem access, anchor verification, regex probing by ripgrep, and forget eligibility remain subsequent checks that require valid arguments.
83
-
84
- ### Edit operations
85
-
86
- `edit` declares a required `path` and a non-empty structured `edits` array. This extension does not normalize alternate formats: stringified JSON and top-level single-op fields are rejected. Pi's own argument validation may convert a single edit object to a one-element array before the extension sees it. Anchors are `"LINE#HASH"` strings whose hash has exactly `hashLen` characters from uppercase Crockford base32 (digits and A–Z except I, L, O, and U). Line numbers are positive safe integers without leading zeroes. Each `body` element is one logical line without CR or LF. An anchor of a different hash length, such as one copied before a `hashLen` change, is rejected before the file is read, and the error names each such anchor. When several anchors have the wrong hash length, the recovery hint appears only with the first one.
58
+ ### Read
87
59
 
88
- | `op` | Required | Optional | Effect |
89
- | --- | --- | --- | --- |
90
- | `replace` | `anchor`, `body` | `end` | Replace one line or an inclusive range. |
91
- | `delete` | `anchor` | `end` | Delete one line or an inclusive range; no `body`. |
92
- | `insert_before` / `insert_after` | `anchor`, `body` | — | Insert beside the anchor; keep the anchor line. |
93
- | `prepend` / `append` | `body` | — | Insert at the start/end; no anchors. |
60
+ Required: non-empty `path`. Optional: `offset` (1-based, default 1) and `limit` (default 500). Both must be positive safe integers.
94
61
 
95
- Every `body` holds at least one line; `[""]` is a single blank line. Remove lines with `delete`. An empty `body: []` is rejected for every operation before the file is read, together with other independently detectable argument errors.
62
+ The line limit and [byte budget](#output-budgets) bound output. When more content remains, `pagination` gives `start`, inclusive `end`, `totalLines`, and `nextOffset`; use that offset to continue. EOF results omit pagination. `truncatedAt` identifies a byte limit, and `lineTooLong` means the first requested row cannot fit. No partial editable rows are returned: reducing `limit` cannot split an oversized line.
96
63
 
97
- If an edit leaves a blank line at the end, it writes the terminator needed to preserve that logical line, even when the original file lacked a final newline. For example, appending `[""]` to `"a"` produces `"a\n\n"`; replacing its only line with `[""]` produces `"\n"`. A BOM-only file already represents one blank line and keeps its BOM without an extra terminator. A non-empty final line retains the original final-newline state.
64
+ ### Grep
98
65
 
99
- All operations in a batch use the same snapshot. Validation failure rejects the whole batch. Unknown fields, conflicting fields, and overlapping operations are rejected; some touching operations also conflict and need separate calls with fresh anchors. For insertion, **do not repeat the anchor line in `body`**. `edit` uses structured operations, not `oldText`/`newText` pairs.
66
+ | Parameter | Default | Meaning |
67
+ | --- | --- | --- |
68
+ | `pattern` | Required | Non-empty string or array of strings; arrays match any pattern (OR). |
69
+ | `path` | Current directory | Existing file or directory, or a non-empty array of roots. Wildcards belong in `glob`. |
70
+ | `glob` | None | Glob or ordered array of globs; prefix exclusions with `!`. |
71
+ | `literal` | Required | `true` for exact text, `false` for JavaScript regex. Literal mode still uses the case settings. |
72
+ | `flags` | `m` | Host JavaScript flags. Explicit flags replace the default; `g` is always enabled and duplicates are ignored. |
73
+ | `ignoreCase` | `i` or smart-case | `true` enables `i`, `false` removes it. Otherwise `i` wins; without it, any uppercase letter in the decoded query makes the search case-sensitive. |
74
+ | `multiline` | `false` | Allow matches across physical lines. `\n` then matches LF or CRLF. |
75
+ | `context` | `0` | Integer from 0 to 20; surrounding lines do not count toward `limit` or enable multiline matching. |
76
+ | `limit` | `100` | Positive safe-integer maximum of distinct matching physical lines, across files and patterns. |
77
+ | `outputMode` | `"content"` | Anchored rows and context; `"files"` returns paths, `"count"` returns per-file matching-line counts. |
100
78
 
101
- The TUI edit header shows the total operation count and counts by type, for example `4 ops: replace ×2, delete ×1, append ×1`. During argument streaming, incomplete or unrecognized operation types count as `unknown`; the counts refresh as arguments change.
79
+ JavaScript validates and executes every pattern. Invalid patterns or flags, including incompatible `u` and `v`, fail before searching. Scoped modifiers retain their local effect; if smart-case analysis reaches a parser limit, the default is case-sensitive. Grep does not accept the former `matchMode`, `excludePattern`, `wordMatch`, `pcre2`, `follow`, or `noIgnore` fields. Use lookaround and `\b` for pattern constraints.
102
80
 
103
- For multi-operation batches that reach snapshot verification, rejected edits report each supplied anchor's status: `matched` or `mismatched`. Schema-invalid inputs fail before reading the file and have no anchor-status table. Single-operation edits omit the summary table and report the failure directly. Entries identify the zero-based operation index, `anchor` or `end`, and the cited token. The bounded list reports omitted entries explicitly. These statuses do not establish range/overlap validity, semantic intent, publication, command success, or validity on a later retry.
81
+ Directory searches respect ignore rules, include hidden files except `.git`, and do not follow symlinks. Explicit paths can name ignored files, `.git`, or symlink targets; ordered glob filters still apply to named files. The tool uses bundled ripgrep and ignores external ripgrep configuration. Ripgrep selects candidates; JavaScript decides the matches. An empty result does not rule out matches in excluded files.
104
82
 
105
- When an anchor no longer matches, `edit` looks for where the line went. Recovery only reports; it never edits or retries by itself:
83
+ All modes use the same limited set of matching lines, rather than individual match objects. `matches` and `files` state the confirmed totals. Reaching `limit` sets `matchLimit` without proving that another match exists. File order follows search completion; with a limit, the selected files can vary between runs. A final newline does not add an empty row, and a zero-width EOF match belongs to the last line only when it has no final newline.
106
84
 
107
- ```text
108
- cited anchor LINE#HASH
109
- |
110
- v
111
- hash of the cited line matches? -- yes --> verified
112
- | no
113
- v
114
- shiftRadius is 0? -- yes -------------------------------+
115
- | no |
116
- v |
117
- search within ±shiftRadius lines |
118
- | |
119
- v |
120
- any local candidate? -- no --> search the rest |
121
- | yes of the file |
122
- v | |
123
- how many candidates? <--------------+ |
124
- | |
125
- +-- one -----> unique: new anchor and full row |
126
- | |
127
- +-- several -> ambiguous: first 8 anchors and |
128
- | ±3-line neighborhoods |
129
- | |
130
- +-- none ----> unresolved: current cited row <--------+
131
-
132
- Every outcome rejects the whole batch and writes nothing;
133
- inspect the result and resubmit.
134
- ```
85
+ NUL-containing files are skipped. Other invalid UTF-8 is searched as lossy preview text and listed in `invalidUtf8`; its `LINE│content` rows have no editable anchors. Long lines show labeled partial previews, but their hashes cover the full line. Read the complete content before reconstructing one. Preview columns are 1-based UTF-16 positions.
135
86
 
136
- - Candidates are found by hashing each line's current content with the **cited** line number; each returned anchor uses the candidate's actual line number, so the details show both the old and current positions. Diagnostics say `Search: local` or `Search: full file`. A unique local candidate does not establish uniqueness across the file, because matches outside the window were not checked.
137
- - A unique candidate shows its new anchor and complete row once, without a neighborhood. Rows over 4 KiB are omitted in full with a prompt to use `read` or `grep`.
138
- - Ambiguous neighborhoods come from the same snapshot, are clipped to file boundaries, merged, and emitted in ascending line order within byte budgets. Their rows are observations, not suggested targets; candidate content already shown there is not repeated in the failure details.
139
- - With no candidate, the current cited row is shown as a complete `LINE#HASH│content` observation within the 4 KiB row limit. Confirm it is the intended target before reusing its anchor; use `read` or `grep` for more context, omitted rows, or out-of-range lines.
87
+ Each matched file is tied to its byte revision. Files that change during searching or display are excluded with diagnostics; confirmed matches from other files remain available. Incomplete results set `details.incomplete` and carry `diagnostics`. If no results can be returned, the tool reports `SEARCH_INCOMPLETE` rather than an unqualified no-match result.
140
88
 
141
- Every submitted anchor is verified again on retry.
89
+ Broad queries may search whole candidate files. `candidates: "files"` means required literals narrowed the files; `"all"` means every file in scope was eligible. The latter stops queueing after [256 MiB](src/pi/grep-candidates.ts) and reports `scanLimit`. Narrow `path`, `glob`, or the pattern to continue. A physical line, or an entire file for multiline matching, may hold at most [64 MiB](src/pi/grep-search.ts); exceeding that limit produces an incomplete-search diagnostic. Isolated regex requests are bounded by `grep.regexTimeoutMs`.
142
90
 
143
- ### Bulk replacement
144
-
145
- For a rename across a file:
146
-
147
- ```json
148
- { "path": "src/foo.ts", "replacements": [{ "find": "oldName", "replace": "newName" }] }
149
- ```
150
-
151
- Literal mode keeps `$` text verbatim. Both literal and regex modes match the shared LF view: actual CRLF in the file and `find` normalizes to LF; standalone CR remains content. Match ranges map back to the original text before replacement, preserving bytes and separators outside each match, including an unmatched BOM or final newline.
91
+ ### Edit operations
152
92
 
153
- Replacement text also normalizes CRLF to LF, then reuses matched separators in order. Additional lines use the last matched separator, or the file style when the match contains no separator (CRLF if present anywhere, otherwise LF).
93
+ Required: `path` and a non-empty `edits` array. Anchors are `"LINE#HASH"` strings copied from inspection. Line numbers are positive safe integers without leading zeroes; hashes must use the configured `hashLen`. An optional `end` selects an inclusive range; omit it for one line. `end: null` is invalid.
154
94
 
155
- Regex patterns use JavaScript syntax, unlike `grep`, which uses ripgrep's Rust regex; a pattern that works in one tool may fail or match differently in the other. Add the `m` flag for per-line `^`/`$`. `\d` matches only ASCII digits; `\w` and `\b` are ASCII-based, except that with both `i` and `u` they also treat `ſ` (U+017F) and `K` (U+212A) as word characters through case folding. Regex patterns run on LF text, so use `\n` for a line boundary. Captures and replacement templates also use the LF snapshot; the result then restores original separators. Use `write` for explicit line-ending conversion. Source-code escapes are ordinary text: JSON `"find": "\\r\\n"` finds the visible four-character sequence in literal mode, while `"find": "\r\n"` contains an actual CRLF boundary. Set `regex: true` for JavaScript capture groups and replacement templates:
95
+ | `op` | Required fields | Optional | Effect |
96
+ | --- | --- | --- | --- |
97
+ | `replace` | `anchor`, `body` | `end` | Replace a line or range. |
98
+ | `delete` | `anchor` | `end` | Remove a line or range. |
99
+ | `copy` / `move` | `anchor`, exactly one of `before` / `after` | `end` | Transfer original lines within the file; `move` also removes the source. |
100
+ | `insert_before` / `insert_after` | `anchor`, `body` | — | Insert beside the anchor, keeping that line. |
101
+ | `prepend` / `append` | `body` | — | Insert at the start or end. |
156
102
 
157
- ```json
158
- { "path": "src/foo.ts", "replacements": [{ "find": "get([A-Z]\\w*)", "replace": "fetch$1", "regex": true }] }
159
- ```
103
+ Each `body` element is one line without CR or LF. `body` must contain at least one element; `[""]` is a blank line. Use `delete` to remove lines, and do not repeat an insertion's anchor line in its body. `edit` accepts structured operations, not `oldText`/`newText` pairs or stringified JSON. Pi may convert a single operation object into an array during its own argument validation.
160
104
 
161
- To apply several rules against the same original content:
105
+ All operations use one original snapshot. Invalid anchors, ranges, or overlapping mutations reject the whole batch. Some touching edits also conflict; split them into calls and inspect any changed anchors between calls.
162
106
 
163
107
  ```json
164
108
  {
165
109
  "path": "src/foo.ts",
166
- "replacements": [
167
- { "find": "foo", "replace": "bar" },
168
- { "find": "bar", "replace": "baz" }
110
+ "edits": [
111
+ { "op": "copy", "anchor": "10#ABCD", "end": "12#EFGH", "before": "30#JKMN" }
169
112
  ]
170
113
  }
171
114
  ```
172
115
 
173
- Original `foo bar` becomes `bar baz`; inserted text is not searched again. All rules must succeed before one file commit. `then_run`, when supplied, runs once after the entire batch succeeds.
174
-
175
- <details>
176
- <summary><strong>Full read, grep, replace, write, and forget parameter reference</strong></summary>
177
-
178
- ### Read
179
-
180
- Required: non-empty `path`. Optional: positive safe-integer `offset` (1-based; default 1) and positive safe-integer `limit` (default 500 lines, set by `read.defaultLimit`). Fractions, zero, negative values, and unknown fields are rejected. Returned text is capped at 256 KiB by default (`read.maxKiB`); oversized rows are not returned as partial editable lines. Files without a final newline are identified in the header. Content delegated to Pi's built-in read is displayed without interpreting source text as hashline anchors.
181
-
182
- When the line limit leaves more content, the result reports the shown range and the next `offset`, for example `showing lines 1-500 of 1200; use offset 501 to continue`. `details.pagination` contains 1-based `start`, inclusive `end`, `totalLines`, and `nextOffset`. This applies to default and explicit limits. Reads reaching EOF omit pagination; byte-limited reads retain their byte-truncation notice and metadata.
183
-
184
- ### Grep
185
-
186
- | Parameter | Default | Meaning |
187
- | --- | --- | --- |
188
- | `pattern` | Required | Non-empty string (including whitespace-only text) or array of non-empty strings; arrays match any pattern (OR). When `ignoreCase` is omitted, smart-case is resolved for the entire query, not separately for each array item. |
189
- | `path` | Current directory | Omit `path` to search the working directory. If supplied, it must be one non-empty existing file or directory, or a non-empty array of search roots; `""` and `[]` are invalid. Wildcards are not expanded; use `glob` to filter filenames. |
190
- | `glob` | None | One non-empty glob or a non-empty ordered array; prefix exclusions with `!`. |
191
- | `literal` | Required | `true` matches every pattern as exact text, including regex punctuation such as `pi.on(`; use it for names, paths, and code snippets. It does not force case-sensitive matching. `false` treats every pattern as ripgrep Rust regex, not JavaScript regex: lookaround and backreferences are unsupported, `^`/`$` match at line boundaries, and a valid regex such as `foo(0)` matches `foo0`, not `foo(0)`. An invalid regex fails before any file is searched; when it contains lookaround or a backreference, the error says so and points to `replace` for JavaScript regex within one file, otherwise it suggests `literal: true`. |
192
- | `ignoreCase` | Smart-case | Query-level case override: `true` ignores case; `false` distinguishes case. Inline regex case flags may override either setting. |
193
- | `multiline` | `false` | Allow matches across physical lines. Valid UTF-8 CRLF is searched as LF; each distinct matched physical line counts toward `limit`. Content mode adds anchors only for valid UTF-8 files. `context` alone does not enable cross-line matching. The `.` wildcard still does not match newlines; use `\n` or `(?s)`. |
194
- | `context` | `0` | Integer from 0 to 20: include that many lines before and after each match (pass 3–5 to inspect code blocks without another read). Fractions are rejected, not rounded. Context lines do not count toward `limit`. |
195
- | `limit` | `100` | Positive safe-integer maximum of distinct matching physical lines, across all files and patterns. Reaching the limit produces a notice; it does not prove that another match exists. |
196
- | `outputMode` | `"content"` | `"content"` returns matching lines plus context, with anchors for valid UTF-8 or plain line numbers for invalid UTF-8; `"files"` returns distinct paths, and `"count"` returns matching-line counts per file and a total. All modes use the same limited match set: files and counts may be incomplete when the limit or output byte cap is reached. |
197
-
198
- The six former grep fields (`matchMode`, `excludePattern`, `wordMatch`, `pcre2`, `follow`, `noIgnore`) are no longer supported. Calls that contain them, including `false` or `null`, fail before searching; saved session history remains readable, but replaying an old call with these fields requires a new query. They are not silently converted to a different search.
199
-
200
- Grep defaults to line-based code searches. With `multiline: true`, OR patterns are scanned separately to retain overlapping spans, and matching physical lines are deduplicated before counting. There is no built-in content exclusion, same-line AND, whole-word switch, or PCRE2. Displaying neighboring lines with `context` does not itself match across lines. More specialized searches require another tool (for example, Bash when available); an empty grep result does not establish that ignored files or linked directories contain no matches.
201
-
202
- Directory traversal respects ignore rules, does not follow symbolic links, and includes hidden files. Explicitly named files can still be read through a link or from an ignored directory; ordered `glob` filters still apply to explicit file paths. These rules have different priorities for explicit paths and directory traversal and are not simply intersected.
116
+ Copies and moves read original source text even if another operation changes that source. They preserve text and separators without adjusting indentation. Source reads may overlap mutations, but move deletions and destination insertions obey the usual conflict rules. Multiple insertions at one gap conflict. A move destination inside the source range is invalid; moving immediately before its first line or after its last is a no-op. Use body edits when the text needs to change.
203
117
 
204
- Searches use bundled ripgrep, independent of system `rg` or `PATH`. The tool disables external ripgrep configuration with `--no-config` and clears `RIPGREP_CONFIG_PATH`, and uses `--no-crlf` and `--encoding=none` so standalone CR and BOM remain content. NUL-containing files are silently skipped in all output modes, including explicitly named files; they do not consume the match limit. Valid UTF-8 files use the shared LF view: files without CRLF are searched at their original paths, and CRLF text is normalized into temporary snapshots using bounded reads and writes. Batches contain up to 64 files or 8 MiB of source data (one large file can exceed that threshold); snapshots are removed after each batch and on failure/cancellation. Match paths refer to original files. Regexes use ripgrep's default Rust-style engine, not PCRE2.
118
+ On an anchor mismatch, recovery first searches within `shiftRadius`, then the rest of the file if no local candidate matches. Setting the radius to `0` disables both searches. A unique candidate includes its new anchor and bounded content; ambiguous candidates include up to eight anchors and merged ±3-line neighborhoods. With no candidate, the report shows the current cited row when available. A unique local match does not establish uniqueness across the whole file.
205
119
 
206
- Files with invalid UTF-8 and no NUL remain searchable as raw bytes, without CRLF normalization or encoding conversion. Multiline queries for these files must match their actual separators, such as `\r\n`. Queries containing actual CRLF characters retain them for raw-byte files, while valid UTF-8 files receive the LF-normalized query. Ripgrep's Unicode regex rules still apply; use a byte-mode group such as `(?-u:...)` when the pattern must span malformed bytes. Content-mode output uses replacement characters and plain `LINE│content` rows for the entire file, including context, followed by `Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors`. These previews are not editable anchors. Unmatched invalid UTF-8 files produce no warning.
120
+ Recovery never edits or retries automatically. Confirm the intended target before resubmitting; read or grep when content is omitted. Every retry verifies its anchors again. In multi-operation failures, `matched` lists supplied anchors whose checksums passed, and `failures` lists mismatches. Omitted entries are counted, not implied successful. A matching checksum does not establish semantic intent or validate a range's interior.
207
121
 
208
- All output modes verify invalid UTF-8 results against the source's pre-search byte revision and the complete raw-byte match spans reported by ripgrep, including the part of a multiline match omitted by `limit`. The tool keeps fixed-size byte digests and verifies them with a bounded scan; different malformed bytes cannot be accepted merely because both display as the same replacement character. Content output retains its complete-file byte revision check for valid UTF-8 as well. A detected mismatch reports `File changed during search`.
122
+ ### Bulk replacement
209
123
 
210
- Search diagnostics are preserved even when a result limit stops ripgrep. Readable, confirmed matches remain available with a `Search incomplete` notice and `details.incomplete: true`; counts then cover only confirmed matches. If no results can be returned, the tool reports an error rather than claiming there are no matches. Search diagnostics have a separate 4 KiB display budget. Ripgrep stderr and batch aggregation each retain up to 64 KiB. All three limits preserve opening context and the final cause where lines fit, and explicitly mark omitted middle text. The shared implementation is [`DiagnosticBuffer`](src/pi/diagnostic-buffer.ts); limits live in [`budgets.ts`](src/pi/budgets.ts) and [`rg-process.ts`](src/pi/rg-process.ts).
124
+ Required: `path` and a non-empty `replacements` array. Each rule requires non-empty `find` and a `replace` string, which may be empty:
211
125
 
212
- All file-tool errors retain every text block in the TUI, including validation causes and recovery hints. Short errors are shown in full when collapsed; longer errors use the same collapsed preview and expansion as grep results. Expanding reveals all retained diagnostic text, including edit recovery context and combined Action Fusion failure details. These display limits do not shorten the tool result sent to the model.
126
+ ```json
127
+ { "path": "src/foo.ts", "replacements": [{ "find": "oldName", "replace": "newName" }] }
128
+ ```
213
129
 
214
- Long lines show a labeled partial preview of up to 500 UTF-16 units near a reported match column when available; context-only lines and matches without a recorded column show their beginning. Labels report 1-based UTF-16 column ranges, and slicing preserves surrogate pairs. The anchor hashes the entire current line, not the preview; use `read` before reconstructing a line from its content.
130
+ Literal mode is the default and keeps `$` text verbatim. Set `regex: true` for JavaScript captures and replacement templates:
215
131
 
216
- ### Replace
132
+ ```json
133
+ { "path": "src/foo.ts", "replacements": [{ "find": "get([A-Z]\\w*)", "replace": "fetch$1", "regex": true }] }
134
+ ```
217
135
 
218
- Required: non-empty `path` and a non-empty `replacements` array. Use one item for a single rule; top-level `find`, `replace`, `regex`, and `flags` are not accepted. Each rule requires non-empty `find` and a `replace` string (which may be empty), with these optional fields:
136
+ Optional `flags` apply in either mode; accepted characters are `g i m s u y d`, with `g` always added. Unlike grep, replace has no default `m`: add it for per-line `^`/`$`. JavaScript `\d` is ASCII-only; `\w` and `\b` are ASCII-based, with Unicode case-folding exceptions under `iu`.
219
137
 
220
- - `regex`: defaults to `false`; both modes match the shared LF view. Regex mode supports capture groups, the full match, and prefix/suffix substitutions.
221
- - `flags`: applies in both modes; `g` is always added. Only `g i m s u y d` characters are accepted; regex syntax errors are reported per rule before the file is read.
138
+ Rules match the original [LF view](#text-and-line-endings); inserted text is not searched again. For example, rules `foo` → `bar` and `bar` → `baz` turn original `foo bar` into `bar baz`. Captures and prefix/suffix substitutions also refer to the original snapshot.
222
139
 
223
- Zero matches in any rule, an invalid rule, or overlapping match ranges rejects the whole call without writing. Adjacent ranges are allowed. Zero-length matches conflict at the same position or at the start/interior of another match; a zero-length match at another match's end is allowed unless it conflicts with a following match. Error rule indices and string offsets are zero-based (offsets count UTF-16 code units in the original text). Literal and regex rules share the same original ranges for conflict detection.
140
+ Any invalid rule, unmatched rule (`NO_MATCH`), or overlapping matches (`OVERLAPPING_MATCHES`) rejects the entire batch before writing. Adjacent matches are allowed. Zero-length matches conflict at the same position or inside another match, including its start but not its end. Error rule indices and offsets are zero-based; offsets count UTF-16 units in the original text.
224
141
 
225
- Regex captures and prefix/suffix substitutions always refer to the original LF-normalized snapshot.
226
- Regex batches run in a worker and are terminated on cancellation or when `replace.regexTimeoutMs` (default 5000 ms) elapses. A cancelled or timed-out batch leaves the file unchanged; literal-only batches retain their existing execution path.
142
+ Regex batches run in a worker bounded by `replace.regexTimeoutMs`; cancellation or timeout leaves the file unchanged. A supplied `then_run` executes once after the whole batch succeeds. The full rule schema is in [`replace-schema.ts`](src/core/replace-schema.ts).
227
143
 
228
144
  ### Write
229
145
 
230
- Required: `path`, `content`, `mode`. Choose `"create"` for a missing target or `"overwrite"` for an existing target; omitting `mode` is rejected before file access or command execution. Content is used exactly as supplied, including an empty string; anchor-looking prefixes are not stripped. Unknown fields, including misspelled modes, are rejected before writing.
231
-
232
- - `mode: "create"`: refuse an existing target.
233
- - `mode: "overwrite"`: require an existing target.
234
-
235
- Write results report the write outcome without returning line anchors. Use `read` or content-mode `grep` to obtain anchors for a later `edit`.
146
+ Required: `path`, `content`, and `mode`. `"create"` refuses an existing target; `"overwrite"` requires one. Missing or unknown modes fail before file access. Content is used exactly as supplied, including empty text and explicit line endings; anchor-looking prefixes are not stripped.
236
147
 
237
- Normal write result text omits the revision. Programmatic callers can read `details.publishedRevision`; edit and replace use source revisions internally to reject stale writes.
238
-
239
- With Action Fusion enabled, `edit`, `replace`, and `write` also accept `then_run`.
240
-
241
- All three mutation tools treat identical final content as a successful no-op: report `no net change`, leave the existing file untouched, and return `publication: "NOT_PUBLISHED"`. A requested `then_run` still runs after freshness checks. Input, anchor, match, target-type, mode, and cancellation checks still apply; edit/replace reject stale source revisions, while zero matches and an existing target in create mode remain errors. Creating a missing empty file is a publication, not a no-op.
148
+ All mutation tools treat identical final bytes as a successful no-op: the target stays untouched and `publication` is `NOT_PUBLISHED`. Input, anchor, match, revision, target-type, and mode checks still apply. Creating a missing empty file is a publication, and create mode still rejects an existing file. A requested `then_run` can run after a no-op.
242
149
 
243
150
  ### Forget
244
151
 
245
- Forget is disabled by default. Set `"forget": true` in `hashlineEdit` and reload Pi to enable it. While disabled, the extension registers neither the `forget` tool nor its context hooks, and read/grep results carry no result tags. Disabling it does not undo context edits already stored in the session.
246
-
247
- `read` results and content-mode `grep` results of at least 2 KiB of text, and image reads, end with a separate `[result rXXXXX]` block. Smaller results, errors, and `files`/`count` grep output carry no tag. `forget` takes `ids` (a non-empty array of distinct tags) and an optional non-empty `note` for conclusions needed in subsequent work. Omit `note` when none are needed; do not restate the read or forget action.
152
+ Disabled by default; enable `hashlineEdit.forget` and reload Pi. Eligible read and content-mode grep results carry a `resultId` (`rXXXXX`): text of at least [2 KiB](src/pi/budgets.ts), or an image read. Smaller results, errors, and files/count grep output are not tagged.
248
153
 
249
- Only results from the step the model has just seen can be forgotten: the tagged results after its previous response. Any other id rejects the whole call and lists the ids that are available. After the response that called `forget` completes, Pi's context edits replace the entire content of each named result with `[Result rXXXXX: content forgotten; rerun the call to see it again.]`. This removes all text and images, including headers, pagination, truncation and search notices, without inspecting their contents. The tool call, the rest of the exchange, and the `forget` call with its `note` stay in context. Save facts you still need in `note` before forgetting. Files, the raw session, and the TUI are unchanged; navigating to a point before the edit restores the original result.
154
+ A successful codemode result containing a successful read or content-mode grep call uses the same threshold. Its single tag covers the entire script output, including transformed data and other printed results; `forgetScope` states that scope. Nested calls have no separate tags. Use separate scripts when results need independent forgetting decisions.
250
155
 
251
- The `forget` card in the TUI shows the result count in its header, for example `forget · 2 results`, followed by what was forgotten: `build.log · lines 100–200` (with `· truncated` when the read hit its byte limit), `photo.png · image`, or `grep /pattern/ · 12 matches in 3 files` (with `· limit reached` or `· incomplete`). Expanding the card shows each result id beside its receipt; results without a detailed receipt show their id in either view. An optional `note` appears below the header. read and grep keep receipts in result details, which Pi does not send to the model; the model sees only `Forgot rXXXXX.`.
156
+ Call `forget` with a non-empty array of distinct `ids` and, if needed, a non-empty `note` containing conclusions to retain. Only results of the previous response qualify. The model forgets unneeded results in one call alongside its other tool calls, and skips forgetting when it makes no other call. It may forget an inspection result in the same response that submits its anchors to edit. Later responses cannot forget that result.
252
157
 
253
- The restriction bounds how much of the next request changes. Messages before the earliest forgotten result stay as they were; from that result on, the request differs, which covers any later results from the same batch (even ones not forgotten), the response that called `forget`, and its tool results. Forgetting an older result would change every later message. This describes request contents only; how a provider bills prompt caching for the changed part is not measured here.
158
+ Ids that no longer qualify appear in `notForgettable` without blocking valid ids; when none qualify, the call fails with `NOT_FORGETTABLE`. After the calling response completes, Pi replaces each selected result's entire content with a receipt containing `contentForgotten: true`. Keep needed facts in `note`; rerun the original call to see its output again.
254
159
 
255
- After `forget` completes, Pi continues with the next model request as it does for other tools. The selected results have already been replaced with receipts when that request is sent.
256
-
257
- </details>
160
+ Files, raw session history, tool calls, notes, and the TUI remain unchanged. Navigating before the context edit restores the original result. The forget card shows a description of each removed result and adds its id when expanded. Disabling forget prevents new tags and context hooks but does not undo stored edits. This feature changes request contents; provider cache savings are not measured.
258
161
 
259
162
  ## Configuration
260
163
 
@@ -268,33 +171,32 @@ Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json` by defau
268
171
  "forget": false,
269
172
  "hashLen": 4,
270
173
  "shiftRadius": 15,
271
- "read": { "defaultLimit": 500, "maxKiB": 256 },
272
- "grep": { "defaultLimit": 100, "defaultContext": 0 },
174
+ "read": { "defaultLimit": 500 },
175
+ "grep": { "defaultLimit": 100, "defaultContext": 0, "regexTimeoutMs": 5000 },
273
176
  "replace": { "regexTimeoutMs": 5000 }
274
177
  }
275
178
  }
276
179
  ```
277
180
 
278
- Top-level settings control shared behavior; each group configures one tool.
279
-
280
181
  | Setting | Default | Meaning |
281
182
  | --- | --- | --- |
282
- | `enabled` | `true` | Enable the extension. Set `false` to register no tools or hooks and restore built-in tools. |
283
- | `actionFusion` | `true` | Expose `then_run` on mutation tools. Set `false` to disable command support. |
284
- | `forget` | `false` | Register `forget` and tag eligible read/grep results for context removal. |
285
- | `hashLen` | `4` | Integer checksum length, 2–8 characters. `edit` accepts only anchors of this length; anchors produced under another setting must be read again. |
286
- | `shiftRadius` | `15` | Integer first-pass recovery-search radius, 0–100 lines. With no local candidates, recovery searches the rest of the file; `0` disables both searches. |
287
- | `read.defaultLimit` | `500` | Lines returned when a call omits `limit`; positive safe integer. |
288
- | `read.maxKiB` | `256` | Anchored text returned per call, 1–4096 KiB. Calls cannot raise it. |
289
- | `grep.defaultLimit` | `100` | Matching lines returned when a call omits `limit`; positive safe integer. |
290
- | `grep.defaultContext` | `0` | Context lines shown when a call omits `context`, 0–20. |
291
- | `replace.regexTimeoutMs` | `5000` | Time limit for one regex batch, 1000–300000 ms, including worker startup. |
292
-
293
- The project's `hashlineEdit` object replaces the global object as a whole. Each setting is resolved on its own: a missing or invalid setting, or a group that is not an object, uses the defaults while valid neighbors are kept. Types, bounds, and defaults are defined once by the settings schema in `src/pi/config.ts`. Tools receive the resolved configuration at registration, keep it for their lifetime, and state configured defaults in their parameter descriptions. Reload Pi after changes to register tools with the new configuration.
183
+ | `enabled` | `true` | Register the extension's tools and hooks. |
184
+ | `actionFusion` | `true` | Expose `then_run` on mutation tools. |
185
+ | `forget` | `false` | Register forget and tag eligible results. |
186
+ | `hashLen` | `4` | Checksum length, integer 2–8. Re-read anchors after changing it. |
187
+ | `shiftRadius` | `15` | Initial recovery radius, integer 0–100 lines; `0` disables recovery searches. |
188
+ | `read.defaultLimit` | `500` | Default returned lines; positive safe integer. |
189
+ | `read.maxKiB` | Model capacity | Explicit anchored-text cap, 1–4096 KiB. Calls cannot raise it; omit for automatic sizing. |
190
+ | `grep.defaultLimit` | `100` | Default matching lines; positive safe integer. |
191
+ | `grep.defaultContext` | `0` | Default context, integer 0–20. |
192
+ | `grep.regexTimeoutMs` | `5000` | One regex request, integer 3000–300000 ms, including remaining worker startup. |
193
+ | `replace.regexTimeoutMs` | `5000` | One regex batch, integer 3000–300000 ms, including worker startup. |
194
+
195
+ The project's `hashlineEdit` object replaces the global object as a whole. Within it, missing or invalid settings use their defaults while valid neighbors are kept. Invalid `read.maxKiB` selects automatic sizing. The [configuration schema](src/pi/config.ts) defines all types, bounds, and defaults. Reload Pi after changes; registered tools keep their configuration until then.
294
196
 
295
197
  ## Action Fusion
296
198
 
297
- Action Fusion is enabled by default. Set `"actionFusion": false` in `hashlineEdit` and reload Pi to disable it; an existing explicit `false` remains effective. Commands run only when a call supplies `then_run`:
199
+ Enabled by default. `edit`, `replace`, and `write` accept an optional command to run after the mutation:
298
200
 
299
201
  ```json
300
202
  {
@@ -304,150 +206,105 @@ Action Fusion is enabled by default. Set `"actionFusion": false` in `hashlineEdi
304
206
  }
305
207
  ```
306
208
 
307
- `command` is required and must contain a non-whitespace character; `timeout` is optional, in seconds greater than zero and at most 2147483.647, with no default. Unknown `then_run` fields are rejected.
209
+ `command` must contain a non-whitespace character. Optional `timeout` is in seconds, greater than zero and at most 2147483.647, with no default. Unknown fields are rejected before the file is touched. Set `hashlineEdit.actionFusion` to `false` and reload to remove command support.
308
210
 
309
- ```text
310
- edit / replace / write with then_run
311
- |
312
- v
313
- then_run valid? -- no --> rejected before the file is touched
314
- | yes
315
- v
316
- wait for this file's Fusion queue
317
- |
318
- v
319
- mutation completes? -- no, or cancelled first --> mutation error;
320
- | yes command skipped or cancelled
321
- v
322
- file still at the published revision? -- no --> command skipped --+
323
- | yes |
324
- v |
325
- run the session's callable Bash tool |
326
- (succeeded / failed / timeout / cancelled) |
327
- | |
328
- v |
329
- file unchanged at the end? <--------------------------------------+
330
- |
331
- +-- yes --> mutation result (edit/replace include fresh anchors),
332
- | then the command outcome
333
- |
334
- +-- no ---> mutation result with the [then_run:stale] notice,
335
- then the command outcome
336
- ```
211
+ After a successful mutation, Fusion checks that the file still matches the published revision, then invokes the session's callable Bash tool. Bash overrides, approval hooks, argument validation, and result hooks apply. An unavailable or blocked Bash tool produces a command failure. Mutation failure or a changed target prevents the command from starting.
212
+
213
+ Command failure never rolls back the file or turns a completed mutation into a mutation failure. The report carries `then_run.status` (`succeeded`, `failed`, `timeout`, `cancelled`, or `skipped`) and Bash output. A final freshness check reports a changed, missing, or unreadable target and asks for a re-read. The final session result determines command status; a nested `terminate` hint passes to the parent tool result.
337
214
 
338
- Once the mutation completes, it stays successful whatever happens to the command: command failure **does not roll back the file**. The command outcome is returned separately in result text and `details.actionFusion`, rather than thrown as failure of the whole mutation.
215
+ The per-file Fusion queue covers the mutation and command, so another fused call on that file waits. The tool call also waits for command completion and the final freshness check before model continuation. Local queues do not prevent external processes from changing the file.
339
216
 
340
- In the TUI, the mutation card owns the mutation's result or error diagnostics, publication status, and freshness warnings. It turns successful when mutation execution and result generation finish. The command card owns command output and execution status; skipped or cancelled commands are neutral and show a short reason when execution never started. Mutation diagnostics never become command output, and command failure leaves a successful mutation card intact. RPC hosts receive the same progress and choose their own rendering.
217
+ The TUI shows separate mutation and command cards. The diff remains visible while the command runs; skipped or cancelled commands show their reason. With `timeout`, a countdown starts at Bash's first execution update, excluding queue and approval waits. Bash enforces the timeout; an override without progress updates has no live countdown. Saved unfinished commands restore as interrupted with an unknown outcome. RPC hosts receive progress and choose their own presentation.
341
218
 
342
- When `then_run.timeout` is supplied, the command card shows the remaining seconds and refreshes once per second even without further command output. The countdown starts with the Bash tool's first execution update, after mutation, queue waiting, and any approval wait. It stops when execution ends; restored unfinished cards show an unknown final status without a countdown. The selected Bash implementation enforces the timeout; an override that emits no progress has no live countdown. Without `timeout`, there is no countdown or implicit time limit. RPC progress includes `timing.timeoutSeconds` and `timing.remainingSeconds` after a timed command starts.
219
+ ## Reports
343
220
 
344
- Command failures return the Bash tool's diagnostic text to the LLM, including exit or timeout details and whether file changes were saved. The final session result determines success, including nonzero exits and errors supplied by result hooks. Collapsing a TUI card does not shorten the model's result.
221
+ Tool facts are returned as one JSON report. Successful reads and searches append it after their payload; mutations return it alone. Success text omits `tool` and `path`, which the call already supplies, while `details.report` retains them for display. A report with no outcome facts is omitted when there is a payload. Failures return the report as the entire error result.
345
222
 
346
- The Fusion queue holds a file from mutation until its command finishes, so another fused call on the same file cannot change it in between. Commands use the session's nested tool dispatcher (`ctx.executeTool("bash", ...)`), including its argument validation, Bash overrides, `tool_call` approval hooks, and `tool_result` hooks. Bash must be callable in that session. If it is unavailable or a hook blocks the command, Fusion reports command failure and retains the completed mutation.
223
+ Failure reports name the `error`, failing step in `message`, and any underlying `cause`. Mutation failures also state `publication` and `stage` (`prepare`, `commit`, or `post_process`). Tool-specific facts describe pagination, search completeness, replacement counts, or recovery candidates. The optional final `next` field gives the recovery instruction. Follow it before retrying, especially when a write may already have been published.
347
224
 
348
- A nested Bash result's `terminate` hint is passed to the parent mutation result so Pi can apply its normal rule for stopping after the tool batch.
225
+ For example, a successful mutation followed by a failed command returns:
226
+
227
+ ```json
228
+ {
229
+ "publication": "PUBLISHED",
230
+ "then_run": { "status": "failed", "output": "…Bash output…\n\nCommand exited with code 1" }
231
+ }
232
+ ```
233
+
234
+ [`report-schema.ts`](src/pi/report-schema.ts) defines every field, error code, and recovery rule. Each fact has one owner and appears once; native failures retain their diagnostic rather than repeating it in a wrapper. Reports reject unknown fields and require the facts for their code. Old saved formats are not kept compatible. Invalid text-only reports remain raw, and invalid saved Fusion cards are ignored.
235
+
236
+ ### Argument errors
237
+
238
+ `INVALID_ARGUMENTS` means execution did not start. Its `issues` name each field, explain the `reason`, and include a `fix` when needed; shared fixes appear once. Diagnostics collect independent errors, select the relevant operation shape, and avoid duplicate parent summaries. A copy/move with neither or both destinations gets one exactly-one issue. Pi's schema pipeline still controls coercion and acceptance.
239
+
240
+ Field paths use dots for named properties, `[0]` for array indices, and JSON-quoted brackets for other names. `$` denotes a preparation failure without a field diagnostic. `omittedIssues` counts issues excluded by the byte budget; `schemaLimited` means a native diagnostic allowance was reached. These notices remain visible in collapsed cards. Expanding shows all retained issues without repeating the call's arguments.
349
241
 
350
242
  ## Safety and design
351
243
 
352
- - **Anchors are checksums, not identities.** Each hash combines the 1-based line number and content. Short hashes can collide and do not prove the model observed a line.
353
- - **Validation is local to supplied anchors.** Unrelated in-place changes leave stable anchors usable. A range verifies its supplied start/end anchors, not every interior line.
354
- - **Line shifts change anchors.** Insertions/deletions can invalidate later references. Recovery searches within `shiftRadius`, then the rest of the file if no local candidates match. Unique candidates include bounded line content; ambiguous candidates include neighborhoods for comparison. Use `read` when no candidate is found or needed content is omitted. Retries verify again, without fuzzy matching or automatic relocation.
355
- - **Edits preserve text representation.** `edit` preserves existing line endings, untouched separators, and final-newline state, adding a terminator when needed to represent a final blank line. `edit`/`replace` reject invalid UTF-8 source text; all mutations reject NUL and output that cannot be encoded losslessly as UTF-8. Supplied text (`write` content, `edit` body lines, `replace` replacement text) is checked before the file is read, naming the offending field; the final content is checked again before publication, because a transformation such as a regex without `u` can split a surrogate pair. UTF-16 and legacy code pages are not decoded or preserved; a BOM-free file whose bytes happen to be valid UTF-8 may still be misinterpreted.
356
- - **Fresh anchors depend on the final observation.** After `then_run`, anchors are shown only for `unchanged` freshness. Without a command, observed and published revisions must agree. Otherwise every mutation result, including `write`, ends with one notice to re-read before further edits, prefixed with `[then_run:stale]` when a command was requested. Later edits still verify anchors.
357
- - **Local queues are not cross-process transactions.** Revision checks bind mutations to the bytes read, but an external writer can still race a check and publication. There is no strict workspace jail or multi-file transaction.
244
+ Anchors are short checksums of a line's number and content. They can collide and do not prove the model observed the line. A range checks its supplied endpoints, not every interior line. Unrelated changes can leave anchors valid; line shifts usually invalidate them.
358
245
 
359
- <details>
360
- <summary><strong>Output budgets, byte fidelity, publication, and result-state details</strong></summary>
246
+ ### Text and line endings
361
247
 
362
- ### Hashing and BOM handling
248
+ `read`, `grep`, `edit`, and `replace` share an LF view: CRLF becomes LF, while standalone CR and literal source escapes remain content. Thus an actual CRLF in literal `find` matches a line boundary, but JSON `"find": "\\r\\n"` matches the four visible characters. Standalone CR displays as `␍`; that marker is a display aid, not replacement text.
363
249
 
364
- `read` scans text in bounded chunks, validates the whole file, and retains requested line content within its output budget. It reports the total line count and computes hashes for complete output rows. `grep` scans matching files concurrently, retaining only selected matches/context while formatting each file's output. Completed workers retain formatted output blocks in discovery order. It skips NUL-containing files and generates anchors only for files whose complete contents are valid UTF-8. Invalid UTF-8 previews and anchored output both retain byte revision checks. Mutation revision checks cover actual bytes.
250
+ Edit and replace map changes back to original bytes. They reuse matched separators in order, repeat the last for extra gaps, or use the file style (CRLF if present, otherwise LF). Untouched boundaries remain unchanged. Write uses supplied line endings exactly; use it for intentional whole-file conversion, and a raw byte reader to distinguish LF from CRLF.
365
251
 
366
- Line boundaries are LF or CRLF; a standalone CR remains line content. Anchored rows display standalone CR as `␍` (U+240D), while hashes use the original content. Edit/replace `details.diff` marks raw CR as `␍`; `details.displayDiff` renders the shared LF view for the TUI, so CRLF boundary markers stay hidden even in mixed-ending files or beside an unterminated last line. Standalone CR and literal `␍` characters remain visible. Unified patches retain the original characters and line endings. The marker is a display aid, not replacement text.
252
+ For edit, a non-empty final line retains the original final-newline state. A final blank line gets the terminator needed to represent it: appending `[""]` to `"a"` produces `"a\n\n"`. A BOM-only file already represents one blank line and keeps its BOM. Edit preserves an existing UTF-8 BOM at byte zero, including through copies, moves, and deletion of all content. Copy/move excludes that header from captured text; interior `U+FEFF` remains content. Replace can explicitly match the BOM; write uses supplied content.
367
253
 
368
- An existing UTF-8 BOM stays at byte zero through first-line replacement/deletion or insertion; deleting all content leaves the BOM. First-line hashes include it. A copied leading BOM in the first replacement/insertion line denotes the existing header; interior `U+FEFF` remains content. BOM-only files retain one anchored line. `replace` can explicitly match the BOM; `write` uses supplied content.
254
+ Mutations reject NUL and text that cannot be encoded losslessly as UTF-8. Edit and replace also reject invalid UTF-8 source files. UTF-16 and legacy code pages are not supported. Only confirmed malformed UTF-8 is classified as `UNSUPPORTED_ENCODING`; decoder resource failures keep their original error.
369
255
 
370
- ### Output budgets
256
+ Reads check file identity, size, and timestamps before accepting content. Detected concurrent writes, replacement, truncation, or deletion produce `FILE_CHANGED`; grep omits that file with diagnostics. These checks are not atomic snapshots and cannot detect changes hidden by timestamp resolution. Grep and mutations also retain byte-revision checks.
371
257
 
372
- These limits bound model context, not file size. Omission notices direct the caller to read more.
258
+ ### Publication
373
259
 
374
- | Output | Limit |
260
+ All mutations use the [shared commit layer](src/pi/file-commit.ts). Edit and replace bind publication to the revision of the bytes they read. Complete content is written and synced in a sibling temporary directory, then published with a link for creation or a rename for overwrite; the old target is never deleted first.
261
+
262
+ | State | Meaning |
375
263
  | --- | --- |
376
- | `read` | Default 500 rows (`read.defaultLimit`), overridable with `limit`; 256 KiB of anchored text (`read.maxKiB`). No partial anchor rows. An oversized single row directs the caller to inspect chunks with `bash` or make a known text change with `replace`; reducing `limit` cannot split a physical line. |
377
- | `grep` | Default 100 matching lines (`grep.defaultLimit`), overridable; up to 500 UTF-16 units per partial line preview, plus labels and Pi's total output limits. Match previews use rg byte offsets; hashes use full content. Search error notices have a separate 4 KiB budget. |
378
- | `forget` tag | With `forget` enabled: `read` and content-mode `grep` text results of 2 KiB or more, and image reads; smaller results are not tagged. |
379
- | `edit` / `replace` anchors | 16 KiB including heading/omission notice, with no fixed entry-count limit. Compact tokens for changed positions; selected deletion successors retain complete content. The omission notice consumes budget only when rows are omitted. Rows that do not fit are omitted in full; later rows that fit are still returned. |
380
- | Argument errors | 16 KiB for the combined tool-specific and Pi schema diagnostics; longer reports retain opening/closing text and label the omitted middle. Pi's schema error limit applies separately within each top-level field. |
381
- | Anchor failure details | 16 KiB, with no fixed failure-count limit; unique candidates include complete rows up to 4 KiB, and ambiguous failures list up to eight candidates each. Unresolved anchors show the current cited row when it fits; oversized or out-of-range rows require a fresh `read` or `grep`. |
382
- | Input-anchor checks | Independent 16 KiB block, with no fixed entry-count limit. Truncation is reported explicitly; omitted entries are not implied matched. |
383
- | Ambiguous-candidate neighborhoods | 16 KiB of complete anchored row text, lowest-line first, plus headings; no fixed row-count limit. Uses the same first eight candidates per failure as the detail lists. Each listed candidate row is limited to 4 KiB. Rows exceeding either limit are omitted in full; later rows that fit are still returned, with gaps reflected in the neighborhood headings. |
264
+ | `NOT_PUBLISHED` | No file change was published, including a successful no-op. |
265
+ | `PUBLISHED` | The file was published, even if a later step failed. |
266
+ | `UNKNOWN` | Publication could not be confirmed; inspect the file before retrying. |
384
267
 
385
- The diagnostic blocks have independent budgets; their combined output can exceed 16 KiB. Truncation notices identify exhausted budgets; context windows also report shown/omitted row counts. Limits apply to rendered diagnostics; core failure results retain all input-anchor checks.
268
+ Overwrites resolve symlinks and preserve the link; unresolved links, non-regular files (including FIFOs), and multiple hard links are rejected. Existing mode bits are copied; new files use `0600`. Directory sync is attempted on POSIX, tolerating unsupported-operation errors; Windows skips it.
386
269
 
387
- ### Publication
270
+ Post-publication failures retain the publication state and any completed command outcome. A `PUBLISHED` or `UNKNOWN` failure tells the model to read before repeating the change. Successful results expose `details.publishedRevision`; later observations that cannot confirm it add `freshness` (`changed`, `missing`, or `unknown`), with `freshnessError` for a failed observation.
388
271
 
389
- All three mutation tools publish through one commit layer. `edit`/`replace` bind it to the revision of the bytes they read:
272
+ Revision checks and local queues do not create a cross-process transaction: an external writer can race a check and publication. There is no strict workspace jail or multi-file transaction.
390
273
 
391
- ```text
392
- validate content and target: regular file, -- fails --> NOT_PUBLISHED
393
- single link, mode, expected revision
394
- |
395
- v
396
- same bytes as the current file? -- yes ----> no-op: NOT_PUBLISHED,
397
- | no target untouched
398
- v
399
- write and fsync complete content in a -- fails --> NOT_PUBLISHED
400
- sibling temporary directory
401
- |
402
- v
403
- edit/replace: still at the revision read? -- no -----> NOT_PUBLISHED
404
- | yes
405
- v
406
- create: link(temp, target) -- target appeared -> NOT_PUBLISHED
407
- overwrite: rename(temp, target) -- other failure ---> UNKNOWN
408
- |
409
- v
410
- sync directory (POSIX), read back the revision,
411
- remove the temporary directory
412
- |
413
- v
414
- PUBLISHED, even if a step after publication fails
415
- ```
274
+ ### Output budgets
416
275
 
417
- | Case | Behavior |
418
- | --- | --- |
419
- | No-op | After validation, return existing revisions without creating a temporary file or replacing the target. |
420
- | Create | Same-filesystem `link(temp, target)` refuses a target created by another writer during publication. |
421
- | Overwrite | `rename(temp, target)` publishes the replacement; never delete the old target first. |
422
- | Symlinks | Resolve the regular-file target for overwrite and preserve the link; reject dangling/unresolvable links. |
423
- | Non-regular files | Check the opened file handle before reading mutation snapshots or revisions. POSIX FIFO targets, including symlink aliases, are rejected without waiting for a writer. |
424
- | Multiple hard links | Reject existing regular files with multiple links to avoid splitting the link set. |
425
- | Permissions | Copy existing mode bits; new files use `0600`. No separate public permission setting. |
426
- | Post-publication failure | Directory-sync, result-generation, revision observation, or cleanup errors retain `PUBLISHED`; unconfirmed publication is `UNKNOWN`. Read before retrying uncertain mutations. |
427
- | Durability | Attempt directory synchronization on POSIX, including macOS; tolerate `EINVAL` / `ENOTSUP` from directory fsync and propagate other failures. Windows skips directory synchronization. |
428
- | Cancellation | Every tool reports cancellation as an error starting with `Operation aborted`, matching Pi's built-in tools. Mutation tools add where it stopped and whether the file changed, for example `Operation aborted before apply; src/foo.ts was not changed.` |
429
-
430
- ### Result and card states
431
-
432
- | Field | Meaning |
276
+ Budgets use the selected model's declared `contextWindow`, not remaining context or output `maxTokens`. They limit individual outputs, not the whole conversation or a combined codemode result. [`budgets.ts`](src/pi/budgets.ts) defines the policy; [`model-budgets.ts`](src/pi/model-budgets.ts) refreshes it when the selected model or capacity changes. Each call keeps one budget snapshot.
277
+
278
+ For a valid capacity `N`:
279
+
280
+ | Allowance | Calculation |
433
281
  | --- | --- |
434
- | `publication` | `NOT_PUBLISHED`, `PUBLISHED`, or `UNKNOWN`. Fusion also reports it in `actionFusion.publication`. |
435
- | `baseRevision` | SHA-256 of bytes read before mutation, when available. |
436
- | `publishedRevision` | SHA-256 of intended published bytes. |
437
- | `observedRevision` | SHA-256 observed by the commit layer after publication, or at the no-op check. |
438
- | `actionFusion.command` | `not_requested`, `skipped`, `succeeded`, `failed`, `timeout`, or `cancelled`. |
439
- | `actionFusion.freshness` | `unchanged`, `changed`, `missing`, or `unknown`, relative to the published revision. |
440
- | `actionFusion.mutationCompleted` | Progress flag set after mutation execution and result generation succeed; publication alone is not mutation success. |
282
+ | Content (`B`) | One byte per context token, capped at 4096 KiB |
283
+ | Diagnostic block (`D`) | `max(512, floor(B / 4))` bytes |
284
+ | Text field / candidate row (`F`) | `max(128, floor(D / 4))` bytes |
285
+ | Grep preview (`P`) | `floor(F / 4)` UTF-16 units, excluding labels |
441
286
 
442
- Streaming mutation summaries omit anchors. Result-generation failures preserve publication status and any completed command outcome; progress callback failures are reported separately from mutation/command outcomes. Command progress `output` contains only command output or execution errors, with an optional `reason` for commands that never started. Command cards persist only their own state and use native Bash output rendering. Final cards survive reloads without adding model-context messages; unfinished saved commands show an interrupted/unknown outcome.
287
+ Unknown capacity uses read 256 KiB, grep 50 KiB, diagnostic blocks 16 KiB, fields 4 KiB, and previews of 500 units. An explicit `read.maxKiB` changes only read's content cap.
443
288
 
444
- </details>
289
+ Read returns whole anchored rows within `B`; grep uses `B` for payload and `P` for each long-line preview. Report and cause messages, argument reasons/fixes, and grep diagnostics use `F`, retaining opening and ending text with omission notices. Argument reports stay valid JSON within `D` and omit whole issues when needed.
290
+
291
+ Anchor failures, matched-anchor lists, and candidate neighborhoods each have an independent `D` allowance. Candidate content uses `F`; neighborhoods retain complete anchored rows in line order. Omitted items are counted. These independent allowances mean a report can exceed `D` overall; `next` is outside the budgets. Images, delegated reads, Bash output, process buffers, and collapsed TUI previews retain their own limits. Expanding a TUI card does not change the model's result.
445
292
 
446
293
  ## Verification
447
294
 
448
- - `npm run typecheck` checks source, test, and benchmark types in `src/` and `bench/`.
449
- - `npm run format:check` checks formatting in both directories.
450
- - `npm test` runs core and tool tests.
451
- - `npm run test:integration` exercises bundled ripgrep, files over 100 MiB with LF and CRLF text, platform file types, and Action Fusion through real Pi sessions with command failures, cancellation, overrides, and approval/result hooks.
452
- - `npm run bench` measures core throughput and long-line match mapping.
453
- - `node --expose-gc bench/grep-memory.bench.ts` measures grep latency and sampled peak heap/RSS for 24 files totaling 192 MiB, each with one matching line. It creates and removes its fixtures in the system temporary directory.
295
+ | Command | Checks |
296
+ | --- | --- |
297
+ | `npm run format:check` | Formatting in `src/` and `bench/`. |
298
+ | `npm run typecheck` | Source, test, and benchmark types. |
299
+ | `npm test` | Core and tool tests. |
300
+ | `npm run test:integration` | Bundled ripgrep, large files, platform file types, installed packages, and real Pi session behavior. |
301
+ | `npm run test:all` | Unit and integration suites. |
302
+ | `npm run test:cartesian` | Only the Cartesian regex matrices from both suites. |
303
+ | `npm run bench` | Core throughput and long-line match mapping. |
304
+ | `node --expose-gc bench/grep-memory.bench.ts` | Grep latency and sampled peak heap/RSS on temporary fixtures. |
305
+
306
+ Cartesian matrices take minutes each and are skipped by the ordinary suites and CI. Run them after changing regex translation, candidate derivation, or prefiltering.
307
+
308
+ Tests run with isolated Node options and temporary Pi settings. Session tests use local scripted responses, never provider requests. Installed-package tests cannot resolve checkout development dependencies; the npm archive test checks tool registration, regex workers, commands, and forgetting through Pi's loader. It requires npm and tar.
309
+
310
+ Module responsibilities are documented in [`src/core/AGENTS.md`](src/core/AGENTS.md) and [`src/pi/AGENTS.md`](src/pi/AGENTS.md). [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) records the sources and licenses of borrowed regex analysis techniques and test cases.