dsh-better-edit 0.1.8 → 0.2.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 +28 -6
- package/README.md +27 -7
- package/README.zh.md +24 -7
- package/assets/logo.svg +183 -18
- package/lib/contract.js +95 -0
- package/lib/drift.js +1 -1
- package/lib/edit-diff.js +2 -2
- package/lib/edit-engine.js +456 -0
- package/lib/edit-pipeline.js +41 -116
- package/lib/file-reader.js +1 -2
- package/lib/fs-bridge.js +2 -2
- package/lib/fs-write.js +3 -46
- package/lib/hash-store.js +246 -13
- package/lib/hashline/apply.js +2 -2
- package/lib/hashline/hash.js +16 -206
- package/lib/hashline/index.js +4 -3
- package/lib/hashline/parse.js +1 -1
- package/lib/hashline/pure.js +213 -0
- package/lib/hashline/resolve.js +1 -5
- package/lib/hashline/served.js +2 -2
- package/lib/paths.js +55 -1
- package/lib/read-and-serve.js +46 -0
- package/lib/schema.js +1 -1
- package/lib/served-store.js +144 -183
- package/lib/tool-batch-edit.js +28 -280
- package/lib/tool-edit.js +37 -32
- package/lib/tool-read.js +8 -31
- package/lib/tool-undo.js +4 -13
- package/lib/types/contract.d.ts +39 -0
- package/lib/types/edit-engine.d.ts +179 -0
- package/lib/types/edit-pipeline.d.ts +10 -17
- package/lib/types/fs-write.d.ts +0 -1
- package/lib/types/hash-store.d.ts +73 -25
- package/lib/types/hashline/hash.d.ts +8 -13
- package/lib/types/hashline/index.d.ts +4 -3
- package/lib/types/hashline/pure.d.ts +26 -0
- package/lib/types/hashline/resolve.d.ts +0 -1
- package/lib/types/paths.d.ts +9 -0
- package/lib/types/read-and-serve.d.ts +39 -0
- package/lib/types/schema.d.ts +2 -16
- package/lib/types/served-store.d.ts +63 -32
- package/lib/types/tool-batch-edit.d.ts +4 -1
- package/lib/types/tool-undo.d.ts +1 -1
- package/lib/undo-edit.js +16 -1
- package/lib/write-hook.js +30 -50
- package/package.json +4 -3
- package/lib/served-state.js +0 -34
- package/lib/snapshot-store.js +0 -108
- package/lib/types/served-state.d.ts +0 -3
- package/lib/types/snapshot-store.d.ts +0 -14
- package/lib/types/undo-store.d.ts +0 -14
- package/lib/undo-store.js +0 -43
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The edit-sequence engine shared by `edit`, `batch_edit`, and previews:
|
|
3
|
+
* apply-one-edit against in-memory content with served verification, the
|
|
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.
|
|
11
|
+
* @module dsh-better-edit/edit-engine
|
|
12
|
+
*/
|
|
13
|
+
import { restoreEndings } from "./edit-diff.js";
|
|
14
|
+
import { normFromText } from "./file-reader.js";
|
|
15
|
+
import { scanDrift } from "./drift.js";
|
|
16
|
+
import { applyEdit, lineHashes, resEdit, parseHashRef, MAX_HASH_LINES, } from "./hashline/index.js";
|
|
17
|
+
import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "./hashline/served.js";
|
|
18
|
+
import { loadServed } from "./served-store.js";
|
|
19
|
+
import { findSnapshotPathsByHashes } from "./hash-store.js";
|
|
20
|
+
import { saveUndo } from "./undo-edit.js";
|
|
21
|
+
import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
|
|
22
|
+
import { NOOP_LOOP_THRESHOLD } from "./constants.js";
|
|
23
|
+
import { abortIf, splitLines } from "./utils.js";
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
// request / counting helpers shared by both tool paths
|
|
26
|
+
/**
|
|
27
|
+
* Resolve a request's missing `path` from its anchors: the only file whose
|
|
28
|
+
* stored hashes contain both anchors. Returns the path plus an autocorrect
|
|
29
|
+
* warning, or undefined when no resolution is possible.
|
|
30
|
+
*/
|
|
31
|
+
export async function resolveMissingPath(request) {
|
|
32
|
+
if (typeof request.path === "string")
|
|
33
|
+
return undefined;
|
|
34
|
+
const from = request.remove_from;
|
|
35
|
+
const to = request.remove_to;
|
|
36
|
+
if (typeof from !== "string" || typeof to !== "string")
|
|
37
|
+
return undefined;
|
|
38
|
+
const hashes = [];
|
|
39
|
+
for (const ref of [from, to]) {
|
|
40
|
+
try {
|
|
41
|
+
hashes.push(parseHashRef(ref).hash);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
let matches;
|
|
48
|
+
try {
|
|
49
|
+
matches = await findSnapshotPathsByHashes(hashes);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
if (matches.length === 1) {
|
|
55
|
+
return {
|
|
56
|
+
path: matches[0],
|
|
57
|
+
warning: `[E_BAD_SHAPE] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
if (matches.length > 1) {
|
|
61
|
+
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.`);
|
|
62
|
+
}
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
/** The hashes a range edit removes, for stable re-hash bookkeeping. */
|
|
66
|
+
export function collectRemovedHashes(edit, originalHashes) {
|
|
67
|
+
const removedHashes = new Set();
|
|
68
|
+
const startHash = edit.hash_bounds[0].hash;
|
|
69
|
+
const endHash = edit.hash_bounds[1].hash;
|
|
70
|
+
const startLine = originalHashes.indexOf(startHash);
|
|
71
|
+
const endLine = originalHashes.indexOf(endHash);
|
|
72
|
+
if (startLine >= 0 && endLine >= 0) {
|
|
73
|
+
const firstLine = Math.min(startLine, endLine);
|
|
74
|
+
const lastLine = Math.max(startLine, endLine);
|
|
75
|
+
for (let i = firstLine; i <= lastLine; i++) {
|
|
76
|
+
removedHashes.add(originalHashes[i]);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return removedHashes;
|
|
80
|
+
}
|
|
81
|
+
/** Added/removed line counts for one resolved edit against a file's original hashes. */
|
|
82
|
+
export function countLineChanges(edit, originalHashes, isNoop, removedAutoFixes) {
|
|
83
|
+
if (isNoop)
|
|
84
|
+
return { totalAddedLines: 0, totalRemovedLines: 0 };
|
|
85
|
+
let totalRemovedLines = 0;
|
|
86
|
+
const startLine = originalHashes.indexOf(edit.hash_bounds[0].hash);
|
|
87
|
+
const endLine = originalHashes.indexOf(edit.hash_bounds[1].hash);
|
|
88
|
+
if (startLine >= 0 && endLine >= 0) {
|
|
89
|
+
totalRemovedLines = Math.abs(endLine - startLine) + 1;
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
totalAddedLines: Math.max(0, edit.content_lines.length - removedAutoFixes),
|
|
93
|
+
totalRemovedLines,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* One edit against in-memory content: resolve (unless a pre-resolved edit was
|
|
98
|
+
* given) → apply with served verification → stable re-hash → line counts.
|
|
99
|
+
*
|
|
100
|
+
* `onReject` owns the reject-and-serve policy: it receives resolve/verify
|
|
101
|
+
* failures (and the edit that failed, when resolved) and MUST throw. The
|
|
102
|
+
* single path rethrows the original anchor error after recording echo serves;
|
|
103
|
+
* the batch path wraps with [E_BATCH_ABORT] plus the current-range echo.
|
|
104
|
+
*/
|
|
105
|
+
export async function applyOne(input, onReject) {
|
|
106
|
+
let edit;
|
|
107
|
+
if (input.edit) {
|
|
108
|
+
edit = input.edit;
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
try {
|
|
112
|
+
edit = resEdit({
|
|
113
|
+
remove_from: input.removeFrom,
|
|
114
|
+
remove_to: input.removeTo,
|
|
115
|
+
replacement_text: input.replacementText,
|
|
116
|
+
}, input.warnings);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
return onReject(error, undefined);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
let anchorResult;
|
|
123
|
+
try {
|
|
124
|
+
anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served);
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
if (error instanceof AnchorMismatchError ||
|
|
128
|
+
error instanceof ServedRejectionError) {
|
|
129
|
+
return onReject(error, edit);
|
|
130
|
+
}
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
const result = anchorResult.content;
|
|
134
|
+
const noop = result === input.content;
|
|
135
|
+
const removedHashes = noop
|
|
136
|
+
? undefined
|
|
137
|
+
: collectRemovedHashes(edit, input.hashes);
|
|
138
|
+
const resultHashes = noop
|
|
139
|
+
? input.hashes
|
|
140
|
+
: await lineHashes(result, input.absolutePath, {
|
|
141
|
+
content: input.content,
|
|
142
|
+
hashes: input.hashes,
|
|
143
|
+
removedHashes,
|
|
144
|
+
}, input.store, input.persist);
|
|
145
|
+
const { totalAddedLines, totalRemovedLines } = countLineChanges(edit, input.countHashes ?? input.hashes, noop, anchorResult.autoFixes?.length ?? 0);
|
|
146
|
+
return {
|
|
147
|
+
result,
|
|
148
|
+
hashes: resultHashes,
|
|
149
|
+
range: anchorResult.range,
|
|
150
|
+
noop,
|
|
151
|
+
edit,
|
|
152
|
+
noopEdit: anchorResult.noopEdit,
|
|
153
|
+
firstChangedLine: anchorResult.firstChangedLine,
|
|
154
|
+
lastChangedLine: anchorResult.lastChangedLine,
|
|
155
|
+
removedHashes,
|
|
156
|
+
totalAddedLines,
|
|
157
|
+
totalRemovedLines,
|
|
158
|
+
anchorWarnings: anchorResult.warnings,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The shared noop-loop guard. Returns the "twice in a row" notice for the
|
|
163
|
+
* caller to append to warnings, or throws [E_NOOP_LOOP] (after recording the
|
|
164
|
+
* echo serves) once the payload has been submitted NOOP_LOOP_THRESHOLD times
|
|
165
|
+
* with no change. Messages are byte-identical to the pre-engine tools.
|
|
166
|
+
*/
|
|
167
|
+
export async function enforceNoopLoop(opts) {
|
|
168
|
+
const { absolutePath, removeFrom, removeTo, displayPath, index, count, sessionKey, originalHashes, } = opts;
|
|
169
|
+
if (index === undefined) {
|
|
170
|
+
if (count >= NOOP_LOOP_THRESHOLD) {
|
|
171
|
+
const echoRows = buildRangeEcho(opts.range.startLine, opts.range.endLine, originalHashes);
|
|
172
|
+
const echo = fmtServedRows(echoRows, splitLines(opts.originalNormalized));
|
|
173
|
+
await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
174
|
+
throw new Error(`[E_NOOP_LOOP] This exact edit (anchors ${removeFrom} to ${removeTo} in ${displayPath}) 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}`);
|
|
175
|
+
}
|
|
176
|
+
if (count === 2) {
|
|
177
|
+
return `[E_NOOP_LOOP] Notice: this exact edit (anchors ${removeFrom} to ${removeTo} in ${displayPath}) has produced no changes twice in a row. The range already contains the replacement text; resending it again will be rejected.`;
|
|
178
|
+
}
|
|
179
|
+
return undefined;
|
|
180
|
+
}
|
|
181
|
+
if (count >= NOOP_LOOP_THRESHOLD) {
|
|
182
|
+
const originalLines = splitLines(opts.originalNormalized);
|
|
183
|
+
const echoRows = opts.echoRows;
|
|
184
|
+
if (echoRows) {
|
|
185
|
+
await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
186
|
+
}
|
|
187
|
+
throw new Error(`[E_NOOP_LOOP] edits[${index}] (${displayPath}): this exact edit (anchors ${removeFrom} to ${removeTo}) 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.` +
|
|
188
|
+
(echoRows
|
|
189
|
+
? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}`
|
|
190
|
+
: ""));
|
|
191
|
+
}
|
|
192
|
+
if (count === 2) {
|
|
193
|
+
return `[E_NOOP_LOOP] Notice: edits[${index}] (${displayPath}) — this exact edit has produced no changes twice in a row; the range already contains the replacement text. Resending it again will reject the batch.`;
|
|
194
|
+
}
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
// ---------------------------------------------------------------------------
|
|
198
|
+
// per-file sequencer (batch)
|
|
199
|
+
function echoRowsForItem(edit, originalHashes) {
|
|
200
|
+
const startHash = edit.hash_bounds[0].hash;
|
|
201
|
+
const endHash = edit.hash_bounds[1].hash;
|
|
202
|
+
const s = originalHashes.indexOf(startHash);
|
|
203
|
+
const e = originalHashes.indexOf(endHash);
|
|
204
|
+
if (s < 0 || e < 0)
|
|
205
|
+
return undefined;
|
|
206
|
+
return buildRangeEcho(Math.min(s, e) + 1, Math.max(s, e) + 1, originalHashes);
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Run a file's item list against freshly-read content with served
|
|
210
|
+
* verification, evolving content/hashes, union range, noop tracking, and a
|
|
211
|
+
* per-file drift notice. All-or-nothing is enforced by the caller's
|
|
212
|
+
* transaction ({@link persistUndoAndWrite}): nothing here writes to disk.
|
|
213
|
+
*/
|
|
214
|
+
export async function runFileEdits(io, items, opts) {
|
|
215
|
+
const first = items[0];
|
|
216
|
+
abortIf(opts.signal);
|
|
217
|
+
const absolutePath = first.absolutePath;
|
|
218
|
+
const rawText = await io.readText(absolutePath, opts.signal);
|
|
219
|
+
const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
|
|
220
|
+
absolutePath,
|
|
221
|
+
rawText,
|
|
222
|
+
displayPath: first.path,
|
|
223
|
+
signal: opts.signal,
|
|
224
|
+
maxLines: MAX_HASH_LINES,
|
|
225
|
+
});
|
|
226
|
+
const served = await loadServed(opts.sessionKey, absolutePath);
|
|
227
|
+
const warnings = [];
|
|
228
|
+
let currentContent = originalNormalized;
|
|
229
|
+
let currentHashes = originalHashes;
|
|
230
|
+
let appliedCount = 0;
|
|
231
|
+
let noopCount = 0;
|
|
232
|
+
let totalAddedLines = 0;
|
|
233
|
+
let totalRemovedLines = 0;
|
|
234
|
+
let unionStartLine = Infinity;
|
|
235
|
+
let unionEndLine = -Infinity;
|
|
236
|
+
let unionStartHash = "";
|
|
237
|
+
let unionEndHash = "";
|
|
238
|
+
let lastApplied;
|
|
239
|
+
for (const item of items) {
|
|
240
|
+
abortIf(opts.signal);
|
|
241
|
+
const applied = await applyOne({
|
|
242
|
+
content: currentContent,
|
|
243
|
+
hashes: currentHashes,
|
|
244
|
+
served,
|
|
245
|
+
removeFrom: item.remove_from,
|
|
246
|
+
removeTo: item.remove_to,
|
|
247
|
+
replacementText: item.replacement_text,
|
|
248
|
+
absolutePath,
|
|
249
|
+
displayPath: item.path,
|
|
250
|
+
signal: opts.signal,
|
|
251
|
+
warnings,
|
|
252
|
+
countHashes: originalHashes,
|
|
253
|
+
persist: false,
|
|
254
|
+
}, async (error, edit) => {
|
|
255
|
+
if (error instanceof AnchorMismatchError ||
|
|
256
|
+
error instanceof ServedRejectionError) {
|
|
257
|
+
const originalLines = splitLines(originalNormalized);
|
|
258
|
+
const echoRows = error.servedRows.length > 0
|
|
259
|
+
? error.servedRows
|
|
260
|
+
: edit
|
|
261
|
+
? echoRowsForItem(edit, originalHashes)
|
|
262
|
+
: undefined;
|
|
263
|
+
if (echoRows) {
|
|
264
|
+
await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
265
|
+
}
|
|
266
|
+
const echoBlock = echoRows
|
|
267
|
+
? ` Current on-disk range for edits[${item.index}] (unchanged — nothing was written):\n${fmtServedRows(echoRows, originalLines)}`
|
|
268
|
+
: " Call read() to get fresh anchors.";
|
|
269
|
+
throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${error.message}${echoBlock}\n` +
|
|
270
|
+
"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.");
|
|
271
|
+
}
|
|
272
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
273
|
+
throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${message}\n` +
|
|
274
|
+
"The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied.");
|
|
275
|
+
});
|
|
276
|
+
const range = applied.range;
|
|
277
|
+
if (range.startLine < unionStartLine) {
|
|
278
|
+
unionStartLine = range.startLine;
|
|
279
|
+
unionStartHash = range.startHash;
|
|
280
|
+
}
|
|
281
|
+
if (range.endLine > unionEndLine) {
|
|
282
|
+
unionEndLine = range.endLine;
|
|
283
|
+
unionEndHash = range.endHash;
|
|
284
|
+
}
|
|
285
|
+
if (applied.noop) {
|
|
286
|
+
noopCount += 1;
|
|
287
|
+
const payload = noopPayloadKey(absolutePath, item.remove_from, item.remove_to, item.replacement_text);
|
|
288
|
+
const count = trackNoopPayload(absolutePath, payload);
|
|
289
|
+
const notice = await enforceNoopLoop({
|
|
290
|
+
absolutePath,
|
|
291
|
+
removeFrom: item.remove_from,
|
|
292
|
+
removeTo: item.remove_to,
|
|
293
|
+
replacementText: item.replacement_text,
|
|
294
|
+
displayPath: item.path,
|
|
295
|
+
index: item.index,
|
|
296
|
+
count,
|
|
297
|
+
sessionKey: opts.sessionKey,
|
|
298
|
+
originalHashes,
|
|
299
|
+
originalNormalized,
|
|
300
|
+
echoRows: echoRowsForItem(applied.edit, originalHashes),
|
|
301
|
+
});
|
|
302
|
+
if (notice)
|
|
303
|
+
warnings.push(notice);
|
|
304
|
+
warnings.push(`edits[${item.index}] (${item.path}) was a noop: the range already contains the replacement text.`);
|
|
305
|
+
if (applied.anchorWarnings?.length)
|
|
306
|
+
warnings.push(...applied.anchorWarnings);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
appliedCount += 1;
|
|
310
|
+
const removedHashes = applied.removedHashes;
|
|
311
|
+
totalAddedLines += applied.totalAddedLines;
|
|
312
|
+
totalRemovedLines += applied.totalRemovedLines;
|
|
313
|
+
lastApplied = {
|
|
314
|
+
content: currentContent,
|
|
315
|
+
hashes: currentHashes,
|
|
316
|
+
removedHashes,
|
|
317
|
+
};
|
|
318
|
+
currentContent = applied.result;
|
|
319
|
+
currentHashes = applied.hashes;
|
|
320
|
+
clearNoopLoop(absolutePath);
|
|
321
|
+
if (applied.anchorWarnings?.length)
|
|
322
|
+
warnings.push(...applied.anchorWarnings);
|
|
323
|
+
}
|
|
324
|
+
const result = currentContent;
|
|
325
|
+
let resultHashes = currentHashes;
|
|
326
|
+
if (appliedCount > 0 && lastApplied) {
|
|
327
|
+
resultHashes = await lineHashes(result, absolutePath, {
|
|
328
|
+
content: lastApplied.content,
|
|
329
|
+
hashes: lastApplied.hashes,
|
|
330
|
+
removedHashes: lastApplied.removedHashes,
|
|
331
|
+
}, undefined, true);
|
|
332
|
+
}
|
|
333
|
+
if (hadUtf8DecodeErrors) {
|
|
334
|
+
warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
|
|
335
|
+
}
|
|
336
|
+
if (first.pathWarning)
|
|
337
|
+
warnings.unshift(first.pathWarning);
|
|
338
|
+
let driftNotice;
|
|
339
|
+
if (appliedCount > 0 && unionStartLine !== Infinity) {
|
|
340
|
+
const resultLines = splitLines(result);
|
|
341
|
+
const originalLines = splitLines(originalNormalized);
|
|
342
|
+
try {
|
|
343
|
+
driftNotice = await scanDrift({
|
|
344
|
+
sessionKey: opts.sessionKey,
|
|
345
|
+
served,
|
|
346
|
+
resultHashes,
|
|
347
|
+
resultLines,
|
|
348
|
+
range: {
|
|
349
|
+
startLine: unionStartLine,
|
|
350
|
+
endLine: unionEndLine,
|
|
351
|
+
startHash: unionStartHash,
|
|
352
|
+
endHash: unionEndHash,
|
|
353
|
+
delta: resultLines.length - originalLines.length,
|
|
354
|
+
},
|
|
355
|
+
path: absolutePath,
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
catch (error) {
|
|
359
|
+
console.error("Failed to compute drift notice:", error);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return {
|
|
363
|
+
displayPath: first.path,
|
|
364
|
+
absolutePath,
|
|
365
|
+
originalNormalized,
|
|
366
|
+
result,
|
|
367
|
+
bom,
|
|
368
|
+
originalEnding,
|
|
369
|
+
hadUtf8DecodeErrors,
|
|
370
|
+
warnings,
|
|
371
|
+
originalHashes,
|
|
372
|
+
resultHashes,
|
|
373
|
+
appliedCount,
|
|
374
|
+
noopCount,
|
|
375
|
+
totalAddedLines,
|
|
376
|
+
totalRemovedLines,
|
|
377
|
+
driftNotice,
|
|
378
|
+
range: {
|
|
379
|
+
startLine: unionStartLine,
|
|
380
|
+
endLine: unionEndLine,
|
|
381
|
+
startHash: unionStartHash,
|
|
382
|
+
endHash: unionEndHash,
|
|
383
|
+
delta: splitLines(result).length - splitLines(originalNormalized).length,
|
|
384
|
+
},
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* The persist-undo → write-all → restore-on-failure transaction shared by
|
|
389
|
+
* `edit` (one file) and `batch_edit` (many files). Every file's undo entry is
|
|
390
|
+
* persisted before anything is written; if a write fails, already-written
|
|
391
|
+
* files are restored (original content written back, undo entry restored) and
|
|
392
|
+
* the sandbox-mapped error rethrown.
|
|
393
|
+
*/
|
|
394
|
+
export async function persistUndoAndWrite(opts) {
|
|
395
|
+
const { io, files } = opts;
|
|
396
|
+
const undos = [];
|
|
397
|
+
for (const file of files) {
|
|
398
|
+
const undo = await saveUndo(file.absolutePath, {
|
|
399
|
+
content: file.originalNormalized,
|
|
400
|
+
bom: file.bom,
|
|
401
|
+
originalEnding: file.originalEnding,
|
|
402
|
+
hashes: file.originalHashes,
|
|
403
|
+
resultContent: file.result,
|
|
404
|
+
});
|
|
405
|
+
if (!undo.persisted) {
|
|
406
|
+
for (const u of undos) {
|
|
407
|
+
try {
|
|
408
|
+
await u.restore();
|
|
409
|
+
}
|
|
410
|
+
catch (error) {
|
|
411
|
+
console.error("Failed to restore undo entry after abort:", error);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
throw new Error(opts.undoUnavailableMessage(file.displayPath));
|
|
415
|
+
}
|
|
416
|
+
undos.push({ file, restore: undo.restore });
|
|
417
|
+
}
|
|
418
|
+
const written = [];
|
|
419
|
+
try {
|
|
420
|
+
for (const u of undos) {
|
|
421
|
+
abortIf(opts.signal);
|
|
422
|
+
await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), opts.signal, opts.exec, opts.sandboxPolicy);
|
|
423
|
+
written.push(u);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
catch (error) {
|
|
427
|
+
for (const w of written) {
|
|
428
|
+
try {
|
|
429
|
+
await io.writeText(w.file.absolutePath, w.file.bom +
|
|
430
|
+
restoreEndings(w.file.originalNormalized, w.file.originalEnding), undefined, opts.exec, opts.sandboxPolicy);
|
|
431
|
+
}
|
|
432
|
+
catch (restoreError) {
|
|
433
|
+
console.error("Failed to restore file after write failure:", restoreError);
|
|
434
|
+
}
|
|
435
|
+
try {
|
|
436
|
+
await w.restore();
|
|
437
|
+
}
|
|
438
|
+
catch (restoreError) {
|
|
439
|
+
console.error("Failed to restore undo entry after write failure:", restoreError);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
if (opts.restoreUnwrittenUndos) {
|
|
443
|
+
for (const u of undos) {
|
|
444
|
+
if (written.includes(u))
|
|
445
|
+
continue;
|
|
446
|
+
try {
|
|
447
|
+
await u.restore();
|
|
448
|
+
}
|
|
449
|
+
catch (restoreError) {
|
|
450
|
+
console.error("Failed to restore undo entry after write failure:", restoreError);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
throw opts.sandbox.mapError(error, opts.sandboxPolicy);
|
|
455
|
+
}
|
|
456
|
+
}
|
package/lib/edit-pipeline.js
CHANGED
|
@@ -1,100 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The single-edit pipeline shared by `edit`,
|
|
3
|
-
* resolve → normalize → hash → verify anchors against
|
|
4
|
-
* re-hash with stable anchors → drift notice.
|
|
5
|
-
*
|
|
6
|
-
*
|
|
2
|
+
* The single-edit pipeline shared by `edit`, previews, and (through the
|
|
3
|
+
* engine) `batch_edit`: resolve → normalize → hash → verify anchors against
|
|
4
|
+
* served state → apply → re-hash with stable anchors → drift notice. The
|
|
5
|
+
* apply/reject/re-hash computation lives in the edit engine
|
|
6
|
+
* ({@link edit-engine}); this module keeps the single-edit orchestration
|
|
7
|
+
* shape, preview-mode options, and the pipeline result type. All IO goes
|
|
8
|
+
* through the {@link FileIO} bridge so the same pipeline runs on `ctx.fs` and
|
|
9
|
+
* on the host filesystem.
|
|
7
10
|
* @module dsh-better-edit/edit-pipeline
|
|
8
11
|
*/
|
|
9
12
|
import { normFromText, fileSnap } from './file-reader.js';
|
|
10
13
|
import { toCwd } from './paths.js';
|
|
11
|
-
import {
|
|
14
|
+
import { resEdit, MAX_HASH_LINES, } from './hashline/index.js';
|
|
12
15
|
import { AnchorMismatchError, ServedRejectionError, recordEchoServes, } from './hashline/served.js';
|
|
13
16
|
import { loadServed, sessionKeyFor } from './served-store.js';
|
|
14
|
-
import { findSnapshotPathsByHashes } from './snapshot-store.js';
|
|
15
17
|
import { scanDrift } from './drift.js';
|
|
16
|
-
import { abortIf,
|
|
17
|
-
|
|
18
|
-
export function assertReq(request) {
|
|
19
|
-
if (!isRec(request)) {
|
|
20
|
-
throw new Error('[E_BAD_SHAPE] Edit request must be an object.');
|
|
21
|
-
}
|
|
22
|
-
rejectUnknownFields(request, ROOT_KS, 'Edit request');
|
|
23
|
-
if (typeof request.path !== 'string' || request.path.length === 0) {
|
|
24
|
-
throw new Error('[E_BAD_SHAPE] Edit request requires a non-empty "path" string.');
|
|
25
|
-
}
|
|
26
|
-
if (typeof request.remove_from !== 'string' ||
|
|
27
|
-
typeof request.remove_to !== 'string' ||
|
|
28
|
-
typeof request.replacement_text !== 'string') {
|
|
29
|
-
throw new Error('[E_BAD_SHAPE] Edit request requires "remove_from", "remove_to", and "replacement_text" at the top level.');
|
|
30
|
-
}
|
|
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
|
-
export function collectRemovedHashes(edit, originalHashes) {
|
|
67
|
-
const removedHashes = new Set();
|
|
68
|
-
const startHash = edit.hash_bounds[0].hash;
|
|
69
|
-
const endHash = edit.hash_bounds[1].hash;
|
|
70
|
-
const startLine = originalHashes.indexOf(startHash);
|
|
71
|
-
const endLine = originalHashes.indexOf(endHash);
|
|
72
|
-
if (startLine >= 0 && endLine >= 0) {
|
|
73
|
-
const firstLine = Math.min(startLine, endLine);
|
|
74
|
-
const lastLine = Math.max(startLine, endLine);
|
|
75
|
-
for (let i = firstLine; i <= lastLine; i++) {
|
|
76
|
-
removedHashes.add(originalHashes[i]);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
return removedHashes;
|
|
80
|
-
}
|
|
81
|
-
export function countLineChanges(edit, originalHashes, isNoop, removedAutoFixes) {
|
|
82
|
-
if (isNoop)
|
|
83
|
-
return { totalAddedLines: 0, totalRemovedLines: 0 };
|
|
84
|
-
let totalRemovedLines = 0;
|
|
85
|
-
const startLine = originalHashes.indexOf(edit.hash_bounds[0].hash);
|
|
86
|
-
const endLine = originalHashes.indexOf(edit.hash_bounds[1].hash);
|
|
87
|
-
if (startLine >= 0 && endLine >= 0) {
|
|
88
|
-
totalRemovedLines = Math.abs(endLine - startLine) + 1;
|
|
89
|
-
}
|
|
90
|
-
return {
|
|
91
|
-
totalAddedLines: Math.max(0, edit.content_lines.length - removedAutoFixes),
|
|
92
|
-
totalRemovedLines,
|
|
93
|
-
};
|
|
94
|
-
}
|
|
18
|
+
import { abortIf, splitLines } from './utils.js';
|
|
19
|
+
import { applyOne } from './edit-engine.js';
|
|
95
20
|
export async function execPipeline(io, params, cwd, options) {
|
|
96
21
|
const path = params.path;
|
|
97
22
|
const editWarnings = [];
|
|
23
|
+
// Resolve the edit up front (before IO) so malformed anchors fail before
|
|
24
|
+
// any filesystem work, exactly as the tool always did.
|
|
98
25
|
const edit = resEdit({
|
|
99
26
|
remove_from: params.remove_from,
|
|
100
27
|
remove_to: params.remove_to,
|
|
@@ -117,41 +44,39 @@ export async function execPipeline(io, params, cwd, options) {
|
|
|
117
44
|
const sessionKey = options?.sessionKey ?? sessionKeyFor(undefined);
|
|
118
45
|
const served = await loadServed(sessionKey, absolutePath);
|
|
119
46
|
const policy = options?.noPersist === true ? 'preview' : 'live';
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
47
|
+
const applied = await applyOne({
|
|
48
|
+
content: originalNormalized,
|
|
49
|
+
hashes: originalHashes,
|
|
50
|
+
served,
|
|
51
|
+
removeFrom: params.remove_from,
|
|
52
|
+
removeTo: params.remove_to,
|
|
53
|
+
replacementText: params.replacement_text,
|
|
54
|
+
absolutePath,
|
|
55
|
+
displayPath: path,
|
|
56
|
+
signal,
|
|
57
|
+
warnings: editWarnings,
|
|
58
|
+
store: hashStore,
|
|
59
|
+
persist: options?.noPersist !== true,
|
|
60
|
+
edit,
|
|
61
|
+
}, async (error) => {
|
|
125
62
|
if (error instanceof AnchorMismatchError ||
|
|
126
63
|
error instanceof ServedRejectionError) {
|
|
127
64
|
await recordEchoServes(sessionKey, absolutePath, error.servedRows, policy, originalHashes.length);
|
|
128
65
|
}
|
|
129
66
|
throw error;
|
|
130
|
-
}
|
|
131
|
-
const result =
|
|
132
|
-
const isNoop =
|
|
133
|
-
const
|
|
134
|
-
const removedHashes = isNoop
|
|
135
|
-
? undefined
|
|
136
|
-
: collectRemovedHashes(edit, originalHashes);
|
|
137
|
-
const resultHashes = isNoop
|
|
138
|
-
? originalHashes
|
|
139
|
-
: await lineHashes(result, absolutePath, {
|
|
140
|
-
content: originalNormalized,
|
|
141
|
-
hashes: originalHashes,
|
|
142
|
-
removedHashes,
|
|
143
|
-
}, hashStore, noPersist !== true);
|
|
144
|
-
const warnings = [...editWarnings, ...(anchorResult.warnings ?? [])];
|
|
145
|
-
const { totalAddedLines, totalRemovedLines } = countLineChanges(edit, originalHashes, isNoop, anchorResult.autoFixes?.length ?? 0);
|
|
67
|
+
});
|
|
68
|
+
const result = applied.result;
|
|
69
|
+
const isNoop = applied.noop;
|
|
70
|
+
const warnings = [...editWarnings, ...(applied.anchorWarnings ?? [])];
|
|
146
71
|
let driftNotice;
|
|
147
72
|
if (options?.noPersist !== true) {
|
|
148
73
|
try {
|
|
149
74
|
driftNotice = await scanDrift({
|
|
150
75
|
sessionKey,
|
|
151
76
|
served,
|
|
152
|
-
resultHashes,
|
|
77
|
+
resultHashes: applied.hashes,
|
|
153
78
|
resultLines: splitLines(result),
|
|
154
|
-
range:
|
|
79
|
+
range: applied.range,
|
|
155
80
|
path: absolutePath,
|
|
156
81
|
});
|
|
157
82
|
}
|
|
@@ -168,15 +93,15 @@ export async function execPipeline(io, params, cwd, options) {
|
|
|
168
93
|
originalEnding,
|
|
169
94
|
hadUtf8DecodeErrors,
|
|
170
95
|
warnings,
|
|
171
|
-
noopEdit:
|
|
172
|
-
firstChangedLine:
|
|
173
|
-
lastChangedLine:
|
|
174
|
-
resultHashes,
|
|
96
|
+
noopEdit: applied.noopEdit,
|
|
97
|
+
firstChangedLine: applied.firstChangedLine,
|
|
98
|
+
lastChangedLine: applied.lastChangedLine,
|
|
175
99
|
originalHashes,
|
|
176
|
-
|
|
177
|
-
|
|
100
|
+
resultHashes: applied.hashes,
|
|
101
|
+
totalAddedLines: applied.totalAddedLines,
|
|
102
|
+
totalRemovedLines: applied.totalRemovedLines,
|
|
178
103
|
driftNotice,
|
|
179
|
-
range:
|
|
104
|
+
range: applied.range,
|
|
180
105
|
};
|
|
181
106
|
}
|
|
182
107
|
/** Resolve the display path a caller names against the session cwd. */
|
package/lib/file-reader.js
CHANGED
|
@@ -2,8 +2,7 @@ import { constants } from "node:fs";
|
|
|
2
2
|
import { stat } from "fs/promises";
|
|
3
3
|
import { lineHashes } from "./hashline/index.js";
|
|
4
4
|
import { loadFileKindAndText } from "./file-kind.js";
|
|
5
|
-
import { resolveTarget } from "./
|
|
6
|
-
import { toCwd } from "./paths.js";
|
|
5
|
+
import { resolveTarget, toCwd } from "./paths.js";
|
|
7
6
|
import { detectEnding, toLF, stripBOM } from "./edit-diff.js";
|
|
8
7
|
import { abortIf } from "./utils.js";
|
|
9
8
|
import { valKind, valAccess } from "./validation.js";
|
package/lib/fs-bridge.js
CHANGED
|
@@ -15,9 +15,9 @@
|
|
|
15
15
|
* @module dsh-better-edit/fs-bridge
|
|
16
16
|
*/
|
|
17
17
|
import { readFile } from "node:fs/promises";
|
|
18
|
-
import {
|
|
18
|
+
import { writeAtomic } from "./fs-write.js";
|
|
19
19
|
import { fileSnap } from "./file-reader.js";
|
|
20
|
-
import { toCwd } from "./paths.js";
|
|
20
|
+
import { resolveTarget, toCwd } from "./paths.js";
|
|
21
21
|
/**
|
|
22
22
|
* Map an `ctx.fs` failure onto the hashline model-facing vocabulary so the
|
|
23
23
|
* model sees the same structured error codes as the pure pipeline.
|