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
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { splitLines } from "../utils.js";
11
11
  import { loadHashStore } from "../hash-store.js";
12
- import { contentChecksum, initHasher, HASH_RE } from "./hash-assign.js";
12
+ import { contentChecksum, initHasher, HASH_RE, AnchorSpaceExhaustedError } from "./hash-assign.js";
13
13
  import { lineHashesPure, mapStableHashes } from "./hash-assign.js";
14
14
  let defaultHashSnapshotIO;
15
15
  export function setDefaultHashSnapshotIO(io) {
@@ -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,9 +52,9 @@ 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
- const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes, reservedHashes);
57
+ const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes, reservedHashes, retiredHashes.size, previous.hashes.length);
58
58
  if (persist !== false && io) {
59
59
  try {
60
60
  await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
@@ -76,7 +76,7 @@ export async function lineHashes(content, path, previous, ioOrStore, persist, re
76
76
  }
77
77
  if (cached && !cached.some((hash) => retiredHashes.has(hash)))
78
78
  return cached;
79
- const newHashes = lineHashesPure(content, reservedHashes);
79
+ const newHashes = lineHashesPure(content, reservedHashes, retiredHashes.size, 0);
80
80
  if (persist !== false && io) {
81
81
  try {
82
82
  await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
package/lib/index.js CHANGED
@@ -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
@@ -18,10 +18,44 @@ import { normFromText } from "../file-reader.js";
18
18
  import { scanDrift, loadServed, loadServedCanons, loadEpochSnapshotId, loadRetiredAnchors, retireAnchors, } from "../session-view.js";
19
19
  import { applyEdit, resEdit, parseHashRef, } from "../hashline/anchor-pipeline.js";
20
20
  import { lineHashes } from "../hashline/hash.js";
21
+ import { AnchorSpaceExhaustedError, HASH_SPACE } from "../hashline/hash-assign.js";
22
+ function isAnchorSpaceExhausted(e) {
23
+ return (e instanceof AnchorSpaceExhaustedError ||
24
+ (e instanceof Error && e.message.includes("E_ANCHOR_SPACE_EXHAUSTED")));
25
+ }
26
+ function promotionWarning(retiredSize, servedLen) {
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.`;
28
+ }
29
+ async function clearRetiredForPromotion(sessionKey, absolutePath) {
30
+ try {
31
+ const { loadServedStore } = await import("../hash-store.js");
32
+ const store = await loadServedStore();
33
+ store.clearRetiredAnchors(sessionKey ?? "", absolutePath);
34
+ try {
35
+ store.clearCards(sessionKey ?? "", absolutePath);
36
+ }
37
+ catch { }
38
+ }
39
+ catch { }
40
+ }
41
+ async function retryLineHashesWithPromotion(sessionKey, absolutePath, retired, served, warnings, fn) {
42
+ await clearRetiredForPromotion(sessionKey, absolutePath);
43
+ const servedLen = served?.filter((h) => h !== null).length ?? 0;
44
+ warnings.push(promotionWarning(retired?.size ?? 0, servedLen));
45
+ const recomputed = new Set((served?.filter((h) => h !== null) ?? []));
46
+ try {
47
+ return await fn(recomputed, new Set());
48
+ }
49
+ catch (e2) {
50
+ if (isAnchorSpaceExhausted(e2))
51
+ throw new Error(`[MODEL] [E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted even after promotion (served ${servedLen} of ${HASH_SPACE}); file too large for hashline — use write.`);
52
+ throw e2;
53
+ }
54
+ }
21
55
  import { MAX_HASH_LINES } from "../hashline/hash-assign.js";
22
56
  import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "../hashline/anchor-pipeline.js";
23
57
  import { findSnapshotPathsByHashes } from "../hash-store.js";
24
- import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "../noop-guard.js";
58
+ import { clearNoopLoop, noopPayloadKey, trackNoopPayload } from "../noop-guard.js";
25
59
  import { NOOP_LOOP_THRESHOLD } from "../constants.js";
26
60
  import { abortIf, splitLines } from "../utils.js";
27
61
  // ---------------------------------------------------------------------------
@@ -57,11 +91,11 @@ export async function resolveMissingPath(request) {
57
91
  if (matches.length === 1) {
58
92
  return {
59
93
  path: matches[0],
60
- warning: `[E_BAD_SHAPE] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
94
+ warning: `[MODEL] [E_BAD_PAYLOAD] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
61
95
  };
62
96
  }
63
97
  if (matches.length > 1) {
64
- throw new Error(`[E_BAD_SHAPE] Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(', ')}. Include the intended path.`);
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.`);
65
99
  }
66
100
  return undefined;
67
101
  }
@@ -122,29 +156,43 @@ export async function applyOne(input, onReject) {
122
156
  return onReject(error, undefined);
123
157
  }
124
158
  }
159
+ const retiredForApply = input.retired;
125
160
  let anchorResult;
126
161
  try {
127
- anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served, input.servedCanons, input.tombstone, input.epochSnapshotId, input.curSnapshotId, input.strictPos);
162
+ anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served, input.servedCanons, retiredForApply, input.epochSnapshotId, input.curSnapshotId, input.strictPos);
128
163
  }
129
164
  catch (error) {
130
- if (error instanceof AnchorMismatchError ||
131
- error instanceof ServedRejectionError) {
165
+ if (error instanceof AnchorMismatchError || error instanceof ServedRejectionError) {
132
166
  return onReject(error, edit);
133
167
  }
134
168
  throw error;
135
169
  }
136
170
  const result = anchorResult.content;
137
171
  const noop = result === input.content;
138
- const removedHashes = noop
139
- ? undefined
140
- : collectRemovedHashes(edit, input.hashes);
141
- const resultHashes = noop
142
- ? input.hashes
143
- : await lineHashes(result, input.absolutePath, {
144
- content: input.content,
145
- hashes: input.hashes,
146
- removedHashes,
147
- }, input.store, input.persist, input.reservedHashes);
172
+ const removedHashes = noop ? undefined : collectRemovedHashes(edit, input.hashes);
173
+ const retiredForHash = input.retired;
174
+ let resultHashes;
175
+ if (noop) {
176
+ resultHashes = input.hashes;
177
+ }
178
+ else {
179
+ try {
180
+ resultHashes = await lineHashes(result, input.absolutePath, {
181
+ content: input.content,
182
+ hashes: input.hashes,
183
+ removedHashes,
184
+ }, input.store, input.persist, input.reservedHashes, retiredForHash);
185
+ }
186
+ catch (e) {
187
+ if (!isAnchorSpaceExhausted(e))
188
+ throw e;
189
+ resultHashes = await retryLineHashesWithPromotion(input.sessionKey, input.absolutePath, retiredForHash, input.served, input.warnings ?? [], (recomputed, emptyRetired) => lineHashes(result, input.absolutePath, {
190
+ content: input.content,
191
+ hashes: input.hashes,
192
+ removedHashes,
193
+ }, input.store, input.persist, recomputed, emptyRetired));
194
+ }
195
+ }
148
196
  const { totalAddedLines, totalRemovedLines } = countLineChanges(edit, input.countHashes ?? input.hashes, noop, 0);
149
197
  return {
150
198
  result,
@@ -188,9 +236,7 @@ export async function enforceNoopLoop(opts) {
188
236
  await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
189
237
  }
190
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.` +
191
- (echoRows
192
- ? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}`
193
- : ""));
239
+ (echoRows ? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}` : ""));
194
240
  }
195
241
  if (count === 2) {
196
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.`;
@@ -218,8 +264,8 @@ export async function runFileEdits(io, items, opts) {
218
264
  const first = items[0];
219
265
  abortIf(opts.signal);
220
266
  const absolutePath = first.absolutePath;
221
- const perSessionTombstone = await loadRetiredAnchors(opts.sessionKey, absolutePath);
222
- const reservedHashes = new Set(perSessionTombstone);
267
+ const perSessionRetired = await loadRetiredAnchors(opts.sessionKey, absolutePath);
268
+ const reservedHashes = new Set(perSessionRetired);
223
269
  const rawText = await io.readText(absolutePath, opts.signal);
224
270
  const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
225
271
  absolutePath,
@@ -228,7 +274,7 @@ export async function runFileEdits(io, items, opts) {
228
274
  signal: opts.signal,
229
275
  maxLines: MAX_HASH_LINES,
230
276
  reservedHashes,
231
- retiredHashes: perSessionTombstone,
277
+ retiredHashes: perSessionRetired,
232
278
  });
233
279
  const served = await loadServed(opts.sessionKey, absolutePath);
234
280
  const servedCanons = await loadServedCanons(opts.sessionKey, absolutePath);
@@ -238,7 +284,9 @@ export async function runFileEdits(io, items, opts) {
238
284
  curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
239
285
  }
240
286
  catch { }
241
- const strictPos = false; // automatic resist: pos-free for exterior shift, strict via tombstone+canon for whole-span rebind
287
+ const strictPos = epochSnapshotId !== undefined &&
288
+ curSnapshotId !== undefined &&
289
+ epochSnapshotId !== curSnapshotId; // automatic: strict when epoch mismatch (conservative, future: changed∩[L,R] refined)
242
290
  const warnings = [];
243
291
  let currentContent = originalNormalized;
244
292
  let currentHashes = originalHashes;
@@ -269,13 +317,12 @@ export async function runFileEdits(io, items, opts) {
269
317
  persist: false,
270
318
  reservedHashes,
271
319
  servedCanons,
272
- tombstone: new Set([...perSessionTombstone, ...Array.from(newlyRetired)]),
320
+ retired: new Set([...perSessionRetired, ...Array.from(newlyRetired)]),
273
321
  epochSnapshotId,
274
322
  curSnapshotId,
275
323
  strictPos,
276
324
  }, async (error, edit) => {
277
- if (error instanceof AnchorMismatchError ||
278
- error instanceof ServedRejectionError) {
325
+ if (error instanceof AnchorMismatchError || error instanceof ServedRejectionError) {
279
326
  const originalLines = splitLines(originalNormalized);
280
327
  const echoRows = error.servedRows.length > 0
281
328
  ? error.servedRows
@@ -350,11 +397,22 @@ export async function runFileEdits(io, items, opts) {
350
397
  const result = currentContent;
351
398
  let resultHashes = currentHashes;
352
399
  if (appliedCount > 0 && lastApplied) {
353
- resultHashes = await lineHashes(result, absolutePath, {
354
- content: lastApplied.content,
355
- hashes: lastApplied.hashes,
356
- removedHashes: lastApplied.removedHashes,
357
- }, undefined, true, reservedHashes, perSessionTombstone);
400
+ try {
401
+ resultHashes = await lineHashes(result, absolutePath, {
402
+ content: lastApplied.content,
403
+ hashes: lastApplied.hashes,
404
+ removedHashes: lastApplied.removedHashes,
405
+ }, undefined, true, reservedHashes, perSessionRetired);
406
+ }
407
+ catch (e) {
408
+ if (!isAnchorSpaceExhausted(e))
409
+ throw e;
410
+ resultHashes = await retryLineHashesWithPromotion(opts.sessionKey, absolutePath, perSessionRetired, served, warnings, (recomputed, emptyRetired) => lineHashes(result, absolutePath, {
411
+ content: lastApplied.content,
412
+ hashes: lastApplied.hashes,
413
+ removedHashes: lastApplied.removedHashes,
414
+ }, undefined, true, recomputed, emptyRetired));
415
+ }
358
416
  await retireAnchors(opts.sessionKey, absolutePath, newlyRetired);
359
417
  }
360
418
  if (hadUtf8DecodeErrors) {
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";
@@ -57,7 +57,7 @@ export async function execPipeline(io, params, cwd, options) {
57
57
  abortIf(signal);
58
58
  const absolutePath = await io.resolve(path, cwd, signal);
59
59
  const sessionKeyEarly = options?.sessionKey ?? sessionKeyFor(undefined);
60
- const perSessionTombstoneForNorm = await loadRetiredAnchors(sessionKeyEarly, absolutePath);
60
+ const perSessionRetiredForNorm = await loadRetiredAnchors(sessionKeyEarly, absolutePath);
61
61
  const rawText = await io.readText(absolutePath, signal);
62
62
  const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
63
63
  absolutePath,
@@ -67,8 +67,8 @@ export async function execPipeline(io, params, cwd, options) {
67
67
  maxLines: MAX_HASH_LINES,
68
68
  store: hashStore,
69
69
  noPersist: options?.noPersist,
70
- reservedHashes: perSessionTombstoneForNorm,
71
- retiredHashes: perSessionTombstoneForNorm,
70
+ reservedHashes: perSessionRetiredForNorm,
71
+ retiredHashes: perSessionRetiredForNorm,
72
72
  });
73
73
  const sessionKey = options?.sessionKey ?? sessionKeyFor(undefined);
74
74
  const served = await loadServed(sessionKey, absolutePath);
@@ -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 = false; // automatic resist: pos-free for exterior shift, strict via tombstone+canon (changed ∩ [L,R] handled by tombstone interior gated on canon)
83
- const tombstonePerSession = await loadRetiredAnchors(sessionKey, absolutePath);
84
- const policy = options?.noPersist === true ? 'preview' : 'live';
82
+ const strictPos = epochSnapshotId !== undefined &&
83
+ curSnapshotId !== undefined &&
84
+ epochSnapshotId !== curSnapshotId; // automatic: strict when epoch mismatch (conservative, future: changed∩[L,R] refined)
85
+ const retiredPerSession = await loadRetiredAnchors(sessionKey, absolutePath);
86
+ const policy = options?.noPersist === true ? "preview" : "live";
85
87
  const applied = await applyOne({
86
88
  content: originalNormalized,
87
89
  hashes: originalHashes,
@@ -95,16 +97,15 @@ export async function execPipeline(io, params, cwd, options) {
95
97
  warnings: editWarnings,
96
98
  store: hashStore,
97
99
  persist: options?.noPersist !== true,
98
- reservedHashes: perSessionTombstoneForNorm,
100
+ reservedHashes: perSessionRetiredForNorm,
99
101
  servedCanons,
100
- tombstone: tombstonePerSession,
102
+ retired: retiredPerSession,
101
103
  epochSnapshotId,
102
104
  curSnapshotId,
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 {
@@ -274,7 +275,7 @@ export async function execute(opts) {
274
275
  if (built.details.servedRows && built.details.servedRows.length > 0) {
275
276
  const entry = built.details.servedByPath?.[0];
276
277
  if (entry) {
277
- await recordServedTruncated(sessionKey, fileResult.absolutePath, entry.servedRows, splitLines(fileResult.result).length, fileResult.range.startLine - 1);
278
+ await recordServedTruncated(sessionKey, fileResult.absolutePath, entry.servedRows, splitLines(fileResult.result).length, fileResult.range.startLine - 1, splitLines(fileResult.result).map((l) => canon(l)));
278
279
  }
279
280
  }
280
281
  };
package/lib/prompts.js CHANGED
@@ -6,22 +6,23 @@
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 the file path or `null`. `read` returns `HASH\u2502content` (e.g. `wUp\u2502 \"site\": {`) \u2014 for `edit`, " +
11
- "`remove_from`/`remove_to` are HASH anchors (bare 3-char value before `\u2502`, e.g. \"wUp\", \"AU6\"), never `HASH\u2502content` or line content. " +
12
- "`replacement_text` is bare content without `HASH\u2502`, lines joined by \\n (e.g. \" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\"); use \"\" to delete. " +
13
- "Example: read shows `wUp\u2502 \"site\": {` + `AU6\u2502 \"name\": \"old\",` \u2192 edit " +
14
- "`{\"path\":\"scrape.py\",\"edits\":[[\"wUp\",\"AU6\",\" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\"]]}`. " +
15
- "Edits in one call apply atomically; after success reuse `HASH\u2502content` from the returned diff for the next edit (no re-read needed). On failure follow the error hint.";
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
+ "On failure follow the error hint: `[MODEL]` errors need a retry with fresh anchors, `[USER]` notices are human-only.";
16
14
  export const EDIT_GUIDANCE = {
17
- 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).",
18
16
  lines: [
19
- "`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.',
20
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.",
21
- "`edit`: `replacement_text` is plain file content without `HASH\u2502` \u2014 e.g. \" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\" \u2014 never prefix lines with `HASH\u2502`.",
22
- "`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.",
23
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.",
24
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).",
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.",
25
+ "`edit`: on `E_STALE_RANGE`/`E_UNSERVED_RANGE` retry from the echoed fresh anchors (no re-read needed); on `E_STALE_ANCHOR` re-read.",
25
26
  ],
26
27
  };
27
28
  export const READ_DESCRIPTION = "Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. " +
@@ -12,7 +12,9 @@ import { readView, fileSnap } from "./file-view.js";
12
12
  import { canon } from "./hashline/hash-assign.js";
13
13
  import { splitLines } from "./utils.js";
14
14
  import { getAutoGuessFooter } from "./fs-bridge.js";
15
- import { recordServed, clearDriftReported, loadRetiredAnchors, loadServed, } from "./session-view.js";
15
+ import { AnchorSpaceExhaustedError, HASH_SPACE } from "./hashline/hash-assign.js";
16
+ import { recordServed, clearDriftReported, loadRetiredAnchors, loadServed, loadServedCanons, loadEpochSnapshotId, } from "./session-view.js";
17
+ import { loadServedStore } from "./hash-store.js";
16
18
  /** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
17
19
  export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
18
20
  /**
@@ -29,18 +31,87 @@ export async function readAndServe(io, rawPath, cwd, options) {
29
31
  const { sessionKey, signal } = options;
30
32
  abortIf(signal);
31
33
  const absolutePath = await io.resolve(rawPath, cwd, signal);
32
- const retiredHashes = await loadRetiredAnchors(sessionKey, absolutePath);
34
+ let retiredHashes = await loadRetiredAnchors(sessionKey, absolutePath);
33
35
  const servedForNorm = await loadServed(sessionKey, absolutePath);
34
- const reservedHashes = new Set([...retiredHashes, ...servedForNorm.filter((h) => h !== null)]);
35
- const reservations = { reservedHashes, retiredHashes };
36
- const view = await readView(io, rawPath, cwd, {
37
- encoding: options.encoding,
38
- offset: options.offset,
39
- limit: options.limit,
40
- signal,
41
- reservedHashes: reservations.reservedHashes,
42
- retiredHashes: reservations.retiredHashes,
43
- });
36
+ const servedCanons = await loadServedCanons(sessionKey, absolutePath);
37
+ const epochSnapshotId = await loadEpochSnapshotId(sessionKey, absolutePath);
38
+ // Build previous for stable reuse (S): served filtered + canons reconstruction
39
+ let previous;
40
+ if (servedForNorm.some((h) => h !== null)) {
41
+ const filteredHashes = [];
42
+ const filteredCanons = [];
43
+ for (let i = 0; i < servedForNorm.length; i++) {
44
+ const h = servedForNorm[i];
45
+ if (h !== null) {
46
+ filteredHashes.push(h);
47
+ filteredCanons.push(servedCanons[i] ?? "");
48
+ }
49
+ }
50
+ if (filteredHashes.length > 0) {
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
+ const prevContent = filteredCanons.join("\n");
53
+ previous = {
54
+ content: prevContent,
55
+ hashes: filteredHashes,
56
+ removedHashes: new Set(retiredHashes),
57
+ };
58
+ }
59
+ }
60
+ let reservedHashes = new Set([
61
+ ...retiredHashes,
62
+ ...servedForNorm.filter((h) => h !== null),
63
+ ]);
64
+ let reservations = { reservedHashes, retiredHashes };
65
+ let promotionWarning;
66
+ let view;
67
+ try {
68
+ view = await readView(io, rawPath, cwd, {
69
+ encoding: options.encoding,
70
+ offset: options.offset,
71
+ limit: options.limit,
72
+ signal,
73
+ reservedHashes: reservations.reservedHashes,
74
+ retiredHashes: reservations.retiredHashes,
75
+ previous,
76
+ });
77
+ }
78
+ catch (e) {
79
+ if (e instanceof AnchorSpaceExhaustedError ||
80
+ (e instanceof Error && e.message.includes("E_ANCHOR_SPACE_EXHAUSTED"))) {
81
+ const retiredCount = retiredHashes.size;
82
+ const servedCount = servedForNorm.filter((h) => h !== null).length;
83
+ const reservedCount = retiredCount + servedCount;
84
+ // Major GC promotion: clear retired for this (session,path), keep served/canons
85
+ try {
86
+ const store = await loadServedStore();
87
+ store.clearRetiredAnchors(sessionKey, absolutePath);
88
+ try {
89
+ store.clearCards(sessionKey, absolutePath);
90
+ }
91
+ catch { }
92
+ }
93
+ catch { }
94
+ promotionWarning = `[E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted (retired ${retiredCount} + served ${servedCount} = ${reservedCount} of ${HASH_SPACE}); promotion cleared retired — re-read recommended, stale-anchor checks degraded until next full read.`;
95
+ // Retry ignoring retired (served only) — also drop removedHashes from previous
96
+ retiredHashes = new Set();
97
+ reservedHashes = new Set([...servedForNorm.filter((h) => h !== null)]);
98
+ reservations = { reservedHashes, retiredHashes };
99
+ if (previous)
100
+ previous = { content: previous.content, hashes: previous.hashes };
101
+ view = await readView(io, rawPath, cwd, {
102
+ encoding: options.encoding,
103
+ offset: options.offset,
104
+ limit: options.limit,
105
+ signal,
106
+ reservedHashes: reservations.reservedHashes,
107
+ retiredHashes: reservations.retiredHashes,
108
+ previous,
109
+ });
110
+ }
111
+ else {
112
+ throw e;
113
+ }
114
+ }
44
115
  if (view.served.length > 0) {
45
116
  const canons = splitLines(view.normalized).map((l) => canon(l));
46
117
  const canonServed = canons.map((canonText) => canonText);
@@ -55,14 +126,29 @@ export async function readAndServe(io, rawPath, cwd, options) {
55
126
  for (let i = 0; i < view.hashes.length; i++) {
56
127
  fullCanons.push(canons[i] ?? null);
57
128
  }
58
- await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length, view.hashes, fullCanons, snapshotId);
129
+ await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length, {
130
+ hashes: view.hashes,
131
+ canons: fullCanons,
132
+ snapshotId,
133
+ });
59
134
  }
60
- await clearDriftReported(sessionKey, view.absolutePath);
61
- const autoFooter = getAutoGuessFooter(view.absolutePath) ?? getAutoGuessFooter(rawPath) ?? getAutoGuessFooter(view.absolutePath.replace(/\\/g, "/")) ?? "";
62
- const warning = autoFooter || undefined;
63
- const text = view.hadUtf8DecodeErrors
64
- ? `${view.text}\n\n${UTF8_REWRITE_NOTE}`
65
- : view.text;
135
+ // #69: epoch lifecycle belongs to full reads — a partial (paged or
136
+ // truncated) read merges window rows only and must not clear the
137
+ // drift-reported marks; only a full read resets them.
138
+ const isFullRead = options.offset === undefined && options.limit === undefined && !view.truncation?.truncated;
139
+ if (isFullRead)
140
+ await clearDriftReported(sessionKey, view.absolutePath);
141
+ const autoFooter = getAutoGuessFooter(view.absolutePath) ??
142
+ getAutoGuessFooter(rawPath) ??
143
+ getAutoGuessFooter(view.absolutePath.replace(/\\/g, "/")) ??
144
+ "";
145
+ const autoWarning = autoFooter || undefined;
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;
66
152
  return {
67
153
  text,
68
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) {