dsh-better-edit 0.7.1 → 0.8.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 (46) hide show
  1. package/CHANGELOG.md +50 -25
  2. package/README.md +72 -66
  3. package/README.zh.md +83 -83
  4. package/lib/canonical-path.js +4 -1
  5. package/lib/contract.js +67 -22
  6. package/lib/edit-diff.js +1 -5
  7. package/lib/encoding.js +22 -5
  8. package/lib/file-encoding-state.js +50 -11
  9. package/lib/file-view.js +28 -41
  10. package/lib/fs-bridge.js +59 -23
  11. package/lib/fs-write.js +1 -1
  12. package/lib/guidance/materialize.js +1 -6
  13. package/lib/guidance/resolve.js +1 -1
  14. package/lib/hash-store.js +12 -20
  15. package/lib/hashline/anchor-pipeline.js +29 -29
  16. package/lib/hashline/hash-assign.js +7 -4
  17. package/lib/hashline/hash.js +3 -3
  18. package/lib/index.js +6 -0
  19. package/lib/mutation/engine.js +11 -14
  20. package/lib/mutation.js +7 -6
  21. package/lib/prompts.js +9 -8
  22. package/lib/read-and-serve.js +22 -11
  23. package/lib/render-text-warning.js +21 -0
  24. package/lib/sandbox.js +2 -5
  25. package/lib/self-heal.js +30 -27
  26. package/lib/session-view.js +5 -1
  27. package/lib/store-config.js +7 -2
  28. package/lib/store-lifecycle.js +7 -2
  29. package/lib/tool-edit.js +5 -2
  30. package/lib/tool-read.js +6 -9
  31. package/lib/tool-str-replace-editor.js +274 -0
  32. package/lib/tool-undo.js +2 -3
  33. package/lib/types/contract.d.ts +104 -17
  34. package/lib/types/file-encoding-state.d.ts +3 -0
  35. package/lib/types/file-view.d.ts +1 -1
  36. package/lib/types/hashline/index.d.ts +1 -1
  37. package/lib/types/render-text-warning.d.ts +22 -0
  38. package/lib/types/self-heal.d.ts +2 -0
  39. package/lib/types/tool-str-replace-editor.d.ts +27 -0
  40. package/lib/types/undo-edit.d.ts +1 -1
  41. package/lib/types/write-hook.d.ts +2 -2
  42. package/lib/undo-edit.js +6 -8
  43. package/lib/utils.js +1 -2
  44. package/lib/workspace-context.js +1 -1
  45. package/lib/write-hook.js +19 -22
  46. package/package.json +63 -57
@@ -17,7 +17,7 @@
17
17
  * @module dsh-better-edit/hashline/anchor-pipeline
18
18
  */
19
19
  import { abortIf, splitLines, rejectUnknownFields, clipLine, CodedError } from "../utils.js";
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";
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";
21
21
  import { recordServed, servedPositionsOf } from "../session-view.js";
22
22
  import { SERVED_ECHO_CAP } from "../constants.js";
23
23
  import { NEW_CONTENT_NOT_STRING_MSG } from "../constants.js";
@@ -48,8 +48,7 @@ function diagRef(ref) {
48
48
  }
49
49
  function parseRef(ref) {
50
50
  const trimmed = ref.trim();
51
- if (trimmed.length === ANCHOR_LEN &&
52
- ALPH_RE.test(trimmed)) {
51
+ if (trimmed.length === ANCHOR_LEN && ALPH_RE.test(trimmed)) {
53
52
  return { hash: trimmed };
54
53
  }
55
54
  throw new CodedError("E_BAD_ANCHOR", diagRef(ref));
@@ -155,8 +154,7 @@ function assertItem(edit) {
155
154
  if (typeof edit.replacement_text !== "string") {
156
155
  throw new CodedError("E_BAD_PAYLOAD", NEW_CONTENT_NOT_STRING_MSG);
157
156
  }
158
- if (typeof edit.remove_from !== "string" ||
159
- typeof edit.remove_to !== "string") {
157
+ if (typeof edit.remove_from !== "string" || typeof edit.remove_to !== "string") {
160
158
  throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] The edit requires "remove_from" and "remove_to" anchor strings (3-char hashes from read output).`);
161
159
  }
162
160
  }
@@ -223,11 +221,11 @@ function stripBarePrefixes(edit, fileHashes, _warnings) {
223
221
  });
224
222
  if (stripped.length === 0)
225
223
  return edit;
226
- const locations = stripped
227
- .map((s) => `replacement_text line ${s.lineIndex + 1}`)
228
- .join(", ");
224
+ const locations = stripped.map((s) => `replacement_text line ${s.lineIndex + 1}`).join(", ");
229
225
  const matchedCount = stripped.filter((s) => s.matched).length;
230
- const evidence = matchedCount === 0 ? "0 matched — verify literal 'HASH│' content" : `${matchedCount}/${stripped.length} matched`;
226
+ const evidence = matchedCount === 0
227
+ ? "0 matched — verify literal 'HASH│' content"
228
+ : `${matchedCount}/${stripped.length} matched`;
231
229
  if (matchedCount === stripped.length) {
232
230
  throw new BadAnchorError(`[MODEL] [E_BAD_ANCHOR] stripped "HASH│" prefix from ${locations} (${evidence}) — use bare content without HASH│ next time.`, { ...edit, content_lines: contentLines });
233
231
  }
@@ -251,9 +249,7 @@ function stripDiffPrefixes(edit, _warnings) {
251
249
  });
252
250
  if (stripped.length === 0)
253
251
  return edit;
254
- const locations = stripped
255
- .map((i) => `replacement_text line ${i + 1}`)
256
- .join(", ");
252
+ const locations = stripped.map((i) => `replacement_text line ${i + 1}`).join(", ");
257
253
  throw new BadAnchorError(`[MODEL] [E_BAD_ANCHOR] stripped diff-preview marker from ${locations}.`, { ...edit, content_lines: contentLines });
258
254
  }
259
255
  /** @internal — private to anchor-pipeline seam */
@@ -265,9 +261,7 @@ function swapReversedRanges(edit, fileHashes, warnings) {
265
261
  const [startRef, endRef] = edit.hash_bounds;
266
262
  const startLine = lineByHash.get(startRef.hash);
267
263
  const endLine = lineByHash.get(endRef.hash);
268
- if (startLine === undefined ||
269
- endLine === undefined ||
270
- startLine <= endLine) {
264
+ if (startLine === undefined || endLine === undefined || startLine <= endLine) {
271
265
  return edit;
272
266
  }
273
267
  warnings.push(`[USER] [E_REVERSED_ANCHORS] reversed remove_from/remove_to (${startRef.hash} after ${endRef.hash}); swapped (healed).`);
@@ -320,7 +314,9 @@ function valEdit(edit, fileLines, fileHashes, warnings, signal) {
320
314
  mismatches,
321
315
  };
322
316
  }
323
- export function findNewEdge() { return undefined; }
317
+ export function findNewEdge() {
318
+ return undefined;
319
+ }
324
320
  export { warnUnicodeEsc };
325
321
  export class ServedRejectionError extends CodedError {
326
322
  code;
@@ -364,7 +360,9 @@ export function isAnchorMismatch(error) {
364
360
  export function findEditHashEcho(replacementLines, served, startLine) {
365
361
  for (let k = 0; k < replacementLines.length; k++) {
366
362
  const pos = startLine + k - 1;
367
- if (pos < served.length && served[pos] !== null && replacementLines[k].startsWith(served[pos] + HASH_SEP)) {
363
+ if (pos < served.length &&
364
+ served[pos] !== null &&
365
+ replacementLines[k].startsWith(served[pos] + HASH_SEP)) {
368
366
  return { k: k + 1, hash: served[pos] };
369
367
  }
370
368
  }
@@ -386,9 +384,7 @@ export function buildRangeEcho(startLine, endLine, fileHashes) {
386
384
  return rows;
387
385
  }
388
386
  export function fmtServedRows(rows, fileLines) {
389
- return rows
390
- .map((row) => `${row.hash}${HASH_SEP}${fileLines[row.position] ?? ""}`)
391
- .join("\n");
387
+ return rows.map((row) => `${row.hash}${HASH_SEP}${fileLines[row.position] ?? ""}`).join("\n");
392
388
  }
393
389
  function retryHint() {
394
390
  return "Retry with these anchors (no read needed).";
@@ -397,7 +393,7 @@ function paginationHint(nextOffset, more) {
397
393
  return `[... ${more} more — read offset=${nextOffset}]`;
398
394
  }
399
395
  export function verifyServedRange(args) {
400
- const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath, } = args;
396
+ const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath } = args;
401
397
  const where = filePath ? ` in ${filePath}` : "";
402
398
  const retiredSet = args.retired ?? new Set();
403
399
  const servedCanons = args.servedCanons;
@@ -718,7 +714,9 @@ export function verifyServedRange(args) {
718
714
  if (h && retiredSet.has(h)) {
719
715
  const expectedCanon = servedCanons?.[from + k] ?? undefined;
720
716
  const actualCanon = canon(fileLines[startLine - 1 + k] ?? "");
721
- if (expectedCanon !== undefined && expectedCanon !== null && expectedCanon !== actualCanon) {
717
+ if (expectedCanon !== undefined &&
718
+ expectedCanon !== null &&
719
+ expectedCanon !== actualCanon) {
722
720
  throw new ServedRejectionError({
723
721
  code: "E_STALE_RANGE",
724
722
  message: `[MODEL] [E_STALE_RANGE] line ${startLine + k}${where} uses retired anchor "${h}" (freed since last full read, canon changed). Re-read.\nCurrent range:\n${echo}`,
@@ -824,7 +822,7 @@ function resToSpan(edit, content, lineIndex) {
824
822
  }
825
823
  function assemble(content, span, signal) {
826
824
  abortIf(signal);
827
- return (content.slice(0, span.start) + span.replacement + content.slice(span.end));
825
+ return content.slice(0, span.start) + span.replacement + content.slice(span.end);
828
826
  }
829
827
  export function applyEdit(content, edit, signal, precomputedHashes, filePath, served, servedCanons, retired, epochSnapshotId, curSnapshotId, strictPos) {
830
828
  abortIf(signal);
@@ -847,15 +845,19 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
847
845
  for (let i = 0; i < fileHashes.length; i++)
848
846
  lineByHash.set(fileHashes[i], i + 1);
849
847
  const startLine = lineByHash.get(stripped.hash_bounds[0].hash);
850
- const echo = (startLine !== undefined ? findEditHashEcho(edit.content_lines, served, startLine) : undefined) ??
851
- (startLine !== undefined ? findEditHashEcho(stripped.content_lines, served, startLine) : undefined);
848
+ const echo = (startLine !== undefined
849
+ ? findEditHashEcho(edit.content_lines, served, startLine)
850
+ : undefined) ??
851
+ (startLine !== undefined
852
+ ? findEditHashEcho(stripped.content_lines, served, startLine)
853
+ : undefined);
852
854
  if (echo) {
853
855
  const msg = `[MODEL] [E_SERVED_ECHO] Refused edit to ${filePath ?? "(unknown file)"}: replacement line ${echo.k} begins with the exact ${echo.hash}${HASH_SEP} anchor served for this session, path, and range-relative line. Remove the copied anchors and retry. Nothing was written.`;
854
856
  throw new EditHashEchoError(msg, []);
855
857
  }
856
858
  throw error;
857
859
  }
858
- const { resolved: initialResolved, mismatches, } = valEdit(prefixFixed, lineIndex.fileLines, fileHashes, warnings, signal);
860
+ const { resolved: initialResolved, mismatches } = valEdit(prefixFixed, lineIndex.fileLines, fileHashes, warnings, signal);
859
861
  if (mismatches.length || !initialResolved) {
860
862
  const { message, servedRows } = fmtMismatchWithServes(mismatches, lineIndex.fileLines, fileHashes, filePath);
861
863
  throw new AnchorMismatchError(message, servedRows);
@@ -931,9 +933,7 @@ export function fmtRegion(hashes, lines) {
931
933
  if (hashes.length !== lines.length) {
932
934
  throw new Error(`fmtRegion: hashes.length (${hashes.length}) must match lines.length (${lines.length}).`);
933
935
  }
934
- return lines
935
- .map((line, index) => `${hashes[index]}${HASH_SEP}${line}`)
936
- .join("\n");
936
+ return lines.map((line, index) => `${hashes[index]}${HASH_SEP}${line}`).join("\n");
937
937
  }
938
938
  export function changedRange(original, result) {
939
939
  if (original === result)
@@ -21,10 +21,12 @@ export function getH() {
21
21
  return hasher;
22
22
  throw new Error("xxhash-wasm hasher not initialized; await initHasher() before calling hashline APIs.");
23
23
  }
24
- const hasherP = xxhash().then((h) => {
24
+ const hasherP = xxhash()
25
+ .then((h) => {
25
26
  hasher = h;
26
27
  return hasher;
27
- }).catch((err) => {
28
+ })
29
+ .catch((err) => {
28
30
  console.error("xxhash-wasm initialization failed:", err);
29
31
  throw err;
30
32
  });
@@ -107,7 +109,7 @@ function getCanon(cache, line) {
107
109
  }
108
110
  const BITSET_WORDS = Math.ceil(HASH_SPACE / 32);
109
111
  function getBit(bits, idx) {
110
- return (bits[idx >>> 5] >>> (idx & 31) & 1) !== 0;
112
+ return ((bits[idx >>> 5] >>> (idx & 31)) & 1) !== 0;
111
113
  }
112
114
  function setBit(bits, idx) {
113
115
  bits[idx >>> 5] |= 1 << (idx & 31);
@@ -188,7 +190,8 @@ function nearestNew(candidates, target) {
188
190
  }
189
191
  const left = lo - 1;
190
192
  const right = lo;
191
- if (left >= 0 && (right >= candidates.length || target - candidates[left] <= candidates[right] - target)) {
193
+ if (left >= 0 &&
194
+ (right >= candidates.length || target - candidates[left] <= candidates[right] - target)) {
192
195
  return left;
193
196
  }
194
197
  return right < candidates.length ? right : -1;
@@ -25,7 +25,7 @@ export function snapshotIOFor(store) {
25
25
  },
26
26
  };
27
27
  }
28
- return defaultHashSnapshotIO ?? {
28
+ return (defaultHashSnapshotIO ?? {
29
29
  get: async (path, content, deleteCorrupt) => {
30
30
  const s = await loadHashStore();
31
31
  return s.getSnapshot(path, content, deleteCorrupt);
@@ -34,7 +34,7 @@ export function snapshotIOFor(store) {
34
34
  const s = await loadHashStore();
35
35
  s.upsertSnapshot(path, checksum, lineCount, hashes);
36
36
  },
37
- };
37
+ });
38
38
  }
39
39
  export function isValidHashList(value) {
40
40
  if (!Array.isArray(value))
@@ -52,7 +52,7 @@ export async function lineHashes(content, path, previous, ioOrStore, persist, re
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
- : ioOrStore ?? snapshotIOFor(undefined);
55
+ : (ioOrStore ?? snapshotIOFor(undefined));
56
56
  if (previous) {
57
57
  const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes, reservedHashes, retiredHashes.size, previous.hashes.length);
58
58
  if (persist !== false && io) {
package/lib/index.js CHANGED
@@ -2,6 +2,7 @@ import { ctxFsIO } from "./fs-bridge.js";
2
2
  import { FsSandboxController } from "./sandbox.js";
3
3
  import { buildReadTool } from "./tool-read.js";
4
4
  import { buildEditTool } from "./tool-edit.js";
5
+ import { buildStrReplaceEditorTool } from "./tool-str-replace-editor.js";
5
6
  import { registerUndoTool } from "./tool-undo.js";
6
7
  import { registerWriteHook } from "./write-hook.js";
7
8
  import { createSelfHealWatcher } from "./self-heal.js";
@@ -70,6 +71,10 @@ function installAgentTools(rootCtx, agent) {
70
71
  disposers.push(agent.ctx.tools.register(hashReadDef));
71
72
  const hashEditDef = buildEditTool(io, sandbox);
72
73
  disposers.push(agent.ctx.tools.register(hashEditDef));
74
+ // Governed shadow of the preset's built-in str_replace_editor
75
+ // (ADR-0015): identical contract, encoding-governed mutations.
76
+ const hashStrReplaceDef = buildStrReplaceEditorTool(io);
77
+ disposers.push(agent.ctx.tools.register(hashStrReplaceDef));
73
78
  disposers.push(registerUndoTool(rootCtx, agent.ctx, io, sandbox));
74
79
  disposers.push(registerWriteHook(rootCtx, agent.ctx, io));
75
80
  const toolsSvc = rootCtx.get("tools");
@@ -81,6 +86,7 @@ function installAgentTools(rootCtx, agent) {
81
86
  toolsSvc,
82
87
  hashReadDef,
83
88
  hashEditDef,
89
+ hashStrReplaceDef,
84
90
  }));
85
91
  // Shadow the preset's built-in tool guidance with the hashline
86
92
  // contract. Same section names on the agent's own layer win over the
@@ -20,7 +20,8 @@ import { applyEdit, resEdit, parseHashRef, } from "../hashline/anchor-pipeline.j
20
20
  import { lineHashes } from "../hashline/hash.js";
21
21
  import { AnchorSpaceExhaustedError, HASH_SPACE } from "../hashline/hash-assign.js";
22
22
  function isAnchorSpaceExhausted(e) {
23
- return e instanceof AnchorSpaceExhaustedError || (e instanceof Error && e.message.includes("E_ANCHOR_SPACE_EXHAUSTED"));
23
+ return (e instanceof AnchorSpaceExhaustedError ||
24
+ (e instanceof Error && e.message.includes("E_ANCHOR_SPACE_EXHAUSTED")));
24
25
  }
25
26
  function promotionWarning(retiredSize, servedLen) {
26
27
  return `[E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted (retired ${retiredSize} + served ${servedLen} of ${HASH_SPACE}); promotion cleared retired — re-read recommended, stale-anchor checks degraded until next full read.`;
@@ -54,7 +55,7 @@ async function retryLineHashesWithPromotion(sessionKey, absolutePath, retired, s
54
55
  import { MAX_HASH_LINES } from "../hashline/hash-assign.js";
55
56
  import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "../hashline/anchor-pipeline.js";
56
57
  import { findSnapshotPathsByHashes } from "../hash-store.js";
57
- import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "../noop-guard.js";
58
+ import { clearNoopLoop, noopPayloadKey, trackNoopPayload } from "../noop-guard.js";
58
59
  import { NOOP_LOOP_THRESHOLD } from "../constants.js";
59
60
  import { abortIf, splitLines } from "../utils.js";
60
61
  // ---------------------------------------------------------------------------
@@ -94,7 +95,7 @@ export async function resolveMissingPath(request) {
94
95
  };
95
96
  }
96
97
  if (matches.length > 1) {
97
- throw new Error(`[MODEL] [E_BAD_PAYLOAD] Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(', ')}. Include the intended path.`);
98
+ throw new Error(`[MODEL] [E_BAD_PAYLOAD] Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(", ")}. Include the intended path.`);
98
99
  }
99
100
  return undefined;
100
101
  }
@@ -161,17 +162,14 @@ export async function applyOne(input, onReject) {
161
162
  anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served, input.servedCanons, retiredForApply, input.epochSnapshotId, input.curSnapshotId, input.strictPos);
162
163
  }
163
164
  catch (error) {
164
- if (error instanceof AnchorMismatchError ||
165
- error instanceof ServedRejectionError) {
165
+ if (error instanceof AnchorMismatchError || error instanceof ServedRejectionError) {
166
166
  return onReject(error, edit);
167
167
  }
168
168
  throw error;
169
169
  }
170
170
  const result = anchorResult.content;
171
171
  const noop = result === input.content;
172
- const removedHashes = noop
173
- ? undefined
174
- : collectRemovedHashes(edit, input.hashes);
172
+ const removedHashes = noop ? undefined : collectRemovedHashes(edit, input.hashes);
175
173
  const retiredForHash = input.retired;
176
174
  let resultHashes;
177
175
  if (noop) {
@@ -238,9 +236,7 @@ export async function enforceNoopLoop(opts) {
238
236
  await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
239
237
  }
240
238
  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.` +
241
- (echoRows
242
- ? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}`
243
- : ""));
239
+ (echoRows ? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}` : ""));
244
240
  }
245
241
  if (count === 2) {
246
242
  return `[E_NOOP_LOOP] Notice: edits[${index}] (${displayPath}) — identical edit no-op'd twice; range already has this text. Resend will reject the batch.`;
@@ -288,7 +284,9 @@ export async function runFileEdits(io, items, opts) {
288
284
  curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
289
285
  }
290
286
  catch { }
291
- const strictPos = epochSnapshotId !== undefined && curSnapshotId !== undefined && epochSnapshotId !== curSnapshotId; // automatic: strict when epoch mismatch (conservative, future: changed∩[L,R] refined)
287
+ const strictPos = epochSnapshotId !== undefined &&
288
+ curSnapshotId !== undefined &&
289
+ epochSnapshotId !== curSnapshotId; // automatic: strict when epoch mismatch (conservative, future: changed∩[L,R] refined)
292
290
  const warnings = [];
293
291
  let currentContent = originalNormalized;
294
292
  let currentHashes = originalHashes;
@@ -324,8 +322,7 @@ export async function runFileEdits(io, items, opts) {
324
322
  curSnapshotId,
325
323
  strictPos,
326
324
  }, async (error, edit) => {
327
- if (error instanceof AnchorMismatchError ||
328
- error instanceof ServedRejectionError) {
325
+ if (error instanceof AnchorMismatchError || error instanceof ServedRejectionError) {
329
326
  const originalLines = splitLines(originalNormalized);
330
327
  const echoRows = error.servedRows.length > 0
331
328
  ? error.servedRows
package/lib/mutation.js CHANGED
@@ -35,7 +35,7 @@ import { sessionKeyFor } from "./workspace-context.js";
35
35
  import { loadServed, loadServedCanons, loadEpochSnapshotId, loadRetiredAnchors, scanDrift, recordServedTruncated, } from "./session-view.js";
36
36
  import { abortIf, splitLines } from "./utils.js";
37
37
  import { applyOne } from "./mutation/engine.js";
38
- import { runFileEdits, resolveMissingPath, } from "./mutation/engine.js";
38
+ import { runFileEdits, resolveMissingPath } from "./mutation/engine.js";
39
39
  import { saveUndo } from "./undo-edit.js";
40
40
  import { restoreEndings } from "./edit-diff.js";
41
41
  import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-response.js";
@@ -79,9 +79,11 @@ export async function execPipeline(io, params, cwd, options) {
79
79
  curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
80
80
  }
81
81
  catch { }
82
- const strictPos = epochSnapshotId !== undefined && curSnapshotId !== undefined && epochSnapshotId !== curSnapshotId; // automatic: strict when epoch mismatch (conservative, future: changed∩[L,R] refined)
82
+ const strictPos = epochSnapshotId !== undefined &&
83
+ curSnapshotId !== undefined &&
84
+ epochSnapshotId !== curSnapshotId; // automatic: strict when epoch mismatch (conservative, future: changed∩[L,R] refined)
83
85
  const retiredPerSession = await loadRetiredAnchors(sessionKey, absolutePath);
84
- const policy = options?.noPersist === true ? 'preview' : 'live';
86
+ const policy = options?.noPersist === true ? "preview" : "live";
85
87
  const applied = await applyOne({
86
88
  content: originalNormalized,
87
89
  hashes: originalHashes,
@@ -103,8 +105,7 @@ export async function execPipeline(io, params, cwd, options) {
103
105
  strictPos,
104
106
  edit,
105
107
  }, async (error) => {
106
- if (error instanceof AnchorMismatchError ||
107
- error instanceof ServedRejectionError) {
108
+ if (error instanceof AnchorMismatchError || error instanceof ServedRejectionError) {
108
109
  await recordEchoServes(sessionKey, absolutePath, error.servedRows, policy, originalHashes.length);
109
110
  }
110
111
  throw error;
@@ -125,7 +126,7 @@ export async function execPipeline(io, params, cwd, options) {
125
126
  });
126
127
  }
127
128
  catch (error) {
128
- console.error('Failed to compute drift notice:', error);
129
+ console.error("Failed to compute drift notice:", error);
129
130
  }
130
131
  }
131
132
  return {
package/lib/prompts.js CHANGED
@@ -6,18 +6,19 @@
6
6
  * followed by tight bullets.
7
7
  * @module dsh-better-edit/prompts
8
8
  */
9
- export const EDIT_DESCRIPTION = "Edit a range of lines in a text file with `{ \"path\": path, \"edits\": [[remove_from, remove_to, replacement_text], ...] }`. " +
10
- "`path` is file path or null. `read` shows `HASH\u2502content` (e.g. `wUp\u2502 \"site\": {`) \u2014 use bare 3-char HASH anchors for " +
11
- "`remove_from`/`remove_to` (e.g. \"wUp\"), never `HASH\u2502content`. `replacement_text` is bare content, \\n joins lines, \"\" deletes. " +
12
- "Example: `{\"path\":\"a.py\",\"edits\":[[\"wUp\",\"AU6\",\"new\"]]}`. Edits are atomic; reuse `HASH\u2502content` from the diff after success. " +
9
+ export const EDIT_DESCRIPTION = 'Edit a range of lines in a text file with `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], ...] }` (tuple) or object `{remove_from, remove_to, replacement_text}` entries \u2014 mixed batches allowed. ' +
10
+ '`path` is file path or null. `read` shows `HASH\u2502content` (e.g. `wUp\u2502 "site": {`) \u2014 use bare 3-char HASH anchors for ' +
11
+ '`remove_from`/`remove_to` (e.g. "wUp"), never `HASH\u2502content`. `replacement_text` is bare content, \\n joins lines, "" deletes. ' +
12
+ 'Example: `{"path":"a.py","edits":[["wUp","AU6","new"]]}` (object form `{remove_from:"wUp",remove_to:"AU6",replacement_text:"new"}` equivalent). Edits are atomic; reuse `HASH\u2502content` from the diff after success. ' +
13
13
  "On failure follow the error hint: `[MODEL]` errors need a retry with fresh anchors, `[USER]` notices are human-only.";
14
14
  export const EDIT_GUIDANCE = {
15
- intro: "Edit a range of lines via a bare 3-char HASH anchor \u2014 payload is { path, edits: [[hash,hash,text]] } (single-file atomic, null path infers).",
15
+ intro: "Edit a range of lines via a bare 3-char HASH anchor \u2014 payload is { path, edits: [[hash,hash,text]] } or { path, edits: [{remove_from, remove_to, replacement_text}] } (single-file atomic, null path infers; tuple and object forms are equivalent, mixed batches allowed).",
16
16
  lines: [
17
- "`edit`: `HASH` vs `HASH\u2502content` \u2014 `HASH` is the bare 3-char (e.g. \"wUp\"), `HASH\u2502content` is the full line from `read`/`diff` (e.g. `wUp\u2502 \"site\": {`); never mix them.",
17
+ '`edit`: `HASH` vs `HASH\u2502content` \u2014 `HASH` is the bare 3-char (e.g. "wUp"), `HASH\u2502content` is the full line from `read`/`diff` (e.g. `wUp\u2502 "site": {`); never mix them.',
18
18
  "`edit`: get `remove_from`/`remove_to` by copying only the 3 chars before `\u2502` from `read` output \u2014 never include `\u2502` or content after it.",
19
- "`edit`: `replacement_text` is plain file content without `HASH\u2502` \u2014 e.g. \" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\" \u2014 never prefix lines with `HASH\u2502`.",
20
- "`edit`: every `\\n` in `replacement_text` separates lines; mirror trailing blank lines explicitly (use \"\" to delete a range).",
19
+ '`edit`: `replacement_text` is plain file content without `HASH\u2502` \u2014 e.g. " \\"site\\": {\\n \\"class\\": SiteScraper," \u2014 never prefix lines with `HASH\u2502`.',
20
+ '`edit`: every `\\n` in `replacement_text` separates lines; mirror trailing blank lines explicitly (use "" to delete a range).',
21
+ "`edit`: `edits` entries accept either tuple `[remove_from, remove_to, replacement_text]` or object `{remove_from, remove_to, replacement_text}` \u2014 mixed batches allowed, each entry normalizes independently; unknown fields (e.g. stray `path`) are rejected.",
21
22
  "`edit`: after a successful edit the returned diff shows fresh anchors (`HASH\u2502content`) \u2014 copy new `HASH` values from there for the next edit; no need to re-read.",
22
23
  "`edit`: `remove_from`/`remove_to` are inclusive; batch multiple edits to the same file only when independent \u2014 they apply atomically (fail \u2192 nothing written).",
23
24
  "`edit`: `[MODEL]` errors (e.g. `E_STALE_*`, `E_UNSERVED_*`, `E_BAD_PAYLOAD`, `E_SERVED_ECHO`) need a retry \u2014 `[USER]` warnings/`drift:` notices are human-only.",
@@ -50,10 +50,17 @@ export async function readAndServe(io, rawPath, cwd, options) {
50
50
  if (filteredHashes.length > 0) {
51
51
  // Reconstruct previous content from canons — canon is idempotent and whitespace-insensitive (ADR-0002: canon strips ASCII whitespace, so "a b" and "a b" share canon and hash). Joining filteredCanons preserves reuse correctness for mapStableHashes nearest-canon matching; byte-fidelity of whitespace is not required for anchor stability, only canon equality.
52
52
  const prevContent = filteredCanons.join("\n");
53
- previous = { content: prevContent, hashes: filteredHashes, removedHashes: new Set(retiredHashes) };
53
+ previous = {
54
+ content: prevContent,
55
+ hashes: filteredHashes,
56
+ removedHashes: new Set(retiredHashes),
57
+ };
54
58
  }
55
59
  }
56
- let reservedHashes = new Set([...retiredHashes, ...servedForNorm.filter((h) => h !== null)]);
60
+ let reservedHashes = new Set([
61
+ ...retiredHashes,
62
+ ...servedForNorm.filter((h) => h !== null),
63
+ ]);
57
64
  let reservations = { reservedHashes, retiredHashes };
58
65
  let promotionWarning;
59
66
  let view;
@@ -69,7 +76,8 @@ export async function readAndServe(io, rawPath, cwd, options) {
69
76
  });
70
77
  }
71
78
  catch (e) {
72
- if (e instanceof AnchorSpaceExhaustedError || (e instanceof Error && e.message.includes("E_ANCHOR_SPACE_EXHAUSTED"))) {
79
+ if (e instanceof AnchorSpaceExhaustedError ||
80
+ (e instanceof Error && e.message.includes("E_ANCHOR_SPACE_EXHAUSTED"))) {
73
81
  const retiredCount = retiredHashes.size;
74
82
  const servedCount = servedForNorm.filter((h) => h !== null).length;
75
83
  const reservedCount = retiredCount + servedCount;
@@ -127,17 +135,20 @@ export async function readAndServe(io, rawPath, cwd, options) {
127
135
  // #69: epoch lifecycle belongs to full reads — a partial (paged or
128
136
  // truncated) read merges window rows only and must not clear the
129
137
  // drift-reported marks; only a full read resets them.
130
- const isFullRead = options.offset === undefined &&
131
- options.limit === undefined &&
132
- !view.truncation?.truncated;
138
+ const isFullRead = options.offset === undefined && options.limit === undefined && !view.truncation?.truncated;
133
139
  if (isFullRead)
134
140
  await clearDriftReported(sessionKey, view.absolutePath);
135
- const autoFooter = getAutoGuessFooter(view.absolutePath) ?? getAutoGuessFooter(rawPath) ?? getAutoGuessFooter(view.absolutePath.replace(/\\/g, "/")) ?? "";
141
+ const autoFooter = getAutoGuessFooter(view.absolutePath) ??
142
+ getAutoGuessFooter(rawPath) ??
143
+ getAutoGuessFooter(view.absolutePath.replace(/\\/g, "/")) ??
144
+ "";
136
145
  const autoWarning = autoFooter || undefined;
137
- const warning = promotionWarning ? (autoWarning ? `${promotionWarning}\n${autoWarning}` : promotionWarning) : autoWarning;
138
- const text = view.hadUtf8DecodeErrors
139
- ? `${view.text}\n\n${UTF8_REWRITE_NOTE}`
140
- : view.text;
146
+ const warning = promotionWarning
147
+ ? autoWarning
148
+ ? `${promotionWarning}\n${autoWarning}`
149
+ : promotionWarning
150
+ : autoWarning;
151
+ const text = view.hadUtf8DecodeErrors ? `${view.text}\n\n${UTF8_REWRITE_NOTE}` : view.text;
141
152
  return {
142
153
  text,
143
154
  served: view.served,
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Shared output-render seam for the `{ text, warning? }` tool payload.
3
+ *
4
+ * `read` (tool-read.ts) and `str_replace_editor` view (tool-str-replace-editor.ts)
5
+ * previously carried verbatim copies of this render closure, so a warning-format
6
+ * change had to be made in two places (report #7). Both now delegate here.
7
+ * @module dsh-better-edit/render-text-warning
8
+ */
9
+ /**
10
+ * Render a `{ text, warning? }` payload (or bare string) as content blocks:
11
+ * string input yields a single text block, object input yields the text block
12
+ * plus a second block when `warning` is present.
13
+ */
14
+ export function renderTextWarning(value) {
15
+ if (typeof value === "string")
16
+ return [{ type: "text", text: value }];
17
+ const blocks = [{ type: "text", text: value.text }];
18
+ if (value.warning)
19
+ blocks.push({ type: "text", text: value.warning });
20
+ return blocks;
21
+ }
package/lib/sandbox.js CHANGED
@@ -27,9 +27,7 @@ export class FsSandboxController {
27
27
  const defaultMode = ctx.fs.sandboxMode;
28
28
  this.escalationModes = defaultMode === undefined ? [] : ESCALATION_TARGETS;
29
29
  this.policy =
30
- defaultMode === undefined
31
- ? undefined
32
- : ctx.get("sandboxPolicy");
30
+ defaultMode === undefined ? undefined : ctx.get("sandboxPolicy");
33
31
  if (defaultMode !== undefined && this.policy === undefined) {
34
32
  throw new Error("dsh-better-edit: the mounted filesystem confines but ctx.sandboxPolicy is missing");
35
33
  }
@@ -72,8 +70,7 @@ export class FsSandboxController {
72
70
  const standingPolicy = this.policy?.resolve({
73
71
  ...(exec.agent ? { session: exec.agent.session } : {}),
74
72
  });
75
- if (args.sandbox_permissions === undefined ||
76
- args.justification === undefined) {
73
+ if (args.sandbox_permissions === undefined || args.justification === undefined) {
77
74
  return standingPolicy;
78
75
  }
79
76
  if (this.escalationModes.length === 0) {
package/lib/self-heal.js CHANGED
@@ -6,24 +6,30 @@
6
6
  * @module dsh-better-edit/self-heal
7
7
  */
8
8
  export function createSelfHealWatcher(options) {
9
- const { agentId, rootCtx, agent, agentCtx, toolsSvc, hashReadDef, hashEditDef, healMinIntervalMs = 1000, } = options;
9
+ const { agentId, rootCtx, agent, agentCtx, toolsSvc, hashReadDef, hashEditDef, hashStrReplaceDef, healMinIntervalMs = 1000, } = options;
10
+ const watchStrReplace = hashStrReplaceDef !== undefined;
10
11
  let lastHealAt = 0;
11
12
  let healCount = 0;
12
13
  let selfHealDisabled = false;
14
+ const formatFailMsg = (error) => `dsh-better-edit: self-heal failed for agent ${agentId}: ${error instanceof Error ? error.message : String(error)} \u2014 see Rianico/dsh-better-edit#43`;
15
+ const formatRestoredMsg = (toolLabel, attempt) => `dsh-better-edit: restored ${toolLabel} after external takeover \u2014 agent ${agentId} (${attempt}/2) \u2014 see Rianico/dsh-better-edit#43`;
13
16
  const stop = agentCtx.on("tools/change", () => {
14
17
  try {
15
18
  if (selfHealDisabled)
16
19
  return;
17
20
  // SAFETY: toolsSvc is the DSH tools service — shape is `layers.scoped: Map<agent, {tools}>` per cordis internals; narrow at boundary
18
- const layer = toolsSvc
19
- ?.layers?.scoped?.get?.(agent)?.tools;
21
+ const layer = toolsSvc?.layers?.scoped?.get?.(agent)?.tools;
20
22
  if (!layer)
21
23
  return;
22
24
  const currentRead = layer?.get?.("read") ?? layer?.data?.get?.("read");
23
25
  const currentEdit = layer?.get?.("edit") ?? layer?.data?.get?.("edit");
24
26
  const readOk = currentRead === hashReadDef;
25
27
  const editOk = currentEdit === hashEditDef;
26
- if (readOk && editOk)
28
+ const currentStrReplace = watchStrReplace
29
+ ? (layer?.get?.("str_replace_editor") ?? layer?.data?.get?.("str_replace_editor"))
30
+ : hashStrReplaceDef;
31
+ const strReplaceOk = !watchStrReplace || currentStrReplace === hashStrReplaceDef;
32
+ if (readOk && editOk && strReplaceOk)
27
33
  return;
28
34
  const now = Date.now();
29
35
  if (now - lastHealAt < healMinIntervalMs)
@@ -42,55 +48,52 @@ export function createSelfHealWatcher(options) {
42
48
  lastHealAt = now;
43
49
  const restoreRead = !readOk;
44
50
  const restoreEdit = !editOk;
51
+ const restoreStrReplace = watchStrReplace && !strReplaceOk;
45
52
  const restoreCount = healCount;
46
53
  queueMicrotask(() => {
47
54
  try {
48
55
  // SAFETY: re-read layer inside microtask — same shape as above
49
- const currentLayer = toolsSvc
50
- ?.layers?.scoped?.get?.(agent)?.tools;
56
+ const currentLayer = toolsSvc?.layers?.scoped?.get?.(agent)?.tools;
51
57
  if (!currentLayer)
52
58
  return;
53
- if (restoreEdit) {
59
+ const restoreTool = (name, def, toolLabel) => {
54
60
  try {
55
- currentLayer?.data?.delete?.("edit");
61
+ currentLayer?.data?.delete?.(name);
56
62
  }
57
63
  catch {
58
64
  // ignore — best-effort delete of intruding entry
59
65
  }
60
66
  try {
61
- agentCtx.tools.register(hashEditDef);
67
+ agentCtx.tools.register(def);
62
68
  }
63
69
  catch (e) {
64
- rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${e instanceof Error ? e.message : String(e)} \u2014 see Rianico/dsh-better-edit#43`);
65
- return;
70
+ rootCtx.logger.warn(formatFailMsg(e));
71
+ return false;
66
72
  }
67
- rootCtx.logger.warn(`dsh-better-edit: restored hash-anchored edit after external takeover \u2014 agent ${agentId} (${restoreCount}/2) \u2014 see Rianico/dsh-better-edit#43`);
73
+ rootCtx.logger.warn(formatRestoredMsg(toolLabel, restoreCount));
74
+ return true;
75
+ };
76
+ if (restoreEdit) {
77
+ if (!restoreTool("edit", hashEditDef, "hash-anchored edit"))
78
+ return;
79
+ }
80
+ if (restoreStrReplace) {
81
+ if (!restoreTool("str_replace_editor", hashStrReplaceDef, "governed str_replace_editor"))
82
+ return;
68
83
  }
69
84
  if (restoreRead) {
70
- try {
71
- currentLayer?.data?.delete?.("read");
72
- }
73
- catch {
74
- // ignore — best-effort delete of intruding entry
75
- }
76
- try {
77
- agentCtx.tools.register(hashReadDef);
78
- }
79
- catch (e) {
80
- rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${e instanceof Error ? e.message : String(e)} \u2014 see Rianico/dsh-better-edit#43`);
85
+ if (!restoreTool("read", hashReadDef, "hash-anchored read"))
81
86
  return;
82
- }
83
- rootCtx.logger.warn(`dsh-better-edit: restored hash-anchored read after external takeover \u2014 agent ${agentId} (${restoreCount}/2) \u2014 see Rianico/dsh-better-edit#43`);
84
87
  }
85
88
  }
86
89
  catch (error) {
87
- rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${error instanceof Error ? error.message : String(error)} \u2014 see Rianico/dsh-better-edit#43`);
90
+ rootCtx.logger.warn(formatFailMsg(error));
88
91
  }
89
92
  });
90
93
  }
91
94
  catch (error) {
92
95
  try {
93
- rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${error instanceof Error ? error.message : String(error)} \u2014 see Rianico/dsh-better-edit#43`);
96
+ rootCtx.logger.warn(formatFailMsg(error));
94
97
  }
95
98
  catch {
96
99
  // ignore — logger may throw in mock
@@ -273,7 +273,11 @@ export async function recordServedTruncated(sessionKey, path, rows, lineCount, c
273
273
  rowCanon.set(row.position, fullCanons[row.position] ?? null);
274
274
  const updatedCanons = [];
275
275
  for (let i = 0; i < updated.length; i++) {
276
- updatedCanons.push(updated[i] === null ? null : rowCanon.has(i) ? rowCanon.get(i) : (currentCanons[i] ?? null));
276
+ updatedCanons.push(updated[i] === null
277
+ ? null
278
+ : rowCanon.has(i)
279
+ ? rowCanon.get(i)
280
+ : (currentCanons[i] ?? null));
277
281
  }
278
282
  store.upsertServedCanons(sessionKey, path, JSON.stringify(updatedCanons));
279
283
  }