dsh-better-edit 0.8.1 → 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 +162 -97
  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 +2 -2
  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 +59 -24
  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 +10 -4
  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
@@ -9,9 +9,14 @@
9
9
  * and never records served state (so it can feed `write` round-trips but
10
10
  * cannot authorize hashline `edit` anchors).
11
11
  * - `str_replace` / `insert` without a prior `view`/`read` fail loud with
12
- * `E_BLIND_REPLACE` — no disk write.
12
+ * `E_BAD_PAYLOAD` (unviewed file) — no disk write.
13
13
  * - `create` defaults to UTF-8 without BOM.
14
- * - `undo_edit` is out of scope → `E_UNSUPPORTED` (use `undo_last_edit`).
14
+ * - `undo_edit` is out of scope → `E_BAD_PAYLOAD` (use `undo_last_edit`).
15
+ *
16
+ * - `create` / `str_replace` / `insert` stamp the per-call sandbox policy from
17
+ * `FsSandboxController` (the calling session's workspace root plus any
18
+ * approved one-shot escalation), matching the built-in and the hashline
19
+ * `edit` / `undo_last_edit` paths; unconfined deployments stamp `undefined`.
15
20
  *
16
21
  * See ADR-0015.
17
22
  * @module dsh-better-edit/tool-str-replace-editor
@@ -23,12 +28,13 @@ import { stripBOM } from "./edit-diff.js";
23
28
  import { renderTextWarning } from "./render-text-warning.js";
24
29
  import { execCwd, withWorkspace } from "./workspace-context.js";
25
30
  import { abortIf, splitLines } from "./utils.js";
31
+ import { DomainError } from "./domain-errors.js";
26
32
  export const STR_REPLACE_EDITOR_DESCRIPTION = "View, create, and edit text files by exact string match. Commands: " +
27
33
  "`view` {path, view_range?} shows 1-indexed lines; `str_replace` {path, old_str, new_str} " +
28
34
  "replaces the unique occurrence of old_str; `insert` {path, insert_line, new_str} inserts " +
29
35
  "new line(s) before insert_line (1-indexed, lines+1 appends); `create` {path, file_text} " +
30
36
  "creates a new file (fails if it exists). str_replace/insert require a prior view of the " +
31
- "file in this session (E_BLIND_REPLACE otherwise). Encoding is governed: non-UTF-8 files " +
37
+ "file in this session (E_BAD_PAYLOAD otherwise). Encoding is governed: non-UTF-8 files " +
32
38
  "decode via auto-guess when enabled, otherwise fail loud with Top-3 candidates.";
33
39
  const KNOWN_COMMANDS = new Set([
34
40
  "view",
@@ -37,13 +43,20 @@ const KNOWN_COMMANDS = new Set([
37
43
  "create",
38
44
  "undo_edit",
39
45
  ]);
40
- function argError(code, message) {
41
- return new Error(`[MODEL] [${code}] ${message}`);
46
+ /**
47
+ * Sole header composer for this tool's true request-shape refusals (bad
48
+ * fields). The six live contract codes (F4) route directly through
49
+ * DomainError with fact payloads — E_BLIND_REPLACE, E_UNSUPPORTED,
50
+ * E_BAD_COMMAND, E_FILE_EXISTS, E_NO_MATCH, E_AMBIGUOUS_MATCH — so the
51
+ * registry owns every header and no second message-building site exists here.
52
+ */
53
+ function argError(message) {
54
+ return new DomainError("E_BAD_PAYLOAD", { message });
42
55
  }
43
56
  function requireString(args, name) {
44
57
  const value = args[name];
45
58
  if (typeof value !== "string" || value.length === 0) {
46
- throw argError("E_BAD_PAYLOAD", `str_replace_editor: "${name}" must be a non-empty string.`);
59
+ throw argError(`str_replace_editor: "${name}" must be a non-empty string.`);
47
60
  }
48
61
  return value;
49
62
  }
@@ -58,7 +71,7 @@ function requireViewRange(args) {
58
71
  value[0] < 1 ||
59
72
  value[1] < 1 ||
60
73
  value[0] > value[1]) {
61
- throw argError("E_BAD_PAYLOAD", 'str_replace_editor: "view_range" must be [start, end] with 1-indexed positive integers and start <= end.');
74
+ throw argError('str_replace_editor: "view_range" must be [start, end] with 1-indexed positive integers and start <= end.');
62
75
  }
63
76
  return [value[0], value[1]];
64
77
  }
@@ -71,7 +84,28 @@ async function requireObserved(io, absolutePath, displayPath, signal) {
71
84
  const version = await io.statVersion(absolutePath, signal);
72
85
  invalidateIfStale(absolutePath, version);
73
86
  if (!getEncodingState(absolutePath)) {
74
- throw argError("E_BLIND_REPLACE", `str_replace_editor: ${displayPath} has not been viewed in this session (no file encoding state at the current version). Call view first, then retry. Nothing was written.`);
87
+ throw new DomainError("E_BLIND_REPLACE", { path: displayPath, command: "str_replace_editor" });
88
+ }
89
+ }
90
+ /**
91
+ * Governed save: resolve the per-call sandbox policy — the session's standing
92
+ * mode stamped with the calling session's workspace root, or an approved
93
+ * one-shot escalation grant — and hand it to the provider write; a sandbox
94
+ * denial is remapped to the shared `[sandbox: …]` marker plus the escalation
95
+ * hint so the caller can retry once.
96
+ *
97
+ * Without it the confined backend falls back to the deployment default root,
98
+ * so a write inside the session workspace is denied under `workspace-write`
99
+ * even though the built-in `str_replace_editor` (which carries the policy)
100
+ * succeeds there. Mirrors the hashline `edit` / `undo_last_edit` path.
101
+ */
102
+ async function writeGoverned(io, sandbox, absolutePath, content, args, exec) {
103
+ const policy = await sandbox.resolvePolicy("str_replace_editor", args, exec);
104
+ try {
105
+ await io.writeText(absolutePath, content, exec.signal, exec, policy);
106
+ }
107
+ catch (error) {
108
+ throw sandbox.mapError(error, policy);
75
109
  }
76
110
  }
77
111
  function countOccurrences(haystack, needle) {
@@ -99,7 +133,7 @@ function autoGuessWarning(absolutePath, rawPath) {
99
133
  getAutoGuessFooter(absolutePath.replace(/\\/g, "/")) ??
100
134
  undefined);
101
135
  }
102
- export function buildStrReplaceEditorTool(io) {
136
+ export function buildStrReplaceEditorTool(io, sandbox) {
103
137
  return defineTool({
104
138
  name: "str_replace_editor",
105
139
  description: STR_REPLACE_EDITOR_DESCRIPTION,
@@ -134,6 +168,7 @@ export function buildStrReplaceEditorTool(io) {
134
168
  type: "string",
135
169
  description: "Full content for create",
136
170
  },
171
+ ...(sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}),
137
172
  },
138
173
  output: {
139
174
  schema: {
@@ -150,11 +185,11 @@ export function buildStrReplaceEditorTool(io) {
150
185
  const rec = (args ?? {});
151
186
  const command = rec["command"];
152
187
  if (typeof command !== "string" || !KNOWN_COMMANDS.has(command)) {
153
- throw argError("E_BAD_COMMAND", `str_replace_editor: unknown command ${JSON.stringify(command)} — expected one of view, str_replace, insert, create, undo_edit.`);
188
+ throw new DomainError("E_BAD_COMMAND", { command });
154
189
  }
155
190
  const cmd = command;
156
191
  if (cmd === "undo_edit") {
157
- throw new Error("[MODEL] [E_UNSUPPORTED] str_replace_editor undo_edit is not implemented — use undo_last_edit.");
192
+ throw new DomainError("E_UNSUPPORTED", { command: "undo_edit" });
158
193
  }
159
194
  const rawPath = requireString(rec, "path");
160
195
  abortIf(signal);
@@ -198,10 +233,10 @@ export function buildStrReplaceEditorTool(io) {
198
233
  const ver = await io.statVersion(absolutePath, signal);
199
234
  const exists = ver !== undefined;
200
235
  if (exists) {
201
- throw argError("E_FILE_EXISTS", `str_replace_editor: cannot create ${rawPath} — file already exists.`);
236
+ throw new DomainError("E_FILE_EXISTS", { path: rawPath });
202
237
  }
203
238
  // Governed default: UTF-8 without BOM (no memo → no BOM).
204
- await io.writeText(absolutePath, fileText, signal, exec);
239
+ await writeGoverned(io, sandbox, absolutePath, fileText, rec, exec);
205
240
  try {
206
241
  const version = await io.statVersion(absolutePath, signal);
207
242
  recordOpenState(absolutePath, fileText, "utf8", false, version);
@@ -214,7 +249,7 @@ export function buildStrReplaceEditorTool(io) {
214
249
  // str_replace / insert — strict read-first gate, no disk write on failure.
215
250
  // NOTE (report #9): requireObserved's statVersion + the readText below
216
251
  // cost two RPCs by design — the stat invalidates stale encoding memos
217
- // BEFORE the read so a drifted file fails loud with E_BLIND_REPLACE
252
+ // BEFORE the read so a drifted file fails loud with E_BAD_PAYLOAD
218
253
  // without paying for the read, and collapsing them (Promise.all or
219
254
  // skipping the stat) reintroduces TOCTOU: a stale memo could authorize
220
255
  // an edit on drifted bytes. Returning the version from readText would
@@ -225,27 +260,27 @@ export function buildStrReplaceEditorTool(io) {
225
260
  if (cmd === "str_replace") {
226
261
  const oldStr = requireString(rec, "old_str");
227
262
  if (!("new_str" in rec) || typeof rec["new_str"] !== "string") {
228
- throw argError("E_BAD_PAYLOAD", 'str_replace_editor: "new_str" must be a string for str_replace.');
263
+ throw argError('str_replace_editor: "new_str" must be a string for str_replace.');
229
264
  }
230
265
  const newStr = rec["new_str"];
231
266
  const matches = countOccurrences(current, oldStr);
232
267
  if (matches === 0) {
233
- throw argError("E_NO_MATCH", `str_replace_editor: old_str not found in ${rawPath}. Nothing was written.`);
268
+ throw new DomainError("E_NO_MATCH", { path: rawPath });
234
269
  }
235
270
  if (matches > 1) {
236
- throw argError("E_AMBIGUOUS_MATCH", `str_replace_editor: old_str has multiple matches (${matches}) in ${rawPath} — must match exactly once. Narrow old_str with more context. Nothing was written.`);
271
+ throw new DomainError("E_AMBIGUOUS_MATCH", { path: rawPath, matches });
237
272
  }
238
273
  const next = restoreForSave(current.replace(oldStr, newStr), absolutePath);
239
- await io.writeText(absolutePath, next, signal, exec);
274
+ await writeGoverned(io, sandbox, absolutePath, next, rec, exec);
240
275
  return { text: `Replaced 1 occurrence in ${rawPath}.` };
241
276
  }
242
277
  // insert
243
278
  const line = rec["insert_line"];
244
279
  if (!Number.isInteger(line) || line < 1) {
245
- throw argError("E_BAD_PAYLOAD", 'str_replace_editor: "insert_line" must be a positive integer for insert.');
280
+ throw argError('str_replace_editor: "insert_line" must be a positive integer for insert.');
246
281
  }
247
282
  if (!("new_str" in rec) || typeof rec["new_str"] !== "string") {
248
- throw argError("E_BAD_PAYLOAD", 'str_replace_editor: "new_str" must be a string for insert.');
283
+ throw argError('str_replace_editor: "new_str" must be a string for insert.');
249
284
  }
250
285
  const insertText = rec["new_str"];
251
286
  const insertAt = line;
@@ -254,7 +289,7 @@ export function buildStrReplaceEditorTool(io) {
254
289
  const body = endsWithNL ? stripped.slice(0, -1) : stripped;
255
290
  const lines = stripped.length === 0 ? [] : body.split("\n");
256
291
  if (insertAt > lines.length + 1) {
257
- throw argError("E_BAD_PAYLOAD", `str_replace_editor: insert_line ${insertAt} is beyond end of file (${lines.length} lines). Nothing was written.`);
292
+ throw argError(`str_replace_editor: insert_line ${insertAt} is beyond end of file (${lines.length} lines). Nothing was written.`);
258
293
  }
259
294
  const added = insertText.split("\n");
260
295
  lines.splice(insertAt - 1, 0, ...added);
@@ -262,13 +297,13 @@ export function buildStrReplaceEditorTool(io) {
262
297
  if (endsWithNL && out2.length > 0)
263
298
  out2 += "\n";
264
299
  const next = restoreForSave(out2, absolutePath);
265
- await io.writeText(absolutePath, next, signal, exec);
300
+ await writeGoverned(io, sandbox, absolutePath, next, rec, exec);
266
301
  return { text: `Inserted ${added.length} line(s) at line ${insertAt} in ${rawPath}.` };
267
302
  });
268
303
  },
269
304
  });
270
305
  }
271
306
  /** Register the shadow `str_replace_editor` on the calling agent's scope (own layer). */
272
- export function registerStrReplaceEditorTool(agentCtx, io) {
273
- return agentCtx.tools.register(buildStrReplaceEditorTool(io));
307
+ export function registerStrReplaceEditorTool(agentCtx, io, sandbox) {
308
+ return agentCtx.tools.register(buildStrReplaceEditorTool(io, sandbox));
274
309
  }
package/lib/tool-undo.js CHANGED
@@ -7,9 +7,10 @@
7
7
  import { defineTool } from "@deepseek-ai/dsh-tools";
8
8
  import { toLF, stripBOM, genDiff, restoreEndings } from "./edit-diff.js";
9
9
  import { cntDiff, splitLines, codeOf } from "./utils.js";
10
+ import { DomainError, formatError } from "./domain-errors.js";
10
11
  import { assertUndoRequest } from "./contract.js";
11
12
  import { normalizeRequest as normReq } from "./contract.js";
12
- import { upsertSnapshotFor } from "./hash-store.js";
13
+ import { loadHashStore, withStore } from "./hash-store.js";
13
14
  import { canon, contentChecksum } from "./hashline/hash-assign.js";
14
15
  import { lineHashes } from "./hashline/hash.js";
15
16
  import { changedRange } from "./hashline/anchor-pipeline.js";
@@ -64,13 +65,13 @@ export function buildUndoTool(io, sandbox) {
64
65
  const message = error instanceof Error ? error.message : String(error);
65
66
  if (codeOf(error) === "E_NOT_FOUND") {
66
67
  await clearUndo(absolutePath);
67
- return `[E_UNDO_STALE] cannot undo on ${path}: file no longer exists.`;
68
+ return formatError("E_UNDO_STALE", { path, reason: "deleted" });
68
69
  }
69
70
  throw error;
70
71
  }
71
72
  if (currentRaw !== undo.bom + restoreEndings(undo.resultContent, undo.originalEnding)) {
72
73
  await clearUndo(absolutePath);
73
- return `[E_UNDO_STALE] cannot undo on ${path}: file modified after edit — undo would overwrite changes.`;
74
+ return formatError("E_UNDO_STALE", { path, reason: "modified" });
74
75
  }
75
76
  const { text: currentStripped } = stripBOM(currentRaw);
76
77
  const currentNormalized = toLF(currentStripped);
@@ -104,21 +105,37 @@ export function buildUndoTool(io, sandbox) {
104
105
  catch (error) {
105
106
  throw sandbox.mapError(error, sandboxPolicy);
106
107
  }
108
+ // The file is reverted; the store pair must move as ONE unit: the snapshot/lineage
109
+ // adopt (`upsertSnapshot`) and the undo-pair clear (`deleteUndoPair`) are both-or-neither.
110
+ // `withStore` routes both calls through the store's single re-entrant transaction owner
111
+ // (the store was just loaded for this workspace, so `currentStore()` is that same handle).
112
+ // Fail loud: a cleared pair over an un-adopted snapshot is a desync no later read/edit can see.
113
+ const store = await loadHashStore();
107
114
  try {
108
- await upsertSnapshotFor(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, restoredHashes);
115
+ withStore(() => {
116
+ store.upsertSnapshot(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, restoredHashes, undo.content);
117
+ store.deleteUndoPair(absolutePath);
118
+ });
109
119
  }
110
120
  catch (error) {
111
- console.error("Failed to restore hash store snapshot after undo:", error);
121
+ // Not a swallow: the raw cause is logged for diagnosis, then the tool fails loud.
122
+ console.error("Failed to record the undo restore in the hash store:", error);
123
+ throw new DomainError("E_UNDO_NOT_RECORDED", { path });
112
124
  }
113
- await clearUndo(absolutePath);
114
125
  const parts = [`Undone last edit on ${path}.`];
115
126
  if (linesAddedByEdit > 0 || linesRemovedByEdit > 0) {
116
127
  parts.push(`Removed ${linesAddedByEdit} line(s) that were added and restored ${linesRemovedByEdit} line(s) that were removed.`);
117
128
  }
118
- parts.push("File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits.");
129
+ // The serve write is a SECOND unit, deliberately outside the committed pair: a fault
130
+ // here must not roll the revert back. But it decides whether the anchors below are
131
+ // usable, so the claim is made only when the serve landed.
132
+ let serveLanded = true;
119
133
  if (undoDenseRows.length > 0) {
120
- await recordServedTruncated(sessionKey, absolutePath, undoDenseRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? undoDiffResult.firstChangedLine ?? 0, splitLines(undo.content).map((l) => canon(l)));
134
+ serveLanded = await recordServedTruncated(sessionKey, absolutePath, undoDenseRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? undoDiffResult.firstChangedLine ?? 0, splitLines(undo.content).map((l) => canon(l)), { content: undo.content, hashes: restoredHashes });
121
135
  }
136
+ parts.push(serveLanded
137
+ ? "File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits."
138
+ : "File reverted to previous state. WARNING: the restored file\u2019s fresh anchors were NOT recorded as served — the diff rows below are NOT usable anchors and no edit can be based on them. Re-read the file before editing it.");
122
139
  return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
123
140
  });
124
141
  },
@@ -3,13 +3,16 @@ export declare const SNIFF_BYTES = 8192;
3
3
  export declare const MAX_BYTES: number;
4
4
  export declare const MAX_READ_LINE_BYTES: number;
5
5
  export declare const HASH_STORE_BUSY_TIMEOUT = 1000;
6
- export declare const HASH_STORE_VERSION = 6;
6
+ export declare const HASH_STORE_VERSION = 7;
7
7
  export declare const EDITS_MAX_ITEMS = 32;
8
8
  /** @deprecated batch_edit seam removed (ADR-0003) — use EDITS_MAX_ITEMS */
9
9
  export declare const BATCH_EDIT_MAX_ITEMS = 32;
10
10
  export declare const SERVED_TTL_MS: number;
11
11
  export declare const SERVED_ECHO_CAP = 150;
12
+ export declare const DIFF_REMOVED_CAP = 6;
13
+ export declare const DIFF_REMOVED_EDGE = 2;
12
14
  export declare const NOOP_LOOP_THRESHOLD = 3;
15
+ export declare const NEW_CONTENT_BODY: string;
16
+ /** Model-facing header for a non-string replace_with, composed once by the registry. */
13
17
  export declare const NEW_CONTENT_NOT_STRING_MSG: string;
14
18
  export declare function eLargeFileMsg(displayPath: string, lineCount: number, maxLines: number): string;
15
- export declare const E_ANCHOR_SPACE_EXHAUSTED_WARNING = "[E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted";
@@ -2,45 +2,50 @@
2
2
  * One module owns the request shapes for the hashline tools — edit,
3
3
  * read, undo_last_edit — plus their validation. Field sets are
4
4
  * declared once here; every tool validates through these asserts, and the
5
- * [E_BAD_PAYLOAD] vocabulary is shared instead of re-implemented per tool.
5
+ * E_BAD_PAYLOAD vocabulary is shared instead of re-implemented per tool.
6
6
  *
7
- * Contract now mirrors upstream ADR-0007: {path: string|null, edits: [[remove_from,remove_to,replacement_text],...]} tuple payload
8
- * (plus object-form {remove_from, remove_to, replacement_text} per #64), single-file, atomic. batch_edit is removed.
7
+ * Contract mirrors upstream ADR-0015: {file: string|null, edits: [{anchor_from, anchor_to, replace_with},...]} named-object payload
8
+ * (plus legacy tuple items and legacy key spellings folded pre-validation), single-file, atomic. batch_edit is removed.
9
9
  * @module dsh-better-edit/contract
10
10
  */
11
+ import type { ReadWindow } from "./file-view.js";
12
+ export type EditMode = "general" | "literal";
11
13
  export type EditItem = {
12
- remove_from: string;
13
- remove_to: string;
14
- replacement_text: string;
14
+ anchor_from: string;
15
+ anchor_to: string;
16
+ replace_with: string;
15
17
  };
16
18
  export type EditRequest = {
17
- path: string | null;
19
+ file: string | null;
18
20
  edits: EditItem[];
21
+ /**
22
+ * "general" (default) refuses bytes reproducing served rows;
23
+ * "literal" declares them as intended file content (W_LITERAL_BYPASS).
24
+ */
25
+ mode?: EditMode;
19
26
  };
20
27
  export interface EditParams {
21
- path: string;
22
- remove_from: string;
23
- remove_to: string;
24
- replacement_text: string;
28
+ file: string;
29
+ anchor_from: string;
30
+ anchor_to: string;
31
+ replace_with: string;
32
+ /** Legacy single-edit path: literal bypasses the served-echo guard. */
33
+ mode?: EditMode;
25
34
  }
26
35
  export interface ReadParams {
27
36
  path: string;
28
37
  offset?: number;
29
38
  limit?: number;
30
39
  encoding?: string;
40
+ /**
41
+ * Multi-window read — disjoint line ranges served in one call. Shape and count
42
+ * (max MAX_READ_WINDOWS) are validated in file-view's normWindows.
43
+ */
44
+ windows?: ReadWindow[];
31
45
  }
32
46
  export interface UndoParams {
33
47
  path: string;
34
48
  }
35
- export interface BatchItemParams {
36
- path?: string;
37
- remove_from: string;
38
- remove_to: string;
39
- replacement_text: string;
40
- }
41
- export interface BatchEditParams {
42
- edits: BatchItemParams[];
43
- }
44
49
  export declare const normalizedEdit: unique symbol;
45
50
  export type NormalizedEditRequest = EditRequest & {
46
51
  [normalizedEdit]?: true;
@@ -48,15 +53,16 @@ export type NormalizedEditRequest = EditRequest & {
48
53
  export declare function isNormalizedEdit(input: unknown): input is NormalizedEditRequest;
49
54
  export declare function itemFromTuple(value: unknown): EditItem | undefined;
50
55
  /**
51
- * Accept both the tuple form (["a", "b", "c"]) and the object form
52
- * ({ remove_from, remove_to, replacement_text }) per edits entry (#64).
53
- * Missing/mistyped fields and unknown fields still return undefined so the
54
- * caller rejects with E_BAD_PAYLOAD.
56
+ * Accept the named-object form ({ anchor_from, anchor_to, replace_with }),
57
+ * the legacy tuple form ([a, b, t]), and the legacy-key form
58
+ * (legacy spelling) per edits entry — all fold
59
+ * to the named triple. Mixed old/new keys, extra keys, and 2-/4-position
60
+ * tuples still return undefined so the caller rejects with E_BAD_PAYLOAD.
55
61
  */
56
62
  export declare function itemFromEntry(value: unknown): EditItem | undefined;
57
63
  export declare function editRequestFrom(input: unknown): NormalizedEditRequest | undefined;
58
64
  export declare function sanitizePath(value: unknown): string | null;
59
- export declare const EDIT_TUPLE_HINT: string;
65
+ export declare const EDIT_PAYLOAD_HINT: string;
60
66
  /**
61
67
  * Normalize `file_path` → `path` alias on the request record and tuple edits → objects.
62
68
  * Returns the input unchanged when not a record; otherwise returns a shallow copy with
@@ -67,20 +73,19 @@ export declare function normalizeRequest(input: unknown): unknown;
67
73
  export declare const normReq: typeof normalizeRequest;
68
74
  export declare function prepareEditArguments(args: unknown): Record<string, unknown>;
69
75
  export declare function assertEditRequest(request: unknown): asserts request is NormalizedEditRequest;
70
- export declare function assertBatchEditRequest(_request: unknown): asserts _request is BatchEditParams;
71
76
  export declare function assertReadRequest(request: unknown): asserts request is ReadParams;
72
77
  export declare function assertUndoRequest(request: unknown): asserts request is UndoParams;
73
- export declare const replacementTextSchema: {
78
+ export declare const replaceWithSchema: {
74
79
  readonly type: "string";
75
- readonly description: 'Complete replacement for the range; use "" to delete';
80
+ readonly description: 'Bare file content for the range; use "" to delete';
76
81
  };
77
- export declare const removeFromSchema: {
82
+ export declare const anchorFromSchema: {
78
83
  readonly type: "string";
79
- readonly description: "First line to remove (inclusive)";
84
+ readonly description: "Bare 3-char hash anchor of the first range line (inclusive)";
80
85
  };
81
- export declare const removeToSchema: {
86
+ export declare const anchorToSchema: {
82
87
  readonly type: "string";
83
- readonly description: "Last line to remove (inclusive)";
88
+ readonly description: "Bare 3-char hash anchor of the last range line (inclusive)";
84
89
  };
85
90
  export declare const pathSchema: {
86
91
  readonly type: "string";
@@ -100,82 +105,82 @@ export declare const editTupleSchema: {
100
105
  readonly type: "array";
101
106
  readonly prefixItems: readonly [{
102
107
  readonly type: "string";
103
- readonly description: "First line to remove (inclusive)";
108
+ readonly description: "Bare 3-char hash anchor of the first range line (inclusive)";
104
109
  }, {
105
110
  readonly type: "string";
106
- readonly description: "Last line to remove (inclusive)";
111
+ readonly description: "Bare 3-char hash anchor of the last range line (inclusive)";
107
112
  }, {
108
113
  readonly type: "string";
109
- readonly description: 'Complete replacement for the range; use "" to delete';
114
+ readonly description: 'Bare file content for the range; use "" to delete';
110
115
  }];
111
116
  readonly minItems: 3;
112
117
  readonly maxItems: 3;
113
- readonly description: "[remove_from, remove_to, replacement_text]";
118
+ readonly description: "[anchor_from, anchor_to, replace_with] (legacy tuple form)";
114
119
  };
115
120
  export declare const editObjectSchema: {
116
121
  readonly type: "object";
117
122
  readonly additionalProperties: false;
118
- readonly required: readonly ["remove_from", "remove_to", "replacement_text"];
123
+ readonly required: readonly ["anchor_from", "anchor_to", "replace_with"];
119
124
  readonly properties: {
120
- readonly remove_from: {
125
+ readonly anchor_from: {
121
126
  readonly type: "string";
122
- readonly description: "First line to remove (inclusive)";
127
+ readonly description: "Bare 3-char hash anchor of the first range line (inclusive)";
123
128
  };
124
- readonly remove_to: {
129
+ readonly anchor_to: {
125
130
  readonly type: "string";
126
- readonly description: "Last line to remove (inclusive)";
131
+ readonly description: "Bare 3-char hash anchor of the last range line (inclusive)";
127
132
  };
128
- readonly replacement_text: {
133
+ readonly replace_with: {
129
134
  readonly type: "string";
130
- readonly description: 'Complete replacement for the range; use "" to delete';
135
+ readonly description: 'Bare file content for the range; use "" to delete';
131
136
  };
132
137
  };
133
- readonly description: "{remove_from, remove_to, replacement_text}";
138
+ readonly description: "{anchor_from, anchor_to, replace_with}";
134
139
  };
135
140
  export declare const editItemSchema: {
136
141
  readonly anyOf: readonly [{
137
142
  readonly type: "array";
138
143
  readonly prefixItems: readonly [{
139
144
  readonly type: "string";
140
- readonly description: "First line to remove (inclusive)";
145
+ readonly description: "Bare 3-char hash anchor of the first range line (inclusive)";
141
146
  }, {
142
147
  readonly type: "string";
143
- readonly description: "Last line to remove (inclusive)";
148
+ readonly description: "Bare 3-char hash anchor of the last range line (inclusive)";
144
149
  }, {
145
150
  readonly type: "string";
146
- readonly description: 'Complete replacement for the range; use "" to delete';
151
+ readonly description: 'Bare file content for the range; use "" to delete';
147
152
  }];
148
153
  readonly minItems: 3;
149
154
  readonly maxItems: 3;
150
- readonly description: "[remove_from, remove_to, replacement_text]";
155
+ readonly description: "[anchor_from, anchor_to, replace_with] (legacy tuple form)";
151
156
  }, {
152
157
  readonly type: "object";
153
158
  readonly additionalProperties: false;
154
- readonly required: readonly ["remove_from", "remove_to", "replacement_text"];
159
+ readonly required: readonly ["anchor_from", "anchor_to", "replace_with"];
155
160
  readonly properties: {
156
- readonly remove_from: {
161
+ readonly anchor_from: {
157
162
  readonly type: "string";
158
- readonly description: "First line to remove (inclusive)";
163
+ readonly description: "Bare 3-char hash anchor of the first range line (inclusive)";
159
164
  };
160
- readonly remove_to: {
165
+ readonly anchor_to: {
161
166
  readonly type: "string";
162
- readonly description: "Last line to remove (inclusive)";
167
+ readonly description: "Bare 3-char hash anchor of the last range line (inclusive)";
163
168
  };
164
- readonly replacement_text: {
169
+ readonly replace_with: {
165
170
  readonly type: "string";
166
- readonly description: 'Complete replacement for the range; use "" to delete';
171
+ readonly description: 'Bare file content for the range; use "" to delete';
167
172
  };
168
173
  };
169
- readonly description: "{remove_from, remove_to, replacement_text}";
174
+ readonly description: "{anchor_from, anchor_to, replace_with}";
170
175
  }];
171
176
  readonly description: "Edit entry — either tuple or object form (mixed batches allowed)";
172
177
  };
173
178
  export declare const editToolSchema: {
174
179
  readonly type: "object";
175
180
  readonly additionalProperties: false;
176
- readonly required: readonly ["path", "edits"];
181
+ readonly required: readonly ["file", "edits"];
177
182
  readonly properties: {
178
- readonly path: {
183
+ readonly file: {
179
184
  readonly anyOf: readonly [{
180
185
  readonly type: "string";
181
186
  readonly minLength: 1;
@@ -187,7 +192,7 @@ export declare const editToolSchema: {
187
192
  };
188
193
  readonly edits: {
189
194
  readonly type: "array";
190
- readonly description: "Ordered list of edit entries — each entry is either a tuple [remove_from, remove_to, replacement_text] or an object {remove_from, remove_to, replacement_text} (mixed batches allowed)";
195
+ readonly description: "Ordered list of edit entries — each entry is a named object {anchor_from, anchor_to, replace_with} (legacy tuples still fold pre-validation)";
191
196
  readonly minItems: 1;
192
197
  readonly maxItems: 32;
193
198
  readonly items: {
@@ -195,36 +200,36 @@ export declare const editToolSchema: {
195
200
  readonly type: "array";
196
201
  readonly prefixItems: readonly [{
197
202
  readonly type: "string";
198
- readonly description: "First line to remove (inclusive)";
203
+ readonly description: "Bare 3-char hash anchor of the first range line (inclusive)";
199
204
  }, {
200
205
  readonly type: "string";
201
- readonly description: "Last line to remove (inclusive)";
206
+ readonly description: "Bare 3-char hash anchor of the last range line (inclusive)";
202
207
  }, {
203
208
  readonly type: "string";
204
- readonly description: 'Complete replacement for the range; use "" to delete';
209
+ readonly description: 'Bare file content for the range; use "" to delete';
205
210
  }];
206
211
  readonly minItems: 3;
207
212
  readonly maxItems: 3;
208
- readonly description: "[remove_from, remove_to, replacement_text]";
213
+ readonly description: "[anchor_from, anchor_to, replace_with] (legacy tuple form)";
209
214
  }, {
210
215
  readonly type: "object";
211
216
  readonly additionalProperties: false;
212
- readonly required: readonly ["remove_from", "remove_to", "replacement_text"];
217
+ readonly required: readonly ["anchor_from", "anchor_to", "replace_with"];
213
218
  readonly properties: {
214
- readonly remove_from: {
219
+ readonly anchor_from: {
215
220
  readonly type: "string";
216
- readonly description: "First line to remove (inclusive)";
221
+ readonly description: "Bare 3-char hash anchor of the first range line (inclusive)";
217
222
  };
218
- readonly remove_to: {
223
+ readonly anchor_to: {
219
224
  readonly type: "string";
220
- readonly description: "Last line to remove (inclusive)";
225
+ readonly description: "Bare 3-char hash anchor of the last range line (inclusive)";
221
226
  };
222
- readonly replacement_text: {
227
+ readonly replace_with: {
223
228
  readonly type: "string";
224
- readonly description: 'Complete replacement for the range; use "" to delete';
229
+ readonly description: 'Bare file content for the range; use "" to delete';
225
230
  };
226
231
  };
227
- readonly description: "{remove_from, remove_to, replacement_text}";
232
+ readonly description: "{anchor_from, anchor_to, replace_with}";
228
233
  }];
229
234
  readonly description: "Edit entry — either tuple or object form (mixed batches allowed)";
230
235
  };