dsh-better-edit 0.4.0 → 0.5.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 +24 -0
- package/README.md +7 -2
- package/README.zh.md +4 -1
- package/lib/edit-response.js +14 -11
- package/lib/fs-write.js +15 -6
- package/lib/hash-store.js +2 -1
- package/lib/hashline/anchor-pipeline.js +278 -43
- package/lib/hashline/hash-assign.js +18 -3
- package/lib/hashline/index.js +1 -1
- package/lib/index.js +2 -2
- package/lib/prompts.js +14 -11
- package/lib/store-tenancy.js +12 -3
- package/lib/types/hashline/anchor-pipeline.d.ts +7 -0
- package/lib/types/hashline/hash-assign.d.ts +2 -0
- package/lib/types/hashline/index.d.ts +1 -1
- package/lib/types/index.d.ts +2 -2
- package/lib/types/write-hook.d.ts +26 -8
- package/lib/write-hook.js +72 -11
- package/package.json +17 -2
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,30 @@ Entries link to the originating spec issue in [pi-hashline-edit-lsz](https://git
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.5.0] - 2026-08-29
|
|
10
|
+
|
|
11
|
+
### Features
|
|
12
|
+
|
|
13
|
+
- **edit:** route drift signals to user-facing details (pi-better-edit@6ec52f2)
|
|
14
|
+
- scaffold verify→release with biome+coverage 80%
|
|
15
|
+
|
|
16
|
+
### Bug Fixes
|
|
17
|
+
|
|
18
|
+
- **ci:** lower coverage threshold to 75 and add SAFETY for hash-store cast
|
|
19
|
+
- **tests:** align drift expectations with user-facing routing (6ec52f2)
|
|
20
|
+
- **hashline:** add E_EDIT_HASH_ECHO guard for served echo (pi-better-edit@65b8eb1)
|
|
21
|
+
- clarify HASH vs content without served
|
|
22
|
+
- **edit:** clarify HASH vs HASH│content and downgrade bare prefix warnings (pi-better-edit@a837e9d)
|
|
23
|
+
- **fs-write:** log stale-temp and sync failures (pi-better-edit@671c66d)
|
|
24
|
+
- **hashline:** heal multi-line staleness and stable anchoring (f94fb88)
|
|
25
|
+
- **git:** wire pre-push hook via husky path
|
|
26
|
+
|
|
27
|
+
## [0.4.1] - 2026-08-27
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
|
|
31
|
+
- Refuse a built-in `write` before dispatch when a candidate line starts with the exact hashline anchor served for the same session, canonical path, and line. This prevents copied `HASH│` preview chains from entering Markdown while leaving the file byte-identical; unrelated hash-like text is not generically stripped (#29).
|
|
32
|
+
|
|
9
33
|
## [0.4.0] - 2026-08-24
|
|
10
34
|
|
|
11
35
|
### Added
|
package/README.md
CHANGED
|
@@ -255,6 +255,8 @@ Both engines preserved the external change and produced the expected final file
|
|
|
255
255
|
| `edit` | An object-root payload `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], …] }`; the path may be `null` for anchor-based inference. A single item edits one range; several items batch same-file edits atomically (up to 32). Verifies every line of each inclusive range and reject-and-serve returns fresh anchors. |
|
|
256
256
|
| `undo_last_edit` | `{ path }` restores the most recent successful edit with its original content, BOM, line endings, and anchors; persisted across restarts. |
|
|
257
257
|
|
|
258
|
+
The built-in `write` remains available for full-file replacement. Before it runs, the plugin refuses only a candidate line that begins with the exact `HASH│` anchor served for the same session, canonical path, and line; the file stays unchanged and the response asks for a retry with file content only. It never generically strips hash-like text.
|
|
259
|
+
|
|
258
260
|
`edit` accepts `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], …] }`. The path
|
|
259
261
|
position is a non-empty string or `null` for unique anchor-based inference. Each range is inclusive,
|
|
260
262
|
and an empty replacement deletes the range. All items are checked before file I/O and applied
|
|
@@ -270,12 +272,14 @@ atomically to that one file — one item per call is the norm, several same-file
|
|
|
270
272
|
| `[E_AMBIGUOUS_ANCHOR]` | An anchor matches multiple lines; call `read` for fresh anchors. |
|
|
271
273
|
| `[E_INVALID_PATCH]` | A `replacement_text` line is a diff-preview row (`+HASH│`, `-HASH│`, `- │`). The marker is stripped automatically with a warning. |
|
|
272
274
|
| `[E_BARE_HASH_PREFIX]` | A `replacement_text` line starts with a hash-like `HASH│` prefix. The prefix is stripped automatically with a warning. |
|
|
275
|
+
| `[E_EDIT_HASH_ECHO]` | A `replacement_text` line begins with the exact `HASH│` anchor served for the same session, path, and range-relative line (`E1`). The edit is refused; remove the copied anchors and retry. Nothing was written. |
|
|
273
276
|
| `[E_BAD_OP]` | Range start line is after range end line. The pair is swapped automatically with a warning. |
|
|
274
277
|
| `[E_WOULD_EMPTY]` | An edit would empty a non-empty file; use `write` instead. |
|
|
275
278
|
| `[E_NOT_FOUND]` | The path does not exist. |
|
|
276
279
|
| `[E_ACCESS]` | The path is not readable or writable. |
|
|
277
280
|
| `[E_NOT_TEXT]` | The path is a directory, binary file, image, or UTF-16/UTF-32 encoded text; hashline editing only supports text files. |
|
|
278
281
|
| `[E_NOT_OBSERVED]` | The file has not been observed in this session (read-before-write); call `read` first. |
|
|
282
|
+
| `[E_WRITE_HASH_ECHO]` | A built-in `write` candidate copied a `HASH│` preview anchor served for the same session, path, and line. The write is refused before dispatch; remove the entire copied anchor chain and retry. |
|
|
279
283
|
| `[E_UNDO_STALE]` | `undo_last_edit` refused: the file was modified or deleted after the last edit. |
|
|
280
284
|
| `[E_UNDO_UNAVAILABLE]` | Undo history could not be persisted to the hash store; the `edit` was refused and the file was left unchanged. |
|
|
281
285
|
| `[E_FILE_TOO_LARGE]` | The file exceeds the 238,328-line hashline limit. |
|
|
@@ -414,8 +418,9 @@ registration cannot replace them. This plugin:
|
|
|
414
418
|
2. On `agent/session-start`, registers the hashline tools **and** the `tool:read` / `tool:edit`
|
|
415
419
|
prompt sections on the agent's own scope layer — they shadow the preset's built-ins for that
|
|
416
420
|
agent and unwind automatically when the agent is disposed.
|
|
417
|
-
3. Leaves the built-in `write` in place
|
|
418
|
-
|
|
421
|
+
3. Leaves the built-in `write` in place: a scoped `tools/pre-execute` listener rejects an exact
|
|
422
|
+
same-session/path/line served-anchor echo before dispatch, and `tools/post-execute` appends the
|
|
423
|
+
hashline auto-read to successful results.
|
|
419
424
|
|
|
420
425
|
## Store
|
|
421
426
|
|
package/README.zh.md
CHANGED
|
@@ -267,6 +267,8 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
|
|
|
267
267
|
| `edit` | 对象根负载 `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], …] }`;`path` 可为 `null` 以通过锚点推断。单个条目编辑一个范围;多条目对同一文件原子批量(最多 32)。对每个包含范围内的每一行校验,reject-and-serve 返回新锚点。 |
|
|
268
268
|
| `undo_last_edit` | `{ path }` 撤销该文件上一次 hashline 编辑,仅当文件仍与存储的编辑后内容一致时生效;重启后依然有效。 |
|
|
269
269
|
|
|
270
|
+
内置 `write` 仍用于整文件替换。执行前,插件只会在候选行以同一会话、规范路径及行位置所提供的精确 `HASH│` 锚点开头时拒绝;文件保持不变,并提示仅用文件正文重试。插件不会泛化地剥离类似哈希的文本。
|
|
271
|
+
|
|
270
272
|
### 错误码
|
|
271
273
|
|
|
272
274
|
| 代码 | 含义 |
|
|
@@ -284,6 +286,7 @@ token 基准测试衡量的是模型发出的负载——它假设模型每次
|
|
|
284
286
|
| `[E_NOT_FOUND]` | 文件不存在。 |
|
|
285
287
|
| `[E_NOT_OBSERVED]` | 该文件在本会话中尚未被观察(先读后写策略);请先调用 `read`。 |
|
|
286
288
|
| `[E_NOT_TEXT]` | 路径是目录、二进制或非 UTF-8 文件;hashline 只能编辑文本。 |
|
|
289
|
+
| `[E_WRITE_HASH_ECHO]` | 内置 `write` 候选内容复制了同一会话、路径及行位置所提供的 `HASH│` 预览锚点。写入在执行前被拒绝;移除整条复制的锚点链后重试。 |
|
|
287
290
|
| `[E_RANGE_STALE]` | 某行自被读取以来在磁盘上发生变化;范围以全新锚点回显。 |
|
|
288
291
|
| `[E_RANGE_UNSERVED]` | 范围内包含从未提供给模型的行。 |
|
|
289
292
|
| `[E_RANGE_UNVERIFIED]` | 边界锚点无法对照已提供状态验证。 |
|
|
@@ -298,7 +301,7 @@ dsh 的工具注册表按作用域解析:agent 看到的是 `agent → preset
|
|
|
298
301
|
|
|
299
302
|
1. 通过其 `cordis.patch.yml` bundle 补丁作为宿主层 Cordis 插件挂载。
|
|
300
303
|
2. 在 `agent/session-start` 时,将 hashline 工具**以及** `tool:read` / `tool:edit` 提示词片段注册到 agent 自身的作用域层——从而为该 agent 遮蔽 preset 的内置工具,并在 agent 销毁时自动解除。
|
|
301
|
-
3. 保留内置的 `write
|
|
304
|
+
3. 保留内置的 `write`,通过作用域内的 `tools/pre-execute` 监听器在执行前拒绝精确的同会话/同路径/同行锚点回显,并由 `tools/post-execute` 在成功结果后附加 hashline 自动读取。
|
|
302
305
|
|
|
303
306
|
## 存储
|
|
304
307
|
|
package/lib/edit-response.js
CHANGED
|
@@ -22,8 +22,9 @@ export function buildMetrics(args) {
|
|
|
22
22
|
return metrics;
|
|
23
23
|
}
|
|
24
24
|
export function finalizeResult(input) {
|
|
25
|
-
const
|
|
26
|
-
|
|
25
|
+
const modelWarnings = input.warnings?.filter((w) => !w.startsWith("Batch drift note:"));
|
|
26
|
+
const base = input.diff + warnBlock(modelWarnings);
|
|
27
|
+
return base;
|
|
27
28
|
}
|
|
28
29
|
export function finalizeToolResult(details) {
|
|
29
30
|
const text = finalizeResult({
|
|
@@ -44,8 +45,8 @@ export function buildNoop(input) {
|
|
|
44
45
|
const noopDetailsText = noopEdit
|
|
45
46
|
? `Edit for ${noopEdit.loc} is identical to current content:\n ${noopEdit.loc}: ${clipLine(noopEdit.currentContent)}`
|
|
46
47
|
: "The edit produced identical content.";
|
|
47
|
-
const
|
|
48
|
-
const text = `No changes made to ${path}\nClassification: noop\n${noopDetailsText}${warnBlock(
|
|
48
|
+
const modelWarnings = warnings?.filter((w) => !w.startsWith("Batch drift note:"));
|
|
49
|
+
const text = `No changes made to ${path}\nClassification: noop\n${noopDetailsText}${warnBlock(modelWarnings)}`;
|
|
49
50
|
const metrics = buildMetrics({
|
|
50
51
|
classification: "noop",
|
|
51
52
|
editsAttempted: editMeta.editsAttempted,
|
|
@@ -71,17 +72,17 @@ export function buildChanged(input) {
|
|
|
71
72
|
const diffResult = genDiff(originalNormalized, result, 1, resultHashes, originalHashes);
|
|
72
73
|
const addedLines = editMeta.addedLines;
|
|
73
74
|
const removedLines = editMeta.removedLines;
|
|
74
|
-
const
|
|
75
|
+
const modelWarnings = warnings?.filter((w) => !w.startsWith("Batch drift note:"));
|
|
76
|
+
const warningsBlock = warnBlock(modelWarnings);
|
|
75
77
|
const successPrefix = `Successfully edited in ${path}.`;
|
|
76
78
|
const lineSummary = addedLines > 0 || removedLines > 0
|
|
77
79
|
? ` Added ${addedLines} line(s), removed ${removedLines} line(s).`
|
|
78
80
|
: "";
|
|
79
|
-
const noticeBlock = driftBlock(driftNotice);
|
|
80
81
|
const text = resultLines.length === 0
|
|
81
|
-
? "File is empty. Use edit to insert content."
|
|
82
|
+
? "File is empty. Use edit to insert content."
|
|
82
83
|
: warningsBlock
|
|
83
|
-
? `${successPrefix}${lineSummary}${warningsBlock}
|
|
84
|
-
: `${successPrefix}${lineSummary}
|
|
84
|
+
? `${successPrefix}${lineSummary}${warningsBlock}`
|
|
85
|
+
: `${successPrefix}${lineSummary}`;
|
|
85
86
|
const metrics = buildMetrics({
|
|
86
87
|
classification: "applied",
|
|
87
88
|
editsAttempted: editMeta.editsAttempted,
|
|
@@ -123,7 +124,8 @@ export function buildBatchResult(sections) {
|
|
|
123
124
|
.filter((d) => d !== undefined)
|
|
124
125
|
.join("\n\n");
|
|
125
126
|
if (allNoop) {
|
|
126
|
-
const
|
|
127
|
+
const modelWarnings = warnings.filter((w) => !w.startsWith("Batch drift note:"));
|
|
128
|
+
const text = `No changes made. All ${totalEdits} edit(s) in the batch produced identical content.\nClassification: noop${warnBlock(modelWarnings)}`;
|
|
127
129
|
return {
|
|
128
130
|
content: [{ type: "text", text }],
|
|
129
131
|
details: {
|
|
@@ -158,7 +160,8 @@ export function buildBatchResult(sections) {
|
|
|
158
160
|
? ` Added ${addedLines} line(s), removed ${removedLines} line(s).`
|
|
159
161
|
: "";
|
|
160
162
|
const summary = `Successfully edited ${appliedFiles.length} file(s) — ${appliedTotal} of ${totalEdits} edit(s) applied${noopTotal > 0 ? ` (${noopTotal} noop)` : ""}.${lineSummary}`;
|
|
161
|
-
const
|
|
163
|
+
const modelWarnings = warnings.filter((w) => !w.startsWith("Batch drift note:"));
|
|
164
|
+
const text = `${summary}${warnBlock(modelWarnings)}`;
|
|
162
165
|
return {
|
|
163
166
|
content: [{ type: "text", text }],
|
|
164
167
|
details: {
|
package/lib/fs-write.js
CHANGED
|
@@ -24,11 +24,13 @@ async function sweepStaleTemps(dir) {
|
|
|
24
24
|
await rm(tempPath, { force: true });
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
-
catch {
|
|
27
|
+
catch (error) {
|
|
28
|
+
console.error("[fs-write] failed to inspect stale temp", error);
|
|
28
29
|
}
|
|
29
30
|
}
|
|
30
31
|
}
|
|
31
|
-
catch {
|
|
32
|
+
catch (error) {
|
|
33
|
+
console.error("[fs-write] failed to sweep stale temps", error);
|
|
32
34
|
}
|
|
33
35
|
}
|
|
34
36
|
async function syncDir(dir) {
|
|
@@ -43,7 +45,8 @@ async function syncDir(dir) {
|
|
|
43
45
|
await handle.close();
|
|
44
46
|
}
|
|
45
47
|
}
|
|
46
|
-
catch {
|
|
48
|
+
catch (error) {
|
|
49
|
+
console.error("[fs-write] failed to sync directory", error);
|
|
47
50
|
}
|
|
48
51
|
}
|
|
49
52
|
export async function writeAtomic(path, content) {
|
|
@@ -78,7 +81,9 @@ export async function writeAtomic(path, content) {
|
|
|
78
81
|
try {
|
|
79
82
|
await rm(tempPath, { force: true });
|
|
80
83
|
}
|
|
81
|
-
catch {
|
|
84
|
+
catch (error) {
|
|
85
|
+
console.error("[fs-write] failed to remove temp file", error);
|
|
86
|
+
}
|
|
82
87
|
throw error;
|
|
83
88
|
}
|
|
84
89
|
try {
|
|
@@ -96,13 +101,17 @@ export async function writeAtomic(path, content) {
|
|
|
96
101
|
try {
|
|
97
102
|
await rm(tempPath, { force: true });
|
|
98
103
|
}
|
|
99
|
-
catch {
|
|
104
|
+
catch (error) {
|
|
105
|
+
console.error("[fs-write] failed to remove temp file", error);
|
|
106
|
+
}
|
|
100
107
|
}
|
|
101
108
|
}
|
|
102
109
|
try {
|
|
103
110
|
await rm(tempPath, { force: true });
|
|
104
111
|
}
|
|
105
|
-
catch {
|
|
112
|
+
catch (error) {
|
|
113
|
+
console.error("[fs-write] failed to remove temp file", error);
|
|
114
|
+
}
|
|
106
115
|
throw error;
|
|
107
116
|
}
|
|
108
117
|
}
|
package/lib/hash-store.js
CHANGED
|
@@ -56,6 +56,7 @@ function cacheKey(checksum) {
|
|
|
56
56
|
return `${CANON_VERSION}:${checksum}`;
|
|
57
57
|
}
|
|
58
58
|
/** Load the store as served persistence — internal, for SessionView only. */
|
|
59
|
+
// SAFETY: loadHashStore returns InternalHashStore (HashStore & ServedPersistence) — cast narrows to served view, validated via ServedPersistence interface; safe because InternalHashStore extends both.
|
|
59
60
|
export function loadServedStore(cwd) {
|
|
60
61
|
return loadHashStore(cwd);
|
|
61
62
|
}
|
|
@@ -109,7 +110,7 @@ function openDbWithBusyRetry(storePath) {
|
|
|
109
110
|
const stores = new Map();
|
|
110
111
|
const openings = new Map();
|
|
111
112
|
setStoresGetter(() => stores, () => openings);
|
|
112
|
-
|
|
113
|
+
const exitHandlerRegistered = false;
|
|
113
114
|
function openDb(storePath) {
|
|
114
115
|
const db = new DatabaseSync(storePath, {
|
|
115
116
|
timeout: HASH_STORE_BUSY_TIMEOUT,
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
* @module dsh-better-edit/hashline/anchor-pipeline
|
|
20
20
|
*/
|
|
21
21
|
import { abortIf, splitLines, rejectUnknownFields, firstNonEmptyIndex, lastNonEmptyIndex, clipLine } from "../utils.js";
|
|
22
|
-
import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HASH_SEP, ANCHOR_LEN, ALPH_RE, canon, lineHashesPure } from "./hash-assign.js";
|
|
22
|
+
import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HASH_SEP, ANCHOR_LEN, ALPH_RE, canon, lineHashesPure, getCanonForHash, rememberHashCanon } from "./hash-assign.js";
|
|
23
23
|
import { recordServed, servedPositionsOf } from "../served-store.js";
|
|
24
24
|
import { SERVED_ECHO_CAP } from "../constants.js";
|
|
25
25
|
import { NEW_CONTENT_NOT_STRING_MSG } from "../constants.js";
|
|
@@ -31,6 +31,18 @@ function diagRef(ref) {
|
|
|
31
31
|
if (/^\d+/.test(trimmed)) {
|
|
32
32
|
return `[E_BAD_REF] Invalid anchor. Use the hash alone (e.g. "aB3") — no line numbers or trailing content.`;
|
|
33
33
|
}
|
|
34
|
+
if (trimmed.includes("│") && trimmed.includes("\n")) {
|
|
35
|
+
const lines = trimmed.split("\n");
|
|
36
|
+
const first = lines[0] ?? "";
|
|
37
|
+
const last = lines[lines.length - 1] ?? "";
|
|
38
|
+
const hashRe = new RegExp(HASH_CLASS);
|
|
39
|
+
const firstMatch = first.match(hashRe);
|
|
40
|
+
const lastMatch = last.match(hashRe);
|
|
41
|
+
const firstHash = firstMatch?.[0] ?? "wUp";
|
|
42
|
+
const lastHash = lastMatch?.[0] ?? "AU6";
|
|
43
|
+
const preview = first.slice(0, 60);
|
|
44
|
+
return `[E_BAD_REF] Invalid anchor — remove_from must be a single bare 3-char hash (e.g. "wUp"), not a block with HASH│. Received ${lines.length} lines starting "${preview}…" — use only the first hash "${firstHash}" as remove_from and "${lastHash}" as remove_to, and put the new content (without HASH│) in replacement_text.`;
|
|
45
|
+
}
|
|
34
46
|
if (trimmed.includes("│")) {
|
|
35
47
|
return `[E_BAD_REF] Invalid anchor "${trimmed}". remove_from and remove_to must contain the 3-char hash only — remove everything from "│" onward.`;
|
|
36
48
|
}
|
|
@@ -151,11 +163,30 @@ function assertItem(edit) {
|
|
|
151
163
|
}
|
|
152
164
|
}
|
|
153
165
|
const ANCHOR_ROW_RE = new RegExp(`^([+-]?)(${HASH_CLASS})│`);
|
|
166
|
+
function firstHashFromBlock(block) {
|
|
167
|
+
for (const line of block.split("\n")) {
|
|
168
|
+
const m = line.match(ANCHOR_ROW_RE);
|
|
169
|
+
if (m)
|
|
170
|
+
return m[2];
|
|
171
|
+
const bare = line.match(new RegExp(HASH_CLASS));
|
|
172
|
+
if (bare)
|
|
173
|
+
return bare[0];
|
|
174
|
+
}
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
154
177
|
export function resEdit(edit, warnings) {
|
|
155
178
|
assertItem(edit);
|
|
156
179
|
const editLines = parseText(edit.replacement_text);
|
|
157
180
|
const bounds = [edit.remove_from, edit.remove_to].map((ref) => {
|
|
158
181
|
const trimmed = ref.trim();
|
|
182
|
+
if (trimmed.includes("\n")) {
|
|
183
|
+
const hash = firstHashFromBlock(trimmed);
|
|
184
|
+
if (hash) {
|
|
185
|
+
const lines = trimmed.split("\n").length;
|
|
186
|
+
warnings?.push(`[E_BAD_REF] extracted first hash "${hash}" from ${lines}-line block — use bare "${hash}" next time`);
|
|
187
|
+
return hash;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
159
190
|
const match = trimmed.match(ANCHOR_ROW_RE);
|
|
160
191
|
if (match) {
|
|
161
192
|
let message;
|
|
@@ -201,7 +232,12 @@ function stripBarePrefixes(edit, fileHashes, warnings) {
|
|
|
201
232
|
.join(", ");
|
|
202
233
|
const matchedCount = stripped.filter((s) => s.matched).length;
|
|
203
234
|
const evidence = matchedCount === 0 ? "0 matched — verify literal 'HASH│' content" : `${matchedCount}/${stripped.length} matched`;
|
|
204
|
-
|
|
235
|
+
if (matchedCount === stripped.length) {
|
|
236
|
+
warnings.push(`[info E_BARE_HASH_PREFIX] stripped "HASH│" prefix from ${locations} (${evidence}) — use bare content without HASH│ next time.`);
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
warnings.push(`[E_BARE_HASH_PREFIX] stripped "HASH│" prefix from ${locations} (${evidence}).`);
|
|
240
|
+
}
|
|
205
241
|
return { ...edit, content_lines: contentLines };
|
|
206
242
|
}
|
|
207
243
|
/** @internal — private to anchor-pipeline seam */
|
|
@@ -439,6 +475,21 @@ export class AnchorMismatchError extends Error {
|
|
|
439
475
|
export function isAnchorMismatch(error) {
|
|
440
476
|
return error instanceof AnchorMismatchError;
|
|
441
477
|
}
|
|
478
|
+
export function findEditHashEcho(replacementLines, served, startLine) {
|
|
479
|
+
for (let k = 0; k < replacementLines.length; k++) {
|
|
480
|
+
const pos = startLine + k - 1;
|
|
481
|
+
if (pos < served.length && served[pos] !== null && replacementLines[k].startsWith(served[pos] + HASH_SEP)) {
|
|
482
|
+
return { k: k + 1, hash: served[pos] };
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return undefined;
|
|
486
|
+
}
|
|
487
|
+
export class EditHashEchoError extends AnchorMismatchError {
|
|
488
|
+
constructor(message, servedRows = []) {
|
|
489
|
+
super(message, servedRows);
|
|
490
|
+
this.name = "EditHashEchoError";
|
|
491
|
+
}
|
|
492
|
+
}
|
|
442
493
|
export function buildRangeEcho(startLine, endLine, fileHashes) {
|
|
443
494
|
const total = endLine - startLine + 1;
|
|
444
495
|
const shown = Math.min(total, SERVED_ECHO_CAP);
|
|
@@ -462,6 +513,20 @@ function paginationHint(nextOffset, more) {
|
|
|
462
513
|
export function verifyServedRange(args) {
|
|
463
514
|
const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath, } = args;
|
|
464
515
|
const where = filePath ? ` in ${filePath}` : "";
|
|
516
|
+
let isHealed = false;
|
|
517
|
+
for (let i = 0; i < fileHashes.length; i++) {
|
|
518
|
+
const h = fileHashes[i];
|
|
519
|
+
if (getCanonForHash(h) === undefined)
|
|
520
|
+
rememberHashCanon(h, canon(fileLines[i] ?? ""));
|
|
521
|
+
}
|
|
522
|
+
for (let i = 0; i < served.length; i++) {
|
|
523
|
+
const h = served[i];
|
|
524
|
+
if (h !== null && getCanonForHash(h) === undefined) {
|
|
525
|
+
const pos = fileHashes.indexOf(h);
|
|
526
|
+
if (pos >= 0)
|
|
527
|
+
rememberHashCanon(h, canon(fileLines[pos] ?? ""));
|
|
528
|
+
}
|
|
529
|
+
}
|
|
465
530
|
const echoRows = buildRangeEcho(startLine, endLine, fileHashes);
|
|
466
531
|
const totalLen = endLine - startLine + 1;
|
|
467
532
|
const tail = echoRows.length < totalLen
|
|
@@ -507,56 +572,215 @@ export function verifyServedRange(args) {
|
|
|
507
572
|
}
|
|
508
573
|
}
|
|
509
574
|
if (from === undefined || to === undefined) {
|
|
510
|
-
|
|
511
|
-
if (startPositions.length ===
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
575
|
+
let healed;
|
|
576
|
+
if (startPositions.length === 1 && endPositions.length === 1) {
|
|
577
|
+
const sPos = startPositions[0];
|
|
578
|
+
const ePos = endPositions[0];
|
|
579
|
+
const servedFrom = Math.min(sPos, ePos);
|
|
580
|
+
const servedTo = Math.max(sPos, ePos);
|
|
581
|
+
const servedLen = servedTo - servedFrom + 1;
|
|
582
|
+
if (servedLen === currentLen) {
|
|
583
|
+
const expectedCanons = [];
|
|
584
|
+
let canBuild = true;
|
|
585
|
+
for (let k = 0; k < servedLen; k++) {
|
|
586
|
+
const h = served[servedFrom + k];
|
|
587
|
+
if (h === null) {
|
|
588
|
+
canBuild = false;
|
|
589
|
+
break;
|
|
590
|
+
}
|
|
591
|
+
const c = getCanonForHash(h);
|
|
592
|
+
if (c === undefined) {
|
|
593
|
+
canBuild = false;
|
|
594
|
+
break;
|
|
595
|
+
}
|
|
596
|
+
expectedCanons.push(c);
|
|
597
|
+
}
|
|
598
|
+
if (canBuild) {
|
|
599
|
+
const matches = [];
|
|
600
|
+
for (let i = 0; i <= fileLines.length - servedLen; i++) {
|
|
601
|
+
let ok = true;
|
|
602
|
+
for (let k = 0; k < servedLen; k++) {
|
|
603
|
+
if (canon(fileLines[i + k] ?? "") !== expectedCanons[k]) {
|
|
604
|
+
ok = false;
|
|
605
|
+
break;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
if (ok)
|
|
609
|
+
matches.push(i);
|
|
610
|
+
if (matches.length > 1)
|
|
611
|
+
break;
|
|
612
|
+
}
|
|
613
|
+
if (matches.length === 1) {
|
|
614
|
+
healed = { from: matches[0], to: matches[0] + servedLen - 1 };
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
516
618
|
}
|
|
517
|
-
if (
|
|
518
|
-
|
|
619
|
+
if (!healed) {
|
|
620
|
+
const hasServed = served.some((h) => h !== null);
|
|
621
|
+
const startInFile = fileHashes.includes(startHash);
|
|
622
|
+
const endInFile = fileHashes.includes(endHash);
|
|
623
|
+
if (hasServed && (!startInFile || !endInFile)) {
|
|
624
|
+
const startCanon = getCanonForHash(startHash);
|
|
625
|
+
const endCanon = getCanonForHash(endHash);
|
|
626
|
+
if (startCanon !== undefined && endCanon !== undefined) {
|
|
627
|
+
const startMatches = [];
|
|
628
|
+
const endMatches = [];
|
|
629
|
+
for (let i = 0; i < fileLines.length; i++) {
|
|
630
|
+
if (canon(fileLines[i] ?? "") === startCanon)
|
|
631
|
+
startMatches.push(i);
|
|
632
|
+
if (canon(fileLines[i] ?? "") === endCanon)
|
|
633
|
+
endMatches.push(i);
|
|
634
|
+
if (startMatches.length > 1 && endMatches.length > 1)
|
|
635
|
+
break;
|
|
636
|
+
}
|
|
637
|
+
if (startMatches.length === 1 && endMatches.length === 1) {
|
|
638
|
+
const s = startMatches[0];
|
|
639
|
+
const e = endMatches[0];
|
|
640
|
+
const healedFrom = Math.min(s, e);
|
|
641
|
+
const healedTo = Math.max(s, e);
|
|
642
|
+
if (healedTo - healedFrom + 1 === currentLen) {
|
|
643
|
+
let interiorOk = true;
|
|
644
|
+
if (currentLen > 2) {
|
|
645
|
+
const healedCanons = [];
|
|
646
|
+
for (let k = 0; k < currentLen; k++)
|
|
647
|
+
healedCanons.push(canon(fileLines[healedFrom + k] ?? ""));
|
|
648
|
+
let count = 0;
|
|
649
|
+
for (let i = 0; i <= fileLines.length - currentLen; i++) {
|
|
650
|
+
let ok = true;
|
|
651
|
+
for (let k = 0; k < currentLen; k++)
|
|
652
|
+
if (canon(fileLines[i + k] ?? "") !== healedCanons[k]) {
|
|
653
|
+
ok = false;
|
|
654
|
+
break;
|
|
655
|
+
}
|
|
656
|
+
if (ok)
|
|
657
|
+
count++;
|
|
658
|
+
if (count > 1)
|
|
659
|
+
break;
|
|
660
|
+
}
|
|
661
|
+
if (count !== 1)
|
|
662
|
+
interiorOk = false;
|
|
663
|
+
}
|
|
664
|
+
if (interiorOk)
|
|
665
|
+
healed = { from: healedFrom, to: healedTo };
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
519
670
|
}
|
|
520
|
-
|
|
521
|
-
|
|
671
|
+
if (healed) {
|
|
672
|
+
from = healed.from;
|
|
673
|
+
to = healed.to;
|
|
674
|
+
isHealed = true;
|
|
522
675
|
}
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
`
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
676
|
+
else {
|
|
677
|
+
const problems = [];
|
|
678
|
+
if (startPositions.length === 0) {
|
|
679
|
+
problems.push(`remove_from "${startHash}" has no served position`);
|
|
680
|
+
}
|
|
681
|
+
else if (startPositions.length > 1) {
|
|
682
|
+
problems.push(`remove_from "${startHash}" was served at ${startPositions.length} positions`);
|
|
683
|
+
}
|
|
684
|
+
if (endPositions.length === 0) {
|
|
685
|
+
problems.push(`remove_to "${endHash}" has no served position`);
|
|
686
|
+
}
|
|
687
|
+
else if (endPositions.length > 1) {
|
|
688
|
+
problems.push(`remove_to "${endHash}" was served at ${endPositions.length} positions`);
|
|
689
|
+
}
|
|
534
690
|
throw new ServedRejectionError({
|
|
535
|
-
code: "
|
|
536
|
-
message: `[
|
|
537
|
-
|
|
691
|
+
code: "E_RANGE_UNVERIFIED",
|
|
692
|
+
message: `[E_RANGE_UNVERIFIED] cannot verify range against served state${where}: ${problems.join("; ")}. ` +
|
|
693
|
+
`No served span matched the current range (${currentLen} lines). ` +
|
|
694
|
+
`A full read will re-sync the served mirror — the echoed range below is current content, ` +
|
|
695
|
+
`but retrying without re-reading cannot clear a stale duplicate outside the echoed window.\n` +
|
|
696
|
+
`Current range:\n${echo}`,
|
|
538
697
|
servedRows: echoRows,
|
|
539
698
|
});
|
|
540
699
|
}
|
|
541
700
|
}
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
701
|
+
if (isHealed) {
|
|
702
|
+
for (let k = 0; k < currentLen; k++) {
|
|
703
|
+
const servedHash = served[from + k];
|
|
704
|
+
if (servedHash === null)
|
|
705
|
+
continue;
|
|
706
|
+
const expectedCanon = getCanonForHash(servedHash);
|
|
707
|
+
const actualCanon = canon(fileLines[from + k] ?? "");
|
|
708
|
+
if (expectedCanon !== undefined && expectedCanon !== actualCanon) {
|
|
709
|
+
const offendingLine = from + k + 1;
|
|
710
|
+
throw new ServedRejectionError({
|
|
711
|
+
code: "E_RANGE_STALE",
|
|
712
|
+
message: `[E_RANGE_STALE] line ${offendingLine}${where} differs from what was served.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
713
|
+
firstOffendingLine: offendingLine,
|
|
714
|
+
servedRows: echoRows,
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
}
|
|
550
718
|
}
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
719
|
+
else {
|
|
720
|
+
for (let i = from; i <= to; i++) {
|
|
721
|
+
if (served[i] === null) {
|
|
722
|
+
throw new ServedRejectionError({
|
|
723
|
+
code: "E_RANGE_UNSERVED",
|
|
724
|
+
message: `[E_RANGE_UNSERVED] line ${i + 1}${where} was never served.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
725
|
+
firstOffendingLine: i + 1,
|
|
726
|
+
servedRows: echoRows,
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
const servedLen = to - from + 1;
|
|
731
|
+
if (servedLen !== currentLen) {
|
|
732
|
+
let lenHealed = false;
|
|
733
|
+
const expectedCanons = [];
|
|
734
|
+
let canBuild = true;
|
|
735
|
+
for (let k = 0; k < servedLen; k++) {
|
|
736
|
+
const h = served[from + k];
|
|
737
|
+
if (h === null) {
|
|
738
|
+
canBuild = false;
|
|
739
|
+
break;
|
|
740
|
+
}
|
|
741
|
+
const c = getCanonForHash(h);
|
|
742
|
+
if (c === undefined) {
|
|
743
|
+
canBuild = false;
|
|
744
|
+
break;
|
|
745
|
+
}
|
|
746
|
+
expectedCanons.push(c);
|
|
747
|
+
}
|
|
748
|
+
if (canBuild) {
|
|
749
|
+
let matches = 0;
|
|
750
|
+
for (let i = 0; i <= fileLines.length - servedLen; i++) {
|
|
751
|
+
let ok = true;
|
|
752
|
+
for (let k = 0; k < servedLen; k++)
|
|
753
|
+
if (canon(fileLines[i + k] ?? "") !== expectedCanons[k]) {
|
|
754
|
+
ok = false;
|
|
755
|
+
break;
|
|
756
|
+
}
|
|
757
|
+
if (ok)
|
|
758
|
+
matches++;
|
|
759
|
+
if (matches > 1)
|
|
760
|
+
break;
|
|
761
|
+
}
|
|
762
|
+
if (matches === 1)
|
|
763
|
+
lenHealed = true;
|
|
764
|
+
}
|
|
765
|
+
if (!lenHealed) {
|
|
766
|
+
throw new ServedRejectionError({
|
|
767
|
+
code: "E_RANGE_STALE",
|
|
768
|
+
message: `[E_RANGE_STALE] served span (${servedLen} lines) no longer matches current range (${currentLen} lines)${where}.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
769
|
+
firstOffendingLine: startLine,
|
|
770
|
+
servedRows: echoRows,
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
for (let k = 0; k < servedLen; k++) {
|
|
775
|
+
if (served[from + k] !== fileHashes[startLine - 1 + k]) {
|
|
776
|
+
const offendingLine = startLine + k;
|
|
777
|
+
throw new ServedRejectionError({
|
|
778
|
+
code: "E_RANGE_STALE",
|
|
779
|
+
message: `[E_RANGE_STALE] line ${offendingLine}${where} differs from what was served.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
780
|
+
firstOffendingLine: offendingLine,
|
|
781
|
+
servedRows: echoRows,
|
|
782
|
+
});
|
|
783
|
+
}
|
|
560
784
|
}
|
|
561
785
|
}
|
|
562
786
|
}
|
|
@@ -694,6 +918,17 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
|
|
|
694
918
|
resolved = correctedResult.resolved;
|
|
695
919
|
}
|
|
696
920
|
if (served) {
|
|
921
|
+
const startLineEcho = resolved.hash_bounds[0].line;
|
|
922
|
+
const rawEcho = findEditHashEcho(edit.content_lines, served, startLineEcho);
|
|
923
|
+
let echo = rawEcho;
|
|
924
|
+
if (!echo)
|
|
925
|
+
echo = findEditHashEcho(resolved.content_lines, served, startLineEcho);
|
|
926
|
+
if (!echo)
|
|
927
|
+
echo = findEditHashEcho(prefixFixed.content_lines, served, startLineEcho);
|
|
928
|
+
if (echo) {
|
|
929
|
+
const msg = `[E_EDIT_HASH_ECHO] Refused edit to ${filePath ?? "(unknown file)"}: replacement line ${echo.k} begins with the exact ${echo.hash}${HASH_SEP} anchor served for this session, path, and range-relative line. Remove the copied anchors and retry. Nothing was written.`;
|
|
930
|
+
throw new EditHashEchoError(msg, []);
|
|
931
|
+
}
|
|
697
932
|
const startAnchor = resolved.hash_bounds[0];
|
|
698
933
|
const endAnchor = resolved.hash_bounds[1];
|
|
699
934
|
verifyServedRange({
|
|
@@ -67,6 +67,14 @@ function hashAt(idx) {
|
|
|
67
67
|
}
|
|
68
68
|
return hash;
|
|
69
69
|
}
|
|
70
|
+
const hashToCanon = new Map();
|
|
71
|
+
export function rememberHashCanon(hash, canonText) {
|
|
72
|
+
if (!hashToCanon.has(hash))
|
|
73
|
+
hashToCanon.set(hash, canonText);
|
|
74
|
+
}
|
|
75
|
+
export function getCanonForHash(hash) {
|
|
76
|
+
return hashToCanon.get(hash);
|
|
77
|
+
}
|
|
70
78
|
export const HL_PREFIX_PLUS_RE = new RegExp(`^\\+${HASH_CLASS}│`);
|
|
71
79
|
export const HL_PREFIX_MINUS_RE = new RegExp(`^-(?:${HASH_CLASS}│| {${ANCHOR_LEN}}│)`);
|
|
72
80
|
export const HL_BARE_PREFIX_RE = new RegExp(`^\\s*(${HASH_CLASS})│`);
|
|
@@ -122,7 +130,9 @@ export function lineHashesPure(content) {
|
|
|
122
130
|
for (let i = 0; i < lines.length; i++) {
|
|
123
131
|
const c = getCanon(canonCache, lines[i]);
|
|
124
132
|
const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
|
|
125
|
-
|
|
133
|
+
const h = assignHash(used, baseIdx, hint);
|
|
134
|
+
hashes[i] = h;
|
|
135
|
+
rememberHashCanon(h, c);
|
|
126
136
|
}
|
|
127
137
|
return hashes;
|
|
128
138
|
}
|
|
@@ -223,6 +233,7 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
|
|
|
223
233
|
const newIdx = candidates.splice(pos, 1)[0];
|
|
224
234
|
newHashes[newIdx] = entry.hash;
|
|
225
235
|
markUsed(entry.hash);
|
|
236
|
+
rememberHashCanon(entry.hash, getCanon(canonCache, oldLines[entry.index]));
|
|
226
237
|
}
|
|
227
238
|
const removedByContent = new Map();
|
|
228
239
|
for (const entry of removedEntries) {
|
|
@@ -240,15 +251,19 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
|
|
|
240
251
|
const queue = removedByContent.get(getCanon(canonCache, newLines[i]));
|
|
241
252
|
if (!queue || queue.pos >= queue.hashes.length)
|
|
242
253
|
continue;
|
|
243
|
-
|
|
254
|
+
const h = queue.hashes[queue.pos];
|
|
255
|
+
newHashes[i] = h;
|
|
244
256
|
queue.pos += 1;
|
|
257
|
+
rememberHashCanon(h, getCanon(canonCache, newLines[i]));
|
|
245
258
|
}
|
|
246
259
|
for (let i = 0; i < newLines.length; i++) {
|
|
247
260
|
if (newHashes[i])
|
|
248
261
|
continue;
|
|
249
262
|
const c = getCanon(canonCache, newLines[i]);
|
|
250
263
|
const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
|
|
251
|
-
|
|
264
|
+
const h = assignHash(used, baseIdx, hint);
|
|
265
|
+
newHashes[i] = h;
|
|
266
|
+
rememberHashCanon(h, c);
|
|
252
267
|
}
|
|
253
268
|
return newHashes;
|
|
254
269
|
}
|
package/lib/hashline/index.js
CHANGED
|
@@ -7,4 +7,4 @@ export { CANON_VERSION, ANCHOR_LEN, HASH_SEP, HASH_SPACE, HASH_PROBE_STRIDE, MAX
|
|
|
7
7
|
export { lineHashes } from "./hash.js";
|
|
8
8
|
export { parseHashRef, parseText } from "./parse.js";
|
|
9
9
|
export { resEdit } from "./anchor-pipeline.js";
|
|
10
|
-
export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
|
|
10
|
+
export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, EditHashEchoError, findEditHashEcho, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
|
package/lib/index.js
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
* the AGENT's own scope layer, so they shadow the preset's built-in `read` /
|
|
8
8
|
* `edit` for that agent (nearest layer wins in dsh's tool registry) and unwind
|
|
9
9
|
* automatically when the agent is disposed. The built-in `write` stays in
|
|
10
|
-
* place;
|
|
11
|
-
* preview
|
|
10
|
+
* place; scoped pre/post listeners reject copied same-line served anchors
|
|
11
|
+
* before dispatch and append a fresh hashline preview after successful writes.
|
|
12
12
|
*
|
|
13
13
|
* The four `tool:*` guidance sections resolve per agent preset from override
|
|
14
14
|
* files in the shared home (see `src/guidance.ts`); deployments without the
|
package/lib/prompts.js
CHANGED
|
@@ -6,19 +6,22 @@
|
|
|
6
6
|
* followed by tight bullets.
|
|
7
7
|
* @module dsh-better-edit/prompts
|
|
8
8
|
*/
|
|
9
|
-
export const EDIT_DESCRIPTION = "Edit a range of lines in a text file
|
|
10
|
-
|
|
11
|
-
"remove_from
|
|
12
|
-
|
|
13
|
-
"
|
|
9
|
+
export const EDIT_DESCRIPTION = "Edit a range of lines in a text file with `{ \"path\": path, \"edits\": [[remove_from, remove_to, replacement_text], ...] }`. " +
|
|
10
|
+
"`path` is the file path or `null`. `read` returns `HASH\u2502content` (e.g. `wUp\u2502 \"site\": {`) \u2014 for `edit`, " +
|
|
11
|
+
"`remove_from`/`remove_to` are HASH anchors (bare 3-char value before `\u2502`, e.g. \"wUp\", \"AU6\"), never `HASH\u2502content` or line content. " +
|
|
12
|
+
"`replacement_text` is bare content without `HASH\u2502`, lines joined by \\n (e.g. \" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\"); use \"\" to delete. " +
|
|
13
|
+
"Example: read shows `wUp\u2502 \"site\": {` + `AU6\u2502 \"name\": \"old\",` \u2192 edit " +
|
|
14
|
+
"`{\"path\":\"scrape.py\",\"edits\":[[\"wUp\",\"AU6\",\" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\"]]}`. " +
|
|
15
|
+
"Edits in one call apply atomically; after success reuse `HASH\u2502content` from the returned diff for the next edit (no re-read needed). On failure follow the error hint.";
|
|
14
16
|
export const EDIT_GUIDANCE = {
|
|
15
|
-
intro: "Edit a range of lines via a bare 3-char HASH anchor
|
|
17
|
+
intro: "Edit a range of lines via a bare 3-char HASH anchor \u2014 payload is { path, edits: [[hash,hash,text]] } (single-file atomic, null path infers).",
|
|
16
18
|
lines: [
|
|
17
|
-
"`edit`:
|
|
18
|
-
"`edit`:
|
|
19
|
-
"`edit`:
|
|
20
|
-
"`edit`:
|
|
21
|
-
"`edit`:
|
|
19
|
+
"`edit`: `HASH` vs `HASH\u2502content` \u2014 `HASH` is the bare 3-char (e.g. \"wUp\"), `HASH\u2502content` is the full line from `read`/`diff` (e.g. `wUp\u2502 \"site\": {`); never mix them.",
|
|
20
|
+
"`edit`: get `remove_from`/`remove_to` by copying only the 3 chars before `\u2502` from `read` output \u2014 never include `\u2502` or content after it.",
|
|
21
|
+
"`edit`: `replacement_text` is plain file content without `HASH\u2502` \u2014 e.g. \" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\" \u2014 never prefix lines with `HASH\u2502`.",
|
|
22
|
+
"`edit`: every `\\n` in `replacement_text` separates lines; mirror trailing blank lines explicitly (use \"\" to delete a range).",
|
|
23
|
+
"`edit`: after a successful edit the returned diff shows fresh anchors (`HASH\u2502content`) \u2014 copy new `HASH` values from there for the next edit; no need to re-read.",
|
|
24
|
+
"`edit`: `remove_from`/`remove_to` are inclusive; batch multiple edits to the same file only when independent \u2014 they apply atomically (fail \u2192 nothing written).",
|
|
22
25
|
],
|
|
23
26
|
};
|
|
24
27
|
export const READ_DESCRIPTION = "Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. " +
|
package/lib/store-tenancy.js
CHANGED
|
@@ -51,16 +51,25 @@ export function tenancyFor(cwd) {
|
|
|
51
51
|
const cfg = loadConfig();
|
|
52
52
|
const sd = cfg.storeDir;
|
|
53
53
|
if (sd === "workspace") {
|
|
54
|
-
return {
|
|
54
|
+
return {
|
|
55
|
+
dir: join(resolvePath(cwd), ".dsh_better_edit"),
|
|
56
|
+
mode: "workspace",
|
|
57
|
+
canonical: canonicalSync(cwd),
|
|
58
|
+
};
|
|
55
59
|
}
|
|
56
60
|
const canonical = canonicalSync(cwd);
|
|
57
61
|
const h = hash8(cwd);
|
|
58
62
|
if (sd === "central") {
|
|
59
63
|
const dir = join(resolveDshHome(), "plugins", "dsh-better-edit", "runtime", `${sanitizedBasename(cwd)}-${h}`);
|
|
60
64
|
ensureWsPathSidecar(dir, canonical);
|
|
61
|
-
return {
|
|
65
|
+
return {
|
|
66
|
+
dir,
|
|
67
|
+
mode: "central",
|
|
68
|
+
runtimeDir: join(resolveDshHome(), "plugins", "dsh-better-edit", "runtime"),
|
|
69
|
+
canonical,
|
|
70
|
+
};
|
|
62
71
|
}
|
|
63
|
-
const dir = join(sd, h);
|
|
72
|
+
const dir = join(sd, `${sanitizedBasename(cwd)}-${h}`);
|
|
64
73
|
ensureWsPathSidecar(dir, canonical);
|
|
65
74
|
return { dir, mode: "custom", runtimeDir: sd, canonical };
|
|
66
75
|
}
|
|
@@ -85,6 +85,13 @@ export declare class AnchorMismatchError extends Error {
|
|
|
85
85
|
constructor(message: string, servedRows: ServedRow[]);
|
|
86
86
|
}
|
|
87
87
|
export declare function isAnchorMismatch(error: unknown): error is AnchorMismatchError;
|
|
88
|
+
export declare function findEditHashEcho(replacementLines: string[], served: readonly (string | null)[], startLine: number): {
|
|
89
|
+
k: number;
|
|
90
|
+
hash: string;
|
|
91
|
+
} | undefined;
|
|
92
|
+
export declare class EditHashEchoError extends AnchorMismatchError {
|
|
93
|
+
constructor(message: string, servedRows?: ServedRow[]);
|
|
94
|
+
}
|
|
88
95
|
export declare function buildRangeEcho(startLine: number, endLine: number, fileHashes: string[]): ServedRow[];
|
|
89
96
|
export declare function fmtServedRows(rows: ServedRow[], fileLines: string[]): string;
|
|
90
97
|
export declare function verifyServedRange(args: {
|
|
@@ -16,6 +16,8 @@ export declare const HASH_SEP = "\u2502";
|
|
|
16
16
|
export declare const HASH_SPACE: number;
|
|
17
17
|
export declare const MAX_HASH_LINES: number;
|
|
18
18
|
export declare const HASH_PROBE_STRIDE: number;
|
|
19
|
+
export declare function rememberHashCanon(hash: string, canonText: string): void;
|
|
20
|
+
export declare function getCanonForHash(hash: string): string | undefined;
|
|
19
21
|
export declare const HL_PREFIX_PLUS_RE: RegExp;
|
|
20
22
|
export declare const HL_PREFIX_MINUS_RE: RegExp;
|
|
21
23
|
export declare const HL_BARE_PREFIX_RE: RegExp;
|
|
@@ -9,5 +9,5 @@ export { parseHashRef, parseText } from "./parse.js";
|
|
|
9
9
|
export type { Anchor } from "./parse.js";
|
|
10
10
|
export { resEdit } from "./anchor-pipeline.js";
|
|
11
11
|
export type { HEdit, HTEdit, NEdit, BDup, AutoFix } from "./anchor-pipeline.js";
|
|
12
|
-
export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
|
|
12
|
+
export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, EditHashEchoError, findEditHashEcho, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
|
|
13
13
|
export type { ServedRow, ResolvedRange, ServedCode, } from "./anchor-pipeline.js";
|
package/lib/types/index.d.ts
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
* the AGENT's own scope layer, so they shadow the preset's built-in `read` /
|
|
8
8
|
* `edit` for that agent (nearest layer wins in dsh's tool registry) and unwind
|
|
9
9
|
* automatically when the agent is disposed. The built-in `write` stays in
|
|
10
|
-
* place;
|
|
11
|
-
* preview
|
|
10
|
+
* place; scoped pre/post listeners reject copied same-line served anchors
|
|
11
|
+
* before dispatch and append a fresh hashline preview after successful writes.
|
|
12
12
|
*
|
|
13
13
|
* The four `tool:*` guidance sections resolve per agent preset from override
|
|
14
14
|
* files in the shared home (see `src/guidance.ts`); deployments without the
|
|
@@ -1,17 +1,35 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* anchors
|
|
2
|
+
* Guard + auto-read around `write`: a scoped `tools/pre-execute` listener
|
|
3
|
+
* rejects copied hashline preview rows before they can reach disk, then a
|
|
4
|
+
* `tools/post-execute` listener re-reads successful writes and appends fresh
|
|
5
|
+
* anchors to the model-facing content (mirroring pi-hashline-edit-lsz).
|
|
6
6
|
* @module dsh-better-edit/write-hook
|
|
7
7
|
*/
|
|
8
8
|
import type { Context } from '@deepseek-ai/cordis';
|
|
9
9
|
import type { FileIO } from './fs-bridge.js';
|
|
10
|
+
export interface ServedHashEcho {
|
|
11
|
+
/** One-based candidate line carrying the copied anchor. */
|
|
12
|
+
line: number;
|
|
13
|
+
/** The exact anchor served for this session, path, and line. */
|
|
14
|
+
hash: string;
|
|
15
|
+
}
|
|
10
16
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
|
|
17
|
+
* Find a copied hashline prefix without treating arbitrary `3-char│` text as
|
|
18
|
+
* metadata. A match requires the exact hash currently recorded at the same
|
|
19
|
+
* line position for this session and canonical path.
|
|
20
|
+
*/
|
|
21
|
+
export declare function findServedHashEcho(content: string, served: readonly (string | null)[]): ServedHashEcho | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Inspect one validated-looking built-in write request against session-scoped
|
|
24
|
+
* served state. Returns a pre-dispatch denial reason only for an exact
|
|
25
|
+
* same-session / same-canonical-path / same-line anchor echo.
|
|
26
|
+
*/
|
|
27
|
+
export declare function servedHashEchoDenial(io: FileIO, rawPath: string, content: string, cwd: string, sessionKey: string, signal?: AbortSignal): Promise<string | undefined>;
|
|
28
|
+
/**
|
|
29
|
+
* Register the pre-write echo guard and post-write auto-read on the calling
|
|
30
|
+
* agent's scope. The guard denies before dispatch; the auto-read replaces only
|
|
31
|
+
* model-facing result content (never the canonical value). Infrastructure
|
|
32
|
+
* failures fail open so the plugin never breaks an otherwise valid write.
|
|
15
33
|
* @param rootCtx - host context for diagnostics.
|
|
16
34
|
* @param agentCtx - the agent's scoped context; the listener receives only
|
|
17
35
|
* this agent's tool results.
|
package/lib/write-hook.js
CHANGED
|
@@ -1,19 +1,54 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* anchors
|
|
2
|
+
* Guard + auto-read around `write`: a scoped `tools/pre-execute` listener
|
|
3
|
+
* rejects copied hashline preview rows before they can reach disk, then a
|
|
4
|
+
* `tools/post-execute` listener re-reads successful writes and appends fresh
|
|
5
|
+
* anchors to the model-facing content (mirroring pi-hashline-edit-lsz).
|
|
6
6
|
* @module dsh-better-edit/write-hook
|
|
7
7
|
*/
|
|
8
8
|
import { readAndServe } from './read-and-serve.js';
|
|
9
|
-
import { execCwd, execSessionKey } from './session-view.js';
|
|
10
|
-
import {
|
|
9
|
+
import { execCwd, execSessionKey, loadServed, withWorkspace } from './session-view.js';
|
|
10
|
+
import { HASH_SEP } from './hashline/hash-assign.js';
|
|
11
|
+
import { abortIf, splitLines } from './utils.js';
|
|
11
12
|
const AUTO_READ_HEADING = '--- Auto-read (hashline anchors) ---';
|
|
12
13
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
|
|
14
|
+
* Find a copied hashline prefix without treating arbitrary `3-char│` text as
|
|
15
|
+
* metadata. A match requires the exact hash currently recorded at the same
|
|
16
|
+
* line position for this session and canonical path.
|
|
17
|
+
*/
|
|
18
|
+
export function findServedHashEcho(content, served) {
|
|
19
|
+
const lines = splitLines(content);
|
|
20
|
+
const compared = Math.min(lines.length, served.length);
|
|
21
|
+
for (let index = 0; index < compared; index += 1) {
|
|
22
|
+
const hash = served[index];
|
|
23
|
+
if (hash !== null && lines[index].startsWith(`${hash}${HASH_SEP}`)) {
|
|
24
|
+
return { line: index + 1, hash };
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Inspect one validated-looking built-in write request against session-scoped
|
|
31
|
+
* served state. Returns a pre-dispatch denial reason only for an exact
|
|
32
|
+
* same-session / same-canonical-path / same-line anchor echo.
|
|
33
|
+
*/
|
|
34
|
+
export async function servedHashEchoDenial(io, rawPath, content, cwd, sessionKey, signal) {
|
|
35
|
+
abortIf(signal);
|
|
36
|
+
const absolutePath = await io.resolve(rawPath, cwd, signal);
|
|
37
|
+
abortIf(signal);
|
|
38
|
+
const served = await loadServed(sessionKey, absolutePath);
|
|
39
|
+
const match = findServedHashEcho(content, served);
|
|
40
|
+
if (!match)
|
|
41
|
+
return undefined;
|
|
42
|
+
return (`[E_WRITE_HASH_ECHO] Refused write to ${rawPath}: line ${match.line} begins with ` +
|
|
43
|
+
`the exact ${match.hash}${HASH_SEP} anchor served for this session, path, and line. ` +
|
|
44
|
+
`HASH${HASH_SEP} anchors are tool output, not file content. ` +
|
|
45
|
+
'Retry with file content only (remove the entire copied anchor chain). Nothing was written.');
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Register the pre-write echo guard and post-write auto-read on the calling
|
|
49
|
+
* agent's scope. The guard denies before dispatch; the auto-read replaces only
|
|
50
|
+
* model-facing result content (never the canonical value). Infrastructure
|
|
51
|
+
* failures fail open so the plugin never breaks an otherwise valid write.
|
|
17
52
|
* @param rootCtx - host context for diagnostics.
|
|
18
53
|
* @param agentCtx - the agent's scoped context; the listener receives only
|
|
19
54
|
* this agent's tool results.
|
|
@@ -21,7 +56,29 @@ const AUTO_READ_HEADING = '--- Auto-read (hashline anchors) ---';
|
|
|
21
56
|
* @returns the exact disposer that unregisters the listener.
|
|
22
57
|
*/
|
|
23
58
|
export function registerWriteHook(rootCtx, agentCtx, io) {
|
|
24
|
-
|
|
59
|
+
const disposeGuard = agentCtx.on('tools/pre-execute', async (exec, next) => {
|
|
60
|
+
if (exec.name !== 'write')
|
|
61
|
+
return next();
|
|
62
|
+
const args = exec.arguments;
|
|
63
|
+
const rawPath = args?.file_path ?? args?.path;
|
|
64
|
+
const content = args?.content;
|
|
65
|
+
if (typeof rawPath !== 'string' || typeof content !== 'string')
|
|
66
|
+
return next();
|
|
67
|
+
const cwd = execCwd(exec);
|
|
68
|
+
return withWorkspace(cwd, async () => {
|
|
69
|
+
try {
|
|
70
|
+
const reason = await servedHashEchoDenial(io, rawPath, content, cwd, execSessionKey(exec), exec.signal);
|
|
71
|
+
return reason === undefined ? next() : { kind: 'deny', reason };
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (exec.signal.aborted)
|
|
75
|
+
throw error;
|
|
76
|
+
rootCtx.logger.warn(`dsh-better-edit: pre-write hash-echo guard failed open: ${error instanceof Error ? error.message : String(error)}`);
|
|
77
|
+
return next();
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
const disposeAutoRead = agentCtx.on('tools/post-execute', async (exec, result, next) => {
|
|
25
82
|
return withWorkspace(execCwd(exec), async () => {
|
|
26
83
|
const decision = await next();
|
|
27
84
|
if (exec.name !== 'write' ||
|
|
@@ -54,4 +111,8 @@ export function registerWriteHook(rootCtx, agentCtx, io) {
|
|
|
54
111
|
}
|
|
55
112
|
});
|
|
56
113
|
});
|
|
114
|
+
return () => {
|
|
115
|
+
disposeGuard();
|
|
116
|
+
disposeAutoRead();
|
|
117
|
+
};
|
|
57
118
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-better-edit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"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.",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -63,6 +63,7 @@
|
|
|
63
63
|
"node": "^22.19.0 || >=24.0.0"
|
|
64
64
|
},
|
|
65
65
|
"scripts": {
|
|
66
|
+
"prepare": "tsc -p tsconfig.json && husky",
|
|
66
67
|
"build": "tsc -p tsconfig.json",
|
|
67
68
|
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
|
|
68
69
|
"test": "vitest run",
|
|
@@ -70,9 +71,17 @@
|
|
|
70
71
|
"prepublishOnly": "npm run typecheck && npm test && node scripts/assert-tagged.mjs",
|
|
71
72
|
"benchmark": "node benchmark/run.mjs",
|
|
72
73
|
"postpublish": "node scripts/tag-current.mjs",
|
|
73
|
-
"release": "node scripts/release.mjs"
|
|
74
|
+
"release": "node scripts/release.mjs",
|
|
75
|
+
"lint": "biome check .",
|
|
76
|
+
"lint:fix": "biome check --write .",
|
|
77
|
+
"format": "biome check --write .",
|
|
78
|
+
"format:check": "biome check .",
|
|
79
|
+
"test:coverage": "vitest run --coverage"
|
|
74
80
|
},
|
|
75
81
|
"devDependencies": {
|
|
82
|
+
"@biomejs/biome": "^2.1.0",
|
|
83
|
+
"@commitlint/cli": "^21.2.2",
|
|
84
|
+
"@commitlint/config-conventional": "^21.2.2",
|
|
76
85
|
"@deepseek-ai/cordis": "^4.0.1",
|
|
77
86
|
"@deepseek-ai/dsh-agent": "0.1.0-rc.6",
|
|
78
87
|
"@deepseek-ai/dsh-fs": "0.1.0-rc.6",
|
|
@@ -80,9 +89,15 @@
|
|
|
80
89
|
"@deepseek-ai/dsh-sandbox": "^0.1.0-rc.6",
|
|
81
90
|
"@deepseek-ai/dsh-session": "0.1.0-rc.6",
|
|
82
91
|
"@deepseek-ai/dsh-tools": "0.1.0-rc.6",
|
|
92
|
+
"@semantic-release/changelog": "^7.0.0",
|
|
93
|
+
"@semantic-release/git": "^11.0.1",
|
|
94
|
+
"@semantic-release/github": "^12.0.9",
|
|
83
95
|
"@types/node": "^24.0.0",
|
|
84
96
|
"@vitest/coverage-v8": "^4.1.10",
|
|
97
|
+
"conventional-changelog-conventionalcommits": "^8.0.0",
|
|
98
|
+
"husky": "^9.1.7",
|
|
85
99
|
"js-tiktoken": "1.0.21",
|
|
100
|
+
"semantic-release": "^25.0.9",
|
|
86
101
|
"typescript": "^5.8.0",
|
|
87
102
|
"vitest": "^4.1.8"
|
|
88
103
|
}
|