dsh-better-edit 0.5.1 → 0.6.1

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/lib/edit-engine.js +4 -454
  3. package/lib/edit-response.js +24 -2
  4. package/lib/file-encoding-state.js +263 -0
  5. package/lib/file-view.js +5 -1
  6. package/lib/fs-bridge.js +94 -251
  7. package/lib/hash-store.js +180 -2
  8. package/lib/hashline/anchor-pipeline.js +94 -166
  9. package/lib/hashline/hash-assign.js +15 -27
  10. package/lib/hashline/hash.js +5 -5
  11. package/lib/index.js +2 -2
  12. package/lib/mutation/engine.js +415 -0
  13. package/lib/mutation.js +105 -11
  14. package/lib/paths.js +1 -1
  15. package/lib/read-and-serve.js +25 -3
  16. package/lib/session-view.js +107 -58
  17. package/lib/store/index.js +28 -0
  18. package/lib/store-lifecycle.js +1 -1
  19. package/lib/tool-edit.js +2 -2
  20. package/lib/tool-read.js +2 -2
  21. package/lib/tool-undo.js +21 -8
  22. package/lib/types/edit-diff.d.ts +1 -1
  23. package/lib/types/edit-engine.d.ts +4 -176
  24. package/lib/types/edit-response.d.ts +1 -1
  25. package/lib/types/file-encoding-state.d.ts +77 -0
  26. package/lib/types/file-view.d.ts +7 -1
  27. package/lib/types/fs-bridge.d.ts +4 -11
  28. package/lib/types/hash-store.d.ts +15 -0
  29. package/lib/types/hashline/anchor-pipeline.d.ts +12 -21
  30. package/lib/types/hashline/hash-assign.d.ts +2 -2
  31. package/lib/types/hashline/hash.d.ts +1 -1
  32. package/lib/types/hashline/index.d.ts +1 -1
  33. package/lib/types/mutation/engine.d.ts +149 -0
  34. package/lib/types/mutation.d.ts +30 -5
  35. package/lib/types/paths.d.ts +1 -1
  36. package/lib/types/read-and-serve.d.ts +1 -1
  37. package/lib/types/session-view.d.ts +25 -31
  38. package/lib/types/store/index.d.ts +25 -0
  39. package/lib/types/workspace-context.d.ts +23 -0
  40. package/lib/workspace-context.js +44 -0
  41. package/lib/write-hook.js +2 -1
  42. package/package.json +1 -1
@@ -121,10 +121,12 @@ function assignHash(used, baseIdx, hint) {
121
121
  hint.value = nextIdx + HASH_PROBE_STRIDE;
122
122
  return hashAt(nextIdx);
123
123
  }
124
- export function lineHashesPure(content) {
124
+ export function lineHashesPure(content, reservedHashes = new Set()) {
125
125
  const lines = splitLines(content);
126
126
  const hashes = new Array(lines.length);
127
127
  const used = new Uint32Array(BITSET_WORDS);
128
+ for (const hash of reservedHashes)
129
+ markHashUsed(used, hash);
128
130
  const hint = { value: 0 };
129
131
  const canonCache = new Map();
130
132
  for (let i = 0; i < lines.length; i++) {
@@ -163,7 +165,7 @@ function nearestNew(candidates, target) {
163
165
  }
164
166
  return right < candidates.length ? right : -1;
165
167
  }
166
- export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes) {
168
+ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes, reservedHashes = new Set()) {
167
169
  const oldLines = splitLines(oldContent);
168
170
  const newLines = splitLines(newContent);
169
171
  const newHashes = new Array(newLines.length);
@@ -171,6 +173,9 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
171
173
  const hint = { value: 0 };
172
174
  const canonCache = new Map();
173
175
  const removed = removedHashes ?? new Set();
176
+ const blocked = new Set(reservedHashes);
177
+ for (const hash of removed)
178
+ blocked.add(hash);
174
179
  const oldHashIndex = new Map();
175
180
  for (let i = 0; i < oldHashes.length; i++) {
176
181
  const hash = oldHashes[i];
@@ -185,6 +190,8 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
185
190
  if (idx !== undefined)
186
191
  removedIndexes.add(idx);
187
192
  }
193
+ for (const hash of blocked)
194
+ markHashUsed(used, hash);
188
195
  let spanStart = oldLines.length;
189
196
  let spanEnd = -1;
190
197
  for (const idx of removedIndexes) {
@@ -197,12 +204,9 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
197
204
  const replacementLen = newLines.length - oldLines.length + spanLen;
198
205
  const shiftAfterSpan = spanEnd >= spanStart ? replacementLen - spanLen : 0;
199
206
  const survivors = [];
200
- const removedEntries = [];
201
207
  for (let i = 0; i < oldLines.length; i++) {
202
208
  const entry = { index: i, hash: oldHashes[i] };
203
- if (removedIndexes.has(i))
204
- removedEntries.push(entry);
205
- else
209
+ if (!removedIndexes.has(i))
206
210
  survivors.push(entry);
207
211
  }
208
212
  const newByContent = new Map();
@@ -235,27 +239,6 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
235
239
  markUsed(entry.hash);
236
240
  rememberHashCanon(entry.hash, getCanon(canonCache, oldLines[entry.index]));
237
241
  }
238
- const removedByContent = new Map();
239
- for (const entry of removedEntries) {
240
- const key = getCanon(canonCache, oldLines[entry.index]);
241
- let queue = removedByContent.get(key);
242
- if (!queue) {
243
- queue = { hashes: [], pos: 0 };
244
- removedByContent.set(key, queue);
245
- }
246
- queue.hashes.push(entry.hash);
247
- }
248
- for (let i = 0; i < newLines.length; i++) {
249
- if (newHashes[i])
250
- continue;
251
- const queue = removedByContent.get(getCanon(canonCache, newLines[i]));
252
- if (!queue || queue.pos >= queue.hashes.length)
253
- continue;
254
- const h = queue.hashes[queue.pos];
255
- newHashes[i] = h;
256
- queue.pos += 1;
257
- rememberHashCanon(h, getCanon(canonCache, newLines[i]));
258
- }
259
242
  for (let i = 0; i < newLines.length; i++) {
260
243
  if (newHashes[i])
261
244
  continue;
@@ -267,4 +250,9 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
267
250
  }
268
251
  return newHashes;
269
252
  }
253
+ function markHashUsed(used, hash) {
254
+ const idx = hashToIndex(hash);
255
+ if (idx >= 0)
256
+ setBit(used, idx);
257
+ }
270
258
  // --- persistence wrapper (from hash.ts) ---
@@ -45,16 +45,16 @@ export function isValidHashList(value) {
45
45
  }
46
46
  return true;
47
47
  }
48
- export async function lineHashes(content, path, previous, ioOrStore, persist) {
48
+ export async function lineHashes(content, path, previous, ioOrStore, persist, reservedHashes = new Set(), retiredHashes = new Set()) {
49
49
  await initHasher();
50
50
  if (!path)
51
- return lineHashesPure(content);
51
+ return lineHashesPure(content, reservedHashes);
52
52
  // Back-compat: caller may pass HashStore as 4th arg; adapt to IO.
53
53
  const io = ioOrStore && "getSnapshot" in ioOrStore
54
54
  ? snapshotIOFor(ioOrStore)
55
55
  : ioOrStore ?? snapshotIOFor(undefined);
56
56
  if (previous) {
57
- const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes);
57
+ const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes, reservedHashes);
58
58
  if (persist !== false && io) {
59
59
  try {
60
60
  await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
@@ -74,9 +74,9 @@ export async function lineHashes(content, path, previous, ioOrStore, persist) {
74
74
  console.error("Failed to read hash store snapshot:", e);
75
75
  }
76
76
  }
77
- if (cached)
77
+ if (cached && !cached.some((hash) => retiredHashes.has(hash)))
78
78
  return cached;
79
- const newHashes = lineHashesPure(content);
79
+ const newHashes = lineHashesPure(content, reservedHashes);
80
80
  if (persist !== false && io) {
81
81
  try {
82
82
  await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
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 "./paths.js";
26
+ import { configDir } from "./store/index.js";
27
27
  import { ensureDefaultConfig } from "./store-config.js";
28
- import { onAppStart, onSessionStart } from "./store-lifecycle.js";
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,415 @@
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 { loadConfig } from "../store-config.js";
15
+ import { canon } from "../hashline/hash-assign.js";
16
+ import { fileSnap } from "../file-view.js";
17
+ import { normFromText } from "../file-reader.js";
18
+ import { scanDrift, loadServed, loadServedCanons, loadEpochSnapshotId, loadRetiredAnchors, retireAnchors, } from "../session-view.js";
19
+ import { applyEdit, resEdit, parseHashRef, } from "../hashline/anchor-pipeline.js";
20
+ import { lineHashes } from "../hashline/hash.js";
21
+ import { MAX_HASH_LINES } from "../hashline/hash-assign.js";
22
+ import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "../hashline/anchor-pipeline.js";
23
+ import { findSnapshotPathsByHashes } from "../hash-store.js";
24
+ import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "../noop-guard.js";
25
+ import { NOOP_LOOP_THRESHOLD } from "../constants.js";
26
+ import { abortIf, splitLines } from "../utils.js";
27
+ // ---------------------------------------------------------------------------
28
+ // request / counting helpers shared by both tool paths
29
+ /**
30
+ * Resolve a request's missing `path` from its anchors: the only file whose
31
+ * stored hashes contain both anchors. Returns the path plus an autocorrect
32
+ * warning, or undefined when no resolution is possible.
33
+ */
34
+ export async function resolveMissingPath(request) {
35
+ if (typeof request.path === "string")
36
+ return undefined;
37
+ const from = request.remove_from;
38
+ const to = request.remove_to;
39
+ if (typeof from !== "string" || typeof to !== "string")
40
+ return undefined;
41
+ const hashes = [];
42
+ for (const ref of [from, to]) {
43
+ try {
44
+ hashes.push(parseHashRef(ref).hash);
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ }
50
+ let matches;
51
+ try {
52
+ matches = await findSnapshotPathsByHashes(hashes);
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ if (matches.length === 1) {
58
+ return {
59
+ path: matches[0],
60
+ warning: `[E_BAD_SHAPE] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
61
+ };
62
+ }
63
+ if (matches.length > 1) {
64
+ 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.`);
65
+ }
66
+ return undefined;
67
+ }
68
+ /** The hashes a range edit removes, for stable re-hash bookkeeping. */
69
+ export function collectRemovedHashes(edit, originalHashes) {
70
+ const removedHashes = new Set();
71
+ const startHash = edit.hash_bounds[0].hash;
72
+ const endHash = edit.hash_bounds[1].hash;
73
+ const startLine = originalHashes.indexOf(startHash);
74
+ const endLine = originalHashes.indexOf(endHash);
75
+ if (startLine >= 0 && endLine >= 0) {
76
+ const firstLine = Math.min(startLine, endLine);
77
+ const lastLine = Math.max(startLine, endLine);
78
+ for (let i = firstLine; i <= lastLine; i++) {
79
+ removedHashes.add(originalHashes[i]);
80
+ }
81
+ }
82
+ return removedHashes;
83
+ }
84
+ /** Added/removed line counts for one resolved edit against a file's original hashes. */
85
+ export function countLineChanges(edit, originalHashes, isNoop, removedAutoFixes) {
86
+ if (isNoop)
87
+ return { totalAddedLines: 0, totalRemovedLines: 0 };
88
+ let totalRemovedLines = 0;
89
+ const startLine = originalHashes.indexOf(edit.hash_bounds[0].hash);
90
+ const endLine = originalHashes.indexOf(edit.hash_bounds[1].hash);
91
+ if (startLine >= 0 && endLine >= 0) {
92
+ totalRemovedLines = Math.abs(endLine - startLine) + 1;
93
+ }
94
+ return {
95
+ totalAddedLines: Math.max(0, edit.content_lines.length - removedAutoFixes),
96
+ totalRemovedLines,
97
+ };
98
+ }
99
+ /**
100
+ * One edit against in-memory content: resolve (unless a pre-resolved edit was
101
+ * given) → apply with served verification → stable re-hash → line counts.
102
+ *
103
+ * `onReject` owns the reject-and-serve policy: it receives resolve/verify
104
+ * failures (and the edit that failed, when resolved) and MUST throw. The
105
+ * single path rethrows the original anchor error after recording echo serves;
106
+ * the batch path wraps with [E_BATCH_ABORT] plus the current-range echo.
107
+ */
108
+ export async function applyOne(input, onReject) {
109
+ let edit;
110
+ if (input.edit) {
111
+ edit = input.edit;
112
+ }
113
+ else {
114
+ try {
115
+ edit = resEdit({
116
+ remove_from: input.removeFrom,
117
+ remove_to: input.removeTo,
118
+ replacement_text: input.replacementText,
119
+ }, input.warnings);
120
+ }
121
+ catch (error) {
122
+ return onReject(error, undefined);
123
+ }
124
+ }
125
+ let anchorResult;
126
+ try {
127
+ anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served, input.servedCanons, input.tombstone, input.epochSnapshotId, input.curSnapshotId, input.strictPos);
128
+ }
129
+ catch (error) {
130
+ if (error instanceof AnchorMismatchError ||
131
+ error instanceof ServedRejectionError) {
132
+ return onReject(error, edit);
133
+ }
134
+ throw error;
135
+ }
136
+ const result = anchorResult.content;
137
+ const noop = result === input.content;
138
+ const removedHashes = noop
139
+ ? undefined
140
+ : collectRemovedHashes(edit, input.hashes);
141
+ const resultHashes = noop
142
+ ? input.hashes
143
+ : await lineHashes(result, input.absolutePath, {
144
+ content: input.content,
145
+ hashes: input.hashes,
146
+ removedHashes,
147
+ }, input.store, input.persist, input.reservedHashes);
148
+ const { totalAddedLines, totalRemovedLines } = countLineChanges(edit, input.countHashes ?? input.hashes, noop, 0);
149
+ return {
150
+ result,
151
+ hashes: resultHashes,
152
+ range: anchorResult.range,
153
+ noop,
154
+ edit,
155
+ noopEdit: anchorResult.noopEdit,
156
+ firstChangedLine: anchorResult.firstChangedLine,
157
+ lastChangedLine: anchorResult.lastChangedLine,
158
+ removedHashes,
159
+ totalAddedLines,
160
+ totalRemovedLines,
161
+ anchorWarnings: anchorResult.warnings,
162
+ };
163
+ }
164
+ /**
165
+ * The shared noop-loop guard. Returns the "twice in a row" notice for the
166
+ * caller to append to warnings, or throws [E_NOOP_LOOP] (after recording the
167
+ * echo serves) once the payload has been submitted NOOP_LOOP_THRESHOLD times
168
+ * with no change. Messages are byte-identical to the pre-engine tools.
169
+ */
170
+ export async function enforceNoopLoop(opts) {
171
+ const { absolutePath, removeFrom, removeTo, displayPath, index, count, sessionKey, originalHashes, } = opts;
172
+ if (index === undefined) {
173
+ if (count >= NOOP_LOOP_THRESHOLD) {
174
+ const echoRows = buildRangeEcho(opts.range.startLine, opts.range.endLine, originalHashes);
175
+ const echo = fmtServedRows(echoRows, splitLines(opts.originalNormalized));
176
+ await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
177
+ 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}`);
178
+ }
179
+ if (count === 2) {
180
+ return `[E_NOOP_LOOP] Notice: identical edit (${removeFrom} → ${removeTo} in ${displayPath}) no-op'd twice; range already has this text. Resend will reject.`;
181
+ }
182
+ return undefined;
183
+ }
184
+ if (count >= NOOP_LOOP_THRESHOLD) {
185
+ const originalLines = splitLines(opts.originalNormalized);
186
+ const echoRows = opts.echoRows;
187
+ if (echoRows) {
188
+ await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
189
+ }
190
+ 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.` +
191
+ (echoRows
192
+ ? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}`
193
+ : ""));
194
+ }
195
+ if (count === 2) {
196
+ return `[E_NOOP_LOOP] Notice: edits[${index}] (${displayPath}) — identical edit no-op'd twice; range already has this text. Resend will reject the batch.`;
197
+ }
198
+ return undefined;
199
+ }
200
+ // ---------------------------------------------------------------------------
201
+ // per-file sequencer (batch)
202
+ function echoRowsForItem(edit, originalHashes) {
203
+ const startHash = edit.hash_bounds[0].hash;
204
+ const endHash = edit.hash_bounds[1].hash;
205
+ const s = originalHashes.indexOf(startHash);
206
+ const e = originalHashes.indexOf(endHash);
207
+ if (s < 0 || e < 0)
208
+ return undefined;
209
+ return buildRangeEcho(Math.min(s, e) + 1, Math.max(s, e) + 1, originalHashes);
210
+ }
211
+ /**
212
+ * Run a file's item list against freshly-read content with served
213
+ * verification, evolving content/hashes, union range, noop tracking, and a
214
+ * per-file drift notice. All-or-nothing is enforced by the caller's
215
+ * transaction ({@link persistUndoAndWrite}): nothing here writes to disk.
216
+ */
217
+ export async function runFileEdits(io, items, opts) {
218
+ const first = items[0];
219
+ abortIf(opts.signal);
220
+ const absolutePath = first.absolutePath;
221
+ const perSessionTombstone = await loadRetiredAnchors(opts.sessionKey, absolutePath);
222
+ const reservedHashes = new Set(perSessionTombstone);
223
+ const rawText = await io.readText(absolutePath, opts.signal);
224
+ const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
225
+ absolutePath,
226
+ rawText,
227
+ displayPath: first.path,
228
+ signal: opts.signal,
229
+ maxLines: MAX_HASH_LINES,
230
+ reservedHashes,
231
+ retiredHashes: perSessionTombstone,
232
+ });
233
+ const served = await loadServed(opts.sessionKey, absolutePath);
234
+ const servedCanons = await loadServedCanons(opts.sessionKey, absolutePath);
235
+ const epochSnapshotId = await loadEpochSnapshotId(opts.sessionKey, absolutePath);
236
+ let curSnapshotId;
237
+ try {
238
+ curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
239
+ }
240
+ catch { }
241
+ const strictPos = false; // automatic resist: pos-free for exterior shift, strict via tombstone+canon for whole-span rebind
242
+ const warnings = [];
243
+ let currentContent = originalNormalized;
244
+ let currentHashes = originalHashes;
245
+ let appliedCount = 0;
246
+ let noopCount = 0;
247
+ let totalAddedLines = 0;
248
+ let totalRemovedLines = 0;
249
+ let unionStartLine = Infinity;
250
+ let unionEndLine = -Infinity;
251
+ let unionStartHash = "";
252
+ let unionEndHash = "";
253
+ let lastApplied;
254
+ const newlyRetired = new Set();
255
+ for (const item of items) {
256
+ abortIf(opts.signal);
257
+ const applied = await applyOne({
258
+ content: currentContent,
259
+ hashes: currentHashes,
260
+ served,
261
+ removeFrom: item.remove_from,
262
+ removeTo: item.remove_to,
263
+ replacementText: item.replacement_text,
264
+ absolutePath,
265
+ displayPath: item.path,
266
+ signal: opts.signal,
267
+ warnings,
268
+ countHashes: originalHashes,
269
+ persist: false,
270
+ reservedHashes,
271
+ servedCanons,
272
+ tombstone: new Set([...perSessionTombstone, ...Array.from(newlyRetired)]),
273
+ epochSnapshotId,
274
+ curSnapshotId,
275
+ strictPos,
276
+ }, async (error, edit) => {
277
+ if (error instanceof AnchorMismatchError ||
278
+ error instanceof ServedRejectionError) {
279
+ const originalLines = splitLines(originalNormalized);
280
+ const echoRows = error.servedRows.length > 0
281
+ ? error.servedRows
282
+ : edit
283
+ ? echoRowsForItem(edit, originalHashes)
284
+ : undefined;
285
+ if (echoRows) {
286
+ await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live", originalHashes.length);
287
+ }
288
+ const echoBlock = echoRows
289
+ ? ` Current on-disk range for edits[${item.index}] (unchanged — nothing was written):\n${fmtServedRows(echoRows, originalLines)}`
290
+ : " Call read() to get fresh anchors.";
291
+ throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${error.message}${echoBlock}\n` +
292
+ "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.");
293
+ }
294
+ const message = error instanceof Error ? error.message : String(error);
295
+ throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${message}\n` +
296
+ "The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied.");
297
+ });
298
+ const range = applied.range;
299
+ if (range.startLine < unionStartLine) {
300
+ unionStartLine = range.startLine;
301
+ unionStartHash = range.startHash;
302
+ }
303
+ if (range.endLine > unionEndLine) {
304
+ unionEndLine = range.endLine;
305
+ unionEndHash = range.endHash;
306
+ }
307
+ if (applied.noop) {
308
+ noopCount += 1;
309
+ const payload = noopPayloadKey(absolutePath, item.remove_from, item.remove_to, item.replacement_text);
310
+ const count = trackNoopPayload(absolutePath, payload);
311
+ const notice = await enforceNoopLoop({
312
+ absolutePath,
313
+ removeFrom: item.remove_from,
314
+ removeTo: item.remove_to,
315
+ replacementText: item.replacement_text,
316
+ displayPath: item.path,
317
+ index: item.index,
318
+ count,
319
+ sessionKey: opts.sessionKey,
320
+ originalHashes,
321
+ originalNormalized,
322
+ echoRows: echoRowsForItem(applied.edit, originalHashes),
323
+ });
324
+ if (notice)
325
+ warnings.push(notice);
326
+ warnings.push(`edits[${item.index}] (${item.path}) was a noop: the range already contains the replacement text.`);
327
+ if (applied.anchorWarnings?.length)
328
+ warnings.push(...applied.anchorWarnings);
329
+ continue;
330
+ }
331
+ appliedCount += 1;
332
+ const removedHashes = applied.removedHashes;
333
+ for (const hash of removedHashes) {
334
+ reservedHashes.add(hash);
335
+ newlyRetired.add(hash);
336
+ }
337
+ totalAddedLines += applied.totalAddedLines;
338
+ totalRemovedLines += applied.totalRemovedLines;
339
+ lastApplied = {
340
+ content: currentContent,
341
+ hashes: currentHashes,
342
+ removedHashes,
343
+ };
344
+ currentContent = applied.result;
345
+ currentHashes = applied.hashes;
346
+ clearNoopLoop(absolutePath);
347
+ if (applied.anchorWarnings?.length)
348
+ warnings.push(...applied.anchorWarnings);
349
+ }
350
+ const result = currentContent;
351
+ let resultHashes = currentHashes;
352
+ if (appliedCount > 0 && lastApplied) {
353
+ resultHashes = await lineHashes(result, absolutePath, {
354
+ content: lastApplied.content,
355
+ hashes: lastApplied.hashes,
356
+ removedHashes: lastApplied.removedHashes,
357
+ }, undefined, true, reservedHashes, perSessionTombstone);
358
+ await retireAnchors(opts.sessionKey, absolutePath, newlyRetired);
359
+ }
360
+ if (hadUtf8DecodeErrors) {
361
+ warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
362
+ }
363
+ if (first.pathWarning)
364
+ warnings.unshift(first.pathWarning);
365
+ let driftNotice;
366
+ if (appliedCount > 0 && unionStartLine !== Infinity) {
367
+ const resultLines = splitLines(result);
368
+ const originalLines = splitLines(originalNormalized);
369
+ try {
370
+ driftNotice = await scanDrift({
371
+ sessionKey: opts.sessionKey,
372
+ served,
373
+ resultHashes,
374
+ resultLines,
375
+ range: {
376
+ startLine: unionStartLine,
377
+ endLine: unionEndLine,
378
+ startHash: unionStartHash,
379
+ endHash: unionEndHash,
380
+ delta: resultLines.length - originalLines.length,
381
+ },
382
+ path: absolutePath,
383
+ });
384
+ }
385
+ catch (error) {
386
+ console.error("Failed to compute drift notice:", error);
387
+ }
388
+ }
389
+ return {
390
+ displayPath: first.path,
391
+ absolutePath,
392
+ originalNormalized,
393
+ result,
394
+ bom,
395
+ originalEnding,
396
+ hadUtf8DecodeErrors,
397
+ warnings,
398
+ originalHashes,
399
+ resultHashes,
400
+ appliedCount,
401
+ noopCount,
402
+ totalAddedLines,
403
+ totalRemovedLines,
404
+ driftNotice,
405
+ range: {
406
+ startLine: unionStartLine,
407
+ endLine: unionEndLine,
408
+ startHash: unionStartHash,
409
+ endHash: unionEndHash,
410
+ delta: splitLines(result).length - splitLines(originalNormalized).length,
411
+ },
412
+ };
413
+ }
414
+ // ---------------------------------------------------------------------------
415
+ // the write transaction