dsh-better-edit 0.7.1 → 0.8.1

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 (46) hide show
  1. package/CHANGELOG.md +50 -25
  2. package/README.md +72 -66
  3. package/README.zh.md +83 -83
  4. package/lib/canonical-path.js +4 -1
  5. package/lib/contract.js +67 -22
  6. package/lib/edit-diff.js +1 -5
  7. package/lib/encoding.js +22 -5
  8. package/lib/file-encoding-state.js +50 -11
  9. package/lib/file-view.js +28 -41
  10. package/lib/fs-bridge.js +59 -23
  11. package/lib/fs-write.js +1 -1
  12. package/lib/guidance/materialize.js +1 -6
  13. package/lib/guidance/resolve.js +1 -1
  14. package/lib/hash-store.js +12 -20
  15. package/lib/hashline/anchor-pipeline.js +29 -29
  16. package/lib/hashline/hash-assign.js +7 -4
  17. package/lib/hashline/hash.js +3 -3
  18. package/lib/index.js +6 -0
  19. package/lib/mutation/engine.js +11 -14
  20. package/lib/mutation.js +7 -6
  21. package/lib/prompts.js +9 -8
  22. package/lib/read-and-serve.js +22 -11
  23. package/lib/render-text-warning.js +21 -0
  24. package/lib/sandbox.js +2 -5
  25. package/lib/self-heal.js +30 -27
  26. package/lib/session-view.js +5 -1
  27. package/lib/store-config.js +7 -2
  28. package/lib/store-lifecycle.js +7 -2
  29. package/lib/tool-edit.js +5 -2
  30. package/lib/tool-read.js +6 -9
  31. package/lib/tool-str-replace-editor.js +274 -0
  32. package/lib/tool-undo.js +2 -3
  33. package/lib/types/contract.d.ts +104 -17
  34. package/lib/types/file-encoding-state.d.ts +3 -0
  35. package/lib/types/file-view.d.ts +1 -1
  36. package/lib/types/hashline/index.d.ts +1 -1
  37. package/lib/types/render-text-warning.d.ts +22 -0
  38. package/lib/types/self-heal.d.ts +2 -0
  39. package/lib/types/tool-str-replace-editor.d.ts +27 -0
  40. package/lib/types/undo-edit.d.ts +1 -1
  41. package/lib/types/write-hook.d.ts +2 -2
  42. package/lib/undo-edit.js +6 -8
  43. package/lib/utils.js +1 -2
  44. package/lib/workspace-context.js +1 -1
  45. package/lib/write-hook.js +19 -22
  46. package/package.json +63 -57
package/README.zh.md CHANGED
@@ -37,8 +37,8 @@
37
37
 
38
38
  ---
39
39
 
40
- > *"瓶颈在于 harness——而不是模型。"*
41
- > —— Can Bölük,[*The Harness Problem*]
40
+ > _"瓶颈在于 harness——而不是模型。"_
41
+ > —— Can Bölük,[_The Harness Problem_]
42
42
  >
43
43
  > **这是 harness 的修复。** 内容哈希取代行号——上方编辑永不使下方锚点移位。每个范围都对照 Agent 实际看到的内容校验。过期或未见的行被硬拒绝并回传新锚点重试——无需 `read`。
44
44
  >
@@ -79,11 +79,11 @@ npx @deepseek-ai/dsh plugin --profile web add /path/to/dsh-better-edit # 从
79
79
  dsh --profile <name> --dump-config # 会显示 "# == dsh-better-edit" 层
80
80
  ```
81
81
 
82
- | 要求 | |
83
- | --- | --- |
84
- | Node | `^22.19.0 \|\| >=24.0.0`(dsh 的要求;存储使用 `node:sqlite`) |
85
- | Profile | 一个 dsh profile(首次使用 `dsh plugin` 时初始化) |
86
- | 后端 | 支持沙箱/远程文件系统(写入经 `ctx.fs`) |
82
+ | 要求 | |
83
+ | ------- | -------------------------------------------------------------- |
84
+ | Node | `^22.19.0 \|\| >=24.0.0`(dsh 的要求;存储使用 `node:sqlite`) |
85
+ | Profile | 一个 dsh profile(首次使用 `dsh plugin` 时初始化) |
86
+ | 后端 | 支持沙箱/远程文件系统(写入经 `ctx.fs`) |
87
87
 
88
88
  `read` 返回的每一行都带有哈希前缀——哈希*就是*这一行的地址:
89
89
 
@@ -127,11 +127,11 @@ kQm│}
127
127
 
128
128
  ```yaml
129
129
  # $DSH_HOME/plugins/dsh-better-edit/config.yaml
130
- storeDir: central # 存储位置:"central"(默认,位于 $DSH_HOME/.../runtime/<name>-<hash8>/)| "workspace"(旧版 <ws>/.dsh_better_edit/)| "/abs/path"(自定义根目录)
131
- autoGitignore: false # 仅 workspace:当 .git 存在但 .gitignore 缺少 .dsh_better_edit/ 时,true = 自动追加 ".dsh_better_edit/",false = 仅告警一次
132
- undo_ttl_s: 604800 # 撤销历史 TTL(秒);-1 = 永久保留(默认 604800 = 7 天)
133
- storeMaxAgeS: 2592000 # central 清理:runtime/<name>-<hash8>/ 目录最大闲置时长(秒),超时后被清理(默认 2592000 = 30 天)
134
- storeMaxTotalBytes: 524288000 # central 清理:runtime/ 下总字节数上限,超限后按 LRU 清理(默认 524288000 = 500 MB)
130
+ storeDir: central # 存储位置:"central"(默认,位于 $DSH_HOME/.../runtime/<name>-<hash8>/)| "workspace"(旧版 <ws>/.dsh_better_edit/)| "/abs/path"(自定义根目录)
131
+ autoGitignore: false # 仅 workspace:当 .git 存在但 .gitignore 缺少 .dsh_better_edit/ 时,true = 自动追加 ".dsh_better_edit/",false = 仅告警一次
132
+ undo_ttl_s: 604800 # 撤销历史 TTL(秒);-1 = 永久保留(默认 604800 = 7 天)
133
+ storeMaxAgeS: 2592000 # central 清理:runtime/<name>-<hash8>/ 目录最大闲置时长(秒),超时后被清理(默认 2592000 = 30 天)
134
+ storeMaxTotalBytes: 524288000 # central 清理:runtime/ 下总字节数上限,超限后按 LRU 清理(默认 524288000 = 500 MB)
135
135
  ```
136
136
 
137
137
  > [!TIP]
@@ -156,11 +156,11 @@ $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
156
156
 
157
157
  (默认主目录 `~/.dsh`,即 `~/.dsh/plugins/dsh-better-edit/`)。片段对照表:
158
158
 
159
- | 文件 | 提示词片段 | 默认 order |
160
- | --- | --- | --- |
161
- | `read.md` | `tool:read` | 130 |
162
- | `edit.md` | `tool:edit` | 131 |
163
- | `undo_last_edit.md` | `tool:undo_last_edit` | 133 |
159
+ | 文件 | 提示词片段 | 默认 order |
160
+ | ------------------- | --------------------- | ---------- |
161
+ | `read.md` | `tool:read` | 130 |
162
+ | `edit.md` | `tool:edit` | 131 |
163
+ | `undo_last_edit.md` | `tool:undo_last_edit` | 133 |
164
164
 
165
165
  首次启动时插件会为三个随附 preset——`standard/`、`code/`、`minimal/`、`cordis/`——各自写入编译内置的可编辑指引文件(含 `order` front-matter)。详见[配置详情](#按-preset-配置指引)的重置/恢复。完整规范:`docs/specs/issue-24-store-tenancy.md` 与指引文档。
166
166
 
@@ -194,20 +194,20 @@ $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
194
194
 
195
195
  ### 对比
196
196
 
197
- | | hashline `edit` | `str_replace`(Claude Code / Codex) | @oh-my-pi/hashline 补丁 |
198
- | --- | :---: | :---: | :---: |
199
- | 调用中永不回显被替换文本 | ✅ 只有两个哈希 | ❌ 逐字回显 | ✅ 只有 `+` 行 |
200
- | 按什么定位行 | 内容哈希 | 文本匹配 | 行号 + 文件内容标签 |
201
- | 对照模型所见内容校验 | ✅ 每一行 | ❌ 取第一个匹配 | ~ 仅文件版本 |
202
- | 检测文件已过期 | ✅ 拒绝并回传新锚点 | ❌ 可能匹配到错误位置 | ✅ 标签不匹配 → 拒绝或三方合并 |
203
- | 上方编辑后锚点依然有效 | ✅ 内容寻址 | ✅ 基于内容 | ❌ 重新编号 + 新标签 |
204
- | 连续编辑无需重读 | ✅ diff 提供新锚点 | ~ | ~ 从编辑响应取行号 |
205
- | 文本重复时无歧义 | ✅ 边界锚点需校验 | ❌ 取第一个出现 | ~ 按位置,行未逐行校验 |
206
- | 错行编辑永远不会悄悄落盘 | ✅ 每一行都校验 | ❌ 取第一个匹配 | ~ 原则上可能(标签只校验版本,不校验行) |
207
- | 块操作 / 寄存器 / `MV` / `REM` | ❌ | ❌ | ✅ |
208
- | 一次变更一个文档 | ❌ 每次一个调用 | ❌ 每次一个调用 | ✅ 多 hunk 补丁 |
209
- | 运行时 | ✅ Node(dsh) | — | ⚠️ 仅 Bun |
210
- | 撤销 | ✅ 持久化 | ❌ | ❌ 不在范围内 |
197
+ | | hashline `edit` | `str_replace`(Claude Code / Codex) | @oh-my-pi/hashline 补丁 |
198
+ | ------------------------------ | :-----------------: | :----------------------------------: | :--------------------------------------: |
199
+ | 调用中永不回显被替换文本 | ✅ 只有两个哈希 | ❌ 逐字回显 | ✅ 只有 `+` 行 |
200
+ | 按什么定位行 | 内容哈希 | 文本匹配 | 行号 + 文件内容标签 |
201
+ | 对照模型所见内容校验 | ✅ 每一行 | ❌ 取第一个匹配 | ~ 仅文件版本 |
202
+ | 检测文件已过期 | ✅ 拒绝并回传新锚点 | ❌ 可能匹配到错误位置 | ✅ 标签不匹配 → 拒绝或三方合并 |
203
+ | 上方编辑后锚点依然有效 | ✅ 内容寻址 | ✅ 基于内容 | ❌ 重新编号 + 新标签 |
204
+ | 连续编辑无需重读 | ✅ diff 提供新锚点 | ~ | ~ 从编辑响应取行号 |
205
+ | 文本重复时无歧义 | ✅ 边界锚点需校验 | ❌ 取第一个出现 | ~ 按位置,行未逐行校验 |
206
+ | 错行编辑永远不会悄悄落盘 | ✅ 每一行都校验 | ❌ 取第一个匹配 | ~ 原则上可能(标签只校验版本,不校验行) |
207
+ | 块操作 / 寄存器 / `MV` / `REM` | ❌ | ❌ | ✅ |
208
+ | 一次变更一个文档 | ❌ 每次一个调用 | ❌ 每次一个调用 | ✅ 多 hunk 补丁 |
209
+ | 运行时 | ✅ Node(dsh) | — | ⚠️ 仅 Bun |
210
+ | 撤销 | ✅ 持久化 | ❌ | ❌ 不在范围内 |
211
211
 
212
212
  > `~` = 偶尔/不稳定。`@oh-my-pi/hashline` 是一种紧凑的行锚定补丁语言([npm](https://www.npmjs.com/package/@oh-my-pi/hashline)、[仓库](https://github.com/can1357/oh-my-pi/tree/main/packages/hashline)):`[path#tag]` 头把每个 hunk 绑定到全文件内容哈希,`PUT N.=M:` 按行号定位;每次编辑都会重新编号——下一次的行号与标签取自编辑响应或重新 `read`。
213
213
 
@@ -217,15 +217,15 @@ $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
217
217
 
218
218
  token 基准测试衡量的是模型发出的负载——它假设模型每次都能拿到**正确**的地址,而且免费。正确性才是两种 hashline 实现真正分道扬镳的地方。下面是 harness-problem 文献里的真实故障模式(错行编辑、漂移、重复文本),以及各自在遭遇它们时的表现:
219
219
 
220
- | 边界情况 | hashline `edit`(本插件) | @oh-my-pi/hashline 补丁 |
221
- | --- | --- | --- |
222
- | 错误地址(锚点/行号差一行) | **不可能**——锚点解析到具体行;解析出的每一行都对照已提供状态校验,在**写入任何内容之前**被拒绝 | **可能**——当前标签下的错误行号会**悄悄**落到错误位置;标签只证明文件版本,从不证明行 |
223
- | 模型查看后文件在磁盘上被改动 | 硬拒绝 + 回传新锚点(reject-and-serve);重试无需 `read` | 标签不匹配 → 拒绝**或**对未知的当前内容做尽力而为的三方合并 |
224
- | 上方编辑导致文件移位 | 什么都不移位——锚点是内容地址;diff 提供新锚点 | **每次编辑都重新编号**——“RE-GROUND AFTER EVERY EDIT” 是它自己的头号规则;账由模型记 |
225
- | 重复/相同文本 | 每行哈希唯一(冲突已消解);歧义 → `[E_AMBIGUOUS_ANCHOR]` | 基于位置,重复不会混淆——但位置本身未被校验 |
226
- | 从未展示给模型的行 | `[E_RANGE_UNSERVED]`——硬拒绝并回传新锚点 | 未展示的 hunk 被拒绝——同样依赖模型知道自己看过什么 |
227
- | 表达式中间 / 错误的块节点 | 无关——任何已校验的行范围都合法 | 语法规则 + `PUT N*:` 节点选择;点错(锚在 `def` 会让装饰器变成孤儿)会悄悄落错;无语法检查 |
228
- | 多编辑批量中途失败 | `edit` 多条目——原子、全有或全无;失败项以新锚点回显 | 多段补丁先预检——同样原子 |
220
+ | 边界情况 | hashline `edit`(本插件) | @oh-my-pi/hashline 补丁 |
221
+ | ---------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
222
+ | 错误地址(锚点/行号差一行) | **不可能**——锚点解析到具体行;解析出的每一行都对照已提供状态校验,在**写入任何内容之前**被拒绝 | **可能**——当前标签下的错误行号会**悄悄**落到错误位置;标签只证明文件版本,从不证明行 |
223
+ | 模型查看后文件在磁盘上被改动 | 硬拒绝 + 回传新锚点(reject-and-serve);重试无需 `read` | 标签不匹配 → 拒绝**或**对未知的当前内容做尽力而为的三方合并 |
224
+ | 上方编辑导致文件移位 | 什么都不移位——锚点是内容地址;diff 提供新锚点 | **每次编辑都重新编号**——“RE-GROUND AFTER EVERY EDIT” 是它自己的头号规则;账由模型记 |
225
+ | 重复/相同文本 | 每行哈希唯一(冲突已消解);歧义 → `[E_AMBIGUOUS_ANCHOR]` | 基于位置,重复不会混淆——但位置本身未被校验 |
226
+ | 从未展示给模型的行 | `[E_RANGE_UNSERVED]`——硬拒绝并回传新锚点 | 未展示的 hunk 被拒绝——同样依赖模型知道自己看过什么 |
227
+ | 表达式中间 / 错误的块节点 | 无关——任何已校验的行范围都合法 | 语法规则 + `PUT N*:` 节点选择;点错(锚在 `def` 会让装饰器变成孤儿)会悄悄落错;无语法检查 |
228
+ | 多编辑批量中途失败 | `edit` 多条目——原子、全有或全无;失败项以新锚点回显 | 多段补丁先预检——同样原子 |
229
229
 
230
230
  > oh-my-pi 42–53% 的负载节省来自更轻的线格式;上表才是该格式反过来要求模型记在脑中的东西——重新编号、追标签、选节点——而这恰恰是最容易出错的组件(替换式编辑的补丁失败率 46–51%)。本插件 31% 的代价买来的是一个“错编辑落不了地、任何拒绝都不需要重读”的契约。
231
231
 
@@ -233,25 +233,25 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
233
233
 
234
234
  在同一份 103 行文件上、用相同的 12 组替换(8 个单行、4 个 3/6/10/15 行多行),以固定的 `js-tiktoken` `cl100k_base` 词表测量。三个被测方发出相同的替换文本:本插件的 `edit`(两个 3 字符锚点)、`str_replace` 工具(逐字回显旧文本)、以及 [`@oh-my-pi/hashline`](https://www.npmjs.com/package/@oh-my-pi/hashline) 的两种模式——每次编辑一个 `[path#tag]` 段(`seq`)和一个多 hunk 批量文档(`batch`):
235
235
 
236
- | 指标 | hashline | str_replace | oh-my-pi seq / batch |
237
- | ----------- | :---: | :---: | :---: |
238
- | 被替换文本是否上线 | ✅ 从不 | ❌ 每次编辑都发 | ✅ 从不 |
239
- | 输出 token 节省(12 次编辑) | ✅ **31%** | ❌ 0% | ✅ **42% / 53%** |
240
- | 多行范围节省(3–15 行) | ✅ **29–47%** | ❌ 0% | ✅ **40–53%** |
241
- | 按 5 倍输出计价的实际成本 | ✅ **低约 1.4 倍** | ❌ 1× | ✅ **低约 1.7 倍 / 2.1 倍** |
242
- | 范围对照已提供状态校验 | ✅ 100% | ❌ 无 | ~ 仅文件版本 |
243
- | 模型需要跟踪的行号 | ✅ 无——内容锚点 | ✅ 无——文本匹配 | ❌ 每次编辑重新编号 |
244
- | 确定性、可在本地复现 | ✅ `npm run benchmark` | — | — |
236
+ | 指标 | hashline | str_replace | oh-my-pi seq / batch |
237
+ | ---------------------------- | :--------------------: | :-------------: | :-------------------------: |
238
+ | 被替换文本是否上线 | ✅ 从不 | ❌ 每次编辑都发 | ✅ 从不 |
239
+ | 输出 token 节省(12 次编辑) | ✅ **31%** | ❌ 0% | ✅ **42% / 53%** |
240
+ | 多行范围节省(3–15 行) | ✅ **29–47%** | ❌ 0% | ✅ **40–53%** |
241
+ | 按 5 倍输出计价的实际成本 | ✅ **低约 1.4 倍** | ❌ 1× | ✅ **低约 1.7 倍 / 2.1 倍** |
242
+ | 范围对照已提供状态校验 | ✅ 100% | ❌ 无 | ~ 仅文件版本 |
243
+ | 模型需要跟踪的行号 | ✅ 无——内容锚点 | ✅ 无——文本匹配 | ❌ 每次编辑重新编号 |
244
+ | 确定性、可在本地复现 | ✅ `npm run benchmark` | — | — |
245
245
 
246
246
  ### 可复现
247
247
 
248
248
  上面的数字**是确定性的,你可以本地复现**——`npm run benchmark`:
249
249
 
250
- | 场景 | 行数 | hashline | str_replace | oh-my-pi seq | oh-my-pi batch |
251
- | --- | :---: | :---: | :---: | :---: | :---: |
252
- | 单行 ×8 | 1 | 309 | 324 | 241 | — |
253
- | 多行 ×4 | 3–15 | 393 | 691 | 349 | — |
254
- | **合计 ×12** | | **702** | **1015** | **590** | **480** |
250
+ | 场景 | 行数 | hashline | str_replace | oh-my-pi seq | oh-my-pi batch |
251
+ | ------------ | :--: | :------: | :---------: | :----------: | :------------: |
252
+ | 单行 ×8 | 1 | 309 | 324 | 241 | — |
253
+ | 多行 ×4 | 3–15 | 393 | 691 | 349 | — |
254
+ | **合计 ×12** | | **702** | **1015** | **590** | **480** |
255
255
 
256
256
  相对 `str_replace` 的节省:hashline **313(31%)** · oh-my-pi 逐次 **425(42%)** · oh-my-pi 批量 **535(53%)**。
257
257
 
@@ -261,39 +261,39 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
261
261
 
262
262
  ## 工具
263
263
 
264
- | 工具 | 作用 |
265
- | ------ | ------ |
266
- | `read` | 以 `HASH│内容` 形式返回文件。参数:`offset`(1 起始)、`limit`。分页输出以 `[Showing lines N-M of T. Use offset=… to continue.]` 结尾。超过 200KB 的行显示为标记并附 `sed` 提示——哈希锚点需要完整行。 |
267
- | `edit` | 对象根负载 `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], …] }`;`path` 可为 `null` 以通过锚点推断。单个条目编辑一个范围;多条目对同一文件原子批量(最多 32)。对每个包含范围内的每一行校验,reject-and-serve 返回新锚点。 |
268
- | `undo_last_edit` | `{ path }` 撤销该文件上一次 hashline 编辑,仅当文件仍与存储的编辑后内容一致时生效;重启后依然有效。 |
264
+ | 工具 | 作用 |
265
+ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
266
+ | `read` | 以 `HASH│内容` 形式返回文件。参数:`offset`(1 起始)、`limit`。分页输出以 `[Showing lines N-M of T. Use offset=… to continue.]` 结尾。超过 200KB 的行显示为标记并附 `sed` 提示——哈希锚点需要完整行。 |
267
+ | `edit` | 对象根负载 `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], …] }`;`path` 可为 `null` 以通过锚点推断。单个条目编辑一个范围;多条目对同一文件原子批量(最多 32)。对每个包含范围内的每一行校验,reject-and-serve 返回新锚点。 |
268
+ | `undo_last_edit` | `{ path }` 撤销该文件上一次 hashline 编辑,仅当文件仍与存储的编辑后内容一致时生效;重启后依然有效。 |
269
269
 
270
270
  内置 `write` 仍用于整文件替换。执行前,插件只会在候选行以同一会话、规范路径及行位置所提供的精确 `HASH│` 锚点开头时拒绝;文件保持不变,并提示仅用文件正文重试。插件不会泛化地剥离类似哈希的文本。
271
271
 
272
272
  ### 错误码
273
273
 
274
- | 代码 | 含义 |
275
- | --- | --- |
276
- | `[E_ACCESS]` | 文件存在但工具不可读/不可写。 |
277
- | `[E_AMBIGUOUS_ANCHOR]` | 一个哈希匹配当前多行;调用 `read` 获取新锚点。 |
278
- | `[E_BAD_OP]` | 范围结束先于范围开始(首尾颠倒时会自动纠正)。 |
279
- | `[E_BAD_REF]` | `remove_from`/`remove_to` 不是裸 3 字符哈希。 |
280
- | `[E_BAD_SHAPE]` | 请求/字段形态错误(未知字段、缺少 path、非字符串文本等)。 |
281
- | `[E_BARE_HASH_PREFIX]` | `HASH│` 前缀被粘贴进 `replacement_text`(自动纠正)。 |
282
- | `[E_BATCH_ABORT]` | 批次内某项失败;整个批次被拒绝,未写入任何内容。 |
283
- | `[E_FILE_TOO_LARGE]` | 文件超过 hashline 行数上限;请改用 `write` 或其他方式。 |
284
- | `[E_INVALID_PATCH]` | diff 预览标记被粘贴进 `replacement_text`(自动纠正)。 |
285
- | `[E_NOOP_LOOP]` | 完全相同的编辑反复不产生任何变化;再次提交会被拒绝。 |
286
- | `[E_NOT_FOUND]` | 文件不存在。 |
287
- | `[E_NOT_OBSERVED]` | 该文件在本会话中尚未被观察(先读后写策略);请先调用 `read`。 |
288
- | `[E_NOT_TEXT]` | 路径是目录、二进制或非 UTF-8 文件;hashline 只能编辑文本。 |
289
- | `[E_WRITE_HASH_ECHO]` | 内置 `write` 候选内容复制了同一会话、路径及行位置所提供的 `HASH│` 预览锚点。写入在执行前被拒绝;移除整条复制的锚点链后重试。 |
290
- | `[E_RANGE_STALE]` | 某行自被读取以来在磁盘上发生变化;范围以全新锚点回显。 |
291
- | `[E_RANGE_UNSERVED]` | 范围内包含从未提供给模型的行。 |
292
- | `[E_RANGE_UNVERIFIED]` | 边界锚点无法对照已提供状态验证。 |
293
- | `[E_STALE_ANCHOR]` | 锚点不再能解析;调用 `read` 获取新锚点。 |
294
- | `[E_UNDO_STALE]` | 无法撤销:编辑之后文件被修改(或删除)。 |
295
- | `[E_UNDO_UNAVAILABLE]` | 撤销历史无法持久化;编辑未被应用。 |
296
- | `[E_WOULD_EMPTY]` | 编辑会把非空文件清空;请用 `write` 清空。 |
274
+ | 代码 | 含义 |
275
+ | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
276
+ | `[E_ACCESS]` | 文件存在但工具不可读/不可写。 |
277
+ | `[E_AMBIGUOUS_ANCHOR]` | 一个哈希匹配当前多行;调用 `read` 获取新锚点。 |
278
+ | `[E_BAD_OP]` | 范围结束先于范围开始(首尾颠倒时会自动纠正)。 |
279
+ | `[E_BAD_REF]` | `remove_from`/`remove_to` 不是裸 3 字符哈希。 |
280
+ | `[E_BAD_SHAPE]` | 请求/字段形态错误(未知字段、缺少 path、非字符串文本等)。 |
281
+ | `[E_BARE_HASH_PREFIX]` | `HASH│` 前缀被粘贴进 `replacement_text`(自动纠正)。 |
282
+ | `[E_BATCH_ABORT]` | 批次内某项失败;整个批次被拒绝,未写入任何内容。 |
283
+ | `[E_FILE_TOO_LARGE]` | 文件超过 hashline 行数上限;请改用 `write` 或其他方式。 |
284
+ | `[E_INVALID_PATCH]` | diff 预览标记被粘贴进 `replacement_text`(自动纠正)。 |
285
+ | `[E_NOOP_LOOP]` | 完全相同的编辑反复不产生任何变化;再次提交会被拒绝。 |
286
+ | `[E_NOT_FOUND]` | 文件不存在。 |
287
+ | `[E_NOT_OBSERVED]` | 该文件在本会话中尚未被观察(先读后写策略);请先调用 `read`。 |
288
+ | `[E_NOT_TEXT]` | 路径是目录、二进制或非 UTF-8 文件;hashline 只能编辑文本。 |
289
+ | `[E_WRITE_HASH_ECHO]` | 内置 `write` 候选内容复制了同一会话、路径及行位置所提供的 `HASH│` 预览锚点。写入在执行前被拒绝;移除整条复制的锚点链后重试。 |
290
+ | `[E_RANGE_STALE]` | 某行自被读取以来在磁盘上发生变化;范围以全新锚点回显。 |
291
+ | `[E_RANGE_UNSERVED]` | 范围内包含从未提供给模型的行。 |
292
+ | `[E_RANGE_UNVERIFIED]` | 边界锚点无法对照已提供状态验证。 |
293
+ | `[E_STALE_ANCHOR]` | 锚点不再能解析;调用 `read` 获取新锚点。 |
294
+ | `[E_UNDO_STALE]` | 无法撤销:编辑之后文件被修改(或删除)。 |
295
+ | `[E_UNDO_UNAVAILABLE]` | 撤销历史无法持久化;编辑未被应用。 |
296
+ | `[E_WOULD_EMPTY]` | 编辑会把非空文件清空;请用 `write` 清空。 |
297
297
 
298
298
  ## 如何替换内置工具
299
299
 
@@ -375,7 +375,7 @@ MIT License——详见 [LICENSE](LICENSE)。移植自 pi-hashline-edit-lsz(MI
375
375
 
376
376
  ## 致谢
377
377
 
378
- 哈希锚定编辑源于 Can Bölük 的 [*The Harness Problem*](https://stencil.so/blog/the-harness-problem)——那篇文章证明了瓶颈在于 harness 而非模型,并证明锚定编辑优于搜索替换。本项目站在以下巨人的肩膀上:
378
+ 哈希锚定编辑源于 Can Bölük 的 [_The Harness Problem_](https://stencil.so/blog/the-harness-problem)——那篇文章证明了瓶颈在于 harness 而非模型,并证明锚定编辑优于搜索替换。本项目站在以下巨人的肩膀上:
379
379
 
380
380
  - [**pi-hashline-edit**](https://github.com/RimuruW/pi-hashline-edit)(RimuruW)——引入 3 字符哈希与冲突消解的原创 pi-coding-agent 扩展。
381
381
  - [**pi-hashline-edit-pro**](https://github.com/YuGiMob/pi-hashline-edit-pro)(YuGiMob)——本仓库 hashline 核心所移植自的加固版 fork。
@@ -14,7 +14,10 @@ function splitAfterRoot(absolutePath) {
14
14
  const { root } = parse(absolutePath);
15
15
  return {
16
16
  root,
17
- parts: absolutePath.slice(root.length).split(sep).filter((p) => p.length > 0),
17
+ parts: absolutePath
18
+ .slice(root.length)
19
+ .split(sep)
20
+ .filter((p) => p.length > 0),
18
21
  };
19
22
  }
20
23
  function eLoopError(ws) {
package/lib/contract.js CHANGED
@@ -4,8 +4,8 @@
4
4
  * declared once here; every tool validates through these asserts, and the
5
5
  * [E_BAD_PAYLOAD] vocabulary is shared instead of re-implemented per tool.
6
6
  *
7
- * Contract now mirrors upstream ADR-0007: {path: string|null, edits: [[remove_from,remove_to,replacement_text],...]} tuple payload,
8
- * single-file, atomic. batch_edit is removed.
7
+ * Contract now mirrors upstream ADR-0007: {path: string|null, edits: [[remove_from,remove_to,replacement_text],...]} tuple payload
8
+ * (plus object-form {remove_from, remove_to, replacement_text} per #64), single-file, atomic. batch_edit is removed.
9
9
  * @module dsh-better-edit/contract
10
10
  */
11
11
  import { EDITS_MAX_ITEMS } from "./constants.js";
@@ -19,10 +19,34 @@ export function itemFromTuple(value) {
19
19
  if (!Array.isArray(value) || value.length !== 3)
20
20
  return undefined;
21
21
  const [remove_from, remove_to, replacement_text] = value;
22
- if (typeof remove_from !== "string" || typeof remove_to !== "string" || typeof replacement_text !== "string")
22
+ if (typeof remove_from !== "string" ||
23
+ typeof remove_to !== "string" ||
24
+ typeof replacement_text !== "string")
23
25
  return undefined;
24
26
  return { remove_from, remove_to, replacement_text };
25
27
  }
28
+ /**
29
+ * Accept both the tuple form (["a", "b", "c"]) and the object form
30
+ * ({ remove_from, remove_to, replacement_text }) per edits entry (#64).
31
+ * Missing/mistyped fields and unknown fields still return undefined so the
32
+ * caller rejects with E_BAD_PAYLOAD.
33
+ */
34
+ export function itemFromEntry(value) {
35
+ if (Array.isArray(value))
36
+ return itemFromTuple(value);
37
+ if (isRec(value)) {
38
+ const rec = value;
39
+ const { remove_from, remove_to, replacement_text } = rec;
40
+ if (typeof remove_from !== "string" ||
41
+ typeof remove_to !== "string" ||
42
+ typeof replacement_text !== "string")
43
+ return undefined;
44
+ if (Object.keys(rec).some((k) => !EDIT_ITEM_KS.has(k)))
45
+ return undefined;
46
+ return { remove_from, remove_to, replacement_text };
47
+ }
48
+ return undefined;
49
+ }
26
50
  export function editRequestFrom(input) {
27
51
  if (!isRec(input) || !("path" in input) || !("edits" in input))
28
52
  return undefined;
@@ -42,13 +66,14 @@ export function editRequestFrom(input) {
42
66
  return undefined;
43
67
  effectivePath = sanitized;
44
68
  }
45
- if (effectivePath !== null && (typeof effectivePath !== "string" || effectivePath.length === 0))
69
+ if (effectivePath !== null &&
70
+ (typeof effectivePath !== "string" || effectivePath.length === 0))
46
71
  return undefined;
47
72
  if (!Array.isArray(edits) || edits.length === 0)
48
73
  return undefined;
49
74
  const items = [];
50
75
  for (const item of edits) {
51
- const normalized = itemFromTuple(item);
76
+ const normalized = itemFromEntry(item);
52
77
  if (!normalized)
53
78
  return undefined;
54
79
  items.push(normalized);
@@ -97,8 +122,10 @@ export function sanitizePath(value) {
97
122
  }
98
123
  export const EDIT_TUPLE_HINT = "Edit must be called with exactly one payload. Use the canonical payload " +
99
124
  '{"path": path, "edits": [[remove_from, remove_to, replacement_text], ...]}: ' +
100
- "path is a non-empty string (or null to infer from anchors), each item is a " +
101
- "fixed 3-position array of two inclusive bare-3-char anchors and the full " +
125
+ "path is a non-empty string (or null to infer from anchors), each item is " +
126
+ "either a fixed 3-position array [remove_from, remove_to, replacement_text] " +
127
+ "or an object {remove_from, remove_to, replacement_text} (mixed batches allowed) " +
128
+ "of two inclusive bare-3-char anchors and the full " +
102
129
  "replacement (an empty string deletes the range).";
103
130
  function describeReceived(input) {
104
131
  if (input === undefined)
@@ -114,6 +141,7 @@ function describeReceived(input) {
114
141
  // ---- filed sets (declared once) ---------------------------------------------
115
142
  const EDIT_KS = new Set(["path", "edits", "sandbox_permissions", "justification"]);
116
143
  const READ_KS = new Set(["path", "offset", "limit", "encoding"]);
144
+ const EDIT_ITEM_KS = new Set(["remove_from", "remove_to", "replacement_text"]);
117
145
  // ---- normalization -----------------------------------------------------------
118
146
  /**
119
147
  * Normalize `file_path` → `path` alias on the request record and tuple edits → objects.
@@ -153,12 +181,12 @@ export function prepareEditArguments(args) {
153
181
  // ---- assertions ---------------------------------------------------------------
154
182
  export function assertEditRequest(request) {
155
183
  if (!isNormalizedEdit(request)) {
156
- throw new CodedError("E_BAD_PAYLOAD", "[MODEL] [E_BAD_PAYLOAD] Edit request must be exactly { path, edits: [[remove_from, remove_to, replacement_text], ...] }.");
184
+ throw new CodedError("E_BAD_PAYLOAD", "[MODEL] [E_BAD_PAYLOAD] Edit request must be exactly { path, edits: [[remove_from, remove_to, replacement_text], ...] } or { path, edits: [{remove_from, remove_to, replacement_text}, ...] } (mixed batches allowed).");
157
185
  }
158
186
  rejectUnknownFields(request, EDIT_KS, "Edit request");
159
187
  const req = request;
160
188
  if (req.path !== null && (typeof req.path !== "string" || req.path.length === 0)) {
161
- throw new CodedError("E_BAD_PAYLOAD", '[MODEL] [E_BAD_PAYLOAD] Edit request path must be a non-empty string or null.');
189
+ throw new CodedError("E_BAD_PAYLOAD", "[MODEL] [E_BAD_PAYLOAD] Edit request path must be a non-empty string or null.");
162
190
  }
163
191
  if (!Array.isArray(req.edits) || req.edits.length === 0) {
164
192
  throw new CodedError("E_BAD_PAYLOAD", '[MODEL] [E_BAD_PAYLOAD] Edit request requires a non-empty "edits" array.');
@@ -168,8 +196,10 @@ export function assertEditRequest(request) {
168
196
  }
169
197
  for (let index = 0; index < req.edits.length; index++) {
170
198
  const item = req.edits[index];
171
- if (typeof item.remove_from !== "string" || typeof item.remove_to !== "string" || typeof item.replacement_text !== "string") {
172
- throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] Edit request edits[${index}] must be a three-position array [remove_from, remove_to, replacement_text].`);
199
+ if (typeof item.remove_from !== "string" ||
200
+ typeof item.remove_to !== "string" ||
201
+ typeof item.replacement_text !== "string") {
202
+ throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] Edit request edits[${index}] must be a three-position array [remove_from, remove_to, replacement_text] or an object {remove_from, remove_to, replacement_text}.`);
173
203
  }
174
204
  }
175
205
  }
@@ -195,46 +225,61 @@ export function assertUndoRequest(request) {
195
225
  }
196
226
  // ---- shared JSON Schema literals (co-located with field sets) ---------------
197
227
  export const replacementTextSchema = {
198
- type: 'string',
228
+ type: "string",
199
229
  description: 'Complete replacement for the range; use "" to delete',
200
230
  };
201
231
  export const removeFromSchema = {
202
- type: 'string',
232
+ type: "string",
203
233
  description: "First line to remove (inclusive)",
204
234
  };
205
235
  export const removeToSchema = {
206
- type: 'string',
236
+ type: "string",
207
237
  description: "Last line to remove (inclusive)",
208
238
  };
209
239
  export const pathSchema = {
210
- type: 'string',
240
+ type: "string",
211
241
  description: "File path; null infers it from anchors",
212
242
  };
213
243
  export const editPathSchema = {
214
244
  anyOf: [
215
- { type: 'string', minLength: 1, description: "File path; null infers it from anchors" },
216
- { type: 'null', description: "null infers path from anchors" },
245
+ { type: "string", minLength: 1, description: "File path; null infers it from anchors" },
246
+ { type: "null", description: "null infers path from anchors" },
217
247
  ],
218
248
  };
219
249
  export const editTupleSchema = {
220
- type: 'array',
250
+ type: "array",
221
251
  prefixItems: [removeFromSchema, removeToSchema, replacementTextSchema],
222
252
  minItems: 3,
223
253
  maxItems: 3,
224
254
  description: "[remove_from, remove_to, replacement_text]",
225
255
  };
256
+ export const editObjectSchema = {
257
+ type: "object",
258
+ additionalProperties: false,
259
+ required: ["remove_from", "remove_to", "replacement_text"],
260
+ properties: {
261
+ remove_from: removeFromSchema,
262
+ remove_to: removeToSchema,
263
+ replacement_text: replacementTextSchema,
264
+ },
265
+ description: "{remove_from, remove_to, replacement_text}",
266
+ };
267
+ export const editItemSchema = {
268
+ anyOf: [editTupleSchema, editObjectSchema],
269
+ description: "Edit entry — either tuple or object form (mixed batches allowed)",
270
+ };
226
271
  export const editToolSchema = {
227
- type: 'object',
272
+ type: "object",
228
273
  additionalProperties: false,
229
274
  required: ["path", "edits"],
230
275
  properties: {
231
276
  path: editPathSchema,
232
277
  edits: {
233
- type: 'array',
234
- description: "Ordered list of edit tuples",
278
+ type: "array",
279
+ description: "Ordered list of edit entries — each entry is either a tuple [remove_from, remove_to, replacement_text] or an object {remove_from, remove_to, replacement_text} (mixed batches allowed)",
235
280
  minItems: 1,
236
281
  maxItems: EDITS_MAX_ITEMS,
237
- items: editTupleSchema,
282
+ items: editItemSchema,
238
283
  },
239
284
  },
240
285
  };
package/lib/edit-diff.js CHANGED
@@ -80,11 +80,7 @@ export function genDiff(oldContent, newContent, contextLines = 2, newContentHash
80
80
  }
81
81
  else if (nextPartIsChange && displayLines.length > contextLines * 2) {
82
82
  const tail = displayLines.slice(-contextLines);
83
- linesToShow = [
84
- ...displayLines.slice(0, contextLines),
85
- ELLIPSIS_MARKER,
86
- ...tail,
87
- ];
83
+ linesToShow = [...displayLines.slice(0, contextLines), ELLIPSIS_MARKER, ...tail];
88
84
  skipMiddle = displayLines.length - contextLines * 2;
89
85
  }
90
86
  else if (linesToShow.length > contextLines) {
package/lib/encoding.js CHANGED
@@ -55,14 +55,23 @@ export function isSupportedEncoding(enc) {
55
55
  const norm = normalizeEncoding(enc);
56
56
  if (!norm)
57
57
  return false;
58
- return SUPPORTED_ENCODINGS.includes(norm) || ["utf8", "utf8bom", "utf16le", "utf16be", "utf32le", "utf32be"].includes(norm);
58
+ return (SUPPORTED_ENCODINGS.includes(norm) ||
59
+ ["utf8", "utf8bom", "utf16le", "utf16be", "utf32le", "utf32be"].includes(norm));
59
60
  }
60
61
  export function detectBom(bytes) {
61
62
  if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf)
62
63
  return { encoding: "utf8bom", bomLen: 3, hasBOM: true };
63
- if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xfe && bytes[2] === 0x00 && bytes[3] === 0x00)
64
+ if (bytes.length >= 4 &&
65
+ bytes[0] === 0xff &&
66
+ bytes[1] === 0xfe &&
67
+ bytes[2] === 0x00 &&
68
+ bytes[3] === 0x00)
64
69
  return { encoding: "utf32le", bomLen: 4, hasBOM: true };
65
- if (bytes.length >= 4 && bytes[0] === 0x00 && bytes[1] === 0x00 && bytes[2] === 0xfe && bytes[3] === 0xff)
70
+ if (bytes.length >= 4 &&
71
+ bytes[0] === 0x00 &&
72
+ bytes[1] === 0x00 &&
73
+ bytes[2] === 0xfe &&
74
+ bytes[3] === 0xff)
66
75
  return { encoding: "utf32be", bomLen: 4, hasBOM: true };
67
76
  if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe)
68
77
  return { encoding: "utf16le", bomLen: 2, hasBOM: true };
@@ -287,7 +296,11 @@ export async function chardetTop3Candidates(bytes, allowlist) {
287
296
  if (idx === -1)
288
297
  return text.slice(0, 50);
289
298
  const start = Math.max(0, idx - 32);
290
- return text.slice(start, start + 64).slice(0, 50).replace(/\s+/g, " ").trim();
299
+ return text
300
+ .slice(start, start + 64)
301
+ .slice(0, 50)
302
+ .replace(/\s+/g, " ")
303
+ .trim();
291
304
  })();
292
305
  out.push({ encoding: norm, confidence: r.confidence, sample });
293
306
  if (out.length >= 3)
@@ -302,7 +315,11 @@ export async function chardetTop3Candidates(bytes, allowlist) {
302
315
  export async function getTop3Candidates(bytes, allowlist) {
303
316
  const chardetCands = await chardetTop3Candidates(bytes, allowlist);
304
317
  if (chardetCands.length > 0) {
305
- return chardetCands.map((c) => ({ encoding: c.encoding, sample: c.sample, score: c.confidence }));
318
+ return chardetCands.map((c) => ({
319
+ encoding: c.encoding,
320
+ sample: c.sample,
321
+ score: c.confidence,
322
+ }));
306
323
  }
307
324
  return top3Candidates(bytes, allowlist);
308
325
  }