@criogaid/pi-hashline-edit 0.1.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.
- package/LICENSE +21 -0
- package/README.md +279 -0
- package/package.json +50 -0
- package/src/core/apply.test.ts +327 -0
- package/src/core/apply.ts +264 -0
- package/src/core/hash.test.ts +54 -0
- package/src/core/hash.ts +68 -0
- package/src/core/index.ts +13 -0
- package/src/core/lines.test.ts +33 -0
- package/src/core/lines.ts +52 -0
- package/src/core/types.ts +87 -0
- package/src/index.ts +44 -0
- package/src/integration/grep-rg.test.ts +390 -0
- package/src/pi/action-fusion.test.ts +244 -0
- package/src/pi/action-fusion.ts +284 -0
- package/src/pi/config.test.ts +22 -0
- package/src/pi/config.ts +56 -0
- package/src/pi/edit-tool.ts +367 -0
- package/src/pi/execute.test.ts +521 -0
- package/src/pi/failure-context.test.ts +88 -0
- package/src/pi/failure-context.ts +98 -0
- package/src/pi/failure-path.test.ts +60 -0
- package/src/pi/file-commit.test.ts +200 -0
- package/src/pi/file-commit.ts +185 -0
- package/src/pi/fusion-card.test.ts +69 -0
- package/src/pi/fusion-card.ts +78 -0
- package/src/pi/grep-tool.ts +795 -0
- package/src/pi/grep.test.ts +515 -0
- package/src/pi/pi.test.ts +19 -0
- package/src/pi/read-tool.ts +178 -0
- package/src/pi/registration.test.ts +41 -0
- package/src/pi/render.ts +103 -0
- package/src/pi/replace-tool.ts +303 -0
- package/src/pi/replace.test.ts +287 -0
- package/src/pi/rg-line-filter.test.ts +79 -0
- package/src/pi/rg-line-filter.ts +358 -0
- package/src/pi/rg-line-ranges.test.ts +30 -0
- package/src/pi/rg-line-ranges.ts +106 -0
- package/src/pi/state.ts +27 -0
- package/src/pi/write-tool.ts +83 -0
- package/src/pi/write.test.ts +126 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chien Zhang and contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
# @criogaid/pi-hashline-edit
|
|
2
|
+
|
|
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
|
+
|
|
5
|
+
> Hashline-style local file tools for [pi](https://github.com/earendil-works/pi-coding-agent) — `read` and `grep` emit content-verified `LINE#HASH` anchors, `edit` applies surgical anchored changes, `replace` handles whole-file string/regex transforms, and `write` publishes complete content safely.
|
|
6
|
+
|
|
7
|
+
All five tools replace pi's local-filesystem toolset as one switchable unit. Optional Hashline Fusion attaches a `then_run` command to a successful `edit`/`replace`/`write` mutation, with file-scoped serialization and explicit publication, command, and freshness state.
|
|
8
|
+
|
|
9
|
+
This repository is the standalone home of the implementation. The `@criogaid` release line starts at `0.1.0`; pre-split Git history is retained for provenance, while releases of the former `@d3ara1n` package belong to that package and are not releases of this one.
|
|
10
|
+
|
|
11
|
+
## Why hashline?
|
|
12
|
+
|
|
13
|
+
The built-in `edit` matches `oldText`/`newText` exactly. When the model can't reproduce the source verbatim — wrong indentation, a non-unique snippet, or a line that drifted since the read — the edit fails and you loop. Hashline sidesteps all of it:
|
|
14
|
+
|
|
15
|
+
- **No string-not-found loops** — you edit by reference (`LINE#HASH`), not by retyping the line you want to change.
|
|
16
|
+
- **No whitespace battles** — the new content is the only thing you type; nothing has to match what's already there. Indentation mistakes on the *old* code are impossible.
|
|
17
|
+
- **Unique-by-construction hashes** — the line number is folded into the hash, so identical lines (blank lines, `}`) never share a hash and never collide.
|
|
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
|
|
50
|
+
|
|
51
|
+
**No reservations.** Structured ops are home turf for this family (tested: GPT 5.6 sol/terra/luna): no fabricated or mistyped anchors observed, and `insert_after` was never misused — the anchor-line-into-`body` duplication (see DeepSeek above) never occurred. The few rejected anchors were the *expected* kind: a size-changing `edit` invalidating the hashes of the lines below it between edits — the documented hash-drift tradeoff rather than a model error, and exactly what the self-healing rescan exists to rescue. Even those ran fewer than expected; small-sample observation, take it directionally.
|
|
52
|
+
|
|
53
|
+
## Gotchas (vs. the built-in `read`/`edit`)
|
|
54
|
+
|
|
55
|
+
Once hashline overrides the built-ins, a few things behave differently:
|
|
56
|
+
|
|
57
|
+
- **`read` is globally overridden.** Every read shows the `LINE#HASH│` prefix on each line — even reads that won't lead to an edit. This is expected (it's the substrate the reliability is built on), just don't be surprised when the format changes for all files.
|
|
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.
|
|
59
|
+
|
|
60
|
+
## `replace` — bulk + regex
|
|
61
|
+
|
|
62
|
+
A separate, location-blind tool for transforms `edit` can't express: replace **all** occurrences of a string/regex across the whole file in one call. Use it for renames, normalizations, and pattern-based rewrites that would otherwise need many individual anchored ops.
|
|
63
|
+
|
|
64
|
+
- **Two modes** — `regex: false` (default) treats `find` as a literal substring (replaceAll; the replacement is inserted verbatim, no `$` expansion); `regex: true` treats `find` as a JavaScript pattern source and `replace` supports `$1`, `$2`, `$&`, …
|
|
65
|
+
- **Flags** — `flags` adds regex flags in both modes (`g` is always forced so every occurrence is replaced): `i` (case-insensitive), `m` (per-line `^`/`$`), `s` (dotall, `.` matches `\n`), `u` (unicode).
|
|
66
|
+
- **Safety** — a `maxMatches` cap (default 2000) errors *before writing* if exceeded, so a runaway pattern can't produce a catastrophic write. `0` matches is an error (no silent no-op).
|
|
67
|
+
- **Shares the edit queue** — `replace` and `edit` on the same file are serialized via the same mutation queue, so concurrent edits never interleave.
|
|
68
|
+
- **Returns a diff + fresh anchors** for the changed region, so a follow-up `edit` can chain on the new content without a re-read (when the region is small).
|
|
69
|
+
|
|
70
|
+
`edit` vs `replace`: `edit` is **surgical and verified** (you point at a `LINE#HASH` and the tool confirms the line is unchanged before rewriting it). `replace` is **global and unverified** (you give a pattern, it rewrites every match sight-unseen). Pick by intent: change a known spot → `edit`; transform every occurrence → `replace`.
|
|
71
|
+
|
|
72
|
+
## Design
|
|
73
|
+
|
|
74
|
+
- **Per-line hash + line number, dual anchor**: `read` shows each line as `3#AF32│code`; `edit` references `LINE#HASH`. The line number is the address; the hash is a checksum that the line at that address is still what was read.
|
|
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).
|
|
82
|
+
|
|
83
|
+
## Why line hashes, not file tags
|
|
84
|
+
|
|
85
|
+
### The short version
|
|
86
|
+
|
|
87
|
+
This plugin is a line-hash editor: every line comes back tagged with a content hash that folds in its line number, and you edit by citing that `LINE#HASH`. That is, deliberately, the *original* hashline idea — the one omp shipped in February 2026 and then walked away from. omp's current engine anchors on a **whole-file** hash instead, and has since mid-2026. I looked at that route and stayed on the line-hash one on purpose. What follows is my case for that choice, stated as a tradeoff rather than a verdict — the honest limitations, including the ones that argue for the other route, come right after.
|
|
88
|
+
|
|
89
|
+
### Where this comes from
|
|
90
|
+
|
|
91
|
+
The idea that a model should edit by pointing at a **stable, verifiable anchor** instead of retyping code it already saw is not mine — it is can1357's, argued in [*The Harness Problem*](https://blog.can.ac/2026/02/12/the-harness-problem/) (2026-02-12), and omp's first implementation was exactly this shape: every read line tagged with a short per-line content hash, edits expressed as structured `old`/`new` ops. That first design had a real problem, and omp and I fixed it in opposite directions.
|
|
92
|
+
|
|
93
|
+
**Identical lines collide.** A per-line *content* hash gives every `}`, every `)`, every blank line the same hash — and a hash that is not unique is not an anchor. omp's fix was to stop hashing lines and hash the **whole file** instead: a 4-hex file tag, with no per-line hash in `read` output at all. My fix was to fold the line number into each line's hash, so two identical lines at different positions can never share one — unique by construction, no file-level state required.
|
|
94
|
+
|
|
95
|
+
That single divergence cascades into everything else. (It also means the picture most people have of "hashline" is the line-hash one: omp's own docs site still describes per-line anchors that its current implementation no longer emits.)
|
|
96
|
+
|
|
97
|
+
### The case against the file-tag route
|
|
98
|
+
|
|
99
|
+
I can't speak to omp's motives for the switch — collision-proofing a per-line hash is hard, and the file tag sidesteps it entirely. But the clearest *payoff* I see in a whole-file tag is one my design gives up: **awareness of edits made by anyone else.** If another process touches the file, its whole-file tag changes, the next anchored edit is rejected, and the model is forced to re-read fresh state. For a swarm of agents editing one tree, that is a genuinely good property. It costs three things I wasn't willing to pay:
|
|
100
|
+
|
|
101
|
+
- **The tag can't tell whether the model actually *read* a line.** A whole-file hash proves the file is byte-for-byte what it was — not that the model ever saw the specific line it is now rewriting. To stop hallucinated edits on never-displayed lines, omp carries a separate `seenLines` guard alongside the tag. A per-line hash *is* the proof of having-seen: you cannot cite `LINE#HASH` without having read that line's content. No side array needed.
|
|
102
|
+
- **It needs out-of-band state.** A 16-bit file tag "is not meaningful outside that store" (omp's own words) — it can collide, so omp keeps a `SnapshotStore`, an LRU of recent file versions, to disambiguate. My hashes are content-derived and self-contained: an anchor is verified by rehashing the current line at that number, at apply time, against nothing but the file on disk. **This plugin has no SnapshotStore, no seenLines array, nothing to keep in sync.** That is the point, not an omission.
|
|
103
|
+
- **The verification is coarse.** A whole-file tag couples every edit to the entire file: an unrelated change *anywhere* invalidates the tag and drags the whole patch through recovery. Line hashes verify only the lines you cite — an unrelated edit elsewhere never blocks you.
|
|
104
|
+
|
|
105
|
+
### Why a JSON schema, not a text DSL
|
|
106
|
+
|
|
107
|
+
The other visible difference: omp delivers edits as a **text patch language** (`PUT`/`CUT`/`REM`/`MV` today, `SWAP`/`DEL`/`INS` before that, JSON before *that*). This plugin uses **structured JSON ops**. Two reasons:
|
|
108
|
+
|
|
109
|
+
- **Validation belongs to the tool, not the model.** A JSON schema rejects a malformed op at the parameter layer before any logic runs. A text DSL puts the burden of emitting exactly-correct syntax back on the model, and the error rate is high enough that the DSL route accretes layer after layer of lenient parsing and heuristic repair to compensate — omp has shipped both, including a documented incident where the repair silently dropped content. The whole reason to anchor by hash was to stop depending on the model reproducing text perfectly; a hand-written DSL quietly reintroduces that dependency on the other side of the call.
|
|
110
|
+
- **The token savings aren't worth it.** A DSL saves a handful of structural characters per op. Against a higher malformed-edit rate and the cost of format churn — omp's patch syntax has broken compatibly five-plus times, stranding third-party ports on dead dialects — that saving is noise.
|
|
111
|
+
|
|
112
|
+
### Compared by capability
|
|
113
|
+
|
|
114
|
+
Not by version: omp's later generations refine the same whole-file-tag core, so the real comparison is *line-hash route* vs *file-tag route*.
|
|
115
|
+
|
|
116
|
+
| Capability | This plugin (line-hash) | omp (file-tag) |
|
|
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 |
|
|
130
|
+
|
|
131
|
+
### Honest limitations
|
|
132
|
+
|
|
133
|
+
Including the ones that argue *for* the route I didn't take.
|
|
134
|
+
|
|
135
|
+
- **Hash drift after an edit.** Because the line number is part of the hash, inserting or deleting lines changes every subsequent line's hash. A successful edit hands back fresh anchors for the region it just produced, and the ±15-line rescan rescues nearby drift — but to cite lines well below a size-changing edit, you re-read. That is the price of stateless verification: I keep no snapshot that would track those shifts for you. I consider it a fair trade for having no out-of-band state to corrupt or resync; a clean core matters more to me than saving a read.
|
|
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.
|
|
141
|
+
|
|
142
|
+
## Protocol
|
|
143
|
+
|
|
144
|
+
`read` output (each line anchored):
|
|
145
|
+
|
|
146
|
+
```
|
|
147
|
+
src/foo.ts · 6 lines
|
|
148
|
+
1#AF32│import { compute } from "./util"
|
|
149
|
+
2#7QK3│
|
|
150
|
+
3#MP04│export function foo(x: number) {
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`grep` output (results grouped by file, each line anchored — copy `LINE#HASH` straight into an edit):
|
|
154
|
+
|
|
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
|
+
```
|
|
162
|
+
|
|
163
|
+
The `grep` override also covers the compound queries that otherwise push models into bash pipelines:
|
|
164
|
+
|
|
165
|
+
- `matchMode: "all"` — a line must match **every** pattern (`grep A | grep B` without the pipe)
|
|
166
|
+
- `excludePattern` — drop matching lines (`grep -v`), applied after pattern matching
|
|
167
|
+
- `wordMatch` — whole words only (`rg -w`)
|
|
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)`
|
|
174
|
+
|
|
175
|
+
Filters run before the match limit counts, and context windows are rebuilt from surviving matches, so `limit` and `context` compose cleanly with `matchMode`/`excludePattern`. `files` and `count` use the same limited set of matching physical lines; they are not unlimited repository totals.
|
|
176
|
+
|
|
177
|
+
All inclusion and exclusion patterns are evaluated by ripgrep. The default engine is ripgrep's standard Rust regex engine with query-level smart-case; `pcre2: true` selects the bundled PCRE2 engine without silently changing engines or falling back to literal text. Searches are CRLF-aware and single-line by default. The extension passes `--no-config`, includes hidden files while retaining ignore rules, and invokes the platform-specific binary installed through `@vscode/ripgrep`, independent of a system `rg` or `PATH`.
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
`edit` takes `path` + `edits`. Copy `anchor` and `end` directly as `"LINE#HASH"` strings; `body` contains the new lines:
|
|
181
|
+
|
|
182
|
+
```jsonc
|
|
183
|
+
{
|
|
184
|
+
"path": "src/foo.ts",
|
|
185
|
+
"edits": [
|
|
186
|
+
{ "op": "replace", "anchor": "4#K7P2", "body": [" return x + 2"] },
|
|
187
|
+
{ "op": "insert_after", "anchor": "6#B2H4", "body": ["", "export const bar = foo"] }
|
|
188
|
+
]
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Ops: `replace` · `delete` · `insert_after` · `insert_before` · `append` · `prepend`. Replace/delete affect only the anchor line unless an inclusive `end` is supplied. To change multiple existing lines, supply both anchors. Insert operations keep the anchor line and accept no `end`; append/prepend accept neither anchor. `body` is required except for delete, which accepts no body. Conflicting fields are rejected before publication.
|
|
193
|
+
|
|
194
|
+
**Migration:** Object anchors (`{ "line": 4, "hash": "K7P2" }`) are no longer accepted by the tool. Use `"4#K7P2"` instead, including in saved calls and retry code. Core library anchors remain objects.
|
|
195
|
+
|
|
196
|
+
Successful `write` results include a revision and compact anchor tokens (up to 40), without echoing the content just supplied. Edit/replace results retain changed-line content where it helps identify subsequent edits. Parameter rules live in the schemas; prompt guidelines cover only tool selection and batching.
|
|
197
|
+
|
|
198
|
+
`replace` takes `path`, `find`, `replace` (+ optional `regex`, `flags`, `maxMatches`) and substitutes **every** match:
|
|
199
|
+
|
|
200
|
+
```jsonc
|
|
201
|
+
{
|
|
202
|
+
"path": "src/foo.ts",
|
|
203
|
+
"find": "oldName",
|
|
204
|
+
"replace": "newName"
|
|
205
|
+
}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Regex with a capture group (rename `getName()` → `get_name()` everywhere):
|
|
209
|
+
|
|
210
|
+
```jsonc
|
|
211
|
+
{ "path": "src/foo.ts", "find": "get([A-Z]\w*)", "replace": "get_$1", "regex": true }
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Case-insensitive literal rename across the whole file:
|
|
215
|
+
|
|
216
|
+
```jsonc
|
|
217
|
+
{ "path": "src/foo.ts", "find": "TODO", "replace": "FIXME", "flags": "i" }
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
## Configuration
|
|
221
|
+
|
|
222
|
+
Add a `hashlineEdit` field to `~/.pi/agent/settings.json` (global) or `.pi/settings.json` in a project (project replaces global):
|
|
223
|
+
|
|
224
|
+
```jsonc
|
|
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.
|
|
238
|
+
|
|
239
|
+
In the TUI, each `then_run` gets a separate transcript card showing the command, waiting/running state, live output, and final outcome. If the mutation succeeded but the command failed, the main card retains its successful mutation preview/diff and only the command card shows the failure. Command output is not repeated in the main card. Cards reuse Pi's native Bash command and output renderers, including the collapsed output preview and expand hint, with the same pending/success/error background colors as native tools. Expand them to inspect the captured output. Cards preserve their final state across session reloads without adding messages to model context. If the session ended before a final outcome was saved, the card reports an interrupted command with unknown final status. RPC hosts receive the same progress through tool execution updates; rendering depends on the host.
|
|
240
|
+
|
|
241
|
+
Fusion errors tell the model whether file changes were saved and whether the command ran. When a requested command leaves freshness anything other than explicitly `unchanged`, pre-command anchors from `write` and `edit` are omitted and the result requests a fresh read before further editing. Structured publication, command, and freshness states remain available to the card and other consumers.
|
|
242
|
+
|
|
243
|
+
### File publication boundaries
|
|
244
|
+
|
|
245
|
+
All three mutation tools use the same `commitFile` layer. Complete content is prepared in a sibling temporary directory and synced before publication.
|
|
246
|
+
|
|
247
|
+
- `mode: "create"` publishes with same-filesystem `link(temp, target)`, so a target that appears during the race is rejected rather than overwritten.
|
|
248
|
+
- Replacement publishes with `rename(temp, target)` and never deletes the old target first.
|
|
249
|
+
- Existing symlinks are resolved for overwrite and preserved; dangling or unresolvable symlinks are rejected.
|
|
250
|
+
- Existing regular files with multiple hard links are rejected instead of silently splitting the link set.
|
|
251
|
+
- Existing permission bits are copied to the replacement; new files are created with `0600`, which is also their final default mode. There is no separate public permission setting.
|
|
252
|
+
- `publication` remains `PUBLISHED` if revision calculation, directory sync, or temporary cleanup fails after publication; an unconfirmed publish is `UNKNOWN`.
|
|
253
|
+
- POSIX directory synchronization is attempted after publication. Windows does not provide the same directory-sync path here, so this package does not claim crash-persistence guarantees there.
|
|
254
|
+
|
|
255
|
+
The default workspace path behavior is unchanged. Strict workspace jail remains an explicit future mode, not a default.
|
|
256
|
+
|
|
257
|
+
### Validation boundary
|
|
258
|
+
|
|
259
|
+
The standalone `0.1.0` candidate was typechecked against Pi `0.86.1` and passed the unit and bundled-ripgrep integration suites on GitHub-hosted Ubuntu, macOS, and Windows under Node 24. The same suites and an npm pack dry run passed locally on Windows `win32` with NTFS using Node `v26.9.0` and npm `11.19.1`; the tarball contains only the README, license, package metadata, and `src`. An installed-package loader smoke test was previously completed on Windows with Pi `0.85.1`. Network filesystems, full crash durability, Windows symlink permissions, and successful Windows atomic-read visibility remain unverified.
|
|
260
|
+
|
|
261
|
+
## Installation
|
|
262
|
+
|
|
263
|
+
```bash
|
|
264
|
+
pi install npm:@criogaid/pi-hashline-edit
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Or add to `~/.pi/agent/settings.json`:
|
|
268
|
+
|
|
269
|
+
```jsonc
|
|
270
|
+
{
|
|
271
|
+
"extensions": [
|
|
272
|
+
"/absolute/path/to/pi-hashline-edit"
|
|
273
|
+
]
|
|
274
|
+
}
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
## Dependencies
|
|
278
|
+
|
|
279
|
+
- No additional `@criogaid/pi-*` dependencies; peer `@earendil-works/pi-coding-agent` ships with pi (framework-level, not listed by convention).
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@criogaid/pi-hashline-edit",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Hashline-style file editing for pi — line-anchored edits verified by content hash, replacing oldText/newText matching",
|
|
6
|
+
"homepage": "https://github.com/Criogaid/pi-hashline-edit#readme",
|
|
7
|
+
"bugs": {
|
|
8
|
+
"url": "https://github.com/Criogaid/pi-hashline-edit/issues"
|
|
9
|
+
},
|
|
10
|
+
"keywords": [
|
|
11
|
+
"pi-package",
|
|
12
|
+
"pi"
|
|
13
|
+
],
|
|
14
|
+
"main": "src/index.ts",
|
|
15
|
+
"files": [
|
|
16
|
+
"src",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"typecheck": "tsc --noEmit",
|
|
22
|
+
"test": "node --test src/core/*.test.ts src/pi/*.test.ts",
|
|
23
|
+
"test:integration": "node --test src/integration/*.test.ts",
|
|
24
|
+
"test:all": "npm test && npm run test:integration"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@vscode/ripgrep": "1.18.0"
|
|
28
|
+
},
|
|
29
|
+
"peerDependencies": {
|
|
30
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@earendil-works/pi-agent-core": "*",
|
|
34
|
+
"@earendil-works/pi-ai": "*",
|
|
35
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
36
|
+
"@earendil-works/pi-tui": "*",
|
|
37
|
+
"typebox": "^1.1.38",
|
|
38
|
+
"typescript": "^7.0.2"
|
|
39
|
+
},
|
|
40
|
+
"pi": {
|
|
41
|
+
"extensions": [
|
|
42
|
+
"./src/index.ts"
|
|
43
|
+
]
|
|
44
|
+
},
|
|
45
|
+
"repository": {
|
|
46
|
+
"type": "git",
|
|
47
|
+
"url": "git+https://github.com/Criogaid/pi-hashline-edit.git"
|
|
48
|
+
},
|
|
49
|
+
"license": "MIT"
|
|
50
|
+
}
|