dsh-better-edit 0.5.1 → 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 +11 -0
- package/lib/edit-engine.js +4 -454
- package/lib/edit-response.js +24 -2
- package/lib/file-encoding-state.js +263 -0
- package/lib/fs-bridge.js +94 -251
- package/lib/hash-store.js +1 -1
- 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/session-view.js +16 -49
- package/lib/store/index.js +28 -0
- package/lib/store-lifecycle.js +1 -1
- package/lib/tool-edit.js +2 -2
- package/lib/tool-read.js +2 -2
- package/lib/tool-undo.js +2 -2
- 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/file-encoding-state.d.ts +77 -0
- package/lib/types/file-view.d.ts +1 -1
- package/lib/types/fs-bridge.d.ts +4 -11
- 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 +1 -1
- package/lib/types/session-view.d.ts +16 -30
- package/lib/types/store/index.d.ts +25 -0
- 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 +1 -1
|
@@ -2,25 +2,23 @@
|
|
|
2
2
|
* AnchorPipeline — deep module owning the anchor autofix chain.
|
|
3
3
|
*
|
|
4
4
|
* Single ordering invariant (private):
|
|
5
|
-
* swapReversed → stripBare → stripDiff → valEdit →
|
|
5
|
+
* swapReversed → stripBare → stripDiff → valEdit → verifyServed → resToSpan
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
* were split across resolve.ts / apply.ts with an implicit coupling.
|
|
9
|
-
* This seam co-locates that invariant. Public surface is two functions:
|
|
7
|
+
* This seam co-locates the ordering invariant. Public surface is two functions:
|
|
10
8
|
* resEdit — pre-validation (tool-layer, no file state)
|
|
11
9
|
* applyEdit — full pipeline (file + hashes + served verification)
|
|
12
10
|
*
|
|
13
11
|
* Private to this seam (not re-exported): stripBarePrefixes, stripDiffPrefixes,
|
|
14
|
-
* swapReversedRanges, valEdit,
|
|
12
|
+
* swapReversedRanges, valEdit, warnUnicodeEsc,
|
|
15
13
|
* resAnchorFromMap, assertAligned, etc. They remain exported from resolve.ts
|
|
16
14
|
* for backwards compat but are marked @internal and should be imported via this
|
|
17
15
|
* module only.
|
|
18
16
|
*
|
|
19
17
|
* @module dsh-better-edit/hashline/anchor-pipeline
|
|
20
18
|
*/
|
|
21
|
-
import { abortIf, splitLines, rejectUnknownFields,
|
|
19
|
+
import { abortIf, splitLines, rejectUnknownFields, clipLine } from "../utils.js";
|
|
22
20
|
import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HASH_SEP, ANCHOR_LEN, ALPH_RE, canon, lineHashesPure, getCanonForHash, rememberHashCanon } from "./hash-assign.js";
|
|
23
|
-
import { recordServed, servedPositionsOf } from "../
|
|
21
|
+
import { recordServed, servedPositionsOf } from "../session-view.js";
|
|
24
22
|
import { SERVED_ECHO_CAP } from "../constants.js";
|
|
25
23
|
import { NEW_CONTENT_NOT_STRING_MSG } from "../constants.js";
|
|
26
24
|
function diagRef(ref) {
|
|
@@ -281,126 +279,10 @@ function swapReversedRanges(edit, fileHashes, warnings) {
|
|
|
281
279
|
warnings.push(`[E_BAD_OP] reversed remove_from/remove_to (${startRef.hash} after ${endRef.hash}); swapped.`);
|
|
282
280
|
return { ...edit, hash_bounds: [endRef, startRef] };
|
|
283
281
|
}
|
|
284
|
-
function trailingDups(contentLines, fileLines, endLine) {
|
|
285
|
-
const start = lastNonEmptyIndex(contentLines);
|
|
286
|
-
if (start < 0)
|
|
287
|
-
return [];
|
|
288
|
-
const dups = [];
|
|
289
|
-
const maxK = Math.min(start + 1, fileLines.length - endLine);
|
|
290
|
-
for (let k = 0; k < maxK; k++) {
|
|
291
|
-
if (contentLines[start - k] !== fileLines[endLine + k])
|
|
292
|
-
break;
|
|
293
|
-
dups.push({ kind: "trailing", replacementLineIndex: start - k });
|
|
294
|
-
}
|
|
295
|
-
return dups;
|
|
296
|
-
}
|
|
297
|
-
function leadingDups(contentLines, fileLines, startLine) {
|
|
298
|
-
const start = firstNonEmptyIndex(contentLines);
|
|
299
|
-
if (start < 0)
|
|
300
|
-
return [];
|
|
301
|
-
const dups = [];
|
|
302
|
-
const maxK = Math.min(contentLines.length - start, startLine - 1);
|
|
303
|
-
for (let k = 0; k < maxK; k++) {
|
|
304
|
-
if (contentLines[start + k] !== fileLines[startLine - 2 - k])
|
|
305
|
-
break;
|
|
306
|
-
dups.push({ kind: "leading", replacementLineIndex: start + k });
|
|
307
|
-
}
|
|
308
|
-
return dups;
|
|
309
|
-
}
|
|
310
|
-
function sectionIsUnique(canonLines, start, length) {
|
|
311
|
-
let count = 0;
|
|
312
|
-
for (let i = 0; i + length <= canonLines.length; i++) {
|
|
313
|
-
let k = 0;
|
|
314
|
-
while (k < length && canonLines[i + k] === canonLines[start + k])
|
|
315
|
-
k++;
|
|
316
|
-
if (k < length)
|
|
317
|
-
continue;
|
|
318
|
-
count++;
|
|
319
|
-
if (count > 1)
|
|
320
|
-
return false;
|
|
321
|
-
}
|
|
322
|
-
return true;
|
|
323
|
-
}
|
|
324
|
-
function firstNewAfterDups(contentLines, rangeLines, canonLines, endLine) {
|
|
325
|
-
const firstNew = findNewEdge(contentLines, rangeLines, false);
|
|
326
|
-
if (!firstNew)
|
|
327
|
-
return [];
|
|
328
|
-
const maxK = Math.min(contentLines.length - firstNew.index, canonLines.length - endLine);
|
|
329
|
-
let runLen = 0;
|
|
330
|
-
while (runLen < maxK &&
|
|
331
|
-
canon(contentLines[firstNew.index + runLen]) ===
|
|
332
|
-
canonLines[endLine + runLen]) {
|
|
333
|
-
runLen++;
|
|
334
|
-
}
|
|
335
|
-
if (runLen === 0 || !sectionIsUnique(canonLines, endLine, runLen))
|
|
336
|
-
return [];
|
|
337
|
-
const dups = [];
|
|
338
|
-
for (let k = 0; k < runLen; k++) {
|
|
339
|
-
dups.push({
|
|
340
|
-
kind: "first-new-after",
|
|
341
|
-
replacementLineIndex: firstNew.index + k,
|
|
342
|
-
});
|
|
343
|
-
}
|
|
344
|
-
return dups;
|
|
345
|
-
}
|
|
346
|
-
function lastNewBeforeDups(contentLines, rangeLines, canonLines, startLine) {
|
|
347
|
-
const lastNew = findNewEdge(contentLines, rangeLines, true);
|
|
348
|
-
if (!lastNew)
|
|
349
|
-
return [];
|
|
350
|
-
const maxK = Math.min(lastNew.index + 1, startLine - 1);
|
|
351
|
-
let runLen = 0;
|
|
352
|
-
while (runLen < maxK &&
|
|
353
|
-
canon(contentLines[lastNew.index - runLen]) ===
|
|
354
|
-
canonLines[startLine - 2 - runLen]) {
|
|
355
|
-
runLen++;
|
|
356
|
-
}
|
|
357
|
-
if (runLen === 0)
|
|
358
|
-
return [];
|
|
359
|
-
const sectionStart = startLine - 1 - runLen;
|
|
360
|
-
if (!sectionIsUnique(canonLines, sectionStart, runLen))
|
|
361
|
-
return [];
|
|
362
|
-
const dups = [];
|
|
363
|
-
for (let k = 0; k < runLen; k++) {
|
|
364
|
-
dups.push({
|
|
365
|
-
kind: "last-new-before",
|
|
366
|
-
replacementLineIndex: lastNew.index - k,
|
|
367
|
-
});
|
|
368
|
-
}
|
|
369
|
-
return dups;
|
|
370
|
-
}
|
|
371
|
-
function canonCounts(lines) {
|
|
372
|
-
const counts = new Map();
|
|
373
|
-
for (const line of lines) {
|
|
374
|
-
const key = canon(line);
|
|
375
|
-
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
376
|
-
}
|
|
377
|
-
return counts;
|
|
378
|
-
}
|
|
379
282
|
/** @internal — private to anchor-pipeline seam */
|
|
380
|
-
export function findNewEdge(contentLines, rangeLines, fromEnd) {
|
|
381
|
-
const multiset = canonCounts(rangeLines);
|
|
382
|
-
const step = fromEnd ? -1 : 1;
|
|
383
|
-
const start = fromEnd ? contentLines.length - 1 : 0;
|
|
384
|
-
for (let i = start; i >= 0 && i < contentLines.length; i += step) {
|
|
385
|
-
const line = contentLines[i];
|
|
386
|
-
if (line.length === 0)
|
|
387
|
-
continue;
|
|
388
|
-
const key = canon(line);
|
|
389
|
-
const count = multiset.get(key) ?? 0;
|
|
390
|
-
if (count > 0) {
|
|
391
|
-
multiset.set(key, count - 1);
|
|
392
|
-
}
|
|
393
|
-
else {
|
|
394
|
-
return { index: i, line };
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
return undefined;
|
|
398
|
-
}
|
|
399
|
-
/** @internal — private to anchor-pipeline seam: detection + boundaryDups belongs to AnchorPipeline ordering */
|
|
400
283
|
function valEdit(edit, fileLines, fileHashes, warnings, signal) {
|
|
401
284
|
assertAligned(fileLines, fileHashes, "valEdit");
|
|
402
285
|
const mismatches = [];
|
|
403
|
-
const boundaryDups = [];
|
|
404
286
|
const hashIndex = new Map();
|
|
405
287
|
for (let i = 0; i < fileHashes.length; i++) {
|
|
406
288
|
const h = fileHashes[i];
|
|
@@ -430,24 +312,21 @@ function valEdit(edit, fileLines, fileHashes, warnings, signal) {
|
|
|
430
312
|
if (endMismatch && endMismatch.kind === "not_found")
|
|
431
313
|
endMismatch.context = startResolved;
|
|
432
314
|
}
|
|
433
|
-
return { resolved: undefined, mismatches
|
|
315
|
+
return { resolved: undefined, mismatches };
|
|
434
316
|
}
|
|
435
317
|
if (startResolved.line > endResolved.line) {
|
|
436
318
|
throw new Error(`[E_BAD_OP] Range start line ${startResolved.line} must be <= end line ${endResolved.line} (anchors ${edit.hash_bounds[0].hash} and ${edit.hash_bounds[1].hash}).`);
|
|
437
319
|
}
|
|
438
320
|
const endLine = endResolved.line;
|
|
439
|
-
const rangeLines = fileLines.slice(startResolved.line - 1, endLine);
|
|
440
|
-
const canonLines = fileLines.map((line) => canon(line));
|
|
441
|
-
boundaryDups.push(...trailingDups(edit.content_lines, fileLines, endLine), ...leadingDups(edit.content_lines, fileLines, startResolved.line), ...firstNewAfterDups(edit.content_lines, rangeLines, canonLines, endLine), ...lastNewBeforeDups(edit.content_lines, rangeLines, canonLines, startResolved.line));
|
|
442
321
|
return {
|
|
443
322
|
resolved: {
|
|
444
323
|
content_lines: edit.content_lines,
|
|
445
324
|
hash_bounds: [startResolved, endResolved],
|
|
446
325
|
},
|
|
447
326
|
mismatches,
|
|
448
|
-
boundaryDups,
|
|
449
327
|
};
|
|
450
328
|
}
|
|
329
|
+
export function findNewEdge() { return undefined; }
|
|
451
330
|
export { warnUnicodeEsc };
|
|
452
331
|
export class ServedRejectionError extends Error {
|
|
453
332
|
code;
|
|
@@ -876,47 +755,13 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
|
|
|
876
755
|
const warnings = [];
|
|
877
756
|
const rangeFixed = swapReversedRanges(edit, fileHashes, warnings);
|
|
878
757
|
const prefixFixed = stripDiffPrefixes(stripBarePrefixes(rangeFixed, fileHashes, warnings), warnings);
|
|
879
|
-
const { resolved: initialResolved, mismatches,
|
|
758
|
+
const { resolved: initialResolved, mismatches, } = valEdit(prefixFixed, lineIndex.fileLines, fileHashes, warnings, signal);
|
|
880
759
|
if (mismatches.length || !initialResolved) {
|
|
881
760
|
const { message, servedRows } = fmtMismatchWithServes(mismatches, lineIndex.fileLines, fileHashes, filePath);
|
|
882
761
|
throw new AnchorMismatchError(message, servedRows);
|
|
883
762
|
}
|
|
884
763
|
warnUnicodeEsc(prefixFixed, warnings);
|
|
885
|
-
|
|
886
|
-
let autoFixes;
|
|
887
|
-
if (boundaryDups.length > 0) {
|
|
888
|
-
autoFixes = [];
|
|
889
|
-
const correctedEdit = {
|
|
890
|
-
...prefixFixed,
|
|
891
|
-
content_lines: [...prefixFixed.content_lines],
|
|
892
|
-
};
|
|
893
|
-
const seen = new Set();
|
|
894
|
-
const uniqueDups = [];
|
|
895
|
-
for (const dup of boundaryDups) {
|
|
896
|
-
if (seen.has(dup.replacementLineIndex))
|
|
897
|
-
continue;
|
|
898
|
-
seen.add(dup.replacementLineIndex);
|
|
899
|
-
uniqueDups.push(dup);
|
|
900
|
-
}
|
|
901
|
-
const dupsByIndex = uniqueDups.sort((a, b) => b.replacementLineIndex - a.replacementLineIndex);
|
|
902
|
-
for (const dup of dupsByIndex) {
|
|
903
|
-
const idx = dup.replacementLineIndex;
|
|
904
|
-
if (idx < 0 || idx >= correctedEdit.content_lines.length)
|
|
905
|
-
continue;
|
|
906
|
-
const removed = correctedEdit.content_lines.splice(idx, 1)[0];
|
|
907
|
-
autoFixes.push({
|
|
908
|
-
kind: dup.kind,
|
|
909
|
-
removedLine: removed,
|
|
910
|
-
removedLineIndex: idx,
|
|
911
|
-
});
|
|
912
|
-
}
|
|
913
|
-
const correctedResult = valEdit(correctedEdit, lineIndex.fileLines, fileHashes, warnings, signal);
|
|
914
|
-
if (correctedResult.mismatches.length || !correctedResult.resolved) {
|
|
915
|
-
const { message, servedRows } = fmtMismatchWithServes(correctedResult.mismatches, lineIndex.fileLines, fileHashes, filePath);
|
|
916
|
-
throw new AnchorMismatchError(message, servedRows);
|
|
917
|
-
}
|
|
918
|
-
resolved = correctedResult.resolved;
|
|
919
|
-
}
|
|
764
|
+
const resolved = initialResolved;
|
|
920
765
|
if (served) {
|
|
921
766
|
const startLineEcho = resolved.hash_bounds[0].line;
|
|
922
767
|
const rawEcho = findEditHashEcho(edit.content_lines, served, startLineEcho);
|
|
@@ -965,7 +810,6 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
|
|
|
965
810
|
lastChangedLine: changed?.lastChangedLine,
|
|
966
811
|
range: resolvedRange(resolved),
|
|
967
812
|
...(warnings.length ? { warnings } : {}),
|
|
968
|
-
...(autoFixes ? { autoFixes } : {}),
|
|
969
813
|
};
|
|
970
814
|
}
|
|
971
815
|
function resolvedRange(resolved) {
|
|
@@ -1019,3 +863,13 @@ export function changedRange(original, result) {
|
|
|
1019
863
|
lastChangedLine: Math.max(first, lastRes) + 1,
|
|
1020
864
|
};
|
|
1021
865
|
}
|
|
866
|
+
// ---------------------------------------------------------------------------
|
|
867
|
+
// Sealed seam — single public entry for hashline (Candidate 5)
|
|
868
|
+
// HashAssign allocation + hash persistence re-exported here so callers import
|
|
869
|
+
// only from anchor-pipeline. Private modules (hash-assign, hash, hasher,
|
|
870
|
+
// alphabet, pure, parse, apply, resolve, served) are @internal and guarded
|
|
871
|
+
// by biome noRestrictedImports. Deleting this re-export block would scatter
|
|
872
|
+
// the hashline surface again — it concentrates (deep).
|
|
873
|
+
// ---------------------------------------------------------------------------
|
|
874
|
+
export { HASH_RE, HASH_CLASS, HASH_SEP, ANCHOR_LEN, ALPH_RE, ALPH, HASH_LEN, HASH_SPACE, MAX_HASH_LINES, HASH_PROBE_STRIDE, CANON_VERSION, canon, lineHashesPure, mapStableHashes, initHasher, contentChecksum, getCanonForHash, rememberHashCanon, } from "./hash-assign.js";
|
|
875
|
+
export { lineHashes } from "./hash.js";
|
package/lib/index.js
CHANGED
|
@@ -23,9 +23,9 @@ import { registerUndoTool } from "./tool-undo.js";
|
|
|
23
23
|
import { registerWriteHook } from "./write-hook.js";
|
|
24
24
|
import { initHasher } from "./hashline/hash-assign.js";
|
|
25
25
|
import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
|
|
26
|
-
import { configDir } from "./
|
|
26
|
+
import { configDir } from "./store/index.js";
|
|
27
27
|
import { ensureDefaultConfig } from "./store-config.js";
|
|
28
|
-
import { onAppStart, onSessionStart } from "./store
|
|
28
|
+
import { onAppStart, onSessionStart } from "./store/index.js";
|
|
29
29
|
/** Cordis plugin name used by loader diagnostics. */
|
|
30
30
|
export const name = "dsh-better-edit";
|
|
31
31
|
/**
|
|
@@ -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
|