dsh-better-edit 0.8.2 → 1.0.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 (75) hide show
  1. package/CHANGELOG.md +158 -99
  2. package/README.md +2 -2
  3. package/README.zh.md +3 -3
  4. package/cordis.patch.yml +1 -1
  5. package/lib/constants.js +19 -4
  6. package/lib/contract.js +136 -79
  7. package/lib/domain-errors.js +570 -0
  8. package/lib/edit-diff.js +33 -7
  9. package/lib/file-encoding-state.js +27 -7
  10. package/lib/file-view.js +305 -82
  11. package/lib/fs-bridge.js +23 -7
  12. package/lib/hash-store.js +404 -278
  13. package/lib/hashline/anchor-pipeline.js +586 -378
  14. package/lib/hashline/hash-assign.js +21 -22
  15. package/lib/hashline/hash.js +6 -6
  16. package/lib/hashline/index.js +1 -1
  17. package/lib/hashline/resolve.js +1 -1
  18. package/lib/hashline/served-guard.js +181 -0
  19. package/lib/index.js +1 -1
  20. package/lib/mutation/engine.js +392 -96
  21. package/lib/mutation.js +22 -130
  22. package/lib/noop-guard.js +20 -9
  23. package/lib/prompts.js +20 -18
  24. package/lib/read-and-serve.js +44 -20
  25. package/lib/sandbox.js +1 -1
  26. package/lib/session-view.js +57 -43
  27. package/lib/snapshot-store/index.js +97 -0
  28. package/lib/snapshot-store/lineage-store.js +400 -0
  29. package/lib/snapshot-store/migrate.js +80 -0
  30. package/lib/snapshot-store/pairing.js +412 -0
  31. package/lib/snapshot-store/txn.js +63 -0
  32. package/lib/snapshot-store/vacuum.js +243 -0
  33. package/lib/store-lifecycle.js +13 -1
  34. package/lib/store-retry.js +34 -0
  35. package/lib/tool-edit.js +90 -44
  36. package/lib/tool-read.js +29 -1
  37. package/lib/tool-str-replace-editor.js +26 -18
  38. package/lib/tool-undo.js +25 -8
  39. package/lib/types/constants.d.ts +5 -2
  40. package/lib/types/contract.d.ts +76 -71
  41. package/lib/types/domain-errors.d.ts +410 -0
  42. package/lib/types/edit-response.d.ts +1 -1
  43. package/lib/types/file-encoding-state.d.ts +1 -0
  44. package/lib/types/file-view.d.ts +35 -6
  45. package/lib/types/hash-store.d.ts +38 -19
  46. package/lib/types/hashline/anchor-pipeline.d.ts +117 -36
  47. package/lib/types/hashline/hash-assign.d.ts +5 -5
  48. package/lib/types/hashline/hash.d.ts +1 -1
  49. package/lib/types/hashline/index.d.ts +2 -2
  50. package/lib/types/hashline/served-guard.d.ts +100 -0
  51. package/lib/types/index.d.ts +2 -2
  52. package/lib/types/mutation/engine.d.ts +49 -30
  53. package/lib/types/mutation.d.ts +1 -39
  54. package/lib/types/noop-guard.d.ts +4 -4
  55. package/lib/types/prompts.d.ts +1 -1
  56. package/lib/types/read-and-serve.d.ts +6 -0
  57. package/lib/types/sandbox.d.ts +1 -1
  58. package/lib/types/session-view.d.ts +38 -9
  59. package/lib/types/snapshot-store/index.d.ts +28 -0
  60. package/lib/types/snapshot-store/lineage-store.d.ts +96 -0
  61. package/lib/types/snapshot-store/migrate.d.ts +16 -0
  62. package/lib/types/snapshot-store/pairing.d.ts +99 -0
  63. package/lib/types/snapshot-store/txn.d.ts +12 -0
  64. package/lib/types/snapshot-store/vacuum.d.ts +79 -0
  65. package/lib/types/store-lifecycle.d.ts +0 -1
  66. package/lib/types/store-retry.d.ts +6 -0
  67. package/lib/types/tool-edit.d.ts +2 -2
  68. package/lib/types/tool-str-replace-editor.d.ts +2 -2
  69. package/lib/types/utils.d.ts +5 -6
  70. package/lib/types/workspace-context.d.ts +0 -1
  71. package/lib/undo-edit.js +27 -11
  72. package/lib/utils.js +12 -12
  73. package/lib/workspace-context.js +4 -8
  74. package/lib/write-hook.js +13 -4
  75. package/package.json +9 -10
package/lib/mutation.js CHANGED
@@ -13,28 +13,22 @@
13
13
  *
14
14
  * Public surface:
15
15
  * execute(io, items, {sessionKey, exec, sandbox, signal}) → string — deep seam: ONE interface
16
- * applySingle(io, params, cwd, opts) → PipelineResult — single-edit helper
17
16
  * applySequence(io, items, ctx) → FileEditResult — per-file sequencer
18
17
  * commit(io, files, {exec, sandboxPolicy, signal}) → void — transaction
19
18
  *
20
19
  * Depth: small interface (execute) with large implementation — locality and leverage.
21
20
  *
22
21
  * Internals (private): verifyServedRange, resToSpan, assemble, scanDrift,
23
- * boundaryDups, noopGuard. Tested via PipelineResult/FileEditResult, not via split e2e.
22
+ * boundaryDups, noopGuard. Tested via FileEditResult, not via split e2e.
24
23
  *
25
24
  * @module dsh-better-edit/mutation
26
25
  */
27
- import { loadConfig } from "./store-config.js";
26
+ import { formatError } from "./domain-errors.js";
28
27
  import { canon } from "./hashline/hash-assign.js";
29
- import { normFromText, fileSnap } from "./file-reader.js";
28
+ import { fileSnap } from "./file-reader.js";
30
29
  import { toCwd } from "./paths.js";
31
- import { resEdit } from "./hashline/anchor-pipeline.js";
32
- import { MAX_HASH_LINES } from "./hashline/hash-assign.js";
33
- import { AnchorMismatchError, ServedRejectionError, recordEchoServes, } from "./hashline/anchor-pipeline.js";
34
- import { sessionKeyFor } from "./workspace-context.js";
35
- import { loadServed, loadServedCanons, loadEpochSnapshotId, loadRetiredAnchors, scanDrift, recordServedTruncated, } from "./session-view.js";
30
+ import { recordServedTruncated, scanDrift } from "./session-view.js";
36
31
  import { abortIf, splitLines } from "./utils.js";
37
- import { applyOne } from "./mutation/engine.js";
38
32
  import { runFileEdits, resolveMissingPath } from "./mutation/engine.js";
39
33
  import { saveUndo } from "./undo-edit.js";
40
34
  import { restoreEndings } from "./edit-diff.js";
@@ -42,113 +36,6 @@ import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-
42
36
  import { genDiff, toLF, stripBOM } from "./edit-diff.js";
43
37
  import { computeDrift } from "./session-view.js";
44
38
  import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js";
45
- export async function execPipeline(io, params, cwd, options) {
46
- const path = params.path;
47
- const editWarnings = [];
48
- // Resolve the edit up front (before IO) so malformed anchors fail before
49
- // any filesystem work, exactly as the tool always did.
50
- const edit = resEdit({
51
- remove_from: params.remove_from,
52
- remove_to: params.remove_to,
53
- replacement_text: params.replacement_text,
54
- }, editWarnings);
55
- const hashStore = options?.store;
56
- const signal = options?.signal;
57
- abortIf(signal);
58
- const absolutePath = await io.resolve(path, cwd, signal);
59
- const sessionKeyEarly = options?.sessionKey ?? sessionKeyFor(undefined);
60
- const perSessionRetiredForNorm = await loadRetiredAnchors(sessionKeyEarly, absolutePath);
61
- const rawText = await io.readText(absolutePath, signal);
62
- const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
63
- absolutePath,
64
- rawText,
65
- displayPath: path,
66
- signal,
67
- maxLines: MAX_HASH_LINES,
68
- store: hashStore,
69
- noPersist: options?.noPersist,
70
- reservedHashes: perSessionRetiredForNorm,
71
- retiredHashes: perSessionRetiredForNorm,
72
- });
73
- const sessionKey = options?.sessionKey ?? sessionKeyFor(undefined);
74
- const served = await loadServed(sessionKey, absolutePath);
75
- const servedCanons = await loadServedCanons(sessionKey, absolutePath);
76
- const epochSnapshotId = await loadEpochSnapshotId(sessionKey, absolutePath);
77
- let curSnapshotId;
78
- try {
79
- curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
80
- }
81
- catch { }
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";
87
- const applied = await applyOne({
88
- content: originalNormalized,
89
- hashes: originalHashes,
90
- served,
91
- removeFrom: params.remove_from,
92
- removeTo: params.remove_to,
93
- replacementText: params.replacement_text,
94
- absolutePath,
95
- displayPath: path,
96
- signal,
97
- warnings: editWarnings,
98
- store: hashStore,
99
- persist: options?.noPersist !== true,
100
- reservedHashes: perSessionRetiredForNorm,
101
- servedCanons,
102
- retired: retiredPerSession,
103
- epochSnapshotId,
104
- curSnapshotId,
105
- strictPos,
106
- edit,
107
- }, async (error) => {
108
- if (error instanceof AnchorMismatchError || error instanceof ServedRejectionError) {
109
- await recordEchoServes(sessionKey, absolutePath, error.servedRows, policy, originalHashes.length);
110
- }
111
- throw error;
112
- });
113
- const result = applied.result;
114
- const isNoop = applied.noop;
115
- const warnings = [...editWarnings, ...(applied.anchorWarnings ?? [])];
116
- let driftNotice;
117
- if (options?.noPersist !== true) {
118
- try {
119
- driftNotice = await scanDrift({
120
- sessionKey,
121
- served,
122
- resultHashes: applied.hashes,
123
- resultLines: splitLines(result),
124
- range: applied.range,
125
- path: absolutePath,
126
- });
127
- }
128
- catch (error) {
129
- console.error("Failed to compute drift notice:", error);
130
- }
131
- }
132
- return {
133
- path,
134
- absolutePath,
135
- originalNormalized,
136
- result,
137
- bom,
138
- originalEnding,
139
- hadUtf8DecodeErrors,
140
- warnings,
141
- noopEdit: applied.noopEdit,
142
- firstChangedLine: applied.firstChangedLine,
143
- lastChangedLine: applied.lastChangedLine,
144
- originalHashes,
145
- resultHashes: applied.hashes,
146
- totalAddedLines: applied.totalAddedLines,
147
- totalRemovedLines: applied.totalRemovedLines,
148
- driftNotice,
149
- range: applied.range,
150
- };
151
- }
152
39
  /** Resolve the display path a caller names against the session cwd. */
153
40
  export function resolveDisplayPath(path, cwd) {
154
41
  return toCwd(path, cwd);
@@ -271,20 +158,29 @@ export async function execute(opts) {
271
158
  totalAddedLines: fileResult.totalAddedLines,
272
159
  totalRemovedLines: fileResult.totalRemovedLines,
273
160
  });
161
+ // The serve write is a SECOND unit, deliberately outside the committed pair: a fault there must
162
+ // not roll the edit back. But it decides whether the diff's anchors are usable, so the claim is
163
+ // made only when the serve landed. Same vocabulary as the undo warning (src/tool-undo.ts).
164
+ const serveNotRecordedNotice = "WARNING: the edit applied and stands \u2014 nothing was rolled back \u2014 but the edited rows " +
165
+ "were NOT recorded as served. The diff's `HASH\u2502` rows above are NOT usable anchors and no " +
166
+ "edit can be based on them. Re-read the file before the next edit.";
167
+ const withServeNotice = (text, serveLanded) => serveLanded ? text : `${text}\n\n${serveNotRecordedNotice}`;
274
168
  const recordIfNeeded = async (built) => {
275
169
  if (built.details.servedRows && built.details.servedRows.length > 0) {
276
170
  const entry = built.details.servedByPath?.[0];
277
171
  if (entry) {
278
- await recordServedTruncated(sessionKey, fileResult.absolutePath, entry.servedRows, splitLines(fileResult.result).length, fileResult.range.startLine - 1, splitLines(fileResult.result).map((l) => canon(l)));
172
+ return recordServedTruncated(sessionKey, fileResult.absolutePath, entry.servedRows, splitLines(fileResult.result).length, fileResult.range.startLine - 1, splitLines(fileResult.result).map((l) => canon(l)), { content: fileResult.result, hashes: fileResult.resultHashes });
279
173
  }
280
174
  }
175
+ // Nothing to record, so nothing can fail: vacuously landed.
176
+ return true;
281
177
  };
282
178
  const isSingleCall = items.length === 1 && fileResult.appliedCount + fileResult.noopCount === 1;
283
179
  if (isSingleCall) {
284
180
  if (fileResult.appliedCount === 0) {
285
181
  const built = buildBatchResult([toSection()]);
286
- await recordIfNeeded(built);
287
- return built.content[0].text;
182
+ const serveLanded = await recordIfNeeded(built);
183
+ return withServeNotice(built.content[0].text, serveLanded);
288
184
  }
289
185
  await commitSingle({
290
186
  io,
@@ -303,11 +199,11 @@ export async function execute(opts) {
303
199
  sandbox,
304
200
  sandboxPolicy,
305
201
  signal,
306
- undoUnavailableMessage: (displayPath) => `[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the edit was NOT applied and ${displayPath} is unchanged. Retry the edit, or use write if the store cannot be recovered.`,
202
+ undoUnavailableMessage: (displayPath) => formatError("E_UNDO_UNAVAILABLE", { path: displayPath }),
307
203
  });
308
204
  const built = buildBatchResult([toSection()]);
309
- await recordIfNeeded(built);
310
- return built.content[0].text;
205
+ const serveLanded = await recordIfNeeded(built);
206
+ return withServeNotice(built.content[0].text, serveLanded);
311
207
  }
312
208
  if (fileResult.appliedCount === 0 && fileResult.noopCount > 0) {
313
209
  // all noops — no commit
@@ -330,16 +226,12 @@ export async function execute(opts) {
330
226
  sandbox,
331
227
  sandboxPolicy,
332
228
  signal,
333
- undoUnavailableMessage: () => "[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the batch was NOT applied and no file was written. Retry the batch, or use write if the store cannot be recovered.",
229
+ undoUnavailableMessage: (displayPath) => formatError("E_UNDO_UNAVAILABLE", { path: displayPath, batch: true }),
334
230
  });
335
231
  }
336
232
  const built = buildBatchResult([toSection()]);
337
- await recordIfNeeded(built);
338
- return built.content[0].text;
339
- }
340
- /** Apply a single edit — owns read→normalize→loadServed→applyOne→stableRehash→drift. */
341
- export async function applySingle(io, params, cwd, opts) {
342
- return execPipeline(io, params, cwd, opts);
233
+ const serveLanded = await recordIfNeeded(built);
234
+ return withServeNotice(built.content[0].text, serveLanded);
343
235
  }
344
236
  /** Apply a per-file sequence (batch's group) — owns the loop + unionRange + counters. */
345
237
  export async function applySequence(io, items, ctx) {
package/lib/noop-guard.js CHANGED
@@ -1,7 +1,8 @@
1
+ import { formatError, formatWarning } from "./domain-errors.js";
1
2
  import { NOOP_LOOP_THRESHOLD } from "./constants.js";
2
3
  const noopLoopTracker = new Map();
3
- export function noopPayloadKey(absolutePath, removeFrom, removeTo, replacementText) {
4
- return JSON.stringify([absolutePath, removeFrom, removeTo, replacementText]);
4
+ export function noopPayloadKey(absolutePath, anchorFrom, anchorTo, replaceWith) {
5
+ return JSON.stringify([absolutePath, anchorFrom, anchorTo, replaceWith]);
5
6
  }
6
7
  export function trackNoopPayload(absolutePath, payload) {
7
8
  const existing = noopLoopTracker.get(absolutePath);
@@ -15,21 +16,31 @@ export function clearNoopLoop(absolutePath) {
15
16
  export { NOOP_LOOP_THRESHOLD };
16
17
  export function runNoopPolicySync(input, count) {
17
18
  if (count >= NOOP_LOOP_THRESHOLD) {
18
- const message = input.batch
19
- ? `[E_NOOP_LOOP] ${input.ref}: identical edit (${input.removeFrom} → ${input.removeTo}) submitted ${count}×, no changes each time. Range already contains this text; resend will reject the batch.`
20
- : `[E_NOOP_LOOP] identical edit (${input.removeFrom} → ${input.removeTo} ${input.ref}) submitted ${count}×, no changes each time. Range already contains this text; resend will reject.`;
19
+ const message = formatError("E_NOOP_LOOP", {
20
+ ref: input.ref,
21
+ anchorFrom: input.anchorFrom,
22
+ anchorTo: input.anchorTo,
23
+ count,
24
+ batch: input.batch,
25
+ servedBlock: "",
26
+ });
21
27
  return { action: "reject", count, message };
22
28
  }
23
29
  if (count === 2) {
24
- const notice = input.batch
25
- ? `[E_NOOP_LOOP] Notice: ${input.ref} — identical edit no-op'd twice; range already has this text. Resend will reject the batch.`
26
- : `[E_NOOP_LOOP] Notice: identical edit (${input.removeFrom} → ${input.removeTo} ${input.ref}) no-op'd twice; range already has this text. Resend will reject.`;
30
+ // Channel rule: applied-tier notices are human-observable → USER audience via the registry.
31
+ const notice = formatWarning("W_NOOP", {
32
+ ref: input.ref,
33
+ anchorFrom: input.anchorFrom,
34
+ anchorTo: input.anchorTo,
35
+ batch: input.batch,
36
+ count,
37
+ });
27
38
  return { action: "warn", count, notice };
28
39
  }
29
40
  return { action: "proceed", count };
30
41
  }
31
42
  export async function runNoopPolicy(input) {
32
- const payload = noopPayloadKey(input.absolutePath, input.removeFrom, input.removeTo, input.replacementText);
43
+ const payload = noopPayloadKey(input.absolutePath, input.anchorFrom, input.anchorTo, input.replaceWith);
33
44
  const count = trackNoopPayload(input.absolutePath, payload);
34
45
  return runNoopPolicySync(input, count);
35
46
  }
package/lib/prompts.js CHANGED
@@ -6,33 +6,35 @@
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], ...] }` (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.";
9
+ export const EDIT_DESCRIPTION = 'Edit a range of lines in a text file with `{ "file": file, "edits": [{ "anchor_from": a, "anchor_to": b, "replace_with": text }, ...] }` (arity = edits.length, atomic, one file per call). ' +
10
+ '`file` is the text file (a file, never a directory). `read` shows `HASH\u2502content` (e.g. `wUp\u2502 "site": {`) \u2014 use bare 3-char HASH anchors for ' +
11
+ '`anchor_from`/`anchor_to` (e.g. "wUp"), never `HASH\u2502content`. `replace_with` is bare content, \\n joins lines, "" deletes. ' +
12
+ 'Example: `{"file":"a.py","edits":[{"anchor_from":"wUp","anchor_to":"AU6","replace_with":"new"}]}` (legacy tuples still fold). Reuse `HASH\u2502content` from the diff after success unless the result says NOT recorded as served, then re-read. ' +
13
+ "On failure follow the error hint: `[TO MODEL]` errors need a retry with fresh anchors, `[USER]` is 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]] } or { path, edits: [{remove_from, remove_to, replacement_text}] } (single-file atomic, null path infers; tuple and object forms are equivalent, mixed batches allowed).",
15
+ intro: "Edit a range of lines via a bare 3-char HASH anchor \u2014 payload is { file, edits: [{anchor_from, anchor_to, replace_with}] } (single-file atomic; legacy tuples still fold pre-validation).",
16
16
  lines: [
17
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
- "`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).',
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.",
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.",
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.",
18
+ "`edit`: get `anchor_from`/`anchor_to` by copying only the 3 chars before `\u2502` from `read` output \u2014 never include `\u2502` or content after it.",
19
+ '`edit`: `replace_with` 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 `replace_with` separates lines; mirror trailing blank lines explicitly (use "" to delete a range).',
21
+ "`edit`: `edits` entries are objects `{anchor_from, anchor_to, replace_with}` \u2014 legacy tuples still fold pre-validation; unknown fields are rejected.",
22
+ "`edit`: after an edit whose serve landed, the returned diff shows fresh anchors (`HASH\u2502content`) \u2014 copy new `HASH` values from there for the next edit; if the result says the rows were NOT recorded as served, re-read instead.",
23
+ "`edit`: `anchor_from`/`anchor_to` are inclusive; batch multiple edits to the same file only when independent \u2014 they apply atomically (fail \u2192 nothing written).",
24
+ "`edit`: `[TO MODEL]` errors (e.g. `E_STALE_*`, `E_UNSERVED_*`, `E_BAD_PAYLOAD`, `E_SUSPICIOUS_TEXT`) need a retry \u2014 `[USER]` warnings/`drift:` notices are human-only.",
25
+ "`edit`: on `E_STALE_ANCHOR` re-read for fresh anchors; on `E_STALE_RANGE`/`E_UNSERVED_RANGE` the echoed rows are the file's current anchors, NOT serves — re-read before retrying.",
26
26
  ],
27
27
  };
28
28
  export const READ_DESCRIPTION = "Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. " +
29
29
  "No line numbers — use the HASH as the anchor in edit calls. Binary/directory → rejected; " +
30
- "empty → HASH│ (edit to insert); pageable with offset/limit; BOM stripped; non-UTF-8 shown as U+FFFD.";
30
+ "empty → HASH│ (edit to insert); pageable with offset/limit, or several disjoint ranges in one call " +
31
+ "with `windows: [{offset, limit}, ...]` (every listed window is served there, so anchors from all " +
32
+ "of them work in one edit); BOM stripped; non-UTF-8 shown as U+FFFD.";
31
33
  export const READ_GUIDANCE = {
32
34
  intro: "Use read, not shell commands, to inspect text files and obtain the HASH anchors the editing tools require.",
33
35
  lines: [
34
36
  "`read`: call it only for content the tools have not served — a page you never saw, or lines past the post-edit diff.",
35
- "`read`: each row is `HASH│content`; the HASH is the anchor (no line numbers). Rejection echoes return fresh rows that count as serves.",
37
+ "`read`: each row is `HASH│content`; the HASH is the anchor (no line numbers). Rejection echoes show the file's current rows — they are NOT recorded as serves, so re-read before retrying.",
36
38
  "`read`: binary/directory rejects; page large files with offset/limit.",
37
39
  ],
38
40
  };
@@ -42,12 +44,12 @@ export const UNDO_GUIDANCE = {
42
44
  intro: "Revert the last edit on a file.",
43
45
  lines: [
44
46
  "`undo_last_edit`: reverts only the most recent edit — any write clears history, so call it immediately after a bad edit.",
45
- "`undo_last_edit`: the restored diff\u2019s `+HASH│` and ` HASH│` rows are fresh anchors for follow-up edits.",
47
+ "`undo_last_edit`: the restored diff\u2019s `+HASH│` and ` HASH│` rows are fresh anchors for follow-up edits \u2014 unless the result says the rows were NOT recorded as served, then re-read.",
46
48
  ],
47
49
  };
48
50
  /**
49
51
  * @deprecated batch_edit guidance seam was removed with ADR-0003 (payload contract
50
- * merged batch_edit into edit's {path, edits:[[hash,hash,text]]} arity). This alias
52
+ * merged batch_edit into edit's {file, edits:[...]} arity). This alias
51
53
  * is kept for backwards compat — use EDIT_DESCRIPTION. The guidance system no
52
54
  * longer includes tool:batch_edit.
53
55
  */
@@ -8,15 +8,22 @@
8
8
  * @module dsh-better-edit/read-and-serve
9
9
  */
10
10
  import { abortIf } from "./utils.js";
11
- import { readView, fileSnap } from "./file-view.js";
11
+ import { hasRequestedWindows, readView } 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
15
  import { AnchorSpaceExhaustedError, HASH_SPACE } from "./hashline/hash-assign.js";
16
- import { recordServed, clearDriftReported, loadRetiredAnchors, loadServed, loadServedCanons, loadEpochSnapshotId, } from "./session-view.js";
16
+ import { recordServed, clearDriftReported, loadRetiredAnchors, loadServed, loadServedCanons, } from "./session-view.js";
17
17
  import { loadServedStore } from "./hash-store.js";
18
18
  /** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
19
19
  export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
20
+ /**
21
+ * Appended when the read's serve write did not land: the rows are shown, but their anchors are not
22
+ * usable for editing. Goes in `text`, not `warning` — `tool-read` renders both, but the write hook
23
+ * (`src/write-hook.ts`) renders `text` only, and both consumers must see the downgrade.
24
+ */
25
+ const SERVE_NOT_RECORDED_NOTE = "WARNING: the rows above were NOT recorded as served — their `HASH│` anchors are NOT " +
26
+ "usable for editing. Re-read the file to re-sync before editing.";
20
27
  /**
21
28
  * Perform one read-and-serve: normalize the file at `rawPath`, render its
22
29
  * hashline preview, record the shown rows as served for the session, and clear
@@ -34,10 +41,16 @@ export async function readAndServe(io, rawPath, cwd, options) {
34
41
  let retiredHashes = await loadRetiredAnchors(sessionKey, absolutePath);
35
42
  const servedForNorm = await loadServed(sessionKey, absolutePath);
36
43
  const servedCanons = await loadServedCanons(sessionKey, absolutePath);
37
- const epochSnapshotId = await loadEpochSnapshotId(sessionKey, absolutePath);
38
- // Build previous for stable reuse (S): served filtered + canons reconstruction
44
+ // Build previous for stable reuse (S): served filtered + canons reconstruction.
45
+ // #62 alignment gate: the reconstructed arrays carry the SERVED index as the line
46
+ // position, which equals the real line number only when the mirror is dense — the
47
+ // `row.position === index` half of the `isFullRead` predicate (session-view.ts).
48
+ // With holes (a partial mirror), `mapStableHashes` would match compressed indices
49
+ // against whole-file positions and reshuffle anchors of an UNCHANGED file; pass
50
+ // `previous = undefined` instead and take the content-addressed snapshot path
51
+ // (hash.ts cache), which is deterministic for unchanged content.
39
52
  let previous;
40
- if (servedForNorm.some((h) => h !== null)) {
53
+ if (servedForNorm.every((h) => h !== null)) {
41
54
  const filteredHashes = [];
42
55
  const filteredCanons = [];
43
56
  for (let i = 0; i < servedForNorm.length; i++) {
@@ -69,6 +82,7 @@ export async function readAndServe(io, rawPath, cwd, options) {
69
82
  encoding: options.encoding,
70
83
  offset: options.offset,
71
84
  limit: options.limit,
85
+ windows: options.windows,
72
86
  signal,
73
87
  reservedHashes: reservations.reservedHashes,
74
88
  retiredHashes: reservations.retiredHashes,
@@ -77,7 +91,7 @@ export async function readAndServe(io, rawPath, cwd, options) {
77
91
  }
78
92
  catch (e) {
79
93
  if (e instanceof AnchorSpaceExhaustedError ||
80
- (e instanceof Error && e.message.includes("E_ANCHOR_SPACE_EXHAUSTED"))) {
94
+ (e instanceof Error && e.message.includes("probing failed over"))) {
81
95
  const retiredCount = retiredHashes.size;
82
96
  const servedCount = servedForNorm.filter((h) => h !== null).length;
83
97
  const reservedCount = retiredCount + servedCount;
@@ -88,10 +102,16 @@ export async function readAndServe(io, rawPath, cwd, options) {
88
102
  try {
89
103
  store.clearCards(sessionKey, absolutePath);
90
104
  }
91
- catch { }
105
+ catch {
106
+ // Best-effort: card state is a cache; the promotion retry below proceeds without it.
107
+ }
92
108
  }
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.`;
109
+ catch {
110
+ // Best-effort: a store fault here must not fail the read — the retry proceeds on the
111
+ // in-memory reservation state (ADR-0020 R2, promotion/wipe arm).
112
+ }
113
+ // Soft promotion notice: plain non-header text (no [E_] code, no audience).
114
+ promotionWarning = `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
115
  // Retry ignoring retired (served only) — also drop removedHashes from previous
96
116
  retiredHashes = new Set();
97
117
  reservedHashes = new Set([...servedForNorm.filter((h) => h !== null)]);
@@ -102,6 +122,7 @@ export async function readAndServe(io, rawPath, cwd, options) {
102
122
  encoding: options.encoding,
103
123
  offset: options.offset,
104
124
  limit: options.limit,
125
+ windows: options.windows,
105
126
  signal,
106
127
  reservedHashes: reservations.reservedHashes,
107
128
  retiredHashes: reservations.retiredHashes,
@@ -112,30 +133,29 @@ export async function readAndServe(io, rawPath, cwd, options) {
112
133
  throw e;
113
134
  }
114
135
  }
136
+ let servedLanded = true;
115
137
  if (view.served.length > 0) {
116
138
  const canons = splitLines(view.normalized).map((l) => canon(l));
117
139
  const canonServed = canons.map((canonText) => canonText);
118
- // For full read, compute snapshotId
119
- let snapshotId;
120
- try {
121
- snapshotId = (await fileSnap(view.absolutePath)).snapshotId;
122
- }
123
- catch { }
124
140
  // Pad or trim canons to served length? For now use canons for full file
125
141
  const fullCanons = [];
126
142
  for (let i = 0; i < view.hashes.length; i++) {
127
143
  fullCanons.push(canons[i] ?? null);
128
144
  }
129
- await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length, {
145
+ servedLanded = await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length, {
130
146
  hashes: view.hashes,
131
147
  canons: fullCanons,
132
- snapshotId,
148
+ content: view.normalized,
133
149
  });
134
150
  }
135
151
  // #69: epoch lifecycle belongs to full reads — a partial (paged or
136
152
  // 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;
153
+ // drift-reported marks; only a full read resets them. The `undefined`/`[]` →
154
+ // no-windows rule is owned by file-view's `hasRequestedWindows`.
155
+ const isFullRead = options.offset === undefined &&
156
+ options.limit === undefined &&
157
+ !hasRequestedWindows(options.windows) &&
158
+ !view.truncation?.truncated;
139
159
  if (isFullRead)
140
160
  await clearDriftReported(sessionKey, view.absolutePath);
141
161
  const autoFooter = getAutoGuessFooter(view.absolutePath) ??
@@ -148,7 +168,11 @@ export async function readAndServe(io, rawPath, cwd, options) {
148
168
  ? `${promotionWarning}\n${autoWarning}`
149
169
  : promotionWarning
150
170
  : autoWarning;
151
- const text = view.hadUtf8DecodeErrors ? `${view.text}\n\n${UTF8_REWRITE_NOTE}` : view.text;
171
+ const baseText = view.hadUtf8DecodeErrors ? `${view.text}\n\n${UTF8_REWRITE_NOTE}` : view.text;
172
+ // The serve write is a second unit: a fault there must not fail the read, but it does decide
173
+ // whether the anchors above are usable — so the claim is downgraded in the one channel both
174
+ // consumers render.
175
+ const text = servedLanded ? baseText : `${baseText}\n\n${SERVE_NOT_RECORDED_NOTE}`;
152
176
  return {
153
177
  text,
154
178
  served: view.served,
package/lib/sandbox.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * The sandbox-escalation API for the hashline mutating tools, mirroring
3
3
  * `@deepseek-ai/dsh-tool-fs`'s `FsSandboxController` (same vocabulary, same
4
4
  * fail-closed approval sequence, shared `@deepseek-ai/dsh-sandbox` pieces) so
5
- * `edit`/`batch_edit`/`undo_last_edit` escalate exactly like the built-in
5
+ * `edit`/`undo_last_edit` escalate exactly like the built-in
6
6
  * `write`/`edit` — and, critically, stamp the per-call policy with the SESSION
7
7
  * workspace root. Without the policy the sandbox backend falls back to the
8
8
  * deployment default root, so an edit inside the session workspace is denied