@criogaid/pi-hashline-edit 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +74 -222
  2. package/README.zh-CN.md +162 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +172 -134
  6. package/src/core/apply.ts +28 -30
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +41 -9
  14. package/src/core/ranges.ts +11 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +5 -7
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +16 -8
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +127 -87
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +3 -4
  34. package/src/integration/model-budget-lifecycle.test.ts +15 -6
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +1 -1
  37. package/src/integration/npm-package.testing.ts +6 -32
  38. package/src/integration/publication-read-changes.test.ts +58 -26
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +2 -2
  42. package/src/integration/utf8-errors.test.ts +2 -2
  43. package/src/pi/AGENTS.md +12 -13
  44. package/src/pi/action-fusion.test.ts +71 -216
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +1 -1
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +5 -16
  52. package/src/pi/argument-validation.test.ts +59 -25
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +9 -12
  60. package/src/pi/execute.test.ts +80 -149
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +12 -9
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +270 -169
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +25 -16
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +4 -5
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +54 -49
  92. package/src/pi/render.test.ts +196 -93
  93. package/src/pi/render.ts +32 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +27 -26
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +55 -43
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +157 -117
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
package/README.md CHANGED
@@ -2,11 +2,19 @@
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 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.
5
+ English · [简体中文](README.zh-CN.md)
6
6
 
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).
7
+ Hash-anchored file editing for [Pi](https://github.com/earendil-works/pi-coding-agent). The model edits lines by citing anchors from `read` or `grep`; every anchor is checked against the current file before anything is written. Stale or mistaken edits are rejected with enough context for the model to correct them, instead of silently changing the wrong lines.
8
8
 
9
- [Quick start](#quick-start) · [Tools](#tools) · [Configuration](#configuration) · [Reports](#reports) · [Safety and design](#safety-and-design)
9
+ ## Why use it
10
+
11
+ - **Edits land where the model meant.** Each line carries a short `LINE#HASH` anchor. If the file changed since the model looked, the edit is rejected, and the report points to where the line moved.
12
+ - **No text matching.** The model never has to reproduce old text exactly, so whitespace drift, duplicate snippets, and long blocks stop causing failed or misplaced edits.
13
+ - **Files stay byte-faithful.** BOMs, CRLF/LF line endings, final newlines, and untouched bytes are preserved. Invalid UTF-8 and NUL bytes are rejected before writing.
14
+ - **Safe publication.** Writes are atomic (temporary file, then link or rename). Read-modify-write calls bind publication to the bytes they read; failures report whether publication happened.
15
+ - **Fewer round trips.** A mutation can carry a follow-up command such as `npm test` ([Action Fusion](#action-fusion)).
16
+ - **JavaScript regex everywhere.** `grep` and `replace` use the JavaScript regex semantics the model already knows, with ripgrep speed for finding candidate files.
17
+ - **Output sized to the model.** Result sizes scale with the selected model's context window, so small models are not flooded and large models are not starved.
10
18
 
11
19
  ## Install
12
20
 
@@ -14,11 +22,11 @@ Overrides `read`, `grep`, `edit`, and `write`, adds `replace` for file-wide subs
14
22
  pi install npm:@criogaid/pi-hashline-edit
15
23
  ```
16
24
 
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.
25
+ 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 the built-in tools.
18
26
 
19
27
  ## Quick start
20
28
 
21
- Pi's model uses these tools automatically. A `read` of `greet.ts` returns lines with `LINE#HASH` anchors:
29
+ Pi's model uses the tools automatically. A `read` returns lines with anchors:
22
30
 
23
31
  ```text
24
32
  greet.ts · 3 lines
@@ -27,148 +35,79 @@ greet.ts · 3 lines
27
35
  3#FNSZ│}
28
36
  ```
29
37
 
30
- Copy an anchor into `edit` and supply the new line content:
38
+ The model copies an anchor into `edit`:
31
39
 
32
40
  ```json
33
41
  {
34
42
  "path": "greet.ts",
35
- "edits": [
36
- { "op": "replace", "anchor": "2#GFYR", "body": [" return \"hello, hashline\";"] }
37
- ]
43
+ "edits": [{ "op": "replace", "anchor": "2#GFYR", "body": [" return \"hello, hashline\";"] }]
38
44
  }
39
45
  ```
40
46
 
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.
47
+ The edit succeeds only if line 2 still has that content. The TUI shows the diff; the model receives a short JSON report.
42
48
 
43
49
  ## Tools
44
50
 
45
- | Tool | Use it for |
46
- | --- | --- |
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. |
53
-
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.
55
-
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).
57
-
58
- ### Read
59
-
60
- Required: non-empty `path`. Optional: `offset` (1-based, default 1) and `limit` (default 500). Both must be positive safe integers.
51
+ The extension replaces Pi's `read`, `grep`, `edit`, and `write`, and adds `replace`.
61
52
 
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.
63
-
64
- ### Grep
53
+ | Tool | What it does |
54
+ | --- | --- |
55
+ | `read` | Shows UTF-8 text with anchors, paginated within the model's output budget. Images and files containing NUL bytes go to Pi's built-in read. |
56
+ | `grep` | Searches files and directories with JavaScript regex or literal text; returns anchored matches, file paths, or counts in traversal order; a limit keeps the first matches in that order. Respects ignore rules. |
57
+ | `edit` | Replaces, inserts, deletes, copies, or moves whole lines by anchor. All operations in one call apply to the same snapshot, or none apply. |
58
+ | `replace` | Applies literal or regex substitutions across one file. Every rule must match, and overlapping matches reject the batch. |
59
+ | `write` | Creates a file (`mode: "create"`) or overwrites one (`mode: "overwrite"`), using the content exactly as given. |
65
60
 
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. |
61
+ Grep visits input paths in the order supplied and uses ripgrep's sorted directory traversal within each root. Repeated candidate paths are searched once, at their first occurrence. This is not global lexicographic sorting of full paths.
78
62
 
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.
63
+ Grep matches the LF view with native JavaScript regexes. Without `multiline`, each physical line is searched separately; with it, the whole file is searched and every physical line touched by a match is returned. Context rows do not count toward `limit`. Content output re-reads matched files and omits any whose revision changed; `files` and `count` report the searched snapshot without a second read. Incomplete scans state their diagnostics or scan limit in the report.
80
64
 
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.
65
+ Edit operations:
82
66
 
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.
67
+ | `op` | Effect |
68
+ | --- | --- |
69
+ | `replace` / `delete` | Replace or remove a line, or an inclusive range with `end`. |
70
+ | `insert_before` / `insert_after` | Insert lines next to an anchor. |
71
+ | `prepend` / `append` | Insert lines at the start or end of the file. |
72
+ | `copy` / `move` | Copy or move a line range to before or after another anchor. |
84
73
 
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.
74
+ The model sees each tool's full parameter schema; the definitions live in the tool files under [`src/pi/`](src/pi/).
86
75
 
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.
76
+ Range operations verify the cited `anchor` and `end`, plus the destination for copy/move. Interior lines have no individual anchor check. Changes elsewhere before the call do not invalidate unchanged anchors; publication rechecks the bytes read while applying the call and rejects a detected change.
88
77
 
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`.
78
+ ## When an edit is rejected
90
79
 
91
- ### Edit operations
80
+ Argument and anchor validation failures leave the file untouched. The report names the error, the fields involved, and a `next` instruction. For a stale anchor it also shows where the line most likely moved, with its new anchor and nearby lines, so the model can confirm and resubmit without re-reading the whole file. Recovery never edits on its own; every retry is verified again.
92
81
 
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.
82
+ A failure during or after publication states `NOT_PUBLISHED`, `PUBLISHED`, or `UNKNOWN`. Follow the report's `next` before retrying: an error after publication can leave the requested change on disk.
94
83
 
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. |
84
+ Argument mistakes are reported per field, with what the field means and how to fix it, before any file is touched.
102
85
 
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.
86
+ ## Action Fusion
104
87
 
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.
88
+ `edit`, `replace`, and `write` accept an optional `then_run` command that runs right after a successful change:
106
89
 
107
90
  ```json
108
91
  {
109
92
  "path": "src/foo.ts",
110
- "edits": [
111
- { "op": "copy", "anchor": "10#ABCD", "end": "12#EFGH", "before": "30#JKMN" }
112
- ]
93
+ "replacements": [{ "find": "oldName", "literal": true, "replace": "newName" }],
94
+ "then_run": { "command": "npm test", "timeout": 60 }
113
95
  }
114
96
  ```
115
97
 
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.
117
-
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.
119
-
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.
121
-
122
- ### Bulk replacement
123
-
124
- Required: `path` and a non-empty `replacements` array. Each rule requires non-empty `find` and a `replace` string, which may be empty:
98
+ The command runs through the session's own Bash tool, so approvals, overrides, and hooks still apply. It starts only if the change succeeded and the file is still as written. A failing command never rolls back the file. The TUI shows the change and the command as separate cards, with a live countdown when a timeout is set.
125
99
 
126
- ```json
127
- { "path": "src/foo.ts", "replacements": [{ "find": "oldName", "replace": "newName" }] }
128
- ```
129
-
130
- Literal mode is the default and keeps `$` text verbatim. Set `regex: true` for JavaScript captures and replacement templates:
131
-
132
- ```json
133
- { "path": "src/foo.ts", "replacements": [{ "find": "get([A-Z]\\w*)", "replace": "fetch$1", "regex": true }] }
134
- ```
135
-
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`.
137
-
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.
139
-
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.
141
-
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).
143
-
144
- ### Write
145
-
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.
147
-
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.
149
-
150
- ### Forget
151
-
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.
153
-
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.
155
-
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.
157
-
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.
159
-
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.
100
+ Command cards use Pi's native tool component for mouse clicks and the global expand shortcut. Each card keeps its own expansion while output streams or the screen redraws. The built-in Bash renderer displays the command's original content and details, which are also saved for session restore; custom Bash renderer overrides are not exposed by the supported Pi API.
161
101
 
162
102
  ## Configuration
163
103
 
164
- Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json` by default) or the project's `.pi/settings.json`:
104
+ Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json`) or a project's `.pi/settings.json`:
165
105
 
166
106
  ```json
167
107
  {
168
108
  "hashlineEdit": {
169
109
  "enabled": true,
170
110
  "actionFusion": true,
171
- "forget": false,
172
111
  "hashLen": 4,
173
112
  "shiftRadius": 15,
174
113
  "read": { "defaultLimit": 500 },
@@ -180,131 +119,44 @@ Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json` by defau
180
119
 
181
120
  | Setting | Default | Meaning |
182
121
  | --- | --- | --- |
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.
122
+ | `enabled` | `true` | Register the extension's tools. |
123
+ | `actionFusion` | `true` | Allow `then_run` on mutation tools. |
124
+ | `hashLen` | `4` | Anchor hash length, 2–8. |
125
+ | `shiftRadius` | `15` | Lines searched around a stale anchor before the whole file, 0–100; `0` disables recovery search. |
126
+ | `read.defaultLimit` | `500` | Lines returned when the call gives no limit. |
127
+ | `read.maxKiB` | Model-based | Fixed cap on read output, 1–4096 KiB. |
128
+ | `grep.defaultLimit` | `100` | Matching lines returned when the call gives no limit. |
129
+ | `grep.defaultContext` | `0` | Context lines around each match, 0–20. |
130
+ | `grep.regexTimeoutMs` / `replace.regexTimeoutMs` | `5000` | Time limit for one regex evaluation, 3000–300000 ms. |
196
131
 
197
- ## Action Fusion
132
+ A project's `hashlineEdit` replaces the global one as a whole; invalid values fall back to their defaults. Reload Pi after changing settings. The [configuration schema](src/pi/config.ts) is the source of truth.
198
133
 
199
- Enabled by default. `edit`, `replace`, and `write` accept an optional command to run after the mutation:
134
+ ## Output budgets
200
135
 
201
- ```json
202
- {
203
- "path": "src/foo.ts",
204
- "replacements": [{ "find": "oldName", "replace": "newName" }],
205
- "then_run": { "command": "npm test", "timeout": 60 }
206
- }
207
- ```
208
-
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.
210
-
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.
214
-
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.
216
-
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.
218
-
219
- ## Reports
220
-
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.
222
-
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.
224
-
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.
241
-
242
- ## Safety and design
136
+ The selected model's declared context capacity sets the output budgets; remaining context is never used. For a known capacity, anchored read rows and grep payloads receive one byte per context token, up to 4 MiB. Diagnostic blocks receive a quarter of that budget (at least 512 bytes), and free-text fields a quarter of the block budget (at least 128 bytes). Grep previews keep one UTF-16 code unit per four field bytes. The definitions and fallback values live in [`budgets.ts`](src/pi/budgets.ts).
243
137
 
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.
138
+ When model capacity is unknown or invalid, the defaults are 256 KiB for read rows, 50 KiB for grep payloads, 16 KiB per diagnostic block, 4 KiB per free-text field, and 500 UTF-16 code units per grep preview. An explicit `read.maxKiB` overrides only the read cap. Each execution keeps the budget snapshot it started with.
245
139
 
246
- ### Text and line endings
140
+ Read reports pagination when the extension cuts a window or its byte budget; a caller-supplied `limit` alone does not add a pagination report. A first row that cannot fit gets a `lineTooLong` fact. Grep reports payload and preview truncation separately, and plain previews for invalid UTF-8 never carry edit anchors.
247
141
 
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.
142
+ ## Limits
249
143
 
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.
144
+ - Anchors are short checksums: they catch changed and shifted lines, but can collide and do not prove the model read the line.
145
+ - Only UTF-8 text is edited; UTF-16 and legacy code pages are not supported.
146
+ - Revision checks catch most concurrent changes, but there is no cross-process lock or multi-file transaction.
147
+ - Overwrites keep symlinks pointing at their target; FIFOs, other non-regular files, and files with multiple hard links are not overwritten.
148
+ - Grep's [search limits](src/pi/grep-search.ts) allow multiline files up to 64 MiB and individual physical lines up to 64 × 1024² UTF-16 code units. Matching runs in at most four workers, each with a 512 MiB V8 old-generation heap limit; individual regex evaluations use the configured timeout.
149
+ - When discovery falls back to every file in scope, it stops queuing files once their combined sizes reach the [256 MiB whole-scope budget](src/pi/grep-candidates.ts); the last queued file can cross that threshold. The report states when this prevents another file from being scanned. Ripgrep protocol records have a [16 MiB limit](src/pi/rg-process.ts). Unsupported or over-limit candidate analysis widens discovery; JavaScript still decides the matches.
251
150
 
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.
253
-
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.
255
-
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.
257
-
258
- ### Publication
259
-
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 |
263
- | --- | --- |
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. |
267
-
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.
269
-
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.
271
-
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.
273
-
274
- ### Output budgets
275
-
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 |
281
- | --- | --- |
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 |
286
-
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.
288
-
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.
292
-
293
- ## Verification
151
+ ## Development
294
152
 
295
153
  | Command | Checks |
296
154
  | --- | --- |
297
- | `npm run format:check` | Formatting in `src/` and `bench/`. |
298
- | `npm run typecheck` | Source, test, and benchmark types. |
155
+ | `npm run format:check` | Formatting. |
156
+ | `npm run typecheck` | Types for source, tests, and benchmarks. |
299
157
  | `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.
158
+ | `npm run test:integration` | Real ripgrep, large files, installed packages, and real Pi sessions. |
159
+ | `npm run test:all` | Both suites, as in CI. |
160
+ | `npm run test:cartesian` | Slow Cartesian regex matrices; run after changing regex translation or prefiltering. |
309
161
 
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.
162
+ Result fields and error codes are defined in [`report-schema.ts`](src/pi/report-schema.ts). Module responsibilities are 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) lists borrowed techniques and test cases.
@@ -0,0 +1,162 @@
1
+ # @criogaid/pi-hashline-edit
2
+
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
+
5
+ [English](README.md) · 简体中文
6
+
7
+ 为 [Pi](https://github.com/earendil-works/pi-coding-agent) 提供基于行哈希锚点的文件编辑。模型引用 `read` 或 `grep` 输出中的锚点来修改行,写入前每个锚点都会与当前文件核对。过期或错误的修改会被拒绝,并附带足够的信息让模型自行纠正,而不是悄悄改错行。
8
+
9
+ ## 优势
10
+
11
+ - **改到模型想改的位置。** 每一行都带一个简短的 `行号#哈希` 锚点。模型看过之后文件如果变了,修改会被拒绝,报告会指出这一行移到了哪里。
12
+ - **不靠文本匹配。** 模型不需要原样复述旧文本,空白差异、重复片段和大段代码不再导致修改失败或改错地方。
13
+ - **文件字节不走样。** 保留 BOM、CRLF/LF 换行、文件末尾换行和所有未改动的字节;非法 UTF-8 和 NUL 字节在写入前就被拒绝。
14
+ - **安全写入。** 先写临时文件,再通过 link 或 rename 原子发布;读改写调用绑定实际读取的字节,出错时明确告知文件是否已经发布。
15
+ - **减少来回。** 修改可以顺带一条后续命令,例如 `npm test`([Action Fusion](#action-fusion))。
16
+ - **统一使用 JavaScript 正则。** `grep` 和 `replace` 都采用模型熟悉的 JavaScript 正则语义,同时借助 ripgrep 快速筛选候选文件。
17
+ - **输出按模型调整。** 结果大小随所选模型的上下文窗口缩放:小模型不会被撑爆,大模型也不会信息不足。
18
+
19
+ ## 安装
20
+
21
+ ```bash
22
+ pi install npm:@criogaid/pi-hashline-edit
23
+ ```
24
+
25
+ 需要 Pi 0.99.1 或更高版本。扩展只处理本地文件;如果使用远程或自定义存储,把 `hashlineEdit.enabled` 设为 `false` 并重新加载 Pi,即可恢复内置工具。
26
+
27
+ ## 快速上手
28
+
29
+ Pi 的模型会自动使用这些工具。`read` 返回带锚点的行:
30
+
31
+ ```text
32
+ greet.ts · 3 lines
33
+ 1#ZR63│export function greet() {
34
+ 2#GFYR│ return "hello";
35
+ 3#FNSZ│}
36
+ ```
37
+
38
+ 模型把锚点复制到 `edit` 中:
39
+
40
+ ```json
41
+ {
42
+ "path": "greet.ts",
43
+ "edits": [{ "op": "replace", "anchor": "2#GFYR", "body": [" return \"hello, hashline\";"] }]
44
+ }
45
+ ```
46
+
47
+ 只有第 2 行内容仍然一致时修改才会成功。TUI 显示 diff,模型收到一份简短的 JSON 报告。
48
+
49
+ ## 工具
50
+
51
+ 扩展替换 Pi 的 `read`、`grep`、`edit`、`write`,并新增 `replace`。
52
+
53
+ | 工具 | 作用 |
54
+ | --- | --- |
55
+ | `read` | 显示带锚点的 UTF-8 文本,按模型的输出预算分页。图片和含 NUL 字节的文件交给 Pi 内置的 read。 |
56
+ | `grep` | 用 JavaScript 正则或字面文本搜索文件和目录,按遍历顺序返回带锚点的匹配行、文件路径或计数,设了 limit 时保留该顺序下的前若干条匹配;遵守忽略规则。 |
57
+ | `edit` | 按锚点替换、插入、删除、复制或移动整行。一次调用中的所有操作基于同一份快照,要么全部生效,要么全部不生效。 |
58
+ | `replace` | 在单个文件内批量执行字面或正则替换。每条规则都必须有匹配,匹配区域重叠时整批拒绝。 |
59
+ | `write` | 新建文件(`mode: "create"`)或覆盖文件(`mode: "overwrite"`),内容原样写入。 |
60
+
61
+ Grep 按传入顺序访问各个搜索路径,在每个根路径内采用 ripgrep 的有序目录遍历。重复候选路径只在第一次出现时搜索。这不是对所有文件完整路径做全局字典序排序。
62
+
63
+ Grep 用原生 JavaScript 正则匹配 LF 视图。不设 `multiline` 时逐物理行搜索;设为 true 时搜索整个文件,返回匹配涉及的每一物理行。上下文行不计入 `limit`。content 输出会重读匹配文件,略过版本已变的文件;`files` 和 `count` 直接报告搜索时的快照,不做第二次读取。扫描不完整时,报告会给出诊断或扫描上限。
64
+
65
+ `edit` 的操作:
66
+
67
+ | `op` | 效果 |
68
+ | --- | --- |
69
+ | `replace` / `delete` | 替换或删除一行;配合 `end` 处理闭区间范围。 |
70
+ | `insert_before` / `insert_after` | 在锚点前或后插入行。 |
71
+ | `prepend` / `append` | 在文件开头或末尾插入行。 |
72
+ | `copy` / `move` | 把一段行复制或移动到另一个锚点之前或之后。 |
73
+
74
+ 模型能看到每个工具完整的参数 schema,定义位于 [`src/pi/`](src/pi/) 下的各工具文件。
75
+
76
+ 范围操作核对给出的 `anchor`、`end`,以及复制或移动的目标锚点,不逐行验证区间内部的内容。调用前其他位置的变化不会使未改变的锚点失效;发布前会复核修改操作实际读取的字节,检测到变化时拒绝发布。
77
+
78
+ ## 修改被拒绝时
79
+
80
+ 参数和锚点校验失败时不会改动文件。报告会给出错误码、相关字段和一条 `next` 指引。锚点过期时,报告还会给出这一行最可能的新位置、新锚点和附近几行,模型确认后即可重新提交,不必重读整个文件。恢复过程从不自动修改,每次重试都会重新核对。
81
+
82
+ 发布期间或发布后的失败会明确标记 `NOT_PUBLISHED`、`PUBLISHED` 或 `UNKNOWN`。重试前应遵循报告的 `next`:发布后的错误可能意味着所需修改已经写入磁盘。
83
+
84
+ 参数错误按字段逐条报告,说明字段的含义和修正方法,此时还不会碰任何文件。
85
+
86
+ ## Action Fusion
87
+
88
+ `edit`、`replace`、`write` 可以带一个可选的 `then_run` 命令,在修改成功后立即运行:
89
+
90
+ ```json
91
+ {
92
+ "path": "src/foo.ts",
93
+ "replacements": [{ "find": "oldName", "literal": true, "replace": "newName" }],
94
+ "then_run": { "command": "npm test", "timeout": 60 }
95
+ }
96
+ ```
97
+
98
+ 命令通过会话自己的 Bash 工具执行,审批、覆盖和钩子照常生效。只有修改成功且文件仍是刚写入的内容时才会启动。命令失败不会回滚文件。TUI 把修改和命令分成两张卡片显示,设置了超时时会显示实时倒计时。
99
+
100
+ 命令卡片使用 Pi 原生工具组件处理鼠标点击和全局展开快捷键,输出更新或屏幕重绘时保留各自的展开状态。内置 Bash 渲染器直接显示命令的原始内容和 details,并将它们保存到会话中以供恢复;当前支持的 Pi API 无法取得其他扩展自定义的 Bash 渲染器。
101
+
102
+ ## 配置
103
+
104
+ 在 Pi 的全局设置(`~/.pi/agent/settings.json`)或项目的 `.pi/settings.json` 中添加 `hashlineEdit`:
105
+
106
+ ```json
107
+ {
108
+ "hashlineEdit": {
109
+ "enabled": true,
110
+ "actionFusion": true,
111
+ "hashLen": 4,
112
+ "shiftRadius": 15,
113
+ "read": { "defaultLimit": 500 },
114
+ "grep": { "defaultLimit": 100, "defaultContext": 0, "regexTimeoutMs": 5000 },
115
+ "replace": { "regexTimeoutMs": 5000 }
116
+ }
117
+ }
118
+ ```
119
+
120
+ | 设置项 | 默认值 | 含义 |
121
+ | --- | --- | --- |
122
+ | `enabled` | `true` | 注册扩展的工具。 |
123
+ | `actionFusion` | `true` | 允许修改类工具使用 `then_run`。 |
124
+ | `hashLen` | `4` | 锚点哈希长度,2–8。 |
125
+ | `shiftRadius` | `15` | 锚点过期时先在附近多少行内查找,再查全文件,0–100;`0` 关闭恢复查找。 |
126
+ | `read.defaultLimit` | `500` | 调用未指定时返回的行数。 |
127
+ | `read.maxKiB` | 按模型 | read 输出的固定上限,1–4096 KiB。 |
128
+ | `grep.defaultLimit` | `100` | 调用未指定时返回的匹配行数。 |
129
+ | `grep.defaultContext` | `0` | 每个匹配前后的上下文行数,0–20。 |
130
+ | `grep.regexTimeoutMs` / `replace.regexTimeoutMs` | `5000` | 单次正则计算的时限,3000–300000 毫秒。 |
131
+
132
+ 项目中的 `hashlineEdit` 会整体替换全局配置;非法值回退为默认值。修改设置后需重新加载 Pi。以 [配置 schema](src/pi/config.ts) 为准。
133
+
134
+ ## 输出预算
135
+
136
+ 输出预算根据所选模型声明的上下文容量计算,不使用剩余上下文。容量已知时,带锚点的 read 行和 grep 载荷各获得每上下文 token 一字节的预算,最高 4 MiB。诊断块获得其四分之一,至少 512 字节;自由文本字段获得诊断块预算的四分之一,至少 128 字节。Grep 预览每四字节字段预算保留一个 UTF-16 单元。定义和回退值位于 [`budgets.ts`](src/pi/budgets.ts)。
137
+
138
+ 模型容量未知或非法时,默认上限为 read 行 256 KiB、grep 载荷 50 KiB、每个诊断块 16 KiB、每个自由文本字段 4 KiB、每条 grep 预览 500 个 UTF-16 单元。显式设置 `read.maxKiB` 只覆盖 read 上限。每次执行使用开始时取得的预算快照。
139
+
140
+ Read 因默认行数或字节预算截断窗口时会报告分页;只有调用方指定的 `limit` 生效时不额外报告分页。首行放不下时报告 `lineTooLong`。Grep 分别报告载荷和行预览的截断,非法 UTF-8 的普通预览不带编辑锚点。
141
+
142
+ ## 限制
143
+
144
+ - 锚点是简短的校验和:能发现内容变化和行位移,但可能碰撞,也不能证明模型真的读过这一行。
145
+ - 只编辑 UTF-8 文本,不支持 UTF-16 和旧式代码页。
146
+ - 版本检查能发现大多数并发修改,但没有跨进程锁,也没有多文件事务。
147
+ - 覆盖写入时保留符号链接、改写其指向的文件;FIFO 等非普通文件和有多个硬链接的文件不会被覆盖。
148
+ - Grep 的[搜索限制](src/pi/grep-search.ts)允许 multiline 文件最多 64 MiB、单条物理行最多 64 × 1024² 个 UTF-16 单元。最多使用四个匹配 worker,每个 worker 的 V8 老生代堆上限为 512 MiB;单次正则计算受配置中的超时约束。
149
+ - 候选发现回退到作用域内所有文件时,累计排入队列的文件大小达到 [256 MiB 扫描预算](src/pi/grep-candidates.ts) 后停止继续加入文件;最后一个文件可以使总量超过该阈值。报告会指出预算是否阻止了后续文件的扫描。Ripgrep 协议记录的[上限为 16 MiB](src/pi/rg-process.ts)。候选分析不支持或超限时会扩大候选范围,最终匹配仍由 JavaScript 决定。
150
+
151
+ ## 开发
152
+
153
+ | 命令 | 检查内容 |
154
+ | --- | --- |
155
+ | `npm run format:check` | 格式。 |
156
+ | `npm run typecheck` | 源码、测试和基准测试的类型。 |
157
+ | `npm test` | 核心与工具测试。 |
158
+ | `npm run test:integration` | 真实 ripgrep、大文件、已安装包和真实 Pi 会话。 |
159
+ | `npm run test:all` | 两套测试,与 CI 一致。 |
160
+ | `npm run test:cartesian` | 耗时较长的笛卡尔积正则矩阵;修改正则翻译或预筛后运行。 |
161
+
162
+ 报告字段和错误码定义在 [`report-schema.ts`](src/pi/report-schema.ts)。模块职责见 [`src/core/AGENTS.md`](src/core/AGENTS.md) 与 [`src/pi/AGENTS.md`](src/pi/AGENTS.md)。[`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) 列出了借鉴的技术和测试用例。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@criogaid/pi-hashline-edit",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
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",
@@ -15,6 +15,7 @@
15
15
  "files": [
16
16
  "src",
17
17
  "README.md",
18
+ "README.zh-CN.md",
18
19
  "LICENSE",
19
20
  "THIRD_PARTY_NOTICES.md"
20
21
  ],
@@ -7,7 +7,7 @@ Internal pure engine: no Pi imports and no public API. It trusts input already f
7
7
  - `hash.ts` computes position-dependent line checksums (line number + content → `LINE#HASH`). `lines.ts` handles splitting, line-ending detection, and physical line counts. `text.ts` does strict UTF-8 decoding.
8
8
  - `apply.ts` `applyEdits` validates a whole batch of `Edit` ops (see `types.ts`) against a single snapshot: anchor checks, overlap and conflict detection, and shifted-anchor recovery (`AnchorRecovery`: local `shiftRadius` search, then full file). It returns new text or structured failures and never touches the filesystem.
9
9
  - `regex.ts` builds JavaScript regexes on the LF view (`regexSource`, `buildRegex`) for both grep and replace; neither engine imports the other.
10
- - `replace.ts` is replace's engine: literal and JavaScript-regex matching on the LF view, separator restoration, and overlap rejection. `replace-schema.ts` defines the tool's replacement schema and the engine's derived rule type.
10
+ - `replace.ts` is replace's engine: literal and JavaScript-regex matching on the LF view, separator restoration, and overlap rejection. `replace-schema.ts` defines the tool's replacement schema and the engine's result schema, with their derived types.
11
11
  - `search.ts` evaluates native JavaScript queries on the LF view and returns bounded physical rows; `search-schema.ts` defines its result.
12
12
  - `search-analysis.ts` parses patterns with regexpp (V8 has already accepted them at tool entry), decides smart case, and derives the literals every match must contain; `case-fold.ts` supplies JavaScript's case equivalence; `character-set.ts` owns character-class sets and shared AST surrogate-pair decoding for both candidate strategies.
13
13
  - `errors.ts` holds the classified `HashlineError`, typed by code so its facts and `next` alternative must match the code's schema, and errno classification.