dsh-better-edit 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +327 -238
  3. package/README.zh.md +44 -16
  4. package/lib/contract.js +40 -1
  5. package/lib/edit-engine.js +4 -4
  6. package/lib/edit-pipeline.js +4 -4
  7. package/lib/file-view.js +63 -0
  8. package/lib/guidance/index.js +8 -0
  9. package/lib/guidance/materialize.js +191 -0
  10. package/lib/guidance/parse.js +80 -0
  11. package/lib/guidance/resolve.js +122 -0
  12. package/lib/guidance.js +6 -279
  13. package/lib/hash-store.js +1 -2
  14. package/lib/hashline/anchor-pipeline.js +23 -0
  15. package/lib/hashline/hash-assign.js +20 -0
  16. package/lib/hashline/index.js +4 -5
  17. package/lib/hashline/resolve.js +5 -0
  18. package/lib/index.js +10 -2
  19. package/lib/mutation.js +58 -0
  20. package/lib/read-and-serve.js +23 -23
  21. package/lib/served-store.js +1 -1
  22. package/lib/session-view.js +34 -0
  23. package/lib/tool-batch-edit.js +9 -10
  24. package/lib/tool-edit.js +9 -11
  25. package/lib/tool-read.js +3 -5
  26. package/lib/tool-undo.js +6 -6
  27. package/lib/types/contract.d.ts +31 -0
  28. package/lib/types/edit-engine.d.ts +2 -2
  29. package/lib/types/edit-pipeline.d.ts +2 -2
  30. package/lib/types/file-view.d.ts +74 -0
  31. package/lib/types/guidance/index.d.ts +8 -0
  32. package/lib/types/guidance/materialize.d.ts +23 -0
  33. package/lib/types/guidance/parse.d.ts +36 -0
  34. package/lib/types/guidance/resolve.d.ts +55 -0
  35. package/lib/types/guidance.d.ts +6 -95
  36. package/lib/types/hashline/anchor-pipeline.d.ts +26 -0
  37. package/lib/types/hashline/hash-assign.d.ts +19 -0
  38. package/lib/types/hashline/index.d.ts +7 -5
  39. package/lib/types/hashline/resolve.d.ts +5 -0
  40. package/lib/types/mutation.d.ts +78 -0
  41. package/lib/types/read-and-serve.d.ts +6 -5
  42. package/lib/types/session-view.d.ts +33 -0
  43. package/lib/write-hook.js +2 -2
  44. package/package.json +2 -10
package/README.zh.md CHANGED
@@ -5,8 +5,8 @@
5
5
  <h1 align="center">dsh-better-edit</h1>
6
6
 
7
7
  <p align="center">
8
- <strong>面向 DeepSeek Harness 的哈希锚定编辑工具。<br>
9
- 按内容地址编辑——不靠行号,也不靠字符串替换。更省 token。更多注意力留给真正的工作。绝不会改错行。</strong>
8
+ <strong>一个专为 DeepSeek Harness 而生的更好的编辑工具。<br>
9
+ 底层基于 hash-anchored 定位——不依赖行号,也不靠字符串替换,更少的词源消耗,留出更多的上下文空间给真正的工作。</strong>
10
10
  </p>
11
11
 
12
12
  <p align="center">
@@ -23,7 +23,7 @@
23
23
  </p>
24
24
 
25
25
  <p align="center">
26
- <img src="https://img.shields.io/badge/version-0.1.9-blue.svg" alt="Version">
26
+ <img src="https://img.shields.io/badge/version-0.3.0-blue.svg" alt="Version">
27
27
  <img src="https://img.shields.io/badge/license-MIT-green.svg" alt="MIT License">
28
28
  <img src="https://img.shields.io/badge/DeepSeek_Harness-Plugin-blueviolet.svg" alt="DeepSeek Harness Plugin">
29
29
  <img src="https://img.shields.io/npm/v/dsh-better-edit" alt="npm version">
@@ -38,7 +38,11 @@
38
38
  ---
39
39
 
40
40
  > *"瓶颈在于 harness——而不是模型。"*
41
- > —— Can Bölük,[*The Harness Problem*](https://stencil.so/blog/the-harness-problem)
41
+ > —— Can Bölük,[*The Harness Problem*]
42
+ >
43
+ > **这是 harness 的修复。** 内容哈希取代行号——上方编辑永不使下方锚点移位。每个范围都对照 Agent 实际看到的内容校验。过期或未见的行被硬拒绝并回传新锚点重试——无需 `read`。
44
+ >
45
+ > **3 次调用 vs 6 次 · -55.8% tokens · 23/23 正确性。** 同样的外部漂移重构,同样正确的文件(单次随机运行 vs OMP;[完整方法](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/results/2026-08-17-practical-token-benchmark.md))。
42
46
 
43
47
  大多数编辑工具要求模型在改动任何东西之前,先**逐 token** 复述旧代码——而这正是 Agent 最容易出错的地方:多个模型在 replace 式编辑下的补丁格式失败率高达 46–51%。**dsh-better-edit** 走得更远。文件的每一行都分配一个唯一的 3 字符内容哈希,编辑时按哈希定位。旧文本从不回显,锚点在编辑后依然有效,每个解析出的范围都会与模型实际看到的内容逐一核对——错行编辑不可能悄悄落盘。
44
48
 
@@ -48,6 +52,15 @@
48
52
 
49
53
  Hashline 用两个哈希代替旧文本——**编辑 token 减少 31%**(多行范围达 43%)——并对照模型所见内容校验每个范围:编辑要么落在你想要的行的位置,要么响亮失败并回传新锚点。锚点是内容地址,上方编辑后依然有效,连续编辑无需重读;上下文更精简,模型的注意力也保持在代码上,而不是复述上。
50
54
 
55
+ > [!TIP]
56
+ > **亮点——诚实且可衡量:**
57
+ >
58
+ > - **自愈而非静默。** 外部编辑永不被覆盖——过期范围被拒绝并以全新 `HASH│content` 重发重试;孤儿 served 条目无需全量重读即可自愈(ADR-0008)。Fail-closed,而非自动合并。
59
+ > - **格式化容忍。** ASCII 空白不敏感锚点在 `prettier`/`black`/`eslint --fix` 之间存活(`formatOnSave`、监听、CI)。仅限 linter 场景——字符串内的空白不区分(ADR-0005)。
60
+ > - **链式与批量,无重读仪式。** 未受影响行的锚点保持有效;diff/回显/拒绝行即视为已提供。`edit` 最多 32 个同文件编辑原子执行(`[E_BATCH_ABORT]`),相比 `str_replace` 信封约 -40%。
61
+ > - **读守卫。** 从未展示过的行永不被编辑——`[E_RANGE_UNSERVED]`/`[E_RANGE_UNVERIFIED]`/`[E_STALE_ANCHOR]` 在写入前拒绝,随后 `reject-and-serve`。
62
+ > - **更少往返。** 实测:同样外部漂移重构,OMP 封装需 6 次调用,hashline 仅 3 次;信封 vs `str_replace` 的节省是稳定值—— upstream 电池可复现(算法相同)。
63
+
51
64
  不适用于单行小改动(接近持平)或新建文件(用 `write`)。它的价值在长会话与结构性编辑中体现——任何不允许改错行的场景。
52
65
 
53
66
  ## 快速开始
@@ -55,8 +68,9 @@ Hashline 用两个哈希代替旧文本——**编辑 token 减少 31%**(多
55
68
  ### 安装
56
69
 
57
70
  ```sh
58
- dsh plugin --profile <name> add dsh-better-edit # 从 npm
59
- dsh plugin --profile <name> add /path/to/dsh-better-edit # 从本地源码
71
+ npx @deepseek-ai/dsh plugin --profile web add github:Rianico/dsh-better-edit # 从 github
72
+ npx @deepseek-ai/dsh plugin --profile web add dsh-better-edit # 从 npm
73
+ npx @deepseek-ai/dsh plugin --profile web add /path/to/dsh-better-edit # 从本地源码
60
74
  ```
61
75
 
62
76
  该 profile 的下一个会话将带着 hashline 工具运行。验证该层是否生效:
@@ -84,9 +98,7 @@ kQm│}
84
98
  ```json
85
99
  {
86
100
  "path": "src/main.ts",
87
- "remove_from": "szJ",
88
- "remove_to": "szJ",
89
- "replacement_text": " console.log('hi');"
101
+ "edits": [["szJ", "szJ", " console.log('hi');"]]
90
102
  }
91
103
  ```
92
104
 
@@ -100,7 +112,7 @@ kQm│}
100
112
 
101
113
  ## 按 preset 配置指引
102
114
 
103
- `tool:read` / `tool:edit` / `tool:batch_edit` / `tool:undo_last_edit` 四个提示词片段的指引是
115
+ `tool:read` / `tool:edit` / `tool:undo_last_edit` 三个提示词片段的指引是
104
116
  纯 Markdown 文件,可以按 agent preset 覆盖。覆盖文件位于插件的共享主目录——绝不放在工作区存储中:
105
117
 
106
118
  ```
@@ -113,12 +125,11 @@ $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
113
125
  | --- | --- | --- |
114
126
  | `read.md` | `tool:read` | 130 |
115
127
  | `edit.md` | `tool:edit` | 131 |
116
- | `batch_edit.md` | `tool:batch_edit` | 132 |
117
128
  | `undo_last_edit.md` | `tool:undo_last_edit` | 133 |
118
129
 
119
- 首次启动时插件会为四个随附 preset——`standard/`、`code/`、`minimal/`、`cordis/`——各自写入编译内置的
130
+ 首次启动时插件会为三个随附 preset——`standard/`、`code/`、`minimal/`、`cordis/`——各自写入编译内置的
120
131
  可编辑指引文件(含 `order` front-matter),让每个 preset 的指引一开始就可编辑,而不是空白。插件主目录
121
- 根的 `README.md` 说明整套机制。文件只在首次写入时生成、之后绝不被覆盖,因此你的修改会保留。preset 目录
132
+ 根的 `README.md` 说明整套机制。文件只在首次写入时生成、之后绝不被覆盖,因此你的修改会保留——唯一的例外是重置(见下文 *重置 / 恢复默认*)。preset 目录
122
133
  里可以只放你想覆盖的片段文件,其余自动回退到编译内置默认值。
123
134
 
124
135
  文件默认为纯文本;除非以 `order` front-matter 栅栏开头,它会改变该片段在组装后的系统提示中的位置:
@@ -137,6 +148,24 @@ session-start 时读取一次,因此修改只影响新会话——绝不影响
137
148
  (即没有 preset 名册)的部署继续使用编译内置默认值,完全不会触碰这些文件;
138
149
  preset 从来不是必需的。
139
150
 
151
+ ### 重置 / 恢复默认
152
+
153
+ **想让指引“回到默认”?删掉覆盖文件,或把它清空(同时删掉开头的 `---` 栅栏)即可。**
154
+
155
+ 清空文件时,只要文件里是空白内容、并且没有 `---` 栅栏,插件就认为你不想再自定义这一片段了,于是:
156
+
157
+ - 新会话开始时,直接使用插件内置的默认指引;
158
+ - 下一次启动插件时,会用默认内容把这个文件重新生成。
159
+
160
+ 再细致一点:
161
+
162
+ - **为什么要连栅栏一起删**:只要文件里还有 `---` 栅栏,哪怕是空的、什么内容也没有,插件都当成“你有意留空”,不会去动它。所以“故意留空”就保留栅栏;“恢复默认”就把栅栏和内容一起清掉。
163
+ - **栅栏写错了会怎样**:少了一个 `---`、`order` 不是数字、出现了不认识的键——只要栅栏格式不对,插件会直接忽略这个文件:仍然渲染默认指引,并在日志里提示是哪个文件、哪里写错了。你写的正文会原样留在磁盘上,方便改好后再用。
164
+ - **自带 preset 与自定义 preset**:插件自带的四个 preset(`standard`、`code`、`minimal`、`cordis`)会在下一次启动时自动补全空白文件;自定义 preset 里删除的覆盖文件不会自动出现(删了就当“没有这个文件”)。删掉某一整个 preset 目录,下次启动时插件会重新生成里面的四个文件(仅限自带 preset)。
165
+ - **恢复的是“当前版本”的默认**:插件升级后,重置得到的是新版本带的新默认内容,不是旧版本留下的。
166
+
167
+ 文件的重新生成只发生在插件启动时,绝不影响进行中的会话。
168
+
140
169
  ## 为什么用 Hashline
141
170
 
142
171
  **省 token。** 一次编辑调用只携带 `remove_from` / `remove_to`(两个 3 字符哈希)加替换文本——从不回显被替换的文本。`str_replace` 调用则必须逐字复现被替换的文本。在一个真实文件上的 12 次编辑会话中,这可以**减少 31% 的输出 token**(多行范围达 43%)——而且这些是*输出* token,按输入的约 5-6 倍计费。见[基准测试](#基准测试)。
@@ -180,7 +209,7 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
180
209
  | 重复/相同文本 | 每行哈希唯一(冲突已消解);歧义 → `[E_AMBIGUOUS_ANCHOR]` | 基于位置,重复不会混淆——但位置本身未被校验 |
181
210
  | 从未展示给模型的行 | `[E_RANGE_UNSERVED]`——硬拒绝并回传新锚点 | 未展示的 hunk 被拒绝——同样依赖模型知道自己看过什么 |
182
211
  | 表达式中间 / 错误的块节点 | 无关——任何已校验的行范围都合法 | 语法规则 + `PUT N*:` 节点选择;点错(锚在 `def` 会让装饰器变成孤儿)会悄悄落错;无语法检查 |
183
- | 多编辑批量中途失败 | `batch_edit`——原子、全有或全无;失败项以新锚点回显 | 多段补丁先预检——同样原子 |
212
+ | 多编辑批量中途失败 | `edit` 多条目——原子、全有或全无;失败项以新锚点回显 | 多段补丁先预检——同样原子 |
184
213
 
185
214
  > oh-my-pi 42–53% 的负载节省来自更轻的线格式;上表才是该格式反过来要求模型记在脑中的东西——重新编号、追标签、选节点——而这恰恰是最容易出错的组件(替换式编辑的补丁失败率 46–51%)。本插件 31% 的代价买来的是一个“错编辑落不了地、任何拒绝都不需要重读”的契约。
186
215
 
@@ -219,8 +248,7 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
219
248
  | 工具 | 作用 |
220
249
  | ------ | ------ |
221
250
  | `read` | 以 `HASH│内容` 形式返回文件。参数:`offset`(1 起始)、`limit`。分页输出以 `[Showing lines N-M of T. Use offset=… to continue.]` 结尾。超过 200KB 的行显示为标记并附 `sed` 提示——哈希锚点需要完整行。 |
222
- | `edit` | 按哈希替换行范围。`path` · `remove_from` · `remove_to` · `replacement_text`(`""` 表示删除)。对解析出的范围内**每一行**对照已提供状态校验;`[E_RANGE_STALE]` / `[E_RANGE_UNSERVED]` / `[E_RANGE_UNVERIFIED]` 拒绝并回传新锚点。 |
223
- | `batch_edit` | 单次原子调用最多 32 项编辑:`{ edits: [{ path?, remove_from, remove_to, replacement_text }, …] }`。全有或全无;失败项的范围会以新锚点的形式回显。 |
251
+ | `edit` | 对象根负载 `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], …] }`;`path` 可为 `null` 以通过锚点推断。单个条目编辑一个范围;多条目对同一文件原子批量(最多 32)。对每个包含范围内的每一行校验,reject-and-serve 返回新锚点。 |
224
252
  | `undo_last_edit` | `{ path }` 撤销该文件上一次 hashline 编辑,仅当文件仍与存储的编辑后内容一致时生效;重启后依然有效。 |
225
253
 
226
254
  ### 错误码
package/lib/contract.js CHANGED
@@ -12,7 +12,7 @@
12
12
  */
13
13
  import { BATCH_EDIT_MAX_ITEMS } from "./constants.js";
14
14
  import { isRec, normalizeFilePath, rejectUnknownFields } from "./utils.js";
15
- // ---- field sets (declared once) ---------------------------------------------
15
+ // ---- filed sets (declared once) ---------------------------------------------
16
16
  const EDIT_KS = new Set([
17
17
  "path",
18
18
  "remove_from",
@@ -33,6 +33,21 @@ const BATCH_ITEM_KS = new Set([
33
33
  "replacement_text",
34
34
  ]);
35
35
  const READ_KS = new Set(["path", "offset", "limit"]);
36
+ // ---- normalization -----------------------------------------------------------
37
+ /**
38
+ * Normalize `file_path` → `path` alias on the request record. Returns the
39
+ * input unchanged when not a record; otherwise returns a shallow copy with
40
+ * the alias applied so callers never mutate the original `args` object.
41
+ */
42
+ export function normalizeRequest(input) {
43
+ if (!isRec(input))
44
+ return input;
45
+ const record = { ...input };
46
+ normalizeFilePath(record);
47
+ return record;
48
+ }
49
+ /** @deprecated use normalizeRequest — kept as alias for migration */
50
+ export const normReq = normalizeRequest;
36
51
  // ---- assertions ---------------------------------------------------------------
37
52
  export function assertEditRequest(request) {
38
53
  if (!isRec(request)) {
@@ -93,3 +108,27 @@ export function assertUndoRequest(request) {
93
108
  throw new Error('[E_BAD_SHAPE] undo_last_edit request requires a non-empty "path" string.');
94
109
  }
95
110
  }
111
+ // ---- shared JSON Schema literals (co-located with field sets) ---------------
112
+ /**
113
+ * Shared model-facing parameter schemas for the hashline tools, expressed in
114
+ * the dsh schema DSL (not TypeBox). `path` is deliberately NOT `required` at
115
+ * the schema level: the tools accept the built-in `file_path` spelling too
116
+ * (the implicit parameter root stays open), and enforce path presence in
117
+ * `assertEditRequest` after `normalizeFilePath` aliasing.
118
+ */
119
+ export const replacementTextSchema = {
120
+ type: 'string',
121
+ description: 'Replacement text as a single string with \\n line separators; every \\n separates lines, so a trailing \\n adds a final empty line. Mirror the removed lines exactly, blank lines included. A replacement that is only blank lines is written as one \\n per blank line. Use "" to delete the range.',
122
+ };
123
+ export const removeFromSchema = {
124
+ type: 'string',
125
+ description: 'Bare 3-char HASH only (e.g. "aB3") — copy just the hash from the leftmost column of a read row like `aB3│content`; never the line content. Marks the FIRST line to remove (inclusive)',
126
+ };
127
+ export const removeToSchema = {
128
+ type: 'string',
129
+ description: 'Bare 3-char HASH only (e.g. "aB3") — copy just the hash from the leftmost column of a read row like `aB3│content`; never the line content. Marks the LAST line to remove (inclusive)',
130
+ };
131
+ export const pathSchema = {
132
+ type: 'string',
133
+ description: 'Path to edit. Required — always provide it explicitly; it is only auto-resolved from the anchors as a fallback when omitted by mistake.',
134
+ };
@@ -12,10 +12,10 @@
12
12
  */
13
13
  import { restoreEndings } from "./edit-diff.js";
14
14
  import { normFromText } from "./file-reader.js";
15
- import { scanDrift } from "./drift.js";
16
- import { applyEdit, lineHashes, resEdit, parseHashRef, MAX_HASH_LINES, } from "./hashline/index.js";
17
- import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "./hashline/served.js";
18
- import { loadServed } from "./served-store.js";
15
+ import { scanDrift, loadServed } from "./session-view.js";
16
+ import { applyEdit, resEdit, parseHashRef, } from "./hashline/anchor-pipeline.js";
17
+ import { lineHashes, MAX_HASH_LINES } from "./hashline/hash-assign.js";
18
+ import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "./hashline/anchor-pipeline.js";
19
19
  import { findSnapshotPathsByHashes } from "./hash-store.js";
20
20
  import { saveUndo } from "./undo-edit.js";
21
21
  import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
@@ -11,10 +11,10 @@
11
11
  */
12
12
  import { normFromText, fileSnap } from './file-reader.js';
13
13
  import { toCwd } from './paths.js';
14
- import { resEdit, MAX_HASH_LINES, } from './hashline/index.js';
15
- import { AnchorMismatchError, ServedRejectionError, recordEchoServes, } from './hashline/served.js';
16
- import { loadServed, sessionKeyFor } from './served-store.js';
17
- import { scanDrift } from './drift.js';
14
+ import { resEdit } from './hashline/anchor-pipeline.js';
15
+ import { MAX_HASH_LINES } from './hashline/hash-assign.js';
16
+ import { AnchorMismatchError, ServedRejectionError, recordEchoServes, } from './hashline/anchor-pipeline.js';
17
+ import { loadServed, sessionKeyFor, scanDrift } from './session-view.js';
18
18
  import { abortIf, splitLines } from './utils.js';
19
19
  import { applyOne } from './edit-engine.js';
20
20
  export async function execPipeline(io, params, cwd, options) {
@@ -0,0 +1,63 @@
1
+ /**
2
+ * FileView — deep module owning "what the model sees".
3
+ *
4
+ * Single seam for normalize → hash → render → truncate → served-row
5
+ * selection. The read path was 6 shallow modules for one concept:
6
+ * `tool-read → read-and-serve → file-reader → read-render → fs-bridge
7
+ * → file-kind/validation/truncate`, each with interface ≈ implementation.
8
+ *
9
+ * Now: one file to understand reads. The private helpers
10
+ * (`file-reader`, `read-render`, `truncate`, `file-kind`, `validation`)
11
+ * are *private to this seam* — do not import them directly outside this
12
+ * module. Import from `file-view` instead. `fs-bridge` stays as the IO seam.
13
+ *
14
+ * Two surfaces:
15
+ * - `preview` (pure, no IO) — tested without filesystem
16
+ * - `readView` (IO) — read + normalize + render + truncate + hashes
17
+ *
18
+ * The emergent interaction (MAX_HASH_LINES vs MAX_READ_LINE_BYTES vs
19
+ * truncation, partial serve on oversized lines) now lives in one module
20
+ * and is one test surface.
21
+ *
22
+ * @module dsh-better-edit/file-view
23
+ */
24
+ import { normFromText } from "./file-reader.js";
25
+ import { fmtReadPreview, MAX_HASH_LINES } from "./read-render.js";
26
+ /**
27
+ * Pure rendering without IO — tested without filesystem.
28
+ * Wraps `fmtReadPreview` so callers have one place to render.
29
+ */
30
+ export async function preview(content, hashes, opts = {}, absolutePath) {
31
+ return fmtReadPreview(content, opts, hashes, absolutePath);
32
+ }
33
+ /**
34
+ * IO version: read + normalize + render + truncate + hashes.
35
+ * Single place that decides `served[]` — no emergent partial-serve.
36
+ */
37
+ export async function readView(io, path, cwd, opts = {}) {
38
+ const { signal } = opts;
39
+ const absolutePath = await io.resolve(path, cwd, signal);
40
+ const rawText = await io.readText(absolutePath, signal);
41
+ const { normalized, fileHashes, hadUtf8DecodeErrors, bom, originalEnding } = await normFromText({
42
+ absolutePath,
43
+ rawText,
44
+ displayPath: path,
45
+ signal,
46
+ maxLines: MAX_HASH_LINES,
47
+ });
48
+ const r = await fmtReadPreview(normalized, { offset: opts.offset, limit: opts.limit }, fileHashes, absolutePath);
49
+ return {
50
+ text: r.text,
51
+ hashes: fileHashes,
52
+ served: r.served,
53
+ absolutePath,
54
+ truncation: r.truncation,
55
+ nextOffset: r.nextOffset,
56
+ hadUtf8DecodeErrors,
57
+ bom,
58
+ originalEnding,
59
+ normalized,
60
+ };
61
+ }
62
+ // Re-export constants that belong to this seam for callers that need limits
63
+ export { MAX_HASH_LINES };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Barrel for guidance sub-seams — parse (pure), resolve (IO-light), materialize (IO-heavy).
3
+ * Re-exported via `src/guidance.ts` so existing `from "./guidance.js"` imports keep working.
4
+ * @module dsh-better-edit/guidance/index
5
+ */
6
+ export * from "./parse.js";
7
+ export * from "./resolve.js";
8
+ export * from "./materialize.js";
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Materializer: IO-heavy seam owning per-preset directory seeding, blank-heal,
3
+ * and README generation. Idempotent and concurrent-safe (wx).
4
+ * @module dsh-better-edit/guidance/materialize
5
+ */
6
+ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
7
+ import { join } from "node:path";
8
+ import { errCode } from "../utils.js";
9
+ import { isBlankOverride } from "./parse.js";
10
+ import { GUIDANCE_SECTIONS } from "./resolve.js";
11
+ /** The presets shipped by the harness, each seeded with editable guidance. */
12
+ export const DEFAULT_PRESETS = [
13
+ "standard",
14
+ "code",
15
+ "minimal",
16
+ "cordis",
17
+ ];
18
+ /**
19
+ * The root README: the per-preset customization convention users see in the
20
+ * plugin home.
21
+ */
22
+ export const GUIDANCE_HOME_README = `# dsh-better-edit guidance
23
+
24
+ Each agent preset has its own guidance directory here: \`<preset>/<section>.md\`.
25
+ On first boot the plugin seeds the shipped presets (\`standard\`, \`code\`,
26
+ \`minimal\`, \`cordis\`) with the compiled defaults; existing files are never
27
+ overwritten, so your edits survive.
28
+
29
+ Each file is one tool section:
30
+
31
+ - \`read.md\` -> \`tool:read\`
32
+ - \`edit.md\` -> \`tool:edit\`
33
+ - \`batch_edit.md\` -> \`tool:batch_edit\`
34
+ - \`undo_last_edit.md\` -> \`tool:undo_last_edit\`
35
+
36
+ ## Customize
37
+
38
+ Edit the \`<section>.md\` file for the preset and section you want to change —
39
+ the file body IS the text the model reads for that section. Files are read once
40
+ per agent at session-start, so edits apply to new sessions.
41
+
42
+ An optional YAML front-matter fence places the section at a custom position in
43
+ the assembled system prompt:
44
+
45
+ ---
46
+ order: 150
47
+ ---
48
+
49
+ <section text>
50
+
51
+ A file without front-matter keeps the default order. A malformed fence (a
52
+ missing closing \`---\`, a non-integer \`order\`, an unknown key) makes the whole
53
+ file plain prose.
54
+
55
+ ## Fallback
56
+
57
+ A preset with no directory here, or a missing section file, falls back to the
58
+ compiled defaults in the plugin bundle. To customize a preset that has no
59
+ seeded directory, copy a seeded one to its name.
60
+ `;
61
+ export const GUIDANCE_HOME_README_ZH = `# dsh-better-edit 指引
62
+
63
+ 每个 agent preset 在这里都有自己的指引目录:\`<preset>/<section>.md\`。首次启动时
64
+ 插件会为随附的 preset(\`standard\`、\`code\`、\`minimal\`、\`cordis\`)写入编译内置的
65
+ 默认内容;已有文件绝不被覆盖,因此你的编辑会保留。
66
+
67
+ 每个文件对应一个工具片段:
68
+
69
+ - \`read.md\` -> \`tool:read\`
70
+ - \`edit.md\` -> \`tool:edit\`
71
+ - \`batch_edit.md\` -> \`tool:batch_edit\`
72
+ - \`undo_last_edit.md\` -> \`tool:undo_last_edit\`
73
+
74
+ ## 自定义
75
+
76
+ 编辑你想修改的 preset 与片段的 \`<section>.md\` 文件即可——文件正文就是该片段呈
77
+ 现给模型的文本。文件在 agent 的 session-start 时读取一次,因此修改只影响新会话。
78
+
79
+ 可以用可选的 YAML front-matter 栅栏把片段放到组装后系统提示中的自定义位置:
80
+
81
+ ---
82
+ order: 150
83
+ ---
84
+
85
+ <片段文本>
86
+
87
+ 没有 front-matter 的文件保持默认顺序。格式错误的栅栏(缺少收尾 \`---\`、非整数
88
+ \`order\`、未知键)会让整个文件退化为纯文本。
89
+
90
+ ## 回退
91
+
92
+ 这里没有对应目录的 preset、或缺失某个片段文件时,会回退到插件包内的编译内置默认
93
+ 值。要自定义没有种子目录的 preset,把一个种子目录复制成它的名字即可。
94
+ `;
95
+ /** The content a seeded override file carries, rendered from the current defaults. */
96
+ function seededContent(section) {
97
+ return `---\norder: ${section.defaultOrder}\n---\n\n${section.renderDefault()}`;
98
+ }
99
+ /**
100
+ * Heal an existing empty override file: a blank file means "use the default",
101
+ * so it is rewritten with the current seeded default. Malformed, non-blank, and
102
+ * deliberate-blank (valid-fence) files are left untouched — overwriting a
103
+ * malformed file would destroy the user's salvageable body. Plain overwrite:
104
+ * the file already exists. Errors propagate to the boot caller, which never
105
+ * fails init.
106
+ */
107
+ async function healBlankOverride(path, section) {
108
+ let content;
109
+ try {
110
+ content = await readFile(path, "utf-8");
111
+ }
112
+ catch (error) {
113
+ // Vanished between readdir and read; nothing to heal.
114
+ if (errCode(error) === "ENOENT")
115
+ return;
116
+ throw error;
117
+ }
118
+ if (!isBlankOverride(content))
119
+ return;
120
+ await writeFile(path, seededContent(section), { encoding: "utf-8" });
121
+ }
122
+ /**
123
+ * Materialize per-preset guidance directories in the plugin home.
124
+ *
125
+ * For each of `DEFAULT_PRESETS` creates `<preset>/{read,edit,batch_edit,
126
+ * undo_last_edit}.md` rendered from the compiled defaults (with order
127
+ * front-matter), plus a root `README.md` documenting the convention.
128
+ * Idempotent: a user-edited file survives repeated calls. A blank override file
129
+ * (whitespace-only body, no fence) is re-seeded with the current compiled
130
+ * default; malformed, non-blank, and deliberate-blank (valid-fence) files are
131
+ * never touched. Custom preset directories present on disk are scanned the same
132
+ * way but never fabricated. Missing directories are created on demand (shipped
133
+ * presets only), and shipped files are written exclusively so two concurrent
134
+ * first runs race safely.
135
+ */
136
+ export async function ensurePresetGuidance(homeDir) {
137
+ await mkdir(homeDir, { recursive: true });
138
+ await Promise.all(DEFAULT_PRESETS.map(async (preset) => {
139
+ const dir = join(homeDir, preset);
140
+ await mkdir(dir, { recursive: true });
141
+ const existing = new Set(await readdir(dir));
142
+ await Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
143
+ const path = join(dir, section.file);
144
+ if (existing.has(section.file)) {
145
+ await healBlankOverride(path, section);
146
+ return;
147
+ }
148
+ await writeFile(path, seededContent(section), {
149
+ encoding: "utf-8",
150
+ flag: "wx",
151
+ }).catch((error) => {
152
+ // A concurrent writer landed first; never clobber it.
153
+ if (errCode(error) === "EEXIST")
154
+ return;
155
+ throw error;
156
+ });
157
+ }));
158
+ }));
159
+ // Custom presets present on disk: heal existing blank section files only.
160
+ // Absence is respected — a custom preset's files are never fabricated, and
161
+ // malformed / non-blank / deliberate-blank files are left untouched.
162
+ const entries = await readdir(homeDir, { withFileTypes: true });
163
+ await Promise.all(entries
164
+ .filter((entry) => entry.isDirectory() && !DEFAULT_PRESETS.includes(entry.name))
165
+ .map(async (entry) => {
166
+ const dir = join(homeDir, entry.name);
167
+ const existing = new Set(await readdir(dir));
168
+ await Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
169
+ if (!existing.has(section.file))
170
+ return;
171
+ await healBlankOverride(join(dir, section.file), section);
172
+ }));
173
+ }));
174
+ const homeFiles = new Set(await readdir(homeDir));
175
+ const readmes = [
176
+ ["README.md", GUIDANCE_HOME_README],
177
+ ["README.zh.md", GUIDANCE_HOME_README_ZH],
178
+ ];
179
+ await Promise.all(readmes.map(async ([file, content]) => {
180
+ if (homeFiles.has(file))
181
+ return;
182
+ await writeFile(join(homeDir, file), content, {
183
+ encoding: "utf-8",
184
+ flag: "wx",
185
+ }).catch((error) => {
186
+ if (errCode(error) === "EEXIST")
187
+ return;
188
+ throw error;
189
+ });
190
+ }));
191
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Pure parser for per-preset guidance override files.
3
+ *
4
+ * Only a leading `---` fence whose lines are empty or `order: <integer>` is
5
+ * accepted. This module has zero IO — exhaustive unit testing without a temp
6
+ * home.
7
+ * @module dsh-better-edit/guidance/parse
8
+ */
9
+ function stripCR(line) {
10
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
11
+ }
12
+ function startsWithFenceLine(content) {
13
+ return stripCR(content.split("\n")[0]) === "---";
14
+ }
15
+ /**
16
+ * Parse an override file. Only a leading `---` fence whose lines are empty or
17
+ * `order: <integer>` is accepted. A leading `---` that does not parse (no
18
+ * closing fence, unknown key, non-integer value) is a malformed override;
19
+ * anything else is pure prose (the whole file as text).
20
+ */
21
+ export function parseSectionFile(content) {
22
+ const lines = content.split("\n");
23
+ if (stripCR(lines[0] ?? "") !== "---") {
24
+ return { text: content };
25
+ }
26
+ const close = lines.findIndex((line, index) => index > 0 && stripCR(line) === "---");
27
+ if (close < 0) {
28
+ return { text: content, malformed: true, reason: "missing closing fence" };
29
+ }
30
+ let order;
31
+ for (let index = 1; index < close; index++) {
32
+ const line = stripCR(lines[index]);
33
+ if (line.trim() === "")
34
+ continue;
35
+ const key = line.split(":")[0].trim();
36
+ const match = /^order:\s*(-?\d+)\s*$/.exec(line);
37
+ if (!match) {
38
+ if (key === "order") {
39
+ const value = line.slice(line.indexOf(":") + 1).trim();
40
+ return {
41
+ text: content,
42
+ malformed: true,
43
+ reason: `non-integer order '${value}'`,
44
+ };
45
+ }
46
+ return {
47
+ text: content,
48
+ malformed: true,
49
+ reason: `unknown key '${key}'`,
50
+ };
51
+ }
52
+ order = Number.parseInt(match[1], 10);
53
+ }
54
+ // Front-matter body: strip leading blank lines after the closing fence so
55
+ // `---\n…\n---\n\nbody` and `---\n…\n---\nbody` parse identically (the
56
+ // materialized preset files carry a blank line after the fence).
57
+ const body = lines.slice(close + 1);
58
+ let bodyStart = 0;
59
+ while (bodyStart < body.length && body[bodyStart].trim() === "")
60
+ bodyStart++;
61
+ return { order, text: body.slice(bodyStart).join("\n") };
62
+ }
63
+ /**
64
+ * True when an override file is blank: whitespace-only body and NO front-matter
65
+ * fence (the "I want the default" case). The single source of truth for whether
66
+ * a boot-time materialization pass should re-seed a file. False for prose with
67
+ * content, for any valid fence (including a keyless/empty one — a deliberate
68
+ * blank), and for malformed files.
69
+ */
70
+ export function isBlankOverride(content) {
71
+ const parsed = parseSectionFile(content);
72
+ return (!parsed.malformed &&
73
+ parsed.order === undefined &&
74
+ parsed.text.trim() === "" &&
75
+ !startsWithFenceLine(content));
76
+ }
77
+ /** True when an override file opens with a leading `---` fence that is malformed. */
78
+ export function isMalformedOverride(content) {
79
+ return parseSectionFile(content).malformed === true;
80
+ }