dsh-better-edit 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +317 -240
- package/README.zh.md +19 -11
- package/lib/constants.js +3 -1
- package/lib/contract.js +159 -63
- package/lib/drift.js +5 -98
- package/lib/dsh-context.js +2 -24
- package/lib/edit-engine.js +9 -8
- package/lib/edit-pipeline.js +3 -121
- package/lib/edit-response.js +16 -8
- package/lib/file-kind.js +6 -121
- package/lib/file-reader.js +4 -77
- package/lib/file-view.js +486 -0
- package/lib/guidance/index.js +8 -0
- package/lib/guidance/materialize.js +212 -0
- package/lib/guidance/parse.js +80 -0
- package/lib/guidance/resolve.js +116 -0
- package/lib/guidance.js +6 -388
- package/lib/hash-store.js +6 -4
- package/lib/hashline/alphabet.js +2 -6
- package/lib/hashline/anchor-pipeline.js +786 -0
- package/lib/hashline/apply.js +2 -223
- package/lib/hashline/hash-assign.js +255 -0
- package/lib/hashline/hash.js +67 -29
- package/lib/hashline/hasher.js +2 -23
- package/lib/hashline/index.js +9 -4
- package/lib/hashline/parse.js +2 -35
- package/lib/hashline/pure.js +2 -213
- package/lib/hashline/resolve.js +3 -361
- package/lib/hashline/served.js +2 -120
- package/lib/index.js +1 -3
- package/lib/mutation.js +266 -0
- package/lib/noop-guard.js +20 -0
- package/lib/preview-controller.js +65 -0
- package/lib/prompts.js +14 -20
- package/lib/read-and-serve.js +23 -23
- package/lib/read-render.js +3 -139
- package/lib/served-store.js +2 -216
- package/lib/session-view.js +332 -0
- package/lib/tool-batch-edit.js +9 -10
- package/lib/tool-edit.js +73 -129
- package/lib/tool-read.js +3 -5
- package/lib/tool-undo.js +16 -10
- package/lib/truncate.js +3 -95
- package/lib/types/constants.d.ts +2 -0
- package/lib/types/contract.d.ts +120 -15
- package/lib/types/drift.d.ts +5 -29
- package/lib/types/dsh-context.d.ts +2 -20
- package/lib/types/edit-engine.d.ts +2 -2
- package/lib/types/edit-pipeline.d.ts +3 -44
- package/lib/types/file-kind.d.ts +6 -18
- package/lib/types/file-reader.d.ts +4 -45
- package/lib/types/file-view.d.ts +139 -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/alphabet.d.ts +1 -5
- package/lib/types/hashline/anchor-pipeline.d.ts +127 -0
- package/lib/types/hashline/apply.d.ts +1 -22
- package/lib/types/hashline/hash-assign.d.ts +25 -0
- package/lib/types/hashline/hash.d.ts +8 -9
- package/lib/types/hashline/hasher.d.ts +1 -8
- package/lib/types/hashline/index.d.ts +12 -4
- package/lib/types/hashline/parse.d.ts +1 -7
- package/lib/types/hashline/pure.d.ts +1 -26
- package/lib/types/hashline/resolve.d.ts +1 -58
- package/lib/types/hashline/served.d.ts +1 -43
- package/lib/types/mutation.d.ts +131 -0
- package/lib/types/noop-guard.d.ts +29 -0
- package/lib/types/preview-controller.d.ts +33 -0
- package/lib/types/prompts.d.ts +9 -9
- package/lib/types/read-and-serve.d.ts +6 -5
- package/lib/types/read-render.d.ts +3 -18
- package/lib/types/served-store.d.ts +2 -81
- package/lib/types/session-view.d.ts +92 -0
- package/lib/types/tool-edit.d.ts +3 -14
- package/lib/types/truncate.d.ts +3 -29
- package/lib/types/validation.d.ts +6 -7
- package/lib/types/workspace.d.ts +2 -21
- package/lib/validation.js +6 -33
- package/lib/workspace.js +2 -27
- package/lib/write-hook.js +2 -2
- package/package.json +2 -2
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.1
|
|
26
|
+
<img src="https://img.shields.io/badge/version-0.3.1-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,14 @@
|
|
|
48
52
|
|
|
49
53
|
Hashline 用两个哈希代替旧文本——**编辑 token 减少 31%**(多行范围达 43%)——并对照模型所见内容校验每个范围:编辑要么落在你想要的行的位置,要么响亮失败并回传新锚点。锚点是内容地址,上方编辑后依然有效,连续编辑无需重读;上下文更精简,模型的注意力也保持在代码上,而不是复述上。
|
|
50
54
|
|
|
55
|
+
> [!TIP]
|
|
56
|
+
> **亮点——诚实且可衡量:**
|
|
57
|
+
> - **自愈而非静默。** 外部编辑永不被覆盖——过期范围被拒绝并以全新 `HASH│content` 重发重试;孤儿 served 条目无需全量重读即可自愈(ADR-0008)。Fail-closed,而非自动合并。
|
|
58
|
+
> - **格式化容忍。** ASCII 空白不敏感锚点在 `prettier`/`black`/`eslint --fix` 之间存活(`formatOnSave`、监听、CI)。仅限 linter 场景——字符串内的空白不区分(ADR-0005)。
|
|
59
|
+
> - **链式与批量,无重读仪式。** 未受影响行的锚点保持有效;diff/回显/拒绝行即视为已提供。`edit` 最多 32 个同文件编辑原子执行(`[E_BATCH_ABORT]`),相比 `str_replace` 信封约 -40%。
|
|
60
|
+
> - **读守卫。** 从未展示过的行永不被编辑——`[E_RANGE_UNSERVED]`/`[E_RANGE_UNVERIFIED]`/`[E_STALE_ANCHOR]` 在写入前拒绝,随后 `reject-and-serve`。
|
|
61
|
+
> - **更少往返。** 实测:同样外部漂移重构,OMP 封装需 6 次调用,hashline 仅 3 次;信封 vs `str_replace` 的节省是稳定值—— upstream 电池可复现(算法相同)。
|
|
62
|
+
|
|
51
63
|
不适用于单行小改动(接近持平)或新建文件(用 `write`)。它的价值在长会话与结构性编辑中体现——任何不允许改错行的场景。
|
|
52
64
|
|
|
53
65
|
## 快速开始
|
|
@@ -85,9 +97,7 @@ kQm│}
|
|
|
85
97
|
```json
|
|
86
98
|
{
|
|
87
99
|
"path": "src/main.ts",
|
|
88
|
-
"
|
|
89
|
-
"remove_to": "szJ",
|
|
90
|
-
"replacement_text": " console.log('hi');"
|
|
100
|
+
"edits": [["szJ", "szJ", " console.log('hi');"]]
|
|
91
101
|
}
|
|
92
102
|
```
|
|
93
103
|
|
|
@@ -101,7 +111,7 @@ kQm│}
|
|
|
101
111
|
|
|
102
112
|
## 按 preset 配置指引
|
|
103
113
|
|
|
104
|
-
`tool:read` / `tool:edit` / `tool:
|
|
114
|
+
`tool:read` / `tool:edit` / `tool:undo_last_edit` 三个提示词片段的指引是
|
|
105
115
|
纯 Markdown 文件,可以按 agent preset 覆盖。覆盖文件位于插件的共享主目录——绝不放在工作区存储中:
|
|
106
116
|
|
|
107
117
|
```
|
|
@@ -114,10 +124,9 @@ $DSH_HOME/plugins/dsh-better-edit/<preset>/<section>.md
|
|
|
114
124
|
| --- | --- | --- |
|
|
115
125
|
| `read.md` | `tool:read` | 130 |
|
|
116
126
|
| `edit.md` | `tool:edit` | 131 |
|
|
117
|
-
| `batch_edit.md` | `tool:batch_edit` | 132 |
|
|
118
127
|
| `undo_last_edit.md` | `tool:undo_last_edit` | 133 |
|
|
119
128
|
|
|
120
|
-
|
|
129
|
+
首次启动时插件会为三个随附 preset——`standard/`、`code/`、`minimal/`、`cordis/`——各自写入编译内置的
|
|
121
130
|
可编辑指引文件(含 `order` front-matter),让每个 preset 的指引一开始就可编辑,而不是空白。插件主目录
|
|
122
131
|
根的 `README.md` 说明整套机制。文件只在首次写入时生成、之后绝不被覆盖,因此你的修改会保留——唯一的例外是重置(见下文 *重置 / 恢复默认*)。preset 目录
|
|
123
132
|
里可以只放你想覆盖的片段文件,其余自动回退到编译内置默认值。
|
|
@@ -199,7 +208,7 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
|
|
|
199
208
|
| 重复/相同文本 | 每行哈希唯一(冲突已消解);歧义 → `[E_AMBIGUOUS_ANCHOR]` | 基于位置,重复不会混淆——但位置本身未被校验 |
|
|
200
209
|
| 从未展示给模型的行 | `[E_RANGE_UNSERVED]`——硬拒绝并回传新锚点 | 未展示的 hunk 被拒绝——同样依赖模型知道自己看过什么 |
|
|
201
210
|
| 表达式中间 / 错误的块节点 | 无关——任何已校验的行范围都合法 | 语法规则 + `PUT N*:` 节点选择;点错(锚在 `def` 会让装饰器变成孤儿)会悄悄落错;无语法检查 |
|
|
202
|
-
| 多编辑批量中途失败 | `
|
|
211
|
+
| 多编辑批量中途失败 | `edit` 多条目——原子、全有或全无;失败项以新锚点回显 | 多段补丁先预检——同样原子 |
|
|
203
212
|
|
|
204
213
|
> oh-my-pi 42–53% 的负载节省来自更轻的线格式;上表才是该格式反过来要求模型记在脑中的东西——重新编号、追标签、选节点——而这恰恰是最容易出错的组件(替换式编辑的补丁失败率 46–51%)。本插件 31% 的代价买来的是一个“错编辑落不了地、任何拒绝都不需要重读”的契约。
|
|
205
214
|
|
|
@@ -238,8 +247,7 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
|
|
|
238
247
|
| 工具 | 作用 |
|
|
239
248
|
| ------ | ------ |
|
|
240
249
|
| `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 }, …] }`。全有或全无;失败项的范围会以新锚点的形式回显。 |
|
|
250
|
+
| `edit` | 对象根负载 `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], …] }`;`path` 可为 `null` 以通过锚点推断。单个条目编辑一个范围;多条目对同一文件原子批量(最多 32)。对每个包含范围内的每一行校验,reject-and-serve 返回新锚点。 |
|
|
243
251
|
| `undo_last_edit` | `{ path }` 撤销该文件上一次 hashline 编辑,仅当文件仍与存储的编辑后内容一致时生效;重启后依然有效。 |
|
|
244
252
|
|
|
245
253
|
### 错误码
|
package/lib/constants.js
CHANGED
|
@@ -4,7 +4,9 @@ export const MAX_BYTES = 100 * 1024 * 1024;
|
|
|
4
4
|
export const MAX_READ_LINE_BYTES = 200 * 1024;
|
|
5
5
|
export const HASH_STORE_BUSY_TIMEOUT = 1000;
|
|
6
6
|
export const HASH_STORE_VERSION = 6;
|
|
7
|
-
export const
|
|
7
|
+
export const EDITS_MAX_ITEMS = 32;
|
|
8
|
+
/** @deprecated batch_edit seam removed (ADR-0003) — use EDITS_MAX_ITEMS */
|
|
9
|
+
export const BATCH_EDIT_MAX_ITEMS = EDITS_MAX_ITEMS;
|
|
8
10
|
export const SERVED_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
9
11
|
export const SERVED_ECHO_CAP = 150;
|
|
10
12
|
export const NOOP_LOOP_THRESHOLD = 3;
|
package/lib/contract.js
CHANGED
|
@@ -1,95 +1,191 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* One module owns the request shapes for the hashline tools — edit,
|
|
3
|
-
*
|
|
3
|
+
* read, undo_last_edit — plus their validation. Field sets are
|
|
4
4
|
* declared once here; every tool validates through these asserts, and the
|
|
5
5
|
* [E_BAD_SHAPE] vocabulary is shared instead of re-implemented per tool.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* decoupled from the tool-layer request contract so the hashline module does
|
|
10
|
-
* not depend on this one.
|
|
7
|
+
* Contract now mirrors upstream ADR-0007: {path: string|null, edits: [[remove_from,remove_to,replacement_text],...]} tuple payload,
|
|
8
|
+
* single-file, atomic. batch_edit is removed.
|
|
11
9
|
* @module dsh-better-edit/contract
|
|
12
10
|
*/
|
|
13
|
-
import {
|
|
11
|
+
import { EDITS_MAX_ITEMS } from "./constants.js";
|
|
14
12
|
import { isRec, normalizeFilePath, rejectUnknownFields } from "./utils.js";
|
|
15
|
-
// ----
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
]
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
"
|
|
34
|
-
|
|
13
|
+
// ---- normalized marker -----------------------------------------------------
|
|
14
|
+
export const normalizedEdit = Symbol("normalizedEdit");
|
|
15
|
+
export function isNormalizedEdit(input) {
|
|
16
|
+
return isRec(input) && input[normalizedEdit] === true;
|
|
17
|
+
}
|
|
18
|
+
export function itemFromTuple(value) {
|
|
19
|
+
if (!Array.isArray(value) || value.length !== 3)
|
|
20
|
+
return undefined;
|
|
21
|
+
const [remove_from, remove_to, replacement_text] = value;
|
|
22
|
+
if (typeof remove_from !== "string" || typeof remove_to !== "string" || typeof replacement_text !== "string")
|
|
23
|
+
return undefined;
|
|
24
|
+
return { remove_from, remove_to, replacement_text };
|
|
25
|
+
}
|
|
26
|
+
export function editRequestFrom(input) {
|
|
27
|
+
if (!isRec(input) || !("path" in input) || !("edits" in input))
|
|
28
|
+
return undefined;
|
|
29
|
+
const rec = input;
|
|
30
|
+
// handle file_path alias before checking
|
|
31
|
+
if (typeof rec.path !== "string" && typeof rec.file_path === "string") {
|
|
32
|
+
// alias will be normalized by normalizeFilePath before editRequestFrom in normReq path,
|
|
33
|
+
// but handle here for direct calls
|
|
34
|
+
}
|
|
35
|
+
const { path, edits } = rec;
|
|
36
|
+
if (path !== null && (typeof path !== "string" || path.length === 0))
|
|
37
|
+
return undefined;
|
|
38
|
+
if (!Array.isArray(edits) || edits.length === 0)
|
|
39
|
+
return undefined;
|
|
40
|
+
const items = [];
|
|
41
|
+
for (const item of edits) {
|
|
42
|
+
const normalized = itemFromTuple(item);
|
|
43
|
+
if (!normalized)
|
|
44
|
+
return undefined;
|
|
45
|
+
items.push(normalized);
|
|
46
|
+
}
|
|
47
|
+
return { path: path, edits: items };
|
|
48
|
+
}
|
|
49
|
+
export const EDIT_TUPLE_HINT = "Edit must be called with exactly one payload. Use the canonical payload " +
|
|
50
|
+
'{"path": path, "edits": [[remove_from, remove_to, replacement_text], ...]}: ' +
|
|
51
|
+
"path is a non-empty string (or null to infer from anchors), each item is a " +
|
|
52
|
+
"fixed 3-position array of two inclusive bare-3-char anchors and the full " +
|
|
53
|
+
"replacement (an empty string deletes the range).";
|
|
54
|
+
function describeReceived(input) {
|
|
55
|
+
if (input === undefined)
|
|
56
|
+
return "Received no arguments.";
|
|
57
|
+
if (input === null)
|
|
58
|
+
return "Received null.";
|
|
59
|
+
if (typeof input === "string")
|
|
60
|
+
return `Received a bare string (${JSON.stringify(input)}).`;
|
|
61
|
+
const json = JSON.stringify(input);
|
|
62
|
+
const preview = typeof json === "string" && json.length > 160 ? `${json.slice(0, 160)}…` : json;
|
|
63
|
+
return `Received: ${preview}`;
|
|
64
|
+
}
|
|
65
|
+
// ---- filed sets (declared once) ---------------------------------------------
|
|
66
|
+
const EDIT_KS = new Set(["path", "edits", "sandbox_permissions", "justification"]);
|
|
35
67
|
const READ_KS = new Set(["path", "offset", "limit"]);
|
|
36
|
-
// ----
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
68
|
+
// ---- normalization -----------------------------------------------------------
|
|
69
|
+
/**
|
|
70
|
+
* Normalize `file_path` → `path` alias on the request record and tuple edits → objects.
|
|
71
|
+
* Returns the input unchanged when not a record; otherwise returns a shallow copy with
|
|
72
|
+
* the alias applied so callers never mutate the original `args` object.
|
|
73
|
+
*/
|
|
74
|
+
export function normalizeRequest(input) {
|
|
75
|
+
if (!isRec(input))
|
|
76
|
+
return input;
|
|
77
|
+
const record = { ...input };
|
|
78
|
+
normalizeFilePath(record);
|
|
79
|
+
// also normalize file_path inside edits if they were objects (legacy) — not needed for tuple but harmless
|
|
80
|
+
if (Array.isArray(record.edits)) {
|
|
81
|
+
// keep tuple as-is; editRequestFrom will handle
|
|
40
82
|
}
|
|
41
|
-
|
|
42
|
-
if (
|
|
43
|
-
|
|
83
|
+
const valid = editRequestFrom(record);
|
|
84
|
+
if (!valid)
|
|
85
|
+
return record;
|
|
86
|
+
const normalized = { path: valid.path, edits: valid.edits };
|
|
87
|
+
// preserve non-standard fields like sandbox_permissions/justification for later reject check? but we strip to valid fields and re-add them?
|
|
88
|
+
for (const k of ["sandbox_permissions", "justification"]) {
|
|
89
|
+
if (k in record)
|
|
90
|
+
normalized[k] = record[k];
|
|
44
91
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
92
|
+
Object.defineProperty(normalized, normalizedEdit, { value: true, enumerable: false });
|
|
93
|
+
return normalized;
|
|
94
|
+
}
|
|
95
|
+
/** @deprecated use normalizeRequest — kept as alias for migration */
|
|
96
|
+
export const normReq = normalizeRequest;
|
|
97
|
+
export function prepareEditArguments(args) {
|
|
98
|
+
const valid = editRequestFrom(args);
|
|
99
|
+
if (valid) {
|
|
100
|
+
return { path: valid.path, edits: args.edits };
|
|
49
101
|
}
|
|
102
|
+
throw new Error(`[E_BAD_SHAPE] ${EDIT_TUPLE_HINT} ${describeReceived(args)}`);
|
|
50
103
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
104
|
+
// ---- assertions ---------------------------------------------------------------
|
|
105
|
+
export function assertEditRequest(request) {
|
|
106
|
+
if (!isNormalizedEdit(request)) {
|
|
107
|
+
throw new Error("[E_BAD_SHAPE] Edit request must be exactly { path, edits: [[remove_from, remove_to, replacement_text], ...] }.");
|
|
54
108
|
}
|
|
55
|
-
rejectUnknownFields(request,
|
|
56
|
-
|
|
57
|
-
|
|
109
|
+
rejectUnknownFields(request, EDIT_KS, "Edit request");
|
|
110
|
+
const req = request;
|
|
111
|
+
if (req.path !== null && (typeof req.path !== "string" || req.path.length === 0)) {
|
|
112
|
+
throw new Error('[E_BAD_SHAPE] Edit request path must be a non-empty string or null.');
|
|
58
113
|
}
|
|
59
|
-
if (
|
|
60
|
-
throw new Error(
|
|
114
|
+
if (!Array.isArray(req.edits) || req.edits.length === 0) {
|
|
115
|
+
throw new Error('[E_BAD_SHAPE] Edit request requires a non-empty "edits" array.');
|
|
61
116
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
if (typeof item.remove_from !== "string" ||
|
|
68
|
-
|
|
69
|
-
typeof item.replacement_text !== "string") {
|
|
70
|
-
throw new Error(`[E_BAD_SHAPE] edits[${index}] requires "remove_from", "remove_to", and "replacement_text" strings.`);
|
|
71
|
-
}
|
|
72
|
-
if (item.path !== undefined &&
|
|
73
|
-
(typeof item.path !== "string" || item.path.length === 0)) {
|
|
74
|
-
throw new Error(`[E_BAD_SHAPE] edits[${index}].path must be a non-empty string.`);
|
|
117
|
+
if (req.edits.length > EDITS_MAX_ITEMS) {
|
|
118
|
+
throw new Error(`[E_BAD_SHAPE] edit accepts at most ${EDITS_MAX_ITEMS} edits; got ${req.edits.length}. Split the batch.`);
|
|
119
|
+
}
|
|
120
|
+
for (let index = 0; index < req.edits.length; index++) {
|
|
121
|
+
const item = req.edits[index];
|
|
122
|
+
if (typeof item.remove_from !== "string" || typeof item.remove_to !== "string" || typeof item.replacement_text !== "string") {
|
|
123
|
+
throw new Error(`[E_BAD_SHAPE] Edit request edits[${index}] must be a three-position array [remove_from, remove_to, replacement_text].`);
|
|
75
124
|
}
|
|
76
|
-
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
// legacy — now always fails with new shape message (batch_edit removed)
|
|
128
|
+
export function assertBatchEditRequest(_request) {
|
|
129
|
+
throw new Error("[E_BAD_SHAPE] batch_edit has been removed. Use edit with { path, edits: [[remove_from, remove_to, replacement_text], ...] }.");
|
|
77
130
|
}
|
|
78
131
|
export function assertReadRequest(request) {
|
|
79
|
-
if (!isRec(request))
|
|
132
|
+
if (!isRec(request))
|
|
80
133
|
throw new Error("[E_BAD_SHAPE] Read request must be an object.");
|
|
81
|
-
}
|
|
82
134
|
rejectUnknownFields(request, READ_KS, "Read request");
|
|
83
135
|
if (typeof request.path !== "string" || request.path.length === 0) {
|
|
84
136
|
throw new Error('[E_BAD_SHAPE] Read request requires a non-empty "path" string.');
|
|
85
137
|
}
|
|
86
138
|
}
|
|
87
139
|
export function assertUndoRequest(request) {
|
|
88
|
-
if (!isRec(request))
|
|
140
|
+
if (!isRec(request))
|
|
89
141
|
throw new Error("[E_BAD_SHAPE] undo_last_edit request must be an object.");
|
|
90
|
-
}
|
|
91
142
|
normalizeFilePath(request);
|
|
92
143
|
if (typeof request.path !== "string" || request.path.length === 0) {
|
|
93
144
|
throw new Error('[E_BAD_SHAPE] undo_last_edit request requires a non-empty "path" string.');
|
|
94
145
|
}
|
|
95
146
|
}
|
|
147
|
+
// ---- shared JSON Schema literals (co-located with field sets) ---------------
|
|
148
|
+
export const replacementTextSchema = {
|
|
149
|
+
type: 'string',
|
|
150
|
+
description: 'Complete replacement for the range; use "" to delete',
|
|
151
|
+
};
|
|
152
|
+
export const removeFromSchema = {
|
|
153
|
+
type: 'string',
|
|
154
|
+
description: "First line to remove (inclusive)",
|
|
155
|
+
};
|
|
156
|
+
export const removeToSchema = {
|
|
157
|
+
type: 'string',
|
|
158
|
+
description: "Last line to remove (inclusive)",
|
|
159
|
+
};
|
|
160
|
+
export const pathSchema = {
|
|
161
|
+
type: 'string',
|
|
162
|
+
description: "File path; null infers it from anchors",
|
|
163
|
+
};
|
|
164
|
+
export const editPathSchema = {
|
|
165
|
+
anyOf: [
|
|
166
|
+
{ type: 'string', minLength: 1, description: "File path; null infers it from anchors" },
|
|
167
|
+
{ type: 'null', description: "null infers path from anchors" },
|
|
168
|
+
],
|
|
169
|
+
};
|
|
170
|
+
export const editTupleSchema = {
|
|
171
|
+
type: 'array',
|
|
172
|
+
prefixItems: [removeFromSchema, removeToSchema, replacementTextSchema],
|
|
173
|
+
minItems: 3,
|
|
174
|
+
maxItems: 3,
|
|
175
|
+
description: "[remove_from, remove_to, replacement_text]",
|
|
176
|
+
};
|
|
177
|
+
export const editToolSchema = {
|
|
178
|
+
type: 'object',
|
|
179
|
+
additionalProperties: false,
|
|
180
|
+
required: ["path", "edits"],
|
|
181
|
+
properties: {
|
|
182
|
+
path: editPathSchema,
|
|
183
|
+
edits: {
|
|
184
|
+
type: 'array',
|
|
185
|
+
description: "Ordered list of edit tuples",
|
|
186
|
+
minItems: 1,
|
|
187
|
+
maxItems: EDITS_MAX_ITEMS,
|
|
188
|
+
items: editTupleSchema,
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
};
|
package/lib/drift.js
CHANGED
|
@@ -1,98 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
export
|
|
6
|
-
const { served, resultHashes, resultLines, range, reported, cap = SERVED_ECHO_CAP, } = input;
|
|
7
|
-
const resultHashSet = new Set(resultHashes);
|
|
8
|
-
const currentPosOfHash = new Map();
|
|
9
|
-
for (let i = 0; i < resultHashes.length; i++) {
|
|
10
|
-
currentPosOfHash.set(resultHashes[i], i);
|
|
11
|
-
}
|
|
12
|
-
const startPositions = servedPositionsOf(served, range.startHash);
|
|
13
|
-
const endPositions = servedPositionsOf(served, range.endHash);
|
|
14
|
-
let servedStartIdx;
|
|
15
|
-
let servedEndIdx;
|
|
16
|
-
if (startPositions.length === 1 && endPositions.length === 1) {
|
|
17
|
-
servedStartIdx = startPositions[0];
|
|
18
|
-
servedEndIdx = endPositions[0];
|
|
19
|
-
}
|
|
20
|
-
else {
|
|
21
|
-
servedStartIdx = range.startLine - 1;
|
|
22
|
-
servedEndIdx = range.endLine - 1;
|
|
23
|
-
}
|
|
24
|
-
const rangeFrom = Math.min(servedStartIdx, servedEndIdx);
|
|
25
|
-
const rangeTo = Math.max(servedStartIdx, servedEndIdx);
|
|
26
|
-
let total = 0;
|
|
27
|
-
let unshown = 0;
|
|
28
|
-
let anyNotReported = false;
|
|
29
|
-
const driftedPositions = [];
|
|
30
|
-
for (let p = 0; p < served.length; p++) {
|
|
31
|
-
const servedHash = served[p];
|
|
32
|
-
if (servedHash === null)
|
|
33
|
-
continue;
|
|
34
|
-
if (p >= rangeFrom && p <= rangeTo)
|
|
35
|
-
continue;
|
|
36
|
-
if (resultHashSet.has(servedHash))
|
|
37
|
-
continue;
|
|
38
|
-
total++;
|
|
39
|
-
if (!reported.has(servedHash))
|
|
40
|
-
anyNotReported = true;
|
|
41
|
-
const currentPos = currentPositionOfDrifted(served, currentPosOfHash, resultHashSet, p, range.delta);
|
|
42
|
-
if (currentPos >= 0 &&
|
|
43
|
-
currentPos < resultHashes.length &&
|
|
44
|
-
currentPos < resultLines.length) {
|
|
45
|
-
driftedPositions.push(currentPos);
|
|
46
|
-
}
|
|
47
|
-
else {
|
|
48
|
-
unshown++;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
if (total === 0)
|
|
52
|
-
return undefined;
|
|
53
|
-
const countLabel = `${total} line(s)`;
|
|
54
|
-
if (!anyNotReported) {
|
|
55
|
-
return {
|
|
56
|
-
text: `${DRIFT_NOTICE_HEADING} ${countLabel} outside the edited range drifted and were already reported — call read to refresh.`,
|
|
57
|
-
rows: [],
|
|
58
|
-
total,
|
|
59
|
-
allAlreadyReported: true,
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
const driftedSet = new Set(driftedPositions);
|
|
63
|
-
const windowSet = new Set();
|
|
64
|
-
for (const pos of driftedPositions) {
|
|
65
|
-
for (const w of [pos - 1, pos, pos + 1]) {
|
|
66
|
-
if (w >= 0 && w < resultLines.length)
|
|
67
|
-
windowSet.add(w);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
const windowPositions = [...windowSet].sort((a, b) => a - b);
|
|
71
|
-
const shownPositions = windowPositions.slice(0, cap);
|
|
72
|
-
unshown += windowPositions.length - shownPositions.length;
|
|
73
|
-
const rows = shownPositions.map((position) => ({
|
|
74
|
-
position,
|
|
75
|
-
hash: resultHashes[position],
|
|
76
|
-
content: resultLines[position],
|
|
77
|
-
drifted: driftedSet.has(position),
|
|
78
|
-
}));
|
|
79
|
-
const rowsText = fmtServedRows(rows, resultLines);
|
|
80
|
-
const moreText = unshown > 0
|
|
81
|
-
? `\n[... ${unshown} more line(s) — call read to see them]`
|
|
82
|
-
: "";
|
|
83
|
-
return {
|
|
84
|
-
text: `${DRIFT_NOTICE_HEADING} ${countLabel} outside the edited range drifted. Current content around the drift:\n${rowsText}${moreText}`,
|
|
85
|
-
rows,
|
|
86
|
-
total,
|
|
87
|
-
allAlreadyReported: false,
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
export async function scanDrift(input) {
|
|
91
|
-
const reported = await driftReported(input.sessionKey, input.path);
|
|
92
|
-
const result = computeDrift({ ...input, reported });
|
|
93
|
-
if (!result || result.allAlreadyReported)
|
|
94
|
-
return result?.text;
|
|
95
|
-
await recordServed(input.sessionKey, input.path, result.rows.map((row) => ({ position: row.position, hash: row.hash })), input.resultLines.length);
|
|
96
|
-
await markDriftReported(input.sessionKey, input.path, result.rows.filter((row) => row.drifted).map((row) => row.hash));
|
|
97
|
-
return result.text;
|
|
98
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* @deprecated — private to SessionView seam. Use `from "./session-view.js"` instead.
|
|
3
|
+
* @module dsh-better-edit/drift
|
|
4
|
+
*/
|
|
5
|
+
export * from "./session-view.js";
|
package/lib/dsh-context.js
CHANGED
|
@@ -1,27 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* served-state session key derived from the dsh {@link ToolExecution}.
|
|
2
|
+
* @deprecated — private to SessionView seam. Use `from "./session-view.js"` instead.
|
|
4
3
|
* @module dsh-better-edit/dsh-context
|
|
5
4
|
*/
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* The workspace directory a model-facing filesystem tool resolves relative
|
|
9
|
-
* paths against: the calling agent's per-session cwd (each session's tools act
|
|
10
|
-
* on ITS workspace), falling back to the process cwd for non-agent callers.
|
|
11
|
-
* Mirrors how `dsh-tool-bash` defaults a bash `workdir` to the session cwd.
|
|
12
|
-
* @param exec - the tool-execution context; only its optional `agent` is read.
|
|
13
|
-
* @returns the session cwd, or the process cwd when no agent applies.
|
|
14
|
-
*/
|
|
15
|
-
export function execCwd(exec) {
|
|
16
|
-
return exec.agent?.session.header.cwd ?? process.cwd();
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
19
|
-
* The served-state session key for one execution: the live session id. A
|
|
20
|
-
* stable key per session keeps served rows (what the model was shown) and
|
|
21
|
-
* undo history correctly scoped — never shared across sessions.
|
|
22
|
-
* @param exec - the tool-execution context.
|
|
23
|
-
* @returns the session key.
|
|
24
|
-
*/
|
|
25
|
-
export function execSessionKey(exec) {
|
|
26
|
-
return sessionKeyFor(exec.agent?.session.id);
|
|
27
|
-
}
|
|
5
|
+
export * from "./session-view.js";
|
package/lib/edit-engine.js
CHANGED
|
@@ -12,10 +12,11 @@
|
|
|
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 } from "./hashline/hash.js";
|
|
18
|
+
import { MAX_HASH_LINES } from "./hashline/hash-assign.js";
|
|
19
|
+
import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "./hashline/anchor-pipeline.js";
|
|
19
20
|
import { findSnapshotPathsByHashes } from "./hash-store.js";
|
|
20
21
|
import { saveUndo } from "./undo-edit.js";
|
|
21
22
|
import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
|
|
@@ -171,10 +172,10 @@ export async function enforceNoopLoop(opts) {
|
|
|
171
172
|
const echoRows = buildRangeEcho(opts.range.startLine, opts.range.endLine, originalHashes);
|
|
172
173
|
const echo = fmtServedRows(echoRows, splitLines(opts.originalNormalized));
|
|
173
174
|
await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
174
|
-
throw new Error(`[E_NOOP_LOOP]
|
|
175
|
+
throw new Error(`[E_NOOP_LOOP] identical edit (${removeFrom} → ${removeTo} in ${displayPath}) submitted ${count}×, no changes each time. Range already contains this text; resend will reject. Current range:\n${echo}`);
|
|
175
176
|
}
|
|
176
177
|
if (count === 2) {
|
|
177
|
-
return `[E_NOOP_LOOP] Notice:
|
|
178
|
+
return `[E_NOOP_LOOP] Notice: identical edit (${removeFrom} → ${removeTo} in ${displayPath}) no-op'd twice; range already has this text. Resend will reject.`;
|
|
178
179
|
}
|
|
179
180
|
return undefined;
|
|
180
181
|
}
|
|
@@ -184,13 +185,13 @@ export async function enforceNoopLoop(opts) {
|
|
|
184
185
|
if (echoRows) {
|
|
185
186
|
await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
186
187
|
}
|
|
187
|
-
throw new Error(`[E_NOOP_LOOP] edits[${index}] (${displayPath}):
|
|
188
|
+
throw new Error(`[E_NOOP_LOOP] edits[${index}] (${displayPath}): identical edit (${removeFrom} → ${removeTo}) submitted ${count}×, no changes each time. Range already has this text; resend will reject the batch.` +
|
|
188
189
|
(echoRows
|
|
189
190
|
? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}`
|
|
190
191
|
: ""));
|
|
191
192
|
}
|
|
192
193
|
if (count === 2) {
|
|
193
|
-
return `[E_NOOP_LOOP] Notice: edits[${index}] (${displayPath}) —
|
|
194
|
+
return `[E_NOOP_LOOP] Notice: edits[${index}] (${displayPath}) — identical edit no-op'd twice; range already has this text. Resend will reject the batch.`;
|
|
194
195
|
}
|
|
195
196
|
return undefined;
|
|
196
197
|
}
|