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
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @internal — private to Mutation seam. Do not import from outside src/mutation.
|
|
3
|
+
* The edit-sequence engine private to Mutation:
|
|
4
|
+
* apply-one-edit against in-memory content with served verification and the
|
|
5
|
+
* multi-edit sequencer that drives a whole file's item list against evolving
|
|
6
|
+
* content, the noop-loop guard, and the persist-undo → write → restore
|
|
7
|
+
* Transaction (persist-undo → write → restore) is owned by Mutation, not this engine.
|
|
8
|
+
*
|
|
9
|
+
* The model-facing contract lives here unchanged: [E_BATCH_ABORT],
|
|
10
|
+
* [E_NOOP_LOOP], [E_UNDO_UNAVAILABLE] carry byte-identical messages, and
|
|
11
|
+
* reject-and-serve records the same echo serves.
|
|
12
|
+
* @module dsh-better-edit/mutation/engine
|
|
13
|
+
*/
|
|
14
|
+
import { normFromText } from "../file-reader.js";
|
|
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 { 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, 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] identical edit (${removeFrom} → ${removeTo} in ${displayPath}) submitted ${count}×, no changes each time. Range already contains this text; resend will reject. Current range:\n${echo}`);
|
|
175
|
+
}
|
|
176
|
+
if (count === 2) {
|
|
177
|
+
return `[E_NOOP_LOOP] Notice: identical edit (${removeFrom} → ${removeTo} in ${displayPath}) no-op'd twice; range already has this text. Resend will reject.`;
|
|
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}): identical edit (${removeFrom} → ${removeTo}) submitted ${count}×, no changes each time. Range already has this text; resend will reject the batch.` +
|
|
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}) — identical edit no-op'd twice; range already has this text. Resend 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 write transaction
|
package/lib/mutation.js
CHANGED
|
@@ -29,13 +29,16 @@ import { toCwd } from "./paths.js";
|
|
|
29
29
|
import { resEdit } from "./hashline/anchor-pipeline.js";
|
|
30
30
|
import { MAX_HASH_LINES } from "./hashline/hash-assign.js";
|
|
31
31
|
import { AnchorMismatchError, ServedRejectionError, recordEchoServes, } from "./hashline/anchor-pipeline.js";
|
|
32
|
-
import {
|
|
32
|
+
import { sessionKeyFor } from "./workspace-context.js";
|
|
33
|
+
import { loadServed, scanDrift, recordServedTruncated } from "./session-view.js";
|
|
33
34
|
import { abortIf, splitLines } from "./utils.js";
|
|
34
|
-
import { applyOne } from "./
|
|
35
|
-
import { runFileEdits, resolveMissingPath,
|
|
35
|
+
import { applyOne } from "./mutation/engine.js";
|
|
36
|
+
import { runFileEdits, resolveMissingPath, } from "./mutation/engine.js";
|
|
37
|
+
import { saveUndo } from "./undo-edit.js";
|
|
38
|
+
import { restoreEndings } from "./edit-diff.js";
|
|
36
39
|
import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-response.js";
|
|
37
|
-
import { genDiff,
|
|
38
|
-
import { computeDrift } from "./
|
|
40
|
+
import { genDiff, toLF, stripBOM } from "./edit-diff.js";
|
|
41
|
+
import { computeDrift } from "./session-view.js";
|
|
39
42
|
import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js";
|
|
40
43
|
export async function execPipeline(io, params, cwd, options) {
|
|
41
44
|
const path = params.path;
|
|
@@ -142,11 +145,82 @@ export async function snapshotIdFor(io, absolutePath, signal) {
|
|
|
142
145
|
}
|
|
143
146
|
}
|
|
144
147
|
}
|
|
145
|
-
|
|
148
|
+
// Engine helpers are private to Mutation — not re-exported for new code.
|
|
149
|
+
// Deprecated re-exports kept for existing tests (commitlint: ignore):
|
|
150
|
+
export { runFileEdits, resolveMissingPath };
|
|
151
|
+
export { persistUndoAndWrite };
|
|
146
152
|
export { buildMetrics, buildNoop, buildChanged, buildBatchResult };
|
|
147
153
|
export { genDiff, restoreEndings, toLF, stripBOM };
|
|
148
154
|
export { computeDrift, scanDrift };
|
|
149
155
|
export { trackNoopPayload, clearNoopLoop, noopPayloadKey };
|
|
156
|
+
async function persistUndoAndWrite(opts) {
|
|
157
|
+
const { io, files } = opts;
|
|
158
|
+
const undos = [];
|
|
159
|
+
for (const file of files) {
|
|
160
|
+
const undo = await saveUndo(file.absolutePath, {
|
|
161
|
+
content: file.originalNormalized,
|
|
162
|
+
bom: file.bom,
|
|
163
|
+
originalEnding: file.originalEnding,
|
|
164
|
+
hashes: file.originalHashes,
|
|
165
|
+
resultContent: file.result,
|
|
166
|
+
});
|
|
167
|
+
if (!undo.persisted) {
|
|
168
|
+
for (const u of undos) {
|
|
169
|
+
try {
|
|
170
|
+
await u.restore();
|
|
171
|
+
}
|
|
172
|
+
catch (e) {
|
|
173
|
+
console.error("Failed to restore undo entry after abort:", e);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
throw new Error(opts.undoUnavailableMessage(file.displayPath));
|
|
177
|
+
}
|
|
178
|
+
undos.push({ file, restore: undo.restore });
|
|
179
|
+
}
|
|
180
|
+
const written = [];
|
|
181
|
+
try {
|
|
182
|
+
for (const u of undos) {
|
|
183
|
+
abortIf(opts.signal);
|
|
184
|
+
await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), opts.signal, opts.exec, opts.sandboxPolicy);
|
|
185
|
+
written.push(u);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
for (const w of written) {
|
|
190
|
+
try {
|
|
191
|
+
await io.writeText(w.file.absolutePath, w.file.bom + restoreEndings(w.file.originalNormalized, w.file.originalEnding), undefined, opts.exec, opts.sandboxPolicy);
|
|
192
|
+
}
|
|
193
|
+
catch (e) {
|
|
194
|
+
console.error("Failed to restore file after write failure:", e);
|
|
195
|
+
}
|
|
196
|
+
try {
|
|
197
|
+
await w.restore();
|
|
198
|
+
}
|
|
199
|
+
catch (e) {
|
|
200
|
+
console.error("Failed to restore undo entry after write failure:", e);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (opts.restoreUnwrittenUndos) {
|
|
204
|
+
for (const u of undos) {
|
|
205
|
+
if (written.includes(u))
|
|
206
|
+
continue;
|
|
207
|
+
try {
|
|
208
|
+
await u.restore();
|
|
209
|
+
}
|
|
210
|
+
catch (e) {
|
|
211
|
+
console.error("Failed to restore undo entry after write failure:", e);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
throw opts.sandbox.mapError(error, opts.sandboxPolicy);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
async function commitSingle(opts) {
|
|
219
|
+
return persistUndoAndWrite({ ...opts, restoreUnwrittenUndos: true });
|
|
220
|
+
}
|
|
221
|
+
async function commitBatch(opts) {
|
|
222
|
+
return persistUndoAndWrite({ ...opts, restoreUnwrittenUndos: false });
|
|
223
|
+
}
|
|
150
224
|
// --- Deep seam: unified mutation API (one interface, thin adapters) ---
|
|
151
225
|
/**
|
|
152
226
|
* Deep seam: execute the full mutation lifecycle.
|
|
@@ -190,7 +264,7 @@ export async function execute(opts) {
|
|
|
190
264
|
await recordIfNeeded(built);
|
|
191
265
|
return built.content[0].text;
|
|
192
266
|
}
|
|
193
|
-
await
|
|
267
|
+
await commitSingle({
|
|
194
268
|
io,
|
|
195
269
|
files: [
|
|
196
270
|
{
|
|
@@ -208,7 +282,6 @@ export async function execute(opts) {
|
|
|
208
282
|
sandboxPolicy,
|
|
209
283
|
signal,
|
|
210
284
|
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.`,
|
|
211
|
-
restoreUnwrittenUndos: true,
|
|
212
285
|
});
|
|
213
286
|
const built = buildBatchResult([toSection()]);
|
|
214
287
|
await recordIfNeeded(built);
|
|
@@ -218,7 +291,7 @@ export async function execute(opts) {
|
|
|
218
291
|
// all noops — no commit
|
|
219
292
|
}
|
|
220
293
|
else if (fileResult.appliedCount > 0) {
|
|
221
|
-
await
|
|
294
|
+
await commitBatch({
|
|
222
295
|
io,
|
|
223
296
|
files: [
|
|
224
297
|
{
|
|
@@ -236,7 +309,6 @@ export async function execute(opts) {
|
|
|
236
309
|
sandboxPolicy,
|
|
237
310
|
signal,
|
|
238
311
|
undoUnavailableMessage: () => "[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the batch was NOT applied and no file was written. Retry the batch, or use write if the store cannot be recovered.",
|
|
239
|
-
restoreUnwrittenUndos: false,
|
|
240
312
|
});
|
|
241
313
|
}
|
|
242
314
|
const built = buildBatchResult([toSection()]);
|
|
@@ -261,6 +333,7 @@ export async function commit(opts) {
|
|
|
261
333
|
sandboxPolicy: opts.sandboxPolicy,
|
|
262
334
|
signal: opts.signal,
|
|
263
335
|
undoUnavailableMessage: opts.undoUnavailableMessage,
|
|
264
|
-
restoreUnwrittenUndos: opts.restoreUnwrittenUndos,
|
|
336
|
+
restoreUnwrittenUndos: opts.restoreUnwrittenUndos ?? false,
|
|
265
337
|
});
|
|
266
338
|
}
|
|
339
|
+
export { commitSingle, commitBatch };
|
package/lib/paths.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
import { isAbsolute } from "node:path";
|
|
10
10
|
import { resolve as resolvePath } from "node:path";
|
|
11
11
|
import { expand } from "./store-tenancy.js";
|
|
12
|
-
export * from "./store
|
|
12
|
+
export * from "./store/index.js"; // Store seam — single answer for "which store, where" (tenancy+lifecycle+path)
|
|
13
13
|
export { canonicalAsync as resolveTarget } from "./canonical-path.js";
|
|
14
14
|
export { canonicalSync } from "./canonical-path.js";
|
|
15
15
|
export function toCwd(filePath, cwd) {
|
package/lib/read-and-serve.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { abortIf } from "./utils.js";
|
|
11
11
|
import { readView } from "./file-view.js";
|
|
12
|
+
import { getAutoGuessFooter } from "./fs-bridge.js";
|
|
12
13
|
import { recordServed, clearDriftReported } from "./session-view.js";
|
|
13
14
|
/** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
|
|
14
15
|
export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
|
|
@@ -26,6 +27,7 @@ export async function readAndServe(io, rawPath, cwd, options) {
|
|
|
26
27
|
const { sessionKey, signal } = options;
|
|
27
28
|
abortIf(signal);
|
|
28
29
|
const view = await readView(io, rawPath, cwd, {
|
|
30
|
+
encoding: options.encoding,
|
|
29
31
|
offset: options.offset,
|
|
30
32
|
limit: options.limit,
|
|
31
33
|
signal,
|
|
@@ -34,6 +36,8 @@ export async function readAndServe(io, rawPath, cwd, options) {
|
|
|
34
36
|
await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length);
|
|
35
37
|
}
|
|
36
38
|
await clearDriftReported(sessionKey, view.absolutePath);
|
|
39
|
+
const autoFooter = getAutoGuessFooter(view.absolutePath) ?? getAutoGuessFooter(rawPath) ?? getAutoGuessFooter(view.absolutePath.replace(/\\/g, "/")) ?? "";
|
|
40
|
+
const warning = autoFooter || undefined;
|
|
37
41
|
const text = view.hadUtf8DecodeErrors
|
|
38
42
|
? `${view.text}\n\n${UTF8_REWRITE_NOTE}`
|
|
39
43
|
: view.text;
|
|
@@ -42,5 +46,6 @@ export async function readAndServe(io, rawPath, cwd, options) {
|
|
|
42
46
|
served: view.served,
|
|
43
47
|
hadUtf8DecodeErrors: view.hadUtf8DecodeErrors,
|
|
44
48
|
absolutePath: view.absolutePath,
|
|
49
|
+
warning,
|
|
45
50
|
};
|
|
46
51
|
}
|
package/lib/session-view.js
CHANGED
|
@@ -1,63 +1,30 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* SessionView — deep module owning served rows + drift + position reconstruction.
|
|
3
3
|
*
|
|
4
|
-
* Previously
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* +
|
|
4
|
+
* Previously also owned workspace/session context (AsyncLocalStorage +
|
|
5
|
+
* execCwd/execSessionKey/sessionKeyFor + path re-exports) as
|
|
6
|
+
* "private to this seam, @internal". That mixed two invariants:
|
|
7
|
+
* served-merge+drift vs context propagation. Now this seam owns ONLY
|
|
8
|
+
* served state and drift; WorkspaceContext owns execution context.
|
|
8
9
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* servedPositionsOf, currentPositionOfDrifted, _mergeServedRows (via served-store)
|
|
10
|
+
* Public surface: _mergeServedRows, loadServed, recordServed,
|
|
11
|
+
* recordServedTruncated, driftReported, markDriftReported,
|
|
12
|
+
* clearDriftReported, wipeServedState, servedPositionsOf,
|
|
13
|
+
* currentPositionOfDrifted, computeDrift, scanDrift, and
|
|
14
|
+
* hash-store persistence delegation (ServedPersistence).
|
|
15
15
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* but are marked deprecated.
|
|
22
|
-
*
|
|
23
|
-
* Ownership: This file now OWNS the served-merge invariant
|
|
24
|
-
* (_mergeServedRows), the position-reconstruction math, and the drift
|
|
25
|
-
* computation. Deleting it would scatter the served+drift invariant
|
|
26
|
-
* across 4 files — it concentrates (deep).
|
|
16
|
+
* Ownership: This file OWNS the served-merge invariant
|
|
17
|
+
* (_mergeServedRows with orphan healing per ADR-0008), the
|
|
18
|
+
* position-reconstruction math, and the drift computation. Deleting
|
|
19
|
+
* it would scatter the served+drift invariant across 4 files — it
|
|
20
|
+
* concentrates (deep).
|
|
27
21
|
*
|
|
28
22
|
* @module dsh-better-edit/session-view
|
|
29
23
|
*/
|
|
30
|
-
import { randomUUID } from "node:crypto";
|
|
31
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
32
24
|
import { HASH_RE } from "./hashline/hash-assign.js";
|
|
33
25
|
import { loadHashStore, loadServedStore, withStore } from "./hash-store.js";
|
|
34
26
|
import { SERVED_ECHO_CAP } from "./constants.js";
|
|
35
|
-
import { fmtServedRows } from "./hashline/
|
|
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 };
|
|
27
|
+
import { fmtServedRows } from "./hashline/anchor-pipeline.js";
|
|
61
28
|
// --- hash-store re-export (persistence note) ---
|
|
62
29
|
export { loadHashStore, loadServedStore, shutdownHashStore, withStore } from "./hash-store.js";
|
|
63
30
|
/**
|