dsh-better-edit 0.1.3 → 0.1.5

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/README.md CHANGED
@@ -2,75 +2,102 @@
2
2
 
3
3
  Hash-anchored `read` / `edit` / `batch_edit` / `undo_last_edit` tools for
4
4
  [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`dsh`).
5
- Every line of a file gets a unique 3-character hash, and you edit by hash. No
6
- line numbers, no fuzzy matching, no edits landing on the wrong line.
7
-
8
- This is a dsh port of
9
- [pi-hashline-edit-lsz](https://github.com/Rianico/pi-hashline-edit-lsz) (itself
10
- a self-maintained fork of pi-hashline-edit / pi-hashline-edit-pro by RimuruW
11
- and Yugimob). The hashline core is ported byte-for-byte; the tool layer is
12
- rewritten on dsh's plugin API.
13
-
14
- ## What you get
15
-
16
- - **Read with anchors.** Every line comes back as `HASH│content`. The hash is
17
- the line's address.
18
- - **Edit by hash.** `edit` targets a range of hashes
19
- (`remove_from` / `remove_to`), so edits always land on the lines you meant.
20
- - **Anchors that stay put.** Edit one part of a file and the hashes of the
21
- rest stay the same. Read once, keep editing.
22
- - **Fresh anchors, automatically.** After every `write` you get the new
23
- anchors (auto-read). After every `edit` you get the diff with the new
24
- hashes.
25
- - **Undo when you need it.** The last edit on a file can be reverted, even
26
- after a restart.
27
- - **Safe writes.** Permissions, line endings, BOMs, symlinks, and hard links
28
- survive every edit (writes go through `ctx.fs`, honoring sandboxed/remote
29
- backends).
30
- - **Reject-and-serve.** A stale or never-served range is hard-rejected with
31
- fresh `HASH│content` rows so the retry needs no `read`.
32
-
33
- ## How it replaces the built-in tools
34
-
35
- dsh's tool registry resolves per scope: an agent sees `agent → preset →
36
- global`, and its **own** layer always wins. The built-in `read`/`edit` live on
37
- the agent-preset layer, so a plain global registration cannot replace them.
38
- This plugin:
39
-
40
- 1. Mounts as a host-plane Cordis plugin via its `cordis.patch.yml` bundle
41
- patch.
42
- 2. On `agent/session-start`, registers the hashline tools **and** the
43
- `tool:read` / `tool:edit` prompt sections on the agent's own scope layer —
44
- they shadow the preset's built-ins for that agent and unwind automatically
45
- when the agent is disposed.
46
- 3. Leaves the built-in `write` in place, but a scoped `tools/post-execute`
47
- listener appends the hashline auto-read to write results.
48
-
49
- ## Installation
50
-
51
- From npm:
52
-
53
- ```sh
54
- dsh plugin --profile <name> add dsh-better-edit
5
+ Every line of a file gets a unique 3-character hash — a **content address** —
6
+ and you edit by hash. No line numbers, no fuzzy matching, no edits landing on
7
+ the wrong line.
8
+
9
+ Three things this plugin is built around:
10
+
11
+ - **Token-saving.** An edit call carries `remove_from` / `remove_to` (two
12
+ 3-char hashes) plus the replacement text — it never echoes the text being
13
+ replaced. A `str_replace` call must reproduce that text verbatim. On a
14
+ 12-edit session over a realistic file this is **28% fewer output tokens**
15
+ (40% on multi-line ranges) — see the [benchmark](#benchmark--reproducible).
16
+ - **Correctness.** Every resolved edit range is verified against the exact
17
+ lines the model was shown. A stale, never-served, or ambiguous range is
18
+ hard-rejected **before anything is written**, and the current range is
19
+ echoed back as fresh anchors (reject-and-serve). Wrong-line edits cannot
20
+ silently land.
21
+ - **A modern edit pattern for agents.** Content-addressed anchors are
22
+ line-number-agnostic: edit one part of a file and the hashes of the rest
23
+ stay put, so chained edits need no re-reads. The model pins a line by what
24
+ it *is*, not by where it used to sit.
25
+
26
+ ## Core concepts
27
+
28
+ ```mermaid
29
+ flowchart LR
30
+ F["file.ts"] --> R["read"]
31
+ R --> A["ve7 │ function hello()<br/>szJ │ const x = 1<br/>kQm │ return x<br/>9xR │ }"]
32
+ A --> E["edit by hash<br/>remove_from : szJ<br/>remove_to : kQm<br/>replacement_text : …"]
33
+ E --> D["diff, fresh anchors<br/>− szJ │ const x = 1<br/>+ a3m │ const x = 2<br/> kQm │ return x"]
55
34
  ```
56
35
 
57
- From a local checkout:
36
+ - **Every line is addressed by its content, not its position.** `read`
37
+ returns `HASH│content`; the hash is a stable address for that line. Change
38
+ the line and it gets a new hash; leave it alone and it keeps the hash even
39
+ as the lines around it move.
58
40
 
59
- ```sh
60
- dsh plugin --profile <name> add /path/to/dsh-better-edit
41
+ ```mermaid
42
+ flowchart TB
43
+ B["before<br/>ve7 │ const a = 1<br/>szJ │ const b = 2<br/>kQm │ const c = 3"] --> X["insert 3 lines above const c"]
44
+ X --> C["after<br/>ve7 │ const a = 1<br/>szJ │ const b = 2<br/>x4n │ const d = 4<br/>r7p │ const e = 5<br/>kQm │ const c = 3"]
45
+ C --> N["kQm still names const c = 3<br/>line numbers would have shifted"]
61
46
  ```
62
47
 
63
- The profile's next session runs with the hashline tools installed. To verify
64
- the layer is active:
48
+ - **Anchors survive edits.** Insert or delete lines above a target and its
49
+ hash is unchanged — a later `edit` by that hash still lands on it. With
50
+ line numbers, every edit above shifts everything below and forces a
51
+ re-read.
52
+ - **Reject-and-serve.** A stale or never-served range is hard-rejected with
53
+ the current `HASH│content` rows echoed back, so the retry needs no `read`.
54
+
55
+ ## Why not `str_replace`?
56
+
57
+ Traditional edit tools ask the model to echo the old code token-for-token
58
+ before stating the replacement (`old_string` + `new_string`). That costs
59
+ `O(replaced text)` tokens per edit **and** is where models fail: the original
60
+ [harness-problem](https://stencil.so/blog/the-harness-problem) post reported
61
+ patch-format failure rates of 46–51% for several models with replace-style
62
+ edits, and a **61% output-token reduction** after switching to anchored
63
+ edits. hashline sends two 3-char anchors instead:
64
+
65
+ | | `str_replace` | hashline `edit` |
66
+ | --- | --- | --- |
67
+ | request | `{ path, old_string, new_string }` | `{ path, remove_from, remove_to, replacement_text }` |
68
+ | replaced text | reproduced verbatim | never sent |
69
+ | range verification | none (first match wins) | every line checked against served state |
70
+ | stale file | old_string may still match — and hit the wrong occurrence | rejected with fresh anchors (`E_RANGE_STALE`) |
71
+ | ambiguous text | first occurrence, silently | boundary anchors verified — call `read` for fresh anchors |
72
+
73
+ ## Benchmark — reproducible
74
+
75
+ `benchmark/run.mjs` measures the model-side token cost of the two patterns on
76
+ the same 103-line file with the same 12 replacements (8 single-line, 4
77
+ multi-line of 3/6/10/15 lines), tokenized with the pinned `js-tiktoken`
78
+ `cl100k_base`:
79
+
80
+ | scenario | lines | hashline | str_replace | saved | % |
81
+ | --- | --- | --- | --- | --- | --- |
82
+ | single-line ×8 | 1 | 311 | 314 | 3 | 1% |
83
+ | multi-line ×4 | 3–15 | 390 | 655 | 265 | **40%** |
84
+ | **TOTAL ×12** | | **701** | **969** | **268** | **28%** |
85
+
86
+ Read traffic is identical for both tools and cancels. These are the model's
87
+ **output** tokens, billed at ~5-6× the input rate — at the 5× rate, hashline
88
+ costs **~1.4× less** on effective cost. Savings scale with the replaced text:
89
+ near parity on short single lines (the anchors' overhead roughly cancels a
90
+ one-line `old_string`), 25–46% on multi-line ranges.
91
+
92
+ Reproduce it yourself — deterministic, self-checking, no build step:
65
93
 
66
94
  ```sh
67
- dsh --profile <name> --dump-config # shows a "# == dsh-better-edit" layer
95
+ npm install # installs js-tiktoken (pinned)
96
+ npm run benchmark # node benchmark/run.mjs
68
97
  ```
69
98
 
70
- ### Requirements
71
-
72
- - Node `^22.19.0 || >=24.0.0` (dsh's requirement; the store uses `node:sqlite`)
73
- - A dsh profile (`dsh plugin` initializes one on first use)
99
+ Full methodology, results, and honest limitations (what the baseline does and
100
+ doesn't model) are in [`benchmark/README.md`](benchmark/README.md).
74
101
 
75
102
  ## Usage
76
103
 
@@ -94,7 +121,8 @@ kQm│}
94
121
  ```
95
122
 
96
123
  1. Keep editing. Anchors for lines you didn't touch stay valid; the post-edit
97
- diff and the auto-read after `write` hand you fresh anchors.
124
+ diff and the auto-read after `write` hand you fresh anchors. A `read` is
125
+ on-demand recovery, not a per-edit ritual.
98
126
 
99
127
  ### The read tool
100
128
 
@@ -134,6 +162,48 @@ still matches the stored post-edit content. A later external write clears the
134
162
  history instead of being overwritten. Undo survives restarts (stored in the
135
163
  hash store).
136
164
 
165
+ ## How it replaces the built-in tools
166
+
167
+ dsh's tool registry resolves per scope: an agent sees `agent → preset →
168
+ global`, and its **own** layer always wins. The built-in `read`/`edit` live on
169
+ the agent-preset layer, so a plain global registration cannot replace them.
170
+ This plugin:
171
+
172
+ 1. Mounts as a host-plane Cordis plugin via its `cordis.patch.yml` bundle
173
+ patch.
174
+ 2. On `agent/session-start`, registers the hashline tools **and** the
175
+ `tool:read` / `tool:edit` prompt sections on the agent's own scope layer —
176
+ they shadow the preset's built-ins for that agent and unwind automatically
177
+ when the agent is disposed.
178
+ 3. Leaves the built-in `write` in place, but a scoped `tools/post-execute`
179
+ listener appends the hashline auto-read to write results.
180
+
181
+ ## Installation
182
+
183
+ From npm:
184
+
185
+ ```sh
186
+ dsh plugin --profile <name> add dsh-better-edit
187
+ ```
188
+
189
+ From a local checkout:
190
+
191
+ ```sh
192
+ dsh plugin --profile <name> add /path/to/dsh-better-edit
193
+ ```
194
+
195
+ The profile's next session runs with the hashline tools installed. To verify
196
+ the layer is active:
197
+
198
+ ```sh
199
+ dsh --profile <name> --dump-config # shows a "# == dsh-better-edit" layer
200
+ ```
201
+
202
+ ### Requirements
203
+
204
+ - Node `^22.19.0 || >=24.0.0` (dsh's requirement; the store uses `node:sqlite`)
205
+ - A dsh profile (`dsh plugin` initializes one on first use)
206
+
137
207
  ## Store
138
208
 
139
209
  Hash snapshots, served-state rows, and undo history live in one SQLite store
@@ -177,6 +247,27 @@ home — treat any pre-0.1.2 undo entries as gone.
177
247
  | `[E_UNDO_UNAVAILABLE]` | Undo history could not be persisted; the edit was not applied. |
178
248
  | `[E_WOULD_EMPTY]` | An edit would empty a non-empty file; use `write` to clear it. |
179
249
 
250
+ ## Inspiration and lineage
251
+
252
+ Hash-anchored editing descends from Can Bölük's
253
+ [*The Harness Problem*](https://stencil.so/blog/the-harness-problem), which
254
+ showed that the harness — not the model — was the bottleneck, and that
255
+ anchored edits beat search-and-replace. This project is a dsh port of:
256
+
257
+ - [**pi-hashline-edit**](https://github.com/RimuruW/pi-hashline-edit) by
258
+ RimuruW — the original pi-coding-agent extension that introduced
259
+ 3-character hashes and collision resolution.
260
+ - [**pi-hashline-edit-pro**](https://github.com/YuGiMob/pi-hashline-edit-pro)
261
+ by YuGiMob — the hardened fork the hashline core here is ported from.
262
+ - [**pi-hashline-edit-lsz**](https://github.com/Rianico/pi-hashline-edit-lsz) —
263
+ the self-maintained fork this project tracks. The hashline core is ported
264
+ byte-for-byte; the tool layer is rewritten on dsh's plugin API.
265
+
266
+ Related reading: [Hash anchors + Myers diff + single-token anchors
267
+ (dirac.run)](https://dirac.run/posts/hash-anchors-myers-diff-single-token)
268
+ (a design review of the O(S+R) → O(R) edit-call saving) and an independent
269
+ [hashline-vs-replace benchmark](https://nwyin.com/blogs/hashline-vs-replace-edit-bench.html).
270
+
180
271
  ## Development
181
272
 
182
273
  ```sh
@@ -184,12 +275,13 @@ npm install
184
275
  npm run typecheck # tsc --noEmit
185
276
  npm test # vitest run
186
277
  npm run build # tsc → lib/
278
+ npm run benchmark # reproducible token-cost benchmark (benchmark/)
187
279
  ```
188
280
 
189
- The test suite is ported from pi-hashline-edit-lsz (598 tests) and drives the
281
+ The test suite is ported from pi-hashline-edit-lsz (615 tests) and drives the
190
282
  dsh tool builders directly over a local filesystem bridge.
191
283
 
192
284
  ## License
193
285
 
194
286
  MIT — see [LICENSE](LICENSE). Ported from pi-hashline-edit-lsz (MIT), which
195
- itself carries the upstream copyrights of RimuruW and Yugimob.
287
+ itself carries the upstream copyrights of RimuruW and YuGiMob.
package/lib/drift.js CHANGED
@@ -92,7 +92,7 @@ export async function scanDrift(input) {
92
92
  const result = computeDrift({ ...input, reported });
93
93
  if (!result || result.allAlreadyReported)
94
94
  return result?.text;
95
- await recordServed(input.sessionKey, input.path, result.rows.map((row) => ({ position: row.position, hash: row.hash })));
95
+ await recordServed(input.sessionKey, input.path, result.rows.map((row) => ({ position: row.position, hash: row.hash })), input.resultLines.length);
96
96
  await markDriftReported(input.sessionKey, input.path, result.rows.filter((row) => row.drifted).map((row) => row.hash));
97
97
  return result.text;
98
98
  }
@@ -124,7 +124,7 @@ export async function execPipeline(io, params, cwd, options) {
124
124
  catch (error) {
125
125
  if (error instanceof AnchorMismatchError ||
126
126
  error instanceof ServedRejectionError) {
127
- await recordEchoServes(sessionKey, absolutePath, error.servedRows, policy);
127
+ await recordEchoServes(sessionKey, absolutePath, error.servedRows, policy, originalHashes.length);
128
128
  }
129
129
  throw error;
130
130
  }
@@ -113,8 +113,8 @@ export function verifyServedRange(args) {
113
113
  }
114
114
  }
115
115
  }
116
- export async function recordEchoServes(sessionKey, path, rows, policy) {
116
+ export async function recordEchoServes(sessionKey, path, rows, policy, lineCount) {
117
117
  if (policy !== "live")
118
118
  return;
119
- await recordServed(sessionKey, path, rows);
119
+ await recordServed(sessionKey, path, rows, lineCount);
120
120
  }
package/lib/sandbox.js CHANGED
@@ -9,8 +9,8 @@
9
9
  * under `workspace-write` even though the built-in `write` succeeds there.
10
10
  * @module dsh-better-edit/sandbox
11
11
  */
12
- import { FsError } from '@deepseek-ai/dsh-fs';
13
- import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, validateEscalationArgs, } from '@deepseek-ai/dsh-sandbox';
12
+ import { FsError } from "@deepseek-ai/dsh-fs";
13
+ import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, validateEscalationArgs, } from "@deepseek-ai/dsh-sandbox";
14
14
  /**
15
15
  * The filesystem escalation API: advertisement gating, per-call policy
16
16
  * resolution, the one-approved wider retry, and denial-marker mapping. A pure
@@ -26,9 +26,12 @@ export class FsSandboxController {
26
26
  this.ctx = ctx;
27
27
  const defaultMode = ctx.fs.sandboxMode;
28
28
  this.escalationModes = defaultMode === undefined ? [] : ESCALATION_TARGETS;
29
- this.policy = defaultMode === undefined ? undefined : ctx.get('sandboxPolicy');
29
+ this.policy =
30
+ defaultMode === undefined
31
+ ? undefined
32
+ : ctx.get("sandboxPolicy");
30
33
  if (defaultMode !== undefined && this.policy === undefined) {
31
- throw new Error('dsh-better-edit: the mounted filesystem confines but ctx.sandboxPolicy is missing');
34
+ throw new Error("dsh-better-edit: the mounted filesystem confines but ctx.sandboxPolicy is missing");
32
35
  }
33
36
  }
34
37
  /**
@@ -40,15 +43,15 @@ export class FsSandboxController {
40
43
  schemaFields() {
41
44
  return {
42
45
  sandbox_permissions: {
43
- type: 'string',
46
+ type: "string",
44
47
  enum: [...this.escalationModes],
45
- description: 'The wider sandbox mode this file operation needs. Only valid as a one-shot retry '
46
- + 'of an operation the sandbox just denied; requires justification and user approval.',
48
+ description: "The wider sandbox mode this file operation needs. Only valid as a one-shot retry " +
49
+ "of an operation the sandbox just denied; requires justification and user approval.",
47
50
  },
48
51
  justification: {
49
- type: 'string',
50
- description: 'Required with sandbox_permissions: one sentence for the user explaining '
51
- + 'why this exact file operation needs the wider access.',
52
+ type: "string",
53
+ description: "Required with sandbox_permissions: one sentence for the user explaining " +
54
+ "why this exact file operation needs the wider access.",
52
55
  },
53
56
  };
54
57
  }
@@ -66,16 +69,24 @@ export class FsSandboxController {
66
69
  */
67
70
  async resolvePolicy(toolName, args, exec) {
68
71
  validateEscalationArgs(args.sandbox_permissions, args.justification);
69
- const standingPolicy = this.policy?.resolve({ ...exec.agent ? { session: exec.agent.session } : {} });
70
- if (args.sandbox_permissions === undefined || args.justification === undefined) {
72
+ const standingPolicy = this.policy?.resolve({
73
+ ...(exec.agent ? { session: exec.agent.session } : {}),
74
+ });
75
+ if (args.sandbox_permissions === undefined ||
76
+ args.justification === undefined) {
71
77
  return standingPolicy;
72
78
  }
73
79
  if (this.escalationModes.length === 0) {
74
- throw new Error('sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)');
80
+ throw new Error("sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)");
75
81
  }
76
82
  const policy = standingPolicy;
77
- const approvedMode = await approveEscalation({ requestedMode: args.sandbox_permissions, justification: args.justification, effectiveMode: policy.mode, subject: 'operation' }, {
78
- approver: this.ctx.get('approval'),
83
+ const approvedMode = await approveEscalation({
84
+ requestedMode: args.sandbox_permissions,
85
+ justification: args.justification,
86
+ effectiveMode: policy.mode,
87
+ subject: "operation",
88
+ }, {
89
+ approver: this.ctx.get("approval"),
79
90
  agent: exec.agent,
80
91
  callId: exec.callId,
81
92
  toolName,
@@ -89,9 +100,9 @@ export class FsSandboxController {
89
100
  * hint, keeping the structured code. Any other error passes through.
90
101
  */
91
102
  mapError(error, policy) {
92
- if (!(error instanceof FsError) || error.code !== 'FS_SANDBOX_DENIED')
103
+ if (!(error instanceof FsError) || error.code !== "FS_SANDBOX_DENIED")
93
104
  return error;
94
105
  const mode = policy.mode;
95
- return new FsError(`${sandboxDenialMarker(mode)}\n${escalationHintMarker('operation')}`, 'FS_SANDBOX_DENIED', { cause: error });
106
+ return new FsError(`${sandboxDenialMarker(mode)}\n${escalationHintMarker("operation")}`, "FS_SANDBOX_DENIED", { cause: error });
96
107
  }
97
108
  }
@@ -62,11 +62,39 @@ export function upsertServed(store, sessionKey, path, entries) {
62
62
  store.stmts.servedUpsert(sessionKey, path, JSON.stringify(updated), Date.now());
63
63
  });
64
64
  }
65
- export function recordServes(store, sessionKey, path, rows) {
65
+ export function recordServes(store, sessionKey, path, rows, lineCount) {
66
66
  if (rows.length === 0)
67
67
  return;
68
68
  try {
69
- upsertServed(store, sessionKey, path, rows);
69
+ if (lineCount === undefined) {
70
+ upsertServed(store, sessionKey, path, rows);
71
+ return;
72
+ }
73
+ // A serve of the CURRENT file state must never leave hashes at
74
+ // positions beyond the file's line count: a stale tail would hold a
75
+ // surviving line's hash at its OLD position while the new serve holds
76
+ // it at its current one, and the duplicate makes every later edit on
77
+ // that line fail E_RANGE_UNVERIFIED ("served at N positions").
78
+ withStore(() => {
79
+ const updated = getServed(store, sessionKey, path).slice();
80
+ if (updated.length > lineCount)
81
+ updated.length = lineCount;
82
+ for (const entry of rows) {
83
+ if (!Number.isInteger(entry.position) || entry.position < 0) {
84
+ throw new TypeError(`Invalid served position: ${entry.position}`);
85
+ }
86
+ if (entry.hash !== null &&
87
+ (typeof entry.hash !== "string" || !HASH_RE.test(entry.hash))) {
88
+ throw new TypeError(`Invalid served hash: ${String(entry.hash)}`);
89
+ }
90
+ while (updated.length <= entry.position)
91
+ updated.push(null);
92
+ updated[entry.position] = entry.hash;
93
+ }
94
+ while (updated.length > 0 && updated[updated.length - 1] === null)
95
+ updated.pop();
96
+ store.stmts.servedUpsert(sessionKey, path, JSON.stringify(updated), Date.now());
97
+ });
70
98
  }
71
99
  catch (error) {
72
100
  console.error("Failed to record served rows:", error);
@@ -165,12 +193,12 @@ export async function loadServed(sessionKey, path) {
165
193
  const store = await loadHashStore();
166
194
  return getServed(store, sessionKey, path);
167
195
  }
168
- export async function recordServed(sessionKey, path, rows) {
196
+ export async function recordServed(sessionKey, path, rows, lineCount) {
169
197
  if (rows.length === 0)
170
198
  return;
171
199
  try {
172
200
  const store = await loadHashStore();
173
- recordServes(store, sessionKey, path, rows);
201
+ recordServes(store, sessionKey, path, rows, lineCount);
174
202
  }
175
203
  catch (error) {
176
204
  console.error('Failed to record served rows:', error);
@@ -167,7 +167,7 @@ async function processFile(io, items, _cwd, opts) {
167
167
  ? error.servedRows
168
168
  : echoRowsForItem(edit, originalHashes);
169
169
  if (echoRows) {
170
- await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live");
170
+ await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live", originalHashes.length);
171
171
  }
172
172
  const echoBlock = echoRows
173
173
  ? ` Current on-disk range for edits[${item.index}] (unchanged — nothing was written):\n${fmtServedRows(echoRows, originalLines)}`
@@ -196,7 +196,7 @@ async function processFile(io, items, _cwd, opts) {
196
196
  const originalLines = splitLines(originalNormalized);
197
197
  const echoRows = echoRowsForItem(edit, originalHashes);
198
198
  if (echoRows) {
199
- await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live");
199
+ await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live", originalHashes.length);
200
200
  }
201
201
  throw new Error(`[E_NOOP_LOOP] edits[${item.index}] (${item.path}): this exact edit (anchors ${item.remove_from} to ${item.remove_to}) has been submitted ${count} times and produced no changes each time — the range already contains the replacement text. Do not resend it; it will never change the file. The whole batch was rejected and nothing was written.` +
202
202
  (echoRows
package/lib/tool-edit.js CHANGED
@@ -75,7 +75,7 @@ export function buildEditTool(io, sandbox) {
75
75
  if (count >= NOOP_LOOP_THRESHOLD) {
76
76
  const echoRows = buildRangeEcho(range.startLine, range.endLine, originalHashes);
77
77
  const echo = fmtServedRows(echoRows, splitLines(originalNormalized));
78
- await recordEchoServes(sessionKey, absolutePath, echoRows, "live");
78
+ await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
79
79
  throw new Error(`[E_NOOP_LOOP] This exact edit (anchors ${canonical.remove_from} to ${canonical.remove_to} in ${path}) has been submitted ${count} times and produced no changes each time — the range already contains the replacement text. Do not resend this edit; it will never change the file. Current range:\n${echo}`);
80
80
  }
81
81
  if (count === 2) {
@@ -141,7 +141,8 @@ export function buildEditTool(io, sandbox) {
141
141
  driftNotice,
142
142
  };
143
143
  const changed = buildChanged(successInput);
144
- if (changed.details.servedRows && changed.details.servedRows.length > 0) {
144
+ if (changed.details.servedRows &&
145
+ changed.details.servedRows.length > 0) {
145
146
  await recordServedTruncated(sessionKey, absolutePath, changed.details.servedRows, splitLines(result).length, range.startLine - 1);
146
147
  }
147
148
  return changed.content[0].text;
package/lib/tool-read.js CHANGED
@@ -71,7 +71,7 @@ export function buildReadTool(io) {
71
71
  });
72
72
  const preview = await fmtReadPreview(normalized, { offset: canonical.offset, limit: canonical.limit }, fileHashes, absolutePath);
73
73
  if (preview.served.length > 0) {
74
- await recordServed(sessionKey, absolutePath, preview.served);
74
+ await recordServed(sessionKey, absolutePath, preview.served, fileHashes.length);
75
75
  }
76
76
  await clearDriftReported(sessionKey, absolutePath);
77
77
  // Record the present observation with the fs policy gate so later
@@ -40,4 +40,4 @@ export interface ResolvedRange {
40
40
  delta: number;
41
41
  }
42
42
  export type ServeRecordPolicy = "live" | "preview";
43
- export declare function recordEchoServes(sessionKey: string, path: string, rows: ServedRow[], policy: ServeRecordPolicy): Promise<void>;
43
+ export declare function recordEchoServes(sessionKey: string, path: string, rows: ServedRow[], policy: ServeRecordPolicy, lineCount?: number): Promise<void>;
@@ -9,9 +9,9 @@
9
9
  * under `workspace-write` even though the built-in `write` succeeds there.
10
10
  * @module dsh-better-edit/sandbox
11
11
  */
12
- import type { Context } from '@deepseek-ai/cordis';
13
- import type { ToolExecution } from '@deepseek-ai/dsh-tools';
14
- import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox';
12
+ import type { Context } from "@deepseek-ai/cordis";
13
+ import type { ToolExecution } from "@deepseek-ai/dsh-tools";
14
+ import type { SandboxExecutionPolicy, SandboxMode } from "@deepseek-ai/dsh-sandbox";
15
15
  /** The two escalation arguments a mutating tool may carry (advertised only under a confining backend). */
16
16
  export interface FsEscalationArgs {
17
17
  sandbox_permissions?: string;
@@ -20,12 +20,12 @@ export interface FsEscalationArgs {
20
20
  /** The schema fields for the escalation arguments, spread into a tool's `parameters` when a confining backend is mounted. */
21
21
  export interface EscalationSchemaFields {
22
22
  sandbox_permissions: {
23
- type: 'string';
23
+ type: "string";
24
24
  enum: string[];
25
25
  description: string;
26
26
  };
27
27
  justification: {
28
- type: 'string';
28
+ type: "string";
29
29
  description: string;
30
30
  };
31
31
  }
@@ -17,7 +17,7 @@ export declare function upsertServed(store: HashStore, sessionKey: string, path:
17
17
  export declare function recordServes(store: HashStore, sessionKey: string, path: string, rows: Array<{
18
18
  position: number;
19
19
  hash: string | null;
20
- }>): void;
20
+ }>, lineCount?: number): void;
21
21
  /**
22
22
  * Record post-mutation diff serves against the file's CURRENT length. Before
23
23
  * upserting the diff rows, positions beyond `lineCount` are dropped from the
@@ -41,7 +41,7 @@ export declare function clearReported(store: HashStore, sessionKey: string, path
41
41
  export declare function deleteServed(store: HashStore, sessionKey: string, path: string): void;
42
42
  export declare function wipeServed(store: HashStore, sessionKey: string): void;
43
43
  export declare function loadServed(sessionKey: string, path: string): Promise<(string | null)[]>;
44
- export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[]): Promise<void>;
44
+ export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[], lineCount?: number): Promise<void>;
45
45
  /**
46
46
  * Async sibling of {@link recordServesTruncated}: record post-mutation diff
47
47
  * rows against the file's current line count.
package/lib/write-hook.js CHANGED
@@ -53,7 +53,7 @@ export function registerWriteHook(rootCtx, agentCtx, io) {
53
53
  });
54
54
  const preview = await fmtReadPreview(normalized, {}, fileHashes, absolutePath);
55
55
  if (preview.served.length > 0) {
56
- await recordServed(sessionKey, absolutePath, preview.served);
56
+ await recordServed(sessionKey, absolutePath, preview.served, fileHashes.length);
57
57
  }
58
58
  await clearDriftReported(sessionKey, absolutePath);
59
59
  const text = hadUtf8DecodeErrors
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-better-edit",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "description": "Hash-anchored read/edit/batch_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",
@@ -50,10 +50,10 @@
50
50
  }
51
51
  },
52
52
  "dependencies": {
53
+ "@deepseek-ai/dsh-sandbox": "^0.1.0-rc.6",
53
54
  "diff": "^8.0.2",
54
55
  "file-type": "^21.3.0",
55
- "xxhash-wasm": "^1.1.0",
56
- "@deepseek-ai/dsh-sandbox": "^0.1.0-rc.6"
56
+ "xxhash-wasm": "^1.1.0"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "@deepseek-ai/cordis": "^4.0.0",
@@ -71,7 +71,8 @@
71
71
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
72
72
  "test": "vitest run",
73
73
  "test:watch": "vitest",
74
- "prepublishOnly": "npm run typecheck && npm test"
74
+ "prepublishOnly": "npm run typecheck && npm test",
75
+ "benchmark": "node benchmark/run.mjs"
75
76
  },
76
77
  "devDependencies": {
77
78
  "@deepseek-ai/cordis": "^4.0.1",
@@ -82,6 +83,7 @@
82
83
  "@deepseek-ai/dsh-tools": "0.1.0-rc.6",
83
84
  "@types/node": "^24.0.0",
84
85
  "@vitest/coverage-v8": "^4.1.10",
86
+ "js-tiktoken": "1.0.21",
85
87
  "typescript": "^5.8.0",
86
88
  "vitest": "^4.1.8"
87
89
  }