dsh-better-edit 0.1.8 → 0.2.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 (52) hide show
  1. package/CHANGELOG.md +28 -6
  2. package/README.md +27 -7
  3. package/README.zh.md +24 -7
  4. package/assets/logo.svg +183 -18
  5. package/lib/contract.js +95 -0
  6. package/lib/drift.js +1 -1
  7. package/lib/edit-diff.js +2 -2
  8. package/lib/edit-engine.js +456 -0
  9. package/lib/edit-pipeline.js +41 -116
  10. package/lib/file-reader.js +1 -2
  11. package/lib/fs-bridge.js +2 -2
  12. package/lib/fs-write.js +3 -46
  13. package/lib/hash-store.js +246 -13
  14. package/lib/hashline/apply.js +2 -2
  15. package/lib/hashline/hash.js +16 -206
  16. package/lib/hashline/index.js +4 -3
  17. package/lib/hashline/parse.js +1 -1
  18. package/lib/hashline/pure.js +213 -0
  19. package/lib/hashline/resolve.js +1 -5
  20. package/lib/hashline/served.js +2 -2
  21. package/lib/paths.js +55 -1
  22. package/lib/read-and-serve.js +46 -0
  23. package/lib/schema.js +1 -1
  24. package/lib/served-store.js +144 -183
  25. package/lib/tool-batch-edit.js +28 -280
  26. package/lib/tool-edit.js +37 -32
  27. package/lib/tool-read.js +8 -31
  28. package/lib/tool-undo.js +4 -13
  29. package/lib/types/contract.d.ts +39 -0
  30. package/lib/types/edit-engine.d.ts +179 -0
  31. package/lib/types/edit-pipeline.d.ts +10 -17
  32. package/lib/types/fs-write.d.ts +0 -1
  33. package/lib/types/hash-store.d.ts +73 -25
  34. package/lib/types/hashline/hash.d.ts +8 -13
  35. package/lib/types/hashline/index.d.ts +4 -3
  36. package/lib/types/hashline/pure.d.ts +26 -0
  37. package/lib/types/hashline/resolve.d.ts +0 -1
  38. package/lib/types/paths.d.ts +9 -0
  39. package/lib/types/read-and-serve.d.ts +39 -0
  40. package/lib/types/schema.d.ts +2 -16
  41. package/lib/types/served-store.d.ts +63 -32
  42. package/lib/types/tool-batch-edit.d.ts +4 -1
  43. package/lib/types/tool-undo.d.ts +1 -1
  44. package/lib/undo-edit.js +16 -1
  45. package/lib/write-hook.js +30 -50
  46. package/package.json +4 -3
  47. package/lib/served-state.js +0 -34
  48. package/lib/snapshot-store.js +0 -108
  49. package/lib/types/served-state.d.ts +0 -3
  50. package/lib/types/snapshot-store.d.ts +0 -14
  51. package/lib/types/undo-store.d.ts +0 -14
  52. package/lib/undo-store.js +0 -43
package/CHANGELOG.md CHANGED
@@ -2,6 +2,28 @@
2
2
 
3
3
  All notable changes to the `dsh-better-edit` plugin will be documented in this file.
4
4
 
5
+ Entries link to the originating spec issue in [pi-hashline-edit-lsz](https://github.com/Rianico/pi-hashline-edit-lsz) where one exists.
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.2.0] - 2026-08-16
10
+
11
+ ### Changed
12
+
13
+ - Architecture deepening across six refactors (GitHub issues #1–#6), with the model-facing contract unchanged — every `[E_…]` code and message byte-identical, full suite green (615 → 626 tests):
14
+ - Served state (what the model has been shown) now lives in one async module: the doubled sync/async store interface (whose sync half had zero production callers) is gone, and the served-row merge invariant — stale tail / duplicate anchors — is one shared helper with a regression test.
15
+ - `edit` and `batch_edit` run on one edit-sequence engine — apply-one, the multi-edit sequencer, the noop-loop guard, and the persist-undo → write → restore transaction — replacing `batch_edit`'s duplicated 685-line pipeline with a thin orchestrator. Batch apply, atomic batch rejection, and undo revert are now covered by end-to-end tests.
16
+ - The hashline anchor math is a pure module (no store imports); persistence is a thin wrapper over it. The public hashline interface shrank to the consumer call surface.
17
+ - The `read` tool and the write auto-read share one read-and-serve operation; canonical path resolution moved out of the write module into the path helpers.
18
+ - All four tools validate requests through one contract module — field sets and the `[E_BAD_SHAPE]` vocabulary declared once.
19
+ - The hash store exposes domain APIs (snapshots / undo / served) instead of raw prepared statements; corruption handling and cross-table cleanup are owned by the store, and the import graph is acyclic.
20
+
21
+ ## [0.1.9] - 2026-08-15
22
+
23
+ ### Changed
24
+
25
+ - READMEs (English and 中文): added a concise "Why you need this" opening section — the transcription cost and 46–51% patch-failure rate of `str_replace`, the 31%/43% edit-token savings, verified landing, and the leaner-context benefit (the model's attention stays on the code, not on re-transcribing it) — placed before Quick Start so the demo stays immediately visible. Fixed the stale static version badge.
26
+
5
27
  ## [0.1.8] - 2026-08-15
6
28
 
7
29
  ### Added
@@ -32,15 +54,15 @@ All notable changes to the `dsh-better-edit` plugin will be documented in this f
32
54
 
33
55
  ### Added
34
56
 
35
- - Reproducible token-cost benchmark (`benchmark/run.mjs` + frozen 103-line corpus + methodology): hashline vs `str_replace` on the same file with the same 12 replacements — 28% fewer output tokens over the session (40% on multi-line ranges), ~1.4× cheaper on effective cost at the 5× output-token rate. Deterministic: content-addressed self-checking edit script, pinned `js-tiktoken` `cl100k_base` devDependency. Run with `npm run benchmark`.
57
+ - Reproducible token-cost benchmark (`benchmark/run.mjs` + frozen 103-line corpus + methodology): hashline vs `str_replace` on the same file with the same 12 replacements — 31% fewer output tokens over the session (43% on multi-line ranges), ~1.4× cheaper on effective cost at the 5× output-token rate. Deterministic: content-addressed self-checking edit script, pinned `js-tiktoken` `cl100k_base` devDependency. Run with `npm run benchmark`.
36
58
  - README rewritten around the three pillars — token-saving, correctness, and the modern content-addressed edit pattern — with Mermaid diagrams, a `str_replace` comparison table, and an inspiration/lineage section (The Harness Problem, pi-hashline-edit, pi-hashline-edit-pro, pi-hashline-edit-lsz).
37
59
 
38
60
  ## [0.1.4] - 2026-08-15
39
61
 
40
62
  ### Fixed
41
63
 
42
- - `E_RANGE_UNVERIFIED` ("served at N positions") on edits after a shrinking write: the served-state array was upserted by position but never truncated to the file's current line count, so a stale tail kept a surviving line's hash at its OLD position while the current serve held it at its new one. `recordServed`/`recordServes` now take the current line count and truncate before upserting, threaded from every whole-file serve — read, write auto-read, drift rows, and all rejection-echo sites. Regression test covers the 8-line→2-line write case.
43
- - The same never-truncate behavior exists in pi-hashline-edit-lsz / upstream (`upsertServed`); the fix is a candidate to upstream.
64
+ - `E_RANGE_UNVERIFIED` ("served at N positions") on edits after a shrinking write: the served-state array was upserted by position but never truncated to the file's current line count, so a stale tail kept a surviving line's hash at its OLD position while the current serve held it at its new one. `recordServed`/`recordServes` now take the current line count and truncate before upserting, threaded from every whole-file serve — read, write auto-read, drift rows, and all rejection-echo sites. Regression test covers the 8-line→2-line write case ([Rianico/pi-hashline-edit-lsz#27](https://github.com/Rianico/pi-hashline-edit-lsz/issues/27)).
65
+ - The fix is a candidate to upstream into pi-hashline-edit-lsz / upstream, whose `upsertServed` has the same never-truncate behavior (tracked in [Rianico/pi-hashline-edit-lsz#27](https://github.com/Rianico/pi-hashline-edit-lsz/issues/27)).
44
66
 
45
67
  ## [0.1.3] - 2026-08-15
46
68
 
@@ -65,9 +87,9 @@ All notable changes to the `dsh-better-edit` plugin will be documented in this f
65
87
 
66
88
  ### Added
67
89
 
68
- - Initial dsh port of pi-hashline-edit-lsz: hash-anchored `read` / `edit` / `batch_edit` / `undo_last_edit` tools for DeepSeek Harness. Every line gets a unique 3-character content hash; edits target `remove_from`/`remove_to` hashes. The hashline core is ported byte-for-byte; the tool layer is rewritten on dsh's plugin API.
90
+ - Initial dsh port of pi-hashline-edit-lsz: hash-anchored `read` / `edit` / `batch_edit` / `undo_last_edit` tools for DeepSeek Harness. Every line gets a unique 3-character content hash; edits target `remove_from`/`remove_to` hashes. The hashline core is ported byte-for-byte; the tool layer is rewritten on dsh's plugin API ([batch_edit spec: Rianico/pi-hashline-edit-lsz#19](https://github.com/Rianico/pi-hashline-edit-lsz/issues/19)).
69
91
  - Built-in replacement via scope-layered registry shadowing: on `agent/session-start` the tools and the `tool:read`/`tool:edit` prompt sections are registered on the agent's own layer (own-layer-wins), unwinding automatically on disposal; a `tools/post-execute` listener appends the auto-read to built-in `write` results.
70
- - Served-state range verification with reject-and-serve: every line of the resolved range is checked against what the model was shown; stale/never-served/unverified ranges are hard-rejected with the current `HASH│content` rows echoed back (retry needs no `read`). Drift notices report served territory changed outside the edit range.
92
+ - Served-state range verification with reject-and-serve: every line of the resolved range is checked against what the model was shown; stale/never-served/unverified ranges are hard-rejected with the current `HASH│content` rows echoed back (retry needs no `read`). Drift notices report served territory changed outside the edit range ([reject-and-serve spec: Rianico/pi-hashline-edit-lsz#13](https://github.com/Rianico/pi-hashline-edit-lsz/issues/13)).
71
93
  - Chained edits without re-reading: post-edit diff rows and rejection echoes count as serves, so follow-up edits verify cleanly.
72
- - Error-code contract (`[E_*]` codes, README-documented and test-enforced), `undo_last_edit` surviving restarts, and safe writes preserving permissions/line endings/BOMs/symlinks/hard links via `ctx.fs`.
94
+ - Error-code contract (`[E_*]` codes, README-documented and test-enforced) including the noop-loop guard ([Rianico/pi-hashline-edit-lsz#18](https://github.com/Rianico/pi-hashline-edit-lsz/issues/18)); `undo_last_edit` surviving restarts; and safe writes preserving permissions, line endings, BOMs, symlinks, and hard links via `ctx.fs`.
73
95
  - Test suite ported from pi-hashline-edit-lsz (614 tests at release), driving the dsh tool builders directly over a local filesystem bridge.
package/README.md CHANGED
@@ -24,7 +24,7 @@
24
24
  </p>
25
25
 
26
26
  <p align="center">
27
- <img src="https://img.shields.io/badge/version-0.1.6-blue.svg" alt="Version">
27
+ <img src="https://img.shields.io/badge/version-0.1.9-blue.svg" alt="Version">
28
28
  <img src="https://img.shields.io/badge/license-MIT-green.svg" alt="MIT License">
29
29
  <img src="https://img.shields.io/badge/DeepSeek_Harness-Plugin-blueviolet.svg" alt="DeepSeek Harness Plugin">
30
30
  <img src="https://img.shields.io/npm/v/dsh-better-edit" alt="npm version">
@@ -47,6 +47,14 @@ replace-style edits. **dsh-better-edit** goes deeper. Every line of a file gets
47
47
  content hash, and edits target hashes. The old text is never echoed, anchors survive edits, and every
48
48
  resolved range is verified against exactly what the model saw — wrong-line edits cannot silently land.
49
49
 
50
+ ## Why you need this
51
+
52
+ `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.
53
+
54
+ 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.
55
+
56
+ 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.
57
+
50
58
  ## Quick Start
51
59
 
52
60
  `read` returns every line prefixed by its hash — the hash *is* the line's address:
@@ -80,7 +88,7 @@ and produces a diff with fresh anchors, so the next edit verifies cleanly with n
80
88
 
81
89
  **Token-saving.** An edit call carries `remove_from` / `remove_to` (two 3-char hashes) plus the
82
90
  replacement text — it never echoes the text being replaced. A `str_replace` call must reproduce that
83
- text verbatim. On a 12-edit session over a realistic file this is **28% fewer output tokens** (40%
91
+ text verbatim. On a 12-edit session over a realistic file this is **31% fewer output tokens** (43%
84
92
  on multi-line ranges) — and these are *output* tokens, billed at ~5-6× the input rate. See the
85
93
  [benchmark](#benchmark).
86
94
 
@@ -116,8 +124,8 @@ Measured on the same 103-line file with the same 12 replacements (8 single-line,
116
124
  | Criterion | hashline | str_replace |
117
125
  | ----------- | :---: | :---: |
118
126
  | Replaced text sent over the wire | ✅ never | ❌ every edit |
119
- | Output tokens saved (12-edit session) | ✅ **28%** | ❌ 0% |
120
- | Multi-line range savings (3–15 lines) | ✅ **25–46%** | ❌ 0% |
127
+ | Output tokens saved (12-edit session) | ✅ **31%** | ❌ 0% |
128
+ | Multi-line range savings (3–15 lines) | ✅ **29–47%** | ❌ 0% |
121
129
  | Effective cost at 5× output pricing | ✅ **~1.4× less** | ❌ 1× |
122
130
  | Ranges verified against served state | ✅ 100% | ❌ none |
123
131
  | Deterministic, reproducible locally | ✅ `npm run benchmark` | — |
@@ -128,9 +136,9 @@ The numbers above are **deterministic and you can reproduce them locally** — `
128
136
 
129
137
  | Scenario | Lines | hashline | str_replace | Saved | % |
130
138
  | --- | :---: | :---: | :---: | :---: | :---: |
131
- | single-line ×8 | 1 | 311 | 314 | 3 | 1% |
132
- | multi-line ×4 | 3–15 | 390 | 655 | 265 | **40%** |
133
- | **TOTAL ×12** | | **701** | **969** | **268** | **28%** |
139
+ | single-line ×8 | 1 | 309 | 324 | 15 | 5% |
140
+ | multi-line ×4 | 3–15 | 393 | 691 | 298 | **43%** |
141
+ | **TOTAL ×12** | | **702** | **1015** | **313** | **31%** |
134
142
 
135
143
  The script is deterministic by construction: a frozen corpus, a content-addressed edit script that
136
144
  self-checks (a reformatted corpus throws instead of silently changing what's measured), and a pinned
@@ -260,6 +268,18 @@ npm run build # tsc → lib/
260
268
  npm run benchmark # reproducible token-cost benchmark (benchmark/)
261
269
  ```
262
270
 
271
+ ### Releasing (tag-first)
272
+
273
+ ```sh
274
+ npm run release -- 0.2.0 # bump + CHANGELOG move + commit + tag + push → GitHub release
275
+ npm publish --registry https://registry.npmjs.org # blocked until the version is tagged
276
+ ```
277
+
278
+ `npm run release` bumps `package.json`/lockfile, moves the CHANGELOG `[Unreleased]` section to the
279
+ version, commits, tags `vX.Y.Z`, and pushes — the tag push creates the GitHub release from the
280
+ changelog. `npm publish` refuses to run until that tag exists (prepublishOnly gate), so every npm
281
+ version is always already tagged and released.
282
+
263
283
  The test suite is ported from pi-hashline-edit-lsz and drives the dsh tool builders directly over a
264
284
  local filesystem bridge.
265
285
 
package/README.zh.md CHANGED
@@ -24,7 +24,7 @@
24
24
  </p>
25
25
 
26
26
  <p align="center">
27
- <img src="https://img.shields.io/badge/version-0.1.7-blue.svg" alt="Version">
27
+ <img src="https://img.shields.io/badge/version-0.1.9-blue.svg" alt="Version">
28
28
  <img src="https://img.shields.io/badge/license-MIT-green.svg" alt="MIT License">
29
29
  <img src="https://img.shields.io/badge/DeepSeek_Harness-Plugin-blueviolet.svg" alt="DeepSeek Harness Plugin">
30
30
  <img src="https://img.shields.io/npm/v/dsh-better-edit" alt="npm version">
@@ -43,6 +43,14 @@
43
43
 
44
44
  大多数编辑工具要求模型在改动任何东西之前,先**逐 token** 复述旧代码——而这正是 Agent 最容易出错的地方:多个模型在 replace 式编辑下的补丁格式失败率高达 46–51%。**dsh-better-edit** 走得更远。文件的每一行都分配一个唯一的 3 字符内容哈希,编辑时按哈希定位。旧文本从不回显,锚点在编辑后依然有效,每个解析出的范围都会与模型实际看到的内容逐一核对——错行编辑不可能悄悄落盘。
45
45
 
46
+ ## 为什么需要它
47
+
48
+ `str_replace` 会让模型逐字复述它要替换的代码——纯粹的转录成本(输出 token,按约 5-6 倍输入计费),也是 Agent 最容易出错的地方:真实模型补丁失败率高达 46–51%,块越大越糟,每次失败都要重新读取并重试。
49
+
50
+ Hashline 用两个哈希代替旧文本——**编辑 token 减少 31%**(多行范围达 43%)——并对照模型所见内容校验每个范围:编辑要么落在你想要的行的位置,要么响亮失败并回传新锚点。锚点是内容地址,上方编辑后依然有效,连续编辑无需重读;上下文更精简,模型的注意力也保持在代码上,而不是复述上。
51
+
52
+ 不适用于单行小改动(接近持平)或新建文件(用 `write`)。它的价值在长会话与结构性编辑中体现——任何不允许改错行的场景。
53
+
46
54
  ## 快速开始
47
55
 
48
56
  `read` 返回的每一行都带有哈希前缀——哈希*就是*这一行的地址:
@@ -74,7 +82,7 @@ kQm│}
74
82
 
75
83
  ## 为什么用 Hashline
76
84
 
77
- **省 token。** 一次编辑调用只携带 `remove_from` / `remove_to`(两个 3 字符哈希)加替换文本——从不回显被替换的文本。`str_replace` 调用则必须逐字复现被替换的文本。在一个真实文件上的 12 次编辑会话中,这可以**减少 28% 的输出 token**(多行范围达 40%)——而且这些是*输出* token,按输入的约 5-6 倍计费。见[基准测试](#基准测试)。
85
+ **省 token。** 一次编辑调用只携带 `remove_from` / `remove_to`(两个 3 字符哈希)加替换文本——从不回显被替换的文本。`str_replace` 调用则必须逐字复现被替换的文本。在一个真实文件上的 12 次编辑会话中,这可以**减少 31% 的输出 token**(多行范围达 43%)——而且这些是*输出* token,按输入的约 5-6 倍计费。见[基准测试](#基准测试)。
78
86
 
79
87
  **正确性。** 每个解析出的编辑范围都会与模型实际看到的行逐行核对。过期、从未提供或歧义的范围会在**写入任何内容之前**被硬性拒绝,并把当前范围以全新锚点的形式回显(reject-and-serve)——重试无需 `read`。
80
88
 
@@ -101,8 +109,8 @@ kQm│}
101
109
  | 指标 | hashline | str_replace |
102
110
  | ----------- | :---: | :---: |
103
111
  | 被替换文本是否上线 | ✅ 从不 | ❌ 每次编辑都发 |
104
- | 输出 token 节省(12 次编辑) | ✅ **28%** | ❌ 0% |
105
- | 多行范围节省(3–15 行) | ✅ **25–46%** | ❌ 0% |
112
+ | 输出 token 节省(12 次编辑) | ✅ **31%** | ❌ 0% |
113
+ | 多行范围节省(3–15 行) | ✅ **29–47%** | ❌ 0% |
106
114
  | 按 5 倍输出计价的实际成本 | ✅ **低约 1.4 倍** | ❌ 1× |
107
115
  | 范围对照已提供状态校验 | ✅ 100% | ❌ 无 |
108
116
  | 确定性、可在本地复现 | ✅ `npm run benchmark` | — |
@@ -113,9 +121,9 @@ kQm│}
113
121
 
114
122
  | 场景 | 行数 | hashline | str_replace | 节省 | % |
115
123
  | --- | :---: | :---: | :---: | :---: | :---: |
116
- | 单行 ×8 | 1 | 311 | 314 | 3 | 1% |
117
- | 多行 ×4 | 3–15 | 390 | 655 | 265 | **40%** |
118
- | **合计 ×12** | | **701** | **969** | **268** | **28%** |
124
+ | 单行 ×8 | 1 | 309 | 324 | 15 | 5% |
125
+ | 多行 ×4 | 3–15 | 393 | 691 | 298 | **43%** |
126
+ | **合计 ×12** | | **702** | **1015** | **313** | **31%** |
119
127
 
120
128
  脚本天然确定:固定语料、内容寻址且自带自检的编辑脚本(语料被重排会直接抛错,而不是悄悄改变测量对象)、固定版本的 tokenizer。因为一切都是固定的,`npm run benchmark` 对每个人都是同一个结果。
121
129
 
@@ -226,6 +234,15 @@ npm run build # tsc → lib/
226
234
  npm run benchmark # 可复现的 token 成本基准测试(benchmark/)
227
235
  ```
228
236
 
237
+ ### 发布流程(先打 tag)
238
+
239
+ ```sh
240
+ npm run release -- 0.2.0 # 升版本 + 迁移 CHANGELOG + 提交 + 打 tag + 推送 → 生成 GitHub release
241
+ npm publish --registry https://registry.npmjs.org # 版本未打 tag 前会被阻止
242
+ ```
243
+
244
+ `npm run release` 会更新 `package.json`/lockfile、把 CHANGELOG 的 `[Unreleased]` 段落迁移到版本号下、提交、打 `vX.Y.Z` tag 并推送——tag 推送会基于 changelog 自动创建 GitHub release。`npm publish` 在该 tag 存在之前会拒绝运行(prepublishOnly 门禁),因此每个 npm 版本都一定已经打好 tag 并发布过 release。
245
+
229
246
  测试套件移植自 pi-hashline-edit-lsz,通过本地文件系统桥接直接驱动 dsh 工具构建器。
230
247
 
231
248
  ## 路线图
package/assets/logo.svg CHANGED
@@ -1,21 +1,186 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" width="200" height="200" role="img" aria-label="dsh-better-edit">
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
2
2
  <defs>
3
- <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
4
- <stop offset="0" stop-color="#1c2330"/>
5
- <stop offset="1" stop-color="#0d1117"/>
3
+ <!-- DeepSeek brand gradient matching ref image tone -->
4
+ <linearGradient id="dolphinBody" x1="0%" y1="0%" x2="100%" y2="100%">
5
+ <stop offset="0%" stop-color="#4A5568"/>
6
+ <stop offset="100%" stop-color="#2D3748"/>
6
7
  </linearGradient>
8
+ <!-- Notebook paper -->
9
+ <linearGradient id="paper" x1="0%" y1="0%" x2="0%" y2="100%">
10
+ <stop offset="0%" stop-color="#FEFCFB"/>
11
+ <stop offset="100%" stop-color="#F7F5F3"/>
12
+ </linearGradient>
13
+ <!-- Glow for new hash -->
14
+ <filter id="addGlow" x="-30%" y="-30%" width="160%" height="160%">
15
+ <feGaussianBlur stdDeviation="2" result="blur"/>
16
+ <feMerge>
17
+ <feMergeNode in="blur"/>
18
+ <feMergeNode in="SourceGraphic"/>
19
+ </feMerge>
20
+ </filter>
7
21
  </defs>
8
- <rect x="8" y="8" width="184" height="184" rx="28" fill="url(#bg)" stroke="#30363d" stroke-width="2"/>
9
- <!-- row 1 -->
10
- <rect x="30" y="46" width="38" height="20" rx="6" fill="#1f6feb"/>
11
- <text x="49" y="60" font-family="ui-monospace,SFMono-Regular,Menlo,Consolas,monospace" font-size="13" font-weight="700" fill="#ffffff" text-anchor="middle">ve7</text>
12
- <text x="78" y="60" font-family="ui-monospace,SFMono-Regular,Menlo,Consolas,monospace" font-size="13" fill="#e6edf3">hello()</text>
13
- <!-- row 2 -->
14
- <rect x="30" y="90" width="38" height="20" rx="6" fill="#238636"/>
15
- <text x="49" y="104" font-family="ui-monospace,SFMono-Regular,Menlo,Consolas,monospace" font-size="13" font-weight="700" fill="#ffffff" text-anchor="middle">szJ</text>
16
- <text x="78" y="104" font-family="ui-monospace,SFMono-Regular,Menlo,Consolas,monospace" font-size="13" fill="#e6edf3">const x = 1</text>
17
- <!-- row 3 -->
18
- <rect x="30" y="134" width="38" height="20" rx="6" fill="#bf3989"/>
19
- <text x="49" y="148" font-family="ui-monospace,SFMono-Regular,Menlo,Consolas,monospace" font-size="13" font-weight="700" fill="#ffffff" text-anchor="middle">kQm</text>
20
- <text x="78" y="148" font-family="ui-monospace,SFMono-Regular,Menlo,Consolas,monospace" font-size="13" fill="#e6edf3">return x</text>
21
- </svg>
22
+
23
+ <!-- Clean light background like ref image -->
24
+ <rect width="256" height="256" rx="20" fill="#F7FAFC"/>
25
+
26
+ <!-- ===== NOTEBOOK ===== -->
27
+ <g transform="translate(52, 138)">
28
+ <!-- Notebook cover -->
29
+ <rect width="136" height="88" rx="6" fill="url(#paper)" stroke="#CBD5E0" stroke-width="1.5"/>
30
+ <!-- Spiral binding -->
31
+ <g fill="#718096">
32
+ <circle cx="-5" cy="16" r="3"/>
33
+ <circle cx="-5" cy="34" r="3"/>
34
+ <circle cx="-5" cy="52" r="3"/>
35
+ <circle cx="-5" cy="70" r="3"/>
36
+ </g>
37
+ <!-- Lines -->
38
+ <line x1="14" y1="22" x2="120" y2="22" stroke="#E2E8F0" stroke-width="1.2"/>
39
+ <line x1="14" y1="38" x2="112" y2="38" stroke="#E2E8F0" stroke-width="1.2"/>
40
+ <line x1="14" y1="54" x2="124" y2="54" stroke="#E2E8F0" stroke-width="1.2"/>
41
+ <line x1="14" y1="70" x2="100" y2="70" stroke="#E2E8F0" stroke-width="1.2"/>
42
+
43
+ <!-- Read context on notebook -->
44
+ <text x="18" y="21" font-family="monospace" font-size="7.5" fill="#4A5568">ve7</text>
45
+ <text x="44" y="21" font-family="monospace" font-size="7.5" fill="#4A5568">szJ</text>
46
+ <text x="70" y="21" font-family="monospace" font-size="7.5" fill="#4A5568">kQm</text>
47
+
48
+ <!-- Edit action area: show -szJ +a3m diff -->
49
+ <g transform="translate(18, 48)">
50
+ <!-- Removed hash: -szJ with strikethrough -->
51
+ <text x="0" y="0" font-family="monospace" font-size="9" fill="#E53E3E" text-decoration="line-through" opacity="0.75">szJ</text>
52
+ <!-- Arrow indicator -->
53
+ <text x="30" y="0" font-family="monospace" font-size="9" fill="#A0AEC0">→</text>
54
+ <!-- Added hash: +a3m highlighted -->
55
+ <rect x="42" y="-10" width="28" height="13" rx="2" fill="#C6F6D5" opacity="0.5"/>
56
+ <text x="45" y="0" font-family="monospace" font-size="9" fill="#22543D" font-weight="bold" filter="url(#addGlow)">a3m</text>
57
+ </g>
58
+
59
+ <!-- Remaining unchanged hashes below -->
60
+ <text x="18" y="67" font-family="monospace" font-size="7.5" fill="#718096" opacity="0.6">ve7</text>
61
+ <text x="44" y="67" font-family="monospace" font-size="7.5" fill="#718096" opacity="0.6">kQm</text>
62
+
63
+ <!-- Cursor after edit -->
64
+ <line x1="76" y1="52" x2="76" y2="62" stroke="#4299E1" stroke-width="1.5" stroke-linecap="round">
65
+ <animate attributeName="opacity" values="1;0;1" dur="1s" repeatCount="indefinite"/>
66
+ </line>
67
+ </g>
68
+
69
+ <!-- ===== DOLPHIN — minimalist style matching reference image ===== -->
70
+ <g transform="translate(64, 36)">
71
+ <!-- Body: smooth curved shape like the ref image -->
72
+ <path d="M24,12
73
+ C50,-2 90,6 104,28
74
+ C118,52 98,82 68,88
75
+ C40,92 16,78 8,56
76
+ C0,34 10,18 24,12Z"
77
+ fill="url(#dolphinBody)"/>
78
+
79
+ <!-- White belly patch (like ref image) -->
80
+ <path d="M20,52
81
+ C32,80 60,86 80,68
82
+ C72,78 48,84 28,72
83
+ C18,62 14,54 20,52Z"
84
+ fill="#F7FAFC"/>
85
+
86
+ <!-- Tail fin (small, curved up like ref) -->
87
+ <path d="M8,58
88
+ C-4,50 -6,60 2,66
89
+ C-2,74 4,80 12,72
90
+ Z"
91
+ fill="url(#dolphinBody)"/>
92
+
93
+ <!-- Dorsal fin (small, subtle) -->
94
+ <path d="M68,18
95
+ C78,4 88,6 90,12
96
+ C84,18 76,24 70,24Z"
97
+ fill="#2D3748"/>
98
+
99
+ <!-- Left pectoral fin -->
100
+ <path d="M26,62
101
+ C14,72 16,82 26,78
102
+ C30,70 28,64 26,62Z"
103
+ fill="#2D3748" opacity="0.7"/>
104
+
105
+ <!-- Right pectoral fin (holding pen) -->
106
+ <path d="M78,60
107
+ C92,68 86,80 76,76
108
+ C72,68 74,60 78,60Z"
109
+ fill="#2D3748" opacity="0.7"/>
110
+
111
+ <!-- Eye — looking down at notebook (read) -->
112
+ <ellipse cx="88" cy="40" rx="5" ry="6" fill="#FFFFFF"/>
113
+ <circle cx="89.5" cy="41" r="3" fill="#1A202C"/>
114
+ <circle cx="91" cy="39.5" r="1" fill="#FFFFFF"/>
115
+
116
+ <!-- Subtle smile -->
117
+ <path d="M94,48 Q100,52 106,48" stroke="#2D3748" stroke-width="1.5" fill="none" stroke-linecap="round" opacity="0.5"/>
118
+ </g>
119
+
120
+ <!-- ===== PEN held by right flipper ===== -->
121
+ <g transform="translate(148, 108) rotate(35)">
122
+ <rect x="0" y="0" width="4" height="30" rx="2" fill="#4299E1"/>
123
+ <polygon points="2,30 -1,36 5,36" fill="#1A202C"/>
124
+ <rect x="4" y="4" width="1.5" height="15" rx="0.75" fill="#2B6CB0"/>
125
+ <!-- Ink trail on notebook showing edit -->
126
+ <path d="M2,36 Q4,42 2,48 Q4,52 3,56" stroke="#4299E1" stroke-width="1.5" fill="none" stroke-linecap="round" opacity="0.5"/>
127
+ </g>
128
+
129
+ <!-- ===== FLOATING HASHES — read set + diff visualization ===== -->
130
+ <g font-family="monospace">
131
+
132
+ <!-- Read hashes floating (original state) -->
133
+ <g font-size="11" font-weight="600" opacity="0.85">
134
+ <text x="186" y="46" fill="#4A5568">ve7</text>
135
+ <text x="206" y="66" fill="#4A5568">szJ</text>
136
+ <text x="188" y="86" fill="#4A5568">kQm</text>
137
+ </g>
138
+
139
+ <!-- DIFF ANIMATION AREA: show -szJ → +a3m transition -->
140
+ <g transform="translate(176, 108)">
141
+ <!-- Minus: removed hash szJ fading out -->
142
+ <text x="0" y="0" font-family="monospace" font-size="12" font-weight="bold" fill="#E53E3E" opacity="0.6">
143
+ −szJ
144
+ <animate attributeName="opacity" values="0.6;0.2;0.6" dur="2s" repeatCount="indefinite"/>
145
+ <animateTransform attributeName="transform" type="translate" values="0,0; -8,0; 0,0" dur="2s" repeatCount="indefinite"/>
146
+ </text>
147
+
148
+ <!-- Plus: new hash a3m glowing in -->
149
+ <text x="38" y="0" font-family="monospace" font-size="12" font-weight="bold" fill="#38A169" filter="url(#addGlow)">
150
+ +a3m
151
+ <animate attributeName="opacity" values="0.9;1;0.9" dur="2s" repeatCount="indefinite"/>
152
+ </text>
153
+ </g>
154
+
155
+ <!-- Connecting dots between original hashes -->
156
+ <g fill="#CBD5E0" opacity="0.3">
157
+ <circle cx="198" cy="50" r="1.2"/>
158
+ <circle cx="216" cy="72" r="1.2"/>
159
+ <circle cx="200" cy="92" r="1.2"/>
160
+ </g>
161
+
162
+ <!-- Small arrow indicating transformation -->
163
+ <g transform="translate(196, 96)" fill="#A0AEC0" opacity="0.4">
164
+ <path d="M0,0 L6,4 L0,8 Z"/>
165
+ </g>
166
+ </g>
167
+
168
+ <!-- ===== LABELS ===== -->
169
+ <!-- "read" label near dolphin's gaze -->
170
+ <g transform="translate(160, 56)">
171
+ <rect x="0" y="0" width="28" height="14" rx="3" fill="#EDF2F7" opacity="0.8"/>
172
+ <text x="14" y="10" font-family="monospace" font-size="7" fill="#4A5568" text-anchor="middle" font-weight="600">read</text>
173
+ </g>
174
+
175
+ <!-- "edit" label near pen -->
176
+ <g transform="translate(178, 128)">
177
+ <rect x="0" y="0" width="28" height="14" rx="3" fill="#EBF8FF" opacity="0.8"/>
178
+ <text x="14" y="10" font-family="monospace" font-size="7" fill="#2B6CB0" text-anchor="middle" font-weight="600">edit</text>
179
+ </g>
180
+
181
+ <!-- Corner decoration dots (subtle) -->
182
+ <circle cx="228" cy="28" r="2" fill="#E2E8F0"/>
183
+ <circle cx="236" cy="36" r="1.5" fill="#E2E8F0"/>
184
+ <circle cx="20" cy="228" r="2" fill="#E2E8F0"/>
185
+ <circle cx="28" cy="236" r="1.5" fill="#E2E8F0"/>
186
+ </svg>
@@ -0,0 +1,95 @@
1
+ /**
2
+ * One module owns the request shapes for the hashline tools — edit,
3
+ * batch_edit, read, undo_last_edit — plus their validation. Field sets are
4
+ * declared once here; every tool validates through these asserts, and the
5
+ * [E_BAD_SHAPE] vocabulary is shared instead of re-implemented per tool.
6
+ *
7
+ * Note: `resolve.ts` keeps its own internal item check (content-only fields,
8
+ * no path) — that is the hashline-internal edit-item shape, deliberately
9
+ * decoupled from the tool-layer request contract so the hashline module does
10
+ * not depend on this one.
11
+ * @module dsh-better-edit/contract
12
+ */
13
+ import { BATCH_EDIT_MAX_ITEMS } from "./constants.js";
14
+ import { isRec, normalizeFilePath, rejectUnknownFields } from "./utils.js";
15
+ // ---- field sets (declared once) ---------------------------------------------
16
+ const EDIT_KS = new Set([
17
+ "path",
18
+ "remove_from",
19
+ "remove_to",
20
+ "replacement_text",
21
+ "sandbox_permissions",
22
+ "justification",
23
+ ]);
24
+ const BATCH_ROOT_KS = new Set([
25
+ "edits",
26
+ "sandbox_permissions",
27
+ "justification",
28
+ ]);
29
+ const BATCH_ITEM_KS = new Set([
30
+ "path",
31
+ "remove_from",
32
+ "remove_to",
33
+ "replacement_text",
34
+ ]);
35
+ const READ_KS = new Set(["path", "offset", "limit"]);
36
+ // ---- assertions ---------------------------------------------------------------
37
+ export function assertEditRequest(request) {
38
+ if (!isRec(request)) {
39
+ throw new Error("[E_BAD_SHAPE] Edit request must be an object.");
40
+ }
41
+ rejectUnknownFields(request, EDIT_KS, "Edit request");
42
+ if (typeof request.path !== "string" || request.path.length === 0) {
43
+ throw new Error('[E_BAD_SHAPE] Edit request requires a non-empty "path" string.');
44
+ }
45
+ if (typeof request.remove_from !== "string" ||
46
+ typeof request.remove_to !== "string" ||
47
+ typeof request.replacement_text !== "string") {
48
+ throw new Error('[E_BAD_SHAPE] Edit request requires "remove_from", "remove_to", and "replacement_text" at the top level.');
49
+ }
50
+ }
51
+ export function assertBatchEditRequest(request) {
52
+ if (!isRec(request)) {
53
+ throw new Error('[E_BAD_SHAPE] batch_edit request must be an object with an "edits" array.');
54
+ }
55
+ rejectUnknownFields(request, BATCH_ROOT_KS, "batch_edit request");
56
+ if (!Array.isArray(request.edits) || request.edits.length === 0) {
57
+ throw new Error('[E_BAD_SHAPE] batch_edit request requires a non-empty "edits" array.');
58
+ }
59
+ if (request.edits.length > BATCH_EDIT_MAX_ITEMS) {
60
+ throw new Error(`[E_BAD_SHAPE] batch_edit accepts at most ${BATCH_EDIT_MAX_ITEMS} edits; got ${request.edits.length}. Split the batch.`);
61
+ }
62
+ request.edits.forEach((item, index) => {
63
+ if (!isRec(item)) {
64
+ throw new Error(`[E_BAD_SHAPE] edits[${index}] must be an object with remove_from, remove_to, and replacement_text.`);
65
+ }
66
+ rejectUnknownFields(item, BATCH_ITEM_KS, `edits[${index}]`);
67
+ if (typeof item.remove_from !== "string" ||
68
+ typeof item.remove_to !== "string" ||
69
+ typeof item.replacement_text !== "string") {
70
+ throw new Error(`[E_BAD_SHAPE] edits[${index}] requires "remove_from", "remove_to", and "replacement_text" strings.`);
71
+ }
72
+ if (item.path !== undefined &&
73
+ (typeof item.path !== "string" || item.path.length === 0)) {
74
+ throw new Error(`[E_BAD_SHAPE] edits[${index}].path must be a non-empty string.`);
75
+ }
76
+ });
77
+ }
78
+ export function assertReadRequest(request) {
79
+ if (!isRec(request)) {
80
+ throw new Error("[E_BAD_SHAPE] Read request must be an object.");
81
+ }
82
+ rejectUnknownFields(request, READ_KS, "Read request");
83
+ if (typeof request.path !== "string" || request.path.length === 0) {
84
+ throw new Error('[E_BAD_SHAPE] Read request requires a non-empty "path" string.');
85
+ }
86
+ }
87
+ export function assertUndoRequest(request) {
88
+ if (!isRec(request)) {
89
+ throw new Error("[E_BAD_SHAPE] undo_last_edit request must be an object.");
90
+ }
91
+ normalizeFilePath(request);
92
+ if (typeof request.path !== "string" || request.path.length === 0) {
93
+ throw new Error('[E_BAD_SHAPE] undo_last_edit request requires a non-empty "path" string.');
94
+ }
95
+ }
package/lib/drift.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { SERVED_ECHO_CAP } from "./constants.js";
2
2
  import { fmtServedRows, } from "./hashline/served.js";
3
- import { currentPositionOfDrifted, driftReported, markDriftReported, recordServed, servedPositionsOf, } from "./served-state.js";
3
+ import { currentPositionOfDrifted, driftReported, markDriftReported, recordServed, servedPositionsOf, } from "./served-store.js";
4
4
  export const DRIFT_NOTICE_HEADING = "Drift notice:";
5
5
  export function computeDrift(input) {
6
6
  const { served, resultHashes, resultLines, range, reported, cap = SERVED_ECHO_CAP, } = input;
package/lib/edit-diff.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as Diff from "diff";
2
- import { _lineHashesPure, ANCHOR_LEN, HASH_SEP } from "./hashline/index.js";
2
+ import { lineHashesPure, ANCHOR_LEN, HASH_SEP } from "./hashline/index.js";
3
3
  export function detectEnding(content) {
4
4
  const lfIdx = content.indexOf("\n");
5
5
  if (lfIdx === -1) {
@@ -34,7 +34,7 @@ function fmtDiffLine(prefix, line, hash) {
34
34
  const ELLIPSIS_MARKER = Symbol("ellipsis");
35
35
  const isEllipsisMarker = (line) => line === ELLIPSIS_MARKER;
36
36
  export function genDiff(oldContent, newContent, contextLines = 2, newContentHashes, oldContentHashes) {
37
- const effectiveNewHashes = newContentHashes ?? _lineHashesPure(newContent);
37
+ const effectiveNewHashes = newContentHashes ?? lineHashesPure(newContent);
38
38
  const parts = Diff.diffLines(oldContent, newContent);
39
39
  const output = [];
40
40
  const servedRows = [];