dsh-better-edit 1.0.0 → 1.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.
package/CHANGELOG.md CHANGED
@@ -11,6 +11,37 @@ All notable changes to this project will be documented in this file.
11
11
 
12
12
  ## [Unreleased]
13
13
 
14
+ ## [1.2.0] - 2026-10-29
15
+
16
+ ### Features
17
+
18
+ * **edit-diff:** formalize single-projection contract with counted span markers (#92)
19
+
20
+ ### Bug Fixes
21
+
22
+ * **edit-diff:** render ctx-0 middle gaps marker-only with correct skip (#92)
23
+ * **edit-diff:** render small middle gaps whole, keep anchors aligned (#92)
24
+
25
+ ### Documentation
26
+
27
+ * **agents:** replace CONTEXT with GLOSSARY single-context (#86)
28
+ * **absorb:** record the upstream v2.3.0 gap-projection range — basis `b92e0ec`..`v2.3.0`, 3 semantic commits ported (`31d67d8` small middle gaps render whole with aligned anchors, `71e0107` single-projection contract with counted span markers, `ab06895` ctx-0 middle gaps marker-only with correct skip); the release commit `0925f1a` is deliberately not ported and no downstream version bump rides the absorb (#92)
29
+
30
+ ## [1.1.0] - 2026-10-22
31
+
32
+ ### Bug Fixes
33
+
34
+ * **dsh:** follow the session's live working directory instead of the immutable creation header - a `working_directory` change now retargets relative-path resolution and the per-workspace store (the 0.2.1 `workingDirectory` service; the header stays as the pre-0.2.1 fallback) (#83)
35
+ * **guidance:** derive each tool section's default order from the harness's canonical slot (`systemPrompt.getSectionOrder` for `TOOL_READ`/`TOOL_EDIT`, with a `1100`/`1300`/`1310` fallback) and seed the shipped `ptc` preset in place of the retired `code` (#83)
36
+
37
+ ### Documentation
38
+
39
+ * **docs:** state and document dsh `0.2.0+` support in both READMEs, and sync the plugin-authoring skill for `0.2.1-rc.2` - `agent/created`, the 1000-band section orders, the `workingDirectory` seam, the shipped preset ids, and `sandboxPermissionsDescription` (#83)
40
+
41
+ ### Miscellaneous Chores
42
+
43
+ * **deps:** upgrade the `@deepseek-ai/dsh-*` dev baseline to `0.2.1-rc.2` and `@deepseek-ai/cordis` to `4.0.5` (#83)
44
+
14
45
  ## [1.0.0] - 2026-09-27
15
46
 
16
47
  ### Features
package/README.md CHANGED
@@ -4,8 +4,8 @@
4
4
 
5
5
  <h1 align="center">dsh-better-edit</h1>
6
6
  <p align="center">
7
- <strong>A better edit tool for DeepSeek Harness<br>
8
- Position-free hashes — one read, many edits, fewer tokens, more room for real work.</strong>
7
+ <strong>High-precision, hash-anchored file editing for DeepSeek Harness (dsh).</strong><br>
8
+ Replaces fragile line numbers and token-wasting code echoes with content-addressed line hashes &mdash; 0 silent miswrites, 0 token re-reads.
9
9
  </p>
10
10
  <p align="center">
11
11
  <strong>English</strong> ·
@@ -13,14 +13,15 @@
13
13
  </p>
14
14
 
15
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>
16
+ <a href="#why-you-need-it"><img src="https://img.shields.io/badge/why-hashline-blue?style=flat" alt="why hashline"></a>
17
17
  <a href="#quick-start"><img src="https://img.shields.io/badge/quick_start-30s-brightgreen?style=flat" alt="quick start 30s"></a>
18
18
  <a href="#benchmark"><img src="https://img.shields.io/badge/correctness-23%2F23-success?style=flat" alt="23/23 battery"></a>
19
19
  </p>
20
20
 
21
21
  <p align="center">
22
+ <a href="#why-you-need-it">Why You Need It</a> •
23
+ <a href="#core-pillars">Core Pillars</a> •
22
24
  <a href="#quick-start">Quick Start</a> •
23
- <a href="#why-hashline">Why Hashline</a> •
24
25
  <a href="#tools">Tools</a> •
25
26
  <a href="#benchmark">Benchmark</a> •
26
27
  <a href="#how-anchors-work">How Anchors Work</a> •
@@ -28,7 +29,7 @@
28
29
  </p>
29
30
 
30
31
  <p align="center">
31
- <img src="https://img.shields.io/badge/version-0.7.0-blue.svg" alt="Version">
32
+ <img src="https://img.shields.io/badge/version-1.0.0-blue.svg" alt="Version">
32
33
  <img src="https://img.shields.io/badge/license-MIT-green.svg" alt="MIT License">
33
34
  <img src="https://img.shields.io/badge/DeepSeek_Harness-Plugin-blueviolet.svg" alt="DeepSeek Harness Plugin">
34
35
  <img src="https://img.shields.io/npm/v/dsh-better-edit" alt="npm version">
@@ -42,31 +43,55 @@
42
43
 
43
44
  ---
44
45
 
45
- > _"The harness — not the model — is the bottleneck."_ — Can Bölük, [_The Harness Problem_](https://stencil.so/blog/the-harness-problem)
46
+ > **What is `dsh-better-edit`?**
47
+ > A high-precision file editing plugin for [DeepSeek Harness (`dsh`)](https://github.com/deepseek-ai) that replaces volatile line numbers and token-wasting code echoes with immutable, content-addressed 3-character line hashes (`szJ│code`).
48
+ >
49
+ > **Core Philosophy:** Local compute is free; **the model's context window is the most precious resource**. By shifting verification, snapshotting, and alignment to the host, `dsh-better-edit` slashes output tokens by 40–60%, auto-rebases external file drift (e.g., Prettier, Git), and eliminates silent miswrites without forcing full-file re-reads.
46
50
 
47
- > **This is the harness fix.** Hashes replace line numbers — edits above don't shift anchors below. One `read` serves many `edit`s; drift outside your range passes with a notice, true conflicts retry with fresh anchors — no full `read` needed.
51
+ ---
48
52
 
49
- > **3 calls vs 6 · -55.8% tokens · 23/23 correctness.** Same external-drift refactor, same file (single stochastic run; [method](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/results/2026-08-17-practical-token-benchmark.md)). Payload numbers are deterministic — see [Benchmark](#benchmark).
53
+ ## Why You Need It
50
54
 
51
- ## Why you need this
55
+ ### The 3 Fatal Editing Traps of Autonomous Coding Agents
52
56
 
53
- **If you've watched `line 47 → 74` corrupt a file after an insert — this is for you.**
57
+ File editing is the #1 point of failure for autonomous agents. Traditional tools break down in three distinct ways:
54
58
 
55
- | Before: `str_replace` / line numbers | After: hashline `edit` |
56
- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
57
- | Re-types old code (~5-6× billed) | Two `3-char` hashes, old text never echoed |
58
- | One insert shifts every number → silent wrong line | Content addresses — edits above don't move anchors below |
59
- | No check against what was shown | Every line verified; `[E_STALE_RANGE]`/`[E_UNSERVED_RANGE]` reject before write, then **reject-and-serve** returns fresh `HASH│content` |
59
+ | Fatal Trap in Traditional Tools | Why It Breaks Agents | How `dsh-better-edit` Solves It |
60
+ | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
61
+ | **`str_replace` Token Bleed** | Must re-type 30+ lines of unchanged code just to change 1 line ($O(S+R)$), burning expensive output tokens (billed ~5–6× input). | **$O(R)$ Payloads**: Sends only two 3-char hashes (`anchor_from`, `anchor_to`) + replacement. Cuts output tokens by 40–60%. |
62
+ | **Line-Number Coordinate Rot** | Inserting 1 line shifts all line numbers below it. Agents suffer off-by-one errors or must repeatedly re-read the file. | **Position-Independent Anchors**: Line hashes follow content, not line coordinates. Exterior shifts auto-rebase cleanly. |
63
+ | **Silent Miswrites & Drift** | Duplicate lines match the wrong function; external formatters (Prettier) or git updates cause blind overwrites or fatal errors. | **Content-Addressed Line Verification**: Unique anchors via coprime probing; format-tolerant whitespace hashing; fail-closed reject-and-serve. |
60
64
 
61
- > [!TIP]
62
- > **Shining points — honest:**
63
- >
64
- > - **Position-free.** `read 1..5` → `insert @0` → `edit 10..12` still lands at `10..12`. Anchors are `canon(line)` hashes, not positions (ADR-0013). Exterior drift is a notice, not a re-read.
65
- > - **Fewer round-trips.** Single-session `1 read → N edits` — no ritual re-reads. Multi-session exterior `A:10..12 / B:20..30` also passes; only overlapping `A∩B≠∅` retries once via `servedRows` (no full `read`). Harness `9/9` green.
66
- > - **Fewer tokens.** Compact payload `{path, edits:[[from,to,text]]}` + never echoing `old_string`; diff/echo/rejection rows count as serves. Envelope `-40%` pinned 12-edit corpus, session `-55.8%` on external-drift.
67
- > - **Concurrent-safe, not silent.** `retired anchor` per `(session,path)` epoch blocks re-bound `S@3→@3`; `retired` + `canon` + `hash` + `changed∩[L,R]` makes `pos-free` single-thread and `strict` only on true overlap. One retry vs silent wrong-line.
65
+ ---
66
+
67
+ ## Core Pillars
68
+
69
+ ### 1. 🪙 Token Economics (40–60% Context Savings)
70
+
71
+ - **$O(R)$ Edit Payloads**: The model emits only `{ "path": "...", "edits": [["a1b", "c3d", "..."]] }`, never echoing existing code.
72
+ - **Self-Serving Diffs**: Every applied edit returns fresh anchors in the post-edit diff — zero re-read roundtrips to chain edits.
73
+ - **Zero-Token Auto-Rebase**: Non-conflicting exterior shifts resolve locally without agent intervention — 0 tokens, 0 retries.
74
+ - **Atomic Multi-Item Batches**: Apply up to 32 same-file edits in one tool call; overlapping spans abort atomically (`[E_BATCH_ABORT]`) before touching disk.
68
75
 
69
- Not for one-line touch-ups (near parity) or new files (`write`). Pays off in long sessions and structural edits.
76
+ ### 2. 🛡️ Resistance to External Writes (Drift & Concurrency)
77
+
78
+ - **Auto-Formatter Immunity**: Strips ASCII whitespace before hashing. Prettier, Black, and ESLint format-on-save passes never rotate anchors.
79
+ - **Exterior Shift Auto-Rebase**: External edits, git checkouts, or background processes outside the edit span rebase seamlessly without agent intervention.
80
+ - **Fail-Closed Reject-and-Serve**: Contested interior spans fail closed without disk corruption and immediately return fresh on-disk rows in the error (`[E_STALE_RANGE]`, `[E_UNSERVED_RANGE]`) — recovering in **exactly 1 turn**.
81
+ - **Session-Keyed Leases**: Leases are isolated per session, preventing cross-agent race conditions or state pollution.
82
+
83
+ ### 3. 🎯 Zero Silent Miswrites
84
+
85
+ - **Decoupled Line Identity**: Lines are verified against served snapshot lineage, not ephemeral line coordinates.
86
+ - **Collision-Free Anchors**: Coprime bitset probing ensures duplicate lines in a file receive distinct, unambiguous 3-character hashes.
87
+ - **No Heuristic Guessing**: Retires fuzzy matching. If an anchor cannot be unambiguously resolved, it fails closed safely.
88
+ - **Persisted Undo**: `undo_last_edit` restores exact file content, BOM, line endings, and original anchors, persisting across session restarts.
89
+
90
+ ---
91
+
92
+ > _"The harness — not the model — is the bottleneck."_ — Can Bölük, [_The Harness Problem_](https://stencil.so/blog/the-harness-problem)
93
+ >
94
+ > **3 calls vs 6 · -55.8% tokens · 23/23 correctness.** Tested on realistic external-drift refactoring against OMP wrapper. Payload numbers are deterministic — see [Benchmark](#benchmark).
70
95
 
71
96
  ## Quick Start — install to verified edit in 30s
72
97
 
@@ -84,11 +109,14 @@ No config. Next session runs with hashline tools. Verify:
84
109
  dsh --profile <name> --dump-config # shows "# == dsh-better-edit" layer
85
110
  ```
86
111
 
87
- | Requirement | |
88
- | ----------- | ---------------------------------------- |
89
- | Node | `^22.19.0 \|\| >=24.0.0` |
90
- | Profile | `dsh` profile (`dsh plugin` creates one) |
91
- | Backends | sandboxed / remote `ctx.fs` |
112
+ | Requirement | |
113
+ | ----------- | --------------------------------------------------------------------------------- |
114
+ | Node | `^22.19.0 \|\| >=24.0.0` |
115
+ | Profile | `dsh` profile (`dsh plugin` creates one) |
116
+ | Backends | sandboxed / remote `ctx.fs` |
117
+ | dsh | `0.2.1-rc.2` (verified end-to-end; `0.1.6-alpha.2` was the last pre-0.2 baseline) |
118
+
119
+ **dsh 0.2.0+ is supported.** Registration uses `agent/created`, path resolution follows the session's live working directory (`workingDirectory`, with the session header as the pre-0.2.1 fallback), and tool-guidance order comes from `systemPrompt.getSectionOrder`. There is no peer range and no runtime version probing: compatibility comes from that stable surface plus optional-service fallbacks, so a composition that omits `workingDirectory` or `agentPresets` keeps working.
92
120
 
93
121
  ### See it work
94
122
 
@@ -150,7 +178,7 @@ storeMaxTotalBytes: 524288000 # 500 MB LRU
150
178
 
151
179
  Env overrides yaml (`DSH_BETTER_EDIT_STORE_DIR`, `DSH_BETTER_EDIT_AUTO_GITIGNORE`).
152
180
 
153
- **Guidance per preset** — `tool:read` / `tool:edit` / `tool:undo_last_edit` are plain markdown per preset at `$DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md` (orders `130/131/133`). Delete or empty a file → default re-seeds at next boot; keep a `---` fence to blank on purpose.
181
+ **Guidance per preset** — `tool:read` / `tool:edit` / `tool:undo_last_edit` are plain markdown per preset at `$DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md`. The default order is the harness's own tool slot (`systemPrompt.getSectionOrder`: `1100` read, `1300` edit, `1310` undo), so a band change upstream moves the sections with it; front-matter pins a custom order. The seeded roster is the shipped presets — `standard`, `ptc`, `minimal`, `cordis`. Delete or empty a file → default re-seeds at next boot; keep a `---` fence to blank on purpose.
154
182
 
155
183
  ## Why Hashline
156
184
 
@@ -281,12 +309,12 @@ Saved **313 (31%)**. Reproduce: upstream `npm run benchmark`. See [`pi-better-ed
281
309
 
282
310
  ## Roadmap
283
311
 
284
- **Current `0.7.0`:** pos-free `resist`/`strict` + retired anchor/canons/epoch, per-session `(session,path)` store, `1222` tests, `9/9` harness.
312
+ **Current `1.0.0`:** the v2 line-identity architecture, per-session `(session,path)` store, `1648` tests, dsh `0.2.1-rc.2`.
285
313
 
286
314
  <details><summary>Next</summary>
287
315
 
288
316
  - Keep `benchmark/run.mjs` in sync with `ADR-0013` (reads/retries/tokens per session)
289
- - Re-check wiring vs next `dsh` (pinned `0.1.0-rc.6`)
317
+ - Re-check wiring vs next `dsh` (pinned `0.2.1-rc.2`)
290
318
  - `README.zh.md` parity
291
319
 
292
320
  </details>
package/README.zh.md CHANGED
@@ -79,11 +79,14 @@ 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
+ | dsh | `0.2.1-rc.2`(已端到端验证;`0.1.6-alpha.2` 是上一个 0.2 之前的基线) |
88
+
89
+ **支持 dsh 0.2.0 及以上。** 注册走 `agent/created`,路径解析跟随会话的**实时**工作目录(`workingDirectory`,0.2.1 之前回退到 session header),工具指引的 order 取自 `systemPrompt.getSectionOrder`。没有 peer 版本范围,也不做运行时版本探测:兼容性来自这层稳定接口加可选服务回退——缺少 `workingDirectory` 或 `agentPresets` 的组合同样可用。
87
90
 
88
91
  `read` 返回的每一行都带有哈希前缀——哈希*就是*这一行的地址:
89
92
 
@@ -144,7 +147,7 @@ DSH_BETTER_EDIT_STORE_DIR=central|workspace|/abs
144
147
  DSH_BETTER_EDIT_AUTO_GITIGNORE=true|false # 大小写不敏感
145
148
  ```
146
149
 
147
- 旧的 `<workspace>/.dsh_better_edit/` 在首次以 central 打开时一次性拷贝;`runtime/<name>-<hash8>/` 可通过 `ls` 查看,带 `.wsPath` 旁路文件。生命周期详见 `docs/specs/issue-24-store-tenancy.md`(janitor `mtime>storeMaxAgeS` 后 LRU、WAL checkpoint、`undo` TTL)。
150
+ 旧的 `<workspace>/.dsh_better_edit/` 在首次以 central 打开时一次性拷贝;`runtime/<name>-<hash8>/` 可通过 `ls` 查看,带 `.wsPath` 旁路文件。工作区身份跟随会话的**实时**工作目录(`working_directory` 工具),而不是会话创建时的目录。生命周期详见 `docs/specs/issue-24-store-tenancy.md`(janitor `mtime>storeMaxAgeS` 后 LRU、WAL checkpoint、`undo` TTL)。
148
151
 
149
152
  #### 按 preset 的指引
150
153
 
@@ -158,11 +161,11 @@ $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
158
161
 
159
162
  | 文件 | 提示词片段 | 默认 order |
160
163
  | ------------------- | --------------------- | ---------- |
161
- | `read.md` | `tool:read` | 130 |
162
- | `edit.md` | `tool:edit` | 131 |
163
- | `undo_last_edit.md` | `tool:undo_last_edit` | 133 |
164
+ | `read.md` | `tool:read` | 1100 |
165
+ | `edit.md` | `tool:edit` | 1300 |
166
+ | `undo_last_edit.md` | `tool:undo_last_edit` | 1310 |
164
167
 
165
- 首次启动时插件会为三个随附 preset——`standard/`、`code/`、`minimal/`、`cordis/`——各自写入编译内置的可编辑指引文件(含 `order` front-matter)。详见[配置详情](#按-preset-配置指引)的重置/恢复。完整规范:`docs/specs/issue-24-store-tenancy.md` 与指引文档。
168
+ 首次启动时插件会为四个随附 preset——`standard/`、`ptc/`、`minimal/`、`cordis/`——各自写入编译内置的可编辑指引文件(含 `order` front-matter)。默认 order 取自 harness 自己的工具槽位(`systemPrompt.getSectionOrder`),上游调整 band 时会自动跟随;front-matter 可自行钉死。详见[配置详情](#按-preset-配置指引)的重置/恢复。完整规范:`docs/specs/issue-24-store-tenancy.md` 与指引文档。
166
169
 
167
170
  ##### 重置 / 恢复默认
168
171
 
@@ -177,7 +180,7 @@ $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
177
180
 
178
181
  - **为什么要连栅栏一起删**:只要文件里还有 `---` 栅栏,哪怕是空的、什么内容也没有,插件都当成“你有意留空”,不会去动它。所以“故意留空”就保留栅栏;“恢复默认”就把栅栏和内容一起清掉。
179
182
  - **栅栏写错了会怎样**:少了一个 `---`、`order` 不是数字、出现了不认识的键——只要栅栏格式不对,插件会直接忽略这个文件:仍然渲染默认指引,并在日志里提示是哪个文件、哪里写错了。你写的正文会原样留在磁盘上,方便改好后再用。
180
- - **自带 preset 与自定义 preset**:插件自带的四个 preset(`standard`、`code`、`minimal`、`cordis`)会在下一次启动时自动补全空白文件;自定义 preset 里删除的覆盖文件不会自动出现(删了就当“没有这个文件”)。删掉某一整个 preset 目录,下次启动时插件会重新生成里面的四个文件(仅限自带 preset)。
183
+ - **自带 preset 与自定义 preset**:插件自带的四个 preset(`standard`、`ptc`、`minimal`、`cordis`)会在下一次启动时自动补全空白文件;自定义 preset 里删除的覆盖文件不会自动出现(删了就当“没有这个文件”)。删掉某一整个 preset 目录,下次启动时插件会重新生成里面的三个片段文件(仅限自带 preset)。
181
184
  - **恢复的是“当前版本”的默认**:插件升级后,重置得到的是新版本带的新默认内容,不是旧版本留下的。
182
185
 
183
186
  文件的重新生成只发生在插件启动时,绝不影响进行中的会话。
@@ -354,14 +357,14 @@ npm publish --registry https://registry.npmjs.org # 版本未打 tag 前会被
354
357
 
355
358
  ## 路线图
356
359
 
357
- **当前状态(0.1.7):** 615 个测试、按工作区存储、参与沙箱策略、served-tail 截断修复、可复现基准测试、中英双语 README、已发布 npm。
360
+ **当前状态(1.0.0):** v2 行身份架构、按会话 `(session,path)` 存储、1648 个测试、中英双语 README、dsh `0.2.1-rc.2`。
358
361
 
359
362
  <details><summary>下一步</summary>
360
363
 
361
364
  - **缩小或证明与 @oh-my-pi/hashline 的差距**(参考:[`../oh-my-pi.md`](../oh-my-pi.md))。这个兄弟补丁语言负载更轻——基准测试中相对 `str_replace` 省 42%/53%,而我们省 31%,因为它裸文本式的补丁文档跳过了我们每次调用都要付的 JSON 外壳——还提供了我们不支持的四种能力:语法块操作(`PUT N*:`)、寄存器 + `REM`/`MV`、一次变更一个多 hunk 文档、可插拔文件系统。代价在正确性一侧:它的行号未经验证(当前标签下的错行号会静默落盘)、每次编辑都要重新编号、过期标签触发尽力而为的三方合并而非校验、语法也抬高了模型的技能门槛。逐项决定是拒绝还是采纳——负载差距本身不足以成为切换格式的理由。
362
- - 在 dsh 会话中实测 0.1.7(served-tail 修复之后)。
365
+ - 在 dsh 会话中实测 1.0.0(0.2.1-rc.2 运行时)。
363
366
  - 把 served-tail 截断修复回馈给 pi-hashline-edit-lsz / 上游(他们的 `upsertServed` 同样从不截断)。
364
- - 对照下一个 dsh 版本重新核对插件接线(当前固定在 `0.1.0-rc.6`;dsh 处于开发者预览阶段,承诺会有破坏性变更)。
367
+ - 对照下一个 dsh 版本重新核对插件接线(当前固定在 `0.2.1-rc.2`;dsh 处于开发者预览阶段,承诺会有破坏性变更)。
365
368
 
366
369
  </details>
367
370
 
package/lib/edit-diff.js CHANGED
@@ -32,8 +32,8 @@ function fmtDiffLine(prefix, line, hash) {
32
32
  }
33
33
  return `${prefix}${hash}${HASH_SEP}${line}`;
34
34
  }
35
- const ELLIPSIS_MARKER = Symbol("ellipsis");
36
- const isEllipsisMarker = (line) => line === ELLIPSIS_MARKER;
35
+ const UNTOUCHED_MARKER = Symbol("untouched");
36
+ const isUntouchedMarker = (line) => line === UNTOUCHED_MARKER;
37
37
  function formatRemovedLines(displayLines, oldContentHashes, oldLineNum) {
38
38
  const rows = [];
39
39
  let cursor = oldLineNum;
@@ -50,14 +50,28 @@ function formatRemovedLines(displayLines, oldContentHashes, oldLineNum) {
50
50
  const omitted = displayLines.length - DIFF_REMOVED_EDGE * 2;
51
51
  for (const line of displayLines.slice(0, DIFF_REMOVED_EDGE))
52
52
  emit(line);
53
- // WHY: ADR-0024/D3 — the model sees the deletion's head, tail, and exact size; the omitted rows
53
+ // WHY: ADR-0024/D3 — the model sees the deletion's head, tail, and exact size; the hidden rows
54
54
  // WHY: still advance the cursor so every later row keeps its exact old line number and hash.
55
- rows.push(` - ... [${omitted} lines omitted] ...`);
55
+ // WHY: #169 — the marker's count is the exact deleted span and uses the unified `lines deleted` diction.
56
+ rows.push(` - ... [${omitted} lines deleted] ...`);
56
57
  cursor += omitted;
57
58
  for (const line of displayLines.slice(-DIFF_REMOVED_EDGE))
58
59
  emit(line);
59
60
  return { rows, nextOldLineNum: cursor };
60
61
  }
62
+ /**
63
+ * genDiff is the single diff projection (#169). Return contract:
64
+ * - every emitted row's anchor equals the true new-file line content hash at that
65
+ * position; removed rows carry the true old-file hash when old hashes are provided.
66
+ * - every emitted marker's count equals the span it hides:
67
+ * ` ... [N lines untouched] ...` advances both cursors past N hidden rows (lease-covered,
68
+ * they stay addressable through the served leases), and ` - ... [N lines deleted] ...`
69
+ * advances the old cursor past N deleted rows (cursor-exact).
70
+ * - collapse invariant: a middle gap smaller than 2×context renders whole (#166/#172);
71
+ * at context 0 every non-empty middle gap collapses to a single counted untouched
72
+ * marker (#170); bare ` ...` appears only at leading/trailing edges; added spans are never collapsed.
73
+ * - servedRows mirror exactly the rendered context/addition rows (position + hash).
74
+ */
61
75
  export function genDiff(oldContent, newContent, contextLines = 2, newContentHashes, oldContentHashes) {
62
76
  const effectiveNewHashes = newContentHashes ?? lineHashesPure(newContent);
63
77
  const parts = Diff.diffLines(oldContent, newContent);
@@ -105,11 +119,15 @@ export function genDiff(oldContent, newContent, contextLines = 2, newContentHash
105
119
  linesToShow = displayLines.slice(skipStart);
106
120
  }
107
121
  else if (nextPartIsChange && displayLines.length > contextLines * 2) {
108
- const tail = displayLines.slice(-contextLines);
109
- linesToShow = [...displayLines.slice(0, contextLines), ELLIPSIS_MARKER, ...tail];
122
+ // WHY: #170 — slice(-0) returns the whole array, so at context 0 the tail is taken
123
+ // WHY: explicitly; the gap then renders marker-only with the count covering the full span.
124
+ const tail = contextLines === 0 ? [] : displayLines.slice(-contextLines);
125
+ linesToShow = [...displayLines.slice(0, contextLines), UNTOUCHED_MARKER, ...tail];
110
126
  skipMiddle = displayLines.length - contextLines * 2;
111
127
  }
112
- else if (linesToShow.length > contextLines) {
128
+ else if (!nextPartIsChange && linesToShow.length > contextLines) {
129
+ // WHY: #166 — only trailing gaps may be sliced away silently; a middle gap renders whole
130
+ // WHY: below 2×context, otherwise hidden rows would desync the anchors that follow it.
113
131
  linesToShow = linesToShow.slice(0, contextLines);
114
132
  }
115
133
  if (skipStart > 0) {
@@ -118,8 +136,10 @@ export function genDiff(oldContent, newContent, contextLines = 2, newContentHash
118
136
  oldLineNum += skipStart;
119
137
  }
120
138
  for (const line of linesToShow) {
121
- if (isEllipsisMarker(line)) {
122
- output.push(" ...");
139
+ if (isUntouchedMarker(line)) {
140
+ // WHY: #169 — a hidden middle span is a counted `lines untouched` marker; both cursors
141
+ // WHY: advance past the exact hidden count, so anchors after it stay aligned.
142
+ output.push(` ... [${skipMiddle} lines untouched] ...`);
123
143
  newLineNum += skipMiddle;
124
144
  oldLineNum += skipMiddle;
125
145
  continue;
@@ -9,7 +9,7 @@ import { errCode } from "../utils.js";
9
9
  import { isBlankOverride } from "./parse.js";
10
10
  import { GUIDANCE_SECTIONS } from "./resolve.js";
11
11
  /** The presets shipped by the harness, each seeded with editable guidance. */
12
- export const DEFAULT_PRESETS = ["standard", "code", "minimal", "cordis"];
12
+ export const DEFAULT_PRESETS = ["standard", "ptc", "minimal", "cordis"];
13
13
  /**
14
14
  * The root README: the per-preset customization convention users see in the
15
15
  * plugin home.
@@ -17,7 +17,7 @@ export const DEFAULT_PRESETS = ["standard", "code", "minimal", "cordis"];
17
17
  export const GUIDANCE_HOME_README = `# dsh-better-edit guidance
18
18
 
19
19
  Each agent preset has its own guidance directory here: \`<preset>/<section>.md\`.
20
- On first boot the plugin seeds the shipped presets (\`standard\`, \`code\`,
20
+ On first boot the plugin seeds the shipped presets (\`standard\`, \`ptc\`,
21
21
  \`minimal\`, \`cordis\`) with the compiled defaults; existing files are never
22
22
  overwritten, so your edits survive.
23
23
 
@@ -31,13 +31,13 @@ Each file is one tool section:
31
31
 
32
32
  Edit the \`<section>.md\` file for the preset and section you want to change —
33
33
  the file body IS the text the model reads for that section. Files are read once
34
- per agent at session-start, so edits apply to new sessions.
34
+ per agent when it is created (\`agent/created\`), so edits apply to new sessions.
35
35
 
36
36
  An optional YAML front-matter fence places the section at a custom position in
37
37
  the assembled system prompt:
38
38
 
39
39
  ---
40
- order: 150
40
+ order: 1100
41
41
  ---
42
42
 
43
43
  <section text>
@@ -55,7 +55,7 @@ seeded directory, copy a seeded one to its name.
55
55
  export const GUIDANCE_HOME_README_ZH = `# dsh-better-edit 指引
56
56
 
57
57
  每个 agent preset 在这里都有自己的指引目录:\`<preset>/<section>.md\`。首次启动时
58
- 插件会为随附的 preset(\`standard\`、\`code\`、\`minimal\`、\`cordis\`)写入编译内置的
58
+ 插件会为随附的 preset(\`standard\`、\`ptc\`、\`minimal\`、\`cordis\`)写入编译内置的
59
59
  默认内容;已有文件绝不被覆盖,因此你的编辑会保留。
60
60
 
61
61
  每个文件对应一个工具片段:
@@ -67,12 +67,12 @@ export const GUIDANCE_HOME_README_ZH = `# dsh-better-edit 指引
67
67
  ## 自定义
68
68
 
69
69
  编辑你想修改的 preset 与片段的 \`<section>.md\` 文件即可——文件正文就是该片段呈
70
- 现给模型的文本。文件在 agent 的 session-start 时读取一次,因此修改只影响新会话。
70
+ 现给模型的文本。文件在 agent 创建时(\`agent/created\`)读取一次,因此修改只影响新会话。
71
71
 
72
72
  可以用可选的 YAML front-matter 栅栏把片段放到组装后系统提示中的自定义位置:
73
73
 
74
74
  ---
75
- order: 150
75
+ order: 1100
76
76
  ---
77
77
 
78
78
  <片段文本>
@@ -12,7 +12,7 @@ import { errCode } from "../utils.js";
12
12
  import { isBlankOverride, parseSectionFile } from "./parse.js";
13
13
  /**
14
14
  * Render one tool's guidance as its intro line, a blank line, then bullets.
15
- * Uniform across the four sections: no tool-schema description is duplicated
15
+ * Uniform across the three sections: no tool-schema description is duplicated
16
16
  * (that already reaches the model through the tool catalog).
17
17
  */
18
18
  function guidanceText(g) {
@@ -26,19 +26,22 @@ export const GUIDANCE_SECTIONS = [
26
26
  {
27
27
  name: "tool:read",
28
28
  file: "read.md",
29
- defaultOrder: 130,
29
+ defaultOrder: 1100,
30
+ orderName: "TOOL_READ",
30
31
  renderDefault: () => guidanceText(READ_GUIDANCE),
31
32
  },
32
33
  {
33
34
  name: "tool:edit",
34
35
  file: "edit.md",
35
- defaultOrder: 131,
36
+ defaultOrder: 1300,
37
+ orderName: "TOOL_EDIT",
36
38
  renderDefault: () => guidanceText(EDIT_GUIDANCE),
37
39
  },
38
40
  {
39
41
  name: "tool:undo_last_edit",
40
42
  file: "undo_last_edit.md",
41
- defaultOrder: 133,
43
+ // Immediately after the edit slot it annotates; there is no TOOL_UNDO name.
44
+ defaultOrder: 1310,
42
45
  renderDefault: () => guidanceText(UNDO_GUIDANCE),
43
46
  },
44
47
  ];
@@ -67,6 +70,7 @@ export async function resolveSection(name, options) {
67
70
  const section = SECTION_BY_NAME.get(name);
68
71
  if (!section)
69
72
  throw new Error(`unknown guidance section: ${name}`);
73
+ const defaultOrder = options.defaultOrder?.(section) ?? section.defaultOrder;
70
74
  for (const candidate of overrideCandidates(section.file, options)) {
71
75
  const content = await readFile(candidate, "utf-8").catch((error) => {
72
76
  if (errCode(error) === "ENOENT")
@@ -80,7 +84,7 @@ export async function resolveSection(name, options) {
80
84
  // A broken override must never reach the model. Resolve to the
81
85
  // compiled default and report the file + parse reason to the caller.
82
86
  return {
83
- order: section.defaultOrder,
87
+ order: defaultOrder,
84
88
  text: section.renderDefault(),
85
89
  malformed: {
86
90
  file: candidate,
@@ -92,19 +96,20 @@ export async function resolveSection(name, options) {
92
96
  // fallback chain rather than render an empty section.
93
97
  if (isBlankOverride(content))
94
98
  continue;
95
- return { order: parsed.order ?? section.defaultOrder, text: parsed.text };
99
+ return { order: parsed.order ?? defaultOrder, text: parsed.text };
96
100
  }
97
- return { order: section.defaultOrder, text: section.renderDefault() };
101
+ return { order: defaultOrder, text: section.renderDefault() };
98
102
  }
99
103
  /**
100
104
  * Resolve all three sections for a preset. `presetId === undefined` skips the
101
105
  * `<preset>/` layer and resolves straight to the compiled defaults.
102
106
  */
103
- export async function composeSections(presetId, homeDir) {
107
+ export async function composeSections(presetId, homeDir, defaultOrder) {
104
108
  return Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
105
109
  const resolved = await resolveSection(section.name, {
106
110
  presetId,
107
111
  homeDir,
112
+ ...(defaultOrder === undefined ? {} : { defaultOrder }),
108
113
  });
109
114
  return {
110
115
  name: section.name,
package/lib/index.js CHANGED
@@ -21,16 +21,40 @@ export const name = "dsh-better-edit";
21
21
  * session-start.
22
22
  */
23
23
  export const inject = ["tools", "systemPrompt", "fs"];
24
- /** The four sections as compiled, byte-identical to the pre-guidance install. */
25
- function compiledDefaultSections() {
24
+ /**
25
+ * The harness's canonical slot for a guidance section, when the installed
26
+ * `systemPrompt` registry exposes one (`getSectionOrder`, dsh 0.1.5+). Sections
27
+ * without a canonical slot — `undo_last_edit` is plugin-owned — keep their
28
+ * compiled default. A registry that predates the API keeps every default.
29
+ */
30
+ function sectionOrderFor(rootCtx) {
31
+ const systemPrompt = rootCtx.systemPrompt;
32
+ const getSectionOrder = systemPrompt.getSectionOrder;
33
+ if (typeof getSectionOrder !== "function")
34
+ return (section) => section.defaultOrder;
35
+ return (section) => {
36
+ if (section.orderName === undefined)
37
+ return section.defaultOrder;
38
+ try {
39
+ return getSectionOrder.call(systemPrompt, section.orderName);
40
+ }
41
+ catch {
42
+ // A registry that does not know the name keeps the compiled default.
43
+ return section.defaultOrder;
44
+ }
45
+ };
46
+ }
47
+ /** The three sections as compiled, byte-identical to the pre-guidance install. */
48
+ function compiledDefaultSections(rootCtx) {
49
+ const orderFor = sectionOrderFor(rootCtx);
26
50
  return GUIDANCE_SECTIONS.map((section) => ({
27
51
  name: section.name,
28
- order: section.defaultOrder,
52
+ order: orderFor(section),
29
53
  text: section.renderDefault(),
30
54
  }));
31
55
  }
32
56
  /**
33
- * Resolve the four guidance sections for one agent. Without the `agentPresets`
57
+ * Resolve the three guidance sections for one agent. Without the `agentPresets`
34
58
  * service the fast path returns the compiled defaults untouched. With it, the
35
59
  * agent's preset id drives `composeSections` against the shared home; any
36
60
  * resolution failure degrades to compiled defaults so a bad override file can
@@ -39,10 +63,10 @@ function compiledDefaultSections() {
39
63
  async function resolveAgentSections(rootCtx, agent) {
40
64
  const agentPresets = rootCtx.get("agentPresets");
41
65
  if (!agentPresets)
42
- return compiledDefaultSections();
66
+ return compiledDefaultSections(rootCtx);
43
67
  try {
44
68
  const presetId = agentPresets.composedPreset(agent.ctx);
45
- const sections = await composeSections(presetId, configDir());
69
+ const sections = await composeSections(presetId, configDir(), sectionOrderFor(rootCtx));
46
70
  // Warn once per agent install (this runs once per agent, under the
47
71
  // WeakSet guard) about any malformed override we had to ignore.
48
72
  for (const section of sections) {
@@ -54,15 +78,16 @@ async function resolveAgentSections(rootCtx, agent) {
54
78
  }
55
79
  catch (error) {
56
80
  rootCtx.logger.warn(`dsh-better-edit: guidance resolution failed for agent ${agent.id}, using compiled defaults: ${error instanceof Error ? error.message : String(error)}`);
57
- return compiledDefaultSections();
81
+ return compiledDefaultSections(rootCtx);
58
82
  }
59
83
  }
60
84
  function installAgentTools(rootCtx, agent) {
61
85
  agent.ctx.effect(async () => {
62
86
  // `fs` is host-plane: use the plugin's own context (covered by
63
87
  // inject) rather than the agent's scoped one, whose fiber chain does
64
- // not declare it. Session cwd still reaches the bridge per call via
65
- // exec.agent.session.header.cwd.
88
+ // not declare it. The session's live directory still reaches the bridge
89
+ // per call via `execCwd` (the `workingDirectory` service, falling back to
90
+ // `exec.agent.session.header.cwd`).
66
91
  const io = ctxFsIO(rootCtx.fs, rootCtx);
67
92
  const disposers = [];
68
93
  const sandbox = new FsSandboxController(rootCtx);
@@ -90,7 +115,8 @@ function installAgentTools(rootCtx, agent) {
90
115
  }));
91
116
  // Shadow the preset's built-in tool guidance with the hashline
92
117
  // contract. Same section names on the agent's own layer win over the
93
- // preset's; text and order come from the per-preset resolution.
118
+ // preset's; text and order come from the per-preset resolution, with the
119
+ // harness's canonical tool slot as the default order.
94
120
  const sections = await resolveAgentSections(rootCtx, agent);
95
121
  for (const section of sections) {
96
122
  disposers.push(agent.ctx.systemPrompt.section(section));
@@ -7,6 +7,19 @@ export declare function stripBOM(content: string): {
7
7
  bom: string;
8
8
  text: string;
9
9
  };
10
+ /**
11
+ * genDiff is the single diff projection (#169). Return contract:
12
+ * - every emitted row's anchor equals the true new-file line content hash at that
13
+ * position; removed rows carry the true old-file hash when old hashes are provided.
14
+ * - every emitted marker's count equals the span it hides:
15
+ * ` ... [N lines untouched] ...` advances both cursors past N hidden rows (lease-covered,
16
+ * they stay addressable through the served leases), and ` - ... [N lines deleted] ...`
17
+ * advances the old cursor past N deleted rows (cursor-exact).
18
+ * - collapse invariant: a middle gap smaller than 2×context renders whole (#166/#172);
19
+ * at context 0 every non-empty middle gap collapses to a single counted untouched
20
+ * marker (#170); bare ` ...` appears only at leading/trailing edges; added spans are never collapsed.
21
+ * - servedRows mirror exactly the rendered context/addition rows (position + hash).
22
+ */
10
23
  export declare function genDiff(oldContent: string, newContent: string, contextLines?: number, newContentHashes?: string[], oldContentHashes?: string[]): {
11
24
  diff: string;
12
25
  firstChangedLine: number | undefined;
@@ -4,8 +4,8 @@ export declare const DEFAULT_PRESETS: readonly string[];
4
4
  * The root README: the per-preset customization convention users see in the
5
5
  * plugin home.
6
6
  */
7
- export declare const GUIDANCE_HOME_README = "# dsh-better-edit guidance\n\nEach agent preset has its own guidance directory here: `<preset>/<section>.md`.\nOn first boot the plugin seeds the shipped presets (`standard`, `code`,\n`minimal`, `cordis`) with the compiled defaults; existing files are never\noverwritten, so your edits survive.\n\nEach file is one tool section:\n\n- `read.md` -> `tool:read`\n- `edit.md` -> `tool:edit`\n- `undo_last_edit.md` -> `tool:undo_last_edit`\n\n## Customize\n\nEdit the `<section>.md` file for the preset and section you want to change \u2014\nthe file body IS the text the model reads for that section. Files are read once\nper agent at session-start, so edits apply to new sessions.\n\nAn optional YAML front-matter fence places the section at a custom position in\nthe assembled system prompt:\n\n ---\n order: 150\n ---\n\n <section text>\n\nA file without front-matter keeps the default order. A malformed fence (a\nmissing closing `---`, a non-integer `order`, an unknown key) makes the whole\nfile plain prose.\n\n## Fallback\n\nA preset with no directory here, or a missing section file, falls back to the\ncompiled defaults in the plugin bundle. To customize a preset that has no\nseeded directory, copy a seeded one to its name.\n";
8
- export declare const GUIDANCE_HOME_README_ZH = "# dsh-better-edit \u6307\u5F15\n\n\u6BCF\u4E2A agent preset \u5728\u8FD9\u91CC\u90FD\u6709\u81EA\u5DF1\u7684\u6307\u5F15\u76EE\u5F55\uFF1A`<preset>/<section>.md`\u3002\u9996\u6B21\u542F\u52A8\u65F6\n\u63D2\u4EF6\u4F1A\u4E3A\u968F\u9644\u7684 preset\uFF08`standard`\u3001`code`\u3001`minimal`\u3001`cordis`\uFF09\u5199\u5165\u7F16\u8BD1\u5185\u7F6E\u7684\n\u9ED8\u8BA4\u5185\u5BB9\uFF1B\u5DF2\u6709\u6587\u4EF6\u7EDD\u4E0D\u88AB\u8986\u76D6\uFF0C\u56E0\u6B64\u4F60\u7684\u7F16\u8F91\u4F1A\u4FDD\u7559\u3002\n\n\u6BCF\u4E2A\u6587\u4EF6\u5BF9\u5E94\u4E00\u4E2A\u5DE5\u5177\u7247\u6BB5\uFF1A\n\n- `read.md` -> `tool:read`\n- `edit.md` -> `tool:edit`\n- `undo_last_edit.md` -> `tool:undo_last_edit`\n\n## \u81EA\u5B9A\u4E49\n\n\u7F16\u8F91\u4F60\u60F3\u4FEE\u6539\u7684 preset \u4E0E\u7247\u6BB5\u7684 `<section>.md` \u6587\u4EF6\u5373\u53EF\u2014\u2014\u6587\u4EF6\u6B63\u6587\u5C31\u662F\u8BE5\u7247\u6BB5\u5448\n\u73B0\u7ED9\u6A21\u578B\u7684\u6587\u672C\u3002\u6587\u4EF6\u5728 agent \u7684 session-start \u65F6\u8BFB\u53D6\u4E00\u6B21\uFF0C\u56E0\u6B64\u4FEE\u6539\u53EA\u5F71\u54CD\u65B0\u4F1A\u8BDD\u3002\n\n\u53EF\u4EE5\u7528\u53EF\u9009\u7684 YAML front-matter \u6805\u680F\u628A\u7247\u6BB5\u653E\u5230\u7EC4\u88C5\u540E\u7CFB\u7EDF\u63D0\u793A\u4E2D\u7684\u81EA\u5B9A\u4E49\u4F4D\u7F6E\uFF1A\n\n ---\n order: 150\n ---\n\n <\u7247\u6BB5\u6587\u672C>\n\n\u6CA1\u6709 front-matter \u7684\u6587\u4EF6\u4FDD\u6301\u9ED8\u8BA4\u987A\u5E8F\u3002\u683C\u5F0F\u9519\u8BEF\u7684\u6805\u680F\uFF08\u7F3A\u5C11\u6536\u5C3E `---`\u3001\u975E\u6574\u6570\n`order`\u3001\u672A\u77E5\u952E\uFF09\u4F1A\u8BA9\u6574\u4E2A\u6587\u4EF6\u9000\u5316\u4E3A\u7EAF\u6587\u672C\u3002\n\n## \u56DE\u9000\n\n\u8FD9\u91CC\u6CA1\u6709\u5BF9\u5E94\u76EE\u5F55\u7684 preset\u3001\u6216\u7F3A\u5931\u67D0\u4E2A\u7247\u6BB5\u6587\u4EF6\u65F6\uFF0C\u4F1A\u56DE\u9000\u5230\u63D2\u4EF6\u5305\u5185\u7684\u7F16\u8BD1\u5185\u7F6E\u9ED8\u8BA4\n\u503C\u3002\u8981\u81EA\u5B9A\u4E49\u6CA1\u6709\u79CD\u5B50\u76EE\u5F55\u7684 preset\uFF0C\u628A\u4E00\u4E2A\u79CD\u5B50\u76EE\u5F55\u590D\u5236\u6210\u5B83\u7684\u540D\u5B57\u5373\u53EF\u3002\n";
7
+ export declare const GUIDANCE_HOME_README = "# dsh-better-edit guidance\n\nEach agent preset has its own guidance directory here: `<preset>/<section>.md`.\nOn first boot the plugin seeds the shipped presets (`standard`, `ptc`,\n`minimal`, `cordis`) with the compiled defaults; existing files are never\noverwritten, so your edits survive.\n\nEach file is one tool section:\n\n- `read.md` -> `tool:read`\n- `edit.md` -> `tool:edit`\n- `undo_last_edit.md` -> `tool:undo_last_edit`\n\n## Customize\n\nEdit the `<section>.md` file for the preset and section you want to change \u2014\nthe file body IS the text the model reads for that section. Files are read once\nper agent when it is created (`agent/created`), so edits apply to new sessions.\n\nAn optional YAML front-matter fence places the section at a custom position in\nthe assembled system prompt:\n\n ---\n order: 1100\n ---\n\n <section text>\n\nA file without front-matter keeps the default order. A malformed fence (a\nmissing closing `---`, a non-integer `order`, an unknown key) makes the whole\nfile plain prose.\n\n## Fallback\n\nA preset with no directory here, or a missing section file, falls back to the\ncompiled defaults in the plugin bundle. To customize a preset that has no\nseeded directory, copy a seeded one to its name.\n";
8
+ export declare const GUIDANCE_HOME_README_ZH = "# dsh-better-edit \u6307\u5F15\n\n\u6BCF\u4E2A agent preset \u5728\u8FD9\u91CC\u90FD\u6709\u81EA\u5DF1\u7684\u6307\u5F15\u76EE\u5F55\uFF1A`<preset>/<section>.md`\u3002\u9996\u6B21\u542F\u52A8\u65F6\n\u63D2\u4EF6\u4F1A\u4E3A\u968F\u9644\u7684 preset\uFF08`standard`\u3001`ptc`\u3001`minimal`\u3001`cordis`\uFF09\u5199\u5165\u7F16\u8BD1\u5185\u7F6E\u7684\n\u9ED8\u8BA4\u5185\u5BB9\uFF1B\u5DF2\u6709\u6587\u4EF6\u7EDD\u4E0D\u88AB\u8986\u76D6\uFF0C\u56E0\u6B64\u4F60\u7684\u7F16\u8F91\u4F1A\u4FDD\u7559\u3002\n\n\u6BCF\u4E2A\u6587\u4EF6\u5BF9\u5E94\u4E00\u4E2A\u5DE5\u5177\u7247\u6BB5\uFF1A\n\n- `read.md` -> `tool:read`\n- `edit.md` -> `tool:edit`\n- `undo_last_edit.md` -> `tool:undo_last_edit`\n\n## \u81EA\u5B9A\u4E49\n\n\u7F16\u8F91\u4F60\u60F3\u4FEE\u6539\u7684 preset \u4E0E\u7247\u6BB5\u7684 `<section>.md` \u6587\u4EF6\u5373\u53EF\u2014\u2014\u6587\u4EF6\u6B63\u6587\u5C31\u662F\u8BE5\u7247\u6BB5\u5448\n\u73B0\u7ED9\u6A21\u578B\u7684\u6587\u672C\u3002\u6587\u4EF6\u5728 agent \u521B\u5EFA\u65F6\uFF08`agent/created`\uFF09\u8BFB\u53D6\u4E00\u6B21\uFF0C\u56E0\u6B64\u4FEE\u6539\u53EA\u5F71\u54CD\u65B0\u4F1A\u8BDD\u3002\n\n\u53EF\u4EE5\u7528\u53EF\u9009\u7684 YAML front-matter \u6805\u680F\u628A\u7247\u6BB5\u653E\u5230\u7EC4\u88C5\u540E\u7CFB\u7EDF\u63D0\u793A\u4E2D\u7684\u81EA\u5B9A\u4E49\u4F4D\u7F6E\uFF1A\n\n ---\n order: 1100\n ---\n\n <\u7247\u6BB5\u6587\u672C>\n\n\u6CA1\u6709 front-matter \u7684\u6587\u4EF6\u4FDD\u6301\u9ED8\u8BA4\u987A\u5E8F\u3002\u683C\u5F0F\u9519\u8BEF\u7684\u6805\u680F\uFF08\u7F3A\u5C11\u6536\u5C3E `---`\u3001\u975E\u6574\u6570\n`order`\u3001\u672A\u77E5\u952E\uFF09\u4F1A\u8BA9\u6574\u4E2A\u6587\u4EF6\u9000\u5316\u4E3A\u7EAF\u6587\u672C\u3002\n\n## \u56DE\u9000\n\n\u8FD9\u91CC\u6CA1\u6709\u5BF9\u5E94\u76EE\u5F55\u7684 preset\u3001\u6216\u7F3A\u5931\u67D0\u4E2A\u7247\u6BB5\u6587\u4EF6\u65F6\uFF0C\u4F1A\u56DE\u9000\u5230\u63D2\u4EF6\u5305\u5185\u7684\u7F16\u8BD1\u5185\u7F6E\u9ED8\u8BA4\n\u503C\u3002\u8981\u81EA\u5B9A\u4E49\u6CA1\u6709\u79CD\u5B50\u76EE\u5F55\u7684 preset\uFF0C\u628A\u4E00\u4E2A\u79CD\u5B50\u76EE\u5F55\u590D\u5236\u6210\u5B83\u7684\u540D\u5B57\u5373\u53EF\u3002\n";
9
9
  /**
10
10
  * Materialize per-preset guidance directories in the plugin home.
11
11
  *
@@ -4,8 +4,18 @@ export interface GuidanceSection {
4
4
  name: string;
5
5
  /** Override file name inside a preset directory, e.g. `edit.md`. */
6
6
  file: string;
7
- /** Order used when the override file carries no front-matter `order`. */
7
+ /**
8
+ * Order used when neither the override file nor the harness names one — the
9
+ * fallback for a registry that predates `systemPrompt.getSectionOrder`.
10
+ * Mirrors dsh 0.2.1's `SECTION_ORDERS` tool band.
11
+ */
8
12
  defaultOrder: number;
13
+ /**
14
+ * The `systemPrompt.getSectionOrder` name of the tool slot this section
15
+ * shadows (e.g. `TOOL_READ`), so the live band wins over `defaultOrder`.
16
+ * Absent for plugin-owned sections with no harness slot.
17
+ */
18
+ orderName?: "TOOL_READ" | "TOOL_EDIT";
9
19
  /** The compiled default text, byte-identical to today's inline rendering. */
10
20
  renderDefault(): string;
11
21
  }
@@ -19,6 +29,8 @@ export interface ResolveGuidanceOptions {
19
29
  presetId?: string;
20
30
  /** Plugin shared home directory (`$DSH_HOME/plugins/dsh-better-edit`). */
21
31
  homeDir: string;
32
+ /** Live harness slot for a section, when the registry exposes one. */
33
+ defaultOrder?: (section: GuidanceSection) => number;
22
34
  }
23
35
  /** The resolved text and order for one section. */
24
36
  export interface GuidanceResolution {
@@ -52,4 +64,4 @@ export interface SectionOverride {
52
64
  * Resolve all three sections for a preset. `presetId === undefined` skips the
53
65
  * `<preset>/` layer and resolves straight to the compiled defaults.
54
66
  */
55
- export declare function composeSections(presetId: string | undefined, homeDir: string): Promise<SectionOverride[]>;
67
+ export declare function composeSections(presetId: string | undefined, homeDir: string, defaultOrder?: (section: GuidanceSection) => number): Promise<SectionOverride[]>;
@@ -10,7 +10,7 @@
10
10
  * place; scoped pre/post listeners reject copied same-line served anchors
11
11
  * before dispatch and append a fresh hashline preview after successful writes.
12
12
  *
13
- * The four `tool:*` guidance sections resolve per agent preset from override
13
+ * The three `tool:*` guidance sections resolve per agent preset from override
14
14
  * files in the shared home (see `src/guidance.ts`); deployments without the
15
15
  * `agentPresets` service keep the compiled defaults unchanged.
16
16
  * @module dsh-better-edit
@@ -1,33 +1,15 @@
1
1
  import { z } from "zod";
2
2
  export declare function expand(filePath: string): string;
3
3
  declare const StoreConfigSchema: z.ZodObject<{
4
- storeDir: z.ZodEffects<z.ZodDefault<z.ZodString>, string, string | undefined>;
4
+ storeDir: z.ZodPipe<z.ZodDefault<z.ZodString>, z.ZodTransform<string, string>>;
5
5
  autoGitignore: z.ZodDefault<z.ZodBoolean>;
6
6
  autoGuessEncoding: z.ZodDefault<z.ZodBoolean>;
7
7
  normalizeToUtf8: z.ZodDefault<z.ZodBoolean>;
8
- supportedEncodings: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
8
+ supportedEncodings: z.ZodDefault<z.ZodArray<z.ZodString>>;
9
9
  undo_ttl_s: z.ZodDefault<z.ZodNumber>;
10
10
  storeMaxAgeS: z.ZodDefault<z.ZodNumber>;
11
11
  storeMaxTotalBytes: z.ZodDefault<z.ZodNumber>;
12
- }, "strip", z.ZodTypeAny, {
13
- storeDir: string;
14
- autoGitignore: boolean;
15
- autoGuessEncoding: boolean;
16
- normalizeToUtf8: boolean;
17
- supportedEncodings: string[];
18
- undo_ttl_s: number;
19
- storeMaxAgeS: number;
20
- storeMaxTotalBytes: number;
21
- }, {
22
- storeDir?: string | undefined;
23
- autoGitignore?: boolean | undefined;
24
- autoGuessEncoding?: boolean | undefined;
25
- normalizeToUtf8?: boolean | undefined;
26
- supportedEncodings?: string[] | undefined;
27
- undo_ttl_s?: number | undefined;
28
- storeMaxAgeS?: number | undefined;
29
- storeMaxTotalBytes?: number | undefined;
30
- }>;
12
+ }, z.core.$strip>;
31
13
  export type StoreConfig = z.infer<typeof StoreConfigSchema>;
32
14
  /** Default config.yaml content with comments — generated when the file does not exist. */
33
15
  export declare const DEFAULT_CONFIG_YAML = "# dsh-better-edit config\n# Location: $DSH_HOME/plugins/dsh-better-edit/config.yaml\n# Docs: https://github.com/Rianico/dsh-better-edit#configuration\n# Generated with defaults on first load \u2014 edit or delete freely.\n# DB files are disposable caches \u2014 safe to delete, rebuilt on next `read`.\n\n# where the store lives: \"central\" (default, in $DSH_HOME/.../runtime/<name>-<hash8>/) | \"workspace\" (legacy <ws>/.dsh_better_edit/) | \"/abs/path\" (custom root)\nstoreDir: central\n\n# workspace only: when .git exists but .gitignore lacks .dsh_better_edit/, true = auto-append \".dsh_better_edit/\", false = warn once\nautoGitignore: false\n\n# encoding: deterministic BOM\u2192UTF-8 first, guessing only when autoGuessEncoding:true\n# when true, FS_NOT_TEXT scores supportedEncodings and surfaces top-3 previews for model pick\nautoGuessEncoding: false\n# when true, legacy files (GBK etc.) migrate to UTF-8 on first write\nnormalizeToUtf8: false\n# allowlist scored for top-3 previews when autoGuessEncoding:true\nsupportedEncodings: [gbk, big5, shift_jis, euc-kr, windows-1251, iso-8859-1]\n\n# undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)\nundo_ttl_s: 604800\n\n# central janitor: max idle age in seconds before evicting runtime/<name>-<hash8>/ (default 2592000 = 30 days)\nstoreMaxAgeS: 2592000\n\n# central janitor: max total bytes under runtime/ before LRU eviction (default 524288000 = 500 MB)\nstoreMaxTotalBytes: 524288000\n";
@@ -18,5 +18,15 @@ import type { ToolExecution } from "@deepseek-ai/dsh-tools";
18
18
  export declare function withWorkspace<T>(cwd: string, fn: () => Promise<T>): Promise<T>;
19
19
  export declare function workspaceCwd(): string | undefined;
20
20
  export declare function sessionKeyFor(sessionId?: string): string;
21
+ /**
22
+ * The directory this call operates in.
23
+ *
24
+ * Since dsh 0.2.1 the session header keeps only the directory the session was
25
+ * CREATED in — the `working_directory` tool may have moved the session since —
26
+ * so the effective directory is read from the `workingDirectory` service, whose
27
+ * synchronous `get(session)` returns the committed value. A composition without
28
+ * that service falls back to the header, where the directory lived before the
29
+ * service existed.
30
+ */
21
31
  export declare function execCwd(exec: ToolExecution): string;
22
32
  export declare function execSessionKey(exec: ToolExecution): string;
@@ -32,8 +32,30 @@ export function sessionKeyFor(sessionId) {
32
32
  return sessionId;
33
33
  throw new Error("sessionKeyFor: tool context carries no session — entrypoints must supply the ToolExecution's session id");
34
34
  }
35
+ /** The live working directory, when the agent's scope can see the service. */
36
+ function workingDirectoryFor(agent) {
37
+ const ctx = agent?.ctx;
38
+ if (typeof ctx?.get !== "function")
39
+ return undefined;
40
+ return ctx.get("workingDirectory");
41
+ }
42
+ /**
43
+ * The directory this call operates in.
44
+ *
45
+ * Since dsh 0.2.1 the session header keeps only the directory the session was
46
+ * CREATED in — the `working_directory` tool may have moved the session since —
47
+ * so the effective directory is read from the `workingDirectory` service, whose
48
+ * synchronous `get(session)` returns the committed value. A composition without
49
+ * that service falls back to the header, where the directory lived before the
50
+ * service existed.
51
+ */
35
52
  export function execCwd(exec) {
36
- return exec.agent?.session.header.cwd ?? process.cwd();
53
+ const session = exec.agent?.session;
54
+ const workingDirectory = workingDirectoryFor(exec.agent);
55
+ if (session !== undefined && workingDirectory !== undefined) {
56
+ return workingDirectory.get(session);
57
+ }
58
+ return session?.header.cwd ?? process.cwd();
37
59
  }
38
60
  export function execSessionKey(exec) {
39
61
  return sessionKeyFor(exec.agent?.session.id);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-better-edit",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Hash-anchored read/edit/undo_last_edit tools for DeepSeek Harness (dsh). Every line gets a unique 3-char hash (A-Za-z0-9) that stays stable across edits; stale or ambiguous anchors are rejected, never fuzzy-matched. Undo persists across restarts.",
5
5
  "keywords": [
6
6
  "anchors",
@@ -48,43 +48,27 @@
48
48
  },
49
49
  "./package.json": "./package.json"
50
50
  },
51
- "scripts": {
52
- "prepare": "tsc -p tsconfig.json && husky",
53
- "build": "tsc -p tsconfig.json",
54
- "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
55
- "typecheck:test": "tsc --noEmit -p tsconfig.test.json",
56
- "test": "vitest run",
57
- "test:watch": "vitest",
58
- "prepublishOnly": "npm run typecheck && npm test && node scripts/assert-tagged.mjs",
59
- "benchmark": "node benchmark/run.mjs",
60
- "lint": "oxlint .",
61
- "lint:fix": "oxlint --fix .",
62
- "format": "oxfmt --check .",
63
- "format:check": "oxfmt --check .",
64
- "test:coverage": "vitest run --coverage",
65
- "format:fix": "oxfmt ."
66
- },
67
51
  "dependencies": {
68
52
  "diff": "^8.0.2",
69
53
  "file-type": "^21.3.0",
70
54
  "iconv-lite": "^0.6.3",
71
55
  "xxhash-wasm": "^1.1.0",
72
- "zod": "^3.25.76"
56
+ "zod": "^4.6.7"
73
57
  },
74
58
  "devDependencies": {
75
59
  "@biomejs/biome": "^2.1.0",
76
60
  "@commitlint/cli": "^21.2.2",
77
61
  "@commitlint/config-conventional": "^21.2.2",
78
- "@deepseek-ai/cordis": "^4.0.1",
79
- "@deepseek-ai/dsh-agent": "0.1.6-alpha.2",
80
- "@deepseek-ai/dsh-fs": "0.1.6-alpha.2",
81
- "@deepseek-ai/dsh-home-paths": "0.1.6-alpha.2",
82
- "@deepseek-ai/dsh-sandbox": "0.1.6-alpha.2",
83
- "@deepseek-ai/dsh-session": "0.1.6-alpha.2",
84
- "@deepseek-ai/dsh-tools": "0.1.6-alpha.2",
62
+ "@deepseek-ai/cordis": "^4.0.5",
63
+ "@deepseek-ai/dsh-agent": "0.2.1-rc.2",
64
+ "@deepseek-ai/dsh-fs": "0.2.1-rc.2",
65
+ "@deepseek-ai/dsh-home-paths": "0.2.1-rc.2",
66
+ "@deepseek-ai/dsh-sandbox": "0.2.1-rc.2",
67
+ "@deepseek-ai/dsh-session": "0.2.1-rc.2",
68
+ "@deepseek-ai/dsh-tools": "0.2.1-rc.2",
85
69
  "@semantic-release/changelog": "^7.0.0",
86
70
  "@semantic-release/git": "^11.0.1",
87
- "@semantic-release/github": "^12.0.9",
71
+ "@semantic-release/github": "^12.0.10",
88
72
  "@types/node": "^24.0.0",
89
73
  "@vitest/coverage-v8": "^4.1.10",
90
74
  "conventional-changelog-conventionalcommits": "^8.0.0",
@@ -95,8 +79,8 @@
95
79
  "semantic-release": "^25.0.9",
96
80
  "tsx": ">=4",
97
81
  "typescript": ">=7",
98
- "vite": ">=8",
99
- "vitest": "^4.1.8"
82
+ "vite": "^8.3.5",
83
+ "vitest": "^4.1.12"
100
84
  },
101
85
  "optionalDependencies": {
102
86
  "chardet": "2.2.0"
@@ -104,10 +88,25 @@
104
88
  "engines": {
105
89
  "node": ">=24"
106
90
  },
107
- "packageManager": "pnpm@12.0.0",
108
91
  "dsh": {
109
92
  "bundle": {
110
93
  "patch": "./cordis.patch.yml"
111
94
  }
95
+ },
96
+ "scripts": {
97
+ "build": "tsc -p tsconfig.json",
98
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
99
+ "typecheck:test": "tsc --noEmit -p tsconfig.test.json",
100
+ "test": "vitest run",
101
+ "test:watch": "vitest",
102
+ "benchmark": "node benchmark/run.mjs",
103
+ "lint": "oxlint .",
104
+ "lint:fix": "oxlint --fix .",
105
+ "format": "oxfmt --check .",
106
+ "format:check": "oxfmt --check .",
107
+ "test:coverage": "vitest run --coverage",
108
+ "format:fix": "oxfmt .",
109
+ "audit": "pnpm audit --audit-level high --registry https://registry.npmjs.org/",
110
+ "verify": "pnpm run lint && pnpm run format && pnpm run typecheck && pnpm run test:coverage"
112
111
  }
113
- }
112
+ }