@criogaid/pi-hashline-edit 0.1.0 → 0.1.2

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 CHANGED
@@ -2,278 +2,249 @@
2
2
 
3
3
  [![CI](https://github.com/Criogaid/pi-hashline-edit/actions/workflows/ci.yml/badge.svg)](https://github.com/Criogaid/pi-hashline-edit/actions/workflows/ci.yml) [![npm version](https://img.shields.io/npm/v/@criogaid/pi-hashline-edit)](https://www.npmjs.com/package/@criogaid/pi-hashline-edit) [![npm downloads](https://img.shields.io/npm/dm/@criogaid/pi-hashline-edit)](https://www.npmjs.com/package/@criogaid/pi-hashline-edit) [![license](https://img.shields.io/npm/l/@criogaid/pi-hashline-edit)](https://www.npmjs.com/package/@criogaid/pi-hashline-edit)
4
4
 
5
- > 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.
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
- 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.
7
+ Overrides `read`, `grep`, `edit`, and `write`, and adds `replace` for bulk transformations.
8
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.
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:** optional Action Fusion runs a command after a successful mutation, with separate file and command outcomes and separate TUI cards.
10
13
 
11
- ## Why hashline?
14
+ [Quick start](#quick-start) · [Tools](#tools) · [Configuration](#configuration) · [Action Fusion](#action-fusion) · [Safety and design](#safety-and-design)
12
15
 
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:
16
+ ## Install
14
17
 
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
18
+ ```bash
19
+ pi install npm:@criogaid/pi-hashline-edit
20
+ ```
50
21
 
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.
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
- ## Gotchas (vs. the built-in `read`/`edit`)
24
+ ## Quick start
54
25
 
55
- Once hashline overrides the built-ins, a few things behave differently:
26
+ Once installed, Pi's model uses these tool calls automatically. The examples below show the read → edit protocol.
56
27
 
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.
28
+ A `read` of `greet.ts` returns:
59
29
 
60
- ## `replace` — bulk + regex
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
- 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.
37
+ To change the return value, copy the second line's anchor into `edit` and supply only the new content:
63
38
 
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).
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
- `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`.
48
+ The result includes a diff and the updated anchor:
71
49
 
72
- ## Design
50
+ ```text
51
+ Updated anchors (use these for the next edit):
52
+ 2#V8AT│ return "hello, hashline";
53
+ ```
73
54
 
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).
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
- ## Why line hashes, not file tags
57
+ ## Tools
84
58
 
85
- ### The short version
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
- 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.
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
- ### Where this comes from
69
+ ### Edit operations
90
70
 
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.
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
- **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.
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
- 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.)
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
- ### The case against the file-tag route
82
+ ### Bulk replacement
98
83
 
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:
84
+ For a rename across a file:
100
85
 
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.
86
+ ```json
87
+ { "path": "src/foo.ts", "find": "oldName", "replace": "newName" }
88
+ ```
104
89
 
105
- ### Why a JSON schema, not a text DSL
90
+ Literal mode inserts replacement text verbatim. Set `regex: true` for JavaScript capture groups and replacement templates:
106
91
 
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:
92
+ ```json
93
+ { "path": "src/foo.ts", "find": "get([A-Z]\\w*)", "replace": "fetch$1", "regex": true }
94
+ ```
108
95
 
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.
96
+ <details>
97
+ <summary><strong>Full read, grep, replace, and write parameter reference</strong></summary>
111
98
 
112
- ### Compared by capability
99
+ ### Read
113
100
 
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*.
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
- | 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 |
103
+ ### Grep
130
104
 
131
- ### Honest limitations
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
- Including the ones that argue *for* the route I didn't take.
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
- - **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.
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
- ## Protocol
127
+ ### Replace
143
128
 
144
- `read` output (each line anchored):
129
+ Required: `path`, `find`, `replace`. Optional:
145
130
 
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
- ```
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
- `grep` output (results grouped by file, each line anchored — copy `LINE#HASH` straight into an edit):
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
- The `grep` override also covers the compound queries that otherwise push models into bash pipelines:
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
- - `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)`
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
- 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.
145
+ With Action Fusion enabled, `edit`, `replace`, and `write` also accept `then_run`.
176
146
 
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`.
147
+ </details>
178
148
 
149
+ ## Configuration
179
150
 
180
- `edit` takes `path` + `edits`. Copy `anchor` and `end` directly as `"LINE#HASH"` strings; `body` contains the new lines:
151
+ Add `hashlineEdit` to Pi's global settings (`~/.pi/agent/settings.json` by default) or the project's `.pi/settings.json`:
181
152
 
182
- ```jsonc
153
+ ```json
183
154
  {
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
- ]
155
+ "hashlineEdit": {
156
+ "enabled": true,
157
+ "actionFusion": false,
158
+ "hashLen": 4,
159
+ "shiftRadius": 15
160
+ }
189
161
  }
190
162
  ```
191
163
 
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.
164
+ | Setting | Default | Meaning |
165
+ | --- | --- | --- |
166
+ | `enabled` | `true` | Enable all five tools as one unit. Set `false` to restore built-in tools. |
167
+ | `actionFusion` | `false` | Expose `then_run` on mutation tools. |
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
- **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.
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
- 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.
173
+ ## Action Fusion
197
174
 
198
- `replace` takes `path`, `find`, `replace` (+ optional `regex`, `flags`, `maxMatches`) and substitutes **every** match:
175
+ With `actionFusion: true`, attach a command to a mutation:
199
176
 
200
- ```jsonc
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
- Regex with a capture group (rename `getName()` → `get_name()` everywhere):
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
- ```jsonc
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
- Case-insensitive literal rename across the whole file:
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
- ```jsonc
217
- { "path": "src/foo.ts", "find": "TODO", "replace": "FIXME", "flags": "i" }
218
- ```
192
+ ## Safety and design
219
193
 
220
- ## Configuration
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
- Add a `hashlineEdit` field to `~/.pi/agent/settings.json` (global) or `.pi/settings.json` in a project (project replaces global):
201
+ <details>
202
+ <summary><strong>Output budgets, byte fidelity, publication, and result-state details</strong></summary>
223
203
 
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.
204
+ ### Hashing and BOM handling
238
205
 
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.
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
- 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.
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
- ### File publication boundaries
210
+ ### Output budgets
244
211
 
245
- All three mutation tools use the same `commitFile` layer. Complete content is prepared in a sibling temporary directory and synced before publication.
212
+ These limits bound model context, not file size. Omission notices direct the caller to read more.
246
213
 
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.
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
- The default workspace path behavior is unchanged. Strict workspace jail remains an explicit future mode, not a default.
222
+ ### Publication
256
223
 
257
- ### Validation boundary
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
- 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.
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
- ## Installation
236
+ ### Result and card states
262
237
 
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
- ```
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
- ## Dependencies
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
- - No additional `@criogaid/pi-*` dependencies; peer `@earendil-works/pi-coding-agent` ships with pi (framework-level, not listed by convention).
250
+ </details>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@criogaid/pi-hashline-edit",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
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",
@@ -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
- let result = lines.map((content, i) => ({ content, separator: separators[i] ?? "" }));
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
- content,
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) {