dsh-better-edit 0.8.2 → 1.1.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 (79) hide show
  1. package/CHANGELOG.md +173 -99
  2. package/README.md +61 -33
  3. package/README.zh.md +20 -17
  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/guidance/materialize.js +7 -7
  13. package/lib/guidance/resolve.js +13 -8
  14. package/lib/hash-store.js +404 -278
  15. package/lib/hashline/anchor-pipeline.js +586 -378
  16. package/lib/hashline/hash-assign.js +21 -22
  17. package/lib/hashline/hash.js +6 -6
  18. package/lib/hashline/index.js +1 -1
  19. package/lib/hashline/resolve.js +1 -1
  20. package/lib/hashline/served-guard.js +181 -0
  21. package/lib/index.js +37 -11
  22. package/lib/mutation/engine.js +392 -96
  23. package/lib/mutation.js +22 -130
  24. package/lib/noop-guard.js +20 -9
  25. package/lib/prompts.js +20 -18
  26. package/lib/read-and-serve.js +44 -20
  27. package/lib/sandbox.js +1 -1
  28. package/lib/session-view.js +57 -43
  29. package/lib/snapshot-store/index.js +97 -0
  30. package/lib/snapshot-store/lineage-store.js +400 -0
  31. package/lib/snapshot-store/migrate.js +80 -0
  32. package/lib/snapshot-store/pairing.js +412 -0
  33. package/lib/snapshot-store/txn.js +63 -0
  34. package/lib/snapshot-store/vacuum.js +243 -0
  35. package/lib/store-lifecycle.js +13 -1
  36. package/lib/store-retry.js +34 -0
  37. package/lib/tool-edit.js +90 -44
  38. package/lib/tool-read.js +29 -1
  39. package/lib/tool-str-replace-editor.js +26 -18
  40. package/lib/tool-undo.js +25 -8
  41. package/lib/types/constants.d.ts +5 -2
  42. package/lib/types/contract.d.ts +76 -71
  43. package/lib/types/domain-errors.d.ts +410 -0
  44. package/lib/types/edit-response.d.ts +1 -1
  45. package/lib/types/file-encoding-state.d.ts +1 -0
  46. package/lib/types/file-view.d.ts +35 -6
  47. package/lib/types/guidance/materialize.d.ts +2 -2
  48. package/lib/types/guidance/resolve.d.ts +14 -2
  49. package/lib/types/hash-store.d.ts +38 -19
  50. package/lib/types/hashline/anchor-pipeline.d.ts +117 -36
  51. package/lib/types/hashline/hash-assign.d.ts +5 -5
  52. package/lib/types/hashline/hash.d.ts +1 -1
  53. package/lib/types/hashline/index.d.ts +2 -2
  54. package/lib/types/hashline/served-guard.d.ts +100 -0
  55. package/lib/types/index.d.ts +3 -3
  56. package/lib/types/mutation/engine.d.ts +49 -30
  57. package/lib/types/mutation.d.ts +1 -39
  58. package/lib/types/noop-guard.d.ts +4 -4
  59. package/lib/types/prompts.d.ts +1 -1
  60. package/lib/types/read-and-serve.d.ts +6 -0
  61. package/lib/types/sandbox.d.ts +1 -1
  62. package/lib/types/session-view.d.ts +38 -9
  63. package/lib/types/snapshot-store/index.d.ts +28 -0
  64. package/lib/types/snapshot-store/lineage-store.d.ts +96 -0
  65. package/lib/types/snapshot-store/migrate.d.ts +16 -0
  66. package/lib/types/snapshot-store/pairing.d.ts +99 -0
  67. package/lib/types/snapshot-store/txn.d.ts +12 -0
  68. package/lib/types/snapshot-store/vacuum.d.ts +79 -0
  69. package/lib/types/store-lifecycle.d.ts +0 -1
  70. package/lib/types/store-retry.d.ts +6 -0
  71. package/lib/types/tool-edit.d.ts +2 -2
  72. package/lib/types/tool-str-replace-editor.d.ts +2 -2
  73. package/lib/types/utils.d.ts +5 -6
  74. package/lib/types/workspace-context.d.ts +10 -1
  75. package/lib/undo-edit.js +27 -11
  76. package/lib/utils.js +12 -12
  77. package/lib/workspace-context.js +27 -9
  78. package/lib/write-hook.js +13 -4
  79. package/package.json +28 -30
@@ -0,0 +1,570 @@
1
+ /**
2
+ * Domain error registry — the closed, type-safe contract for every
3
+ * model-facing diagnostic. Zero dependencies: no imports, so any seam can
4
+ * throw without wiring a store, session, or hasher.
5
+ *
6
+ * INVARIANT (the point of this module): a code is never declared without a
7
+ * producer. Every `DomainErrorCode` member must have at least one
8
+ * `new DomainError(code, …)` / `formatError(code, …)` producer in src/
9
+ * (subclass constructions `new EditHashEchoError` / `new BadAnchorError` /
10
+ * `new AnchorMismatchError("E_STALE_ANCHOR", …)` /
11
+ * `new ServedRejectionError({ code, … })` /
12
+ * `new AnchorSpaceExhaustedError(…)` count as producers of their code), or be
13
+ * listed in `DEFERRED_PRODUCERS`, and every code passed at a producer site
14
+ * must be a union member. Asserted BOTH directions in
15
+ * test/arch/domain-error-registry.test.ts. This is what makes the registry a
16
+ * contract instead of a list.
17
+ *
18
+ * COUNT DEVIATION (F4, ratified): this registry's E_* vocabulary is larger
19
+ * than upstream's 19. Upstream has no str_replace_editor shadow; the six
20
+ * shadow codes (E_BLIND_REPLACE, E_UNSUPPORTED, E_BAD_COMMAND, E_FILE_EXISTS,
21
+ * E_NO_MATCH, E_AMBIGUOUS_MATCH) are live model-facing contract per accepted
22
+ * ADR-0015, and E_UNSERVED_RANGE is live contract too (T4 declined its
23
+ * retirement — its producers are reachable, CP1 H1 → `SR@790`). A closed
24
+ * vocabulary that omits live codes is not closed — it just pushes them
25
+ * outside the contract (T4 also deleted four declarations that had no local
26
+ * producer at all; see `DEFERRED_PRODUCERS`).
27
+ * WHY payloads carry facts, not pre-baked strings: the producer already holds
28
+ * the evidence (line numbers, hashes, paths, counts), so the registry owns the
29
+ * neutral sentence and the producer passes values. The one deliberate
30
+ * exception is `E_BAD_PAYLOAD`, whose payload is `{ message }` rendered
31
+ * verbatim — admission-boundary rejections are too heterogeneous for a fixed
32
+ * shape, and the message is the fact.
33
+ *
34
+ * WHY a remedy clause may appear only when it is helpful, unharmful and
35
+ * fail-closed, AND the evidence pins a single cause. When the intent is
36
+ * ambiguous the payload states the fact and carries NO remedy, because an
37
+ * intent-guessing suggestion steers the model's next action. Remedy-free by
38
+ * rule (no `remedy` field on the registry entry):
39
+ * - `E_UNKNOWN`: no cause is knowable at all.
40
+ * - `E_NOOP_LOOP`: the refusal's evidence pins the fact (the range already
41
+ * contains the text) but not the model's intent, so a remedy clause would
42
+ * dress a status fact as an action.
43
+ *
44
+ * WHY `remedy` is declaration-only and never rendered into the message: the
45
+ * `format` strings already carry their own retry prose where the evidence pins
46
+ * it. Do not "fix" this by appending `remedy` to the rendered text. The
47
+ * declaration is owned by `DECLARATION_ONLY_FIELDS` below, which the arch oracle
48
+ * pins by identity AND checks for readers (0 today) — so it cannot rot quietly.
49
+ *
50
+ * @module dsh-better-edit/domain-errors
51
+ */
52
+ // WHY: the `Retry with these anchors (no read needed).` affordance was deleted by T6. It was
53
+ // WHY: unreachable from production (every producer set `reread: true`), and its premise was
54
+ // WHY: false: the echoed rows are the current file's anchors, not serves, so a retry with them
55
+ // WHY: rejects at the same site. The retry affordance a payload carries is its rows.
56
+ // WHY: 3-char is the hashline anchor width; this module stays zero-dependency
57
+ // WHY: so the width is stated, never imported.
58
+ const ANCHOR_WIDTH = 3;
59
+ function suspiciousSubmission(count) {
60
+ if (count === undefined)
61
+ return "";
62
+ const submitted = `(submission ${count}×)`;
63
+ if (count < 2)
64
+ return ` Nothing was written. ${submitted}`;
65
+ return (` Nothing was written. ${submitted}` +
66
+ ` Identical refusal submitted ${count}× — the bytes still reproduce a served row.` +
67
+ ` Omit the copied anchors from \`replace_with\` and retry with the same anchors, or declare intent with mode: "literal".`);
68
+ }
69
+ function suspiciousFormat(payload) {
70
+ if (payload.target === "write") {
71
+ return (`Refused write to ${payload.path}: line ${payload.line} begins with ` +
72
+ `the exact ${payload.hash}│ anchor served for this session, path, and line ${payload.servedLine}. ` +
73
+ `HASH│ anchors are tool output, not file content. ` +
74
+ // F2: the built-in write tool takes no mode flag, so the write arm
75
+ // must not promise a literal retry — file content only.
76
+ `Retry with file content only (remove the entire copied anchor chain). ` +
77
+ `Re-read the file for fresh anchors if needed.` +
78
+ suspiciousSubmission(payload.count));
79
+ }
80
+ return (`Refused edit to ${payload.path}: replacement line ${payload.line} begins with ` +
81
+ `the exact ${payload.hash}│ anchor served for this session, path, and line ${payload.servedLine}. ` +
82
+ `HASH│ anchors are tool output, not file content. ` +
83
+ `Omit the copied anchors from \`replace_with\` and retry with the same anchors, or declare intent with mode: "literal". ` +
84
+ `Re-read the file for fresh anchors if needed.` +
85
+ suspiciousSubmission(payload.count));
86
+ }
87
+ function unsupportedFormat(payload) {
88
+ if (payload.kind === "directory") {
89
+ return (`Path is a directory: ${payload.path}. Pass the text file inside it ` +
90
+ `(a file, never a directory) in "file" and retry.`);
91
+ }
92
+ if (payload.kind === "image") {
93
+ return (`Path is an image file: ${payload.path}. Hashline edit only supports text files; ` +
94
+ `choose a text file and retry.`);
95
+ }
96
+ return (`Path is a binary file: ${payload.path} (${payload.description ?? "binary"}). ` +
97
+ `Hashline edit only supports text files; choose a text file and retry.`);
98
+ }
99
+ function accessFormat(payload) {
100
+ if (payload.kind === "symlink-loop") {
101
+ return (`Too many symbolic links while resolving: ${payload.path}. ` +
102
+ `Retry with the real file location.`);
103
+ }
104
+ if (payload.kind === "unreachable") {
105
+ return (`Cannot access file: ${payload.path}. Verify the "file" value exists and is reachable, ` +
106
+ `then retry.`);
107
+ }
108
+ const label = payload.access === "write" ? "not writable" : "not readable";
109
+ return `File is ${label}: ${payload.path}. Fix permissions or choose a writable file and retry.`;
110
+ }
111
+ function largeFileFormat(payload) {
112
+ if (payload.limitKind === "hash-space") {
113
+ return (`Cannot allocate a unique hash anchor: the file exceeds the ${payload.limit}-line limit ` +
114
+ `for ${ANCHOR_WIDTH}-char hashline anchors. For very large files use write or a non-line-based approach.`);
115
+ }
116
+ const observed = payload.lineCount === undefined ? `more than ${payload.limit}` : `${payload.lineCount}`;
117
+ const where = payload.path ?? "the file";
118
+ return (`${where} has ${observed} lines, exceeding the ${payload.limit}-line edit limit. ` +
119
+ `Hashline editing targets source-sized files; for very large files use write or a non-line-based approach.`);
120
+ }
121
+ function staleAnchorFormat(payload) {
122
+ // F6: stale anchors carry their context block directly — no `Current
123
+ // range:` heading and no retry hint. The headline already says "Re-read
124
+ // for fresh anchors"; appending "Retry with these anchors" would
125
+ // contradict it in the same breath.
126
+ if (!payload.servedBlock)
127
+ return payload.headline;
128
+ return `${payload.headline}\n\n${payload.servedBlock}`;
129
+ }
130
+ function staleRangeFormat(payload) {
131
+ // F7: the `Current range:` heading exists only when there are rows to
132
+ // show; a row-less rejection (e.g. the version-guard arm) renders the
133
+ // headline alone; the payload's rows are its retry affordance.
134
+ if (!payload.servedBlock)
135
+ return payload.headline;
136
+ return `${payload.headline}\nCurrent range:\n${payload.servedBlock}`;
137
+ }
138
+ function blindReplaceFormat(payload) {
139
+ if (payload.command === "str_replace_editor") {
140
+ return (`str_replace_editor: ${payload.path} has not been viewed in this session ` +
141
+ `(no file encoding state at the current version). Call view first, then retry. Nothing was written.`);
142
+ }
143
+ return (`${payload.path} has not been observed in this session (read-before-write policy). ` +
144
+ `Call read() first, then retry the edit.`);
145
+ }
146
+ function unservedRangeFormat(payload) {
147
+ // F7: heading only when rows exist; one rule for both range codes.
148
+ if (!payload.servedBlock)
149
+ return payload.headline;
150
+ return `${payload.headline}\nCurrent range:\n${payload.servedBlock}`;
151
+ }
152
+ // WHY: an all-digit anchor is shape evidence pinned to the anchor string itself
153
+ // (upstream ADR-0021 decision 4) — not a guess about path versus session — so the note
154
+ // states the shape fact in declarative terms. No imperative, no remedy field.
155
+ const NUMERIC_ANCHOR_RE = /^\d+$/;
156
+ export function numericAnchorNote(anchors) {
157
+ const numeric = anchors.filter((anchor) => NUMERIC_ANCHOR_RE.test(anchor));
158
+ if (numeric.length === 0)
159
+ return "";
160
+ const quoted = numeric.map((anchor) => `"${anchor}"`).join(", ");
161
+ const noun = numeric.length === 1 ? `anchor ${quoted}` : `anchors ${quoted}`;
162
+ const verb = numeric.length === 1 ? "consists" : "consist";
163
+ const resemblance = numeric.length === 1 ? "resembles a line number" : "resemble line numbers";
164
+ return (` Note: ${noun} ${verb} only of digits and ${resemblance}. ` +
165
+ `Edit anchors are 3-character alphanumeric content hashes (e.g. "aB3") served by the read tool, not line numbers.`);
166
+ }
167
+ /** SAFETY: exact heading for an unverified fresh-read serve — machine-checkable. */
168
+ export const FRESH_READ_HEADING = "Current range (fresh read):";
169
+ /** SAFETY: one general headline clause for an unplaceable bound — no narration. */
170
+ export const UNVERIFIED_HEADLINE = "a bound of this range no longer resolves to the line identity it was served with.";
171
+ /** SAFETY: recovery sentence for a target-lost rejection — the only retry is a read. */
172
+ export const TARGET_LOST_RECOVERY = "The line you targeted was deleted or replaced; your anchors describe a version of this file that no longer exists. Read the file and re-target.";
173
+ function unknownAnchorFormat(payload) {
174
+ const anchors = payload.anchors;
175
+ if (anchors.length === 1) {
176
+ return `${payload.path} has not served the anchor "${anchors[0]}"; nothing was written.${numericAnchorNote(anchors)}`;
177
+ }
178
+ if (anchors.length === 0) {
179
+ return `${payload.path} has not served an anchor; nothing was written.`;
180
+ }
181
+ return `${payload.path} has not served the anchors ${anchors.map((a) => `"${a}"`).join(", ")}; nothing was written.${numericAnchorNote(anchors)}`;
182
+ }
183
+ function foreignHomesDisplay(homes) {
184
+ if (homes.length <= 3)
185
+ return homes.join(", ");
186
+ return `${homes.slice(0, 3).join(", ")} and ${homes.length - 3} more`;
187
+ }
188
+ function foreignAnchorFormat(payload) {
189
+ const anchors = payload.anchors;
190
+ const noun = anchors.length === 1
191
+ ? `the anchor "${anchors[0]}"`
192
+ : `the anchors ${anchors.map((a) => `"${a}"`).join(", ")}`;
193
+ const verb = anchors.length === 1 ? "is" : "are";
194
+ const homes = foreignHomesDisplay(payload.homes);
195
+ if (homes.length === 0) {
196
+ return `${noun} ${verb} inconsistent with ${payload.path}; nothing was written.`;
197
+ }
198
+ return `${noun} ${verb} inconsistent with ${payload.path}; served for ${homes}; nothing was written.`;
199
+ }
200
+ const BATCH_ATOMICITY_TRAILER = "The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied.";
201
+ function batchAbortFormat(payload) {
202
+ // C: several failures name every failing item in order (one resubmission
203
+ // fixes them all); each item keeps its own `[E_*]` inline in `inner`.
204
+ if (payload.failures !== undefined && payload.failures.length > 1) {
205
+ const parts = payload.failures.map((f) => `edits[${f.index}] (${payload.path}) failed: ${f.inner}`);
206
+ return (`${parts.join("; ")}\n${BATCH_ATOMICITY_TRAILER} ` +
207
+ "Fix the failing edits (and any later edits that depend on them), then resubmit the batch.");
208
+ }
209
+ const base = `edits[${payload.index}] (${payload.path}) failed: ${payload.inner}\n${payload.echoBlock.trimStart()}\n` +
210
+ BATCH_ATOMICITY_TRAILER;
211
+ // WHY: echoBlock is empty exactly when no range context exists (non-anchor
212
+ // WHY: failures carry no echo), and only a ranged failure can name the edit
213
+ // WHY: to fix — so the merge hint rides on the same condition.
214
+ if (!payload.echoBlock)
215
+ return base;
216
+ return `${base} Fix the failing edit (and any later edit that depends on it), then resubmit the batch.`;
217
+ }
218
+ function noopLoopFormat(payload) {
219
+ // WHY batch first: the batch ref already names the item (edits[i] (path)),
220
+ // so the batch arm renders from ref and appends the on-disk range when the
221
+ // engine supplies one; the path arm is the engine single-edit flavor.
222
+ if (payload.batch) {
223
+ return (`${payload.ref}: identical edit (${payload.anchorFrom} → ${payload.anchorTo}) submitted ${payload.count}×, no changes each time. ` +
224
+ `Range already contains this text; resend will reject the batch.` +
225
+ (payload.servedBlock ? `\nCurrent on-disk range:\n${payload.servedBlock}` : ""));
226
+ }
227
+ if (payload.path !== undefined) {
228
+ return (`identical edit (${payload.anchorFrom} → ${payload.anchorTo} in ${payload.path}) submitted ${payload.count}×, no changes each time. ` +
229
+ `Range already contains this text; resend will reject. Current range:\n${payload.servedBlock}`);
230
+ }
231
+ return (`identical edit (${payload.anchorFrom} → ${payload.anchorTo} ${payload.ref}) submitted ${payload.count}×, no changes each time. ` +
232
+ `Range already contains this text; resend will reject.`);
233
+ }
234
+ export const ERROR_REGISTRY = {
235
+ E_BAD_PAYLOAD: {
236
+ audience: "MODEL",
237
+ format: ({ message }) => message,
238
+ },
239
+ E_EMPTY_RANGE: {
240
+ audience: "MODEL",
241
+ format: () => "Cannot empty a non-empty file via edit. Use `write` if you need to clear the file.",
242
+ // WHY remedy: the resolved edit empties a non-empty file, so clearing belongs to write.
243
+ remedy: "Use write to clear the file.",
244
+ },
245
+ E_STALE_ANCHOR: {
246
+ audience: "MODEL",
247
+ format: staleAnchorFormat,
248
+ // WHY remedy: the anchors did not resolve against the current file (unresolved or
249
+ // ambiguous in `valEdit`), and context rows are shown only when one anchor resolved —
250
+ // so the only fail-closed recovery is a read.
251
+ remedy: "Read the file again for fresh anchors, then retry.",
252
+ },
253
+ E_UNKNOWN_ANCHOR: {
254
+ audience: "MODEL",
255
+ format: unknownAnchorFormat,
256
+ },
257
+ E_FOREIGN_ANCHOR: {
258
+ audience: "MODEL",
259
+ format: foreignAnchorFormat,
260
+ },
261
+ E_STALE_RANGE: {
262
+ audience: "MODEL",
263
+ format: staleRangeFormat,
264
+ },
265
+ E_TARGET_LOST: {
266
+ audience: "MODEL",
267
+ format: ({ servedLine, path }) => `line ${servedLine}${path ? ` in ${path}` : ""} no longer resolves to the line identity it was served with.\n${TARGET_LOST_RECOVERY}`,
268
+ // WHY remedy: the leased identity is gone with no surviving window to serve — servedLine
269
+ // names the dead line, so recovery is a read (upstream b92e0ec:src/domain-errors.ts:381).
270
+ remedy: "Read the file and re-target.",
271
+ },
272
+ E_UNVERIFIED_RANGE: {
273
+ audience: "MODEL",
274
+ format: ({ servedBlock }) => `${UNVERIFIED_HEADLINE}\n${FRESH_READ_HEADING}\n${servedBlock}`,
275
+ },
276
+ E_MALFORMED_ANCHOR: {
277
+ audience: "MODEL",
278
+ format: ({ rawAnchor, reason }) => `Invalid anchor "${rawAnchor}": ${reason}`,
279
+ // WHY remedy: the parse rejected the token before any resolution — rawAnchor and reason name the shape failure.
280
+ remedy: "Pass the bare 3-char anchor and retry.",
281
+ },
282
+ E_SUSPICIOUS_TEXT: {
283
+ audience: "MODEL",
284
+ format: suspiciousFormat,
285
+ // WHY remedy: the replacement reproduces a served hash echo for this session, path and line — target, hash and servedLine pin the row.
286
+ // F2/F10.4: no mode:"literal" promise here — the built-in write tool
287
+ // takes no mode flag, so the declared remedy stays truthful for both targets.
288
+ remedy: "Omit the copied anchors and retry with the same anchors.",
289
+ },
290
+ E_BATCH_ABORT: {
291
+ audience: "MODEL",
292
+ format: batchAbortFormat,
293
+ // WHY remedy: the item index and path pin the failing edit of the rejected batch.
294
+ remedy: "Fix the failing edit, then resubmit the batch.",
295
+ },
296
+ E_NOOP_LOOP: {
297
+ audience: "MODEL",
298
+ format: noopLoopFormat,
299
+ },
300
+ E_UNSUPPORTED_FILE: {
301
+ audience: "MODEL",
302
+ format: unsupportedFormat,
303
+ // WHY remedy: detection classified the target — kind (directory, binary or image) proves it is not an editable text file.
304
+ remedy: "Choose a text file and retry.",
305
+ },
306
+ E_ACCESS: {
307
+ audience: "MODEL",
308
+ format: accessFormat,
309
+ },
310
+ E_NOT_FOUND: {
311
+ audience: "MODEL",
312
+ format: ({ path }) => `File not found: ${path}. Check the "file" value (a text file, never a directory); ` +
313
+ `use ls on the parent directory and retry with the corrected file.`,
314
+ // WHY remedy: the filesystem answered not-found — path names a file that does not exist to edit.
315
+ remedy: "Use ls on the parent directory and retry with the corrected file.",
316
+ },
317
+ E_UNDO_STALE: {
318
+ audience: "MODEL",
319
+ format: ({ path, reason }) => reason === "deleted"
320
+ ? `cannot undo on ${path}: file no longer exists.`
321
+ : `cannot undo on ${path}: file modified after edit — undo would overwrite changes.`,
322
+ },
323
+ E_UNDO_NOT_RECORDED: {
324
+ audience: "MODEL",
325
+ format: ({ path }) => `Reverted ${path} on disk, but the hash store could not record the revert — the previous ` +
326
+ `undo history is still in place and the stored snapshot still describes the pre-revert file. ` +
327
+ `The file no longer matches the recorded post-edit content, so the next undo_last_edit ` +
328
+ `clears that history as stale.`,
329
+ // WHY remedy: the file is already reverted and the pair is intact; the next undo reconciles
330
+ // the pair against the reverted file and terminates, so no store repair is required.
331
+ remedy: "Re-read the file; the next undo_last_edit will clear the stale history.",
332
+ },
333
+ E_UNDO_UNAVAILABLE: {
334
+ audience: "MODEL",
335
+ format: ({ path, batch }) => batch === true
336
+ ? `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.`
337
+ : `Cannot persist undo history to the hash store; the edit was NOT applied and ${path} is unchanged. ` +
338
+ `Retry the edit, or use write if the store cannot be recovered.`,
339
+ // WHY remedy: the hash store persist failed with the edit unapplied and the file unchanged, so retrying the edit is safe.
340
+ remedy: "Retry the edit.",
341
+ },
342
+ E_UNKNOWN: {
343
+ audience: "MODEL",
344
+ format: ({ errorName, message }) => `unexpected ${errorName}: ${message.split("\n")[0].slice(0, 300)}`,
345
+ },
346
+ E_LARGE_FILE: {
347
+ audience: "MODEL",
348
+ format: largeFileFormat,
349
+ // WHY remedy: the named limit was exceeded — limitKind (lines with lineCount, or hash-space) and limit pin the capacity.
350
+ remedy: "Use write or a non-line-based approach for very large files.",
351
+ },
352
+ E_UNSERVED_RANGE: {
353
+ audience: "MODEL",
354
+ format: unservedRangeFormat,
355
+ },
356
+ E_BLIND_REPLACE: {
357
+ audience: "MODEL",
358
+ format: blindReplaceFormat,
359
+ },
360
+ E_UNSUPPORTED: {
361
+ audience: "MODEL",
362
+ format: ({ command }) => `str_replace_editor ${command} is not implemented — use undo_last_edit.`,
363
+ },
364
+ E_BAD_COMMAND: {
365
+ audience: "MODEL",
366
+ format: ({ command }) => `str_replace_editor: unknown command ${JSON.stringify(command)} — expected one of view, str_replace, insert, create, undo_edit.`,
367
+ },
368
+ E_FILE_EXISTS: {
369
+ audience: "MODEL",
370
+ format: ({ path }) => `str_replace_editor: cannot create ${path} — file already exists.`,
371
+ },
372
+ E_NO_MATCH: {
373
+ audience: "MODEL",
374
+ format: ({ path }) => `str_replace_editor: old_str not found in ${path}. Nothing was written.`,
375
+ },
376
+ E_AMBIGUOUS_MATCH: {
377
+ audience: "MODEL",
378
+ format: ({ path, matches }) => `str_replace_editor: old_str has multiple matches (${matches}) in ${path} — must match exactly once. Narrow old_str with more context. Nothing was written.`,
379
+ },
380
+ E_STORE_NEWER_VERSION: {
381
+ audience: "MODEL",
382
+ format: ({ path, storedVersion, supportedVersion }) => `The hash store at ${path} was written by a newer dsh-better-edit (store schema ${storedVersion}; this build supports ${supportedVersion}). Nothing was written — this build refuses to touch a newer store. Upgrade dsh-better-edit to the newer version, or point the store at a different directory.`,
383
+ // WHY remedy: the stamp proves a newer writer owns the file and this build cannot read it — upgrade or retarget pins the recovery.
384
+ remedy: "Upgrade dsh-better-edit to the newer version, or point the store at a different directory.",
385
+ },
386
+ };
387
+ function neverServedShapeFormat(payload) {
388
+ if (payload.count === 1) {
389
+ return ("1 replacement line opens with an anchor-shaped token " +
390
+ "never served for this session and file. Applied verbatim.");
391
+ }
392
+ return (`${payload.count} replacement lines open with anchor-shaped tokens ` +
393
+ "never served for this session and file. Applied verbatim.");
394
+ }
395
+ function servedPrefixMismatchFormat(payload) {
396
+ return (`Line ${payload.k} begins with the exact ${payload.anchor}│ anchor ` +
397
+ `served for this session and file for line ${payload.servedLine}, ` +
398
+ "but its content differs from what was served. Applied verbatim.");
399
+ }
400
+ function noopWarnFormat(payload) {
401
+ if (payload.batch) {
402
+ return (`Notice: ${payload.ref} — identical edit no-op'd twice; ` +
403
+ "range already has this text. Resend will reject the batch.");
404
+ }
405
+ if (payload.path !== undefined) {
406
+ return (`Notice: identical edit (${payload.anchorFrom} → ${payload.anchorTo} in ${payload.path}) ` +
407
+ "no-op'd twice; range already has this text. Resend will reject.");
408
+ }
409
+ return (`Notice: identical edit (${payload.anchorFrom} → ${payload.anchorTo} ${payload.ref}) ` +
410
+ "no-op'd twice; range already has this text. Resend will reject.");
411
+ }
412
+ export const WARNING_REGISTRY = {
413
+ W_NEVER_SERVED_SHAPE: {
414
+ audience: "MODEL",
415
+ format: neverServedShapeFormat,
416
+ },
417
+ W_SERVED_PREFIX_MISMATCH: {
418
+ audience: "MODEL",
419
+ format: servedPrefixMismatchFormat,
420
+ },
421
+ W_REVERSED_ANCHORS: {
422
+ audience: "USER",
423
+ format: ({ fromHash, toHash }) => `anchor_from/anchor_to were reversed (${fromHash} after ${toHash}); ` +
424
+ "healed and applied with the range swapped.",
425
+ },
426
+ W_UNICODE_LITERAL: {
427
+ audience: "USER",
428
+ format: ({ line }) => `Literal \\uDDDD detected on replacement line ${line}; applied verbatim.`,
429
+ },
430
+ W_LITERAL_BYPASS: {
431
+ audience: "USER",
432
+ format: () => "served-echo check bypassed by literal declaration.",
433
+ },
434
+ W_NOOP: {
435
+ audience: "USER",
436
+ format: noopWarnFormat,
437
+ },
438
+ };
439
+ /**
440
+ * SAFETY: the sole producer of `[W_*]` headers. Renders
441
+ * `[<AUDIENCE>] [<W_CODE>] <neutral-observation>` from the registry, so every
442
+ * applied-tier warning carries its machine-readable code and audience by
443
+ * construction.
444
+ *
445
+ * PURE by contract (T6 CP2, F2): a formatter carries no state. The deferral
446
+ * witnesses below are INJECTED (`AllowlistTrigger.holds(fired)`), never accumulated —
447
+ * a module-global "did it fire?" latch made a guard's verdict depend on whether an
448
+ * earlier test happened to render the warning, so a witness satisfiable by another
449
+ * test's side effect proved nothing about the guard that consumed it. The witness is
450
+ * derived by the test layer from a source scan (`test/support/arch-scan.ts`,
451
+ * `firedWarnings`) — a READ, so the verdict is a pure function of the tree and cannot
452
+ * depend on evaluation order or on a test-only reset hook.
453
+ */
454
+ export function formatWarning(code, payload) {
455
+ const spec = WARNING_REGISTRY[code];
456
+ return `[${spec.audience}] [${code}] ${spec.format(payload)}`;
457
+ }
458
+ /**
459
+ * SAFETY: the sole composer of `[TO <AUDIENCE>] [<E_CODE>]` prefixes for errors.
460
+ * `DomainError` delegates here, so header construction has exactly one site.
461
+ */
462
+ export function formatError(code, payload) {
463
+ const spec = ERROR_REGISTRY[code];
464
+ return `[TO ${spec.audience}] [${code}] ${spec.format(payload)}`;
465
+ }
466
+ export class DomainError extends Error {
467
+ code;
468
+ audience;
469
+ payload;
470
+ servedRows;
471
+ servedBlock;
472
+ cause;
473
+ firstOffendingLine;
474
+ details;
475
+ constructor(code, payload) {
476
+ super(formatError(code, payload));
477
+ this.name = "DomainError";
478
+ this.code = code;
479
+ this.audience = ERROR_REGISTRY[code].audience;
480
+ this.payload = payload;
481
+ const fields = payload;
482
+ this.servedRows = fields.servedRows ?? [];
483
+ this.servedBlock = fields.servedBlock ?? "";
484
+ if (fields.cause !== undefined)
485
+ this.cause = fields.cause;
486
+ if (fields.firstOffendingLine !== undefined) {
487
+ this.firstOffendingLine = fields.firstOffendingLine;
488
+ }
489
+ this.details = {
490
+ code,
491
+ ...(fields.cause !== undefined ? { cause: fields.cause } : {}),
492
+ };
493
+ }
494
+ }
495
+ // WHY: only registry members route the typed path — this guard keeps
496
+ // WHY: errno-style codes (ENOENT, EACCES) and unknown strings out of the
497
+ // WHY: domain contract. The `E_` prefix plus registry membership check means
498
+ // WHY: errno codes without an underscore after E (ENOENT, EACCES, EPERM,
499
+ // WHY: ELOOP) can never match, and underscored non-members fail the lookup.
500
+ export function isDomainErrorCode(code) {
501
+ return typeof code === "string" && code.startsWith("E_") && code in ERROR_REGISTRY;
502
+ }
503
+ /** Warning analogue of `isDomainErrorCode`: only registry members qualify. */
504
+ export function isDomainWarningCode(code) {
505
+ return typeof code === "string" && code.startsWith("W_") && code in WARNING_REGISTRY;
506
+ }
507
+ /** Owners and trigger texts must start with one of these addressable forms. */
508
+ export const ADDRESSABLE_OWNER_RE = /^(#\d{1,5}|Q-T\d+|absorb\/[a-z0-9-]+|src\/[a-z0-9./-]+)\b/;
509
+ /**
510
+ * Registry fields that are declared but never rendered, keyed by field name.
511
+ * `owner`/`trigger` are identities (see `AllowlistEntry`); the arch oracle pins
512
+ * this map by identity against its own copy **and** independently computes the
513
+ * "still declaration-only" predicate (0 readers of `.<field>` across `src/`).
514
+ */
515
+ export const DECLARATION_ONLY_FIELDS = {
516
+ remedy: {
517
+ owner: "src/domain-errors.ts",
518
+ trigger: {
519
+ text: "src/domain-errors.ts",
520
+ holds: () => Object.values(ERROR_REGISTRY).some((spec) => "remedy" in spec),
521
+ },
522
+ },
523
+ };
524
+ /**
525
+ * Codes declared by the contract but produced by a later ticket. Shrink-only:
526
+ * a code that gains a producer MUST be removed from this map (the arch oracle
527
+ * fails otherwise).
528
+ *
529
+ * Upstream parity is NOT a reason to keep a code nothing can produce — and it
530
+ * is not a reason to hide one either. T4 (CP1-r3) removed four declarations
531
+ * that had zero local producers, zero reachable messages and no nameable local
532
+ * owner. FU-4 (absorb/follow-upstream, upstream `pi-better-edit@b92e0ec`)
533
+ * re-introduced all four WITH their producers — per-code decision: **adopt the
534
+ * upstream diagnostic** (the alternative, mapping onto `E_STALE_RANGE` /
535
+ * `E_UNSERVED_RANGE`, is what ADR-0022 recorded and what this absorb
536
+ * supersedes):
537
+ *
538
+ * | ported upstream diagnostic | upstream producer (pi-better-edit@b92e0ec) | local producer |
539
+ * |---|---|---|
540
+ * | `E_FOREIGN_ANCHOR` | `lease-resolve.ts:116` | `anchor-pipeline.ts` (`throwUnknownOrForeign`, boundary placement) |
541
+ * | `E_UNKNOWN_ANCHOR` | `lease-resolve.ts:118`, `served-verification.ts:745` | `anchor-pipeline.ts` (boundary placement, pre-gate) |
542
+ * | `E_UNVERIFIED_RANGE` | `lease-resolve.ts:186`, `served-verification.ts:187` | `anchor-pipeline.ts` (pre-gate stale-boundary arm) |
543
+ * | `E_TARGET_LOST` | `served-verification.ts:170`, `lease-resolve.ts:196` | `anchor-pipeline.ts` (pre-gate stale-boundary arm) |
544
+ *
545
+ * Their owner is `"upstream absorb"` and their trigger is the absorb that
546
+ * ports the corresponding producer. When that happens, reintroduce the code
547
+ * WITH its producer: the union member is gone, so the port will not compile
548
+ * until the absorber records a per-code decision (adopt the upstream
549
+ * diagnostic, or map it onto `E_STALE_RANGE` / `E_UNSERVED_RANGE` /
550
+ * `E_STALE_ANCHOR`). `docs/absorption-plan.md` ("Debt — T4 …") carries the
551
+ * same record for the next absorb.
552
+ *
553
+ * ── IDENTITY, NOT SHAPE (T4 CP1-r4/r5; T6 R15) ──
554
+ * `owner` and `trigger.text` below are pinned BY IDENTITY in
555
+ * `test/arch/domain-error-registry.test.ts` (C7/C16), so changing one is a
556
+ * deliberate edit that must touch the test — never a silent one. T6 replaced the
557
+ * lane-letter owner (`Q-T6`) with the addressable producer seam, and the
558
+ * `holds: () => isDomainWarningCode(…)` with a predicate over an INJECTED witness:
559
+ * `holds(fired)` is false exactly when a producer for that code is visible to the
560
+ * caller's scan (T6 CP2 F2). Production keeps no state, so the verdict cannot be
561
+ * satisfied by another test's earlier firing — the defect the first form had. The arch
562
+ * oracle derives the witness from source (a read) and recomputes the same producer scan
563
+ * as its independent second referent.
564
+ *
565
+ * FU-5 (absorb/follow-upstream, upstream `pi-better-edit@b92e0ec` §4.7) landed the
566
+ * two deferred `W_*` producers in `src/hashline/served-guard.ts` — per the shrink-only
567
+ * rule above both entries are removed. The map is empty; the mechanism and the
568
+ * identity pins stay for the next deferral.
569
+ */
570
+ export const DEFERRED_PRODUCERS = {};
package/lib/edit-diff.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import * as Diff from "diff";
2
+ import { DIFF_REMOVED_CAP, DIFF_REMOVED_EDGE } from "./constants.js";
2
3
  import { lineHashesPure, ANCHOR_LEN, HASH_SEP } from "./hashline/index.js";
3
4
  export function detectEnding(content) {
4
5
  const lfIdx = content.indexOf("\n");
@@ -33,6 +34,30 @@ function fmtDiffLine(prefix, line, hash) {
33
34
  }
34
35
  const ELLIPSIS_MARKER = Symbol("ellipsis");
35
36
  const isEllipsisMarker = (line) => line === ELLIPSIS_MARKER;
37
+ function formatRemovedLines(displayLines, oldContentHashes, oldLineNum) {
38
+ const rows = [];
39
+ let cursor = oldLineNum;
40
+ const emit = (line) => {
41
+ const hash = oldContentHashes?.[cursor - 1];
42
+ rows.push(fmtDiffLine("-", line, hash));
43
+ cursor++;
44
+ };
45
+ if (displayLines.length <= DIFF_REMOVED_CAP) {
46
+ for (const line of displayLines)
47
+ emit(line);
48
+ return { rows, nextOldLineNum: cursor };
49
+ }
50
+ const omitted = displayLines.length - DIFF_REMOVED_EDGE * 2;
51
+ for (const line of displayLines.slice(0, DIFF_REMOVED_EDGE))
52
+ emit(line);
53
+ // WHY: ADR-0024/D3 — the model sees the deletion's head, tail, and exact size; the omitted rows
54
+ // WHY: still advance the cursor so every later row keeps its exact old line number and hash.
55
+ rows.push(` - ... [${omitted} lines omitted] ...`);
56
+ cursor += omitted;
57
+ for (const line of displayLines.slice(-DIFF_REMOVED_EDGE))
58
+ emit(line);
59
+ return { rows, nextOldLineNum: cursor };
60
+ }
36
61
  export function genDiff(oldContent, newContent, contextLines = 2, newContentHashes, oldContentHashes) {
37
62
  const effectiveNewHashes = newContentHashes ?? lineHashesPure(newContent);
38
63
  const parts = Diff.diffLines(oldContent, newContent);
@@ -51,8 +76,8 @@ export function genDiff(oldContent, newContent, contextLines = 2, newContentHash
51
76
  if (part.added || part.removed) {
52
77
  if (firstChangedLine === undefined)
53
78
  firstChangedLine = newLineNum;
54
- for (let k = 0; k < displayLines.length; k++) {
55
- if (part.added) {
79
+ if (part.added) {
80
+ for (let k = 0; k < displayLines.length; k++) {
56
81
  const hash = effectiveNewHashes[newLineNum - 1];
57
82
  output.push(fmtDiffLine("+", displayLines[k], hash));
58
83
  if (hash !== undefined) {
@@ -60,11 +85,12 @@ export function genDiff(oldContent, newContent, contextLines = 2, newContentHash
60
85
  }
61
86
  newLineNum++;
62
87
  }
63
- else {
64
- const hash = oldContentHashes?.[oldLineNum - 1];
65
- output.push(fmtDiffLine("-", displayLines[k], hash));
66
- oldLineNum++;
67
- }
88
+ }
89
+ else {
90
+ const removed = formatRemovedLines(displayLines, oldContentHashes, oldLineNum);
91
+ for (const row of removed.rows)
92
+ output.push(row);
93
+ oldLineNum = removed.nextOldLineNum;
68
94
  }
69
95
  lastWasChange = true;
70
96
  continue;