@criogaid/pi-hashline-edit 0.4.0 → 0.5.1

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 (66) hide show
  1. package/README.md +134 -30
  2. package/package.json +3 -3
  3. package/src/core/apply.test.ts +194 -104
  4. package/src/core/apply.ts +6 -37
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +8 -8
  7. package/src/core/hash.ts +5 -5
  8. package/src/{pi/replace-apply.ts → core/replace.ts} +4 -4
  9. package/src/core/text.test.ts +30 -1
  10. package/src/core/text.ts +9 -6
  11. package/src/core/types.ts +4 -7
  12. package/src/index.ts +9 -11
  13. package/src/integration/config-registration.test.ts +206 -0
  14. package/src/integration/grep-rg.test.ts +285 -153
  15. package/src/integration/large-text.test.ts +11 -12
  16. package/src/integration/replace-package.test.ts +11 -7
  17. package/src/pi/action-fusion.test.ts +251 -39
  18. package/src/pi/action-fusion.ts +113 -117
  19. package/src/pi/anchor-format.test.ts +91 -24
  20. package/src/pi/anchor-format.ts +43 -9
  21. package/src/pi/budgets.ts +7 -2
  22. package/src/pi/config.test.ts +153 -40
  23. package/src/pi/config.ts +87 -41
  24. package/src/pi/diagnostic-buffer.test.ts +58 -0
  25. package/src/pi/diagnostic-buffer.ts +59 -0
  26. package/src/pi/e2e-scenarios.test.ts +13 -11
  27. package/src/pi/edit-tool.ts +21 -157
  28. package/src/pi/error-text.ts +10 -5
  29. package/src/pi/execute.test.ts +299 -175
  30. package/src/pi/failure-context.test.ts +7 -2
  31. package/src/pi/failure-context.ts +155 -8
  32. package/src/pi/failure-path.test.ts +33 -26
  33. package/src/pi/file-commit.ts +2 -1
  34. package/src/pi/fusion-card.test.ts +26 -0
  35. package/src/pi/fusion-card.ts +102 -6
  36. package/src/pi/grep-output.ts +50 -35
  37. package/src/pi/grep-render.ts +13 -15
  38. package/src/pi/grep-scope.ts +8 -46
  39. package/src/pi/grep-search.ts +90 -63
  40. package/src/pi/grep-tool.ts +109 -121
  41. package/src/pi/grep.test.ts +597 -377
  42. package/src/pi/mutation-outcome.testing.ts +22 -0
  43. package/src/pi/mutation-result.test.ts +51 -2
  44. package/src/pi/mutation-result.ts +62 -55
  45. package/src/pi/mutation-runner.ts +16 -33
  46. package/src/pi/pi.test.ts +11 -6
  47. package/src/pi/read-tool.ts +62 -34
  48. package/src/pi/registration.test.ts +7 -7
  49. package/src/pi/render.test.ts +143 -9
  50. package/src/pi/render.ts +32 -96
  51. package/src/pi/replace-regex.ts +54 -0
  52. package/src/pi/replace-tool.ts +25 -59
  53. package/src/pi/replace-worker.ts +2 -2
  54. package/src/pi/replace.test.ts +62 -58
  55. package/src/pi/result-safety.test.ts +124 -84
  56. package/src/pi/rg-line-ranges.ts +3 -2
  57. package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
  58. package/src/pi/{rg-line-filter.ts → rg-process.ts} +43 -9
  59. package/src/pi/rg-text-view.ts +25 -38
  60. package/src/pi/schema.ts +2 -10
  61. package/src/pi/text-stream.test.ts +153 -0
  62. package/src/pi/text-stream.ts +33 -13
  63. package/src/pi/write-tool.ts +3 -2
  64. package/src/pi/write.test.ts +10 -9
  65. package/src/core/index.ts +0 -14
  66. package/src/pi/state.ts +0 -26
package/README.md CHANGED
@@ -61,20 +61,20 @@ Successful `edit` and `replace` results omit candidate rows whose full content a
61
61
  | Tool | Use it for |
62
62
  | --- | --- |
63
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 matches/context, file paths, or counts. |
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
65
  | `edit` | Change specific lines or ranges using verified anchors. |
66
66
  | `replace` | Replace every occurrence of a literal string or JavaScript regex across one file. |
67
67
  | `write` | Create a file or replace its complete contents. |
68
68
 
69
- All 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 such as `/c/file`, `/mnt/c/file`, and `/cygdrive/c/file` resolve to native drive paths. Mutation tools share the file-mutation queue and commit layer.
69
+ All 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.
70
70
 
71
- All 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.
71
+ 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.
72
72
 
73
73
  `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.
74
74
 
75
75
  ### Edit operations
76
76
 
77
- `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; 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.
77
+ `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.
78
78
 
79
79
  | `op` | Required | Optional | Effect |
80
80
  | --- | --- | --- | --- |
@@ -89,15 +89,43 @@ All operations in a batch use the same snapshot. Validation failure rejects the
89
89
 
90
90
  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.
91
91
 
92
- Recovery first searches within `shiftRadius` of the cited line. If that search finds no candidates, it searches the rest of the file and collects all checksum matches before deciding whether the result is unique or ambiguous. Existing local candidates take priority; distant matches are not added when local candidates exist. `shiftRadius: 0` disables both searches. Candidate matching holds the original line number fixed when hashing current content; returned anchors use each candidate's actual line number.
92
+ When an anchor no longer matches, `edit` looks for where the line went. Recovery only reports; it never edits or retries by itself:
93
93
 
94
- Candidate diagnostics identify the search as `Search: local` or `Search: full file`. Local results explicitly state that matches outside the window were not checked: a unique local candidate does not establish uniqueness across the file. The cited line and returned candidate anchor show the old and current positions.
95
-
96
- A unique recovery candidate returns its new anchor and complete line content, without a neighborhood. Content is shown once per line and is limited to 4 KiB per candidate row; oversized content is omitted in full with a prompt to use `read` or `grep`.
94
+ ```text
95
+ cited anchor LINE#HASH
96
+ |
97
+ v
98
+ hash of the cited line matches? -- yes --> verified
99
+ | no
100
+ v
101
+ shiftRadius is 0? -- yes -------------------------------+
102
+ | no |
103
+ v |
104
+ search within ±shiftRadius lines |
105
+ | |
106
+ v |
107
+ any local candidate? -- no --> search the rest |
108
+ | yes of the file |
109
+ v | |
110
+ how many candidates? <--------------+ |
111
+ | |
112
+ +-- one -----> unique: new anchor and full row |
113
+ | |
114
+ +-- several -> ambiguous: first 8 anchors and |
115
+ | ±3-line neighborhoods |
116
+ | |
117
+ +-- none ----> unresolved: current cited row <--------+
118
+
119
+ Every outcome rejects the whole batch and writes nothing;
120
+ inspect the result and resubmit.
121
+ ```
97
122
 
98
- Ambiguous failures list up to eight candidate anchors and include a bounded ±3-line neighborhood around each listed candidate from the same snapshot. Windows are clipped to file boundaries, merged, and emitted in ascending line order within byte budgets. Neighboring rows are observations, not recommended replacement targets. Candidate content already present in a neighborhood is not repeated in failure details. Inspect the code to choose the correct anchor and operation, then resubmit. No edit or retry is performed automatically, and every submitted anchor is verified again.
123
+ - 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.
124
+ - 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`.
125
+ - 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.
126
+ - 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.
99
127
 
100
- When no candidate is found, diagnostics show the current cited line as a complete `LINE#HASH│content` observation within the 4 KiB row limit. Confirm it is the intended target before reusing its anchor directly. Use `read` or `grep` for additional context, omitted rows, or out-of-range references. Retries revalidate.
128
+ Every submitted anchor is verified again on retry.
101
129
 
102
130
  ### Bulk replacement
103
131
 
@@ -136,7 +164,7 @@ Original `foo bar` becomes `bar baz`; inserted text is not searched again. All r
136
164
 
137
165
  ### Read
138
166
 
139
- Required: non-empty `path`. Optional: positive safe-integer `offset` (1-based; default 1) and positive safe-integer `limit` (default 500 lines). Fractions, zero, negative values, and unknown fields are rejected. Returned text is capped at 256 KiB; oversized rows are not returned as partial editable lines. Files without a final newline are identified in the header.
167
+ 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.
140
168
 
141
169
  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.
142
170
 
@@ -147,12 +175,12 @@ When the line limit leaves more content, the result reports the shown range and
147
175
  | `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. |
148
176
  | `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. |
149
177
  | `glob` | None | One non-empty glob or a non-empty ordered array; prefix exclusions with `!`. |
150
- | `literal` | Automatic | Set `true` for literal code text, including regex punctuation such as `pi.on(`; this does not force case-sensitive matching. Set `false` for intentional ripgrep Rust regex, not JavaScript regex: lookaround and backreferences are unsupported, and `^`/`$` match at line boundaries. Automatic mode tries regex for metacharacters; an invalid single-pattern query falls back to searching the **entire string** literally and reports the fallback. Invalid pattern arrays fail instead of changing their meaning; invalid regex with `literal: false` fails. When the pattern contains lookaround or a backreference, the error or fallback notice says so and points to `replace` for JavaScript regex within one file. |
178
+ | `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`. |
151
179
  | `ignoreCase` | Smart-case | Query-level case override: `true` ignores case; `false` distinguishes case. Inline regex case flags may override either setting. |
152
- | `multiline` | `false` | Allow matches across physical lines. CRLF is searched as LF; each distinct matched physical line counts toward `limit` and receives an anchor in content mode. `context` alone does not enable cross-line matching. The `.` wildcard still does not match newlines; use `\n` or `(?s)`. |
153
- | `context` | `0` | Integer from 0 to 20: include that many anchored 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`. |
180
+ | `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)`. |
181
+ | `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`. |
154
182
  | `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. |
155
- | `outputMode` | `"content"` | `"content"` returns anchored matching lines plus context, `"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. |
183
+ | `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. |
156
184
 
157
185
  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.
158
186
 
@@ -160,9 +188,13 @@ Grep defaults to line-based code searches. With `multiline: true`, OR patterns a
160
188
 
161
189
  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.
162
190
 
163
- Searches use bundled ripgrep on the shared LF view, 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 searched as raw bytes; confirmed content-mode hits are rejected before anchoring, and multiline hits are rejected before mapping physical lines. Files without CRLF are searched at their original paths; 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; text line and column positions refer to logical text. Regexes use ripgrep's default Rust-style engine, not PCRE2.
191
+ 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.
192
+
193
+ 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`. 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. Files/count modes include their confirmed matches. Unmatched invalid UTF-8 files produce no warning. Content output still verifies the file's byte revision before returning results.
164
194
 
165
- 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.
195
+ 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).
196
+
197
+ 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.
166
198
 
167
199
  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.
168
200
 
@@ -176,7 +208,7 @@ Required: non-empty `path` and a non-empty `replacements` array. Use one item fo
176
208
  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.
177
209
 
178
210
  Regex captures and prefix/suffix substitutions always refer to the original LF-normalized snapshot.
179
- Regex batches run in a worker and are terminated on cancellation or after 5 seconds of evaluation. A cancelled or timed-out batch leaves the file unchanged; literal-only batches retain their existing execution path.
211
+ 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.
180
212
 
181
213
  ### Write
182
214
 
@@ -205,19 +237,29 @@ Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json` by defau
205
237
  "enabled": true,
206
238
  "actionFusion": true,
207
239
  "hashLen": 4,
208
- "shiftRadius": 15
240
+ "shiftRadius": 15,
241
+ "read": { "defaultLimit": 500, "maxKiB": 256 },
242
+ "grep": { "defaultLimit": 100, "defaultContext": 0 },
243
+ "replace": { "regexTimeoutMs": 5000 }
209
244
  }
210
245
  }
211
246
  ```
212
247
 
248
+ Top-level settings apply to every tool; each group applies to one tool.
249
+
213
250
  | Setting | Default | Meaning |
214
251
  | --- | --- | --- |
215
252
  | `enabled` | `true` | Enable all five tools as one unit. Set `false` to restore built-in tools. |
216
253
  | `actionFusion` | `true` | Expose `then_run` on mutation tools. Set `false` to disable command support. |
217
254
  | `hashLen` | `4` | Integer checksum length, 2–8 characters. `edit` accepts only anchors of this length; anchors produced under another setting must be read again. |
218
255
  | `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. |
256
+ | `read.defaultLimit` | `500` | Lines returned when a call omits `limit`; positive safe integer. |
257
+ | `read.maxKiB` | `256` | Anchored text returned per call, 1–4096 KiB. Calls cannot raise it. |
258
+ | `grep.defaultLimit` | `100` | Matching lines returned when a call omits `limit`; positive safe integer. |
259
+ | `grep.defaultContext` | `0` | Context lines shown when a call omits `context`, 0–20. |
260
+ | `replace.regexTimeoutMs` | `5000` | Time limit for one regex batch, 1000–300000 ms, including worker startup. |
219
261
 
220
- The project's `hashlineEdit` object replaces the global object as a whole; missing or invalid fields use defaults. Reload Pi after changes.
262
+ 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.
221
263
 
222
264
  ## Action Fusion
223
265
 
@@ -231,11 +273,46 @@ Action Fusion is enabled by default. Set `"actionFusion": false` in `hashlineEdi
231
273
  }
232
274
  ```
233
275
 
234
- `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. Invalid command parameters fail before mutation. Mutation failure skips the command. Command failure after mutation success **does not roll back the file**: it is returned separately in result text and `details.actionFusion`, rather than thrown as failure of the whole mutation.
276
+ `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.
235
277
 
236
- In the TUI, the mutation card owns the mutation's result or error summary, 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.
278
+ ```text
279
+ edit / replace / write with then_run
280
+ |
281
+ v
282
+ then_run valid? -- no --> rejected before the file is touched
283
+ | yes
284
+ v
285
+ wait for this file's Fusion queue
286
+ |
287
+ v
288
+ mutation completes? -- no, or cancelled first --> mutation error;
289
+ | yes command skipped or cancelled
290
+ v
291
+ file still at the published revision? -- no --> command skipped --+
292
+ | yes |
293
+ v |
294
+ run the command with Pi's built-in Bash |
295
+ (succeeded / failed / timeout / cancelled) |
296
+ | |
297
+ v |
298
+ file unchanged at the end? <--------------------------------------+
299
+ |
300
+ +-- yes --> mutation result (edit/replace include fresh anchors),
301
+ | then the command outcome
302
+ |
303
+ +-- no ---> mutation result with the [then_run:stale] notice,
304
+ then the command outcome
305
+ ```
237
306
 
238
- Fusion serializes each mutation/command sequence for its target and checks the published revision before running the command. Commands invoke Pi's built-in Bash definition directly, without a separate Bash tool call; Bash-only approval/sandbox extensions must explicitly cover these tools' `then_run` inputs.
307
+ 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.
308
+
309
+ 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.
310
+
311
+ When `then_run.timeout` is supplied, the command card shows the remaining seconds and refreshes once per second even without command output. The countdown starts when the command starts, after mutation and queue waiting. It stops when execution ends; restored unfinished cards show an unknown final status without a countdown. Pi Bash enforces the timeout. Without `timeout`, there is no countdown or implicit time limit. RPC progress includes `timing.timeoutSeconds` and `timing.remainingSeconds` after a timed command starts.
312
+
313
+ Command failures return Pi Bash's diagnostic text to the LLM, including exit or timeout details and whether file changes were saved. Collapsing a TUI card does not shorten the model's result.
314
+
315
+ 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 invoke Pi's built-in Bash definition directly, without a separate Bash tool call; Bash-only approval/sandbox extensions must explicitly cover these tools' `then_run` inputs.
239
316
 
240
317
  ## Safety and design
241
318
 
@@ -243,7 +320,7 @@ Fusion serializes each mutation/command sequence for its target and checks the p
243
320
  - **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.
244
321
  - **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.
245
322
  - **Edits preserve text representation.** `edit` preserves existing line endings, untouched separators, and the absence of a final newline. `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.
246
- - **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. Later edits still verify anchors.
323
+ - **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.
247
324
  - **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.
248
325
 
249
326
  <details>
@@ -251,7 +328,7 @@ Fusion serializes each mutation/command sequence for its target and checks the p
251
328
 
252
329
  ### Hashing and BOM handling
253
330
 
254
- `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. NUL-containing files are searched as raw bytes and confirmed content-mode hits are rejected before anchoring. Mutation revision checks cover actual bytes.
331
+ `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.
255
332
 
256
333
  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.
257
334
 
@@ -263,9 +340,9 @@ These limits bound model context, not file size. Omission notices direct the cal
263
340
 
264
341
  | Output | Limit |
265
342
  | --- | --- |
266
- | `read` | Default 500 rows, overridable with `limit`; 256 KiB of anchored text. 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. |
267
- | `grep` | Default 100 matching lines, 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. |
268
- | `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. Rows that do not fit are omitted in full; later rows that fit are still returned. |
343
+ | `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. |
344
+ | `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. |
345
+ | `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. |
269
346
  | 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`. |
270
347
  | Input-anchor checks | Independent 16 KiB block, with no fixed entry-count limit. Truncation is reported explicitly; omitted entries are not implied matched. |
271
348
  | 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. |
@@ -274,7 +351,33 @@ The diagnostic blocks have independent budgets; their combined output can exceed
274
351
 
275
352
  ### Publication
276
353
 
277
- The shared commit layer validates the target and skips publication when the requested UTF-8 bytes have the current file's SHA-256. Otherwise, it prepares and syncs complete content in a sibling temporary directory. `edit`/`replace` bind this check and publication to the revision of the bytes they read.
354
+ All three mutation tools publish through one commit layer. `edit`/`replace` bind it to the revision of the bytes they read:
355
+
356
+ ```text
357
+ validate content and target: regular file, -- fails --> NOT_PUBLISHED
358
+ single link, mode, expected revision
359
+ |
360
+ v
361
+ same bytes as the current file? -- yes ----> no-op: NOT_PUBLISHED,
362
+ | no target untouched
363
+ v
364
+ write and fsync complete content in a -- fails --> NOT_PUBLISHED
365
+ sibling temporary directory
366
+ |
367
+ v
368
+ edit/replace: still at the revision read? -- no -----> NOT_PUBLISHED
369
+ | yes
370
+ v
371
+ create: link(temp, target) -- target appeared -> NOT_PUBLISHED
372
+ overwrite: rename(temp, target) -- other failure ---> UNKNOWN
373
+ |
374
+ v
375
+ sync directory (POSIX), read back the revision,
376
+ remove the temporary directory
377
+ |
378
+ v
379
+ PUBLISHED, even if a step after publication fails
380
+ ```
278
381
 
279
382
  | Case | Behavior |
280
383
  | --- | --- |
@@ -306,7 +409,8 @@ Streaming mutation summaries omit anchors. Result-generation failures preserve p
306
409
 
307
410
  ## Verification
308
411
 
309
- - `npm run typecheck` checks source and test types.
412
+ - `npm run typecheck` checks source, test, and benchmark types in `src/` and `bench/`.
413
+ - `npm run format:check` checks formatting in both directories.
310
414
  - `npm test` runs core and tool tests.
311
415
  - `npm run test:integration` exercises bundled ripgrep and files over 100 MiB, including LF and CRLF text.
312
416
  - `npm run bench` measures core throughput and long-line match mapping.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@criogaid/pi-hashline-edit",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "type": "module",
5
5
  "description": "Hashline-style file editing for pi — line-anchored edits verified by content hash, replacing oldText/newText matching",
6
6
  "homepage": "https://github.com/Criogaid/pi-hashline-edit#readme",
@@ -18,8 +18,8 @@
18
18
  "LICENSE"
19
19
  ],
20
20
  "scripts": {
21
- "format": "biome format --write src/",
22
- "format:check": "biome format src/",
21
+ "format": "biome format --write src/ bench/",
22
+ "format:check": "biome format src/ bench/",
23
23
  "typecheck": "tsc --noEmit",
24
24
  "test": "node --test src/core/*.test.ts src/pi/*.test.ts",
25
25
  "test:integration": "node --test src/integration/*.test.ts",