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.
Files changed (85) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +317 -240
  3. package/README.zh.md +19 -11
  4. package/lib/constants.js +3 -1
  5. package/lib/contract.js +159 -63
  6. package/lib/drift.js +5 -98
  7. package/lib/dsh-context.js +2 -24
  8. package/lib/edit-engine.js +9 -8
  9. package/lib/edit-pipeline.js +3 -121
  10. package/lib/edit-response.js +16 -8
  11. package/lib/file-kind.js +6 -121
  12. package/lib/file-reader.js +4 -77
  13. package/lib/file-view.js +486 -0
  14. package/lib/guidance/index.js +8 -0
  15. package/lib/guidance/materialize.js +212 -0
  16. package/lib/guidance/parse.js +80 -0
  17. package/lib/guidance/resolve.js +116 -0
  18. package/lib/guidance.js +6 -388
  19. package/lib/hash-store.js +6 -4
  20. package/lib/hashline/alphabet.js +2 -6
  21. package/lib/hashline/anchor-pipeline.js +786 -0
  22. package/lib/hashline/apply.js +2 -223
  23. package/lib/hashline/hash-assign.js +255 -0
  24. package/lib/hashline/hash.js +67 -29
  25. package/lib/hashline/hasher.js +2 -23
  26. package/lib/hashline/index.js +9 -4
  27. package/lib/hashline/parse.js +2 -35
  28. package/lib/hashline/pure.js +2 -213
  29. package/lib/hashline/resolve.js +3 -361
  30. package/lib/hashline/served.js +2 -120
  31. package/lib/index.js +1 -3
  32. package/lib/mutation.js +266 -0
  33. package/lib/noop-guard.js +20 -0
  34. package/lib/preview-controller.js +65 -0
  35. package/lib/prompts.js +14 -20
  36. package/lib/read-and-serve.js +23 -23
  37. package/lib/read-render.js +3 -139
  38. package/lib/served-store.js +2 -216
  39. package/lib/session-view.js +332 -0
  40. package/lib/tool-batch-edit.js +9 -10
  41. package/lib/tool-edit.js +73 -129
  42. package/lib/tool-read.js +3 -5
  43. package/lib/tool-undo.js +16 -10
  44. package/lib/truncate.js +3 -95
  45. package/lib/types/constants.d.ts +2 -0
  46. package/lib/types/contract.d.ts +120 -15
  47. package/lib/types/drift.d.ts +5 -29
  48. package/lib/types/dsh-context.d.ts +2 -20
  49. package/lib/types/edit-engine.d.ts +2 -2
  50. package/lib/types/edit-pipeline.d.ts +3 -44
  51. package/lib/types/file-kind.d.ts +6 -18
  52. package/lib/types/file-reader.d.ts +4 -45
  53. package/lib/types/file-view.d.ts +139 -0
  54. package/lib/types/guidance/index.d.ts +8 -0
  55. package/lib/types/guidance/materialize.d.ts +23 -0
  56. package/lib/types/guidance/parse.d.ts +36 -0
  57. package/lib/types/guidance/resolve.d.ts +55 -0
  58. package/lib/types/guidance.d.ts +6 -127
  59. package/lib/types/hashline/alphabet.d.ts +1 -5
  60. package/lib/types/hashline/anchor-pipeline.d.ts +127 -0
  61. package/lib/types/hashline/apply.d.ts +1 -22
  62. package/lib/types/hashline/hash-assign.d.ts +25 -0
  63. package/lib/types/hashline/hash.d.ts +8 -9
  64. package/lib/types/hashline/hasher.d.ts +1 -8
  65. package/lib/types/hashline/index.d.ts +12 -4
  66. package/lib/types/hashline/parse.d.ts +1 -7
  67. package/lib/types/hashline/pure.d.ts +1 -26
  68. package/lib/types/hashline/resolve.d.ts +1 -58
  69. package/lib/types/hashline/served.d.ts +1 -43
  70. package/lib/types/mutation.d.ts +131 -0
  71. package/lib/types/noop-guard.d.ts +29 -0
  72. package/lib/types/preview-controller.d.ts +33 -0
  73. package/lib/types/prompts.d.ts +9 -9
  74. package/lib/types/read-and-serve.d.ts +6 -5
  75. package/lib/types/read-render.d.ts +3 -18
  76. package/lib/types/served-store.d.ts +2 -81
  77. package/lib/types/session-view.d.ts +92 -0
  78. package/lib/types/tool-edit.d.ts +3 -14
  79. package/lib/types/truncate.d.ts +3 -29
  80. package/lib/types/validation.d.ts +6 -7
  81. package/lib/types/workspace.d.ts +2 -21
  82. package/lib/validation.js +6 -33
  83. package/lib/workspace.js +2 -27
  84. package/lib/write-hook.js +2 -2
  85. package/package.json +2 -2
@@ -0,0 +1,332 @@
1
+ /**
2
+ * SessionView — deep module owning served rows + drift + position reconstruction.
3
+ *
4
+ * Previously split: served-store (merge invariant, persistence via hash-store)
5
+ * and drift (pure computeDrift + IO scanDrift that reads+writes served state).
6
+ * The drift notice both *reads* served state and *writes* it (marking reported
7
+ * + recording drift rows) — a side effect hidden inside a "notice" module.
8
+ *
9
+ * This seam co-locates that invariant. Public surface:
10
+ * view(sessionKey, path) -> {served, reported}
11
+ * recordRead(sessionKey, path, rows, lineCount)
12
+ * recordEdit(sessionKey, path, rows, lineCount, clearFrom)
13
+ * scanDrift(sessionKey, path, resultHashes, resultLines, range) -> notice?
14
+ * servedPositionsOf, currentPositionOfDrifted, _mergeServedRows (via served-store)
15
+ *
16
+ * Explicit Workspace note: loadHashStore(cwd) now requires cwd. The
17
+ * AsyncLocalStorage magic in workspace.ts is @internal — new code should pass
18
+ * cwd explicitly through read-and-serve / edit-pipeline / drift. Forgetting
19
+ * cwd is now a compile error where callers use this seam; legacy callers
20
+ * via served-store still fall back to workspaceCwd() for backwards compat
21
+ * but are marked deprecated.
22
+ *
23
+ * Ownership: This file now OWNS the served-merge invariant
24
+ * (_mergeServedRows), the position-reconstruction math, and the drift
25
+ * computation. Deleting it would scatter the served+drift invariant
26
+ * across 4 files — it concentrates (deep).
27
+ *
28
+ * @module dsh-better-edit/session-view
29
+ */
30
+ import { randomUUID } from "node:crypto";
31
+ import { AsyncLocalStorage } from "node:async_hooks";
32
+ import { HASH_RE } from "./hashline/hash-assign.js";
33
+ import { loadHashStore, withStore } from "./hash-store.js";
34
+ import { SERVED_ECHO_CAP } from "./constants.js";
35
+ import { fmtServedRows } from "./hashline/served.js";
36
+ import { configDir, hashStorePath, resolveTarget } from "./paths.js";
37
+ // --- workspace (private to this seam, @internal) ---
38
+ const current = new AsyncLocalStorage();
39
+ export function withWorkspace(cwd, fn) {
40
+ return current.run(cwd, fn);
41
+ }
42
+ export function workspaceCwd() {
43
+ return current.getStore();
44
+ }
45
+ // --- dsh-context (private to this seam) ---
46
+ let fallbackSessionKey;
47
+ export function sessionKeyFor(sessionId) {
48
+ if (sessionId && sessionId.length > 0)
49
+ return sessionId;
50
+ // fallback for previews/tests
51
+ return fallbackSessionKey ??= randomUUID();
52
+ }
53
+ export function execCwd(exec) {
54
+ return exec.agent?.session.header.cwd ?? process.cwd();
55
+ }
56
+ export function execSessionKey(exec) {
57
+ return sessionKeyFor(exec.agent?.session.id);
58
+ }
59
+ // --- paths re-export (seam visibility) ---
60
+ export { configDir, hashStorePath, resolveTarget };
61
+ // --- hash-store re-export (persistence note) ---
62
+ export { loadHashStore, shutdownHashStore, withStore } from "./hash-store.js";
63
+ /**
64
+ * Merge served rows into a copy of the stored array. This single helper owns
65
+ * the served-merge invariant shared by recordServed and recordServedTruncated.
66
+ * Eagerly heals orphaned serves: if the same hash is written at a new position
67
+ * the old position is nulled (O(n) scan, no extra I/O). This prevents a
68
+ * partial re-serve from leaving a stale duplicate behind (ADR-0008).
69
+ */
70
+ export function _mergeServedRows(current, rows, options) {
71
+ const updated = current.slice();
72
+ if (options?.truncateTo !== undefined && updated.length > options.truncateTo) {
73
+ updated.length = options.truncateTo;
74
+ }
75
+ if (options?.clearFrom !== undefined) {
76
+ for (let i = options.clearFrom; i < updated.length; i++)
77
+ updated[i] = null;
78
+ }
79
+ // Build index of existing hashes and heal duplicates already in the array
80
+ const index = new Map();
81
+ for (let i = 0; i < updated.length; i++) {
82
+ const h = updated[i];
83
+ if (h === null)
84
+ continue;
85
+ const prev = index.get(h);
86
+ if (prev !== undefined) {
87
+ updated[prev] = null;
88
+ }
89
+ index.set(h, i);
90
+ }
91
+ for (const entry of rows) {
92
+ if (!Number.isInteger(entry.position) || entry.position < 0) {
93
+ throw new TypeError(`Invalid served position: ${entry.position}`);
94
+ }
95
+ if (entry.hash !== null && (typeof entry.hash !== "string" || !HASH_RE.test(entry.hash))) {
96
+ throw new TypeError(`Invalid served hash: ${String(entry.hash)}`);
97
+ }
98
+ while (updated.length <= entry.position)
99
+ updated.push(null);
100
+ if (entry.hash !== null) {
101
+ const existing = index.get(entry.hash);
102
+ if (existing !== undefined && existing !== entry.position) {
103
+ updated[existing] = null;
104
+ index.delete(entry.hash);
105
+ }
106
+ const oldAtPos = updated[entry.position];
107
+ if (oldAtPos !== null && oldAtPos !== entry.hash) {
108
+ index.delete(oldAtPos);
109
+ }
110
+ index.set(entry.hash, entry.position);
111
+ }
112
+ else {
113
+ const oldAtPos = updated[entry.position];
114
+ if (oldAtPos !== null)
115
+ index.delete(oldAtPos);
116
+ }
117
+ updated[entry.position] = entry.hash;
118
+ }
119
+ while (updated.length > 0 && updated[updated.length - 1] === null)
120
+ updated.pop();
121
+ return updated;
122
+ }
123
+ export async function loadServed(sessionKey, path) {
124
+ const store = await loadHashStore();
125
+ return store.getServed(sessionKey, path);
126
+ }
127
+ export async function recordServed(sessionKey, path, rows, lineCount) {
128
+ if (rows.length === 0)
129
+ return;
130
+ try {
131
+ const store = await loadHashStore();
132
+ withStore(() => {
133
+ const current = store.getServed(sessionKey, path);
134
+ const updated = _mergeServedRows(current, rows, lineCount === undefined ? undefined : { truncateTo: lineCount });
135
+ if (current.length === updated.length && current.every((v, i) => v === updated[i]))
136
+ return;
137
+ store.upsertServed(sessionKey, path, JSON.stringify(updated));
138
+ });
139
+ }
140
+ catch (error) {
141
+ console.error("Failed to record served rows:", error);
142
+ }
143
+ }
144
+ export async function recordServedTruncated(sessionKey, path, rows, lineCount, clearFrom = 0) {
145
+ if (rows.length === 0)
146
+ return;
147
+ try {
148
+ const store = await loadHashStore();
149
+ withStore(() => {
150
+ const current = store.getServed(sessionKey, path);
151
+ const updated = _mergeServedRows(current, rows, { truncateTo: lineCount, clearFrom });
152
+ // Avoid no-op writes (perf: O(1) check, no extra I/O beyond current read)
153
+ if (current.length === updated.length && current.every((v, i) => v === updated[i]))
154
+ return;
155
+ store.upsertServed(sessionKey, path, JSON.stringify(updated));
156
+ });
157
+ }
158
+ catch (error) {
159
+ console.error("Failed to record truncated served rows:", error);
160
+ }
161
+ }
162
+ export async function driftReported(sessionKey, path) {
163
+ try {
164
+ const store = await loadHashStore();
165
+ return store.getServedReported(sessionKey, path);
166
+ }
167
+ catch (error) {
168
+ console.error("Failed to load reported drift set:", error);
169
+ return new Set();
170
+ }
171
+ }
172
+ export async function markDriftReported(sessionKey, path, hashes) {
173
+ try {
174
+ const valid = hashes.filter((hash) => HASH_RE.test(hash));
175
+ if (valid.length === 0)
176
+ return;
177
+ const store = await loadHashStore();
178
+ withStore(() => {
179
+ const current = store.getServedReported(sessionKey, path);
180
+ for (const hash of valid)
181
+ current.add(hash);
182
+ store.upsertServedReported(sessionKey, path, JSON.stringify([...current]));
183
+ });
184
+ }
185
+ catch (error) {
186
+ console.error("Failed to record reported drift set:", error);
187
+ }
188
+ }
189
+ export async function clearDriftReported(sessionKey, path) {
190
+ try {
191
+ const store = await loadHashStore();
192
+ withStore(() => {
193
+ store.clearServedReported(sessionKey, path);
194
+ });
195
+ }
196
+ catch (error) {
197
+ console.error("Failed to clear reported drift set:", error);
198
+ }
199
+ }
200
+ export async function wipeServedState(sessionKey) {
201
+ try {
202
+ const store = await loadHashStore();
203
+ store.wipeServed(sessionKey);
204
+ }
205
+ catch (error) {
206
+ console.error("Failed to wipe served state:", error);
207
+ }
208
+ }
209
+ export function servedPositionsOf(served, hash) {
210
+ const out = [];
211
+ for (let i = 0; i < served.length; i++) {
212
+ if (served[i] === hash)
213
+ out.push(i);
214
+ }
215
+ return out;
216
+ }
217
+ function nearestSurvivingPosition(served, surviving, from, direction) {
218
+ if (direction === "below") {
219
+ for (let q = from - 1; q >= 0; q--) {
220
+ const hash = served[q];
221
+ if (hash !== null && surviving.has(hash))
222
+ return q;
223
+ }
224
+ return undefined;
225
+ }
226
+ for (let q = from + 1; q < served.length; q++) {
227
+ const hash = served[q];
228
+ if (hash !== null && surviving.has(hash))
229
+ return q;
230
+ }
231
+ return undefined;
232
+ }
233
+ export function currentPositionOfDrifted(served, currentPositions, surviving, servedIndex, delta) {
234
+ const below = nearestSurvivingPosition(served, surviving, servedIndex, "below");
235
+ if (below !== undefined)
236
+ return currentPositions.get(served[below]) + 1;
237
+ const above = nearestSurvivingPosition(served, surviving, servedIndex, "above");
238
+ if (above !== undefined)
239
+ return currentPositions.get(served[above]) - 1;
240
+ return servedIndex + delta;
241
+ }
242
+ export const DRIFT_NOTICE_HEADING = "drift:";
243
+ export function computeDrift(input) {
244
+ const { served, resultHashes, resultLines, range, reported, cap = SERVED_ECHO_CAP } = input;
245
+ const resultHashSet = new Set(resultHashes);
246
+ const currentPosOfHash = new Map();
247
+ for (let i = 0; i < resultHashes.length; i++) {
248
+ currentPosOfHash.set(resultHashes[i], i);
249
+ }
250
+ const startPositions = servedPositionsOf(served, range.startHash);
251
+ const endPositions = servedPositionsOf(served, range.endHash);
252
+ let servedStartIdx;
253
+ let servedEndIdx;
254
+ if (startPositions.length === 1 && endPositions.length === 1) {
255
+ servedStartIdx = startPositions[0];
256
+ servedEndIdx = endPositions[0];
257
+ }
258
+ else {
259
+ servedStartIdx = range.startLine - 1;
260
+ servedEndIdx = range.endLine - 1;
261
+ }
262
+ const rangeFrom = Math.min(servedStartIdx, servedEndIdx);
263
+ const rangeTo = Math.max(servedStartIdx, servedEndIdx);
264
+ let total = 0;
265
+ let unshown = 0;
266
+ let anyNotReported = false;
267
+ const driftedPositions = [];
268
+ for (let p = 0; p < served.length; p++) {
269
+ const servedHash = served[p];
270
+ if (servedHash === null)
271
+ continue;
272
+ if (p >= rangeFrom && p <= rangeTo)
273
+ continue;
274
+ if (resultHashSet.has(servedHash))
275
+ continue;
276
+ total++;
277
+ if (!reported.has(servedHash))
278
+ anyNotReported = true;
279
+ const currentPos = currentPositionOfDrifted(served, currentPosOfHash, resultHashSet, p, range.delta);
280
+ if (currentPos >= 0 && currentPos < resultHashes.length && currentPos < resultLines.length) {
281
+ driftedPositions.push(currentPos);
282
+ }
283
+ else {
284
+ unshown++;
285
+ }
286
+ }
287
+ if (total === 0)
288
+ return undefined;
289
+ const countLabel = `${total} line(s)`;
290
+ if (!anyNotReported) {
291
+ return {
292
+ text: `${DRIFT_NOTICE_HEADING} ${countLabel} changed outside the range (already reported) — re-read to refresh.`,
293
+ rows: [],
294
+ total,
295
+ allAlreadyReported: true,
296
+ };
297
+ }
298
+ const driftedSet = new Set(driftedPositions);
299
+ const windowSet = new Set();
300
+ for (const pos of driftedPositions) {
301
+ for (const w of [pos - 1, pos, pos + 1]) {
302
+ if (w >= 0 && w < resultLines.length)
303
+ windowSet.add(w);
304
+ }
305
+ }
306
+ const windowPositions = [...windowSet].sort((a, b) => a - b);
307
+ const shownPositions = windowPositions.slice(0, cap);
308
+ unshown += windowPositions.length - shownPositions.length;
309
+ const rows = shownPositions.map((position) => ({
310
+ position,
311
+ hash: resultHashes[position],
312
+ content: resultLines[position],
313
+ drifted: driftedSet.has(position),
314
+ }));
315
+ const rowsText = fmtServedRows(rows, resultLines);
316
+ const moreText = unshown > 0 ? `\n[... ${unshown} more — re-read to see]` : "";
317
+ return {
318
+ text: `${DRIFT_NOTICE_HEADING} ${countLabel} changed outside the range:\n${rowsText}${moreText}`,
319
+ rows,
320
+ total,
321
+ allAlreadyReported: false,
322
+ };
323
+ }
324
+ export async function scanDrift(input) {
325
+ const reported = await driftReported(input.sessionKey, input.path);
326
+ const result = computeDrift({ ...input, reported });
327
+ if (!result || result.allAlreadyReported)
328
+ return result?.text;
329
+ await recordServed(input.sessionKey, input.path, result.rows.map((row) => ({ position: row.position, hash: row.hash })), input.resultLines.length);
330
+ await markDriftReported(input.sessionKey, input.path, result.rows.filter((row) => row.drifted).map((row) => row.hash));
331
+ return result.text;
332
+ }
@@ -9,15 +9,14 @@
9
9
  */
10
10
  import { defineTool } from "@deepseek-ai/dsh-tools";
11
11
  import { abortIf, isRec, normalizeFilePath, splitLines, } from "./utils.js";
12
- import { assertBatchEditRequest, } from "./contract.js";
13
- import { normReq } from "./edit-normalize.js";
14
- import { persistUndoAndWrite, resolveMissingPath, runFileEdits, } from "./edit-engine.js";
15
- import { buildBatchResult } from "./edit-response.js";
16
- import { recordServedTruncated } from "./served-store.js";
12
+ import { assertBatchEditRequest, normalizeRequest as normReq, } from "./contract.js";
13
+ import { commit, resolveMissingPath, applySequence, } from "./mutation.js";
14
+ import { buildBatchResult } from "./mutation.js";
15
+ import { recordServedTruncated } from "./session-view.js";
17
16
  import { BATCH_EDIT_DESCRIPTION } from "./prompts.js";
18
- import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema, } from "./schema.js";
19
- import { execCwd, execSessionKey } from "./dsh-context.js";
20
- import { withWorkspace } from "./workspace.js";
17
+ import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema, } from "./contract.js";
18
+ import { execCwd, execSessionKey } from "./session-view.js";
19
+ import { withWorkspace } from "./session-view.js";
21
20
  async function prepareItems(io, params, cwd, signal) {
22
21
  const items = [];
23
22
  for (let index = 0; index < params.edits.length; index++) {
@@ -141,12 +140,12 @@ export function buildBatchEditTool(io, sandbox) {
141
140
  const processed = [];
142
141
  for (const groupItems of groups.values()) {
143
142
  abortIf(signal);
144
- processed.push(await runFileEdits(io, groupItems, {
143
+ processed.push(await applySequence(io, groupItems, {
145
144
  signal,
146
145
  sessionKey,
147
146
  }));
148
147
  }
149
- await persistUndoAndWrite({
148
+ await commit({
150
149
  io,
151
150
  files: processed
152
151
  .filter((file) => file.appliedCount > 0)
package/lib/tool-edit.js CHANGED
@@ -1,40 +1,60 @@
1
1
  /**
2
2
  * The dsh `edit` tool: hash-anchored literal range edits that shadow the
3
- * built-in `edit` on the agent's own scope layer. Registered through the
4
- * agent context so the model-facing contract (remove_from/remove_to hashes,
5
- * served-range verification, reject-and-serve) replaces the built-in one.
3
+ * built-in `edit` on the agent's own scope layer. Now the sole mutation tool
4
+ * (batch_edit removed, ADR-0007): payload is { path: string|null, edits: [[remove_from,remove_to,replacement_text],...] }
5
+ * single-file atomic batch, null path inference via anchors.
6
6
  * @module dsh-better-edit/tool-edit
7
7
  */
8
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
- import { normReq } from "./edit-normalize.js";
10
- import { abortIf, isRec, splitLines } from "./utils.js";
11
- import { assertEditRequest } from "./contract.js";
12
- import { enforceNoopLoop, persistUndoAndWrite, resolveMissingPath, } from "./edit-engine.js";
13
- import { execPipeline, snapshotIdFor, } from "./edit-pipeline.js";
14
- import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
15
- import { buildNoop, buildChanged } from "./edit-response.js";
16
- import { recordServedTruncated } from "./served-store.js";
9
+ import { normalizeRequest as normReq, assertEditRequest, } from "./contract.js";
10
+ import { abortIf } from "./utils.js";
11
+ import { execute } from "./mutation.js";
17
12
  import { EDIT_DESCRIPTION } from "./prompts.js";
18
- import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema, } from "./schema.js";
19
- import { execCwd, execSessionKey } from "./dsh-context.js";
20
- import { withWorkspace } from "./workspace.js";
21
- /**
22
- * Register the hash-anchored `edit` tool on the calling agent's scope.
23
- * @param _rootCtx - host context (logger, lifecycle).
24
- * @param agentCtx - the agent's scoped context; registrations here land on the
25
- * agent's OWN scope layer, shadowing the preset's built-in `edit`.
26
- * @param io - the filesystem bridge (ctx.fs backed in deployment).
27
- * @returns the exact disposer that unregisters the tool.
28
- */
13
+ import { execCwd, execSessionKey } from "./session-view.js";
14
+ import { withWorkspace } from "./session-view.js";
15
+ import { findSnapshotPathsByHashes } from "./hash-store.js";
16
+ import { parseHashRef } from "./hashline/anchor-pipeline.js";
17
+ async function resolveNullPath(edits) {
18
+ if (edits.length === 0)
19
+ return undefined;
20
+ const first = edits[0];
21
+ try {
22
+ const h1 = parseHashRef(first.remove_from).hash;
23
+ const h2 = parseHashRef(first.remove_to).hash;
24
+ const matches = await findSnapshotPathsByHashes([h1, h2]);
25
+ if (matches.length === 1) {
26
+ return {
27
+ path: matches[0],
28
+ warning: `[E_BAD_SHAPE] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
29
+ };
30
+ }
31
+ if (matches.length > 1) {
32
+ throw new Error(`[E_BAD_SHAPE] Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(", ")}. Include the intended path.`);
33
+ }
34
+ }
35
+ catch (e) {
36
+ if (e instanceof Error && e.message.startsWith("[E_BAD_SHAPE]"))
37
+ throw e;
38
+ return undefined;
39
+ }
40
+ return undefined;
41
+ }
29
42
  export function buildEditTool(io, sandbox) {
30
43
  return defineTool({
31
44
  name: "edit",
32
45
  description: EDIT_DESCRIPTION,
33
46
  parameters: {
34
- path: pathSchema,
35
- remove_from: removeFromSchema,
36
- remove_to: removeToSchema,
37
- replacement_text: replacementTextSchema,
47
+ path: {
48
+ oneOf: [
49
+ { type: "string", description: "File path; null infers it from anchors" },
50
+ { type: "null", description: "null infers path from anchors" },
51
+ ],
52
+ },
53
+ edits: {
54
+ type: "array",
55
+ description: "Ordered list of edit tuples [remove_from, remove_to, replacement_text] — one edit per tuple, single-file atomic",
56
+ items: { type: "json", description: "[remove_from, remove_to, replacement_text]" },
57
+ },
38
58
  ...(sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}),
39
59
  },
40
60
  output: {
@@ -47,117 +67,41 @@ export function buildEditTool(io, sandbox) {
47
67
  const sessionKey = execSessionKey(exec);
48
68
  const signal = exec.signal;
49
69
  const canonical = normReq(args);
50
- const resolution = isRec(canonical)
51
- ? await resolveMissingPath(canonical)
52
- : undefined;
53
- if (resolution && isRec(canonical)) {
54
- canonical.path = resolution.path;
55
- }
56
70
  assertEditRequest(canonical);
57
- const sandboxPolicy = await sandbox.resolvePolicy("edit", canonical, exec);
58
- const normalizedParams = canonical;
59
- const path = normalizedParams.path;
60
- abortIf(signal);
61
- const pipeline = await execPipeline(io, normalizedParams, cwd, {
62
- signal,
63
- sessionKey,
64
- });
65
- const { originalNormalized, originalHashes, result, bom, originalEnding, hadUtf8DecodeErrors, warnings, noopEdit, firstChangedLine, lastChangedLine, resultHashes, totalAddedLines, totalRemovedLines, driftNotice, range, absolutePath, } = pipeline;
66
- if (resolution) {
67
- warnings.unshift(resolution.warning);
68
- }
69
- const editsAttempted = 1;
70
- if (originalNormalized === result) {
71
- const payload = noopPayloadKey(absolutePath, canonical.remove_from, canonical.remove_to, canonical.replacement_text);
72
- const count = trackNoopPayload(absolutePath, payload);
73
- const notice = await enforceNoopLoop({
74
- absolutePath,
75
- removeFrom: canonical.remove_from,
76
- removeTo: canonical.remove_to,
77
- replacementText: canonical.replacement_text,
78
- displayPath: path,
79
- count,
80
- sessionKey,
81
- originalHashes,
82
- originalNormalized,
83
- range,
84
- });
85
- if (notice)
86
- warnings.push(notice);
87
- const noopSnapshotId = await snapshotIdFor(io, absolutePath, signal);
88
- const noopResult = buildNoop({
89
- path,
90
- noopEdit,
91
- snapshotId: noopSnapshotId,
92
- editMeta: {
93
- editsAttempted,
94
- noopEditsCount: noopEdit ? 1 : 0,
95
- addedLines: 0,
96
- removedLines: 0,
97
- },
98
- warnings,
99
- driftNotice,
100
- });
101
- return noopResult.content[0].text;
102
- }
103
- clearNoopLoop(absolutePath);
104
- if (hadUtf8DecodeErrors) {
105
- warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
71
+ const req = canonical;
72
+ let resolvedPath = req.path;
73
+ let pathWarning;
74
+ if (resolvedPath === null) {
75
+ const resolved = await resolveNullPath(req.edits);
76
+ if (resolved) {
77
+ resolvedPath = resolved.path;
78
+ pathWarning = resolved.warning;
79
+ }
80
+ else {
81
+ throw new Error("[E_BAD_SHAPE] Edit request path is null and could not be inferred from anchors — anchors match no known file. Include the intended path.");
82
+ }
106
83
  }
84
+ const sandboxPolicy = await sandbox.resolvePolicy("edit", { path: resolvedPath, edits: req.edits }, exec);
107
85
  abortIf(signal);
108
- await persistUndoAndWrite({
109
- io,
110
- files: [
111
- {
112
- absolutePath,
113
- displayPath: path,
114
- originalNormalized,
115
- bom,
116
- originalEnding,
117
- originalHashes,
118
- result,
119
- },
120
- ],
121
- exec,
122
- sandbox,
123
- sandboxPolicy,
124
- signal,
125
- undoUnavailableMessage: (displayPath) => `[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the edit was NOT applied and ${displayPath} is unchanged. Retry the edit, or use write if the store cannot be recovered.`,
126
- restoreUnwrittenUndos: true,
127
- });
128
- const updatedSnapshotId = await snapshotIdFor(io, absolutePath, signal);
129
- const editMeta = {
130
- editsAttempted,
131
- noopEditsCount: noopEdit ? 1 : 0,
132
- firstChangedLine,
133
- lastChangedLine,
134
- addedLines: totalAddedLines,
135
- removedLines: totalRemovedLines,
136
- };
137
- const successInput = {
138
- path,
139
- originalNormalized,
140
- originalHashes,
141
- result,
142
- resultHashes,
143
- warnings,
144
- snapshotId: updatedSnapshotId,
145
- editMeta,
146
- driftNotice,
147
- };
148
- const changed = buildChanged(successInput);
149
- if (changed.details.servedRows &&
150
- changed.details.servedRows.length > 0) {
151
- await recordServedTruncated(sessionKey, absolutePath, changed.details.servedRows, splitLines(result).length, range.startLine - 1);
86
+ const items = [];
87
+ for (let index = 0; index < req.edits.length; index++) {
88
+ const e = req.edits[index];
89
+ items.push({
90
+ index,
91
+ path: resolvedPath,
92
+ absolutePath: await io.resolve(resolvedPath, cwd, signal),
93
+ remove_from: e.remove_from,
94
+ remove_to: e.remove_to,
95
+ replacement_text: e.replacement_text,
96
+ pathWarning: index === 0 ? pathWarning : undefined,
97
+ });
152
98
  }
153
- return changed.content[0].text;
99
+ // Deep seam: one interface, all lifecycle branching concentrates in Mutation
100
+ return execute({ io, items, sessionKey, signal, exec, sandbox, sandboxPolicy });
154
101
  });
155
102
  },
156
103
  });
157
104
  }
158
- /**
159
- * Register the hashline tool on the calling agent’s scope (own layer).
160
- */
161
105
  export function registerEditTool(_rootCtx, agentCtx, io, sandbox) {
162
106
  return agentCtx.tools.register(buildEditTool(io, sandbox));
163
107
  }
package/lib/tool-read.js CHANGED
@@ -6,13 +6,11 @@
6
6
  * @module dsh-better-edit/tool-read
7
7
  */
8
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
- import { normReq } from "./edit-normalize.js";
10
- import { assertReadRequest } from "./contract.js";
9
+ import { normalizeRequest as normReq, assertReadRequest, pathSchema } from "./contract.js";
11
10
  import { readAndServe } from "./read-and-serve.js";
12
11
  import { READ_DESCRIPTION } from "./prompts.js";
13
- import { pathSchema } from "./schema.js";
14
- import { execCwd, execSessionKey } from "./dsh-context.js";
15
- import { withWorkspace } from "./workspace.js";
12
+ import { execCwd, execSessionKey } from "./session-view.js";
13
+ import { withWorkspace } from "./session-view.js";
16
14
  /**
17
15
  * Register the hash-anchored `read` tool on the calling agent's scope.
18
16
  * @param _rootCtx - host context.