@criogaid/pi-hashline-edit 0.5.1 → 0.6.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.
- package/README.md +51 -15
- package/package.json +6 -6
- package/src/core/apply.test.ts +66 -16
- package/src/core/apply.ts +36 -19
- package/src/core/lines.ts +3 -3
- package/src/index.ts +2 -0
- package/src/integration/forget-grep.test.ts +98 -0
- package/src/integration/fusion-dispatch.test.ts +343 -0
- package/src/integration/grep-rg.test.ts +269 -33
- package/src/integration/mutation-file-types.test.ts +44 -0
- package/src/pi/action-fusion.test.ts +71 -128
- package/src/pi/action-fusion.ts +83 -45
- package/src/pi/argument-validation.test.ts +136 -0
- package/src/pi/argument-validation.ts +102 -0
- package/src/pi/budgets.ts +4 -1
- package/src/pi/config.test.ts +1 -0
- package/src/pi/config.ts +4 -0
- package/src/pi/directory-sync.test.ts +1 -1
- package/src/pi/edit-tool.ts +55 -36
- package/src/pi/execute.test.ts +185 -645
- package/src/pi/extension-loading.test.ts +34 -0
- package/src/pi/extension-loading.testing.ts +15 -0
- package/src/pi/failure-context.test.ts +4 -3
- package/src/pi/failure-path.test.ts +3 -3
- package/src/pi/file-commit.test.ts +24 -17
- package/src/pi/file-commit.ts +36 -9
- package/src/pi/file-snapshot.test.ts +24 -0
- package/src/pi/forget-tool.ts +268 -0
- package/src/pi/forget.test.ts +343 -0
- package/src/pi/forget.testing.ts +273 -0
- package/src/pi/grep-output.ts +57 -28
- package/src/pi/grep-search.ts +35 -12
- package/src/pi/grep-tool.ts +28 -9
- package/src/pi/grep.test.ts +173 -152
- package/src/pi/mutation-result.test.ts +23 -0
- package/src/pi/mutation-runner.ts +8 -4
- package/src/pi/path.ts +16 -2
- package/src/pi/pi.test.ts +3 -2
- package/src/pi/read-tool.ts +58 -26
- package/src/pi/read.test.ts +361 -0
- package/src/pi/registration.test.ts +115 -2
- package/src/pi/render.test.ts +45 -14
- package/src/pi/replace-tool.ts +18 -27
- package/src/pi/replace.test.ts +8 -107
- package/src/pi/result-safety.test.ts +123 -149
- package/src/pi/rg-match-bytes.ts +95 -0
- package/src/pi/rg-process.test.ts +40 -59
- package/src/pi/rg-text-view.ts +52 -5
- package/src/pi/tool-call.testing.ts +50 -0
- package/src/pi/tool-prompts.ts +15 -0
- package/src/pi/write-tool.ts +17 -26
- package/src/pi/write.test.ts +70 -61
- package/src/pi/e2e-scenarios.test.ts +0 -361
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
Hash-anchored file editing for [Pi](https://github.com/earendil-works/pi-coding-agent). The model references lines it has read and supplies their new content; the tool checks each anchor against the current file before editing.
|
|
6
6
|
|
|
7
|
-
Overrides `read`, `grep`, `edit`, and `write`, and adds `replace` for bulk transformations.
|
|
7
|
+
Overrides `read`, `grep`, `edit`, and `write`, and adds `replace` for bulk transformations. Optional `forget` drops read/grep result content from model context.
|
|
8
8
|
|
|
9
9
|
- **Search → edit:** `read` and `grep` return the same `LINE#HASH` anchors, so search results can feed directly into edits.
|
|
10
10
|
- **Batch and chain edits:** submit structured JSON operations together, then use the returned fresh anchors for the next change.
|
|
@@ -65,16 +65,25 @@ Successful `edit` and `replace` results omit candidate rows whose full content a
|
|
|
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
|
+
| `forget` | When enabled in configuration, drop read or grep result content from model context right after reading it. |
|
|
68
69
|
|
|
69
|
-
|
|
70
|
+
File tools accept relative and absolute paths, `file://` URLs, a leading `@` prefix, and a leading `~` (including `~\` on Windows). As in Pi's built-in file tools, supported Unicode spaces in paths become regular spaces, and Windows shell drive paths using only forward slashes, such as `/c/file`, `/mnt/c/file`, and `/cygdrive/c/file`, resolve to native drive paths. Mixed-separator forms such as `/c/dir\file` do not undergo this drive conversion, matching Pi's built-in tools. Mutation tools share the file-mutation queue and commit layer.
|
|
71
|
+
|
|
72
|
+
Grep returns paths that can be copied back into these tools unchanged. It preserves literal backslashes in POSIX filenames and adds `./` when a relative name would otherwise be interpreted as an input prefix. Names requiring escaping, including supported Unicode spaces or line breaks, use encoded `file://` URLs.
|
|
70
73
|
|
|
71
74
|
Valid UTF-8 text inspection and matching uses one logical representation: CRLF boundaries become LF; standalone CR and source-code escape sequences such as the four characters `\r\n` remain content. `read` and `grep` hash the same logical lines that `edit` verifies; literal and regex `replace` both match this LF view. Mutation offsets map back to the original text. `edit` and `replace` share separator restoration: reuse internal separators positionally, repeat the last for extra gaps, or use the file style (CRLF if present, otherwise LF) when none exist. Boundaries outside the replacement stay unchanged. Invalid UTF-8 grep previews use raw-byte matching as described below.
|
|
72
75
|
|
|
73
76
|
`write` is the full-content boundary: its supplied bytes are authoritative, so it preserves their explicit LF/CRLF choices. Use it for intentional whole-file line-ending conversion. To inspect actual line-ending bytes, use a raw byte reader; anchored line displays intentionally do not distinguish LF from CRLF.
|
|
74
77
|
|
|
78
|
+
### Argument errors
|
|
79
|
+
|
|
80
|
+
All six tools use one argument-validation entry point. Tool-specific checks collect independent issues instead of stopping at the first one; the response also includes Pi's schema diagnostics. For example, an edit batch can report empty bodies, unwritable text, invalid anchor lengths, and invalid `then_run` fields in one rejection. Schema failures are diagnosed per top-level field, so one field cannot consume another field's diagnostic allowance. Received arguments use compact JSON in both model-facing errors and the TUI. Pi still limits schema errors within each field; the response states that more may remain.
|
|
81
|
+
|
|
82
|
+
Argument diagnostics share the 16 KiB block budget in [`budgets.ts`](src/pi/budgets.ts), retain opening and closing text, and label omitted text. Invalid arguments prevent execution. Filesystem access, anchor verification, regex probing by ripgrep, and forget eligibility remain subsequent checks that require valid arguments.
|
|
83
|
+
|
|
75
84
|
### Edit operations
|
|
76
85
|
|
|
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.
|
|
86
|
+
`edit` declares a required `path` and a non-empty structured `edits` array. This extension does not normalize alternate formats: stringified JSON and top-level single-op fields are rejected. Pi's own argument validation may convert a single edit object to a one-element array before the extension sees it. Anchors are `"LINE#HASH"` strings whose hash has exactly `hashLen` characters from uppercase Crockford base32 (digits and A–Z except I, L, O, and U). Line numbers are positive safe integers without leading zeroes. Each `body` element is one logical line without CR or LF. An anchor of a different hash length, such as one copied before a `hashLen` change, is rejected before the file is read, and the error names each such anchor. When several anchors have the wrong hash length, the recovery hint appears only with the first one.
|
|
78
87
|
|
|
79
88
|
| `op` | Required | Optional | Effect |
|
|
80
89
|
| --- | --- | --- | --- |
|
|
@@ -83,10 +92,14 @@ Valid UTF-8 text inspection and matching uses one logical representation: CRLF b
|
|
|
83
92
|
| `insert_before` / `insert_after` | `anchor`, `body` | — | Insert beside the anchor; keep the anchor line. |
|
|
84
93
|
| `prepend` / `append` | `body` | — | Insert at the start/end; no anchors. |
|
|
85
94
|
|
|
86
|
-
An empty `body: []`
|
|
95
|
+
Every `body` holds at least one line; `[""]` is a single blank line. Remove lines with `delete`. An empty `body: []` is rejected for every operation before the file is read, together with other independently detectable argument errors.
|
|
96
|
+
|
|
97
|
+
If an edit leaves a blank line at the end, it writes the terminator needed to preserve that logical line, even when the original file lacked a final newline. For example, appending `[""]` to `"a"` produces `"a\n\n"`; replacing its only line with `[""]` produces `"\n"`. A BOM-only file already represents one blank line and keeps its BOM without an extra terminator. A non-empty final line retains the original final-newline state.
|
|
87
98
|
|
|
88
99
|
All operations in a batch use the same snapshot. Validation failure rejects the whole batch. Unknown fields, conflicting fields, and overlapping operations are rejected; some touching operations also conflict and need separate calls with fresh anchors. For insertion, **do not repeat the anchor line in `body`**. `edit` uses structured operations, not `oldText`/`newText` pairs.
|
|
89
100
|
|
|
101
|
+
The TUI edit header shows the total operation count and counts by type, for example `4 ops: replace ×2, delete ×1, append ×1`. During argument streaming, incomplete or unrecognized operation types count as `unknown`; the counts refresh as arguments change.
|
|
102
|
+
|
|
90
103
|
For multi-operation batches that reach snapshot verification, rejected edits report each supplied anchor's status: `matched` or `mismatched`. Schema-invalid inputs fail before reading the file and have no anchor-status table. Single-operation edits omit the summary table and report the failure directly. Entries identify the zero-based operation index, `anchor` or `end`, and the cited token. The bounded list reports omitted entries explicitly. These statuses do not establish range/overlap validity, semantic intent, publication, command success, or validity on a later retry.
|
|
91
104
|
|
|
92
105
|
When an anchor no longer matches, `edit` looks for where the line went. Recovery only reports; it never edits or retries by itself:
|
|
@@ -160,7 +173,7 @@ To apply several rules against the same original content:
|
|
|
160
173
|
Original `foo bar` becomes `bar baz`; inserted text is not searched again. All rules must succeed before one file commit. `then_run`, when supplied, runs once after the entire batch succeeds.
|
|
161
174
|
|
|
162
175
|
<details>
|
|
163
|
-
<summary><strong>Full read, grep, replace, and
|
|
176
|
+
<summary><strong>Full read, grep, replace, write, and forget parameter reference</strong></summary>
|
|
164
177
|
|
|
165
178
|
### Read
|
|
166
179
|
|
|
@@ -190,7 +203,9 @@ Directory traversal respects ignore rules, does not follow symbolic links, and i
|
|
|
190
203
|
|
|
191
204
|
Searches use bundled ripgrep, independent of system `rg` or `PATH`. The tool disables external ripgrep configuration with `--no-config` and clears `RIPGREP_CONFIG_PATH`, and uses `--no-crlf` and `--encoding=none` so standalone CR and BOM remain content. NUL-containing files are silently skipped in all output modes, including explicitly named files; they do not consume the match limit. Valid UTF-8 files use the shared LF view: files without CRLF are searched at their original paths, and CRLF text is normalized into temporary snapshots using bounded reads and writes. Batches contain up to 64 files or 8 MiB of source data (one large file can exceed that threshold); snapshots are removed after each batch and on failure/cancellation. Match paths refer to original files. Regexes use ripgrep's default Rust-style engine, not PCRE2.
|
|
192
205
|
|
|
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.
|
|
206
|
+
Files with invalid UTF-8 and no NUL remain searchable as raw bytes, without CRLF normalization or encoding conversion. Multiline queries for these files must match their actual separators, such as `\r\n`. Queries containing actual CRLF characters retain them for raw-byte files, while valid UTF-8 files receive the LF-normalized query. Ripgrep's Unicode regex rules still apply; use a byte-mode group such as `(?-u:...)` when the pattern must span malformed bytes. Content-mode output uses replacement characters and plain `LINE│content` rows for the entire file, including context, followed by `Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors`. These previews are not editable anchors. Unmatched invalid UTF-8 files produce no warning.
|
|
207
|
+
|
|
208
|
+
All output modes verify invalid UTF-8 results against the source's pre-search byte revision and the complete raw-byte match spans reported by ripgrep, including the part of a multiline match omitted by `limit`. The tool keeps fixed-size byte digests and verifies them with a bounded scan; different malformed bytes cannot be accepted merely because both display as the same replacement character. Content output retains its complete-file byte revision check for valid UTF-8 as well. A detected mismatch reports `File changed during search`.
|
|
194
209
|
|
|
195
210
|
Search diagnostics are preserved even when a result limit stops ripgrep. Readable, confirmed matches remain available with a `Search incomplete` notice and `details.incomplete: true`; counts then cover only confirmed matches. If no results can be returned, the tool reports an error rather than claiming there are no matches. Search diagnostics have a separate 4 KiB display budget. Ripgrep stderr and batch aggregation each retain up to 64 KiB. All three limits preserve opening context and the final cause where lines fit, and explicitly mark omitted middle text. The shared implementation is [`DiagnosticBuffer`](src/pi/diagnostic-buffer.ts); limits live in [`budgets.ts`](src/pi/budgets.ts) and [`rg-process.ts`](src/pi/rg-process.ts).
|
|
196
211
|
|
|
@@ -212,7 +227,7 @@ Regex batches run in a worker and are terminated on cancellation or when `replac
|
|
|
212
227
|
|
|
213
228
|
### Write
|
|
214
229
|
|
|
215
|
-
Required: `path`, `content`.
|
|
230
|
+
Required: `path`, `content`, `mode`. Choose `"create"` for a missing target or `"overwrite"` for an existing target; omitting `mode` is rejected before file access or command execution. Content is used exactly as supplied, including an empty string; anchor-looking prefixes are not stripped. Unknown fields, including misspelled modes, are rejected before writing.
|
|
216
231
|
|
|
217
232
|
- `mode: "create"`: refuse an existing target.
|
|
218
233
|
- `mode: "overwrite"`: require an existing target.
|
|
@@ -225,6 +240,20 @@ With Action Fusion enabled, `edit`, `replace`, and `write` also accept `then_run
|
|
|
225
240
|
|
|
226
241
|
All three mutation tools treat identical final content as a successful no-op: report `no net change`, leave the existing file untouched, and return `publication: "NOT_PUBLISHED"`. A requested `then_run` still runs after freshness checks. Input, anchor, match, target-type, mode, and cancellation checks still apply; edit/replace reject stale source revisions, while zero matches and an existing target in create mode remain errors. Creating a missing empty file is a publication, not a no-op.
|
|
227
242
|
|
|
243
|
+
### Forget
|
|
244
|
+
|
|
245
|
+
Forget is disabled by default. Set `"forget": true` in `hashlineEdit` and reload Pi to enable it. While disabled, the extension registers neither the `forget` tool nor its context hooks, and read/grep results carry no result tags. Disabling it does not undo context edits already stored in the session.
|
|
246
|
+
|
|
247
|
+
`read` results and content-mode `grep` results of at least 2 KiB of text, and image reads, end with a separate `[result rXXXXX]` block. Smaller results, errors, and `files`/`count` grep output carry no tag. `forget` takes `ids` (a non-empty array of distinct tags) and an optional non-empty `note` for conclusions needed in subsequent work. Omit `note` when none are needed; do not restate the read or forget action.
|
|
248
|
+
|
|
249
|
+
Only results from the step the model has just seen can be forgotten: the tagged results after its previous response. Any other id rejects the whole call and lists the ids that are available. After the response that called `forget` completes, Pi's context edits replace the entire content of each named result with `[Result rXXXXX: content forgotten; rerun the call to see it again.]`. This removes all text and images, including headers, pagination, truncation and search notices, without inspecting their contents. The tool call, the rest of the exchange, and the `forget` call with its `note` stay in context. Save facts you still need in `note` before forgetting. Files, the raw session, and the TUI are unchanged; navigating to a point before the edit restores the original result.
|
|
250
|
+
|
|
251
|
+
The `forget` card in the TUI shows the result count in its header, for example `forget · 2 results`, followed by what was forgotten: `build.log · lines 100–200` (with `· truncated` when the read hit its byte limit), `photo.png · image`, or `grep /pattern/ · 12 matches in 3 files` (with `· limit reached` or `· incomplete`). Expanding the card shows each result id beside its receipt; results without a detailed receipt show their id in either view. An optional `note` appears below the header. read and grep keep receipts in result details, which Pi does not send to the model; the model sees only `Forgot rXXXXX.`.
|
|
252
|
+
|
|
253
|
+
The restriction bounds how much of the next request changes. Messages before the earliest forgotten result stay as they were; from that result on, the request differs, which covers any later results from the same batch (even ones not forgotten), the response that called `forget`, and its tool results. Forgetting an older result would change every later message. This describes request contents only; how a provider bills prompt caching for the changed part is not measured here.
|
|
254
|
+
|
|
255
|
+
After `forget` completes, Pi continues with the next model request as it does for other tools. The selected results have already been replaced with receipts when that request is sent.
|
|
256
|
+
|
|
228
257
|
</details>
|
|
229
258
|
|
|
230
259
|
## Configuration
|
|
@@ -236,6 +265,7 @@ Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json` by defau
|
|
|
236
265
|
"hashlineEdit": {
|
|
237
266
|
"enabled": true,
|
|
238
267
|
"actionFusion": true,
|
|
268
|
+
"forget": false,
|
|
239
269
|
"hashLen": 4,
|
|
240
270
|
"shiftRadius": 15,
|
|
241
271
|
"read": { "defaultLimit": 500, "maxKiB": 256 },
|
|
@@ -245,12 +275,13 @@ Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json` by defau
|
|
|
245
275
|
}
|
|
246
276
|
```
|
|
247
277
|
|
|
248
|
-
Top-level settings
|
|
278
|
+
Top-level settings control shared behavior; each group configures one tool.
|
|
249
279
|
|
|
250
280
|
| Setting | Default | Meaning |
|
|
251
281
|
| --- | --- | --- |
|
|
252
|
-
| `enabled` | `true` | Enable
|
|
282
|
+
| `enabled` | `true` | Enable the extension. Set `false` to register no tools or hooks and restore built-in tools. |
|
|
253
283
|
| `actionFusion` | `true` | Expose `then_run` on mutation tools. Set `false` to disable command support. |
|
|
284
|
+
| `forget` | `false` | Register `forget` and tag eligible read/grep results for context removal. |
|
|
254
285
|
| `hashLen` | `4` | Integer checksum length, 2–8 characters. `edit` accepts only anchors of this length; anchors produced under another setting must be read again. |
|
|
255
286
|
| `shiftRadius` | `15` | Integer first-pass recovery-search radius, 0–100 lines. With no local candidates, recovery searches the rest of the file; `0` disables both searches. |
|
|
256
287
|
| `read.defaultLimit` | `500` | Lines returned when a call omits `limit`; positive safe integer. |
|
|
@@ -291,7 +322,7 @@ mutation completes? -- no, or cancelled first --> mutation error;
|
|
|
291
322
|
file still at the published revision? -- no --> command skipped --+
|
|
292
323
|
| yes |
|
|
293
324
|
v |
|
|
294
|
-
run the
|
|
325
|
+
run the session's callable Bash tool |
|
|
295
326
|
(succeeded / failed / timeout / cancelled) |
|
|
296
327
|
| |
|
|
297
328
|
v |
|
|
@@ -308,18 +339,20 @@ Once the mutation completes, it stays successful whatever happens to the command
|
|
|
308
339
|
|
|
309
340
|
In the TUI, the mutation card owns the mutation's result or error diagnostics, publication status, and freshness warnings. It turns successful when mutation execution and result generation finish. The command card owns command output and execution status; skipped or cancelled commands are neutral and show a short reason when execution never started. Mutation diagnostics never become command output, and command failure leaves a successful mutation card intact. RPC hosts receive the same progress and choose their own rendering.
|
|
310
341
|
|
|
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
|
|
342
|
+
When `then_run.timeout` is supplied, the command card shows the remaining seconds and refreshes once per second even without further command output. The countdown starts with the Bash tool's first execution update, after mutation, queue waiting, and any approval wait. It stops when execution ends; restored unfinished cards show an unknown final status without a countdown. The selected Bash implementation enforces the timeout; an override that emits no progress has no live countdown. Without `timeout`, there is no countdown or implicit time limit. RPC progress includes `timing.timeoutSeconds` and `timing.remainingSeconds` after a timed command starts.
|
|
343
|
+
|
|
344
|
+
Command failures return the Bash tool's diagnostic text to the LLM, including exit or timeout details and whether file changes were saved. The final session result determines success, including nonzero exits and errors supplied by result hooks. Collapsing a TUI card does not shorten the model's result.
|
|
312
345
|
|
|
313
|
-
|
|
346
|
+
The Fusion queue holds a file from mutation until its command finishes, so another fused call on the same file cannot change it in between. Commands use the session's nested tool dispatcher (`ctx.executeTool("bash", ...)`), including its argument validation, Bash overrides, `tool_call` approval hooks, and `tool_result` hooks. Bash must be callable in that session. If it is unavailable or a hook blocks the command, Fusion reports command failure and retains the completed mutation.
|
|
314
347
|
|
|
315
|
-
|
|
348
|
+
A nested Bash result's `terminate` hint is passed to the parent mutation result so Pi can apply its normal rule for stopping after the tool batch.
|
|
316
349
|
|
|
317
350
|
## Safety and design
|
|
318
351
|
|
|
319
352
|
- **Anchors are checksums, not identities.** Each hash combines the 1-based line number and content. Short hashes can collide and do not prove the model observed a line.
|
|
320
353
|
- **Validation is local to supplied anchors.** Unrelated in-place changes leave stable anchors usable. A range verifies its supplied start/end anchors, not every interior line.
|
|
321
354
|
- **Line shifts change anchors.** Insertions/deletions can invalidate later references. Recovery searches within `shiftRadius`, then the rest of the file if no local candidates match. Unique candidates include bounded line content; ambiguous candidates include neighborhoods for comparison. Use `read` when no candidate is found or needed content is omitted. Retries verify again, without fuzzy matching or automatic relocation.
|
|
322
|
-
- **Edits preserve text representation.** `edit` preserves existing line endings, untouched separators, and
|
|
355
|
+
- **Edits preserve text representation.** `edit` preserves existing line endings, untouched separators, and final-newline state, adding a terminator when needed to represent a final blank line. `edit`/`replace` reject invalid UTF-8 source text; all mutations reject NUL and output that cannot be encoded losslessly as UTF-8. Supplied text (`write` content, `edit` body lines, `replace` replacement text) is checked before the file is read, naming the offending field; the final content is checked again before publication, because a transformation such as a regex without `u` can split a surrogate pair. UTF-16 and legacy code pages are not decoded or preserved; a BOM-free file whose bytes happen to be valid UTF-8 may still be misinterpreted.
|
|
323
356
|
- **Fresh anchors depend on the final observation.** After `then_run`, anchors are shown only for `unchanged` freshness. Without a command, observed and published revisions must agree. Otherwise every mutation result, including `write`, ends with one notice to re-read before further edits, prefixed with `[then_run:stale]` when a command was requested. Later edits still verify anchors.
|
|
324
357
|
- **Local queues are not cross-process transactions.** Revision checks bind mutations to the bytes read, but an external writer can still race a check and publication. There is no strict workspace jail or multi-file transaction.
|
|
325
358
|
|
|
@@ -342,7 +375,9 @@ These limits bound model context, not file size. Omission notices direct the cal
|
|
|
342
375
|
| --- | --- |
|
|
343
376
|
| `read` | Default 500 rows (`read.defaultLimit`), overridable with `limit`; 256 KiB of anchored text (`read.maxKiB`). No partial anchor rows. An oversized single row directs the caller to inspect chunks with `bash` or make a known text change with `replace`; reducing `limit` cannot split a physical line. |
|
|
344
377
|
| `grep` | Default 100 matching lines (`grep.defaultLimit`), overridable; up to 500 UTF-16 units per partial line preview, plus labels and Pi's total output limits. Match previews use rg byte offsets; hashes use full content. Search error notices have a separate 4 KiB budget. |
|
|
378
|
+
| `forget` tag | With `forget` enabled: `read` and content-mode `grep` text results of 2 KiB or more, and image reads; smaller results are not tagged. |
|
|
345
379
|
| `edit` / `replace` anchors | 16 KiB including heading/omission notice, with no fixed entry-count limit. Compact tokens for changed positions; selected deletion successors retain complete content. The omission notice consumes budget only when rows are omitted. Rows that do not fit are omitted in full; later rows that fit are still returned. |
|
|
380
|
+
| Argument errors | 16 KiB for the combined tool-specific and Pi schema diagnostics; longer reports retain opening/closing text and label the omitted middle. Pi's schema error limit applies separately within each top-level field. |
|
|
346
381
|
| Anchor failure details | 16 KiB, with no fixed failure-count limit; unique candidates include complete rows up to 4 KiB, and ambiguous failures list up to eight candidates each. Unresolved anchors show the current cited row when it fits; oversized or out-of-range rows require a fresh `read` or `grep`. |
|
|
347
382
|
| Input-anchor checks | Independent 16 KiB block, with no fixed entry-count limit. Truncation is reported explicitly; omitted entries are not implied matched. |
|
|
348
383
|
| Ambiguous-candidate neighborhoods | 16 KiB of complete anchored row text, lowest-line first, plus headings; no fixed row-count limit. Uses the same first eight candidates per failure as the detail lists. Each listed candidate row is limited to 4 KiB. Rows exceeding either limit are omitted in full; later rows that fit are still returned, with gaps reflected in the neighborhood headings. |
|
|
@@ -385,6 +420,7 @@ PUBLISHED, even if a step after publication fails
|
|
|
385
420
|
| Create | Same-filesystem `link(temp, target)` refuses a target created by another writer during publication. |
|
|
386
421
|
| Overwrite | `rename(temp, target)` publishes the replacement; never delete the old target first. |
|
|
387
422
|
| Symlinks | Resolve the regular-file target for overwrite and preserve the link; reject dangling/unresolvable links. |
|
|
423
|
+
| Non-regular files | Check the opened file handle before reading mutation snapshots or revisions. POSIX FIFO targets, including symlink aliases, are rejected without waiting for a writer. |
|
|
388
424
|
| Multiple hard links | Reject existing regular files with multiple links to avoid splitting the link set. |
|
|
389
425
|
| Permissions | Copy existing mode bits; new files use `0600`. No separate public permission setting. |
|
|
390
426
|
| Post-publication failure | Directory-sync, result-generation, revision observation, or cleanup errors retain `PUBLISHED`; unconfirmed publication is `UNKNOWN`. Read before retrying uncertain mutations. |
|
|
@@ -412,6 +448,6 @@ Streaming mutation summaries omit anchors. Result-generation failures preserve p
|
|
|
412
448
|
- `npm run typecheck` checks source, test, and benchmark types in `src/` and `bench/`.
|
|
413
449
|
- `npm run format:check` checks formatting in both directories.
|
|
414
450
|
- `npm test` runs core and tool tests.
|
|
415
|
-
- `npm run test:integration` exercises bundled ripgrep
|
|
451
|
+
- `npm run test:integration` exercises bundled ripgrep, files over 100 MiB with LF and CRLF text, platform file types, and Action Fusion through real Pi sessions with command failures, cancellation, overrides, and approval/result hooks.
|
|
416
452
|
- `npm run bench` measures core throughput and long-line match mapping.
|
|
417
453
|
- `node --expose-gc bench/grep-memory.bench.ts` measures grep latency and sampled peak heap/RSS for 24 files totaling 192 MiB, each with one matching line. It creates and removes its fixtures in the system temporary directory.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@criogaid/pi-hashline-edit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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",
|
|
@@ -31,14 +31,14 @@
|
|
|
31
31
|
"jiti": "2.7.0"
|
|
32
32
|
},
|
|
33
33
|
"peerDependencies": {
|
|
34
|
-
"@earendil-works/pi-coding-agent": "
|
|
34
|
+
"@earendil-works/pi-coding-agent": ">=0.99.1"
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|
|
37
37
|
"@biomejs/biome": "2.5.14",
|
|
38
|
-
"@earendil-works/pi-agent-core": "
|
|
39
|
-
"@earendil-works/pi-ai": "
|
|
40
|
-
"@earendil-works/pi-coding-agent": "
|
|
41
|
-
"@earendil-works/pi-tui": "
|
|
38
|
+
"@earendil-works/pi-agent-core": "0.99.1",
|
|
39
|
+
"@earendil-works/pi-ai": "0.99.1",
|
|
40
|
+
"@earendil-works/pi-coding-agent": "0.99.1",
|
|
41
|
+
"@earendil-works/pi-tui": "0.99.1",
|
|
42
42
|
"typebox": "^1.1.38",
|
|
43
43
|
"typescript": "^7.0.2"
|
|
44
44
|
},
|
package/src/core/apply.test.ts
CHANGED
|
@@ -305,6 +305,72 @@ test("appending to a file without a final newline keeps it absent", () => {
|
|
|
305
305
|
if (r.ok) assert.equal(r.text, "a\nb");
|
|
306
306
|
});
|
|
307
307
|
|
|
308
|
+
test("edits retain empty final logical lines even without an original final newline", () => {
|
|
309
|
+
for (const text of ["old", "head\nold", "head\r\nold"]) {
|
|
310
|
+
const line = splitLines(text).length;
|
|
311
|
+
const ending = text.includes("\r\n") ? "\r\n" : "\n";
|
|
312
|
+
const prefix = text.slice(0, text.lastIndexOf("\n") + 1);
|
|
313
|
+
const cases: [Edit, string, number[]][] = [
|
|
314
|
+
[{ op: "replace", start: at(text, line), body: [""] }, prefix + ending, [line - 1]],
|
|
315
|
+
[
|
|
316
|
+
{ op: "replace", start: at(text, line), body: ["new", ""] },
|
|
317
|
+
`${prefix}new${ending}${ending}`,
|
|
318
|
+
[line - 1, line],
|
|
319
|
+
],
|
|
320
|
+
[{ op: "append", body: [""] }, text + ending + ending, [line]],
|
|
321
|
+
[{ op: "insert_after", anchor: at(text, line), body: [""] }, text + ending + ending, [line]],
|
|
322
|
+
];
|
|
323
|
+
for (const [edit, expected, touched] of cases) {
|
|
324
|
+
const result = applyEdits(text, [edit], 4, 15);
|
|
325
|
+
assert.ok(result.ok);
|
|
326
|
+
assert.equal(result.text, expected, `${edit.op}: ${JSON.stringify(text)}`);
|
|
327
|
+
assert.deepEqual(result.touchedLines, touched);
|
|
328
|
+
const newLines = splitLines(result.text);
|
|
329
|
+
assert.ok(result.touchedLines.every((index) => index < newLines.length));
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
// Deleting an unterminated suffix must also retain an existing blank predecessor.
|
|
333
|
+
for (const text of ["\nlast", "head\r\n\r\nlast"]) {
|
|
334
|
+
const result = applyEdits(
|
|
335
|
+
text,
|
|
336
|
+
[{ op: "delete", start: at(text, splitLines(text).length) }],
|
|
337
|
+
4,
|
|
338
|
+
15,
|
|
339
|
+
);
|
|
340
|
+
assert.ok(result.ok);
|
|
341
|
+
assert.equal(result.text, text.slice(0, -"last".length));
|
|
342
|
+
assert.deepEqual(result.touchedLines, []);
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
test("a BOM represents an empty first line without a terminator, but not an empty later line", () => {
|
|
347
|
+
const cases: [string, Edit[], string, number[]][] = [
|
|
348
|
+
["\uFEFFold", [{ op: "replace", start: at("\uFEFFold", 1), body: [""] }], "\uFEFF", [0]],
|
|
349
|
+
["\uFEFF", [{ op: "replace", start: at("\uFEFF", 1), body: [""] }], "\uFEFF", []],
|
|
350
|
+
["\uFEFF", [{ op: "append", body: [""] }], "\uFEFF\n\n", [1]],
|
|
351
|
+
["\uFEFF", [{ op: "prepend", body: ["new"] }], "\uFEFFnew\n\n", [0]],
|
|
352
|
+
["\uFEFF\nlast", [{ op: "delete", start: at("\uFEFF\nlast", 2) }], "\uFEFF", []],
|
|
353
|
+
];
|
|
354
|
+
for (const [text, edits, expected, touched] of cases) {
|
|
355
|
+
const result = applyEdits(text, edits, 4, 15);
|
|
356
|
+
assert.ok(result.ok);
|
|
357
|
+
assert.equal(result.text, expected, JSON.stringify({ text, edits }));
|
|
358
|
+
assert.deepEqual(result.touchedLines, touched);
|
|
359
|
+
}
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
test("large replacement bodies retain snapshot boundaries without a function argument limit", () => {
|
|
363
|
+
const text = "head\r\nold\ntail";
|
|
364
|
+
const body = Array<string>(150_000).fill("x");
|
|
365
|
+
const result = applyEdits(text, [{ op: "replace", start: at(text, 2), body }], 4, 15);
|
|
366
|
+
assert.ok(result.ok);
|
|
367
|
+
assert.equal(result.text, `head\r\n${"x\r\n".repeat(body.length - 1)}x\ntail`);
|
|
368
|
+
assert.equal(result.touchedLines.length, body.length);
|
|
369
|
+
assert.equal(result.touchedLines[0], 1);
|
|
370
|
+
assert.equal(result.touchedLines.at(-1), body.length);
|
|
371
|
+
assert.deepEqual(result.contextLines, []);
|
|
372
|
+
});
|
|
373
|
+
|
|
308
374
|
test("noop is still detected when the file lacks a final newline", () => {
|
|
309
375
|
const text = "a\nb";
|
|
310
376
|
const r = applyEdits(text, [{ op: "replace", start: at(text, 1), body: ["a"] }], 4, 15);
|
|
@@ -571,19 +637,3 @@ test("matched anchor checks do not imply valid ranges", () => {
|
|
|
571
637
|
assert.ok(result.failure.checks.every((check) => check.status === "matched"));
|
|
572
638
|
}
|
|
573
639
|
});
|
|
574
|
-
|
|
575
|
-
test("zero-length replacement without line deletion does not produce false deletion successors", () => {
|
|
576
|
-
const text = "a\nb\nc\n";
|
|
577
|
-
// A batch with a real change and an empty body insertion
|
|
578
|
-
const edits: Edit[] = [
|
|
579
|
-
{ op: "replace", start: at(text, 1), body: ["A"] },
|
|
580
|
-
{ op: "insert_after", anchor: at(text, 2), body: [] },
|
|
581
|
-
];
|
|
582
|
-
const result = applyEdits(text, edits, 4, 15);
|
|
583
|
-
assert.ok(result.ok);
|
|
584
|
-
if (result.ok) {
|
|
585
|
-
assert.equal(result.changed, true);
|
|
586
|
-
assert.deepEqual(result.touchedLines, [0]);
|
|
587
|
-
assert.deepEqual(result.contextLines, []);
|
|
588
|
-
}
|
|
589
|
-
});
|
package/src/core/apply.ts
CHANGED
|
@@ -268,27 +268,44 @@ export function applyEdits(
|
|
|
268
268
|
const separator = ending === "crlf" ? "\r\n" : "\n";
|
|
269
269
|
// LF-only files have uniform separators; skip the regex scan.
|
|
270
270
|
const separators = ending === "lf" ? undefined : lineSeparators(text);
|
|
271
|
-
//
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
271
|
+
// Build from the verified snapshot in one pass: large bodies must not become
|
|
272
|
+
// function arguments, and later operations keep their original coordinates.
|
|
273
|
+
const result: { content: string; separator: string }[] = [];
|
|
274
|
+
let cursor = 0;
|
|
275
|
+
const appendOriginal = (end: number) => {
|
|
276
|
+
while (cursor < end) {
|
|
277
|
+
const content = lines[cursor];
|
|
278
|
+
// Anchors were checked before separating the BOM from movable line content.
|
|
279
|
+
result.push({
|
|
280
|
+
content: bom && cursor === 0 ? content.slice(1) : content,
|
|
281
|
+
separator: separators?.[cursor] ?? "",
|
|
282
|
+
});
|
|
283
|
+
cursor++;
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
for (const op of sorted) {
|
|
287
|
+
appendOriginal(op.lo);
|
|
278
288
|
// The trailing gap is outside the logical replacement, just as in substring replacement.
|
|
279
|
-
const removedSeparators =
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
289
|
+
const removedSeparators = separators?.slice(op.lo, Math.max(op.lo, op.hi - 1)) ?? [];
|
|
290
|
+
for (let i = 0; i < op.newLines.length; i++) {
|
|
291
|
+
const content = op.newLines[i];
|
|
292
|
+
result.push({
|
|
293
|
+
// A copied first-line BOM denotes the existing file header, not a second BOM.
|
|
294
|
+
content:
|
|
295
|
+
bom && op.lo === 0 && i === 0 && content.startsWith(bom) ? content.slice(1) : content,
|
|
296
|
+
separator:
|
|
297
|
+
i === op.newLines.length - 1 && op.hi > op.lo
|
|
298
|
+
? (separators?.[op.hi - 1] ?? "")
|
|
299
|
+
: replacementSeparator(removedSeparators, i, separator),
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
cursor = op.hi;
|
|
290
303
|
}
|
|
291
|
-
|
|
304
|
+
appendOriginal(lines.length);
|
|
305
|
+
// An empty final logical line needs its own terminator to survive splitLines.
|
|
306
|
+
// A sole BOM-backed line already has a representation without a terminator.
|
|
307
|
+
const finalNewline =
|
|
308
|
+
hasFinalNewline(text) || (result.at(-1)?.content === "" && (result.length > 1 || !bom));
|
|
292
309
|
const newText =
|
|
293
310
|
bom +
|
|
294
311
|
result
|
package/src/core/lines.ts
CHANGED
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
*
|
|
10
10
|
* Final newline: splitLines discards whether the input ended with a terminator
|
|
11
11
|
* (a trailing newline terminates the last line, it does not create one).
|
|
12
|
-
* hasFinalNewline recovers that state
|
|
13
|
-
*
|
|
14
|
-
*
|
|
12
|
+
* hasFinalNewline recovers that state when editing reassembles per-line
|
|
13
|
+
* separators. A non-empty final line retains that state; a final blank line
|
|
14
|
+
* needs a terminator to remain representable, except for a BOM-only line.
|
|
15
15
|
*
|
|
16
16
|
* @module pi-hashline-edit/core
|
|
17
17
|
*/
|
package/src/index.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { loadConfig } from "./pi/config.ts";
|
|
|
18
18
|
import { makeEditOverride } from "./pi/edit-tool.ts";
|
|
19
19
|
import { makeReadOverride } from "./pi/read-tool.ts";
|
|
20
20
|
import { makeGrepOverride } from "./pi/grep-tool.ts";
|
|
21
|
+
import { registerForgetTool } from "./pi/forget-tool.ts";
|
|
21
22
|
import { makeReplaceTool } from "./pi/replace-tool.ts";
|
|
22
23
|
import { makeWriteOverride } from "./pi/write-tool.ts";
|
|
23
24
|
import { createActionFusionExecutor } from "./pi/action-fusion.ts";
|
|
@@ -45,5 +46,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
45
46
|
|
|
46
47
|
pi.registerTool(makeReadOverride(cwd, config));
|
|
47
48
|
pi.registerTool(makeGrepOverride(cwd, config));
|
|
49
|
+
if (config.forget) registerForgetTool(pi);
|
|
48
50
|
}
|
|
49
51
|
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/** Real ripgrep results consumed and forgotten through Pi's session lifecycle. */
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { writeFile } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { test } from "node:test";
|
|
6
|
+
import { FORGET_MIN_BYTES } from "../pi/budgets.ts";
|
|
7
|
+
import {
|
|
8
|
+
assertForgotten,
|
|
9
|
+
finish,
|
|
10
|
+
forgetCall,
|
|
11
|
+
openForgetSession,
|
|
12
|
+
SESSION_TIMEOUT_MS,
|
|
13
|
+
taggedResultId,
|
|
14
|
+
toolResponse,
|
|
15
|
+
toolResult,
|
|
16
|
+
} from "../pi/forget.testing.ts";
|
|
17
|
+
|
|
18
|
+
for (const encoding of ["UTF-8", "invalid UTF-8"] as const) {
|
|
19
|
+
test(`real grep of ${encoding} logs then forget → matched content is absent from the next request`, {
|
|
20
|
+
timeout: SESSION_TIMEOUT_MS,
|
|
21
|
+
}, async (t) => {
|
|
22
|
+
const f = await openForgetSession(t);
|
|
23
|
+
const path = join(f.cwd, "search.log");
|
|
24
|
+
const rowPayloadChars = 128;
|
|
25
|
+
const rowCount = Math.ceil(FORGET_MIN_BYTES / rowPayloadChars);
|
|
26
|
+
const rows = Array.from(
|
|
27
|
+
{ length: rowCount },
|
|
28
|
+
(_, index) => `needle ${index} ${"x".repeat(rowPayloadChars)}`,
|
|
29
|
+
);
|
|
30
|
+
const bytes = Buffer.concat([
|
|
31
|
+
Buffer.from(rows.join("\n")),
|
|
32
|
+
encoding === "invalid UTF-8" ? Buffer.from([0xff]) : Buffer.alloc(0),
|
|
33
|
+
Buffer.from("\n"),
|
|
34
|
+
]);
|
|
35
|
+
await writeFile(path, bytes);
|
|
36
|
+
await f.prompt(
|
|
37
|
+
toolResponse({
|
|
38
|
+
type: "toolCall",
|
|
39
|
+
id: "search",
|
|
40
|
+
name: "grep",
|
|
41
|
+
arguments: { path, pattern: "needle", literal: true },
|
|
42
|
+
}),
|
|
43
|
+
(messages) => toolResponse(forgetCall(messages, "search")),
|
|
44
|
+
finish,
|
|
45
|
+
);
|
|
46
|
+
const original = toolResult(f.requests[1], "search");
|
|
47
|
+
assert.equal(original.isError, false);
|
|
48
|
+
const text = original.content
|
|
49
|
+
.filter((block) => block.type === "text")
|
|
50
|
+
.map((block) => block.text)
|
|
51
|
+
.join("\n");
|
|
52
|
+
assert.ok(text.includes(rows[0]));
|
|
53
|
+
if (encoding === "invalid UTF-8") assert.ok(text.includes("\uFFFD"));
|
|
54
|
+
const id = taggedResultId(original);
|
|
55
|
+
assert.ok(id);
|
|
56
|
+
const forgotten = toolResult(f.requests[2], "search");
|
|
57
|
+
assertForgotten(forgotten, id);
|
|
58
|
+
const receipt = forgotten.content[0];
|
|
59
|
+
assert.ok(receipt.type === "text" && !receipt.text.includes("needle"));
|
|
60
|
+
assert.ok(receipt.type === "text" && !receipt.text.includes("search.log"));
|
|
61
|
+
const displayReceipt = `grep /needle/ · ${rows.length} matches in 1 file`;
|
|
62
|
+
assert.deepEqual(f.rawResult("forget-call").details, {
|
|
63
|
+
forgotten: [{ id, receipt: displayReceipt }],
|
|
64
|
+
});
|
|
65
|
+
assert.ok(f.renderForgetCard().includes(displayReceipt));
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
test("real grep reaches its limit across files → forget card reports the returned counts", {
|
|
70
|
+
timeout: SESSION_TIMEOUT_MS,
|
|
71
|
+
}, async (t) => {
|
|
72
|
+
const f = await openForgetSession(t);
|
|
73
|
+
const rowPayloadChars = 256;
|
|
74
|
+
const rowsPerFile = Math.ceil(FORGET_MIN_BYTES / rowPayloadChars) + 1;
|
|
75
|
+
const limit = rowsPerFile + 1;
|
|
76
|
+
const paths = [join(f.cwd, "one.log"), join(f.cwd, "two.log")];
|
|
77
|
+
const rows = Array.from(
|
|
78
|
+
{ length: rowsPerFile },
|
|
79
|
+
(_, index) => `${index % 2 === 0 ? "needle" : "backup"} ${"x".repeat(rowPayloadChars)}`,
|
|
80
|
+
);
|
|
81
|
+
await Promise.all(paths.map((path) => writeFile(path, `${rows.join("\n")}\n`)));
|
|
82
|
+
await f.prompt(
|
|
83
|
+
toolResponse({
|
|
84
|
+
type: "toolCall",
|
|
85
|
+
id: "search",
|
|
86
|
+
name: "grep",
|
|
87
|
+
arguments: { path: paths, pattern: ["needle", "backup"], literal: true, limit },
|
|
88
|
+
}),
|
|
89
|
+
(messages) => toolResponse(forgetCall(messages, "search")),
|
|
90
|
+
finish,
|
|
91
|
+
);
|
|
92
|
+
const id = taggedResultId(toolResult(f.requests[1], "search"));
|
|
93
|
+
assert.ok(id);
|
|
94
|
+
const receipt = `grep /needle | backup/ · ${limit} matches in ${paths.length} files · limit reached`;
|
|
95
|
+
assert.deepEqual(f.rawResult("forget-call").details, { forgotten: [{ id, receipt }] });
|
|
96
|
+
assert.ok(f.renderForgetCard().includes(receipt));
|
|
97
|
+
assertForgotten(toolResult(f.requests[2], "search"), id);
|
|
98
|
+
});
|