dsh-better-edit 0.1.0 → 0.1.2

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.
@@ -5,29 +5,35 @@
5
5
  * the failing item's current range is echoed as fresh serves.
6
6
  * @module dsh-better-edit/tool-batch-edit
7
7
  */
8
- import { defineTool } from '@deepseek-ai/dsh-tools';
9
- import { restoreEndings } from './edit-diff.js';
10
- import { normFromText } from './file-reader.js';
11
- import { scanDrift } from './drift.js';
12
- import { abortIf, isRec, normalizeFilePath, rejectUnknownFields, splitLines } from './utils.js';
13
- import { normReq } from './edit-normalize.js';
14
- import { applyEdit, lineHashes, resEdit, MAX_HASH_LINES, } from './hashline/index.js';
15
- import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from './hashline/served.js';
16
- import { buildBatchResult } from './edit-response.js';
17
- import { saveUndo } from './undo-edit.js';
18
- import { loadServed, recordServedTruncated } from './served-store.js';
19
- import { BATCH_EDIT_MAX_ITEMS, NOOP_LOOP_THRESHOLD } from './constants.js';
20
- import { collectRemovedHashes, countLineChanges, resolveMissingPath, } from './edit-pipeline.js';
21
- import { clearNoopLoop, noopPayloadKey, trackNoopPayload } from './noop-guard.js';
22
- import { BATCH_EDIT_DESCRIPTION } from './prompts.js';
23
- import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema } from './schema.js';
24
- import { execCwd, execSessionKey } from './dsh-context.js';
25
- const BATCH_ITEM_KS = new Set(['path', 'remove_from', 'remove_to', 'replacement_text']);
8
+ import { defineTool } from "@deepseek-ai/dsh-tools";
9
+ import { restoreEndings } from "./edit-diff.js";
10
+ import { normFromText } from "./file-reader.js";
11
+ import { scanDrift } from "./drift.js";
12
+ import { abortIf, isRec, normalizeFilePath, rejectUnknownFields, splitLines, } from "./utils.js";
13
+ import { normReq } from "./edit-normalize.js";
14
+ import { applyEdit, lineHashes, resEdit, MAX_HASH_LINES, } from "./hashline/index.js";
15
+ import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "./hashline/served.js";
16
+ import { buildBatchResult } from "./edit-response.js";
17
+ import { saveUndo } from "./undo-edit.js";
18
+ import { loadServed, recordServedTruncated } from "./served-store.js";
19
+ import { BATCH_EDIT_MAX_ITEMS, NOOP_LOOP_THRESHOLD } from "./constants.js";
20
+ import { collectRemovedHashes, countLineChanges, resolveMissingPath, } from "./edit-pipeline.js";
21
+ import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
22
+ import { BATCH_EDIT_DESCRIPTION } from "./prompts.js";
23
+ import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema, } from "./schema.js";
24
+ import { execCwd, execSessionKey } from "./dsh-context.js";
25
+ import { withWorkspace } from "./workspace.js";
26
+ const BATCH_ITEM_KS = new Set([
27
+ "path",
28
+ "remove_from",
29
+ "remove_to",
30
+ "replacement_text",
31
+ ]);
26
32
  function assertBatchReq(request) {
27
33
  if (!isRec(request)) {
28
34
  throw new Error('[E_BAD_SHAPE] batch_edit request must be an object with an "edits" array.');
29
35
  }
30
- rejectUnknownFields(request, new Set(['edits']), 'batch_edit request');
36
+ rejectUnknownFields(request, new Set(["edits"]), "batch_edit request");
31
37
  if (!Array.isArray(request.edits) || request.edits.length === 0) {
32
38
  throw new Error('[E_BAD_SHAPE] batch_edit request requires a non-empty "edits" array.');
33
39
  }
@@ -39,13 +45,13 @@ function assertBatchReq(request) {
39
45
  throw new Error(`[E_BAD_SHAPE] edits[${index}] must be an object with remove_from, remove_to, and replacement_text.`);
40
46
  }
41
47
  rejectUnknownFields(item, BATCH_ITEM_KS, `edits[${index}]`);
42
- if (typeof item.remove_from !== 'string' ||
43
- typeof item.remove_to !== 'string' ||
44
- typeof item.replacement_text !== 'string') {
48
+ if (typeof item.remove_from !== "string" ||
49
+ typeof item.remove_to !== "string" ||
50
+ typeof item.replacement_text !== "string") {
45
51
  throw new Error(`[E_BAD_SHAPE] edits[${index}] requires "remove_from", "remove_to", and "replacement_text" strings.`);
46
52
  }
47
53
  if (item.path !== undefined &&
48
- (typeof item.path !== 'string' || item.path.length === 0)) {
54
+ (typeof item.path !== "string" || item.path.length === 0)) {
49
55
  throw new Error(`[E_BAD_SHAPE] edits[${index}].path must be a non-empty string.`);
50
56
  }
51
57
  });
@@ -56,7 +62,7 @@ async function prepareItems(io, params, cwd, signal) {
56
62
  const raw = params.edits[index];
57
63
  const record = { ...raw };
58
64
  normalizeFilePath(record);
59
- let path = typeof record.path === 'string' ? record.path : undefined;
65
+ let path = typeof record.path === "string" ? record.path : undefined;
60
66
  let pathWarning;
61
67
  if (!path) {
62
68
  let resolution;
@@ -131,8 +137,8 @@ async function processFile(io, items, _cwd, opts) {
131
137
  let totalRemovedLines = 0;
132
138
  let unionStartLine = Infinity;
133
139
  let unionEndLine = -Infinity;
134
- let unionStartHash = '';
135
- let unionEndHash = '';
140
+ let unionStartHash = "";
141
+ let unionEndHash = "";
136
142
  let lastApplied;
137
143
  for (const item of items) {
138
144
  abortIf(opts.signal);
@@ -147,7 +153,7 @@ async function processFile(io, items, _cwd, opts) {
147
153
  catch (error) {
148
154
  const message = error instanceof Error ? error.message : String(error);
149
155
  throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${message}\n` +
150
- 'The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied.');
156
+ "The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied.");
151
157
  }
152
158
  let anchorResult;
153
159
  try {
@@ -161,13 +167,13 @@ async function processFile(io, items, _cwd, opts) {
161
167
  ? error.servedRows
162
168
  : echoRowsForItem(edit, originalHashes);
163
169
  if (echoRows) {
164
- await recordEchoServes(opts.sessionKey, absolutePath, echoRows, 'live');
170
+ await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live");
165
171
  }
166
172
  const echoBlock = echoRows
167
173
  ? ` Current on-disk range for edits[${item.index}] (unchanged — nothing was written):\n${fmtServedRows(echoRows, originalLines)}`
168
- : ' Call read() to get fresh anchors.';
174
+ : " Call read() to get fresh anchors.";
169
175
  throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${error.message}${echoBlock}\n` +
170
- '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.');
176
+ "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.");
171
177
  }
172
178
  throw error;
173
179
  }
@@ -190,12 +196,12 @@ async function processFile(io, items, _cwd, opts) {
190
196
  const originalLines = splitLines(originalNormalized);
191
197
  const echoRows = echoRowsForItem(edit, originalHashes);
192
198
  if (echoRows) {
193
- await recordEchoServes(opts.sessionKey, absolutePath, echoRows, 'live');
199
+ await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live");
194
200
  }
195
201
  throw new Error(`[E_NOOP_LOOP] edits[${item.index}] (${item.path}): this exact edit (anchors ${item.remove_from} to ${item.remove_to}) has been submitted ${count} times and produced no changes each time — the range already contains the replacement text. Do not resend it; it will never change the file. The whole batch was rejected and nothing was written.` +
196
202
  (echoRows
197
203
  ? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}`
198
- : ''));
204
+ : ""));
199
205
  }
200
206
  if (count === 2) {
201
207
  warnings.push(`[E_NOOP_LOOP] Notice: edits[${item.index}] (${item.path}) — this exact edit has produced no changes twice in a row; the range already contains the replacement text. Resending it again will reject the batch.`);
@@ -232,7 +238,7 @@ async function processFile(io, items, _cwd, opts) {
232
238
  }, undefined, true);
233
239
  }
234
240
  if (hadUtf8DecodeErrors) {
235
- warnings.push('Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.');
241
+ warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
236
242
  }
237
243
  if (first.pathWarning)
238
244
  warnings.unshift(first.pathWarning);
@@ -257,7 +263,7 @@ async function processFile(io, items, _cwd, opts) {
257
263
  });
258
264
  }
259
265
  catch (error) {
260
- console.error('Failed to compute drift notice:', error);
266
+ console.error("Failed to compute drift notice:", error);
261
267
  }
262
268
  }
263
269
  return {
@@ -309,18 +315,18 @@ function toSection(file) {
309
315
  */
310
316
  export function buildBatchEditTool(io) {
311
317
  return defineTool({
312
- name: 'batch_edit',
318
+ name: "batch_edit",
313
319
  description: BATCH_EDIT_DESCRIPTION,
314
320
  parameters: {
315
321
  edits: {
316
- type: 'array',
322
+ type: "array",
317
323
  required: true,
318
324
  description: `Ordered list of edits, each with the same shape as the edit tool: { path?, remove_from, remove_to, replacement_text }. ` +
319
- 'Edits to the same file are applied in order and verified against what was served before anything is written. ' +
320
- 'The batch is all-or-nothing: if any edit fails validation, nothing is written and the failing edit\u2019s current range is served back. ' +
321
- 'Use batch_edit when you have multiple edits; do not issue several edit calls in one message.',
325
+ "Edits to the same file are applied in order and verified against what was served before anything is written. " +
326
+ "The batch is all-or-nothing: if any edit fails validation, nothing is written and the failing edit\u2019s current range is served back. " +
327
+ "Use batch_edit when you have multiple edits; do not issue several edit calls in one message.",
322
328
  items: {
323
- type: 'object',
329
+ type: "object",
324
330
  additionalProperties: false,
325
331
  properties: {
326
332
  path: pathSchema,
@@ -332,97 +338,99 @@ export function buildBatchEditTool(io) {
332
338
  },
333
339
  },
334
340
  output: {
335
- schema: { type: 'string' },
336
- render: (_args, value) => [{ type: 'text', text: value }],
341
+ schema: { type: "string" },
342
+ render: (_args, value) => [{ type: "text", text: value }],
337
343
  },
338
344
  async execute(args, exec) {
339
- const cwd = execCwd(exec);
340
- const sessionKey = execSessionKey(exec);
341
- const signal = exec.signal;
342
- const canonical = normReq(args);
343
- if (isRec(canonical) && Array.isArray(canonical.edits)) {
344
- canonical.edits = canonical.edits.map((item) => {
345
- if (!isRec(item))
346
- return item;
347
- const cloned = { ...item };
348
- normalizeFilePath(cloned);
349
- return cloned;
350
- });
351
- }
352
- assertBatchReq(canonical);
353
- const items = await prepareItems(io, canonical, cwd, signal);
354
- const groups = groupByPath(items);
355
- const processed = [];
356
- for (const groupItems of groups.values()) {
357
- abortIf(signal);
358
- processed.push(await processFile(io, groupItems, cwd, {
359
- signal,
360
- sessionKey,
361
- }));
362
- }
363
- const undos = [];
364
- for (const file of processed) {
365
- if (file.appliedCount === 0)
366
- continue;
367
- const undo = await saveUndo(file.absolutePath, {
368
- content: file.originalNormalized,
369
- bom: file.bom,
370
- originalEnding: file.originalEnding,
371
- hashes: file.originalHashes,
372
- resultContent: file.result,
373
- });
374
- if (!undo.persisted) {
375
- for (const u of undos) {
376
- try {
377
- await u.restore();
378
- }
379
- catch (error) {
380
- console.error('Failed to restore undo entry after batch abort:', error);
381
- }
382
- }
383
- throw new Error('[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the batch was NOT applied and no file was written. Retry the batch, or use write if the store cannot be recovered.');
345
+ return withWorkspace(execCwd(exec), async () => {
346
+ const cwd = execCwd(exec);
347
+ const sessionKey = execSessionKey(exec);
348
+ const signal = exec.signal;
349
+ const canonical = normReq(args);
350
+ if (isRec(canonical) && Array.isArray(canonical.edits)) {
351
+ canonical.edits = canonical.edits.map((item) => {
352
+ if (!isRec(item))
353
+ return item;
354
+ const cloned = { ...item };
355
+ normalizeFilePath(cloned);
356
+ return cloned;
357
+ });
384
358
  }
385
- undos.push({ file, restore: undo.restore });
386
- }
387
- const written = [];
388
- try {
389
- for (const u of undos) {
359
+ assertBatchReq(canonical);
360
+ const items = await prepareItems(io, canonical, cwd, signal);
361
+ const groups = groupByPath(items);
362
+ const processed = [];
363
+ for (const groupItems of groups.values()) {
390
364
  abortIf(signal);
391
- await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), signal);
392
- written.push(u);
365
+ processed.push(await processFile(io, groupItems, cwd, {
366
+ signal,
367
+ sessionKey,
368
+ }));
393
369
  }
394
- }
395
- catch (error) {
396
- for (const w of written) {
397
- try {
398
- await io.writeText(w.file.absolutePath, w.file.bom +
399
- restoreEndings(w.file.originalNormalized, w.file.originalEnding));
400
- }
401
- catch (restoreError) {
402
- console.error('Failed to restore file after batch write failure:', restoreError);
370
+ const undos = [];
371
+ for (const file of processed) {
372
+ if (file.appliedCount === 0)
373
+ continue;
374
+ const undo = await saveUndo(file.absolutePath, {
375
+ content: file.originalNormalized,
376
+ bom: file.bom,
377
+ originalEnding: file.originalEnding,
378
+ hashes: file.originalHashes,
379
+ resultContent: file.result,
380
+ });
381
+ if (!undo.persisted) {
382
+ for (const u of undos) {
383
+ try {
384
+ await u.restore();
385
+ }
386
+ catch (error) {
387
+ console.error("Failed to restore undo entry after batch abort:", error);
388
+ }
389
+ }
390
+ throw new Error("[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the batch was NOT applied and no file was written. Retry the batch, or use write if the store cannot be recovered.");
403
391
  }
404
- try {
405
- await w.restore();
392
+ undos.push({ file, restore: undo.restore });
393
+ }
394
+ const written = [];
395
+ try {
396
+ for (const u of undos) {
397
+ abortIf(signal);
398
+ await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), signal, exec);
399
+ written.push(u);
406
400
  }
407
- catch (restoreError) {
408
- console.error('Failed to restore undo entry after batch write failure:', restoreError);
401
+ }
402
+ catch (error) {
403
+ for (const w of written) {
404
+ try {
405
+ await io.writeText(w.file.absolutePath, w.file.bom +
406
+ restoreEndings(w.file.originalNormalized, w.file.originalEnding), undefined, exec);
407
+ }
408
+ catch (restoreError) {
409
+ console.error("Failed to restore file after batch write failure:", restoreError);
410
+ }
411
+ try {
412
+ await w.restore();
413
+ }
414
+ catch (restoreError) {
415
+ console.error("Failed to restore undo entry after batch write failure:", restoreError);
416
+ }
409
417
  }
418
+ throw error;
410
419
  }
411
- throw error;
412
- }
413
- const result = buildBatchResult(processed.map(toSection));
414
- if (result.details.servedRows && result.details.servedRows.length > 0) {
415
- const byPath = result.details.servedByPath ?? [];
416
- for (const entry of byPath) {
417
- if (entry.servedRows.length === 0)
418
- continue;
419
- const file = processed.find((f) => f.displayPath === entry.path);
420
- if (file) {
421
- await recordServedTruncated(sessionKey, file.absolutePath, entry.servedRows, splitLines(file.result).length, file.range.startLine - 1);
420
+ const result = buildBatchResult(processed.map(toSection));
421
+ if (result.details.servedRows && result.details.servedRows.length > 0) {
422
+ const byPath = result.details.servedByPath ?? [];
423
+ for (const entry of byPath) {
424
+ if (entry.servedRows.length === 0)
425
+ continue;
426
+ const file = processed.find((f) => f.displayPath === entry.path);
427
+ if (file) {
428
+ await recordServedTruncated(sessionKey, file.absolutePath, entry.servedRows, splitLines(file.result).length, file.range.startLine - 1);
429
+ }
422
430
  }
423
431
  }
424
- }
425
- return result.content[0].text;
432
+ return result.content[0].text;
433
+ });
426
434
  },
427
435
  });
428
436
  }
package/lib/tool-edit.js CHANGED
@@ -5,20 +5,21 @@
5
5
  * served-range verification, reject-and-serve) replaces the built-in one.
6
6
  * @module dsh-better-edit/tool-edit
7
7
  */
8
- import { defineTool } from '@deepseek-ai/dsh-tools';
9
- import { restoreEndings } from './edit-diff.js';
10
- import { normReq } from './edit-normalize.js';
11
- import { abortIf, isRec, splitLines } from './utils.js';
12
- import { assertReq, execPipeline, resolveMissingPath, snapshotIdFor, } from './edit-pipeline.js';
13
- import { buildRangeEcho, fmtServedRows, recordEchoServes, } from './hashline/served.js';
14
- import { saveUndo } from './undo-edit.js';
15
- import { clearNoopLoop, noopPayloadKey, trackNoopPayload } from './noop-guard.js';
16
- import { buildNoop, buildChanged } from './edit-response.js';
17
- import { recordServedTruncated } from './served-store.js';
18
- import { NOOP_LOOP_THRESHOLD } from './constants.js';
19
- import { EDIT_DESCRIPTION } from './prompts.js';
20
- import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema } from './schema.js';
21
- import { execCwd, execSessionKey } from './dsh-context.js';
8
+ import { defineTool } from "@deepseek-ai/dsh-tools";
9
+ import { restoreEndings } from "./edit-diff.js";
10
+ import { normReq } from "./edit-normalize.js";
11
+ import { abortIf, isRec, splitLines } from "./utils.js";
12
+ import { assertReq, execPipeline, resolveMissingPath, snapshotIdFor, } from "./edit-pipeline.js";
13
+ import { buildRangeEcho, fmtServedRows, recordEchoServes, } from "./hashline/served.js";
14
+ import { saveUndo } from "./undo-edit.js";
15
+ import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
16
+ import { buildNoop, buildChanged } from "./edit-response.js";
17
+ import { recordServedTruncated } from "./served-store.js";
18
+ import { NOOP_LOOP_THRESHOLD } from "./constants.js";
19
+ import { EDIT_DESCRIPTION } from "./prompts.js";
20
+ import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema, } from "./schema.js";
21
+ import { execCwd, execSessionKey } from "./dsh-context.js";
22
+ import { withWorkspace } from "./workspace.js";
22
23
  /**
23
24
  * Register the hash-anchored `edit` tool on the calling agent's scope.
24
25
  * @param _rootCtx - host context (logger, lifecycle).
@@ -29,7 +30,7 @@ import { execCwd, execSessionKey } from './dsh-context.js';
29
30
  */
30
31
  export function buildEditTool(io) {
31
32
  return defineTool({
32
- name: 'edit',
33
+ name: "edit",
33
34
  description: EDIT_DESCRIPTION,
34
35
  parameters: {
35
36
  path: pathSchema,
@@ -38,109 +39,111 @@ export function buildEditTool(io) {
38
39
  replacement_text: replacementTextSchema,
39
40
  },
40
41
  output: {
41
- schema: { type: 'string' },
42
- render: (_args, value) => [{ type: 'text', text: value }],
42
+ schema: { type: "string" },
43
+ render: (_args, value) => [{ type: "text", text: value }],
43
44
  },
44
45
  async execute(args, exec) {
45
- const cwd = execCwd(exec);
46
- const sessionKey = execSessionKey(exec);
47
- const signal = exec.signal;
48
- const canonical = normReq(args);
49
- const resolution = isRec(canonical)
50
- ? await resolveMissingPath(canonical)
51
- : undefined;
52
- if (resolution && isRec(canonical)) {
53
- canonical.path = resolution.path;
54
- }
55
- assertReq(canonical);
56
- const normalizedParams = canonical;
57
- const path = normalizedParams.path;
58
- abortIf(signal);
59
- const pipeline = await execPipeline(io, normalizedParams, cwd, {
60
- signal,
61
- sessionKey,
62
- });
63
- const { originalNormalized, originalHashes, result, bom, originalEnding, hadUtf8DecodeErrors, warnings, noopEdit, firstChangedLine, lastChangedLine, resultHashes, totalAddedLines, totalRemovedLines, driftNotice, range, absolutePath, } = pipeline;
64
- if (resolution) {
65
- warnings.unshift(resolution.warning);
66
- }
67
- const editsAttempted = 1;
68
- if (originalNormalized === result) {
69
- const payload = noopPayloadKey(absolutePath, canonical.remove_from, canonical.remove_to, canonical.replacement_text);
70
- const count = trackNoopPayload(absolutePath, payload);
71
- if (count >= NOOP_LOOP_THRESHOLD) {
72
- const echoRows = buildRangeEcho(range.startLine, range.endLine, originalHashes);
73
- const echo = fmtServedRows(echoRows, splitLines(originalNormalized));
74
- await recordEchoServes(sessionKey, absolutePath, echoRows, 'live');
75
- throw new Error(`[E_NOOP_LOOP] This exact edit (anchors ${canonical.remove_from} to ${canonical.remove_to} in ${path}) has been submitted ${count} times and produced no changes each time — the range already contains the replacement text. Do not resend this edit; it will never change the file. Current range:\n${echo}`);
46
+ return withWorkspace(execCwd(exec), async () => {
47
+ const cwd = execCwd(exec);
48
+ const sessionKey = execSessionKey(exec);
49
+ const signal = exec.signal;
50
+ const canonical = normReq(args);
51
+ const resolution = isRec(canonical)
52
+ ? await resolveMissingPath(canonical)
53
+ : undefined;
54
+ if (resolution && isRec(canonical)) {
55
+ canonical.path = resolution.path;
56
+ }
57
+ assertReq(canonical);
58
+ const normalizedParams = canonical;
59
+ const path = normalizedParams.path;
60
+ abortIf(signal);
61
+ const pipeline = await execPipeline(io, normalizedParams, cwd, {
62
+ signal,
63
+ sessionKey,
64
+ });
65
+ const { originalNormalized, originalHashes, result, bom, originalEnding, hadUtf8DecodeErrors, warnings, noopEdit, firstChangedLine, lastChangedLine, resultHashes, totalAddedLines, totalRemovedLines, driftNotice, range, absolutePath, } = pipeline;
66
+ if (resolution) {
67
+ warnings.unshift(resolution.warning);
76
68
  }
77
- if (count === 2) {
78
- warnings.push(`[E_NOOP_LOOP] Notice: this exact edit (anchors ${canonical.remove_from} to ${canonical.remove_to} in ${path}) has produced no changes twice in a row. The range already contains the replacement text; resending it again will be rejected.`);
69
+ const editsAttempted = 1;
70
+ if (originalNormalized === result) {
71
+ const payload = noopPayloadKey(absolutePath, canonical.remove_from, canonical.remove_to, canonical.replacement_text);
72
+ const count = trackNoopPayload(absolutePath, payload);
73
+ if (count >= NOOP_LOOP_THRESHOLD) {
74
+ const echoRows = buildRangeEcho(range.startLine, range.endLine, originalHashes);
75
+ const echo = fmtServedRows(echoRows, splitLines(originalNormalized));
76
+ await recordEchoServes(sessionKey, absolutePath, echoRows, "live");
77
+ throw new Error(`[E_NOOP_LOOP] This exact edit (anchors ${canonical.remove_from} to ${canonical.remove_to} in ${path}) has been submitted ${count} times and produced no changes each time — the range already contains the replacement text. Do not resend this edit; it will never change the file. Current range:\n${echo}`);
78
+ }
79
+ if (count === 2) {
80
+ warnings.push(`[E_NOOP_LOOP] Notice: this exact edit (anchors ${canonical.remove_from} to ${canonical.remove_to} in ${path}) has produced no changes twice in a row. The range already contains the replacement text; resending it again will be rejected.`);
81
+ }
82
+ const noopSnapshotId = await snapshotIdFor(io, absolutePath, signal);
83
+ const noopResult = buildNoop({
84
+ path,
85
+ noopEdit,
86
+ snapshotId: noopSnapshotId,
87
+ editMeta: {
88
+ editsAttempted,
89
+ noopEditsCount: noopEdit ? 1 : 0,
90
+ addedLines: 0,
91
+ removedLines: 0,
92
+ },
93
+ warnings,
94
+ driftNotice,
95
+ });
96
+ return noopResult.content[0].text;
79
97
  }
80
- const noopSnapshotId = await snapshotIdFor(io, absolutePath, signal);
81
- const noopResult = buildNoop({
98
+ clearNoopLoop(absolutePath);
99
+ if (hadUtf8DecodeErrors) {
100
+ warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
101
+ }
102
+ abortIf(signal);
103
+ const undo = await saveUndo(absolutePath, {
104
+ content: originalNormalized,
105
+ bom,
106
+ originalEnding,
107
+ hashes: originalHashes,
108
+ resultContent: result,
109
+ });
110
+ if (!undo.persisted) {
111
+ throw new Error(`[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the edit was NOT applied and ${path} is unchanged. Retry the edit, or use write if the store cannot be recovered.`);
112
+ }
113
+ try {
114
+ abortIf(signal);
115
+ await io.writeText(absolutePath, bom + restoreEndings(result, originalEnding), signal, exec);
116
+ }
117
+ catch (error) {
118
+ await undo.restore();
119
+ throw error;
120
+ }
121
+ const updatedSnapshotId = await snapshotIdFor(io, absolutePath, signal);
122
+ const editMeta = {
123
+ editsAttempted,
124
+ noopEditsCount: noopEdit ? 1 : 0,
125
+ firstChangedLine,
126
+ lastChangedLine,
127
+ addedLines: totalAddedLines,
128
+ removedLines: totalRemovedLines,
129
+ };
130
+ const successInput = {
82
131
  path,
83
- noopEdit,
84
- snapshotId: noopSnapshotId,
85
- editMeta: {
86
- editsAttempted,
87
- noopEditsCount: noopEdit ? 1 : 0,
88
- addedLines: 0,
89
- removedLines: 0,
90
- },
132
+ originalNormalized,
133
+ originalHashes,
134
+ result,
135
+ resultHashes,
91
136
  warnings,
137
+ snapshotId: updatedSnapshotId,
138
+ editMeta,
92
139
  driftNotice,
93
- });
94
- return noopResult.content[0].text;
95
- }
96
- clearNoopLoop(absolutePath);
97
- if (hadUtf8DecodeErrors) {
98
- warnings.push('Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.');
99
- }
100
- abortIf(signal);
101
- const undo = await saveUndo(absolutePath, {
102
- content: originalNormalized,
103
- bom,
104
- originalEnding,
105
- hashes: originalHashes,
106
- resultContent: result,
140
+ };
141
+ const changed = buildChanged(successInput);
142
+ if (changed.details.servedRows && changed.details.servedRows.length > 0) {
143
+ await recordServedTruncated(sessionKey, absolutePath, changed.details.servedRows, splitLines(result).length, range.startLine - 1);
144
+ }
145
+ return changed.content[0].text;
107
146
  });
108
- if (!undo.persisted) {
109
- throw new Error(`[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the edit was NOT applied and ${path} is unchanged. Retry the edit, or use write if the store cannot be recovered.`);
110
- }
111
- try {
112
- abortIf(signal);
113
- await io.writeText(absolutePath, bom + restoreEndings(result, originalEnding), signal);
114
- }
115
- catch (error) {
116
- await undo.restore();
117
- throw error;
118
- }
119
- const updatedSnapshotId = await snapshotIdFor(io, absolutePath, signal);
120
- const editMeta = {
121
- editsAttempted,
122
- noopEditsCount: noopEdit ? 1 : 0,
123
- firstChangedLine,
124
- lastChangedLine,
125
- addedLines: totalAddedLines,
126
- removedLines: totalRemovedLines,
127
- };
128
- const successInput = {
129
- path,
130
- originalNormalized,
131
- originalHashes,
132
- result,
133
- resultHashes,
134
- warnings,
135
- snapshotId: updatedSnapshotId,
136
- editMeta,
137
- driftNotice,
138
- };
139
- const changed = buildChanged(successInput);
140
- if (changed.details.servedRows && changed.details.servedRows.length > 0) {
141
- await recordServedTruncated(sessionKey, absolutePath, changed.details.servedRows, splitLines(result).length, range.startLine - 1);
142
- }
143
- return changed.content[0].text;
144
147
  },
145
148
  });
146
149
  }