dsh-better-edit 0.5.0 → 0.6.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 +20 -2
- package/README.md +1 -1
- package/lib/contract.js +1 -1
- package/lib/edit-engine.js +4 -454
- package/lib/edit-response.js +24 -2
- package/lib/encoding.js +308 -0
- package/lib/file-encoding-state.js +263 -0
- package/lib/file-view.js +1 -1
- package/lib/fs-bridge.js +124 -19
- package/lib/hash-store.js +1 -2
- package/lib/hashline/anchor-pipeline.js +19 -165
- package/lib/index.js +2 -2
- package/lib/mutation/engine.js +388 -0
- package/lib/mutation.js +84 -11
- package/lib/paths.js +1 -1
- package/lib/read-and-serve.js +5 -0
- package/lib/session-view.js +16 -49
- package/lib/store/index.js +28 -0
- package/lib/store-config.js +132 -2
- package/lib/store-lifecycle.js +1 -1
- package/lib/tool-edit.js +2 -2
- package/lib/tool-read.js +26 -6
- package/lib/tool-undo.js +2 -2
- package/lib/types/contract.d.ts +1 -0
- package/lib/types/edit-diff.d.ts +1 -1
- package/lib/types/edit-engine.d.ts +4 -176
- package/lib/types/edit-response.d.ts +1 -1
- package/lib/types/encoding.d.ts +46 -0
- package/lib/types/file-encoding-state.d.ts +77 -0
- package/lib/types/file-view.d.ts +2 -1
- package/lib/types/fs-bridge.d.ts +5 -1
- package/lib/types/hashline/anchor-pipeline.d.ts +6 -20
- package/lib/types/hashline/index.d.ts +1 -1
- package/lib/types/mutation/engine.d.ts +143 -0
- package/lib/types/mutation.d.ts +30 -5
- package/lib/types/paths.d.ts +1 -1
- package/lib/types/read-and-serve.d.ts +4 -1
- package/lib/types/session-view.d.ts +16 -30
- package/lib/types/store/index.d.ts +25 -0
- package/lib/types/store-config.d.ts +10 -1
- package/lib/types/workspace-context.d.ts +23 -0
- package/lib/workspace-context.js +44 -0
- package/lib/write-hook.js +2 -1
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,11 +1,29 @@
|
|
|
1
|
+
## [0.6.0](https://github.com/Rianico/dsh-better-edit/compare/v0.5.1...v0.6.0) (2026-08-31)
|
|
2
|
+
|
|
3
|
+
### Features
|
|
4
|
+
|
|
5
|
+
* **edit:** render diff card after tool calling ([df7712c](https://github.com/Rianico/dsh-better-edit/commit/df7712cef265dfec424feefb60c19f833d380f9f))
|
|
6
|
+
* **hashline:** remove boundaryDups auto-fix (Closes [#38](https://github.com/Rianico/dsh-better-edit/issues/38)) ([54d0bc6](https://github.com/Rianico/dsh-better-edit/commit/54d0bc6c9078fbcffa6f7a531e80e005774156a4))
|
|
7
|
+
|
|
8
|
+
### Bug Fixes
|
|
9
|
+
|
|
10
|
+
* **ci:** add neural version check to Verify and Release ([7f85b56](https://github.com/Rianico/dsh-better-edit/commit/7f85b5605e228d19bcde802ce2b10affc90fbde7))
|
|
11
|
+
|
|
12
|
+
## [0.5.1](https://github.com/Rianico/dsh-better-edit/compare/v0.5.0...v0.5.1) (2026-08-30)
|
|
13
|
+
|
|
14
|
+
### Bug Fixes
|
|
15
|
+
|
|
16
|
+
* **encoding:** support non-UTF-8 text files via VS Code model ([#34](https://github.com/Rianico/dsh-better-edit/issues/34)) ([#35](https://github.com/Rianico/dsh-better-edit/issues/35)) ([dd3e553](https://github.com/Rianico/dsh-better-edit/commit/dd3e553a3877e47b08aa2ba6336115e80b5d96f5))
|
|
17
|
+
* **lint:** address biome blockers for release ([00b9270](https://github.com/Rianico/dsh-better-edit/commit/00b92704ac4093a627754e698bb1968acdc3d4e8))
|
|
18
|
+
* remove unused exitHandlerRegistered ([f6a29f3](https://github.com/Rianico/dsh-better-edit/commit/f6a29f3f1dd694e4bb7c55a98d0eba80bc32a58f))
|
|
19
|
+
* **scripts:** map fix to Fixed for Keep a Changelog ([bcd1850](https://github.com/Rianico/dsh-better-edit/commit/bcd18501e280b10d5075108c034de7352ece6922))
|
|
20
|
+
|
|
1
21
|
# Changelog
|
|
2
22
|
|
|
3
23
|
All notable changes to the `dsh-better-edit` plugin will be documented in this file.
|
|
4
24
|
|
|
5
25
|
Entries link to the originating spec issue in [pi-hashline-edit-lsz](https://github.com/Rianico/pi-hashline-edit-lsz) where one exists.
|
|
6
26
|
|
|
7
|
-
## [Unreleased]
|
|
8
|
-
|
|
9
27
|
## [0.5.0] - 2026-08-29
|
|
10
28
|
|
|
11
29
|
### Features
|
package/README.md
CHANGED
|
@@ -124,7 +124,7 @@ Chained edits stay cheap — anchors for untouched lines remain valid, diff/echo
|
|
|
124
124
|
{ "path": "src/main.ts", "edits": [["a1b", "a1b", "new line 1\n"], ["c3d", "c3d", "new line 2"]] }
|
|
125
125
|
```
|
|
126
126
|
|
|
127
|
-
One fails, none write (`[E_BATCH_ABORT]`).
|
|
127
|
+
One fails, none write (`[E_BATCH_ABORT]`). Encoding errors `[E_BAD_ENCODING]`/`[E_DECODE_FAILED]` are also emitted.
|
|
128
128
|
|
|
129
129
|
> [!TIP]
|
|
130
130
|
> **Want proof before you install?** The upstream [23/23 tool battery](https://github.com/Rianico/pi-better-edit/blob/main/benchmarks/README.md) runs with no LLM — stale edits are rejected before they corrupt a file, on every run. Same hashline algorithm, same verification.
|
package/lib/contract.js
CHANGED
|
@@ -64,7 +64,7 @@ function describeReceived(input) {
|
|
|
64
64
|
}
|
|
65
65
|
// ---- filed sets (declared once) ---------------------------------------------
|
|
66
66
|
const EDIT_KS = new Set(["path", "edits", "sandbox_permissions", "justification"]);
|
|
67
|
-
const READ_KS = new Set(["path", "offset", "limit"]);
|
|
67
|
+
const READ_KS = new Set(["path", "offset", "limit", "encoding"]);
|
|
68
68
|
// ---- normalization -----------------------------------------------------------
|
|
69
69
|
/**
|
|
70
70
|
* Normalize `file_path` → `path` alias on the request record and tuple edits → objects.
|
package/lib/edit-engine.js
CHANGED
|
@@ -1,457 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* multi-edit sequencer that drives a whole file's item list against evolving
|
|
5
|
-
* content, the noop-loop guard, and the persist-undo → write → restore
|
|
6
|
-
* transaction both mutating tools run.
|
|
7
|
-
*
|
|
8
|
-
* The model-facing contract lives here unchanged: [E_BATCH_ABORT],
|
|
9
|
-
* [E_NOOP_LOOP], [E_UNDO_UNAVAILABLE] carry byte-identical messages, and
|
|
10
|
-
* reject-and-serve records the same echo serves.
|
|
2
|
+
* @deprecated — private to Mutation seam. Use `from "./mutation/engine.js"` instead.
|
|
3
|
+
* Thin shim re-exporting the engine now owned by Mutation.
|
|
11
4
|
* @module dsh-better-edit/edit-engine
|
|
12
5
|
*/
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
import { scanDrift, loadServed } from "./session-view.js";
|
|
16
|
-
import { applyEdit, resEdit, parseHashRef, } from "./hashline/anchor-pipeline.js";
|
|
17
|
-
import { lineHashes } from "./hashline/hash.js";
|
|
18
|
-
import { MAX_HASH_LINES } from "./hashline/hash-assign.js";
|
|
19
|
-
import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "./hashline/anchor-pipeline.js";
|
|
20
|
-
import { findSnapshotPathsByHashes } from "./hash-store.js";
|
|
21
|
-
import { saveUndo } from "./undo-edit.js";
|
|
22
|
-
import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
|
|
23
|
-
import { NOOP_LOOP_THRESHOLD } from "./constants.js";
|
|
24
|
-
import { abortIf, splitLines } from "./utils.js";
|
|
25
|
-
// ---------------------------------------------------------------------------
|
|
26
|
-
// request / counting helpers shared by both tool paths
|
|
27
|
-
/**
|
|
28
|
-
* Resolve a request's missing `path` from its anchors: the only file whose
|
|
29
|
-
* stored hashes contain both anchors. Returns the path plus an autocorrect
|
|
30
|
-
* warning, or undefined when no resolution is possible.
|
|
31
|
-
*/
|
|
32
|
-
export async function resolveMissingPath(request) {
|
|
33
|
-
if (typeof request.path === "string")
|
|
34
|
-
return undefined;
|
|
35
|
-
const from = request.remove_from;
|
|
36
|
-
const to = request.remove_to;
|
|
37
|
-
if (typeof from !== "string" || typeof to !== "string")
|
|
38
|
-
return undefined;
|
|
39
|
-
const hashes = [];
|
|
40
|
-
for (const ref of [from, to]) {
|
|
41
|
-
try {
|
|
42
|
-
hashes.push(parseHashRef(ref).hash);
|
|
43
|
-
}
|
|
44
|
-
catch {
|
|
45
|
-
return undefined;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
let matches;
|
|
49
|
-
try {
|
|
50
|
-
matches = await findSnapshotPathsByHashes(hashes);
|
|
51
|
-
}
|
|
52
|
-
catch {
|
|
53
|
-
return undefined;
|
|
54
|
-
}
|
|
55
|
-
if (matches.length === 1) {
|
|
56
|
-
return {
|
|
57
|
-
path: matches[0],
|
|
58
|
-
warning: `[E_BAD_SHAPE] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
if (matches.length > 1) {
|
|
62
|
-
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.`);
|
|
63
|
-
}
|
|
64
|
-
return undefined;
|
|
65
|
-
}
|
|
66
|
-
/** The hashes a range edit removes, for stable re-hash bookkeeping. */
|
|
67
|
-
export function collectRemovedHashes(edit, originalHashes) {
|
|
68
|
-
const removedHashes = new Set();
|
|
69
|
-
const startHash = edit.hash_bounds[0].hash;
|
|
70
|
-
const endHash = edit.hash_bounds[1].hash;
|
|
71
|
-
const startLine = originalHashes.indexOf(startHash);
|
|
72
|
-
const endLine = originalHashes.indexOf(endHash);
|
|
73
|
-
if (startLine >= 0 && endLine >= 0) {
|
|
74
|
-
const firstLine = Math.min(startLine, endLine);
|
|
75
|
-
const lastLine = Math.max(startLine, endLine);
|
|
76
|
-
for (let i = firstLine; i <= lastLine; i++) {
|
|
77
|
-
removedHashes.add(originalHashes[i]);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
return removedHashes;
|
|
81
|
-
}
|
|
82
|
-
/** Added/removed line counts for one resolved edit against a file's original hashes. */
|
|
83
|
-
export function countLineChanges(edit, originalHashes, isNoop, removedAutoFixes) {
|
|
84
|
-
if (isNoop)
|
|
85
|
-
return { totalAddedLines: 0, totalRemovedLines: 0 };
|
|
86
|
-
let totalRemovedLines = 0;
|
|
87
|
-
const startLine = originalHashes.indexOf(edit.hash_bounds[0].hash);
|
|
88
|
-
const endLine = originalHashes.indexOf(edit.hash_bounds[1].hash);
|
|
89
|
-
if (startLine >= 0 && endLine >= 0) {
|
|
90
|
-
totalRemovedLines = Math.abs(endLine - startLine) + 1;
|
|
91
|
-
}
|
|
92
|
-
return {
|
|
93
|
-
totalAddedLines: Math.max(0, edit.content_lines.length - removedAutoFixes),
|
|
94
|
-
totalRemovedLines,
|
|
95
|
-
};
|
|
96
|
-
}
|
|
97
|
-
/**
|
|
98
|
-
* One edit against in-memory content: resolve (unless a pre-resolved edit was
|
|
99
|
-
* given) → apply with served verification → stable re-hash → line counts.
|
|
100
|
-
*
|
|
101
|
-
* `onReject` owns the reject-and-serve policy: it receives resolve/verify
|
|
102
|
-
* failures (and the edit that failed, when resolved) and MUST throw. The
|
|
103
|
-
* single path rethrows the original anchor error after recording echo serves;
|
|
104
|
-
* the batch path wraps with [E_BATCH_ABORT] plus the current-range echo.
|
|
105
|
-
*/
|
|
106
|
-
export async function applyOne(input, onReject) {
|
|
107
|
-
let edit;
|
|
108
|
-
if (input.edit) {
|
|
109
|
-
edit = input.edit;
|
|
110
|
-
}
|
|
111
|
-
else {
|
|
112
|
-
try {
|
|
113
|
-
edit = resEdit({
|
|
114
|
-
remove_from: input.removeFrom,
|
|
115
|
-
remove_to: input.removeTo,
|
|
116
|
-
replacement_text: input.replacementText,
|
|
117
|
-
}, input.warnings);
|
|
118
|
-
}
|
|
119
|
-
catch (error) {
|
|
120
|
-
return onReject(error, undefined);
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
let anchorResult;
|
|
124
|
-
try {
|
|
125
|
-
anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served);
|
|
126
|
-
}
|
|
127
|
-
catch (error) {
|
|
128
|
-
if (error instanceof AnchorMismatchError ||
|
|
129
|
-
error instanceof ServedRejectionError) {
|
|
130
|
-
return onReject(error, edit);
|
|
131
|
-
}
|
|
132
|
-
throw error;
|
|
133
|
-
}
|
|
134
|
-
const result = anchorResult.content;
|
|
135
|
-
const noop = result === input.content;
|
|
136
|
-
const removedHashes = noop
|
|
137
|
-
? undefined
|
|
138
|
-
: collectRemovedHashes(edit, input.hashes);
|
|
139
|
-
const resultHashes = noop
|
|
140
|
-
? input.hashes
|
|
141
|
-
: await lineHashes(result, input.absolutePath, {
|
|
142
|
-
content: input.content,
|
|
143
|
-
hashes: input.hashes,
|
|
144
|
-
removedHashes,
|
|
145
|
-
}, input.store, input.persist);
|
|
146
|
-
const { totalAddedLines, totalRemovedLines } = countLineChanges(edit, input.countHashes ?? input.hashes, noop, anchorResult.autoFixes?.length ?? 0);
|
|
147
|
-
return {
|
|
148
|
-
result,
|
|
149
|
-
hashes: resultHashes,
|
|
150
|
-
range: anchorResult.range,
|
|
151
|
-
noop,
|
|
152
|
-
edit,
|
|
153
|
-
noopEdit: anchorResult.noopEdit,
|
|
154
|
-
firstChangedLine: anchorResult.firstChangedLine,
|
|
155
|
-
lastChangedLine: anchorResult.lastChangedLine,
|
|
156
|
-
removedHashes,
|
|
157
|
-
totalAddedLines,
|
|
158
|
-
totalRemovedLines,
|
|
159
|
-
anchorWarnings: anchorResult.warnings,
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* The shared noop-loop guard. Returns the "twice in a row" notice for the
|
|
164
|
-
* caller to append to warnings, or throws [E_NOOP_LOOP] (after recording the
|
|
165
|
-
* echo serves) once the payload has been submitted NOOP_LOOP_THRESHOLD times
|
|
166
|
-
* with no change. Messages are byte-identical to the pre-engine tools.
|
|
167
|
-
*/
|
|
168
|
-
export async function enforceNoopLoop(opts) {
|
|
169
|
-
const { absolutePath, removeFrom, removeTo, displayPath, index, count, sessionKey, originalHashes, } = opts;
|
|
170
|
-
if (index === undefined) {
|
|
171
|
-
if (count >= NOOP_LOOP_THRESHOLD) {
|
|
172
|
-
const echoRows = buildRangeEcho(opts.range.startLine, opts.range.endLine, originalHashes);
|
|
173
|
-
const echo = fmtServedRows(echoRows, splitLines(opts.originalNormalized));
|
|
174
|
-
await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
175
|
-
throw new Error(`[E_NOOP_LOOP] identical edit (${removeFrom} → ${removeTo} in ${displayPath}) submitted ${count}×, no changes each time. Range already contains this text; resend will reject. Current range:\n${echo}`);
|
|
176
|
-
}
|
|
177
|
-
if (count === 2) {
|
|
178
|
-
return `[E_NOOP_LOOP] Notice: identical edit (${removeFrom} → ${removeTo} in ${displayPath}) no-op'd twice; range already has this text. Resend will reject.`;
|
|
179
|
-
}
|
|
180
|
-
return undefined;
|
|
181
|
-
}
|
|
182
|
-
if (count >= NOOP_LOOP_THRESHOLD) {
|
|
183
|
-
const originalLines = splitLines(opts.originalNormalized);
|
|
184
|
-
const echoRows = opts.echoRows;
|
|
185
|
-
if (echoRows) {
|
|
186
|
-
await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
187
|
-
}
|
|
188
|
-
throw new Error(`[E_NOOP_LOOP] edits[${index}] (${displayPath}): identical edit (${removeFrom} → ${removeTo}) submitted ${count}×, no changes each time. Range already has this text; resend will reject the batch.` +
|
|
189
|
-
(echoRows
|
|
190
|
-
? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}`
|
|
191
|
-
: ""));
|
|
192
|
-
}
|
|
193
|
-
if (count === 2) {
|
|
194
|
-
return `[E_NOOP_LOOP] Notice: edits[${index}] (${displayPath}) — identical edit no-op'd twice; range already has this text. Resend will reject the batch.`;
|
|
195
|
-
}
|
|
196
|
-
return undefined;
|
|
197
|
-
}
|
|
198
|
-
// ---------------------------------------------------------------------------
|
|
199
|
-
// per-file sequencer (batch)
|
|
200
|
-
function echoRowsForItem(edit, originalHashes) {
|
|
201
|
-
const startHash = edit.hash_bounds[0].hash;
|
|
202
|
-
const endHash = edit.hash_bounds[1].hash;
|
|
203
|
-
const s = originalHashes.indexOf(startHash);
|
|
204
|
-
const e = originalHashes.indexOf(endHash);
|
|
205
|
-
if (s < 0 || e < 0)
|
|
206
|
-
return undefined;
|
|
207
|
-
return buildRangeEcho(Math.min(s, e) + 1, Math.max(s, e) + 1, originalHashes);
|
|
208
|
-
}
|
|
209
|
-
/**
|
|
210
|
-
* Run a file's item list against freshly-read content with served
|
|
211
|
-
* verification, evolving content/hashes, union range, noop tracking, and a
|
|
212
|
-
* per-file drift notice. All-or-nothing is enforced by the caller's
|
|
213
|
-
* transaction ({@link persistUndoAndWrite}): nothing here writes to disk.
|
|
214
|
-
*/
|
|
215
|
-
export async function runFileEdits(io, items, opts) {
|
|
216
|
-
const first = items[0];
|
|
217
|
-
abortIf(opts.signal);
|
|
218
|
-
const absolutePath = first.absolutePath;
|
|
219
|
-
const rawText = await io.readText(absolutePath, opts.signal);
|
|
220
|
-
const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
|
|
221
|
-
absolutePath,
|
|
222
|
-
rawText,
|
|
223
|
-
displayPath: first.path,
|
|
224
|
-
signal: opts.signal,
|
|
225
|
-
maxLines: MAX_HASH_LINES,
|
|
226
|
-
});
|
|
227
|
-
const served = await loadServed(opts.sessionKey, absolutePath);
|
|
228
|
-
const warnings = [];
|
|
229
|
-
let currentContent = originalNormalized;
|
|
230
|
-
let currentHashes = originalHashes;
|
|
231
|
-
let appliedCount = 0;
|
|
232
|
-
let noopCount = 0;
|
|
233
|
-
let totalAddedLines = 0;
|
|
234
|
-
let totalRemovedLines = 0;
|
|
235
|
-
let unionStartLine = Infinity;
|
|
236
|
-
let unionEndLine = -Infinity;
|
|
237
|
-
let unionStartHash = "";
|
|
238
|
-
let unionEndHash = "";
|
|
239
|
-
let lastApplied;
|
|
240
|
-
for (const item of items) {
|
|
241
|
-
abortIf(opts.signal);
|
|
242
|
-
const applied = await applyOne({
|
|
243
|
-
content: currentContent,
|
|
244
|
-
hashes: currentHashes,
|
|
245
|
-
served,
|
|
246
|
-
removeFrom: item.remove_from,
|
|
247
|
-
removeTo: item.remove_to,
|
|
248
|
-
replacementText: item.replacement_text,
|
|
249
|
-
absolutePath,
|
|
250
|
-
displayPath: item.path,
|
|
251
|
-
signal: opts.signal,
|
|
252
|
-
warnings,
|
|
253
|
-
countHashes: originalHashes,
|
|
254
|
-
persist: false,
|
|
255
|
-
}, async (error, edit) => {
|
|
256
|
-
if (error instanceof AnchorMismatchError ||
|
|
257
|
-
error instanceof ServedRejectionError) {
|
|
258
|
-
const originalLines = splitLines(originalNormalized);
|
|
259
|
-
const echoRows = error.servedRows.length > 0
|
|
260
|
-
? error.servedRows
|
|
261
|
-
: edit
|
|
262
|
-
? echoRowsForItem(edit, originalHashes)
|
|
263
|
-
: undefined;
|
|
264
|
-
if (echoRows) {
|
|
265
|
-
await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
266
|
-
}
|
|
267
|
-
const echoBlock = echoRows
|
|
268
|
-
? ` Current on-disk range for edits[${item.index}] (unchanged — nothing was written):\n${fmtServedRows(echoRows, originalLines)}`
|
|
269
|
-
: " Call read() to get fresh anchors.";
|
|
270
|
-
throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${error.message}${echoBlock}\n` +
|
|
271
|
-
"The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied. Fix the failing edit (and any later edit that depends on it), then resubmit the batch.");
|
|
272
|
-
}
|
|
273
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
274
|
-
throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${message}\n` +
|
|
275
|
-
"The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied.");
|
|
276
|
-
});
|
|
277
|
-
const range = applied.range;
|
|
278
|
-
if (range.startLine < unionStartLine) {
|
|
279
|
-
unionStartLine = range.startLine;
|
|
280
|
-
unionStartHash = range.startHash;
|
|
281
|
-
}
|
|
282
|
-
if (range.endLine > unionEndLine) {
|
|
283
|
-
unionEndLine = range.endLine;
|
|
284
|
-
unionEndHash = range.endHash;
|
|
285
|
-
}
|
|
286
|
-
if (applied.noop) {
|
|
287
|
-
noopCount += 1;
|
|
288
|
-
const payload = noopPayloadKey(absolutePath, item.remove_from, item.remove_to, item.replacement_text);
|
|
289
|
-
const count = trackNoopPayload(absolutePath, payload);
|
|
290
|
-
const notice = await enforceNoopLoop({
|
|
291
|
-
absolutePath,
|
|
292
|
-
removeFrom: item.remove_from,
|
|
293
|
-
removeTo: item.remove_to,
|
|
294
|
-
replacementText: item.replacement_text,
|
|
295
|
-
displayPath: item.path,
|
|
296
|
-
index: item.index,
|
|
297
|
-
count,
|
|
298
|
-
sessionKey: opts.sessionKey,
|
|
299
|
-
originalHashes,
|
|
300
|
-
originalNormalized,
|
|
301
|
-
echoRows: echoRowsForItem(applied.edit, originalHashes),
|
|
302
|
-
});
|
|
303
|
-
if (notice)
|
|
304
|
-
warnings.push(notice);
|
|
305
|
-
warnings.push(`edits[${item.index}] (${item.path}) was a noop: the range already contains the replacement text.`);
|
|
306
|
-
if (applied.anchorWarnings?.length)
|
|
307
|
-
warnings.push(...applied.anchorWarnings);
|
|
308
|
-
continue;
|
|
309
|
-
}
|
|
310
|
-
appliedCount += 1;
|
|
311
|
-
const removedHashes = applied.removedHashes;
|
|
312
|
-
totalAddedLines += applied.totalAddedLines;
|
|
313
|
-
totalRemovedLines += applied.totalRemovedLines;
|
|
314
|
-
lastApplied = {
|
|
315
|
-
content: currentContent,
|
|
316
|
-
hashes: currentHashes,
|
|
317
|
-
removedHashes,
|
|
318
|
-
};
|
|
319
|
-
currentContent = applied.result;
|
|
320
|
-
currentHashes = applied.hashes;
|
|
321
|
-
clearNoopLoop(absolutePath);
|
|
322
|
-
if (applied.anchorWarnings?.length)
|
|
323
|
-
warnings.push(...applied.anchorWarnings);
|
|
324
|
-
}
|
|
325
|
-
const result = currentContent;
|
|
326
|
-
let resultHashes = currentHashes;
|
|
327
|
-
if (appliedCount > 0 && lastApplied) {
|
|
328
|
-
resultHashes = await lineHashes(result, absolutePath, {
|
|
329
|
-
content: lastApplied.content,
|
|
330
|
-
hashes: lastApplied.hashes,
|
|
331
|
-
removedHashes: lastApplied.removedHashes,
|
|
332
|
-
}, undefined, true);
|
|
333
|
-
}
|
|
334
|
-
if (hadUtf8DecodeErrors) {
|
|
335
|
-
warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
|
|
336
|
-
}
|
|
337
|
-
if (first.pathWarning)
|
|
338
|
-
warnings.unshift(first.pathWarning);
|
|
339
|
-
let driftNotice;
|
|
340
|
-
if (appliedCount > 0 && unionStartLine !== Infinity) {
|
|
341
|
-
const resultLines = splitLines(result);
|
|
342
|
-
const originalLines = splitLines(originalNormalized);
|
|
343
|
-
try {
|
|
344
|
-
driftNotice = await scanDrift({
|
|
345
|
-
sessionKey: opts.sessionKey,
|
|
346
|
-
served,
|
|
347
|
-
resultHashes,
|
|
348
|
-
resultLines,
|
|
349
|
-
range: {
|
|
350
|
-
startLine: unionStartLine,
|
|
351
|
-
endLine: unionEndLine,
|
|
352
|
-
startHash: unionStartHash,
|
|
353
|
-
endHash: unionEndHash,
|
|
354
|
-
delta: resultLines.length - originalLines.length,
|
|
355
|
-
},
|
|
356
|
-
path: absolutePath,
|
|
357
|
-
});
|
|
358
|
-
}
|
|
359
|
-
catch (error) {
|
|
360
|
-
console.error("Failed to compute drift notice:", error);
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
return {
|
|
364
|
-
displayPath: first.path,
|
|
365
|
-
absolutePath,
|
|
366
|
-
originalNormalized,
|
|
367
|
-
result,
|
|
368
|
-
bom,
|
|
369
|
-
originalEnding,
|
|
370
|
-
hadUtf8DecodeErrors,
|
|
371
|
-
warnings,
|
|
372
|
-
originalHashes,
|
|
373
|
-
resultHashes,
|
|
374
|
-
appliedCount,
|
|
375
|
-
noopCount,
|
|
376
|
-
totalAddedLines,
|
|
377
|
-
totalRemovedLines,
|
|
378
|
-
driftNotice,
|
|
379
|
-
range: {
|
|
380
|
-
startLine: unionStartLine,
|
|
381
|
-
endLine: unionEndLine,
|
|
382
|
-
startHash: unionStartHash,
|
|
383
|
-
endHash: unionEndHash,
|
|
384
|
-
delta: splitLines(result).length - splitLines(originalNormalized).length,
|
|
385
|
-
},
|
|
386
|
-
};
|
|
387
|
-
}
|
|
388
|
-
/**
|
|
389
|
-
* The persist-undo → write-all → restore-on-failure transaction shared by
|
|
390
|
-
* `edit` (one file) and `batch_edit` (many files). Every file's undo entry is
|
|
391
|
-
* persisted before anything is written; if a write fails, already-written
|
|
392
|
-
* files are restored (original content written back, undo entry restored) and
|
|
393
|
-
* the sandbox-mapped error rethrown.
|
|
394
|
-
*/
|
|
395
|
-
export async function persistUndoAndWrite(opts) {
|
|
396
|
-
const { io, files } = opts;
|
|
397
|
-
const undos = [];
|
|
398
|
-
for (const file of files) {
|
|
399
|
-
const undo = await saveUndo(file.absolutePath, {
|
|
400
|
-
content: file.originalNormalized,
|
|
401
|
-
bom: file.bom,
|
|
402
|
-
originalEnding: file.originalEnding,
|
|
403
|
-
hashes: file.originalHashes,
|
|
404
|
-
resultContent: file.result,
|
|
405
|
-
});
|
|
406
|
-
if (!undo.persisted) {
|
|
407
|
-
for (const u of undos) {
|
|
408
|
-
try {
|
|
409
|
-
await u.restore();
|
|
410
|
-
}
|
|
411
|
-
catch (error) {
|
|
412
|
-
console.error("Failed to restore undo entry after abort:", error);
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
throw new Error(opts.undoUnavailableMessage(file.displayPath));
|
|
416
|
-
}
|
|
417
|
-
undos.push({ file, restore: undo.restore });
|
|
418
|
-
}
|
|
419
|
-
const written = [];
|
|
420
|
-
try {
|
|
421
|
-
for (const u of undos) {
|
|
422
|
-
abortIf(opts.signal);
|
|
423
|
-
await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), opts.signal, opts.exec, opts.sandboxPolicy);
|
|
424
|
-
written.push(u);
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
catch (error) {
|
|
428
|
-
for (const w of written) {
|
|
429
|
-
try {
|
|
430
|
-
await io.writeText(w.file.absolutePath, w.file.bom +
|
|
431
|
-
restoreEndings(w.file.originalNormalized, w.file.originalEnding), undefined, opts.exec, opts.sandboxPolicy);
|
|
432
|
-
}
|
|
433
|
-
catch (restoreError) {
|
|
434
|
-
console.error("Failed to restore file after write failure:", restoreError);
|
|
435
|
-
}
|
|
436
|
-
try {
|
|
437
|
-
await w.restore();
|
|
438
|
-
}
|
|
439
|
-
catch (restoreError) {
|
|
440
|
-
console.error("Failed to restore undo entry after write failure:", restoreError);
|
|
441
|
-
}
|
|
442
|
-
}
|
|
443
|
-
if (opts.restoreUnwrittenUndos) {
|
|
444
|
-
for (const u of undos) {
|
|
445
|
-
if (written.includes(u))
|
|
446
|
-
continue;
|
|
447
|
-
try {
|
|
448
|
-
await u.restore();
|
|
449
|
-
}
|
|
450
|
-
catch (restoreError) {
|
|
451
|
-
console.error("Failed to restore undo entry after write failure:", restoreError);
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
throw opts.sandbox.mapError(error, opts.sandboxPolicy);
|
|
456
|
-
}
|
|
457
|
-
}
|
|
6
|
+
export * from "./mutation/engine.js";
|
|
7
|
+
export { persistUndoAndWrite, commit, commitSingle, commitBatch } from "./mutation.js";
|
package/lib/edit-response.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { genDiff } from "./edit-diff.js";
|
|
2
|
+
import { truncateHead, formatSize } from "./file-view.js";
|
|
2
3
|
import { visLines, clipLine } from "./utils.js";
|
|
3
4
|
export function buildMetrics(args) {
|
|
4
5
|
const metrics = {
|
|
@@ -37,6 +38,23 @@ export function finalizeToolResult(details) {
|
|
|
37
38
|
function warnBlock(warnings) {
|
|
38
39
|
return warnings?.length ? `\n\n${warnings.join("\n")}` : "";
|
|
39
40
|
}
|
|
41
|
+
const DIFF_CARD_MAX_LINES = 400;
|
|
42
|
+
const DIFF_CARD_MAX_BYTES = 80 * 1024;
|
|
43
|
+
function formatDiffCard(diff) {
|
|
44
|
+
if (!diff || diff.trim().length === 0)
|
|
45
|
+
return "";
|
|
46
|
+
const truncation = truncateHead(diff, {
|
|
47
|
+
maxLines: DIFF_CARD_MAX_LINES,
|
|
48
|
+
maxBytes: DIFF_CARD_MAX_BYTES,
|
|
49
|
+
});
|
|
50
|
+
const fenced = `\n\n\`\`\`diff\n${truncation.content}\n\`\`\``;
|
|
51
|
+
if (!truncation.truncated)
|
|
52
|
+
return fenced;
|
|
53
|
+
const hint = truncation.firstLineExceedsLimit
|
|
54
|
+
? `[Diff truncated: first line exceeds ${formatSize(truncation.maxBytes)} — use read to inspect file]`
|
|
55
|
+
: `[Diff truncated: showing ${truncation.outputLines}/${truncation.totalLines} lines (${formatSize(truncation.outputBytes)}/${formatSize(truncation.totalBytes)}) — re-read file to see full content]`;
|
|
56
|
+
return `${fenced}\n\n${hint}`;
|
|
57
|
+
}
|
|
40
58
|
function driftBlock(driftNotice) {
|
|
41
59
|
return driftNotice ? `\n\n${driftNotice}` : "";
|
|
42
60
|
}
|
|
@@ -78,11 +96,13 @@ export function buildChanged(input) {
|
|
|
78
96
|
const lineSummary = addedLines > 0 || removedLines > 0
|
|
79
97
|
? ` Added ${addedLines} line(s), removed ${removedLines} line(s).`
|
|
80
98
|
: "";
|
|
81
|
-
const
|
|
99
|
+
const baseText = resultLines.length === 0
|
|
82
100
|
? "File is empty. Use edit to insert content."
|
|
83
101
|
: warningsBlock
|
|
84
102
|
? `${successPrefix}${lineSummary}${warningsBlock}`
|
|
85
103
|
: `${successPrefix}${lineSummary}`;
|
|
104
|
+
const diffSection = resultLines.length === 0 ? "" : formatDiffCard(diffResult.diff);
|
|
105
|
+
const text = `${baseText}${diffSection}`;
|
|
86
106
|
const metrics = buildMetrics({
|
|
87
107
|
classification: "applied",
|
|
88
108
|
editsAttempted: editMeta.editsAttempted,
|
|
@@ -161,7 +181,9 @@ export function buildBatchResult(sections) {
|
|
|
161
181
|
: "";
|
|
162
182
|
const summary = `Successfully edited ${appliedFiles.length} file(s) — ${appliedTotal} of ${totalEdits} edit(s) applied${noopTotal > 0 ? ` (${noopTotal} noop)` : ""}.${lineSummary}`;
|
|
163
183
|
const modelWarnings = warnings.filter((w) => !w.startsWith("Batch drift note:"));
|
|
164
|
-
const
|
|
184
|
+
const baseText = `${summary}${warnBlock(modelWarnings)}`;
|
|
185
|
+
const diffSection = formatDiffCard(diff);
|
|
186
|
+
const text = `${baseText}${diffSection}`;
|
|
165
187
|
return {
|
|
166
188
|
content: [{ type: "text", text }],
|
|
167
189
|
details: {
|