dsh-better-edit 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +318 -245
  3. package/README.zh.md +20 -11
  4. package/lib/contract.js +40 -1
  5. package/lib/edit-engine.js +4 -4
  6. package/lib/edit-pipeline.js +4 -4
  7. package/lib/file-view.js +63 -0
  8. package/lib/guidance/index.js +8 -0
  9. package/lib/guidance/materialize.js +191 -0
  10. package/lib/guidance/parse.js +80 -0
  11. package/lib/guidance/resolve.js +122 -0
  12. package/lib/guidance.js +6 -388
  13. package/lib/hash-store.js +1 -2
  14. package/lib/hashline/anchor-pipeline.js +23 -0
  15. package/lib/hashline/hash-assign.js +20 -0
  16. package/lib/hashline/index.js +4 -5
  17. package/lib/hashline/resolve.js +5 -0
  18. package/lib/index.js +1 -1
  19. package/lib/mutation.js +58 -0
  20. package/lib/read-and-serve.js +23 -23
  21. package/lib/served-store.js +1 -1
  22. package/lib/session-view.js +34 -0
  23. package/lib/tool-batch-edit.js +9 -10
  24. package/lib/tool-edit.js +9 -11
  25. package/lib/tool-read.js +3 -5
  26. package/lib/tool-undo.js +6 -6
  27. package/lib/types/contract.d.ts +31 -0
  28. package/lib/types/edit-engine.d.ts +2 -2
  29. package/lib/types/edit-pipeline.d.ts +2 -2
  30. package/lib/types/file-view.d.ts +74 -0
  31. package/lib/types/guidance/index.d.ts +8 -0
  32. package/lib/types/guidance/materialize.d.ts +23 -0
  33. package/lib/types/guidance/parse.d.ts +36 -0
  34. package/lib/types/guidance/resolve.d.ts +55 -0
  35. package/lib/types/guidance.d.ts +6 -127
  36. package/lib/types/hashline/anchor-pipeline.d.ts +26 -0
  37. package/lib/types/hashline/hash-assign.d.ts +19 -0
  38. package/lib/types/hashline/index.d.ts +7 -5
  39. package/lib/types/hashline/resolve.d.ts +5 -0
  40. package/lib/types/mutation.d.ts +78 -0
  41. package/lib/types/read-and-serve.d.ts +6 -5
  42. package/lib/types/session-view.d.ts +33 -0
  43. package/lib/write-hook.js +2 -2
  44. package/package.json +1 -1
package/README.md CHANGED
@@ -1,29 +1,35 @@
1
1
  <p align="center">
2
- <img src="assets/logo.svg" alt="dsh-better-edit" width="200">
2
+ <img src="assets/banner.svg" alt="dsh-better-edit banner" width="900">
3
3
  </p>
4
4
 
5
5
  <h1 align="center">dsh-better-edit</h1>
6
-
7
6
  <p align="center">
8
7
  <strong>A better edit tool for DeepSeek Harness<br>
9
8
  Powered by hash‑anchored positioning — not by line numbers, not by string replacement, fewer tokens, more context space for real work.</strong>
10
9
  </p>
11
-
12
10
  <p align="center">
13
11
  <strong>English</strong> ·
14
12
  <a href="README.zh.md">简体中文</a>
15
13
  </p>
16
14
 
15
+ <p align="center">
16
+ <a href="#why-you-need-this"><img src="https://img.shields.io/badge/why-hashline-blue?style=flat" alt="why hashline"></a>
17
+ <a href="#quick-start"><img src="https://img.shields.io/badge/quick_start-30s-brightgreen?style=flat" alt="quick start 30s"></a>
18
+ <a href="#comparison"><img src="https://img.shields.io/badge/correctness-23%2F23-success?style=flat" alt="23/23 battery"></a>
19
+ </p>
20
+
17
21
  <p align="center">
18
22
  <a href="#quick-start">Quick Start</a> •
19
23
  <a href="#why-hashline">Why Hashline</a> •
20
- <a href="#benchmark">Benchmark</a> •
21
24
  <a href="#tools">Tools</a> •
25
+ <a href="#comparison">Comparison</a> •
26
+ <a href="#how-anchors-work">How Anchors Work</a> •
27
+ <a href="#development">Development</a> •
22
28
  <a href="#acknowledgments">Acknowledgments</a>
23
29
  </p>
24
30
 
25
31
  <p align="center">
26
- <img src="https://img.shields.io/badge/version-0.1.9-blue.svg" alt="Version">
32
+ <img src="https://img.shields.io/badge/version-0.3.0-blue.svg" alt="Version">
27
33
  <img src="https://img.shields.io/badge/license-MIT-green.svg" alt="MIT License">
28
34
  <img src="https://img.shields.io/badge/DeepSeek_Harness-Plugin-blueviolet.svg" alt="DeepSeek Harness Plugin">
29
35
  <img src="https://img.shields.io/npm/v/dsh-better-edit" alt="npm version">
@@ -31,32 +37,40 @@
31
37
  <img src="https://img.shields.io/github/stars/Rianico/dsh-better-edit?style=social" alt="GitHub Stars">
32
38
  </p>
33
39
 
34
- <p align="center">
35
- <img src="assets/banner.svg" alt="file.ts → read → hashed lines → edit by hash → diff" width="900">
36
- </p>
37
-
38
40
  ---
39
41
 
40
- > *"The harness — not the model — is the bottleneck."*
41
- > — Can Bölük, [*The Harness Problem*](https://stencil.so/blog/the-harness-problem)
42
-
43
- Most edit tools ask the model to echo the old code **token-for-token** before it can change anything
44
- — and that's exactly where agents fail: 46–51% patch-format failure rates for several models with
45
- replace-style edits. **dsh-better-edit** goes deeper. Every line of a file gets a unique 3-character
46
- content hash, and edits target hashes. The old text is never echoed, anchors survive edits, and every
47
- resolved range is verified against exactly what the model saw — wrong-line edits cannot silently land.
42
+ > *"The harness — not the model — is the bottleneck."* — Can Bölük, [*The Harness Problem*](https://stencil.so/blog/the-harness-problem)
43
+ >
44
+ > **This is the harness fix.** Content hashes replace line numbers — an edit above never shifts the anchor below. Every range is verified against what the agent actually saw. Stale or unseen lines are hard-rejected with fresh anchors to retry — no `read` needed.
45
+ >
46
+ > **3 tool calls vs 6 · -55.8% tokens · 23/23 correctness.** Same external-drift refactor, same correct file (single stochastic run vs OMP; [full method](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/results/2026-08-17-practical-token-benchmark.md)). Benchmark envelope numbers are deterministic — see [Benchmark](#benchmark).
48
47
 
49
48
  ## Why you need this
50
49
 
51
- `str_replace` makes the model re-type the code it's replacing — pure transcription cost (output tokens, billed ~5-6× input), and where agents fail most: 46–51% patch failures on real models, worse on bigger blocks, each failure costing a re-read and a retry.
50
+ **If you've watched an agent corrupt a file because `line 47` became `line 74` after an insert — this is for you.**
52
51
 
53
- Hashline sends two hashes instead of the old text — **31% fewer edit tokens** (43% on multi-line ranges) — and verifies every range against what the model saw: an edit lands where you meant, or fails loudly with fresh anchors. Anchors are content addresses that survive edits above, so chained edits skip re-reads — and a leaner context keeps the model's attention on the code, not on re-transcribing it.
52
+ | Before: `str_replace` / line numbers | After: hashline `edit` |
53
+ | --- | --- |
54
+ | Model re-types old code (output billed ~5-6× input) | Sends two 3-char hashes — old text is never echoed |
55
+ | One insert above shifts every number below → wrong line lands silently | Anchors are content addresses → edits above don't move anchors below |
56
+ | No check that the range matches what was shown | Every line verified against served rows; `[E_RANGE_STALE]`/`[E_RANGE_UNSERVED]` reject before any write, then **reject-and-serve** returns fresh `HASH│content` to retry |
57
+
58
+ > [!TIP]
59
+ > **Shining points — honest and measured:**
60
+ >
61
+ > - **Self-healing, not silent.** External edits never get overwritten — stale ranges are rejected and re-served as fresh `HASH│content` to retry; orphaned serves heal without a full re-read (ADR-0008). Fail-closed, not auto-merge.
62
+ > - **Formatter-tolerant.** ASCII-whitespace-insensitive anchors survive `prettier`/`black`/`eslint --fix` between edits (`formatOnSave`, watcher, CI). Linter-only assumption — whitespace inside string literals is not distinguished (ADR-0005).
63
+ > - **Chained & batched, no re-read ritual.** Anchors for untouched lines stay valid; diff/echo/reject rows count as serves. `edit` batches up to 32 same-file edits atomically (`[E_BATCH_ABORT]`), ~-40% envelope vs `str_replace` on the pinned 12-edit corpus.
64
+ > - **Read guard enforced.** Never edits what it hasn't seen — `[E_RANGE_UNSERVED]`/`[E_RANGE_UNVERIFIED]`/`[E_STALE_ANCHOR]` reject before any write, then `reject-and-serve`.
65
+ > - **Fewer round-trips in practice.** Dated run: **3 calls vs 6** for the OMP wrapper on the same external-drift refactor, same correct file; envelope vs `str_replace` is the durable number — reproducible via the upstream battery (same hashline algorithm, [method](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/results/2026-08-17-practical-token-benchmark.md)). Correctness `23/23` deterministic.
66
+
67
+ Not for one-line touch-ups (near parity) or brand-new files (`write`). It pays off in long sessions and structural edits — anywhere an edit must not land on the wrong line.
54
68
 
55
- Not for one-line touch-ups (near parity) or new files (`write`). It pays off in long sessions and structural edits — anywhere an edit must not land on the wrong line.
69
+ > Deep dive: <a href="#why-hashline">Why Hashline</a> · <a href="#comparison">Comparison</a> · <a href="benchmark/README.md">Benchmark</a>
56
70
 
57
- ## Quick Start
71
+ ## Quick Start — from install to verified edit in 30s
58
72
 
59
- ### Install
73
+ ### Install (pick one)
60
74
 
61
75
  ```sh
62
76
  npx @deepseek-ai/dsh plugin --profile web add github:Rianico/dsh-better-edit # from github
@@ -64,7 +78,7 @@ npx @deepseek-ai/dsh plugin --profile web add dsh-better-edit # from npm
64
78
  npx @deepseek-ai/dsh plugin --profile web add /path/to/dsh-better-edit # from a local checkout
65
79
  ```
66
80
 
67
- The profile's next session runs with the hashline tools installed. To verify the layer is active:
81
+ No config. The profile's next session runs with the hashline tools installed. To verify the layer is active:
68
82
 
69
83
  ```sh
70
84
  dsh --profile <name> --dump-config # shows a "# == dsh-better-edit" layer
@@ -76,6 +90,8 @@ dsh --profile <name> --dump-config # shows a "# == dsh-better-edit" layer
76
90
  | Profile | a dsh profile (`dsh plugin` initializes one on first use) |
77
91
  | Backends | sandboxed / remote filesystems supported (writes go through `ctx.fs`) |
78
92
 
93
+ ### See it work
94
+
79
95
  `read` returns every line prefixed by its hash — the hash *is* the line's address:
80
96
 
81
97
  ```text
@@ -87,242 +103,275 @@ kQm│}
87
103
  `edit` targets a range of hashes, so edits always land on the lines you meant:
88
104
 
89
105
  ```json
90
- {
91
- "path": "src/main.ts",
92
- "remove_from": "szJ",
93
- "remove_to": "szJ",
94
- "replacement_text": " console.log('hi');"
95
- }
106
+ { "path": "src/main.ts", "edits": [["szJ", "szJ", " console.log('hi');"]] }
96
107
  ```
97
108
 
98
- and produces a diff with fresh anchors, so the next edit verifies cleanly with no re-read:
109
+ and returns a diff with fresh anchors, so the next edit verifies cleanly with no re-read:
99
110
 
100
111
  ```text
101
- − szJ │ console.log("world");
112
+ - szJ │ console.log("world");
102
113
  + a3m │ console.log('hi');
103
114
  kQm │ }
104
115
  ```
105
116
 
106
- ## Configuring Guidance per Preset
117
+ Chained edits stay cheap — anchors for untouched lines remain valid, diff/echo rows count as serves, and `read` becomes on-demand recovery, not a ritual. Try batching — one `edit` call, same-file, atomic:
107
118
 
108
- The `tool:read` / `tool:edit` / `tool:batch_edit` / `tool:undo_last_edit` guidance sections are
109
- plain-markdown files, overridable per agent preset. Override files live in the plugin's shared
110
- home — never the workspace store:
111
-
112
- ```
113
- $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
119
+ ```json
120
+ { "path": "src/main.ts", "edits": [["a1b", "a1b", "new line 1\n"], ["c3d", "c3d", "new line 2"]] }
114
121
  ```
115
122
 
116
- (default home `~/.dsh`, so `~/.dsh/plugins/dsh-better-edit/`). The section table:
123
+ One fails, none write (`[E_BATCH_ABORT]`).
117
124
 
118
- | File | Section | Default order |
119
- | --- | --- | --- |
120
- | `read.md` | `tool:read` | 130 |
121
- | `edit.md` | `tool:edit` | 131 |
122
- | `batch_edit.md` | `tool:batch_edit` | 132 |
123
- | `undo_last_edit.md` | `tool:undo_last_edit` | 133 |
125
+ > [!TIP]
126
+ > **Want proof before you install?** The upstream [23/23 tool battery](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/README.md) runs with no LLM — stale edits are rejected before they corrupt a file, on every run. Same hashline algorithm, same verification.
124
127
 
125
- On first boot the plugin seeds the four shipped presets — `standard/`, `code/`,
126
- `minimal/`, `cordis/` — each with the compiled guidance as editable files (plus
127
- `order` front-matter), so every preset's guidance starts editable rather than
128
- blank. A `README.md` at the plugin-home root documents the scheme. Files are
129
- seeded once and never rewritten, so your edits survive — a reset is the one
130
- exception (see *Reset / restore defaults* below). A preset directory may
131
- hold only the sections you want to override — the rest fall through to the
132
- compiled defaults.
128
+ ## Why Hashline
133
129
 
134
- A file is pure prose unless it opens with an `order` front-matter fence, which moves the section in
135
- the assembled system prompt:
130
+ **Correctness, not just brevity.** Every resolved edit range is verified against the
131
+ served rows — what `read`, a post-edit diff, or a rejection echo actually showed the model.
132
+ A line inside the range that changed on disk since it was served, or was never served, is
133
+ hard-rejected before any file I/O: `[E_RANGE_STALE]` / `[E_RANGE_UNSERVED]` /
134
+ `[E_RANGE_UNVERIFIED]`, and the current range is echoed as fresh `HASH│content` rows. The
135
+ retry needs no `read`. Served state is session-scoped, so sub-agent serves never validate the main session's edits and vice versa.
136
136
 
137
- ```md
138
- ---
139
- order: 150
140
- ---
137
+ **Content-addressed anchors.** Anchors are derived from line content (ASCII-whitespace
138
+ stripped), not position: edit one part of a file and the hashes of the rest stay put, so
139
+ chained edits need no re-reads. Re-inserting identical text keeps its hash — "edit X with
140
+ X" doesn't rotate the anchor. Anchors are unique by construction — repeated `}` or
141
+ `import` lines never share one.
141
142
 
142
- <section text>
143
- ```
143
+ **Chained edits without re-reading.** Post-edit diff rows, auto-read rows, and rejection
144
+ echoes all count as serves. `read` is on-demand recovery, not a per-edit ritual.
144
145
 
145
- Per section, resolution reads `<preset>/<section>.md`, else the compiled
146
- default. Files are read once per agent at session-start, so edits apply to new
147
- sessions — never mid-session. A preset with no seeded directory (e.g. a
148
- user-authored one) falls back to the compiled defaults unless you copy a seeded
149
- dir to its name. A deployment without the `agentPresets` service (no preset
150
- roster) keeps the compiled defaults and never touches these files; presets are
151
- never required.
146
+ **Stop the loop.** A no-op edit reports `No changes made` and leaves anchors alone; the
147
+ same no-op re-sent three times is refused (`[E_NOOP_LOOP]`). `edit` applies up to 32
148
+ edits atomically — any stale item aborts the whole batch with `[E_BATCH_ABORT]`.
152
149
 
153
- ### Reset / restore defaults
150
+ ### Token economics: envelope savings
154
151
 
155
- Emptying or deleting an override file restores that section's compiled default
156
- guidance and order: the default renders at session-start, and the file re-seeds
157
- at next boot.
152
+ The compact JSON contract is primarily a **token-saving envelope change**. It removes repeated field names and escaped wrapper syntax while leaving the verified edit semantics unchanged:
158
153
 
159
- - **Reset = delete the file, or empty it AND remove the front-matter fence.** A whitespace-only file with no fence means "I want the default" — the compiled default renders, and the file re-seeds at next boot for any preset dir, shipped or custom.
160
- - **Blank on purpose = keep a valid fence.** Any well-formed `---` fence — even a keyless `---\n---\n`, even an empty body — is a deliberate-intent signal: the file is explicit content and is never reset or re-seeded.
161
- - **Broken fence = fast fail.** A `---` fence that does not parse (missing closing `---`, non-integer `order`, unknown key) is rejected: the malformed text is never injected into the context, the compiled default renders, a warning names the file and the reason, and the file is left untouched on disk for repair.
162
- - **Shipped vs custom.** Shipped preset files (`standard`, `code`, `minimal`, `cordis`) re-seed at boot; a deleted custom-preset override stays absent — absence is no override. Deleting a whole `<preset>/` directory re-seeds all four section files at boot (shipped presets).
163
- - **Reset restores the current bundle defaults** — a plugin upgrade yields new defaults.
154
+ - `edit` is one uniform payload: `{ "path": path, "edits": [[from, to, replacement], …] }` — `path` hoisted, arity by `edits.length`;
155
+ - replacement text is emitted once, and the old text is never repeated in the call.
164
156
 
165
- Re-seeding happens at boot, never mid-session.
157
+ #### Theoretical benchmark — serialized envelopes
166
158
 
167
- ## Why Hashline
159
+ This benchmark counts only the serialized edit payloads, not model reasoning, tool descriptions, reads, retries, or cache traffic. Same hashline algorithm as upstream — numbers reproduced from [`pi-better-edit/benchmarks/results/`](https://github.com/Rianico/pi-better-edit/tree/main/benchmarks/results) (pinned 12-edit corpus, `cl100k_base`):
160
+
161
+ | snapshot | `str_replace` | pi/dsh-better-edit: `edit` | pi/dsh-better-edit: `edit` (multi-item) | OMP: per-edit | OMP: one batch |
162
+ | --- | ---: | ---: | ---: | ---: | ---: |
163
+ | external pinned 12-edit corpus, current-envelope recount | 1,015 | 609 (**-40.0%**) | 582 (**-42.7%**) | 590 (**-41.9%**) | 480 (**-52.7%**) |
164
+ | local 12-edit configuration snapshot | 358 | 272 (**-24.0%**) | 241 (**-32.7%**) | 268 (**-25.1%**) | 180 (**-49.7%**) |
165
+
166
+ All percentages are savings against the `str_replace` value in the same row. The external row uses the pinned corpus, current object-root tuple envelopes, and current 3-character anchors. The local row is reproducible with `npm run benchmark` in the upstream repo; correctness is measured separately with the battery.
167
+
168
+ #### Practical benchmark — coding-agent session
169
+
170
+ This benchmark measures a real coding-agent loop rather than serialized envelopes. The practical advantage is round-trip efficiency: hashline completed the scenario in **3 tool calls**, versus **6 for OMP**. Upstream runs `pi` with `opencode-go/gpt-5.6-luna` at `high` thinking. Same algorithm downstream — we reference the upstream dated artifact:
171
+
172
+ | engine | tool calls | total tokens | saved vs OMP baseline | final correctness |
173
+ | --- | ---: | ---: | ---: | :---: |
174
+ | OMP patch wrapper | **6** | 28,467 | 0.0% | ✅ |
175
+ | hashline `edit` (multi-item) | **3 (fewest)** | 12,593 | **-55.8%** | ✅ |
176
+
177
+ Both engines preserved the external change and produced the expected final file in this sample. This result is one stochastic model run; it must not be read as a universal performance claim. Latest dated artifact: [2026-08-17 practical token benchmark](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/results/2026-08-17-practical-token-benchmark.md) · [hashline library battery](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/results/2026-08-17-hashline-library.md) · [tool battery](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/results/2026-08-17-tool-battery.md).
178
+
179
+ > **Scope & honesty.** These numbers are **payload + round-trip** measures, not throughput claims. The benchmark payload is deterministic; the practical run is stochastic. Dated results live upstream in `benchmarks/results/`; we do not re-run locally because the algorithm is identical.
180
+
181
+ ## Tools
182
+
183
+ | Tool | What it does |
184
+ | ------ | -------------- |
185
+ | `read` | Returns a text file with every line as `HASH│content`. `offset` (1-based), `limit`. Paged output ends with `[Showing lines N-M of T. Use offset=… to continue.]`. Lines >200KB shown as a marker with a `sed` hint — hash anchors need full lines. |
186
+ | `read_skill` | Same file read as plain text — no `HASH│` prefixes, no served rows. For skill content (SKILL.md or any file); records no serves, so editing a file read this way starts with a `[E_RANGE_UNSERVED]` serve on the first edit. |
187
+ | `edit` | An object-root payload `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], …] }`; the path may be `null` for anchor-based inference. A single item edits one range; several items batch same-file edits atomically (up to 32). Verifies every line of each inclusive range and reject-and-serve returns fresh anchors. |
188
+ | `undo_last_edit` | `{ path }` restores the most recent successful edit with its original content, BOM, line endings, and anchors; persisted across restarts. |
168
189
 
169
- **Token-saving.** An edit call carries `remove_from` / `remove_to` (two 3-char hashes) plus the
170
- replacement text — it never echoes the text being replaced. A `str_replace` call must reproduce that
171
- text verbatim. On a 12-edit session over a realistic file this is **31% fewer output tokens** (43%
172
- on multi-line ranges) — and these are *output* tokens, billed at ~5-6× the input rate. See the
173
- [benchmark](#benchmark).
174
-
175
- **But this was never about “fewest tokens.”** Savings scale with the replaced text — near parity on
176
- one-line touch-ups — and a compact patch language like [@oh-my-pi/hashline](#how-it-compares) can
177
- emit a lighter payload still (42–53% on the same session). The point is the *right* kind of edit
178
- call: no re-typing old code, and nothing for the model to track except two stable content addresses.
179
-
180
- **Correctness.** Every resolved edit range is verified against the exact lines the model was shown.
181
- A stale, never-served, or ambiguous range is hard-rejected **before anything is written**, and the
182
- current range is echoed back as fresh anchors (reject-and-serve) — the retry needs no `read`.
183
-
184
- **A modern edit pattern for agents.** Content-addressed anchors are line-number-agnostic: edit one
185
- part of a file and the hashes of the rest stay put, so chained edits need no re-reads. The model
186
- pins a line by what it *is*, not by where it used to sit.
187
-
188
- ### How It Compares
189
-
190
- | | hashline `edit` | `str_replace` (Claude Code / Codex) | @oh-my-pi/hashline patch |
191
- | --- | :---: | :---: | :---: |
192
- | Replaced text never echoed in the call | ✅ 2 hashes only | ❌ verbatim | ✅ `+` rows only |
193
- | Lines addressed by | content hash | text match | number + file-content tag |
194
- | Verified against what the model saw | ✅ every line | ❌ first match wins | ~ file version only |
195
- | Stale file detected | ✅ rejects, fresh anchors | ❌ may match wrong spot | ✅ tag mismatch → refuse or 3-way merge |
196
- | Anchors survive edits above | ✅ content-addressed | ✅ content-based | ❌ renumber + new tag |
197
- | Chained edits without re-reads | ✅ diff serves fresh anchors | ~ | ~ via edit-response numbers |
198
- | Unambiguous when text repeats | ✅ boundary anchors verified | ❌ first occurrence | ~ position, unverified per line |
199
- | Wrong-line edit never lands silently | ✅ every line verified | ❌ first match wins | ~ possible in principle (tag checks version, not lines) |
200
- | Block ops / registers / `MV` / `REM` | ❌ | ❌ | ✅ |
201
- | One document per change | ❌ per-edit call | ❌ per-edit call | ✅ multi-hunk patch |
202
- | Runtime | ✅ Node (dsh) | — | ⚠️ Bun only |
203
- | Undo | ✅ persisted | ❌ | ❌ not in scope |
204
-
205
- > `~` = occasionally / inconsistently. `@oh-my-pi/hashline` is a compact line-anchored patch language
206
- > ([npm](https://www.npmjs.com/package/@oh-my-pi/hashline), [repo](https://github.com/can1357/oh-my-pi/tree/main/packages/hashline)):
207
- > `[path#tag]` headers bind each hunk to a full-file content hash, `PUT N.=M:` addresses lines by
208
- > number, and every edit renumbers — take the next numbers and tag from the edit response or a fresh `read`.
209
-
210
- **Different jobs, same lineage.** Both descend from the
211
- [harness-problem](https://stencil.so/blog/the-harness-problem) insight that the model should never
212
- re-type old code. `@oh-my-pi/hashline` is a **patch-language library** — payload-light (42% saved
213
- per edit, 53% in a single batch document, see [benchmark](#benchmark)), with syntactic block ops
214
- (`PUT N*:`), registers, `REM`/`MV`, multi-hunk documents, a pluggable filesystem for any backend,
215
- and session-aware 3-way-merge recovery on stale tags. This plugin is a **dsh tool pair**: `read`
216
- hands the model 3-char content hashes, `edit` takes two of them, and every resolved line is verified
217
- against the served state — no line numbers to renumber, no tag to re-fetch, a wrong anchor can never
218
- land on the wrong line, and `undo_last_edit` survives restarts. Its trade-offs: a JSON envelope per
219
- edit costs a little payload, there are no block ops, and it lives inside dsh (Node) rather than as a
220
- standalone patcher (Bun). Pick hashline-the-library for a cross-backend patch format; pick
221
- hashline-the-tool for verified, content-addressed edits in your agent.
190
+ `edit` accepts `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], …] }`. The path
191
+ position is a non-empty string or `null` for unique anchor-based inference. Each range is inclusive,
192
+ and an empty replacement deletes the range. All items are checked before file I/O and applied
193
+ atomically to that one file — one item per call is the norm, several same-file items batch in one call.
194
+
195
+ ### Error codes
196
+
197
+ | Code | Meaning |
198
+ | --- | --- |
199
+ | `[E_BAD_SHAPE]` | The payload is not the fixed tuple shape, or a tuple member has an unknown, missing, or wrongly-typed value. |
200
+ | `[E_BAD_REF]` | An anchor in the inclusive range is not a bare 3-char hash. |
201
+ | `[E_STALE_ANCHOR]` | An anchor does not match any line in the current file; call `read` for fresh anchors. |
202
+ | `[E_AMBIGUOUS_ANCHOR]` | An anchor matches multiple lines; call `read` for fresh anchors. |
203
+ | `[E_INVALID_PATCH]` | A `replacement_text` line is a diff-preview row (`+HASH│`, `-HASH│`, `- │`). The marker is stripped automatically with a warning. |
204
+ | `[E_BARE_HASH_PREFIX]` | A `replacement_text` line starts with a hash-like `HASH│` prefix. The prefix is stripped automatically with a warning. |
205
+ | `[E_BAD_OP]` | Range start line is after range end line. The pair is swapped automatically with a warning. |
206
+ | `[E_WOULD_EMPTY]` | An edit would empty a non-empty file; use `write` instead. |
207
+ | `[E_NOT_FOUND]` | The path does not exist. |
208
+ | `[E_ACCESS]` | The path is not readable or writable. |
209
+ | `[E_NOT_TEXT]` | The path is a directory, binary file, image, or UTF-16/UTF-32 encoded text; hashline editing only supports text files. |
210
+ | `[E_NOT_OBSERVED]` | The file has not been observed in this session (read-before-write); call `read` first. |
211
+ | `[E_UNDO_STALE]` | `undo_last_edit` refused: the file was modified or deleted after the last edit. |
212
+ | `[E_UNDO_UNAVAILABLE]` | Undo history could not be persisted to the hash store; the `edit` was refused and the file was left unchanged. |
213
+ | `[E_FILE_TOO_LARGE]` | The file exceeds the 238,328-line hashline limit. |
214
+ | `[E_RANGE_STALE]` | A line inside the resolved edit range changed on disk since it was served (read output, diff, or rejection feedback). The edit is refused and the current range is echoed as fresh `HASH│content` rows; retry with those rows (no `read` needed). |
215
+ | `[E_RANGE_UNSERVED]` | A line inside the resolved edit range was never served to the model (paged reads, truncated output). The edit is refused and the current range is echoed as fresh `HASH│content` rows. |
216
+ | `[E_RANGE_UNVERIFIED]` | A boundary anchor (`remove_from`/`remove_to`) has no served position or was served at multiple positions, so the range cannot be verified against served state. The edit is refused and the current range is echoed as fresh `HASH│content` rows. |
217
+ | `[E_NOOP_LOOP]` | The exact same edit (same path, anchors, and replacement) was re-sent and produced no changes 3 consecutive times — the range already contains the replacement. The edit is refused and the current range is echoed as fresh `HASH│content` rows. |
218
+ | `[E_BATCH_ABORT]` | A multi-item `edit` call was rejected as a whole: an item failed validation or served-state verification. Nothing was written; the failing item's current range is echoed as fresh `HASH│content` rows. |
219
+
220
+ ## Comparison
221
+
222
+ ### Capability comparison
223
+
224
+ | | **dsh-better-edit** (this) | @oh-my-pi/hashline | `str_replace` (Claude Code / Codex) |
225
+ | --- | --- | --- | --- |
226
+ | Layer | dsh tools: `read` / `read_skill` / `edit` / `undo_last_edit` | patch-engine library: `Patcher` / `Patch` / `Filesystem` / `SnapshotStore` | built-in `str_replace` |
227
+ | Address format | `HASH│` — 3-char content hash, no line number | `[path#tag]` — full-file content tag + line numbers | text match |
228
+ | Whitespace-insensitive anchors | ✅ all ASCII whitespace stripped — survives `prettier`/`black`/`eslint --fix` | ~ n/a (anchors are line numbers) | ❌ |
229
+ | Duplicate lines | ✅ unique per line (collision-resolved); ambiguity → `[E_AMBIGUOUS_ANCHOR]` | ~ position-based — repeats fine, position unverified | ❌ first occurrence |
230
+ | Verified against what the model saw | ✅ every resolved line, per session — `[E_RANGE_STALE]`/`[E_RANGE_UNSERVED]` reject before write | ~ seen-lines provenance + file-version tag (H7) | ❌ first match wins |
231
+ | Stale interior | ✅ reject + fresh anchors (`[E_RANGE_STALE]`) | ~ recovery-with-warning, else `MismatchError` | ❌ may overwrite |
232
+ | Blind edit — lines never shown | ✅ hard reject (`[E_RANGE_UNVERIFIED]` / `[E_RANGE_UNSERVED]`) | ~ reject when seen-lines recorded (H7) | ❌ |
233
+ | Batch atomicity | ✅ `edit` multi-item — all-or-nothing, `[E_BATCH_ABORT]` | ✅ multi-section preflight (H8) | ❌ |
234
+ | Undo (persisted) | ✅ survives restarts | ❌ none | ❌ |
235
+ | Sub-agent session isolation | ✅ session-keyed served state | ~ | — |
236
+ | Deterministic battery | ✅ 23/23 | ✅ 10/10 library (own seam) | — |
237
+ | Runtime | dsh (Node) | Bun ≥ 1.3.14 (TS source) | — |
238
+
239
+ > `~` = occasionally / inconsistently. `—` = not specified / not applicable.
240
+
241
+ ### Different jobs, same lineage
242
+
243
+ Both this plugin and `@oh-my-pi/hashline` descend from the harness-problem insight that
244
+ the model should never re-type old code, but they are different layers.
245
+
246
+ `@oh-my-pi/hashline` is a **patch-language library**: `[path#tag]` headers bind every hunk
247
+ to a full-file content hash, `PUT N.=M:` addresses lines by number, and it ships multi-hunk
248
+ documents, a pluggable filesystem for any backend (disk, in-memory, network), and
249
+ session-aware 3-way-merge recovery on stale tags. Its payload per edit is lighter and it cannot
250
+ be confused by repeated text — the line number is unambiguous.
251
+ This plugin is a **dsh tool pair**: `read` hands the model 3-char content hashes, `edit`
252
+ takes two of them, and every resolved line is verified against the served state — no line
253
+ numbers to renumber, no tag to refetch, a wrong anchor can never land on the wrong line,
254
+ and `undo_last_edit` survives restarts. Its trade-offs: a JSON envelope per edit costs a
255
+ little payload, and it lives inside dsh (Node) rather than as a standalone patcher (Bun). Pick
256
+ hashline-the-library for a cross-backend patch format; pick hashline-the-tool for verified,
257
+ content-addressed edits in your agent. Syntax-aware structural edits and file-lifecycle operations
258
+ remain outside this verified line-range contract.
259
+
260
+ ### What you get
261
+
262
+ - **Verified before it writes** — every line of the resolved range is checked against served rows; stale or never-served interiors are hard-rejected (`[E_RANGE_STALE]`/`[E_RANGE_UNSERVED]`/`[E_RANGE_UNVERIFIED]`) and re-served as fresh anchors.
263
+ - **Session-keyed** — sub-agent serves never validate the main session's edits and vice versa.
264
+ - **Drift notices** — served territory outside the range that changed on disk is reported once per episode, not as a warning.
265
+ - **Chained without re-reads** — diff, auto-read, and rejection rows all count as serves.
266
+ - **Atomic batch** — up to 32 same-file edits in one `edit` call, all-or-nothing with `[E_BATCH_ABORT]`.
267
+ - **Formatter-tolerant** — ASCII-whitespace-insensitive anchors survive re-indents; unique by construction (bitset probing).
222
268
 
223
269
  ### Correctness in edge cases
224
270
 
225
- The token benchmark measures the payload the model emits — it assumes the model gets every
226
- address right, for free. Correctness is where the two hashline implementations actually diverge.
227
- These are the real failure modes from the harness-problem literature (wrong-line edits, drift,
228
- repeated text), and what each tool does when they hit:
271
+ The battery below measures *behavior*, where the two hashline implementations actually
272
+ diverge. These are the real failure modes from the harness-problem literature, and what
273
+ each tool does when they hit:
229
274
 
230
- | Edge case | hashline `edit` (this plugin) | @oh-my-pi/hashline patch |
275
+ | Edge case | hashline `edit` (this) | @oh-my-pi/hashline patch |
231
276
  | --- | --- | --- |
232
- | Wrong address (off-by-one anchor / line number) | **Impossible** — anchors resolve to specific lines; every resolved line is verified against served state, rejected **before** anything is written | **Possible** — a wrong line number against a current tag applies **silently** at the wrong place; the tag proves the file version, never the lines |
233
- | File changed on disk after the model's view | Hard reject + fresh anchors echoed (reject-and-serve); retry needs no `read` | Tag mismatch → refuse **or best-effort 3-way merge** onto unknown current content |
234
- | An edit above shifts the file | Nothing shifts — anchors are content addresses; the diff serves fresh anchors | **Every edit renumbers** — “RE-GROUND AFTER EVERY EDIT” is the format's own #1 rule; the model carries the bookkeeping |
277
+ | Wrong address (off-by-one anchor / line number) | **Impossible** — anchors resolve to specific lines; every resolved line is verified against served state, rejected before anything is written | **Possible** — a wrong line number against a current tag applies silently at the wrong place; the tag proves the file version, never the lines |
278
+ | File changed on disk after the model's view | Hard reject + fresh anchors echoed (reject-and-serve); retry needs no `read` | Tag mismatch → refuse **or** best-effort 3-way merge onto unknown current content, with an explicit recovery banner |
279
+ | An edit above shifts the file | Nothing shifts — anchors are content addresses; the diff serves fresh anchors | **Every edit renumbers** — the format's own #1 rule is "re-ground after every edit"; the model carries the bookkeeping |
235
280
  | Repeated / identical text | Per-line hashes are unique (collision-resolved); ambiguity → `[E_AMBIGUOUS_ANCHOR]` | Position-based, so repeats don't confuse it — but the position itself is unverified |
236
- | Lines never shown to the model | `[E_RANGE_UNSERVED]` — hard reject with fresh anchors | Undisplayed hunks rejected — same reliance on the model knowing what it saw |
237
- | Mid-expression / wrong block node | Irrelevant — any verified line range is valid | Grammar rules + `PUT N*:` node choice; mispointing (anchoring `def` orphans its decorator) silently lands wrong; no syntax check |
238
- | Multi-edit batch fails mid-way | `batch_edit` — atomic, all-or-nothing; the failing item is echoed as fresh serves | Multi-section patches preflighted up front — also atomic |
281
+ | Lines never shown to the model | `[E_RANGE_UNSERVED]` — hard reject with fresh anchors | Undisplayed hunks rejected when seen-lines are recorded — same reliance on the model knowing what it saw |
282
+ | Multi-edit batch fails mid-way | `edit` multi-item — atomic, all-or-nothing; the failing item is echoed as fresh serves | Multi-section patches preflighted up front — also atomic |
239
283
 
240
- > The 42–53% oh-my-pi payload saving is a lighter wire format; the table above is what that
241
- > format asks the model to hold in its head instead — renumbering, tag-chasing, node choice —
242
- > the exact component that fails most (46–51% patch-failure rates on replace-style edits). This
243
- > plugin's 31% is the price of a contract where a wrong edit cannot land, and any rejection
244
- > needs no re-read.
284
+ > The oh-my-pi payload saving is a lighter wire format; the table above is what that format
285
+ > asks the model to hold in its head instead — renumbering, tag-chasing — the
286
+ > exact component that fails most with replace-style edits. This plugin's contract is:
287
+ > a wrong edit cannot land, and any rejection needs no re-read. Both engines gate the same guarantee — **stale edits are detected, never silently applied** — with different policies when drift is found (recover-with-warning vs fail-closed rejection).
245
288
 
246
- ## Benchmark
289
+ ### Reproducible benchmark
247
290
 
248
- Measured on the same 103-line file with the same 12 replacements (8 single-line, 4 multi-line of
249
- 3/6/10/15 lines), tokenized with the pinned `js-tiktoken` `cl100k_base`. Three arms emit the same
250
- replacements: this plugin's `edit` (two 3-char anchors), a `str_replace` tool (old text echoed
251
- verbatim), and [`@oh-my-pi/hashline`](https://www.npmjs.com/package/@oh-my-pi/hashline) in both of
252
- its modes — one `[path#tag]` section per edit (`seq`) and one multi-hunk batch document (`batch`):
291
+ The claims above are measured, not asserted. Two deterministic batteries — no LLM in the
292
+ loop, no sampling: a run either reproduces or it doesn't.
253
293
 
254
- | Criterion | hashline | str_replace | oh-my-pi seq / batch |
255
- | ----------- | :---: | :---: | :---: |
256
- | Replaced text sent over the wire | ✅ never | ❌ every edit | ✅ never |
257
- | Output tokens saved (12-edit session) | ✅ **31%** | ❌ 0% | ✅ **42% / 53%** |
258
- | Multi-line range savings (3–15 lines) | ✅ **29–47%** | ❌ 0% | ✅ **40–53%** |
259
- | Effective cost at 5× output pricing | ✅ **~1.4× less** | ❌ 1× | ✅ **~1.7× / ~2.1× less** |
260
- | Ranges verified against served state | ✅ 100% | ❌ none | ~ file version only |
261
- | Line numbers the model must track | ✅ none — content anchors | ✅ none — text match | ❌ renumber every edit |
262
- | Deterministic, reproducible locally | ✅ `npm run benchmark` | — | — |
294
+ **Tool battery — 23 scenarios (2026-08-17):**
263
295
 
264
- ### Reproducible
296
+ | vs expected verdict | correct | silent data-loss cases |
297
+ | --- | --: | --: |
298
+ | **dsh-better-edit** (same algorithm as pi-better-edit 1.1.4) | **23/23** | 0 |
265
299
 
266
- The numbers above are **deterministic and you can reproduce them locally** — `npm run benchmark`:
300
+ Reproduce via upstream: `npm run eval` in `pi-better-edit` (this plugin shares the hashline algorithm byte-for-byte). Library battery for `@oh-my-pi/hashline` is 10/10 separately.
267
301
 
268
- | Scenario | Lines | hashline | str_replace | oh-my-pi seq | oh-my-pi batch |
269
- | --- | :---: | :---: | :---: | :---: | :---: |
270
- | single-line ×8 | 1 | 309 | 324 | 241 | — |
271
- | multi-line ×4 | 3–15 | 393 | 691 | 349 | — |
272
- | **TOTAL ×12** | | **702** | **1015** | **590** | **480** |
302
+ Full method, per-scenario tables, and limitations: upstream [benchmarks/README.md](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/README.md)
303
+ and [benchmarks/results/](https://github.com/Rianico/pi-better-edit/tree/main/benchmarks/results).
273
304
 
274
- Saved vs `str_replace`: hashline **313 (31%)** · oh-my-pi per-edit **425 (42%)** · oh-my-pi batch **535 (53%)**.
305
+ ## Configuring Guidance per Preset
275
306
 
276
- The script is deterministic by construction: a frozen corpus, a content-addressed edit script that
277
- self-checks (a reformatted corpus throws instead of silently changing what's measured), a pinned
278
- tokenizer, and oh-my-pi payloads validated against the package's published grammar before counting.
279
- Because everything is fixed, `npm run benchmark` gives everyone the same result — the numbers in
280
- this README are a snapshot of that run; regenerate, don't trust.
307
+ The `tool:read` / `tool:edit` / `tool:undo_last_edit` guidance sections are
308
+ plain-markdown files, overridable per agent preset. Override files live in the plugin's shared
309
+ home — never the workspace store:
281
310
 
282
- > **Scope & honesty.** The benchmark measures **request-payload tokens** — what the model emits per
283
- > edit call — with identical read traffic excluded (it cancels) and identical replacement text.
284
- > It does **not** model transcription failure and retries, which is where the real-world gap is
285
- > largest: the original [harness-problem](https://stencil.so/blog/the-harness-problem) post reported
286
- > a **61% output-token reduction** and patch-failure drops from 46–51% to near zero after switching
287
- > to anchored edits. It also does **not** model what a line-numbered format costs the model *between*
288
- > calls — renumbering and re-fetching the file tag after every edit — nor block-op power, nor the
289
- > Bun-vs-Node runtime difference, nor the fact that `@oh-my-pi/hashline` is a standalone patcher
290
- > while this plugin is a dsh tool pair with `read`/`edit`/`undo`. Full methodology, the per-edit
291
- > table, and the complete limitation list in [`benchmark/README.md`](benchmark/README.md). The correctness gap behind those numbers is spelled out above in [Correctness in edge cases](#correctness-in-edge-cases).
311
+ ```
312
+ $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
313
+ ```
292
314
 
293
- ## Tools
315
+ (default home `~/.dsh`, so `~/.dsh/plugins/dsh-better-edit/`). The section table:
294
316
 
295
- | Tool | What it does |
296
- | ------ | -------------- |
297
- | `read` | Returns a file with every line as `HASH│content`. Parameters: `offset` (1-based), `limit`. Paged output ends with `[Showing lines N-M of T. Use offset=… to continue.]`. Lines >200KB are shown as a marker with a `sed` hint — hash anchors need full lines. |
298
- | `edit` | Replaces a range of lines by hash. `path` · `remove_from` · `remove_to` · `replacement_text` (`""` deletes). Verifies **every line** of the resolved range against served state; `[E_RANGE_STALE]` / `[E_RANGE_UNSERVED]` / `[E_RANGE_UNVERIFIED]` reject-and-serve fresh anchors. |
299
- | `batch_edit` | Up to 32 edits in one atomic call: `{ edits: [{ path?, remove_from, remove_to, replacement_text }, …] }`. All-or-nothing; the failing item's range is echoed as fresh serves. |
300
- | `undo_last_edit` | `{ path }` reverts the last hashline edit, only while the file still matches the stored post-edit content; survives restarts. |
317
+ | File | Section | Default order |
318
+ | --- | --- | --- |
319
+ | `read.md` | `tool:read` | 130 |
320
+ | `edit.md` | `tool:edit` | 131 |
321
+ | `undo_last_edit.md` | `tool:undo_last_edit` | 133 |
301
322
 
302
- ### Error codes
323
+ On first boot the plugin seeds the three shipped presets — `standard/`, `code/`,
324
+ `minimal/`, `cordis/` — each with the compiled guidance as editable files (plus
325
+ `order` front-matter), so every preset's guidance starts editable rather than
326
+ blank. A `README.md` at the plugin-home root documents the scheme. Files are
327
+ seeded once and never rewritten, so your edits survive — a reset is the one
328
+ exception (see *Reset / restore defaults* below).
303
329
 
304
- | Code | Meaning |
305
- | --- | --- |
306
- | `[E_ACCESS]` | File exists but is not readable/writable by the tool. |
307
- | `[E_AMBIGUOUS_ANCHOR]` | A hash matches more than one current line; call `read` for fresh anchors. |
308
- | `[E_BAD_OP]` | Range end precedes range start (autocorrected when the pair was reversed). |
309
- | `[E_BAD_REF]` | `remove_from`/`remove_to` is not a bare 3-char hash. |
310
- | `[E_BAD_SHAPE]` | Request/field shape is wrong (unknown fields, missing path, non-string text, …). |
311
- | `[E_BARE_HASH_PREFIX]` | `HASH│` prefix pasted into `replacement_text` (autocorrected). |
312
- | `[E_BATCH_ABORT]` | A batch item failed; the whole batch was rejected, nothing written. |
313
- | `[E_FILE_TOO_LARGE]` | File exceeds the hashline line ceiling; use `write` or another approach. |
314
- | `[E_INVALID_PATCH]` | Diff-preview markers pasted into `replacement_text` (autocorrected). |
315
- | `[E_NOOP_LOOP]` | The exact same edit keeps producing no change; resubmitting is rejected. |
316
- | `[E_NOT_FOUND]` | File does not exist. |
317
- | `[E_NOT_OBSERVED]` | The file has not been observed in this session (read-before-write policy); call `read` first. |
318
- | `[E_NOT_TEXT]` | Path is a directory, binary, or non-UTF-8 file; hashline edits only text. |
319
- | `[E_RANGE_STALE]` | A served line differs on disk since it was read; the range is echoed fresh. |
320
- | `[E_RANGE_UNSERVED]` | The range includes lines never served to the model. |
321
- | `[E_RANGE_UNVERIFIED]` | Boundary anchor cannot be verified against served state. |
322
- | `[E_STALE_ANCHOR]` | Anchor(s) no longer resolve; call `read` for fresh anchors. |
323
- | `[E_UNDO_STALE]` | Cannot undo: the file was modified (or deleted) after the edit. |
324
- | `[E_UNDO_UNAVAILABLE]` | Undo history could not be persisted; the edit was not applied. |
325
- | `[E_WOULD_EMPTY]` | An edit would empty a non-empty file; use `write` to clear it. |
330
+ ### Reset / restore defaults
331
+
332
+ Emptying or deleting an override file restores that section's compiled default
333
+ guidance and order: the default renders at session-start, and the file re-seeds
334
+ at next boot.
335
+
336
+ - **Reset = delete the file, or empty it AND remove the front-matter fence.** A whitespace-only file with no fence means "I want the default" — the compiled default renders, and the file re-seeds at next boot for any preset dir, shipped or custom.
337
+ - **Blank on purpose = keep a valid fence.** Any well-formed `---` fence — even a keyless `---\n---\n`, even an empty body — is a deliberate-intent signal: the file is explicit content and is never reset or re-seeded.
338
+ - **Broken fence = fast fail.** A `---` fence that does not parse (missing closing `---`, non-integer `order`, unknown key) is rejected: the malformed text is never injected into the context, the compiled default renders, a warning names the file and the reason, and the file is left untouched on disk for repair.
339
+ - **Shipped vs custom.** Shipped preset files (`standard`, `code`, `minimal`, `cordis`) re-seed at boot; a deleted custom-preset override stays absent — absence is no override. Deleting a whole `<preset>/` directory re-seeds all three section files at boot (shipped presets).
340
+ - **Reset restores the current bundle defaults** — a plugin upgrade yields new defaults.
341
+
342
+ Re-seeding happens at boot, never mid-session.
343
+
344
+ ## How Anchors Work
345
+
346
+ Each line is canonicalized (all ASCII whitespace — spaces, tabs, carriage returns, and
347
+ line feeds — stripped) and hashed with [xxhash-wasm](https://github.com/jungomi/xxhash-wasm)
348
+ (xxHash32), then mapped to a 3-character string over `A-Za-z0-9` — 62³ = 238,328 possible
349
+ anchors. Canonicalization keeps anchors stable across formatting passes and editor-save
350
+ cycles: a line that changes only in ASCII whitespace keeps its anchor, so external linting
351
+ between edits does not invalidate it. Everything that is not ASCII whitespace stays
352
+ significant — string contents, regex classes, comments, quotes, semicolons, and Unicode
353
+ whitespace (NBSP) all rotate the anchor. One caveat: ASCII whitespace *inside* string
354
+ literals and regexes is stripped too, so a whitespace-only change within a string is
355
+ invisible to verification — benign in practice because formatters never alter string
356
+ contents. Token-level edits (quote style, semicolons, brace placement) therefore still
357
+ reject as stale.
358
+
359
+ The alphabet is sized for an LLM consumer — the model tokenizes rather than squinting at
360
+ glyphs, so case and digits are all included. The URL-safe specials `-` and `_` are
361
+ deliberately excluded: a hash starting with `-` is shape-identical to a diff-preview
362
+ deletion row, and `-`/`_` at a line start are markdown-active, inviting mis-copying.
363
+
364
+ Anchors are unique by construction. If a line's base hash collides with an already-assigned
365
+ hash, the next free hash is allocated from a bitset by probing with a stride coprime to the
366
+ hash space (O(1) amortized; the stride is 62² + 62 + 1, so runs of blank lines or repeated
367
+ `}` land on anchors that differ in all three characters). Every line therefore gets a
368
+ unique anchor; two byte-identical lines never share one. The same guarantee sets the file
369
+ size cap: at most 238,328 lines per file, beyond which `read` and `edit` reject with
370
+ `[E_FILE_TOO_LARGE]` (use `write` for very large files).
371
+
372
+ Hashes live in a persistent per-file store
373
+ (`<workspace>/.dsh_better_edit/hash-store.sqlite`, honoring `XDG_CONFIG_HOME` on
374
+ non-Windows) that keeps the hashes of unchanged lines across edits.
326
375
 
327
376
  ## How It Replaces the Built-in Tools
328
377
 
@@ -352,26 +401,24 @@ call (tests, previews) the store falls back to the shared DeepSeek Harness home
352
401
  (`$DSH_HOME/plugins/dsh-better-edit/hash-store.sqlite`).
353
402
 
354
403
  A 7-day TTL prunes served rows; missing-file snapshots are pruned at startup. Corrupt stores are
355
- quarantined and rebuilt automatically. Moving to the per-workspace layout does not migrate earlier
356
- undo history from the shared home — treat any pre-0.1.2 undo entries as gone.
404
+ quarantined and rebuilt automatically.
357
405
 
358
406
  ## Project Structure
359
407
 
360
408
  ```
361
409
  dsh-better-edit/
362
410
  ├── src/
363
- │ ├── hashline/ # hash + served-state core (ported byte-for-byte from pi-hashline-edit-lsz)
411
+ │ ├── hashline/ # hash + served-state core (ported from pi-better-edit)
364
412
  │ ├── tool-read.ts # read — HASH│content, offset/limit paging
365
- │ ├── tool-edit.ts # edit — range-by-hash, reject-and-serve
366
- │ ├── tool-batch-edit.ts
413
+ │ ├── tool-edit.ts # edit — {path, edits:[[hash,hash,text]]}, reject-and-serve
367
414
  │ ├── tool-undo.ts # undo_last_edit
368
415
  │ ├── sandbox.ts # FsSandboxController mirror (sandbox_permissions/justification)
369
416
  │ ├── write-hook.ts # auto-read appended to write results
370
417
  │ ├── served-store.ts # per-workspace SQLite store (node:sqlite)
371
418
  │ └── workspace.ts # session-cwd AsyncLocalStorage carrier
372
- ├── benchmark/ # reproducible hashline-vs-str_replace-vs-oh-my-pi token benchmark
419
+ ├── benchmark/ # frozen 103-line fixture (reference upstream for reproducible numbers)
373
420
  │ └── corpus/ # frozen 103-line fixture
374
- ├── test/ # 615 tests (ported + regression)
421
+ ├── test/ # ported + regression tests
375
422
  ├── assets/ # logo + banner
376
423
  ├── cordis.patch.yml # bundle patch
377
424
  └── package.json # dsh.bundle manifest
@@ -382,15 +429,14 @@ dsh-better-edit/
382
429
  ```sh
383
430
  npm install
384
431
  npm run typecheck # tsc --noEmit
385
- npm test # vitest run (615 tests)
432
+ npm test # vitest run
386
433
  npm run build # tsc → lib/
387
- npm run benchmark # reproducible token-cost benchmark (benchmark/)
388
434
  ```
389
435
 
390
436
  ### Releasing (tag-first)
391
437
 
392
438
  ```sh
393
- npm run release -- 0.2.0 # bump + CHANGELOG move + commit + tag + push → GitHub release
439
+ npm run release -- 0.3.0 # bump + CHANGELOG move + commit + tag + push → GitHub release
394
440
  npm publish --registry https://registry.npmjs.org # blocked until the version is tagged
395
441
  ```
396
442
 
@@ -399,35 +445,60 @@ version, commits, tags `vX.Y.Z`, and pushes — the tag push creates the GitHub
399
445
  changelog. `npm publish` refuses to run until that tag exists (prepublishOnly gate), so every npm
400
446
  version is always already tagged and released.
401
447
 
402
- The test suite is ported from pi-hashline-edit-lsz and drives the dsh tool builders directly over a
403
- local filesystem bridge.
448
+ ## Benchmark
449
+
450
+ Measured on the same 103-line file with the same 12 replacements (8 single-line, 4 multi-line of
451
+ 3/6/10/15 lines), tokenized with the pinned `js-tiktoken` `cl100k_base`. Three arms emit the same
452
+ replacements: this plugin's `edit` (two 3-char anchors via `edits` tuple), a `str_replace` tool (old text echoed
453
+ verbatim), and [`@oh-my-pi/hashline`](https://www.npmjs.com/package/@oh-my-pi/hashline) in both of
454
+ its modes — one `[path#tag]` section per edit (`seq`) and one multi-hunk batch document (`batch`). Same hashline algorithm, so we reference the upstream reproducible results:
455
+
456
+ | Criterion | hashline | str_replace | oh-my-pi seq / batch |
457
+ | ----------- | :---: | :---: | :---: |
458
+ | Replaced text sent over the wire | ✅ never | ❌ every edit | ✅ never |
459
+ | Output tokens saved (12-edit session) | ✅ **31%** | ❌ 0% | ✅ **42% / 53%** |
460
+ | Multi-line range savings (3–15 lines) | ✅ **29–47%** | ❌ 0% | ✅ **40–53%** |
461
+ | Effective cost at 5× output pricing | ✅ **~1.4× less** | ❌ 1× | ✅ **~1.7× / ~2.1× less** |
462
+ | Ranges verified against served state | ✅ 100% | ❌ none | ~ file version only |
463
+ | Line numbers the model must track | ✅ none — content anchors | ✅ none — text match | ❌ renumber every edit |
464
+ | Deterministic, reproducible locally | ✅ via upstream `npm run benchmark` | — | — |
465
+
466
+ | Scenario | Lines | hashline | str_replace | oh-my-pi seq | oh-my-pi batch |
467
+ | --- | :---: | :---: | :---: | :---: | :---: |
468
+ | single-line ×8 | 1 | 309 | 324 | 241 | — |
469
+ | multi-line ×4 | 3–15 | 393 | 691 | 349 | — |
470
+ | **TOTAL ×12** | | **702** | **1015** | **590** | **480** |
471
+
472
+ Saved vs `str_replace`: hashline **313 (31%)** · oh-my-pi per-edit **425 (42%)** · oh-my-pi batch **535 (53%)**.
473
+
474
+ Upstream is the source of truth for reproducibility: [`pi-better-edit/benchmark/README.md`](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/README.md) and [`benchmarks/results/`](https://github.com/Rianico/pi-better-edit/tree/main/benchmarks/results). This plugin shares the hashline algorithm byte-for-byte, so we do not re-run locally.
475
+
476
+ > **Scope & honesty.** The benchmark measures **request-payload tokens** — what the model emits per
477
+ > edit call — with identical read traffic excluded (it cancels) and identical replacement text.
478
+ > It does **not** model transcription failure and retries, which is where the real-world gap is
479
+ > largest. The correctness gap behind those numbers is spelled out above in [Correctness in edge cases](#correctness-in-edge-cases).
404
480
 
405
481
  ## Roadmap
406
482
 
407
- **Current state (0.1.6):** 615 tests, per-workspace store, sandbox policy participation, the
408
- served-tail truncation fix, reproducible benchmark, EN + 中文 READMEs, published on npm.
483
+ **Current state (0.3.0):** hashline `edit` with merged payload `{path, edits:[[hash,hash,text]]}`, whitespace-insensitive anchors, orphan healing, per-workspace store, 674 tests.
409
484
 
410
485
  <details><summary>Next</summary>
411
486
 
412
- - **Close or justify the gap vs @oh-my-pi/hashline** (reference: [`../oh-my-pi.md`](../oh-my-pi.md)). The sibling patch language is payload-lighter — 42%/53% vs our 31% vs `str_replace` on the benchmark, because a bare patch document skips the JSON envelope we pay per call — and offers four abilities we do not support: syntactic block ops (`PUT N*:`), registers + `REM`/`MV`, one multi-hunk document per change, and a pluggable filesystem. The counterweight is correctness: its line numbers are unverified (a wrong number on a current tag lands silently), every edit renumbers, stale tags trigger best-effort 3-way merge instead of verification, and the grammar raises the model skill floor. Decide each ability reject-or-adopt on its own merits — the payload gap alone is not a reason to switch formats.
413
- - Verify 0.1.6 live in a dsh session after the served-tail fix.
414
- - Upstream the served-tail truncation fix to pi-hashline-edit-lsz / upstream (their `upsertServed`
415
- never truncates either).
416
- - Re-check plugin wiring against the next dsh release (pinned to `0.1.0-rc.6`; dsh is in developer
417
- preview and promises breaking changes).
487
+ - Verify 0.3.0 live in a dsh session after the orphan-healing + canon changes.
488
+ - Keep benchmark reference in sync with upstream releases (algorithm is shared).
489
+ - Re-check plugin wiring against the next dsh release (pinned to `0.1.0-rc.6`; dsh is in developer preview and promises breaking changes).
418
490
 
419
491
  </details>
420
492
 
421
493
  ## Contributing
422
494
 
423
495
  See [CONTRIBUTING.md](CONTRIBUTING.md) (or just open an [issue](https://github.com/Rianico/dsh-better-edit/issues)).
424
- The most valuable contributions right now are more benchmark scenarios and edge-case tests for the
496
+ The most valuable contributions right now are more edge-case tests for the
425
497
  served-state verification.
426
498
 
427
499
  ## License
428
500
 
429
- MIT License — see [LICENSE](LICENSE) for details. Ported from pi-hashline-edit-lsz (MIT), which
430
- itself carries the upstream copyrights of RimuruW and YuGiMob.
501
+ MIT License — see [LICENSE](LICENSE) for details. Ported from pi-better-edit.
431
502
 
432
503
  ## Acknowledgments
433
504
 
@@ -437,12 +508,14 @@ harness, not the model, is the bottleneck, and that anchored edits beat search-a
437
508
  project stands on the shoulders of:
438
509
 
439
510
  - [**pi-hashline-edit**](https://github.com/RimuruW/pi-hashline-edit) by RimuruW — the original
440
- pi-coding-agent extension that introduced 3-character hashes and collision resolution.
441
- - [**pi-hashline-edit-pro**](https://github.com/YuGiMob/pi-hashline-edit-pro) by YuGiMob — the
442
- hardened fork the hashline core here is ported from.
443
- - [**pi-hashline-edit-lsz**](https://github.com/Rianico/pi-hashline-edit-lsz) — the self-maintained
444
- fork this project tracks. The hashline core is ported byte-for-byte; the tool layer is rewritten
445
- on dsh's plugin API.
511
+ pi-coding-agent extension that introduced hash anchors and the strict-semantics
512
+ policy.
513
+ - [**pi-hashline-edit-pro**](https://github.com/YuGiMob/pi-hashline-edit-pro) by YuGiMob —
514
+ the hardened fork this project is self-maintained from (3-char hashes, collision
515
+ resolution, served-state verification, persisted undo).
516
+ - [**pi-better-edit**](https://github.com/Rianico/pi-better-edit) — the upstream this project tracks. The hashline core is ported; the tool layer is rewritten on dsh's plugin API.
517
+ - [**@oh-my-pi/hashline**](https://www.npmjs.com/package/@oh-my-pi/hashline)
518
+ by can1357 — the original oh-my-pi implementation and the hashline patch-language concept.
446
519
 
447
520
  Related reading: [Hash anchors + Myers diff + single-token anchors
448
521
  (dirac.run)](https://dirac.run/posts/hash-anchors-myers-diff-single-token) (a design review of the