dsh-better-edit 0.6.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +59 -15
  2. package/README.md +78 -71
  3. package/README.zh.md +83 -83
  4. package/lib/canonical-path.js +4 -1
  5. package/lib/constants.js +5 -1
  6. package/lib/contract.js +127 -33
  7. package/lib/edit-diff.js +1 -5
  8. package/lib/edit-response.js +5 -10
  9. package/lib/encoding.js +23 -6
  10. package/lib/file-encoding-state.js +54 -15
  11. package/lib/file-view.js +42 -53
  12. package/lib/fs-bridge.js +27 -16
  13. package/lib/fs-write.js +1 -1
  14. package/lib/guidance/materialize.js +1 -6
  15. package/lib/guidance/resolve.js +1 -1
  16. package/lib/hash-store.js +133 -43
  17. package/lib/hashline/anchor-pipeline.js +124 -93
  18. package/lib/hashline/hash-assign.js +65 -23
  19. package/lib/hashline/hash.js +6 -6
  20. package/lib/index.js +6 -0
  21. package/lib/mutation/engine.js +89 -31
  22. package/lib/mutation.js +14 -13
  23. package/lib/prompts.js +12 -11
  24. package/lib/read-and-serve.js +105 -19
  25. package/lib/render-text-warning.js +21 -0
  26. package/lib/sandbox.js +2 -5
  27. package/lib/self-heal.js +30 -27
  28. package/lib/session-view.js +161 -24
  29. package/lib/store-config.js +7 -2
  30. package/lib/store-lifecycle.js +7 -2
  31. package/lib/tool-edit.js +10 -6
  32. package/lib/tool-read.js +6 -9
  33. package/lib/tool-str-replace-editor.js +274 -0
  34. package/lib/tool-undo.js +8 -9
  35. package/lib/types/constants.d.ts +2 -0
  36. package/lib/types/contract.d.ts +106 -18
  37. package/lib/types/edit-response.d.ts +4 -0
  38. package/lib/types/encoding.d.ts +1 -1
  39. package/lib/types/file-encoding-state.d.ts +4 -1
  40. package/lib/types/file-view.d.ts +16 -1
  41. package/lib/types/hash-store.d.ts +12 -1
  42. package/lib/types/hashline/anchor-pipeline.d.ts +16 -6
  43. package/lib/types/hashline/hash-assign.d.ts +10 -2
  44. package/lib/types/hashline/index.d.ts +1 -1
  45. package/lib/types/mutation/engine.d.ts +2 -1
  46. package/lib/types/render-text-warning.d.ts +22 -0
  47. package/lib/types/self-heal.d.ts +2 -0
  48. package/lib/types/session-view.d.ts +13 -4
  49. package/lib/types/tool-str-replace-editor.d.ts +27 -0
  50. package/lib/types/undo-edit.d.ts +1 -1
  51. package/lib/types/utils.d.ts +7 -0
  52. package/lib/types/write-hook.d.ts +2 -2
  53. package/lib/undo-edit.js +6 -8
  54. package/lib/utils.js +23 -3
  55. package/lib/workspace-context.js +1 -1
  56. package/lib/write-hook.js +20 -23
  57. package/package.json +63 -57
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
@@ -21,7 +21,7 @@
21
21
  *
22
22
  * @module dsh-better-edit/session-view
23
23
  */
24
- import { HASH_RE } from "./hashline/hash-assign.js";
24
+ import { HASH_RE, canon } from "./hashline/hash-assign.js";
25
25
  import { loadHashStore, loadServedStore, withStore, } from "./hash-store.js";
26
26
  import { SERVED_ECHO_CAP } from "./constants.js";
27
27
  import { fmtServedRows } from "./hashline/anchor-pipeline.js";
@@ -92,9 +92,9 @@ export async function loadServed(sessionKey, path) {
92
92
  return store.getServed(sessionKey, path);
93
93
  }
94
94
  /** Anchors that must not be allocated while any session can still remember them. */
95
- export async function loadAnchorReservations(path) {
95
+ export async function loadAnchorReservations(sessionKey, path) {
96
96
  const store = await loadServedStore();
97
- return store.getAnchorReservations(path);
97
+ return store.getAnchorReservations(sessionKey, path);
98
98
  }
99
99
  export async function loadServedCanons(sessionKey, path) {
100
100
  const store = await loadServedStore();
@@ -119,12 +119,74 @@ function addRetiredAnchors(store, sessionKey, path, hashes) {
119
119
  }
120
120
  retired.add(hash);
121
121
  }
122
+ // Persist as legacy string array for backward compat; new entries with deathPos use object form via addRetiredEntries
122
123
  store.upsertRetiredAnchors(sessionKey, path, JSON.stringify([...retired]));
123
124
  }
125
+ function addRetiredEntries(store, sessionKey, path, entries) {
126
+ if (entries.length === 0)
127
+ return;
128
+ const existing = store.getRetiredEntries(sessionKey, path);
129
+ const seen = new Set(existing.map((e) => e.hash));
130
+ for (const e of entries) {
131
+ if (!HASH_RE.test(e.hash))
132
+ throw new TypeError(`Invalid retired hash: ${e.hash}`);
133
+ if (!seen.has(e.hash)) {
134
+ existing.push(e);
135
+ seen.add(e.hash);
136
+ }
137
+ }
138
+ store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(existing));
139
+ }
124
140
  function displacedHashes(current, updated) {
125
141
  const remaining = new Set(updated.filter((hash) => hash !== null));
126
142
  return new Set(current.filter((hash) => hash !== null && !remaining.has(hash)));
127
143
  }
144
+ function displacedEntries(current, updated) {
145
+ const remaining = new Set(updated.filter((hash) => hash !== null));
146
+ const entries = [];
147
+ for (let i = 0; i < current.length; i++) {
148
+ const h = current[i];
149
+ if (h !== null && !remaining.has(h)) {
150
+ entries.push({ hash: h, deathPos: i });
151
+ }
152
+ }
153
+ return entries;
154
+ }
155
+ // deathPos=null = legacy/unknown position (pre-GC String[] format or migration).
156
+ // These entries are NOT swept incrementally — retained until full-recordServed (isFullRead) or major-GC promotion clears retired.
157
+ // Incremental hazard sweep only frees deathPos (number) whose card was re-observed; null survives partial sweeps by design (minor leak documented here) and is drained only on epoch promotion/full read.
158
+ function sweepRetiredByPositions(store, sessionKey, path, servedPositions) {
159
+ if (servedPositions.size === 0)
160
+ return;
161
+ const entries = store.getRetiredEntries(sessionKey, path);
162
+ if (entries.length === 0)
163
+ return;
164
+ const filtered = entries.filter((e) => e.deathPos === null || !servedPositions.has(e.deathPos));
165
+ if (filtered.length !== entries.length) {
166
+ store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(filtered));
167
+ }
168
+ }
169
+ function sweepAndRetire(store, sessionKey, path, current, updated, rows) {
170
+ const servedPositions = new Set(rows.map((r) => r.position));
171
+ const existingCards = store.getCards(sessionKey, path);
172
+ let cardsChanged = false;
173
+ for (const pos of servedPositions)
174
+ if (!existingCards.has(pos)) {
175
+ existingCards.add(pos);
176
+ cardsChanged = true;
177
+ }
178
+ if (cardsChanged)
179
+ store.upsertCards(sessionKey, path, JSON.stringify([...existingCards]));
180
+ const existingEntries = store.getRetiredEntries(sessionKey, path);
181
+ const displaced = displacedEntries(current, updated);
182
+ const existingHashes = new Set(existingEntries.map((e) => e.hash));
183
+ const filteredDisplaced = displaced.filter((e) => !existingHashes.has(e.hash));
184
+ const afterSweep = existingEntries.filter((e) => e.deathPos === null || !existingCards.has(e.deathPos));
185
+ const merged = [...afterSweep, ...filteredDisplaced];
186
+ if (merged.length !== existingEntries.length || filteredDisplaced.length > 0 || cardsChanged) {
187
+ store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(merged));
188
+ }
189
+ }
128
190
  /** Keep freed anchors dead for this session until it has seen the whole file again. */
129
191
  export async function retireAnchors(sessionKey, path, hashes) {
130
192
  const additions = [...hashes];
@@ -135,14 +197,14 @@ export async function retireAnchors(sessionKey, path, hashes) {
135
197
  addRetiredAnchors(store, sessionKey, path, additions);
136
198
  });
137
199
  }
138
- export async function recordServed(sessionKey, path, rows, lineCount, fullReadHashes, fullReadCanons, fullReadSnapshotId) {
200
+ export async function recordServed(sessionKey, path, rows, lineCount, full) {
139
201
  if (rows.length === 0)
140
202
  return;
141
203
  try {
142
204
  const store = await loadServedStore();
143
- const isFullRead = fullReadHashes !== undefined &&
144
- rows.length === fullReadHashes.length &&
145
- rows.every((row, index) => row.position === index && row.hash === fullReadHashes[index]);
205
+ const isFullRead = full !== undefined &&
206
+ rows.length === full.hashes.length &&
207
+ rows.every((row, index) => row.position === index && row.hash === full.hashes[index]);
146
208
  withStore(() => {
147
209
  const current = store.getServed(sessionKey, path);
148
210
  const updated = _mergeServedRows(current, rows, lineCount === undefined ? undefined : { truncateTo: lineCount });
@@ -151,20 +213,21 @@ export async function recordServed(sessionKey, path, rows, lineCount, fullReadHa
151
213
  }
152
214
  if (isFullRead) {
153
215
  store.clearRetiredAnchors(sessionKey, path);
154
- if (fullReadCanons)
155
- store.upsertServedCanons(sessionKey, path, JSON.stringify(fullReadCanons));
156
- if (fullReadSnapshotId)
157
- store.upsertEpochSnapshotId(sessionKey, path, fullReadSnapshotId);
216
+ store.clearCards(sessionKey, path);
217
+ if (full?.canons)
218
+ store.upsertServedCanons(sessionKey, path, JSON.stringify(full.canons));
219
+ if (full?.snapshotId)
220
+ store.upsertEpochSnapshotId(sessionKey, path, full.snapshotId);
158
221
  }
159
222
  else {
160
223
  // For partial reads, update canons for the served rows via hash-to-canon map (robust for partial views)
161
- if (fullReadCanons && fullReadHashes) {
224
+ if (full?.canons && full.hashes) {
162
225
  const canonByHash = new Map();
163
- for (let i = 0; i < fullReadHashes.length; i++) {
164
- const h = fullReadHashes[i];
165
- const c = fullReadCanons[i] ?? null;
166
- if (h)
167
- canonByHash.set(h, c);
226
+ for (let i = 0; i < full.hashes.length; i++) {
227
+ const lineHash = full.hashes[i];
228
+ const lineCanon = full.canons[i] ?? null;
229
+ if (lineHash)
230
+ canonByHash.set(lineHash, lineCanon);
168
231
  }
169
232
  const currentCanons = store.getServedCanons(sessionKey, path);
170
233
  const updatedCanons = currentCanons.slice();
@@ -180,9 +243,7 @@ export async function recordServed(sessionKey, path, rows, lineCount, fullReadHa
180
243
  updatedCanons.pop();
181
244
  store.upsertServedCanons(sessionKey, path, JSON.stringify(updatedCanons));
182
245
  }
183
- if (fullReadSnapshotId)
184
- store.upsertEpochSnapshotId(sessionKey, path, fullReadSnapshotId);
185
- addRetiredAnchors(store, sessionKey, path, displacedHashes(current, updated));
246
+ sweepAndRetire(store, sessionKey, path, current, updated, rows);
186
247
  }
187
248
  });
188
249
  }
@@ -190,7 +251,7 @@ export async function recordServed(sessionKey, path, rows, lineCount, fullReadHa
190
251
  console.error("Failed to record served rows:", error);
191
252
  }
192
253
  }
193
- export async function recordServedTruncated(sessionKey, path, rows, lineCount, clearFrom = 0) {
254
+ export async function recordServedTruncated(sessionKey, path, rows, lineCount, clearFrom = 0, fullCanons) {
194
255
  if (rows.length === 0)
195
256
  return;
196
257
  try {
@@ -201,7 +262,26 @@ export async function recordServedTruncated(sessionKey, path, rows, lineCount, c
201
262
  if (current.length !== updated.length || current.some((v, i) => v !== updated[i])) {
202
263
  store.upsertServed(sessionKey, path, JSON.stringify(updated));
203
264
  }
204
- addRetiredAnchors(store, sessionKey, path, displacedHashes(current, updated));
265
+ if (fullCanons) {
266
+ // #53: hashes without fresh canons leave the verify collision-guard
267
+ // comparing live content against stale metadata (false E_STALE_RANGE).
268
+ // Refresh canons for recorded rows; null where served is null so the
269
+ // parallel arrays stay consistent (canon null <=> served null).
270
+ const currentCanons = store.getServedCanons(sessionKey, path);
271
+ const rowCanon = new Map();
272
+ for (const row of rows)
273
+ rowCanon.set(row.position, fullCanons[row.position] ?? null);
274
+ const updatedCanons = [];
275
+ for (let i = 0; i < updated.length; i++) {
276
+ updatedCanons.push(updated[i] === null
277
+ ? null
278
+ : rowCanon.has(i)
279
+ ? rowCanon.get(i)
280
+ : (currentCanons[i] ?? null));
281
+ }
282
+ store.upsertServedCanons(sessionKey, path, JSON.stringify(updatedCanons));
283
+ }
284
+ sweepAndRetire(store, sessionKey, path, current, updated, rows);
205
285
  });
206
286
  }
207
287
  catch (error) {
@@ -288,7 +368,60 @@ export function currentPositionOfDrifted(served, currentPositions, surviving, se
288
368
  return currentPositions.get(served[above]) - 1;
289
369
  return servedIndex + delta;
290
370
  }
291
- export const DRIFT_NOTICE_HEADING = "drift:";
371
+ export const DRIFT_NOTICE_HEADING = "[USER] drift:";
372
+ /**
373
+ * WHY (#68 hash-rotation vs content loss): probing + retired growth reassign
374
+ * distinct hashes to identical duplicate lines across sequential edits, so a
375
+ * served hash missing from the result set may still survive under a fresh hash.
376
+ * Suppress those by consuming one matching canon outside the edited span;
377
+ * report only true canon deficit. Whitespace-only reformats stay silent
378
+ * (canon strips ASCII whitespace, ADR-0002). Absent/empty servedCanons keeps
379
+ * legacy hash-equality.
380
+ */
381
+ function buildRotatedSurvivorCheck(input, rangeFrom, rangeTo, delta) {
382
+ const canons = input.servedCanons;
383
+ if (!canons || !canons.some((c) => c !== null))
384
+ return () => false;
385
+ // Edited served interval mapped to result coordinates (single range).
386
+ const spanFrom = Math.max(0, rangeFrom);
387
+ const spanTo = Math.max(spanFrom - 1, rangeTo + delta);
388
+ const remaining = new Map();
389
+ for (let i = 0; i < input.resultLines.length; i++) {
390
+ if (i >= spanFrom && i <= spanTo)
391
+ continue;
392
+ const c = canon(input.resultLines[i] ?? "");
393
+ remaining.set(c, (remaining.get(c) ?? 0) + 1);
394
+ }
395
+ const take = (c) => {
396
+ const left = remaining.get(c) ?? 0;
397
+ if (left <= 0)
398
+ return false;
399
+ remaining.set(c, left - 1);
400
+ return true;
401
+ };
402
+ // Pre-consume: served lines that survived under their own hash already
403
+ // account for their result content, so a deleted duplicate is not masked
404
+ // by a surviving twin (multiset difference, not per-hash presence).
405
+ const currentPosOfHash = new Map();
406
+ for (let i = 0; i < input.resultHashes.length; i++) {
407
+ currentPosOfHash.set(input.resultHashes[i], i);
408
+ }
409
+ for (let p = 0; p < input.served.length; p++) {
410
+ const h = input.served[p];
411
+ if (h === null || (p >= rangeFrom && p <= rangeTo))
412
+ continue;
413
+ const currentPos = currentPosOfHash.get(h);
414
+ if (currentPos === undefined)
415
+ continue;
416
+ take(canon(input.resultLines[currentPos] ?? ""));
417
+ }
418
+ return (servedPos) => {
419
+ const c = canons[servedPos] ?? null;
420
+ if (c === null)
421
+ return false;
422
+ return take(c);
423
+ };
424
+ }
292
425
  export function computeDrift(input) {
293
426
  const { served, resultHashes, resultLines, range, reported, cap = SERVED_ECHO_CAP } = input;
294
427
  const resultHashSet = new Set(resultHashes);
@@ -310,6 +443,7 @@ export function computeDrift(input) {
310
443
  }
311
444
  const rangeFrom = Math.min(servedStartIdx, servedEndIdx);
312
445
  const rangeTo = Math.max(servedStartIdx, servedEndIdx);
446
+ const isRotatedSurvivor = buildRotatedSurvivorCheck(input, rangeFrom, rangeTo, range.delta);
313
447
  let total = 0;
314
448
  let unshown = 0;
315
449
  let anyNotReported = false;
@@ -322,6 +456,8 @@ export function computeDrift(input) {
322
456
  continue;
323
457
  if (resultHashSet.has(servedHash))
324
458
  continue;
459
+ if (isRotatedSurvivor(p))
460
+ continue;
325
461
  total++;
326
462
  if (!reported.has(servedHash))
327
463
  anyNotReported = true;
@@ -372,7 +508,8 @@ export function computeDrift(input) {
372
508
  }
373
509
  export async function scanDrift(input) {
374
510
  const reported = await driftReported(input.sessionKey, input.path);
375
- const result = computeDrift({ ...input, reported });
511
+ const servedCanons = await loadServedCanons(input.sessionKey, input.path);
512
+ const result = computeDrift({ ...input, reported, servedCanons });
376
513
  if (!result || result.allAlreadyReported)
377
514
  return result?.text;
378
515
  await recordServed(input.sessionKey, input.path, result.rows.map((row) => ({ position: row.position, hash: row.hash })), input.resultLines.length);
@@ -76,7 +76,10 @@ function parseAutoGitIgnoreRaw(v) {
76
76
  }
77
77
  function parseSupportedEncodingsRaw(v) {
78
78
  const inner = v.trim().replace(/^\[/, "").replace(/\]$/, "");
79
- const items = inner.split(/[ ,;]+/).map((s) => s.trim().toLowerCase()).filter((s) => s.length > 0);
79
+ const items = inner
80
+ .split(/[ ,;]+/)
81
+ .map((s) => s.trim().toLowerCase())
82
+ .filter((s) => s.length > 0);
80
83
  if (items.length === 0)
81
84
  return undefined;
82
85
  return items;
@@ -90,7 +93,9 @@ const StoreConfigSchema = z.object({
90
93
  autoGitignore: z.boolean().default(false), // workspace only: auto-append ".dsh_better_edit/" to .gitignore when .git exists but entry missing (false = warn once)
91
94
  autoGuessEncoding: z.boolean().default(false), // VS Code files.autoGuessEncoding — deterministic BOM→UTF-8 first, model-assisted top-3 only when true
92
95
  normalizeToUtf8: z.boolean().default(false), // when true, legacy files (GBK etc.) migrate to UTF-8 on first edit/write
93
- supportedEncodings: z.array(z.string()).default(["gbk", "big5", "shift_jis", "euc-kr", "windows-1251", "iso-8859-1"]),
96
+ supportedEncodings: z
97
+ .array(z.string())
98
+ .default(["gbk", "big5", "shift_jis", "euc-kr", "windows-1251", "iso-8859-1"]),
94
99
  undo_ttl_s: z.number().int().min(-1).default(604800), // undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)
95
100
  storeMaxAgeS: z.number().int().min(1).default(2592000), // central janitor: max idle age in seconds before evicting runtime/<name>-<hash8>/ (default 2592000 = 30 days)
96
101
  storeMaxTotalBytes: z.number().int().min(0).default(524288000), // central janitor: max total bytes under runtime/ before LRU eviction (default 524288000 = 500 MB)
@@ -37,7 +37,7 @@ function gitignoreHasEntry(ws) {
37
37
  const content = readFileSync(join(ws, ".gitignore"), "utf-8");
38
38
  return content.split("\n").some((l) => {
39
39
  const t = l.trim();
40
- return t === ".dsh_better_edit" || t === ".dsh_better_edit/" || t.startsWith(".dsh_better_edit/");
40
+ return (t === ".dsh_better_edit" || t === ".dsh_better_edit/" || t.startsWith(".dsh_better_edit/"));
41
41
  });
42
42
  }
43
43
  catch {
@@ -134,7 +134,12 @@ export async function runCentralJanitorIfDue() {
134
134
  if (!st.isDirectory())
135
135
  continue;
136
136
  let totalBytes = 0;
137
- for (const file of ["hash-store.sqlite", "hash-store.sqlite-wal", "hash-store.sqlite-shm", ".wsPath"]) {
137
+ for (const file of [
138
+ "hash-store.sqlite",
139
+ "hash-store.sqlite-wal",
140
+ "hash-store.sqlite-shm",
141
+ ".wsPath",
142
+ ]) {
138
143
  try {
139
144
  totalBytes += (await stat(join(dir, file))).size;
140
145
  }
package/lib/tool-edit.js CHANGED
@@ -6,10 +6,11 @@
6
6
  * @module dsh-better-edit/tool-edit
7
7
  */
8
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
- import { normalizeRequest as normReq, assertEditRequest, } from "./contract.js";
9
+ import { normalizeRequest as normReq, assertEditRequest } from "./contract.js";
10
10
  import { abortIf } from "./utils.js";
11
11
  import { execute } from "./mutation.js";
12
12
  import { EDIT_DESCRIPTION } from "./prompts.js";
13
+ import { codeOf } from "./utils.js";
13
14
  import { execCwd, execSessionKey } from "./workspace-context.js";
14
15
  import { withWorkspace } from "./workspace-context.js";
15
16
  import { findSnapshotPathsByHashes } from "./hash-store.js";
@@ -25,15 +26,15 @@ async function resolveNullPath(edits) {
25
26
  if (matches.length === 1) {
26
27
  return {
27
28
  path: matches[0],
28
- warning: `[E_BAD_SHAPE] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
29
+ warning: `[MODEL] [E_BAD_PAYLOAD] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
29
30
  };
30
31
  }
31
32
  if (matches.length > 1) {
32
- 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.`);
33
+ 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.`);
33
34
  }
34
35
  }
35
36
  catch (e) {
36
- if (e instanceof Error && e.message.startsWith("[E_BAD_SHAPE]"))
37
+ if (codeOf(e) === "E_BAD_PAYLOAD")
37
38
  throw e;
38
39
  return undefined;
39
40
  }
@@ -53,7 +54,10 @@ export function buildEditTool(io, sandbox) {
53
54
  edits: {
54
55
  type: "array",
55
56
  description: "Ordered list of edit tuples [remove_from, remove_to, replacement_text] — one edit per tuple, single-file atomic",
56
- items: { type: "json", description: "[remove_from, remove_to, replacement_text]" },
57
+ items: {
58
+ type: "json",
59
+ description: "[remove_from, remove_to, replacement_text]",
60
+ },
57
61
  },
58
62
  ...(sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}),
59
63
  },
@@ -78,7 +82,7 @@ export function buildEditTool(io, sandbox) {
78
82
  pathWarning = resolved.warning;
79
83
  }
80
84
  else {
81
- throw new Error("[E_BAD_SHAPE] Edit request path is null and could not be inferred from anchors — anchors match no known file. Include the intended path.");
85
+ throw new Error("[MODEL] [E_BAD_PAYLOAD] Edit request path is null and could not be inferred from anchors — anchors match no known file. Include the intended path.");
82
86
  }
83
87
  }
84
88
  const sandboxPolicy = await sandbox.resolvePolicy("edit", { path: resolvedPath, edits: req.edits }, exec);
package/lib/tool-read.js CHANGED
@@ -10,6 +10,7 @@ import { normalizeRequest as normReq, assertReadRequest, pathSchema } from "./co
10
10
  import { readAndServe } from "./read-and-serve.js";
11
11
  import { READ_DESCRIPTION } from "./prompts.js";
12
12
  import { normalizeEncoding } from "./encoding.js";
13
+ import { renderTextWarning } from "./render-text-warning.js";
13
14
  import { execCwd, execSessionKey } from "./workspace-context.js";
14
15
  import { withWorkspace } from "./workspace-context.js";
15
16
  /**
@@ -39,16 +40,12 @@ export function buildReadTool(io) {
39
40
  },
40
41
  },
41
42
  output: {
42
- schema: { type: "object", properties: { text: { type: "string", required: true }, warning: { type: "string" } }, additionalProperties: false },
43
- render: (_args, value) => {
44
- const v = value;
45
- if (typeof v === "string")
46
- return [{ type: "text", text: v }];
47
- const blocks = [{ type: "text", text: v.text }];
48
- if (v.warning)
49
- blocks.push({ type: "text", text: v.warning });
50
- return blocks;
43
+ schema: {
44
+ type: "object",
45
+ properties: { text: { type: "string", required: true }, warning: { type: "string" } },
46
+ additionalProperties: false,
51
47
  },
48
+ render: (_args, value) => renderTextWarning(value),
52
49
  },
53
50
  async execute(args, exec) {
54
51
  return withWorkspace(execCwd(exec), async () => {