dsh-better-edit 0.8.2 → 1.1.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 +173 -99
- package/README.md +61 -33
- package/README.zh.md +20 -17
- package/cordis.patch.yml +1 -1
- package/lib/constants.js +19 -4
- package/lib/contract.js +136 -79
- package/lib/domain-errors.js +570 -0
- package/lib/edit-diff.js +33 -7
- package/lib/file-encoding-state.js +27 -7
- package/lib/file-view.js +305 -82
- package/lib/fs-bridge.js +23 -7
- package/lib/guidance/materialize.js +7 -7
- package/lib/guidance/resolve.js +13 -8
- package/lib/hash-store.js +404 -278
- package/lib/hashline/anchor-pipeline.js +586 -378
- package/lib/hashline/hash-assign.js +21 -22
- package/lib/hashline/hash.js +6 -6
- package/lib/hashline/index.js +1 -1
- package/lib/hashline/resolve.js +1 -1
- package/lib/hashline/served-guard.js +181 -0
- package/lib/index.js +37 -11
- package/lib/mutation/engine.js +392 -96
- package/lib/mutation.js +22 -130
- package/lib/noop-guard.js +20 -9
- package/lib/prompts.js +20 -18
- package/lib/read-and-serve.js +44 -20
- package/lib/sandbox.js +1 -1
- package/lib/session-view.js +57 -43
- package/lib/snapshot-store/index.js +97 -0
- package/lib/snapshot-store/lineage-store.js +400 -0
- package/lib/snapshot-store/migrate.js +80 -0
- package/lib/snapshot-store/pairing.js +412 -0
- package/lib/snapshot-store/txn.js +63 -0
- package/lib/snapshot-store/vacuum.js +243 -0
- package/lib/store-lifecycle.js +13 -1
- package/lib/store-retry.js +34 -0
- package/lib/tool-edit.js +90 -44
- package/lib/tool-read.js +29 -1
- package/lib/tool-str-replace-editor.js +26 -18
- package/lib/tool-undo.js +25 -8
- package/lib/types/constants.d.ts +5 -2
- package/lib/types/contract.d.ts +76 -71
- package/lib/types/domain-errors.d.ts +410 -0
- package/lib/types/edit-response.d.ts +1 -1
- package/lib/types/file-encoding-state.d.ts +1 -0
- package/lib/types/file-view.d.ts +35 -6
- package/lib/types/guidance/materialize.d.ts +2 -2
- package/lib/types/guidance/resolve.d.ts +14 -2
- package/lib/types/hash-store.d.ts +38 -19
- package/lib/types/hashline/anchor-pipeline.d.ts +117 -36
- package/lib/types/hashline/hash-assign.d.ts +5 -5
- package/lib/types/hashline/hash.d.ts +1 -1
- package/lib/types/hashline/index.d.ts +2 -2
- package/lib/types/hashline/served-guard.d.ts +100 -0
- package/lib/types/index.d.ts +3 -3
- package/lib/types/mutation/engine.d.ts +49 -30
- package/lib/types/mutation.d.ts +1 -39
- package/lib/types/noop-guard.d.ts +4 -4
- package/lib/types/prompts.d.ts +1 -1
- package/lib/types/read-and-serve.d.ts +6 -0
- package/lib/types/sandbox.d.ts +1 -1
- package/lib/types/session-view.d.ts +38 -9
- package/lib/types/snapshot-store/index.d.ts +28 -0
- package/lib/types/snapshot-store/lineage-store.d.ts +96 -0
- package/lib/types/snapshot-store/migrate.d.ts +16 -0
- package/lib/types/snapshot-store/pairing.d.ts +99 -0
- package/lib/types/snapshot-store/txn.d.ts +12 -0
- package/lib/types/snapshot-store/vacuum.d.ts +79 -0
- package/lib/types/store-lifecycle.d.ts +0 -1
- package/lib/types/store-retry.d.ts +6 -0
- package/lib/types/tool-edit.d.ts +2 -2
- package/lib/types/tool-str-replace-editor.d.ts +2 -2
- package/lib/types/utils.d.ts +5 -6
- package/lib/types/workspace-context.d.ts +10 -1
- package/lib/undo-edit.js +27 -11
- package/lib/utils.js +12 -12
- package/lib/workspace-context.js +27 -9
- package/lib/write-hook.js +13 -4
- package/package.json +28 -30
package/lib/mutation/engine.js
CHANGED
|
@@ -6,40 +6,55 @@
|
|
|
6
6
|
* content, the noop-loop guard, and the persist-undo → write → restore
|
|
7
7
|
* Transaction (persist-undo → write → restore) is owned by Mutation, not this engine.
|
|
8
8
|
*
|
|
9
|
-
* The model-facing contract lives here unchanged:
|
|
10
|
-
*
|
|
11
|
-
*
|
|
9
|
+
* The model-facing contract lives here unchanged: E_BATCH_ABORT,
|
|
10
|
+
* E_NOOP_LOOP, E_UNDO_UNAVAILABLE carry byte-identical messages, and
|
|
11
|
+
* a rejection rethrows with the current-range echo and records/grants nothing.
|
|
12
12
|
* @module dsh-better-edit/mutation/engine
|
|
13
13
|
*/
|
|
14
|
+
import { loadHashStore } from "../hash-store.js";
|
|
14
15
|
import { loadConfig } from "../store-config.js";
|
|
15
16
|
import { canon } from "../hashline/hash-assign.js";
|
|
16
|
-
import { fileSnap } from "../file-view.js";
|
|
17
17
|
import { normFromText } from "../file-reader.js";
|
|
18
|
-
import { scanDrift, loadServed, loadServedCanons,
|
|
18
|
+
import { scanDrift, loadServed, loadServedCanons, loadRetiredAnchors, retireAnchors, } from "../session-view.js";
|
|
19
19
|
import { applyEdit, resEdit, parseHashRef, } from "../hashline/anchor-pipeline.js";
|
|
20
20
|
import { lineHashes } from "../hashline/hash.js";
|
|
21
21
|
import { AnchorSpaceExhaustedError, HASH_SPACE } from "../hashline/hash-assign.js";
|
|
22
|
+
import { buildNeverServedEditHint } from "../hashline/served-guard.js";
|
|
22
23
|
function isAnchorSpaceExhausted(e) {
|
|
23
24
|
return (e instanceof AnchorSpaceExhaustedError ||
|
|
24
|
-
(e instanceof Error && e.message.includes("
|
|
25
|
+
(e instanceof Error && e.message.includes("probing failed over")));
|
|
25
26
|
}
|
|
26
27
|
function promotionWarning(retiredSize, servedLen) {
|
|
27
|
-
|
|
28
|
+
// Soft promotion notice: plain non-header text (no [E_] code, no audience).
|
|
29
|
+
// The hard capacity refusal routes through E_LARGE_FILE (hash-space).
|
|
30
|
+
return `Anchor space exhausted (retired ${retiredSize} + served ${servedLen} of ${HASH_SPACE}); promotion cleared retired — re-read recommended, stale-anchor checks degraded until next full read.`;
|
|
28
31
|
}
|
|
29
32
|
async function clearRetiredForPromotion(sessionKey, absolutePath) {
|
|
33
|
+
let store;
|
|
30
34
|
try {
|
|
31
35
|
const { loadServedStore } = await import("../hash-store.js");
|
|
32
|
-
|
|
36
|
+
store = await loadServedStore();
|
|
33
37
|
store.clearRetiredAnchors(sessionKey ?? "", absolutePath);
|
|
34
|
-
try {
|
|
35
|
-
store.clearCards(sessionKey ?? "", absolutePath);
|
|
36
|
-
}
|
|
37
|
-
catch { }
|
|
38
38
|
}
|
|
39
|
-
catch {
|
|
39
|
+
catch (error) {
|
|
40
|
+
return (`promotion could not clear retired anchors for ${absolutePath} ` +
|
|
41
|
+
`(${error instanceof Error ? error.message : String(error)}); ` +
|
|
42
|
+
"stale-anchor checks stay degraded until the next full read.");
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
store.clearCards(sessionKey ?? "", absolutePath);
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
return (`promotion could not clear the reported cards for ${absolutePath} ` +
|
|
50
|
+
`(${error instanceof Error ? error.message : String(error)}); ` +
|
|
51
|
+
"the next read may still compare against the pre-promotion range.");
|
|
52
|
+
}
|
|
40
53
|
}
|
|
41
54
|
async function retryLineHashesWithPromotion(sessionKey, absolutePath, retired, served, warnings, fn) {
|
|
42
|
-
await clearRetiredForPromotion(sessionKey, absolutePath);
|
|
55
|
+
const clearWarning = await clearRetiredForPromotion(sessionKey, absolutePath);
|
|
56
|
+
if (clearWarning !== undefined)
|
|
57
|
+
warnings.push(clearWarning);
|
|
43
58
|
const servedLen = served?.filter((h) => h !== null).length ?? 0;
|
|
44
59
|
warnings.push(promotionWarning(retired?.size ?? 0, servedLen));
|
|
45
60
|
const recomputed = new Set((served?.filter((h) => h !== null) ?? []));
|
|
@@ -48,12 +63,13 @@ async function retryLineHashesWithPromotion(sessionKey, absolutePath, retired, s
|
|
|
48
63
|
}
|
|
49
64
|
catch (e2) {
|
|
50
65
|
if (isAnchorSpaceExhausted(e2))
|
|
51
|
-
throw new
|
|
66
|
+
throw new DomainError("E_LARGE_FILE", { limitKind: "hash-space", limit: HASH_SPACE });
|
|
52
67
|
throw e2;
|
|
53
68
|
}
|
|
54
69
|
}
|
|
55
70
|
import { MAX_HASH_LINES } from "../hashline/hash-assign.js";
|
|
56
|
-
import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows,
|
|
71
|
+
import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, } from "../hashline/anchor-pipeline.js";
|
|
72
|
+
import { DomainError, formatError, formatWarning } from "../domain-errors.js";
|
|
57
73
|
import { findSnapshotPathsByHashes } from "../hash-store.js";
|
|
58
74
|
import { clearNoopLoop, noopPayloadKey, trackNoopPayload } from "../noop-guard.js";
|
|
59
75
|
import { NOOP_LOOP_THRESHOLD } from "../constants.js";
|
|
@@ -68,8 +84,8 @@ import { abortIf, splitLines } from "../utils.js";
|
|
|
68
84
|
export async function resolveMissingPath(request) {
|
|
69
85
|
if (typeof request.path === "string")
|
|
70
86
|
return undefined;
|
|
71
|
-
const from = request.
|
|
72
|
-
const to = request.
|
|
87
|
+
const from = request.anchor_from;
|
|
88
|
+
const to = request.anchor_to;
|
|
73
89
|
if (typeof from !== "string" || typeof to !== "string")
|
|
74
90
|
return undefined;
|
|
75
91
|
const hashes = [];
|
|
@@ -91,11 +107,15 @@ export async function resolveMissingPath(request) {
|
|
|
91
107
|
if (matches.length === 1) {
|
|
92
108
|
return {
|
|
93
109
|
path: matches[0],
|
|
94
|
-
warning:
|
|
110
|
+
warning: formatError("E_BAD_PAYLOAD", {
|
|
111
|
+
message: `Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
|
|
112
|
+
}),
|
|
95
113
|
};
|
|
96
114
|
}
|
|
97
115
|
if (matches.length > 1) {
|
|
98
|
-
throw new
|
|
116
|
+
throw new DomainError("E_BAD_PAYLOAD", {
|
|
117
|
+
message: `Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(", ")}. Include the intended path.`,
|
|
118
|
+
});
|
|
99
119
|
}
|
|
100
120
|
return undefined;
|
|
101
121
|
}
|
|
@@ -136,8 +156,9 @@ export function countLineChanges(edit, originalHashes, isNoop, removedAutoFixes)
|
|
|
136
156
|
*
|
|
137
157
|
* `onReject` owns the reject-and-serve policy: it receives resolve/verify
|
|
138
158
|
* failures (and the edit that failed, when resolved) and MUST throw. The
|
|
139
|
-
* single path rethrows the original anchor error
|
|
140
|
-
*
|
|
159
|
+
* single path rethrows the original anchor error; the batch path wraps with
|
|
160
|
+
* E_BATCH_ABORT plus the current-range echo. A rejection records and grants
|
|
161
|
+
* nothing — the recovery is the re-read the message already instructs.
|
|
141
162
|
*/
|
|
142
163
|
export async function applyOne(input, onReject) {
|
|
143
164
|
let edit;
|
|
@@ -147,9 +168,9 @@ export async function applyOne(input, onReject) {
|
|
|
147
168
|
else {
|
|
148
169
|
try {
|
|
149
170
|
edit = resEdit({
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
171
|
+
anchor_from: input.anchorFrom,
|
|
172
|
+
anchor_to: input.anchorTo,
|
|
173
|
+
replace_with: input.replaceWith,
|
|
153
174
|
}, input.warnings);
|
|
154
175
|
}
|
|
155
176
|
catch (error) {
|
|
@@ -159,7 +180,7 @@ export async function applyOne(input, onReject) {
|
|
|
159
180
|
const retiredForApply = input.retired;
|
|
160
181
|
let anchorResult;
|
|
161
182
|
try {
|
|
162
|
-
anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served, input.servedCanons, retiredForApply, input.
|
|
183
|
+
anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served, input.servedCanons, retiredForApply, input.mode, input.leaseSource);
|
|
163
184
|
}
|
|
164
185
|
catch (error) {
|
|
165
186
|
if (error instanceof AnchorMismatchError || error instanceof ServedRejectionError) {
|
|
@@ -207,39 +228,38 @@ export async function applyOne(input, onReject) {
|
|
|
207
228
|
totalAddedLines,
|
|
208
229
|
totalRemovedLines,
|
|
209
230
|
anchorWarnings: anchorResult.warnings,
|
|
231
|
+
neverServedCount: anchorResult.neverServedCount ?? 0,
|
|
210
232
|
};
|
|
211
233
|
}
|
|
212
234
|
/**
|
|
213
235
|
* The shared noop-loop guard. Returns the "twice in a row" notice for the
|
|
214
|
-
* caller to append to warnings, or throws
|
|
215
|
-
* echo
|
|
236
|
+
* caller to append to warnings, or throws E_NOOP_LOOP (with the current-range
|
|
237
|
+
* echo) once the payload has been submitted NOOP_LOOP_THRESHOLD times
|
|
216
238
|
* with no change. Messages are byte-identical to the pre-engine tools.
|
|
217
239
|
*/
|
|
218
240
|
export async function enforceNoopLoop(opts) {
|
|
219
|
-
const {
|
|
220
|
-
if (index === undefined) {
|
|
221
|
-
if (count >= NOOP_LOOP_THRESHOLD) {
|
|
222
|
-
const echoRows = buildRangeEcho(opts.range.startLine, opts.range.endLine, originalHashes);
|
|
223
|
-
const echo = fmtServedRows(echoRows, splitLines(opts.originalNormalized));
|
|
224
|
-
await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
225
|
-
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}`);
|
|
226
|
-
}
|
|
227
|
-
if (count === 2) {
|
|
228
|
-
return `[E_NOOP_LOOP] Notice: identical edit (${removeFrom} → ${removeTo} in ${displayPath}) no-op'd twice; range already has this text. Resend will reject.`;
|
|
229
|
-
}
|
|
230
|
-
return undefined;
|
|
231
|
-
}
|
|
241
|
+
const { anchorFrom, anchorTo, displayPath, index, count } = opts;
|
|
232
242
|
if (count >= NOOP_LOOP_THRESHOLD) {
|
|
233
243
|
const originalLines = splitLines(opts.originalNormalized);
|
|
234
244
|
const echoRows = opts.echoRows;
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
245
|
+
throw new DomainError("E_NOOP_LOOP", {
|
|
246
|
+
ref: `edits[${index}] (${displayPath})`,
|
|
247
|
+
anchorFrom,
|
|
248
|
+
anchorTo,
|
|
249
|
+
count,
|
|
250
|
+
batch: true,
|
|
251
|
+
// F5: pass raw rows — the registry owns the `Current on-disk range:` heading.
|
|
252
|
+
servedBlock: echoRows ? fmtServedRows(echoRows, originalLines) : "",
|
|
253
|
+
});
|
|
240
254
|
}
|
|
241
255
|
if (count === 2) {
|
|
242
|
-
return
|
|
256
|
+
return formatWarning("W_NOOP", {
|
|
257
|
+
ref: `edits[${index}] (${displayPath})`,
|
|
258
|
+
anchorFrom,
|
|
259
|
+
anchorTo,
|
|
260
|
+
batch: true,
|
|
261
|
+
count,
|
|
262
|
+
});
|
|
243
263
|
}
|
|
244
264
|
return undefined;
|
|
245
265
|
}
|
|
@@ -254,6 +274,217 @@ function echoRowsForItem(edit, originalHashes) {
|
|
|
254
274
|
return undefined;
|
|
255
275
|
return buildRangeEcho(Math.min(s, e) + 1, Math.max(s, e) + 1, originalHashes);
|
|
256
276
|
}
|
|
277
|
+
/**
|
|
278
|
+
* Shared echo resolution for batch rejections: prefer the failure's own
|
|
279
|
+
* rows, else the resolved edit's rows. The rows are rendered into the
|
|
280
|
+
* envelope only — a rejection records and grants nothing.
|
|
281
|
+
*/
|
|
282
|
+
async function collectAbortPart(opts) {
|
|
283
|
+
const echoRows = opts.error.servedRows.length > 0
|
|
284
|
+
? opts.error.servedRows
|
|
285
|
+
: opts.edit
|
|
286
|
+
? echoRowsForItem(opts.edit, opts.originalHashes)
|
|
287
|
+
: undefined;
|
|
288
|
+
const originalLines = splitLines(opts.originalNormalized);
|
|
289
|
+
const fmtBlock = echoRows ? fmtServedRows(echoRows, originalLines) : "";
|
|
290
|
+
const echoBlock = echoRows
|
|
291
|
+
? ` Current on-disk range for edits[${opts.index}] (unchanged — nothing was written):\n${fmtBlock}`
|
|
292
|
+
: " Call read() to get fresh anchors.";
|
|
293
|
+
return {
|
|
294
|
+
index: opts.index,
|
|
295
|
+
inner: opts.error.message,
|
|
296
|
+
echoRows,
|
|
297
|
+
echoBlock,
|
|
298
|
+
fmtBlock,
|
|
299
|
+
cause: opts.error.cause,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* One aggregated E_BATCH_ABORT for every failing item (C). A single part
|
|
304
|
+
* renders byte-identically to the legacy single-failure envelope; several
|
|
305
|
+
* parts name every failing item in order with the plural fix sentence.
|
|
306
|
+
* `code` routes the typed path via the first item; servedRows unions every
|
|
307
|
+
* part's rows; servedBlock joins every part's block; cause/details ride
|
|
308
|
+
* only on unanimous diagnosis (DomainError builds details from cause).
|
|
309
|
+
*/
|
|
310
|
+
function buildBatchAbort(file, parts) {
|
|
311
|
+
const first = parts[0];
|
|
312
|
+
const rows = [];
|
|
313
|
+
const blocks = [];
|
|
314
|
+
for (const part of parts) {
|
|
315
|
+
if (part.echoRows)
|
|
316
|
+
rows.push(...part.echoRows);
|
|
317
|
+
if (part.fmtBlock)
|
|
318
|
+
blocks.push(part.fmtBlock);
|
|
319
|
+
}
|
|
320
|
+
const base = {
|
|
321
|
+
index: first.index,
|
|
322
|
+
path: file,
|
|
323
|
+
inner: first.inner,
|
|
324
|
+
echoBlock: first.echoBlock,
|
|
325
|
+
servedRows: rows,
|
|
326
|
+
servedBlock: blocks.join("\n"),
|
|
327
|
+
};
|
|
328
|
+
if (parts.length === 1) {
|
|
329
|
+
// FU-7 conformance (b92e0ec:src/mutation-engine/pipeline.ts:531-560 — `batchAbortFor`): the
|
|
330
|
+
// single-failing-item stage forwards the item's `details.cause` untouched; unanimity is
|
|
331
|
+
// trivially true for one item, so the base envelope must not drop it.
|
|
332
|
+
return new DomainError("E_BATCH_ABORT", {
|
|
333
|
+
...base,
|
|
334
|
+
...(first.cause !== undefined ? { cause: first.cause } : {}),
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
const firstCause = parts[0].cause;
|
|
338
|
+
const unanimous = firstCause !== undefined && parts.every((part) => part.cause === firstCause);
|
|
339
|
+
return new DomainError("E_BATCH_ABORT", {
|
|
340
|
+
...base,
|
|
341
|
+
failures: parts.map((part) => ({ index: part.index, inner: part.inner })),
|
|
342
|
+
...(unanimous ? { cause: firstCause } : {}),
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
/** The `makeDomainStore` object behind the narrowed `HashStore` view. */
|
|
346
|
+
function internalStore(store) {
|
|
347
|
+
// SAFETY: `loadHashStore` and `options.store` return the `makeDomainStore` object, which
|
|
348
|
+
// implements `InternalHashStore`; `HashStore` is its narrowed public view (the same cast
|
|
349
|
+
// session-view.ts documents for its served view).
|
|
350
|
+
return store;
|
|
351
|
+
}
|
|
352
|
+
// WHY — KEEL K-1: every sibling degrade path signals at warn tier through a module-owned ledger
|
|
353
|
+
// (`reportVacuum`'s overflow/skip sets); a throwing `positionsByIdentity` was the one silent
|
|
354
|
+
// fail-open — it silently downgraded the leased-identity guard to the unconditional position
|
|
355
|
+
// check. One warn per file path: the identity of the degrade is the path, stable across retries,
|
|
356
|
+
// so a persistently broken lineage read warns once instead of on every edit. Observability only:
|
|
357
|
+
// never throws, never changes the outcome.
|
|
358
|
+
// BOUND (mirror of vacuum.ts's `REPORT_CONTEXT_CAP`): the ledger holds at most
|
|
359
|
+
// IDENTITY_DEGRADE_REPORT_CAP paths and evicts the oldest inserted first, so the state is capped
|
|
360
|
+
// rather than unbounded across distinct file paths. A process touching more distinct paths than
|
|
361
|
+
// the cap can re-report an evicted one — strictly cheaper than an unbounded Set.
|
|
362
|
+
const IDENTITY_DEGRADE_REPORT_CAP = 256;
|
|
363
|
+
const identityDegradeReported = new Map();
|
|
364
|
+
/** The single report owner for the identity-read degrade: one warn per `absolutePath`. */
|
|
365
|
+
function reportIdentityDegrade(absolutePath, cause) {
|
|
366
|
+
try {
|
|
367
|
+
if (identityDegradeReported.has(absolutePath))
|
|
368
|
+
return;
|
|
369
|
+
if (identityDegradeReported.size >= IDENTITY_DEGRADE_REPORT_CAP) {
|
|
370
|
+
const oldest = identityDegradeReported.keys().next();
|
|
371
|
+
if (oldest.done !== true)
|
|
372
|
+
identityDegradeReported.delete(oldest.value);
|
|
373
|
+
}
|
|
374
|
+
identityDegradeReported.set(absolutePath, true);
|
|
375
|
+
console.warn(`dsh-better-edit: line-identity read failed for ${absolutePath} (${String(cause)}) — the ` +
|
|
376
|
+
`edit proceeds under the unconditional position check.`);
|
|
377
|
+
}
|
|
378
|
+
catch {
|
|
379
|
+
// SAFETY: observability only — a broken diagnostic sink must never fail the caller.
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* The `line_id` -> line-number map for one buffer, or undefined when the store read throws.
|
|
384
|
+
* `undefined` means "no source": the unconditional position check keeps guarding the edit, never a
|
|
385
|
+
* weaker check. The throw is reported once per file (KEEL K-1) — the fail-open stays, the silence
|
|
386
|
+
* goes. `positionsByIdentity` itself writes nothing.
|
|
387
|
+
*/
|
|
388
|
+
function identityPositions(store, absolutePath, content) {
|
|
389
|
+
try {
|
|
390
|
+
return internalStore(store).positionsByIdentity(absolutePath, content);
|
|
391
|
+
}
|
|
392
|
+
catch (cause) {
|
|
393
|
+
reportIdentityDegrade(absolutePath, cause);
|
|
394
|
+
return undefined;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
/** The lease lookups over an already-resolved identity map. Nothing here writes. */
|
|
398
|
+
function leaseSourceFrom(store, sessionKey, absolutePath, positions) {
|
|
399
|
+
const internal = internalStore(store);
|
|
400
|
+
return {
|
|
401
|
+
leaseFor: (anchor) => {
|
|
402
|
+
const lease = internal.leaseFor(sessionKey, absolutePath, anchor);
|
|
403
|
+
if (lease === undefined)
|
|
404
|
+
return undefined;
|
|
405
|
+
return {
|
|
406
|
+
lineId: lease.lineId,
|
|
407
|
+
servedLineNumber: lease.lineNumber,
|
|
408
|
+
servedSnapshotHash: lease.snapshotHash,
|
|
409
|
+
retiredAt: lease.retiredAt,
|
|
410
|
+
};
|
|
411
|
+
},
|
|
412
|
+
rebasedLineOf: (lineId) => positions.get(lineId),
|
|
413
|
+
// Failure-path only (upstream b92e0ec:src/hashline/resolve.ts:41-49): the lease-miss
|
|
414
|
+
// rejection asks which OTHER files this session served the anchor for.
|
|
415
|
+
anchorHomes: (anchor) => internal.leaseHomes(sessionKey, absolutePath, anchor),
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* The read-only lease-identity source for one buffer, or undefined when it cannot be built.
|
|
420
|
+
*
|
|
421
|
+
* Leases come from `served_leases`; the `line_id` -> current-line map comes from the store's
|
|
422
|
+
* `positionsByIdentity` over the buffer the edit is applied to. Nothing is written: the edit path
|
|
423
|
+
* never re-stamps a lease and never retires one.
|
|
424
|
+
*
|
|
425
|
+
* For a buffer that is not a committed snapshot — batch item k > 0 — the caller passes the map it
|
|
426
|
+
* already advanced (`leaseSourceFrom` + `spliceWorkingBufferIds`) rather than re-deriving it here.
|
|
427
|
+
*
|
|
428
|
+
* UPGRADE CONSEQUENCE: a session whose `served` rows predate lease granting (a pre-T2b store) holds
|
|
429
|
+
* no lease for those anchors, so its first edit rejects and needs one re-read. Fail-closed and
|
|
430
|
+
* one-time; it goes in the CP3 ADR and the T7 CHANGELOG note.
|
|
431
|
+
*/
|
|
432
|
+
export function makeLeaseSource(store, sessionKey, absolutePath, content) {
|
|
433
|
+
const positions = identityPositions(store, absolutePath, content);
|
|
434
|
+
if (positions === undefined)
|
|
435
|
+
return undefined;
|
|
436
|
+
return leaseSourceFrom(store, sessionKey, absolutePath, positions);
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Index -> `line_id` for a buffer, from the identity map. `null` is a line the batch created (or
|
|
440
|
+
* one the engine could not prove moved): it carries no identity to resolve against yet.
|
|
441
|
+
*/
|
|
442
|
+
function idsFromPositions(positions, lineCount) {
|
|
443
|
+
const byPosition = new Map();
|
|
444
|
+
for (const [lineId, lineNumber] of positions)
|
|
445
|
+
byPosition.set(lineNumber, lineId);
|
|
446
|
+
return Array.from({ length: lineCount }, (_, index) => byPosition.get(index + 1) ?? null);
|
|
447
|
+
}
|
|
448
|
+
/** The inverse of `idsFromPositions` — the shape `rebasedLineOf` reads. */
|
|
449
|
+
function positionsFromIds(ids) {
|
|
450
|
+
const positions = new Map();
|
|
451
|
+
for (let index = 0; index < ids.length; index++) {
|
|
452
|
+
const lineId = ids[index];
|
|
453
|
+
if (lineId !== null && lineId !== undefined)
|
|
454
|
+
positions.set(lineId, index + 1);
|
|
455
|
+
}
|
|
456
|
+
return positions;
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Advance the working-buffer identity map past one APPLIED item.
|
|
460
|
+
*
|
|
461
|
+
* Lines outside the item's resolved range keep their id — they only shifted, so the same identity
|
|
462
|
+
* lives at a new coordinate. The range's replacement lines become `null`: the batch created them, so
|
|
463
|
+
* they carry no identity to resolve against until a read leases them.
|
|
464
|
+
*
|
|
465
|
+
* WHY this map exists, and why dsh does NOT port upstream's commit-from-map half: resolution needs
|
|
466
|
+
* the working buffer's identities *during* the batch, and re-pairing `S_latest` against the
|
|
467
|
+
* intermediate buffer is ambiguous exactly when the batch introduced a duplicate canon — the map is
|
|
468
|
+
* the deterministic answer there. The COMMIT path is a different question and keeps re-pairing the
|
|
469
|
+
* final content against the latest snapshot, which is *more* identity-preserving than the map for a
|
|
470
|
+
* line inside a replaced range that survived byte-identical: re-pairing inherits it, while the map
|
|
471
|
+
* would assign `null` and force a re-read on the next edit. So the map is resolution-only by design.
|
|
472
|
+
*/
|
|
473
|
+
function spliceWorkingBufferIds(ids, rangeStart, rangeEnd, lineCount) {
|
|
474
|
+
const replaced = rangeEnd - rangeStart + 1;
|
|
475
|
+
const replacementCount = Math.max(lineCount - ids.length + replaced, 0);
|
|
476
|
+
const middle = Array.from({ length: replacementCount }, () => null);
|
|
477
|
+
return [...ids.slice(0, rangeStart - 1), ...middle, ...ids.slice(rangeEnd)];
|
|
478
|
+
}
|
|
479
|
+
/** The ambient store for the lease source, or undefined when it cannot be opened. */
|
|
480
|
+
async function loadLeaseStore() {
|
|
481
|
+
try {
|
|
482
|
+
return await loadHashStore();
|
|
483
|
+
}
|
|
484
|
+
catch {
|
|
485
|
+
return undefined;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
257
488
|
/**
|
|
258
489
|
* Run a file's item list against freshly-read content with served
|
|
259
490
|
* verification, evolving content/hashes, union range, noop tracking, and a
|
|
@@ -270,7 +501,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
270
501
|
const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
|
|
271
502
|
absolutePath,
|
|
272
503
|
rawText,
|
|
273
|
-
displayPath: first.
|
|
504
|
+
displayPath: first.file,
|
|
274
505
|
signal: opts.signal,
|
|
275
506
|
maxLines: MAX_HASH_LINES,
|
|
276
507
|
reservedHashes,
|
|
@@ -278,16 +509,38 @@ export async function runFileEdits(io, items, opts) {
|
|
|
278
509
|
});
|
|
279
510
|
const served = await loadServed(opts.sessionKey, absolutePath);
|
|
280
511
|
const servedCanons = await loadServedCanons(opts.sessionKey, absolutePath);
|
|
281
|
-
const epochSnapshotId = await loadEpochSnapshotId(opts.sessionKey, absolutePath);
|
|
282
|
-
let curSnapshotId;
|
|
283
|
-
try {
|
|
284
|
-
curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
|
|
285
|
-
}
|
|
286
|
-
catch { }
|
|
287
|
-
const strictPos = epochSnapshotId !== undefined &&
|
|
288
|
-
curSnapshotId !== undefined &&
|
|
289
|
-
epochSnapshotId !== curSnapshotId; // automatic: strict when epoch mismatch (conservative, future: changed∩[L,R] refined)
|
|
290
512
|
const warnings = [];
|
|
513
|
+
// FU-R (upstream pipeline.ts:811-822): the never-served soft hint is once per call. Per-item
|
|
514
|
+
// counts travel as structured data (`neverServedCount`), aggregate here, and one counted hint
|
|
515
|
+
// renders after the loop. No other warning tier is capped; a noop writes nothing, so its count
|
|
516
|
+
// is never aggregated.
|
|
517
|
+
let neverServedTotal = 0;
|
|
518
|
+
const pushAppliedWarnings = (list, hintCount) => {
|
|
519
|
+
if (list)
|
|
520
|
+
warnings.push(...list);
|
|
521
|
+
neverServedTotal += hintCount;
|
|
522
|
+
};
|
|
523
|
+
const pushNoopWarnings = (list) => {
|
|
524
|
+
if (list)
|
|
525
|
+
warnings.push(...list);
|
|
526
|
+
};
|
|
527
|
+
// The lease store is resolved once per file edit; the source itself is rebuilt per buffer (the
|
|
528
|
+
// pre-pass resolves against `originalNormalized`, each loop item against `currentContent` plus the
|
|
529
|
+
// working-buffer identity map below).
|
|
530
|
+
const leaseStore = await loadLeaseStore();
|
|
531
|
+
const originalPositions = leaseStore === undefined
|
|
532
|
+
? undefined
|
|
533
|
+
: identityPositions(leaseStore, absolutePath, originalNormalized);
|
|
534
|
+
const originalLeaseSource = leaseStore === undefined || originalPositions === undefined
|
|
535
|
+
? undefined
|
|
536
|
+
: leaseSourceFrom(leaseStore, opts.sessionKey, absolutePath, originalPositions);
|
|
537
|
+
// The working-buffer identity map: index -> `line_id | null`, seeded from the same seam the
|
|
538
|
+
// resolution uses so resolution and any future commit cannot disagree. Advanced after each
|
|
539
|
+
// applied item; a length that disagrees with the buffer's line count falls back to
|
|
540
|
+
// `positionsByIdentity` — never to a guess.
|
|
541
|
+
let currentIds = originalPositions === undefined
|
|
542
|
+
? undefined
|
|
543
|
+
: idsFromPositions(originalPositions, splitLines(originalNormalized).length);
|
|
291
544
|
let currentContent = originalNormalized;
|
|
292
545
|
let currentHashes = originalHashes;
|
|
293
546
|
let appliedCount = 0;
|
|
@@ -300,17 +553,56 @@ export async function runFileEdits(io, items, opts) {
|
|
|
300
553
|
let unionEndHash = "";
|
|
301
554
|
let lastApplied;
|
|
302
555
|
const newlyRetired = new Set();
|
|
556
|
+
// C: pure pre-pass over all items on the pre-batch snapshot — parse each
|
|
557
|
+
// item (resEdit) and resolve its span (applyEdit) with no mutation
|
|
558
|
+
// (warnings go to a throwaway array; noop tracking untouched). Anchor and
|
|
559
|
+
// served failures collect for one aggregated rejection; a non-domain
|
|
560
|
+
// throw is unexpected and aborts immediately. The loop below still owns
|
|
561
|
+
// state-dependent (mid-loop) failures via onReject.
|
|
562
|
+
const preParts = [];
|
|
303
563
|
for (const item of items) {
|
|
304
564
|
abortIf(opts.signal);
|
|
565
|
+
let edit;
|
|
566
|
+
try {
|
|
567
|
+
edit = resEdit({
|
|
568
|
+
anchor_from: item.anchor_from,
|
|
569
|
+
anchor_to: item.anchor_to,
|
|
570
|
+
replace_with: item.replace_with,
|
|
571
|
+
});
|
|
572
|
+
applyEdit(originalNormalized, edit, opts.signal, originalHashes, item.file, served, servedCanons, perSessionRetired, item.mode, originalLeaseSource);
|
|
573
|
+
}
|
|
574
|
+
catch (error) {
|
|
575
|
+
if (!(error instanceof DomainError))
|
|
576
|
+
throw error;
|
|
577
|
+
preParts.push(await collectAbortPart({
|
|
578
|
+
sessionKey: opts.sessionKey,
|
|
579
|
+
absolutePath,
|
|
580
|
+
error,
|
|
581
|
+
edit,
|
|
582
|
+
index: item.index,
|
|
583
|
+
originalNormalized,
|
|
584
|
+
originalHashes,
|
|
585
|
+
}));
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (preParts.length > 0)
|
|
589
|
+
throw buildBatchAbort(first.file, preParts);
|
|
590
|
+
for (const item of items) {
|
|
591
|
+
abortIf(opts.signal);
|
|
592
|
+
const leaseSource = leaseStore === undefined
|
|
593
|
+
? undefined
|
|
594
|
+
: currentIds !== undefined && currentIds.length === splitLines(currentContent).length
|
|
595
|
+
? leaseSourceFrom(leaseStore, opts.sessionKey, absolutePath, positionsFromIds(currentIds))
|
|
596
|
+
: makeLeaseSource(leaseStore, opts.sessionKey, absolutePath, currentContent);
|
|
305
597
|
const applied = await applyOne({
|
|
306
598
|
content: currentContent,
|
|
307
599
|
hashes: currentHashes,
|
|
308
600
|
served,
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
601
|
+
anchorFrom: item.anchor_from,
|
|
602
|
+
anchorTo: item.anchor_to,
|
|
603
|
+
replaceWith: item.replace_with,
|
|
312
604
|
absolutePath,
|
|
313
|
-
displayPath: item.
|
|
605
|
+
displayPath: item.file,
|
|
314
606
|
signal: opts.signal,
|
|
315
607
|
warnings,
|
|
316
608
|
countHashes: originalHashes,
|
|
@@ -318,29 +610,33 @@ export async function runFileEdits(io, items, opts) {
|
|
|
318
610
|
reservedHashes,
|
|
319
611
|
servedCanons,
|
|
320
612
|
retired: new Set([...perSessionRetired, ...Array.from(newlyRetired)]),
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
strictPos,
|
|
613
|
+
mode: item.mode,
|
|
614
|
+
leaseSource,
|
|
324
615
|
}, async (error, edit) => {
|
|
616
|
+
// In-loop (state-dependent) failures keep single-failure envelopes.
|
|
325
617
|
if (error instanceof AnchorMismatchError || error instanceof ServedRejectionError) {
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
? ` Current on-disk range for edits[${item.index}] (unchanged — nothing was written):\n${fmtServedRows(echoRows, originalLines)}`
|
|
337
|
-
: " Call read() to get fresh anchors.";
|
|
338
|
-
throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${error.message}${echoBlock}\n` +
|
|
339
|
-
"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.");
|
|
618
|
+
const part = await collectAbortPart({
|
|
619
|
+
sessionKey: opts.sessionKey,
|
|
620
|
+
absolutePath,
|
|
621
|
+
error,
|
|
622
|
+
edit,
|
|
623
|
+
index: item.index,
|
|
624
|
+
originalNormalized,
|
|
625
|
+
originalHashes,
|
|
626
|
+
});
|
|
627
|
+
throw buildBatchAbort(item.file, [part]);
|
|
340
628
|
}
|
|
341
629
|
const message = error instanceof Error ? error.message : String(error);
|
|
342
|
-
throw
|
|
343
|
-
|
|
630
|
+
throw buildBatchAbort(item.file, [
|
|
631
|
+
{
|
|
632
|
+
index: item.index,
|
|
633
|
+
inner: message,
|
|
634
|
+
echoRows: undefined,
|
|
635
|
+
echoBlock: "",
|
|
636
|
+
fmtBlock: "",
|
|
637
|
+
cause: undefined,
|
|
638
|
+
},
|
|
639
|
+
]);
|
|
344
640
|
});
|
|
345
641
|
const range = applied.range;
|
|
346
642
|
if (range.startLine < unionStartLine) {
|
|
@@ -353,26 +649,21 @@ export async function runFileEdits(io, items, opts) {
|
|
|
353
649
|
}
|
|
354
650
|
if (applied.noop) {
|
|
355
651
|
noopCount += 1;
|
|
356
|
-
const payload = noopPayloadKey(absolutePath, item.
|
|
652
|
+
const payload = noopPayloadKey(absolutePath, item.anchor_from, item.anchor_to, item.replace_with);
|
|
357
653
|
const count = trackNoopPayload(absolutePath, payload);
|
|
358
654
|
const notice = await enforceNoopLoop({
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
replacementText: item.replacement_text,
|
|
363
|
-
displayPath: item.path,
|
|
655
|
+
anchorFrom: item.anchor_from,
|
|
656
|
+
anchorTo: item.anchor_to,
|
|
657
|
+
displayPath: item.file,
|
|
364
658
|
index: item.index,
|
|
365
659
|
count,
|
|
366
|
-
sessionKey: opts.sessionKey,
|
|
367
|
-
originalHashes,
|
|
368
660
|
originalNormalized,
|
|
369
661
|
echoRows: echoRowsForItem(applied.edit, originalHashes),
|
|
370
662
|
});
|
|
371
663
|
if (notice)
|
|
372
664
|
warnings.push(notice);
|
|
373
|
-
warnings.push(`edits[${item.index}] (${item.
|
|
374
|
-
|
|
375
|
-
warnings.push(...applied.anchorWarnings);
|
|
665
|
+
warnings.push(`edits[${item.index}] (${item.file}) was a noop: the range already contains the replacement text.`);
|
|
666
|
+
pushNoopWarnings(applied.anchorWarnings);
|
|
376
667
|
continue;
|
|
377
668
|
}
|
|
378
669
|
appliedCount += 1;
|
|
@@ -389,10 +680,15 @@ export async function runFileEdits(io, items, opts) {
|
|
|
389
680
|
removedHashes,
|
|
390
681
|
};
|
|
391
682
|
currentContent = applied.result;
|
|
683
|
+
if (currentIds !== undefined) {
|
|
684
|
+
currentIds = spliceWorkingBufferIds(currentIds, range.startLine, range.endLine, splitLines(applied.result).length);
|
|
685
|
+
}
|
|
392
686
|
currentHashes = applied.hashes;
|
|
393
687
|
clearNoopLoop(absolutePath);
|
|
394
|
-
|
|
395
|
-
|
|
688
|
+
pushAppliedWarnings(applied.anchorWarnings, applied.neverServedCount);
|
|
689
|
+
}
|
|
690
|
+
if (neverServedTotal > 0) {
|
|
691
|
+
warnings.push(buildNeverServedEditHint({ count: neverServedTotal }));
|
|
396
692
|
}
|
|
397
693
|
const result = currentContent;
|
|
398
694
|
let resultHashes = currentHashes;
|
|
@@ -418,8 +714,8 @@ export async function runFileEdits(io, items, opts) {
|
|
|
418
714
|
if (hadUtf8DecodeErrors) {
|
|
419
715
|
warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
|
|
420
716
|
}
|
|
421
|
-
if (first.
|
|
422
|
-
warnings.unshift(first.
|
|
717
|
+
if (first.fileWarning)
|
|
718
|
+
warnings.unshift(first.fileWarning);
|
|
423
719
|
let driftNotice;
|
|
424
720
|
if (appliedCount > 0 && unionStartLine !== Infinity) {
|
|
425
721
|
const resultLines = splitLines(result);
|
|
@@ -445,7 +741,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
445
741
|
}
|
|
446
742
|
}
|
|
447
743
|
return {
|
|
448
|
-
displayPath: first.
|
|
744
|
+
displayPath: first.file,
|
|
449
745
|
absolutePath,
|
|
450
746
|
originalNormalized,
|
|
451
747
|
result,
|