dsh-better-edit 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +318 -245
- package/README.zh.md +20 -11
- package/lib/contract.js +40 -1
- package/lib/edit-engine.js +4 -4
- package/lib/edit-pipeline.js +4 -4
- package/lib/file-view.js +63 -0
- package/lib/guidance/index.js +8 -0
- package/lib/guidance/materialize.js +191 -0
- package/lib/guidance/parse.js +80 -0
- package/lib/guidance/resolve.js +122 -0
- package/lib/guidance.js +6 -388
- package/lib/hash-store.js +1 -2
- package/lib/hashline/anchor-pipeline.js +23 -0
- package/lib/hashline/hash-assign.js +20 -0
- package/lib/hashline/index.js +4 -5
- package/lib/hashline/resolve.js +5 -0
- package/lib/index.js +1 -1
- package/lib/mutation.js +58 -0
- package/lib/read-and-serve.js +23 -23
- package/lib/served-store.js +1 -1
- package/lib/session-view.js +34 -0
- package/lib/tool-batch-edit.js +9 -10
- package/lib/tool-edit.js +9 -11
- package/lib/tool-read.js +3 -5
- package/lib/tool-undo.js +6 -6
- package/lib/types/contract.d.ts +31 -0
- package/lib/types/edit-engine.d.ts +2 -2
- package/lib/types/edit-pipeline.d.ts +2 -2
- package/lib/types/file-view.d.ts +74 -0
- package/lib/types/guidance/index.d.ts +8 -0
- package/lib/types/guidance/materialize.d.ts +23 -0
- package/lib/types/guidance/parse.d.ts +36 -0
- package/lib/types/guidance/resolve.d.ts +55 -0
- package/lib/types/guidance.d.ts +6 -127
- package/lib/types/hashline/anchor-pipeline.d.ts +26 -0
- package/lib/types/hashline/hash-assign.d.ts +19 -0
- package/lib/types/hashline/index.d.ts +7 -5
- package/lib/types/hashline/resolve.d.ts +5 -0
- package/lib/types/mutation.d.ts +78 -0
- package/lib/types/read-and-serve.d.ts +6 -5
- package/lib/types/session-view.d.ts +33 -0
- package/lib/write-hook.js +2 -2
- package/package.json +1 -1
package/README.zh.md
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
</p>
|
|
24
24
|
|
|
25
25
|
<p align="center">
|
|
26
|
-
<img src="https://img.shields.io/badge/version-0.
|
|
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*]
|
|
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
|
## 快速开始
|
|
@@ -85,9 +98,7 @@ kQm│}
|
|
|
85
98
|
```json
|
|
86
99
|
{
|
|
87
100
|
"path": "src/main.ts",
|
|
88
|
-
"
|
|
89
|
-
"remove_to": "szJ",
|
|
90
|
-
"replacement_text": " console.log('hi');"
|
|
101
|
+
"edits": [["szJ", "szJ", " console.log('hi');"]]
|
|
91
102
|
}
|
|
92
103
|
```
|
|
93
104
|
|
|
@@ -101,7 +112,7 @@ kQm│}
|
|
|
101
112
|
|
|
102
113
|
## 按 preset 配置指引
|
|
103
114
|
|
|
104
|
-
`tool:read` / `tool:edit` / `tool:
|
|
115
|
+
`tool:read` / `tool:edit` / `tool:undo_last_edit` 三个提示词片段的指引是
|
|
105
116
|
纯 Markdown 文件,可以按 agent preset 覆盖。覆盖文件位于插件的共享主目录——绝不放在工作区存储中:
|
|
106
117
|
|
|
107
118
|
```
|
|
@@ -114,10 +125,9 @@ $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
|
|
|
114
125
|
| --- | --- | --- |
|
|
115
126
|
| `read.md` | `tool:read` | 130 |
|
|
116
127
|
| `edit.md` | `tool:edit` | 131 |
|
|
117
|
-
| `batch_edit.md` | `tool:batch_edit` | 132 |
|
|
118
128
|
| `undo_last_edit.md` | `tool:undo_last_edit` | 133 |
|
|
119
129
|
|
|
120
|
-
|
|
130
|
+
首次启动时插件会为三个随附 preset——`standard/`、`code/`、`minimal/`、`cordis/`——各自写入编译内置的
|
|
121
131
|
可编辑指引文件(含 `order` front-matter),让每个 preset 的指引一开始就可编辑,而不是空白。插件主目录
|
|
122
132
|
根的 `README.md` 说明整套机制。文件只在首次写入时生成、之后绝不被覆盖,因此你的修改会保留——唯一的例外是重置(见下文 *重置 / 恢复默认*)。preset 目录
|
|
123
133
|
里可以只放你想覆盖的片段文件,其余自动回退到编译内置默认值。
|
|
@@ -199,7 +209,7 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
|
|
|
199
209
|
| 重复/相同文本 | 每行哈希唯一(冲突已消解);歧义 → `[E_AMBIGUOUS_ANCHOR]` | 基于位置,重复不会混淆——但位置本身未被校验 |
|
|
200
210
|
| 从未展示给模型的行 | `[E_RANGE_UNSERVED]`——硬拒绝并回传新锚点 | 未展示的 hunk 被拒绝——同样依赖模型知道自己看过什么 |
|
|
201
211
|
| 表达式中间 / 错误的块节点 | 无关——任何已校验的行范围都合法 | 语法规则 + `PUT N*:` 节点选择;点错(锚在 `def` 会让装饰器变成孤儿)会悄悄落错;无语法检查 |
|
|
202
|
-
| 多编辑批量中途失败 | `
|
|
212
|
+
| 多编辑批量中途失败 | `edit` 多条目——原子、全有或全无;失败项以新锚点回显 | 多段补丁先预检——同样原子 |
|
|
203
213
|
|
|
204
214
|
> oh-my-pi 42–53% 的负载节省来自更轻的线格式;上表才是该格式反过来要求模型记在脑中的东西——重新编号、追标签、选节点——而这恰恰是最容易出错的组件(替换式编辑的补丁失败率 46–51%)。本插件 31% 的代价买来的是一个“错编辑落不了地、任何拒绝都不需要重读”的契约。
|
|
205
215
|
|
|
@@ -238,8 +248,7 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
|
|
|
238
248
|
| 工具 | 作用 |
|
|
239
249
|
| ------ | ------ |
|
|
240
250
|
| `read` | 以 `HASH│内容` 形式返回文件。参数:`offset`(1 起始)、`limit`。分页输出以 `[Showing lines N-M of T. Use offset=… to continue.]` 结尾。超过 200KB 的行显示为标记并附 `sed` 提示——哈希锚点需要完整行。 |
|
|
241
|
-
| `edit` |
|
|
242
|
-
| `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 返回新锚点。 |
|
|
243
252
|
| `undo_last_edit` | `{ path }` 撤销该文件上一次 hashline 编辑,仅当文件仍与存储的编辑后内容一致时生效;重启后依然有效。 |
|
|
244
253
|
|
|
245
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
|
-
// ----
|
|
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
|
+
};
|
package/lib/edit-engine.js
CHANGED
|
@@ -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 "./
|
|
16
|
-
import { applyEdit,
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
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";
|
package/lib/edit-pipeline.js
CHANGED
|
@@ -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
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import { scanDrift } from './
|
|
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) {
|
package/lib/file-view.js
ADDED
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolver: IO-light seam owning "first existing candidate wins, blank=skip,
|
|
3
|
+
* malformed=fallback+report" policy for guidance override files.
|
|
4
|
+
*
|
|
5
|
+
* Tested via temp-home FS; materializer stubs this module.
|
|
6
|
+
* @module dsh-better-edit/guidance/resolve
|
|
7
|
+
*/
|
|
8
|
+
import { readFile } from "node:fs/promises";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { BATCH_EDIT_GUIDANCE, EDIT_GUIDANCE, READ_GUIDANCE, UNDO_GUIDANCE, } from "../prompts.js";
|
|
11
|
+
import { errCode } from "../utils.js";
|
|
12
|
+
import { isBlankOverride, parseSectionFile } from "./parse.js";
|
|
13
|
+
/**
|
|
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
|
|
16
|
+
* (that already reaches the model through the tool catalog).
|
|
17
|
+
*/
|
|
18
|
+
function guidanceText(g) {
|
|
19
|
+
return [g.intro, "", bulletLines(g.lines)].join("\n");
|
|
20
|
+
}
|
|
21
|
+
function bulletLines(lines) {
|
|
22
|
+
return lines.map((line) => `- ${line}`).join("\n");
|
|
23
|
+
}
|
|
24
|
+
/** The four sections, in default-order sequence. */
|
|
25
|
+
export const GUIDANCE_SECTIONS = [
|
|
26
|
+
{
|
|
27
|
+
name: "tool:read",
|
|
28
|
+
file: "read.md",
|
|
29
|
+
defaultOrder: 130,
|
|
30
|
+
renderDefault: () => guidanceText(READ_GUIDANCE),
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
name: "tool:edit",
|
|
34
|
+
file: "edit.md",
|
|
35
|
+
defaultOrder: 131,
|
|
36
|
+
renderDefault: () => guidanceText(EDIT_GUIDANCE),
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
name: "tool:batch_edit",
|
|
40
|
+
file: "batch_edit.md",
|
|
41
|
+
defaultOrder: 132,
|
|
42
|
+
renderDefault: () => guidanceText(BATCH_EDIT_GUIDANCE),
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
name: "tool:undo_last_edit",
|
|
46
|
+
file: "undo_last_edit.md",
|
|
47
|
+
defaultOrder: 133,
|
|
48
|
+
renderDefault: () => guidanceText(UNDO_GUIDANCE),
|
|
49
|
+
},
|
|
50
|
+
];
|
|
51
|
+
const SECTION_BY_NAME = new Map(GUIDANCE_SECTIONS.map((section) => [section.name, section]));
|
|
52
|
+
/** Render the compiled default text for one section. */
|
|
53
|
+
export function renderSectionDefault(name) {
|
|
54
|
+
const section = SECTION_BY_NAME.get(name);
|
|
55
|
+
if (!section)
|
|
56
|
+
throw new Error(`unknown guidance section: ${name}`);
|
|
57
|
+
return section.renderDefault();
|
|
58
|
+
}
|
|
59
|
+
function overrideCandidates(file, options) {
|
|
60
|
+
const candidates = [];
|
|
61
|
+
if (options.presetId !== undefined) {
|
|
62
|
+
candidates.push(join(options.homeDir, options.presetId, file));
|
|
63
|
+
}
|
|
64
|
+
return candidates;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Resolve one section's guidance: the first override file that exists wins,
|
|
68
|
+
* falling back to the compiled default. A missing or blank file (ENOENT, or
|
|
69
|
+
* whitespace-only with no fence) advances the chain; a malformed file resolves
|
|
70
|
+
* to the compiled default and reports itself; any other read error propagates.
|
|
71
|
+
*/
|
|
72
|
+
export async function resolveSection(name, options) {
|
|
73
|
+
const section = SECTION_BY_NAME.get(name);
|
|
74
|
+
if (!section)
|
|
75
|
+
throw new Error(`unknown guidance section: ${name}`);
|
|
76
|
+
for (const candidate of overrideCandidates(section.file, options)) {
|
|
77
|
+
const content = await readFile(candidate, "utf-8").catch((error) => {
|
|
78
|
+
if (errCode(error) === "ENOENT")
|
|
79
|
+
return undefined;
|
|
80
|
+
throw error;
|
|
81
|
+
});
|
|
82
|
+
if (content === undefined)
|
|
83
|
+
continue;
|
|
84
|
+
const parsed = parseSectionFile(content);
|
|
85
|
+
if (parsed.malformed) {
|
|
86
|
+
// A broken override must never reach the model. Resolve to the
|
|
87
|
+
// compiled default and report the file + parse reason to the caller.
|
|
88
|
+
return {
|
|
89
|
+
order: section.defaultOrder,
|
|
90
|
+
text: section.renderDefault(),
|
|
91
|
+
malformed: {
|
|
92
|
+
file: candidate,
|
|
93
|
+
reason: parsed.reason ?? "malformed override",
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
// Blank (no fence, whitespace-only) means "use the default": advance the
|
|
98
|
+
// fallback chain rather than render an empty section.
|
|
99
|
+
if (isBlankOverride(content))
|
|
100
|
+
continue;
|
|
101
|
+
return { order: parsed.order ?? section.defaultOrder, text: parsed.text };
|
|
102
|
+
}
|
|
103
|
+
return { order: section.defaultOrder, text: section.renderDefault() };
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Resolve all four sections for a preset. `presetId === undefined` skips the
|
|
107
|
+
* `<preset>/` layer and resolves straight to the compiled defaults.
|
|
108
|
+
*/
|
|
109
|
+
export async function composeSections(presetId, homeDir) {
|
|
110
|
+
return Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
|
|
111
|
+
const resolved = await resolveSection(section.name, {
|
|
112
|
+
presetId,
|
|
113
|
+
homeDir,
|
|
114
|
+
});
|
|
115
|
+
return {
|
|
116
|
+
name: section.name,
|
|
117
|
+
order: resolved.order,
|
|
118
|
+
text: resolved.text,
|
|
119
|
+
malformed: resolved.malformed,
|
|
120
|
+
};
|
|
121
|
+
}));
|
|
122
|
+
}
|