dsh-better-edit 0.3.0 → 0.3.2

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 (74) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +9 -5
  3. package/README.zh.md +1 -2
  4. package/lib/constants.js +3 -1
  5. package/lib/contract.js +133 -76
  6. package/lib/drift.js +5 -98
  7. package/lib/dsh-context.js +2 -24
  8. package/lib/edit-engine.js +6 -5
  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 +446 -23
  14. package/lib/fs-bridge.js +39 -1
  15. package/lib/guidance/materialize.js +25 -4
  16. package/lib/guidance/resolve.js +3 -9
  17. package/lib/hash-store.js +6 -3
  18. package/lib/hashline/alphabet.js +2 -6
  19. package/lib/hashline/anchor-pipeline.js +770 -7
  20. package/lib/hashline/apply.js +2 -223
  21. package/lib/hashline/hash-assign.js +248 -13
  22. package/lib/hashline/hash.js +67 -29
  23. package/lib/hashline/hasher.js +2 -23
  24. package/lib/hashline/index.js +7 -1
  25. package/lib/hashline/parse.js +2 -35
  26. package/lib/hashline/pure.js +2 -213
  27. package/lib/hashline/resolve.js +3 -366
  28. package/lib/hashline/served.js +2 -120
  29. package/lib/index.js +0 -2
  30. package/lib/mutation.js +218 -10
  31. package/lib/noop-guard.js +20 -0
  32. package/lib/preview-controller.js +65 -0
  33. package/lib/prompts.js +14 -20
  34. package/lib/read-render.js +3 -139
  35. package/lib/served-store.js +2 -216
  36. package/lib/session-view.js +309 -11
  37. package/lib/tool-edit.js +71 -125
  38. package/lib/tool-undo.js +11 -5
  39. package/lib/truncate.js +3 -95
  40. package/lib/types/constants.d.ts +2 -0
  41. package/lib/types/contract.d.ts +102 -28
  42. package/lib/types/drift.d.ts +5 -29
  43. package/lib/types/dsh-context.d.ts +2 -20
  44. package/lib/types/edit-pipeline.d.ts +3 -44
  45. package/lib/types/file-kind.d.ts +6 -18
  46. package/lib/types/file-reader.d.ts +4 -45
  47. package/lib/types/file-view.d.ts +99 -34
  48. package/lib/types/guidance/materialize.d.ts +3 -3
  49. package/lib/types/guidance/resolve.d.ts +2 -2
  50. package/lib/types/hashline/alphabet.d.ts +1 -5
  51. package/lib/types/hashline/anchor-pipeline.d.ts +111 -10
  52. package/lib/types/hashline/apply.d.ts +1 -22
  53. package/lib/types/hashline/hash-assign.d.ts +25 -19
  54. package/lib/types/hashline/hash.d.ts +8 -9
  55. package/lib/types/hashline/hasher.d.ts +1 -8
  56. package/lib/types/hashline/index.d.ts +7 -1
  57. package/lib/types/hashline/parse.d.ts +1 -7
  58. package/lib/types/hashline/pure.d.ts +1 -26
  59. package/lib/types/hashline/resolve.d.ts +1 -63
  60. package/lib/types/hashline/served.d.ts +1 -43
  61. package/lib/types/mutation.d.ts +63 -10
  62. package/lib/types/noop-guard.d.ts +29 -0
  63. package/lib/types/preview-controller.d.ts +33 -0
  64. package/lib/types/prompts.d.ts +9 -9
  65. package/lib/types/read-render.d.ts +3 -18
  66. package/lib/types/served-store.d.ts +2 -81
  67. package/lib/types/session-view.d.ts +68 -9
  68. package/lib/types/tool-edit.d.ts +3 -14
  69. package/lib/types/truncate.d.ts +3 -29
  70. package/lib/types/validation.d.ts +6 -7
  71. package/lib/types/workspace.d.ts +2 -21
  72. package/lib/validation.js +6 -33
  73. package/lib/workspace.js +2 -27
  74. package/package.json +2 -2
@@ -7,10 +7,10 @@
7
7
  * + recording drift rows) — a side effect hidden inside a "notice" module.
8
8
  *
9
9
  * This seam co-locates that invariant. Public surface:
10
- * view(sessionKey, path) → {served, reported}
10
+ * view(sessionKey, path) -> {served, reported}
11
11
  * recordRead(sessionKey, path, rows, lineCount)
12
12
  * recordEdit(sessionKey, path, rows, lineCount, clearFrom)
13
- * scanDrift(sessionKey, path, resultHashes, resultLines, range) → notice?
13
+ * scanDrift(sessionKey, path, resultHashes, resultLines, range) -> notice?
14
14
  * servedPositionsOf, currentPositionOfDrifted, _mergeServedRows (via served-store)
15
15
  *
16
16
  * Explicit Workspace note: loadHashStore(cwd) now requires cwd. The
@@ -20,15 +20,313 @@
20
20
  * via served-store still fall back to workspaceCwd() for backwards compat
21
21
  * but are marked deprecated.
22
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
+ *
23
28
  * @module dsh-better-edit/session-view
24
29
  */
25
- // --- served state (persistence seam) ---
26
- export { sessionKeyFor, _mergeServedRows, loadServed, recordServed, recordServedTruncated, driftReported, markDriftReported, clearDriftReported, wipeServedState, servedPositionsOf, currentPositionOfDrifted, } from "./served-store.js";
27
- // --- drift (pure + IO) ---
28
- export { computeDrift, scanDrift, DRIFT_NOTICE_HEADING } from "./drift.js";
29
- // --- explicit workspace (re-export for seam visibility) ---
30
- export { withWorkspace, workspaceCwd } from "./workspace.js";
31
- export { execCwd, execSessionKey } from "./dsh-context.js";
32
- export { configDir, hashStorePath, resolveTarget } from "./paths.js";
33
- // Re-export hash-store explicit-cwd API as part of this seam's persistence note
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) ---
34
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
+ }
package/lib/tool-edit.js CHANGED
@@ -1,38 +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 { normalizeRequest as normReq, assertEditRequest, pathSchema, removeFromSchema, removeToSchema, replacementTextSchema } from "./contract.js";
10
- import { abortIf, isRec, splitLines } from "./utils.js";
11
- import { enforceNoopLoop, commit, resolveMissingPath, } from "./mutation.js";
12
- import { applySingle, snapshotIdFor, } from "./mutation.js";
13
- import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
14
- import { buildNoop, buildChanged } from "./mutation.js";
15
- import { recordServedTruncated } from "./session-view.js";
9
+ import { normalizeRequest as normReq, assertEditRequest, } from "./contract.js";
10
+ import { abortIf } from "./utils.js";
11
+ import { execute } from "./mutation.js";
16
12
  import { EDIT_DESCRIPTION } from "./prompts.js";
17
13
  import { execCwd, execSessionKey } from "./session-view.js";
18
14
  import { withWorkspace } from "./session-view.js";
19
- /**
20
- * Register the hash-anchored `edit` tool on the calling agent's scope.
21
- * @param _rootCtx - host context (logger, lifecycle).
22
- * @param agentCtx - the agent's scoped context; registrations here land on the
23
- * agent's OWN scope layer, shadowing the preset's built-in `edit`.
24
- * @param io - the filesystem bridge (ctx.fs backed in deployment).
25
- * @returns the exact disposer that unregisters the tool.
26
- */
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
+ }
27
42
  export function buildEditTool(io, sandbox) {
28
43
  return defineTool({
29
44
  name: "edit",
30
45
  description: EDIT_DESCRIPTION,
31
46
  parameters: {
32
- path: pathSchema,
33
- remove_from: removeFromSchema,
34
- remove_to: removeToSchema,
35
- 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
+ },
36
58
  ...(sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}),
37
59
  },
38
60
  output: {
@@ -45,117 +67,41 @@ export function buildEditTool(io, sandbox) {
45
67
  const sessionKey = execSessionKey(exec);
46
68
  const signal = exec.signal;
47
69
  const canonical = normReq(args);
48
- const resolution = isRec(canonical)
49
- ? await resolveMissingPath(canonical)
50
- : undefined;
51
- if (resolution && isRec(canonical)) {
52
- canonical.path = resolution.path;
53
- }
54
70
  assertEditRequest(canonical);
55
- const sandboxPolicy = await sandbox.resolvePolicy("edit", canonical, exec);
56
- const normalizedParams = canonical;
57
- const path = normalizedParams.path;
58
- abortIf(signal);
59
- const pipeline = await applySingle(io, normalizedParams, cwd, {
60
- signal,
61
- sessionKey,
62
- });
63
- const { originalNormalized, originalHashes, result, bom, originalEnding, hadUtf8DecodeErrors, warnings, noopEdit, firstChangedLine, lastChangedLine, resultHashes, totalAddedLines, totalRemovedLines, driftNotice, range, absolutePath, } = pipeline;
64
- if (resolution) {
65
- warnings.unshift(resolution.warning);
66
- }
67
- const editsAttempted = 1;
68
- if (originalNormalized === result) {
69
- const payload = noopPayloadKey(absolutePath, canonical.remove_from, canonical.remove_to, canonical.replacement_text);
70
- const count = trackNoopPayload(absolutePath, payload);
71
- const notice = await enforceNoopLoop({
72
- absolutePath,
73
- removeFrom: canonical.remove_from,
74
- removeTo: canonical.remove_to,
75
- replacementText: canonical.replacement_text,
76
- displayPath: path,
77
- count,
78
- sessionKey,
79
- originalHashes,
80
- originalNormalized,
81
- range,
82
- });
83
- if (notice)
84
- warnings.push(notice);
85
- const noopSnapshotId = await snapshotIdFor(io, absolutePath, signal);
86
- const noopResult = buildNoop({
87
- path,
88
- noopEdit,
89
- snapshotId: noopSnapshotId,
90
- editMeta: {
91
- editsAttempted,
92
- noopEditsCount: noopEdit ? 1 : 0,
93
- addedLines: 0,
94
- removedLines: 0,
95
- },
96
- warnings,
97
- driftNotice,
98
- });
99
- return noopResult.content[0].text;
100
- }
101
- clearNoopLoop(absolutePath);
102
- if (hadUtf8DecodeErrors) {
103
- 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
+ }
104
83
  }
84
+ const sandboxPolicy = await sandbox.resolvePolicy("edit", { path: resolvedPath, edits: req.edits }, exec);
105
85
  abortIf(signal);
106
- await commit({
107
- io,
108
- files: [
109
- {
110
- absolutePath,
111
- displayPath: path,
112
- originalNormalized,
113
- bom,
114
- originalEnding,
115
- originalHashes,
116
- result,
117
- },
118
- ],
119
- exec,
120
- sandbox,
121
- sandboxPolicy,
122
- signal,
123
- 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.`,
124
- restoreUnwrittenUndos: true,
125
- });
126
- const updatedSnapshotId = await snapshotIdFor(io, absolutePath, signal);
127
- const editMeta = {
128
- editsAttempted,
129
- noopEditsCount: noopEdit ? 1 : 0,
130
- firstChangedLine,
131
- lastChangedLine,
132
- addedLines: totalAddedLines,
133
- removedLines: totalRemovedLines,
134
- };
135
- const successInput = {
136
- path,
137
- originalNormalized,
138
- originalHashes,
139
- result,
140
- resultHashes,
141
- warnings,
142
- snapshotId: updatedSnapshotId,
143
- editMeta,
144
- driftNotice,
145
- };
146
- const changed = buildChanged(successInput);
147
- if (changed.details.servedRows &&
148
- changed.details.servedRows.length > 0) {
149
- 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
+ });
150
98
  }
151
- 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 });
152
101
  });
153
102
  },
154
103
  });
155
104
  }
156
- /**
157
- * Register the hashline tool on the calling agent’s scope (own layer).
158
- */
159
105
  export function registerEditTool(_rootCtx, agentCtx, io, sandbox) {
160
106
  return agentCtx.tools.register(buildEditTool(io, sandbox));
161
107
  }
package/lib/tool-undo.js CHANGED
@@ -10,7 +10,8 @@ import { cntDiff, splitLines } from "./utils.js";
10
10
  import { assertUndoRequest } from "./contract.js";
11
11
  import { normalizeRequest as normReq } from "./contract.js";
12
12
  import { upsertSnapshotFor } from "./hash-store.js";
13
- import { contentChecksum, lineHashes } from "./hashline/hash-assign.js";
13
+ import { contentChecksum } from "./hashline/hash-assign.js";
14
+ import { lineHashes } from "./hashline/hash.js";
14
15
  import { changedRange } from "./hashline/anchor-pipeline.js";
15
16
  import { getUndo, clearUndo } from "./undo-edit.js";
16
17
  import { recordServedTruncated } from "./session-view.js";
@@ -49,6 +50,7 @@ export function buildUndoTool(io, sandbox) {
49
50
  assertUndoRequest(canonical);
50
51
  const path = canonical.path;
51
52
  const absolutePath = await io.resolve(path, cwd, signal);
53
+ // SAFETY: canonical validated by assertUndoRequest; shape is compatible with FsEscalationArgs (path + optional sandbox fields) — narrowing for sandbox.resolvePolicy
52
54
  const sandboxPolicy = await sandbox.resolvePolicy("undo_last_edit", canonical, exec);
53
55
  const undo = await getUndo(absolutePath);
54
56
  if (!undo) {
@@ -62,14 +64,14 @@ export function buildUndoTool(io, sandbox) {
62
64
  const message = error instanceof Error ? error.message : String(error);
63
65
  if (message.includes("[E_NOT_FOUND]")) {
64
66
  await clearUndo(absolutePath);
65
- return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file no longer exists. Call read() to inspect the current state.`;
67
+ return `[E_UNDO_STALE] cannot undo on ${path}: file no longer exists.`;
66
68
  }
67
69
  throw error;
68
70
  }
69
71
  if (currentRaw !==
70
72
  undo.bom + restoreEndings(undo.resultContent, undo.originalEnding)) {
71
73
  await clearUndo(absolutePath);
72
- return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file was modified after the edit, so undoing would overwrite those changes. Call read() to inspect the current state.`;
74
+ return `[E_UNDO_STALE] cannot undo on ${path}: file modified after edit — undo would overwrite changes.`;
73
75
  }
74
76
  const { text: currentStripped } = stripBOM(currentRaw);
75
77
  const currentNormalized = toLF(currentStripped);
@@ -79,6 +81,10 @@ export function buildUndoTool(io, sandbox) {
79
81
  const linesRemovedByEdit = cntDiff(diffResult.diff, "-");
80
82
  const undoDiffResult = genDiff(currentNormalized, undo.content, 1, undo.hashes, currentHashes);
81
83
  const undoDiff = undoDiffResult.diff;
84
+ const undoDenseRows = [];
85
+ for (let i = 0; i < undo.hashes.length; i++) {
86
+ undoDenseRows.push({ position: i, hash: undo.hashes[i] });
87
+ }
82
88
  const restoredRange = changedRange(currentNormalized, undo.content);
83
89
  try {
84
90
  await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal, exec, sandboxPolicy);
@@ -98,8 +104,8 @@ export function buildUndoTool(io, sandbox) {
98
104
  parts.push(`Removed ${linesAddedByEdit} line(s) that were added and restored ${linesRemovedByEdit} line(s) that were removed.`);
99
105
  }
100
106
  parts.push("File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits.");
101
- if (undoDiffResult.servedRows.length > 0) {
102
- await recordServedTruncated(sessionKey, absolutePath, undoDiffResult.servedRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? 0);
107
+ if (undoDenseRows.length > 0) {
108
+ await recordServedTruncated(sessionKey, absolutePath, undoDenseRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? undoDiffResult.firstChangedLine ?? 0);
103
109
  }
104
110
  return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
105
111
  });