@criogaid/pi-hashline-edit 0.1.1 → 0.1.3
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 +168 -197
- package/package.json +1 -1
- package/src/core/apply.test.ts +40 -1
- package/src/core/apply.ts +13 -3
- package/src/core/hash.test.ts +7 -3
- package/src/core/hash.ts +6 -10
- package/src/core/index.ts +1 -0
- package/src/core/text.test.ts +15 -0
- package/src/core/text.ts +18 -0
- package/src/core/types.ts +1 -2
- package/src/index.ts +4 -3
- package/src/integration/grep-rg.test.ts +20 -0
- package/src/pi/action-fusion.test.ts +8 -6
- package/src/pi/action-fusion.ts +39 -18
- package/src/pi/config.test.ts +28 -8
- package/src/pi/config.ts +9 -7
- package/src/pi/edit-tool.ts +44 -70
- package/src/pi/execute.test.ts +50 -1
- package/src/pi/failure-path.test.ts +10 -7
- package/src/pi/file-commit.test.ts +29 -1
- package/src/pi/file-commit.ts +39 -7
- package/src/pi/fusion-card.test.ts +1 -1
- package/src/pi/grep-tool.ts +20 -34
- package/src/pi/grep.test.ts +24 -6
- package/src/pi/mutation-result.ts +46 -0
- package/src/pi/read-tool.ts +4 -4
- package/src/pi/registration.test.ts +69 -9
- package/src/pi/render.ts +51 -1
- package/src/pi/replace-tool.ts +34 -44
- package/src/pi/result-safety.test.ts +169 -0
- package/src/pi/state.ts +2 -3
- package/src/pi/write-tool.ts +12 -2
- package/src/pi/write.test.ts +7 -1
package/README.md
CHANGED
|
@@ -2,278 +2,249 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://github.com/Criogaid/pi-hashline-edit/actions/workflows/ci.yml) [](https://www.npmjs.com/package/@criogaid/pi-hashline-edit) [](https://www.npmjs.com/package/@criogaid/pi-hashline-edit) [](https://www.npmjs.com/package/@criogaid/pi-hashline-edit)
|
|
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
|
-
|
|
7
|
+
Overrides `read`, `grep`, `edit`, and `write`, and adds `replace` for bulk transformations.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
- **Search → edit:** `read` and `grep` return the same `LINE#HASH` anchors, so search results can feed directly into edits.
|
|
10
|
+
- **Batch and chain edits:** submit structured JSON operations together, then use the returned fresh anchors for the next change.
|
|
11
|
+
- **Recover from stale anchors:** rejected edits offer checksum-matching candidates or nearby current-file context for a verified retry. Recovery never applies automatically.
|
|
12
|
+
- **Edit → test:** Action Fusion lets a mutation include an optional follow-up command, with separate file and command outcomes and separate TUI cards.
|
|
10
13
|
|
|
11
|
-
|
|
14
|
+
[Quick start](#quick-start) · [Tools](#tools) · [Configuration](#configuration) · [Action Fusion](#action-fusion) · [Safety and design](#safety-and-design)
|
|
12
15
|
|
|
13
|
-
|
|
16
|
+
## Install
|
|
14
17
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
- **Chain edits without re-reading** — a successful `edit` returns fresh anchors for the lines it produced, so the next edit cites them directly instead of forcing a full re-read.
|
|
19
|
-
- **Grep-to-edit, no detour** — search results carry the same `LINE#HASH` anchors (grouped by file, context lines included); grab one and edit directly, skipping the read you'd otherwise need.
|
|
20
|
-
- **Surgical drift detection** — each cited anchor is rechecked against the current line only; an unrelated change elsewhere never blocks your edit.
|
|
21
|
-
- **Self-healing stale anchors** — a drifted anchor (content shifted by an edit above it) doesn't force a full re-read: the applicator rescans ±lines for the original content and hands back a fresh `LINE#HASH` to retry with. If the original content cannot be recovered, the error includes bounded current-file anchors near the failed locations so the model can re-evaluate and submit a newly verified edit.
|
|
22
|
-
|
|
23
|
-
## When to use it
|
|
24
|
-
|
|
25
|
-
Routine local code editing in pi — the common case. If you spend turns fighting "old_string not found" or fixing indentation the model dropped, this is the fix.
|
|
26
|
-
|
|
27
|
-
## When to turn it off
|
|
28
|
-
|
|
29
|
-
Set `hashlineEdit.enabled = false` (or uninstall) to fall back to the built-in `read`/`edit`/`grep`/`write` when you need **remote or custom-storage files** — the overrides read/write/search the local filesystem directly, so pi's custom `ReadOperations`/`GrepOperations` (SSH, etc.) aren't supported. The same switch lets you opt out per-project. All five tools — `read`, `grep`, `edit`, `replace`, `write` — are one set governed by this switch: when disabled the extension registers none of them and pi behaves as if it were not installed (reload pi after changing the setting).
|
|
30
|
-
|
|
31
|
-
## Model Compatibility
|
|
32
|
-
|
|
33
|
-
Hashline replaces the edit protocol the main model was trained on, so real-world reliability depends on the model more than on anything else. Field observations from real sessions, one family per subsection (June 2026, single environment — directional, not benchmarks; vendors iterate fast, re-test on new releases).
|
|
34
|
-
|
|
35
|
-
### DeepSeek family
|
|
36
|
-
|
|
37
|
-
**Avoid — silent corruption.** Weak tool-call construction (tested: DeepSeek V4 Flash): ~50% of edits fail on the built-in string-replace, and each fix takes several more rounds — string-replace failures are *divergent*, the model retries from the same wrong memory, but at least they are loud. Hashline's rejected anchors *converge* — a mismatched anchor returns the live content plus a ready-to-resend `LINE#HASH`, so one retry closes the loop — but the raw failure rate is high (~80%), and hashline adds a failure class the built-in edit doesn't have.
|
|
38
|
-
|
|
39
|
-
`insert_after` semantics invite wrong parameters even when the tool call itself is well-formed: the model fills `body` string-replace-style, copying the anchor line into it (observed on DeepSeek V4 Flash). The toolcall verifies and succeeds, and the line ends up duplicated. Nothing at the tool layer can catch this — the anchor is valid, the model's *intent* was wrong, and no prompt wording cures it (the schema description already forbids the copy). For a weak model, hashline effectively trades loud failures for silent ones: files come out corrupted edit by edit. Keep the plugin off for this profile; if you must run it, review the diff after every edit.
|
|
40
|
-
|
|
41
|
-
### Kimi family
|
|
42
|
-
|
|
43
|
-
**Turn the plugin off.** Strong, but not trained on hashline (tested: Kimi K3): built-in string-replace is excellent while hashline draws frequent anchor mistakes. Hashline assumes anchor discipline — copy hashes verbatim from read output, never invent one; a model that hasn't internalized that fabricates anchors no matter how capable. When a strong model keeps hitting anchor errors, the fastest fix is disabling the plugin, not more retries.
|
|
44
|
-
|
|
45
|
-
### GLM family
|
|
46
|
-
|
|
47
|
-
**The intended pairing.** Strong and follows the schema as given (tested: GLM 5.2): the occasional not-found / whitespace friction of built-in string-replace disappears — 100% in testing. Capable models never needed the wording in the first place: GLM used `insert_after` correctly even when the tool description didn't explain the op at all. The mismatch lives in the model, not the tool.
|
|
48
|
-
|
|
49
|
-
### GPT family
|
|
18
|
+
```bash
|
|
19
|
+
pi install npm:@criogaid/pi-hashline-edit
|
|
20
|
+
```
|
|
50
21
|
|
|
51
|
-
|
|
22
|
+
This extension works on **local files**. For remote/custom-storage operations, disable it in [configuration](#configuration) and reload Pi to use the built-in tools.
|
|
52
23
|
|
|
53
|
-
##
|
|
24
|
+
## Quick start
|
|
54
25
|
|
|
55
|
-
Once
|
|
26
|
+
Once installed, Pi's model uses these tool calls automatically. The examples below show the read → edit protocol.
|
|
56
27
|
|
|
57
|
-
|
|
58
|
-
- **Conservative overlap.** Two ops whose ranges touch (e.g. `insert_after` immediately followed by `replace` at the same line) are rejected to avoid backfill ambiguity — issue them as two separate `edit` calls.
|
|
28
|
+
A `read` of `greet.ts` returns:
|
|
59
29
|
|
|
60
|
-
|
|
30
|
+
```text
|
|
31
|
+
greet.ts · 3 lines
|
|
32
|
+
1#ZR63│export function greet() {
|
|
33
|
+
2#GFYR│ return "hello";
|
|
34
|
+
3#FNSZ│}
|
|
35
|
+
```
|
|
61
36
|
|
|
62
|
-
|
|
37
|
+
To change the return value, copy the second line's anchor into `edit` and supply only the new content:
|
|
63
38
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
39
|
+
```json
|
|
40
|
+
{
|
|
41
|
+
"path": "greet.ts",
|
|
42
|
+
"edits": [
|
|
43
|
+
{ "op": "replace", "anchor": "2#GFYR", "body": [" return \"hello, hashline\";"] }
|
|
44
|
+
]
|
|
45
|
+
}
|
|
46
|
+
```
|
|
69
47
|
|
|
70
|
-
|
|
48
|
+
The result includes a diff and the updated anchor:
|
|
71
49
|
|
|
72
|
-
|
|
50
|
+
```text
|
|
51
|
+
Updated anchors (use these for the next edit):
|
|
52
|
+
2#V8AT│ return "hello, hashline";
|
|
53
|
+
```
|
|
73
54
|
|
|
74
|
-
|
|
75
|
-
- **Line folded into the hash**: each line's hash mixes its 1-based line number into its content, so every line is unique by construction — no in-file collisions, no length extension. The hash changes when either the content or line number changes; editing a neighbor in place does not affect it.
|
|
76
|
-
- **Live, surgical verification**: at apply time each cited anchor's hash is recomputed from the current line content and compared — no stored snapshot, no whole-file stale check. A line that changed (or was misremembered) fails its own anchor; an unrelated in-place change elsewhere does not. Insertions or deletions above the target trigger shifted-anchor recovery instead of silently retargeting the edit. No fuzzy matching, no boundary repair.
|
|
77
|
-
- **Shifted-anchor recovery**: a mismatched anchor isn't a dead end. The applicator rescans ±`shiftRadius` lines for the original content — holding the original line number fixed and re-hashing each candidate (`hash(line, candidate) === cited` iff the candidate *is* the original) — and returns a ready-to-resend anchor on a unique hit or the candidate list when ambiguous. When the content cannot be recovered, the failure includes a bounded `LINE#HASH│content` window from the validation snapshot; the model must re-evaluate the intended change, and every retry is verified again.
|
|
78
|
-
- **Atomic batches, all failures collected**: every op in one `edit` is verified against the same snapshot; if any anchor fails, *all* failures (each with its recovery) are returned together and nothing is written — partial writes would shift lines and invalidate the very recovery info just returned.
|
|
79
|
-
- **Chain edits without re-reading**: a successful `edit` returns `Updated anchors` for the lines it produced (and the line that shifted into a deletion gap), so the next edit can cite them directly.
|
|
80
|
-
- **Byte-faithful writes**: `edit` rewrites only the lines you name. CRLF files keep CRLF, and a file whose last line has no terminator does not gain one — the state `splitLines` discards is captured before the edit and restored after it. `read` states the fact in its header (`· no trailing newline`), since the numbered rows cannot show it.
|
|
81
|
-
- **No legacy compatibility on `edit`**: `edit` accepts only structured hashline ops; sending legacy `oldText`/`newText` is rejected at the schema layer (never silently degrades) — so you always know whether hashline is actually in use. Bulk/regex replacement is a *separate* tool, `replace`, not an `edit` mode (see below).
|
|
55
|
+
Use returned anchors for subsequent edits. Content-mode `grep` provides the same references, grouped by file. Always copy actual tool output; the examples use the default four-character hash.
|
|
82
56
|
|
|
83
|
-
##
|
|
57
|
+
## Tools
|
|
84
58
|
|
|
85
|
-
|
|
59
|
+
| Tool | Use it for |
|
|
60
|
+
| --- | --- |
|
|
61
|
+
| `read` | Inspect files with line anchors; images/binary handling delegates to Pi. |
|
|
62
|
+
| `grep` | Search with bundled ripgrep and return anchored matches/context, file paths, or counts. |
|
|
63
|
+
| `edit` | Change specific lines or ranges using verified anchors. |
|
|
64
|
+
| `replace` | Replace every occurrence of a literal string or JavaScript regex across one file. |
|
|
65
|
+
| `write` | Create a file or replace its complete contents. |
|
|
86
66
|
|
|
87
|
-
|
|
67
|
+
All tools accept relative or absolute paths and expand a leading `~`. Mutation tools share the file-mutation queue and commit layer.
|
|
88
68
|
|
|
89
|
-
###
|
|
69
|
+
### Edit operations
|
|
90
70
|
|
|
91
|
-
|
|
71
|
+
`edit` takes `path` and an `edits` array. Anchors are `"LINE#HASH"` strings; each `body` element is one logical line without CR or LF.
|
|
92
72
|
|
|
93
|
-
|
|
73
|
+
| `op` | Required | Optional | Effect |
|
|
74
|
+
| --- | --- | --- | --- |
|
|
75
|
+
| `replace` | `anchor`, `body` | `end` | Replace one line or an inclusive range. |
|
|
76
|
+
| `delete` | `anchor` | `end` | Delete one line or an inclusive range; no `body`. |
|
|
77
|
+
| `insert_before` / `insert_after` | `anchor`, `body` | — | Insert beside the anchor; keep the anchor line. |
|
|
78
|
+
| `prepend` / `append` | `body` | — | Insert at the start/end; no anchors. |
|
|
94
79
|
|
|
95
|
-
|
|
80
|
+
All operations in a batch use the same snapshot. Validation failure rejects the whole batch. 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.
|
|
96
81
|
|
|
97
|
-
###
|
|
82
|
+
### Bulk replacement
|
|
98
83
|
|
|
99
|
-
|
|
84
|
+
For a rename across a file:
|
|
100
85
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
86
|
+
```json
|
|
87
|
+
{ "path": "src/foo.ts", "find": "oldName", "replace": "newName" }
|
|
88
|
+
```
|
|
104
89
|
|
|
105
|
-
|
|
90
|
+
Literal mode inserts replacement text verbatim. Set `regex: true` for JavaScript capture groups and replacement templates:
|
|
106
91
|
|
|
107
|
-
|
|
92
|
+
```json
|
|
93
|
+
{ "path": "src/foo.ts", "find": "get([A-Z]\\w*)", "replace": "fetch$1", "regex": true }
|
|
94
|
+
```
|
|
108
95
|
|
|
109
|
-
|
|
110
|
-
|
|
96
|
+
<details>
|
|
97
|
+
<summary><strong>Full read, grep, replace, and write parameter reference</strong></summary>
|
|
111
98
|
|
|
112
|
-
###
|
|
99
|
+
### Read
|
|
113
100
|
|
|
114
|
-
|
|
101
|
+
Required: `path`. Optional: 1-based `offset` (default 1) and `limit` (default 2000 lines). Returned text is capped at 256 KiB; oversized rows are not returned as partial editable lines. Files without a final newline are identified in the header.
|
|
115
102
|
|
|
116
|
-
|
|
117
|
-
|---|---|---|
|
|
118
|
-
| Anchor identity | per-line `LINE#HASH`, line number folded in | whole-file 4-hex `#TAG`, bare line numbers |
|
|
119
|
-
| Identical-line collisions | impossible by construction | n/a (no per-line hash); the file tag itself can collide in 16 bits |
|
|
120
|
-
| Out-of-band state | **none** | `SnapshotStore` (LRU) + `seenLines` guard |
|
|
121
|
-
| "Did the model read this line?" | proven by the anchor itself | needs the separate `seenLines` array |
|
|
122
|
-
| Verification granularity | only the cited lines (surgical) | whole file — any drift enters recovery |
|
|
123
|
-
| Concurrent external edits | not a goal; re-read to proceed | detected by design — tag change forces a re-read |
|
|
124
|
-
| Wire format | JSON schema ops | text patch DSL |
|
|
125
|
-
| Malformed edits | rejected at the schema layer | lenient parsing + heuristic repair |
|
|
126
|
-
| Format stability | one schema | ≥5 breaking format generations |
|
|
127
|
-
| Drift recovery | ±15-line rescan → fresh anchor, else re-read | line-remap replay, fail-closed |
|
|
128
|
-
| Expressiveness | fine-grained ops + separate `replace` | syntax blocks, cross-file registers, `REM`/`MV` |
|
|
129
|
-
| Read-time token cost | 2–4 chars per line | none at read time; cost moves to mismatch output |
|
|
103
|
+
### Grep
|
|
130
104
|
|
|
131
|
-
|
|
105
|
+
| Parameter | Default | Meaning |
|
|
106
|
+
| --- | --- | --- |
|
|
107
|
+
| `pattern` | Required | Non-empty string or array. |
|
|
108
|
+
| `path` | Current directory | One path or an array of search roots. |
|
|
109
|
+
| `matchMode` | `"any"` | OR across patterns; `"all"` requires every pattern on the same physical line, at most 16 patterns. |
|
|
110
|
+
| `excludePattern` | None | String or array; remove lines matching any exclusion. |
|
|
111
|
+
| `literal` | Automatic | `true`: literal strings. `false`: strict regex. Automatic mode detects regex metacharacters and falls back to literal text for all patterns on regex parse failure. |
|
|
112
|
+
| `ignoreCase` | Smart-case | Explicit `true`/`false` overrides case handling; the query-level decision also applies to exclusions. |
|
|
113
|
+
| `wordMatch` | `false` | Whole-word matches. |
|
|
114
|
+
| `glob` | None | One glob or an ordered array; prefix exclusions with `!`. |
|
|
115
|
+
| `noIgnore` | `false` | Include ignored files; explicit globs still apply. |
|
|
116
|
+
| `follow` | `false` | Traverse symlinks and return resolved target paths. |
|
|
117
|
+
| `context` | `0` | Include 0–20 anchored lines before and after matches. |
|
|
118
|
+
| `limit` | `100` | Maximum matching physical lines, counted after filtering. |
|
|
119
|
+
| `outputMode` | `"content"` | `"files"` returns paths; `"count"` returns per-file counts and a total. Both use the same limited match set. |
|
|
120
|
+
| `pcre2` | `false` | Enable PCRE2 lookarounds/backreferences; strict regex, incompatible with `literal: true`. |
|
|
121
|
+
| `multiline` | `false` | Allow cross-line matches; `.` crosses newlines only with inline `(?s)`. |
|
|
132
122
|
|
|
133
|
-
|
|
123
|
+
Context is rebuilt from surviving matches. Multiline filtering, counting, and limits remain line-based. Wildcard-only regexes such as `.*` and `^.+$` are accepted; use `literal: true` to search those characters verbatim.
|
|
134
124
|
|
|
135
|
-
|
|
136
|
-
- **No multi-agent story.** If several agents edit one tree, the file-tag route's external-edit detection is a real advantage this design does not have.
|
|
137
|
-
- **Hash transcription is itself error-prone.** Anchoring assumes the model copies the hash verbatim. It doesn't always: *"It sees `483:d4` in the input, writes `483:3a` in the output. Every model does this, including Opus."* ([geometricagi, *AST Edits*](https://geometricagi.github.io/2026/04/02/ast-edits.html), 2026-04-02). This is a failure class the built-in string-replace does not have — see Model Compatibility above; on a model that hasn't internalized anchor discipline, turn the plugin off rather than fight it.
|
|
138
|
-
- **The edit format may not be your bottleneck at all.** An independent benchmark ([nwyin, *edit-bench*](https://nwyin.com/blogs/hashline-vs-replace-edit-bench.html)) found the hashline-vs-replace delta to be language-dependent — a real penalty on Python, neutral on TypeScript, a wash on Rust — and concluded that *"edit format is not the bottleneck"*: model-to-model differences dwarf format-to-format ones. It also found that the whitespace near-miss anchoring is meant to kill barely occurs — fuzzy matching triggered 0 times across 114 successful edits.
|
|
139
|
-
- **A silent success is worse than a loud failure.** Any anchor scheme is only as safe as its implementation. opencode's early hashline port returned `Updated` while writing to the wrong line ([issue #15424](https://github.com/anomalyco/opencode/issues/15424)) — a buggy anchor check manufactures false trust. This plugin's recovery is built to fail closed and hand back live content instead of guessing, but the warning generalizes.
|
|
140
|
-
- **Model dependence is real and not universally in my favor.** omp routes kimi, mimo, deepseek-v4-flash and step-3.7-flash *away* from hashline by default (they miscount anchors or drop the tag header). My own field notes agree on Kimi and disagree on DeepSeek — same model, opposite conclusions in different environments. There is no globally best edit format; there is a model × task × implementation triple.
|
|
125
|
+
All inclusion/exclusion matching uses bundled ripgrep, independent of system `rg` or `PATH`. Searches are CRLF-aware, include hidden files while respecting ignore rules, and pass `--no-config`. The default engine is Rust regex; PCRE2 never silently falls back to another engine or literal matching.
|
|
141
126
|
|
|
142
|
-
|
|
127
|
+
### Replace
|
|
143
128
|
|
|
144
|
-
`
|
|
129
|
+
Required: `path`, `find`, `replace`. Optional:
|
|
145
130
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
2#7QK3│
|
|
150
|
-
3#MP04│export function foo(x: number) {
|
|
151
|
-
```
|
|
131
|
+
- `regex`: defaults to `false`; regex mode supports capture groups, the full match, and prefix/suffix substitutions.
|
|
132
|
+
- `flags`: applies in both modes; `g` is always added. Supported flags: `g i m s u y d`.
|
|
133
|
+
- `maxMatches`: defaults to 2000; rejects excess matches before writing. Raise it for intentional bulk changes. It does not bound regex execution time or result size.
|
|
152
134
|
|
|
153
|
-
|
|
135
|
+
Zero matches is an error. Identical output reports no net change.
|
|
154
136
|
|
|
155
|
-
|
|
156
|
-
src/foo.ts · 2 matches
|
|
157
|
-
3#MP04│export function foo(x: number) {
|
|
158
|
-
4#K7P2│ return x + 1
|
|
159
|
-
src/util.ts · 1 match
|
|
160
|
-
10#AF32│ const z = compute(x)
|
|
161
|
-
```
|
|
137
|
+
### Write
|
|
162
138
|
|
|
163
|
-
|
|
139
|
+
Required: `path`, `content`. By default, create missing files and overwrite existing ones. Content is used exactly as supplied; anchor-looking prefixes are not stripped.
|
|
164
140
|
|
|
165
|
-
- `
|
|
166
|
-
- `
|
|
167
|
-
- `
|
|
168
|
-
- `outputMode: "files"` / `"count"` — just the file paths (`rg -l`) or per-file counts + total (`grep -c`); `"files"` output pastes straight back as a `path` array
|
|
169
|
-
- `pattern` and `path` accept arrays — several patterns combined per `matchMode`, several search roots in one call
|
|
170
|
-
- `noIgnore` — include files excluded by `.gitignore`, `.ignore`, or `.rgignore`; explicit `glob` filters still apply
|
|
171
|
-
- `follow` — traverse symbolic links and return resolved target paths
|
|
172
|
-
- `pcre2` — opt into PCRE2 lookarounds and backreferences; this is strict regex mode and cannot be combined with `literal: true`
|
|
173
|
-
- `multiline` — allow matches across physical lines; results, filtering, limits, and counts remain line-based, and `.` crosses line breaks only with inline `(?s)`
|
|
141
|
+
- `mode: "create"`: refuse an existing target.
|
|
142
|
+
- `mode: "overwrite"`: require an existing target.
|
|
143
|
+
- `expectedRevision`: strictly check the current file's SHA-256; cannot be combined with create mode.
|
|
174
144
|
|
|
175
|
-
|
|
145
|
+
With Action Fusion enabled, `edit`, `replace`, and `write` also accept `then_run`.
|
|
176
146
|
|
|
177
|
-
|
|
147
|
+
</details>
|
|
178
148
|
|
|
149
|
+
## Configuration
|
|
179
150
|
|
|
180
|
-
|
|
151
|
+
Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json` by default) or the project's `.pi/settings.json`:
|
|
181
152
|
|
|
182
|
-
```
|
|
153
|
+
```json
|
|
183
154
|
{
|
|
184
|
-
"
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
155
|
+
"hashlineEdit": {
|
|
156
|
+
"enabled": true,
|
|
157
|
+
"actionFusion": true,
|
|
158
|
+
"hashLen": 4,
|
|
159
|
+
"shiftRadius": 15
|
|
160
|
+
}
|
|
189
161
|
}
|
|
190
162
|
```
|
|
191
163
|
|
|
192
|
-
|
|
164
|
+
| Setting | Default | Meaning |
|
|
165
|
+
| --- | --- | --- |
|
|
166
|
+
| `enabled` | `true` | Enable all five tools as one unit. Set `false` to restore built-in tools. |
|
|
167
|
+
| `actionFusion` | `true` | Expose `then_run` on mutation tools. Set `false` to disable command support. |
|
|
168
|
+
| `hashLen` | `4` | Integer checksum length, 2–8 characters. |
|
|
169
|
+
| `shiftRadius` | `15` | Integer recovery-search radius, 0–100 lines; `0` disables recovery. |
|
|
193
170
|
|
|
194
|
-
|
|
171
|
+
The project's `hashlineEdit` object replaces the global object as a whole; missing or invalid fields use defaults. Reload Pi after changes.
|
|
195
172
|
|
|
196
|
-
|
|
173
|
+
## Action Fusion
|
|
197
174
|
|
|
198
|
-
|
|
175
|
+
Action Fusion is enabled by default. Set `"actionFusion": false` in `hashlineEdit` and reload Pi to disable it; an existing explicit `false` remains effective. Commands run only when a call supplies `then_run`:
|
|
199
176
|
|
|
200
|
-
```
|
|
177
|
+
```json
|
|
201
178
|
{
|
|
202
179
|
"path": "src/foo.ts",
|
|
203
180
|
"find": "oldName",
|
|
204
|
-
"replace": "newName"
|
|
181
|
+
"replace": "newName",
|
|
182
|
+
"then_run": { "command": "npm test", "timeout": 60 }
|
|
205
183
|
}
|
|
206
184
|
```
|
|
207
185
|
|
|
208
|
-
|
|
186
|
+
`command` is required; `timeout` is optional, in positive seconds, with no default. Mutation failure skips the command. Command failure after mutation success **does not roll back the file**: it is returned separately in result text and `details.actionFusion`, rather than thrown as failure of the whole mutation.
|
|
209
187
|
|
|
210
|
-
|
|
211
|
-
{ "path": "src/foo.ts", "find": "get([A-Z]\w*)", "replace": "get_$1", "regex": true }
|
|
212
|
-
```
|
|
188
|
+
In the TUI, the mutation card turns successful when execution and result generation finish. The command gets its own waiting/running/success/failure card with expandable output. Command failure leaves the successful mutation card intact. RPC hosts receive the same progress and choose their own rendering.
|
|
213
189
|
|
|
214
|
-
|
|
190
|
+
Fusion serializes each mutation/command sequence for its target and checks the published revision before running the command. Commands invoke Pi's built-in Bash definition directly, without a separate Bash tool call; Bash-only approval/sandbox extensions must explicitly cover these tools' `then_run` inputs.
|
|
215
191
|
|
|
216
|
-
|
|
217
|
-
{ "path": "src/foo.ts", "find": "TODO", "replace": "FIXME", "flags": "i" }
|
|
218
|
-
```
|
|
192
|
+
## Safety and design
|
|
219
193
|
|
|
220
|
-
|
|
194
|
+
- **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.
|
|
195
|
+
- **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.
|
|
196
|
+
- **Line shifts change anchors.** Insertions/deletions can invalidate later references. Recovery searches within `shiftRadius` and offers fresh candidates; retries verify again, without fuzzy matching or automatic relocation.
|
|
197
|
+
- **Edits preserve text representation.** `edit` preserves existing line endings, untouched separators, and the absence of a final newline. `edit`/`replace` reject invalid UTF-8 source text; all mutations reject NUL and output that cannot be encoded losslessly as UTF-8.
|
|
198
|
+
- **Fresh anchors depend on the final observation.** After `then_run`, anchors are shown only for `unchanged` freshness. Without a command, observed and published revisions must agree. Later edits still verify anchors.
|
|
199
|
+
- **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.
|
|
221
200
|
|
|
222
|
-
|
|
201
|
+
<details>
|
|
202
|
+
<summary><strong>Output budgets, byte fidelity, publication, and result-state details</strong></summary>
|
|
223
203
|
|
|
224
|
-
|
|
225
|
-
{
|
|
226
|
-
"hashlineEdit": {
|
|
227
|
-
"enabled": true, // set false to disable the extension entirely (built-ins remain; reload pi)
|
|
228
|
-
"actionFusion": false, // set true to expose then_run on edit/replace/write
|
|
229
|
-
"hashLen": 4, // hash length, 2–8 (default 4)
|
|
230
|
-
"shiftRadius": 15 // ±lines scanned to rescue a stale anchor (default 15; 0 disables)
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
```
|
|
234
|
-
|
|
235
|
-
When `actionFusion` is true, `edit`, `replace`, and `write` accept an optional `then_run` object. The mutation runs first; a successful mutation is followed by the command using the same file-scoped Hashline Fusion queue. A command failure does not roll back the mutation. Once the mutation returns successfully, a subsequent command failure is returned in the result's text and `details.actionFusion`, rather than thrown as a failure of the whole tool call. Consumers must inspect the command status separately. Mutation failures still throw, including failures to finish mutation result generation after publication. The command uses Pi's built-in Bash definition directly and does not create a separate Bash tool call, so Bash-only approval or sandbox extensions must explicitly account for `edit.then_run`, `replace.then_run`, and `write.then_run`.
|
|
236
|
-
`write` preserves Pi's complete-content `{ path, content }` shape. By default it creates missing files and overwrites existing files. `mode: "create"` refuses an existing target; `mode: "overwrite"` requires an existing target; `expectedRevision` is optional, but is checked strictly when supplied. Hashline does not automatically strip `LINE#HASH│` prefixes from write content.
|
|
237
|
-
The setting is disabled by default. Keep it false when commands should not be available from Hashline mutations.
|
|
204
|
+
### Hashing and BOM handling
|
|
238
205
|
|
|
239
|
-
|
|
206
|
+
`read` computes line hashes only for its requested window; `grep` hashes selected matches/context. Both still read and decode whole files. Mutation revision checks cover actual bytes.
|
|
240
207
|
|
|
241
|
-
|
|
208
|
+
An existing UTF-8 BOM stays at byte zero through first-line replacement/deletion or insertion; deleting all content leaves the BOM. First-line hashes include it. A copied leading BOM in the first replacement/insertion line denotes the existing header; interior `U+FEFF` remains content. BOM-only files retain one anchored line. `replace` can explicitly match the BOM; `write` uses supplied content.
|
|
242
209
|
|
|
243
|
-
###
|
|
210
|
+
### Output budgets
|
|
244
211
|
|
|
245
|
-
|
|
212
|
+
These limits bound model context, not file size. Omission notices direct the caller to read more.
|
|
246
213
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
214
|
+
| Output | Limit |
|
|
215
|
+
| --- | --- |
|
|
216
|
+
| `read` | Default 2000 rows, overridable with `limit`; 256 KiB of anchored text. No partial anchor rows. |
|
|
217
|
+
| `grep` | Default 100 matching lines, overridable; 500 characters per displayed line, plus Pi's total output limits. Hashes use full content; read truncated lines before reconstructing them. |
|
|
218
|
+
| `edit` / `replace` anchors | Up to 40 complete rows and 16 KiB including heading/omission notice. |
|
|
219
|
+
| `write` anchors | Up to 40 compact tokens, without repeating supplied content. |
|
|
220
|
+
| Anchor failures | 16 KiB total, up to 40 detailed failures and eight candidates per ambiguous failure. Unresolved anchors include nearby current-file context, itself capped at 40 rows/16 KiB. |
|
|
254
221
|
|
|
255
|
-
|
|
222
|
+
### Publication
|
|
256
223
|
|
|
257
|
-
|
|
224
|
+
The shared commit layer prepares and syncs complete content in a sibling temporary directory. `edit`/`replace` bind publication to the revision of the bytes they read.
|
|
258
225
|
|
|
259
|
-
|
|
226
|
+
| Case | Behavior |
|
|
227
|
+
| --- | --- |
|
|
228
|
+
| Create | Same-filesystem `link(temp, target)` refuses a target created by another writer during publication. |
|
|
229
|
+
| Overwrite | `rename(temp, target)` publishes the replacement; never delete the old target first. |
|
|
230
|
+
| Symlinks | Resolve the regular-file target for overwrite and preserve the link; reject dangling/unresolvable links. |
|
|
231
|
+
| Multiple hard links | Reject existing regular files with multiple links to avoid splitting the link set. |
|
|
232
|
+
| Permissions | Copy existing mode bits; new files use `0600`. No separate public permission setting. |
|
|
233
|
+
| Post-publication failure | Directory-sync, result-generation, revision observation, or cleanup errors retain `PUBLISHED`; unconfirmed publication is `UNKNOWN`. Read before retrying uncertain mutations. |
|
|
234
|
+
| Durability | Attempt POSIX directory synchronization. Windows has no equivalent directory-sync path here; no Windows crash-persistence guarantee is claimed. |
|
|
260
235
|
|
|
261
|
-
|
|
236
|
+
### Result and card states
|
|
262
237
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
"/absolute/path/to/pi-hashline-edit"
|
|
273
|
-
]
|
|
274
|
-
}
|
|
275
|
-
```
|
|
238
|
+
| Field | Meaning |
|
|
239
|
+
| --- | --- |
|
|
240
|
+
| `publication` | `NOT_PUBLISHED`, `PUBLISHED`, or `UNKNOWN`. Fusion also reports it in `actionFusion.publication`. |
|
|
241
|
+
| `baseRevision` | SHA-256 of bytes read before mutation, when available. |
|
|
242
|
+
| `publishedRevision` | SHA-256 of intended published bytes; `revision` is its compatibility alias. |
|
|
243
|
+
| `observedRevision` | SHA-256 observed by the commit layer after publication. |
|
|
244
|
+
| `actionFusion.command` | `not_requested`, `skipped`, `succeeded`, `failed`, `timeout`, or `cancelled`. |
|
|
245
|
+
| `actionFusion.freshness` | `unchanged`, `changed`, `missing`, or `unknown`, relative to the published revision. |
|
|
246
|
+
| `actionFusion.mutationCompleted` | Progress flag set after mutation execution and result generation succeed; publication alone is not mutation success. |
|
|
276
247
|
|
|
277
|
-
|
|
248
|
+
Streaming mutation summaries omit anchors. Result-generation failures preserve publication status; progress callback failures are reported separately from mutation/command outcomes. Command output appears on its own card with native Bash rendering. Final cards survive reloads without adding model-context messages; unfinished saved commands show an interrupted/unknown outcome.
|
|
278
249
|
|
|
279
|
-
|
|
250
|
+
</details>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@criogaid/pi-hashline-edit",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
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",
|
package/src/core/apply.test.ts
CHANGED
|
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
|
|
|
3
3
|
import { computeLineHash } from "./hash.ts";
|
|
4
4
|
import { splitLines } from "./lines.ts";
|
|
5
5
|
import { applyEdits } from "./apply.ts";
|
|
6
|
-
import type { Anchor } from "./types.ts";
|
|
6
|
+
import type { Anchor, Edit } from "./types.ts";
|
|
7
7
|
|
|
8
8
|
/** Live anchor: hash the current content at the given line (1-based). */
|
|
9
9
|
function at(text: string, line: number): Anchor {
|
|
@@ -325,3 +325,42 @@ test("shiftRadius=0 disables rescue (always none)", () => {
|
|
|
325
325
|
}
|
|
326
326
|
});
|
|
327
327
|
|
|
328
|
+
|
|
329
|
+
test("rejects CR or LF embedded in body elements", () => {
|
|
330
|
+
for (const body of [["x\ny"], ["x\ry"]]) {
|
|
331
|
+
const result = applyEdits("a\n", [{ op: "append", body }]);
|
|
332
|
+
assert.deepEqual(result, {
|
|
333
|
+
ok: false,
|
|
334
|
+
failure: { kind: "input", message: "INVALID_BODY: each body element must contain exactly one logical line." },
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
test("BOM stays at byte zero through first-line edits while anchors retain their original hashes", () => {
|
|
340
|
+
for (const text of ["\uFEFFfirst\nsecond\n", "\uFEFFfirst\r\nsecond\r\n", "\uFEFFfirst\r\nsecond\n", "\uFEFFfirst\nsecond"]) {
|
|
341
|
+
const ending = text.includes("\r\n") ? "\r\n" : "\n";
|
|
342
|
+
const rest = text.slice(text.indexOf("\n") + 1);
|
|
343
|
+
const cases: [Edit, string][] = [
|
|
344
|
+
[{ op: "replace", start: at(text, 1), body: ["changed"] }, `\uFEFFchanged${ending}${rest}`],
|
|
345
|
+
[{ op: "replace", start: at(text, 1), body: ["\uFEFFchanged"] }, `\uFEFFchanged${ending}${rest}`],
|
|
346
|
+
[{ op: "delete", start: at(text, 1) }, `\uFEFF${rest}`],
|
|
347
|
+
[{ op: "prepend", body: ["new"] }, `\uFEFFnew${ending}${text.slice(1)}`],
|
|
348
|
+
[{ op: "insert_before", anchor: at(text, 1), body: ["new"] }, `\uFEFFnew${ending}${text.slice(1)}`],
|
|
349
|
+
[{ op: "delete", start: at(text, 1), end: at(text, 2) }, "\uFEFF"],
|
|
350
|
+
];
|
|
351
|
+
for (const [edit, expected] of cases) {
|
|
352
|
+
const result = applyEdits(text, [edit]);
|
|
353
|
+
assert.ok(result.ok);
|
|
354
|
+
assert.equal(result.text, expected, `${edit.op}: ${JSON.stringify(text)}`);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
for (const text of ["\uFEFF", "\uFEFFfirst"]) {
|
|
358
|
+
const result = applyEdits(text, [{ op: "replace", start: at(text, 1), body: ["changed"] }]);
|
|
359
|
+
assert.ok(result.ok);
|
|
360
|
+
assert.equal(result.text, "\uFEFFchanged");
|
|
361
|
+
}
|
|
362
|
+
const embedded = "\uFEFFfirst\ninside\uFEFFcontent\n";
|
|
363
|
+
const result = applyEdits(embedded, [{ op: "replace", start: at(embedded, 1), body: ["changed"] }]);
|
|
364
|
+
assert.ok(result.ok);
|
|
365
|
+
assert.equal(result.text, "\uFEFFchanged\ninside\uFEFFcontent\n");
|
|
366
|
+
});
|
package/src/core/apply.ts
CHANGED
|
@@ -170,8 +170,16 @@ function maxAffected(op: SpanOp): number {
|
|
|
170
170
|
* @param hashLen hash length used to verify anchors (default 4)
|
|
171
171
|
* @param shiftRadius ±line radius for shifted-anchor recovery (default 15; 0 disables rescue)
|
|
172
172
|
*/
|
|
173
|
+
function hasInvalidBodyLine(edits: readonly Edit[]): boolean {
|
|
174
|
+
return edits.some((edit) => "body" in edit && edit.body.some((line) => /[\r\n]/.test(line)));
|
|
175
|
+
}
|
|
176
|
+
|
|
173
177
|
export function applyEdits(text: string, edits: Edit[], hashLen = 4, shiftRadius = DEFAULT_SHIFT_RADIUS): ApplyResult {
|
|
178
|
+
if (hasInvalidBodyLine(edits)) {
|
|
179
|
+
return { ok: false, failure: { kind: "input", message: "INVALID_BODY: each body element must contain exactly one logical line." } };
|
|
180
|
+
}
|
|
174
181
|
const lines = splitLines(text);
|
|
182
|
+
const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
|
|
175
183
|
const ending = detectLineEnding(text);
|
|
176
184
|
|
|
177
185
|
const ops: SpanOp[] = [];
|
|
@@ -220,11 +228,13 @@ export function applyEdits(text: string, edits: Edit[], hashLen = 4, shiftRadius
|
|
|
220
228
|
// pure insertion) fall back to the file's customary ending.
|
|
221
229
|
const separators = text.match(/\r?\n/g) ?? [];
|
|
222
230
|
const separator = ending === "crlf" ? "\r\n" : "\n";
|
|
223
|
-
|
|
231
|
+
// Verify legacy anchors above before separating the file BOM from movable line content.
|
|
232
|
+
let result = lines.map((content, i) => ({ content: bom && i === 0 ? content.slice(1) : content, separator: separators[i] ?? "" }));
|
|
224
233
|
for (const op of [...sorted].sort((a, b) => b.lo - a.lo)) {
|
|
225
234
|
const removed = result.slice(op.lo, op.hi);
|
|
226
235
|
const inserted = op.newLines.map((content, i) => ({
|
|
227
|
-
|
|
236
|
+
// A copied first-line BOM denotes the existing file header, not a second BOM.
|
|
237
|
+
content: bom && op.lo === 0 && i === 0 && content.startsWith(bom) ? content.slice(1) : content,
|
|
228
238
|
separator: i === op.newLines.length - 1 && removed.length > 0
|
|
229
239
|
? removed[removed.length - 1].separator
|
|
230
240
|
: removed[i]?.separator || separator,
|
|
@@ -232,7 +242,7 @@ export function applyEdits(text: string, edits: Edit[], hashLen = 4, shiftRadius
|
|
|
232
242
|
result.splice(op.lo, op.hi - op.lo, ...inserted);
|
|
233
243
|
}
|
|
234
244
|
const finalNewline = hasFinalNewline(text);
|
|
235
|
-
const newText = result.map(({ content, separator: current }, i) =>
|
|
245
|
+
const newText = bom + result.map(({ content, separator: current }, i) =>
|
|
236
246
|
content + (i < result.length - 1 || finalNewline ? current || separator : ""),
|
|
237
247
|
).join("");
|
|
238
248
|
if (newText === text) {
|