dsh-better-edit 0.6.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +59 -15
  2. package/README.md +78 -71
  3. package/README.zh.md +83 -83
  4. package/lib/canonical-path.js +4 -1
  5. package/lib/constants.js +5 -1
  6. package/lib/contract.js +127 -33
  7. package/lib/edit-diff.js +1 -5
  8. package/lib/edit-response.js +5 -10
  9. package/lib/encoding.js +23 -6
  10. package/lib/file-encoding-state.js +54 -15
  11. package/lib/file-view.js +42 -53
  12. package/lib/fs-bridge.js +27 -16
  13. package/lib/fs-write.js +1 -1
  14. package/lib/guidance/materialize.js +1 -6
  15. package/lib/guidance/resolve.js +1 -1
  16. package/lib/hash-store.js +133 -43
  17. package/lib/hashline/anchor-pipeline.js +124 -93
  18. package/lib/hashline/hash-assign.js +65 -23
  19. package/lib/hashline/hash.js +6 -6
  20. package/lib/index.js +6 -0
  21. package/lib/mutation/engine.js +89 -31
  22. package/lib/mutation.js +14 -13
  23. package/lib/prompts.js +12 -11
  24. package/lib/read-and-serve.js +105 -19
  25. package/lib/render-text-warning.js +21 -0
  26. package/lib/sandbox.js +2 -5
  27. package/lib/self-heal.js +30 -27
  28. package/lib/session-view.js +161 -24
  29. package/lib/store-config.js +7 -2
  30. package/lib/store-lifecycle.js +7 -2
  31. package/lib/tool-edit.js +10 -6
  32. package/lib/tool-read.js +6 -9
  33. package/lib/tool-str-replace-editor.js +274 -0
  34. package/lib/tool-undo.js +8 -9
  35. package/lib/types/constants.d.ts +2 -0
  36. package/lib/types/contract.d.ts +106 -18
  37. package/lib/types/edit-response.d.ts +4 -0
  38. package/lib/types/encoding.d.ts +1 -1
  39. package/lib/types/file-encoding-state.d.ts +4 -1
  40. package/lib/types/file-view.d.ts +16 -1
  41. package/lib/types/hash-store.d.ts +12 -1
  42. package/lib/types/hashline/anchor-pipeline.d.ts +16 -6
  43. package/lib/types/hashline/hash-assign.d.ts +10 -2
  44. package/lib/types/hashline/index.d.ts +1 -1
  45. package/lib/types/mutation/engine.d.ts +2 -1
  46. package/lib/types/render-text-warning.d.ts +22 -0
  47. package/lib/types/self-heal.d.ts +2 -0
  48. package/lib/types/session-view.d.ts +13 -4
  49. package/lib/types/tool-str-replace-editor.d.ts +27 -0
  50. package/lib/types/undo-edit.d.ts +1 -1
  51. package/lib/types/utils.d.ts +7 -0
  52. package/lib/types/write-hook.d.ts +2 -2
  53. package/lib/undo-edit.js +6 -8
  54. package/lib/utils.js +23 -3
  55. package/lib/workspace-context.js +1 -1
  56. package/lib/write-hook.js +20 -23
  57. package/package.json +63 -57
@@ -0,0 +1,274 @@
1
+ /**
2
+ * The dsh `str_replace_editor` shadow: a governed agent-layer replacement for
3
+ * the built-in `@deepseek-ai/dsh-tool-str-replace-editor` with identical
4
+ * contract (`view` / `str_replace` / `insert` / `create`, no new `encoding`
5
+ * param) but routed through the file-encoding-state seam.
6
+ *
7
+ * - `view` is observation: decode via the `ctxFsIO` path (`decodeForOpen`
8
+ * inside `io.readText`), records file encoding state, emits `fs/observed`,
9
+ * and never records served state (so it can feed `write` round-trips but
10
+ * cannot authorize hashline `edit` anchors).
11
+ * - `str_replace` / `insert` without a prior `view`/`read` fail loud with
12
+ * `E_BLIND_REPLACE` — no disk write.
13
+ * - `create` defaults to UTF-8 without BOM.
14
+ * - `undo_edit` is out of scope → `E_UNSUPPORTED` (use `undo_last_edit`).
15
+ *
16
+ * See ADR-0015.
17
+ * @module dsh-better-edit/tool-str-replace-editor
18
+ */
19
+ import { defineTool } from "@deepseek-ai/dsh-tools";
20
+ import { getAutoGuessFooter } from "./fs-bridge.js";
21
+ import { getEncodingState, invalidateIfStale, prepareForSave, recordOpenState, } from "./file-encoding-state.js";
22
+ import { stripBOM } from "./edit-diff.js";
23
+ import { renderTextWarning } from "./render-text-warning.js";
24
+ import { execCwd, withWorkspace } from "./workspace-context.js";
25
+ import { abortIf, splitLines } from "./utils.js";
26
+ export const STR_REPLACE_EDITOR_DESCRIPTION = "View, create, and edit text files by exact string match. Commands: " +
27
+ "`view` {path, view_range?} shows 1-indexed lines; `str_replace` {path, old_str, new_str} " +
28
+ "replaces the unique occurrence of old_str; `insert` {path, insert_line, new_str} inserts " +
29
+ "new line(s) before insert_line (1-indexed, lines+1 appends); `create` {path, file_text} " +
30
+ "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 " +
32
+ "decode via auto-guess when enabled, otherwise fail loud with Top-3 candidates.";
33
+ const KNOWN_COMMANDS = new Set([
34
+ "view",
35
+ "str_replace",
36
+ "insert",
37
+ "create",
38
+ "undo_edit",
39
+ ]);
40
+ function argError(code, message) {
41
+ return new Error(`[MODEL] [${code}] ${message}`);
42
+ }
43
+ function requireString(args, name) {
44
+ const value = args[name];
45
+ if (typeof value !== "string" || value.length === 0) {
46
+ throw argError("E_BAD_PAYLOAD", `str_replace_editor: "${name}" must be a non-empty string.`);
47
+ }
48
+ return value;
49
+ }
50
+ function requireViewRange(args) {
51
+ const value = args["view_range"];
52
+ if (value === undefined)
53
+ return undefined;
54
+ if (!Array.isArray(value) ||
55
+ value.length !== 2 ||
56
+ !Number.isInteger(value[0]) ||
57
+ !Number.isInteger(value[1]) ||
58
+ value[0] < 1 ||
59
+ value[1] < 1 ||
60
+ 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.');
62
+ }
63
+ return [value[0], value[1]];
64
+ }
65
+ /**
66
+ * Strict read-first gate: the file must carry file encoding state recorded by
67
+ * a prior `view`/`read` at the current version. Stale memos are invalidated
68
+ * first, so drifted files fail loud instead of editing blind. Never writes.
69
+ */
70
+ async function requireObserved(io, absolutePath, displayPath, signal) {
71
+ const version = await io.statVersion(absolutePath, signal);
72
+ invalidateIfStale(absolutePath, version);
73
+ 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.`);
75
+ }
76
+ }
77
+ function countOccurrences(haystack, needle) {
78
+ if (needle.length === 0)
79
+ return 0;
80
+ let count = 0;
81
+ let from = 0;
82
+ while (true) {
83
+ const at = haystack.indexOf(needle, from);
84
+ if (at === -1)
85
+ return count;
86
+ count += 1;
87
+ from = at + needle.length;
88
+ }
89
+ }
90
+ /** Shared-seam save restoration: BOM + lineEnding via `prepareForSave`.
91
+ * Replaces the former local `restoreBom` so the shadow can't diverge from
92
+ * the file-encoding-state round-trip (report #2). */
93
+ function restoreForSave(content, absolutePath) {
94
+ return prepareForSave(content, getEncodingState(absolutePath)).textToWrite;
95
+ }
96
+ function autoGuessWarning(absolutePath, rawPath) {
97
+ return (getAutoGuessFooter(absolutePath) ??
98
+ getAutoGuessFooter(rawPath) ??
99
+ getAutoGuessFooter(absolutePath.replace(/\\/g, "/")) ??
100
+ undefined);
101
+ }
102
+ export function buildStrReplaceEditorTool(io) {
103
+ return defineTool({
104
+ name: "str_replace_editor",
105
+ description: STR_REPLACE_EDITOR_DESCRIPTION,
106
+ parameters: {
107
+ command: {
108
+ type: "string",
109
+ required: true,
110
+ description: "One of: view, str_replace, insert, create, undo_edit",
111
+ },
112
+ path: {
113
+ type: "string",
114
+ required: true,
115
+ description: "File path",
116
+ },
117
+ view_range: {
118
+ type: "json",
119
+ description: "[start, end] 1-indexed inclusive line range for view",
120
+ },
121
+ old_str: {
122
+ type: "string",
123
+ description: "Exact string to replace (must occur exactly once) for str_replace",
124
+ },
125
+ new_str: {
126
+ type: "string",
127
+ description: "Replacement text for str_replace, or line(s) to insert for insert",
128
+ },
129
+ insert_line: {
130
+ type: "number",
131
+ description: "1-indexed line to insert before (lines+1 appends) for insert",
132
+ },
133
+ file_text: {
134
+ type: "string",
135
+ description: "Full content for create",
136
+ },
137
+ },
138
+ output: {
139
+ schema: {
140
+ type: "object",
141
+ properties: { text: { type: "string", required: true }, warning: { type: "string" } },
142
+ additionalProperties: false,
143
+ },
144
+ render: (_args, value) => renderTextWarning(value),
145
+ },
146
+ async execute(args, exec) {
147
+ return withWorkspace(execCwd(exec), async () => {
148
+ const cwd = execCwd(exec);
149
+ const signal = exec.signal;
150
+ const rec = (args ?? {});
151
+ const command = rec["command"];
152
+ 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.`);
154
+ }
155
+ const cmd = command;
156
+ if (cmd === "undo_edit") {
157
+ throw new Error("[MODEL] [E_UNSUPPORTED] str_replace_editor undo_edit is not implemented — use undo_last_edit.");
158
+ }
159
+ const rawPath = requireString(rec, "path");
160
+ abortIf(signal);
161
+ const absolutePath = await io.resolve(rawPath, cwd, signal);
162
+ if (cmd === "view") {
163
+ const text = await io.readText(absolutePath, signal);
164
+ // Observation only: encoding state is recorded by readText;
165
+ // served state is never touched here.
166
+ // NOTE (report #10): the readText + emitObserved pair costs two
167
+ // RPCs by design — readText decodes + records encoding state with
168
+ // no session, while emitObserved emits fs/observed with exec + a
169
+ // fresh stat version. Piggy-backing would need readText to take
170
+ // exec / return a version (FileIO contract break); same pattern
171
+ // as tool-read.ts, so documented, not collapsed.
172
+ await io.emitObserved(absolutePath, exec, signal);
173
+ const display = stripBOM(text).text;
174
+ const range = requireViewRange(rec);
175
+ let out = display;
176
+ if (range) {
177
+ const lines = splitLines(display);
178
+ const total = lines.length === 1 && lines[0] === "" ? 0 : lines.length;
179
+ const [start, end] = range;
180
+ if (total === 0) {
181
+ out = "[File is empty.]";
182
+ }
183
+ else if (start > total) {
184
+ out = `View range [${start}, ${end}] is beyond end of file (${total} lines total).`;
185
+ }
186
+ else {
187
+ out = lines.slice(start - 1, Math.min(end, total)).join("\n");
188
+ if (end < total) {
189
+ out += `\n\n[Showing lines ${start}-${Math.min(end, total)} of ${total}. Use view_range to continue.]`;
190
+ }
191
+ }
192
+ }
193
+ const warning = autoGuessWarning(absolutePath, rawPath);
194
+ return warning ? { text: out, warning } : { text: out };
195
+ }
196
+ if (cmd === "create") {
197
+ const fileText = requireString(rec, "file_text");
198
+ const ver = await io.statVersion(absolutePath, signal);
199
+ const exists = ver !== undefined;
200
+ if (exists) {
201
+ throw argError("E_FILE_EXISTS", `str_replace_editor: cannot create ${rawPath} — file already exists.`);
202
+ }
203
+ // Governed default: UTF-8 without BOM (no memo → no BOM).
204
+ await io.writeText(absolutePath, fileText, signal, exec);
205
+ try {
206
+ const version = await io.statVersion(absolutePath, signal);
207
+ recordOpenState(absolutePath, fileText, "utf8", false, version);
208
+ }
209
+ catch {
210
+ // best-effort: the write succeeded; state is a hint.
211
+ }
212
+ return { text: `Created ${rawPath}.` };
213
+ }
214
+ // str_replace / insert — strict read-first gate, no disk write on failure.
215
+ // NOTE (report #9): requireObserved's statVersion + the readText below
216
+ // 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
218
+ // without paying for the read, and collapsing them (Promise.all or
219
+ // skipping the stat) reintroduces TOCTOU: a stale memo could authorize
220
+ // an edit on drifted bytes. Returning the version from readText would
221
+ // need a FileIO contract break for an unmeasured hot-path nit; same
222
+ // pattern as the view double-RPC above, so documented, not collapsed.
223
+ await requireObserved(io, absolutePath, rawPath, signal);
224
+ const current = await io.readText(absolutePath, signal);
225
+ if (cmd === "str_replace") {
226
+ const oldStr = requireString(rec, "old_str");
227
+ 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.');
229
+ }
230
+ const newStr = rec["new_str"];
231
+ const matches = countOccurrences(current, oldStr);
232
+ if (matches === 0) {
233
+ throw argError("E_NO_MATCH", `str_replace_editor: old_str not found in ${rawPath}. Nothing was written.`);
234
+ }
235
+ 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.`);
237
+ }
238
+ const next = restoreForSave(current.replace(oldStr, newStr), absolutePath);
239
+ await io.writeText(absolutePath, next, signal, exec);
240
+ return { text: `Replaced 1 occurrence in ${rawPath}.` };
241
+ }
242
+ // insert
243
+ const line = rec["insert_line"];
244
+ if (!Number.isInteger(line) || line < 1) {
245
+ throw argError("E_BAD_PAYLOAD", 'str_replace_editor: "insert_line" must be a positive integer for insert.');
246
+ }
247
+ 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.');
249
+ }
250
+ const insertText = rec["new_str"];
251
+ const insertAt = line;
252
+ const stripped = stripBOM(current).text;
253
+ const endsWithNL = stripped.endsWith("\n");
254
+ const body = endsWithNL ? stripped.slice(0, -1) : stripped;
255
+ const lines = stripped.length === 0 ? [] : body.split("\n");
256
+ 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.`);
258
+ }
259
+ const added = insertText.split("\n");
260
+ lines.splice(insertAt - 1, 0, ...added);
261
+ let out2 = lines.join("\n");
262
+ if (endsWithNL && out2.length > 0)
263
+ out2 += "\n";
264
+ const next = restoreForSave(out2, absolutePath);
265
+ await io.writeText(absolutePath, next, signal, exec);
266
+ return { text: `Inserted ${added.length} line(s) at line ${insertAt} in ${rawPath}.` };
267
+ });
268
+ },
269
+ });
270
+ }
271
+ /** 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));
274
+ }
package/lib/tool-undo.js CHANGED
@@ -6,15 +6,15 @@
6
6
  */
7
7
  import { defineTool } from "@deepseek-ai/dsh-tools";
8
8
  import { toLF, stripBOM, genDiff, restoreEndings } from "./edit-diff.js";
9
- import { cntDiff, splitLines } from "./utils.js";
9
+ import { cntDiff, splitLines, codeOf } from "./utils.js";
10
10
  import { assertUndoRequest } from "./contract.js";
11
11
  import { normalizeRequest as normReq } from "./contract.js";
12
12
  import { upsertSnapshotFor } from "./hash-store.js";
13
- import { contentChecksum } from "./hashline/hash-assign.js";
13
+ import { canon, contentChecksum } from "./hashline/hash-assign.js";
14
14
  import { lineHashes } from "./hashline/hash.js";
15
15
  import { changedRange } from "./hashline/anchor-pipeline.js";
16
16
  import { getUndo, clearUndo } from "./undo-edit.js";
17
- import { loadAnchorReservations, recordServedTruncated, retireAnchors, } from "./session-view.js";
17
+ import { loadAnchorReservations, recordServedTruncated, retireAnchors } from "./session-view.js";
18
18
  import { UNDO_DESCRIPTION } from "./prompts.js";
19
19
  import { execCwd, execSessionKey } from "./workspace-context.js";
20
20
  import { withWorkspace } from "./workspace-context.js";
@@ -62,21 +62,20 @@ export function buildUndoTool(io, sandbox) {
62
62
  }
63
63
  catch (error) {
64
64
  const message = error instanceof Error ? error.message : String(error);
65
- if (message.includes("[E_NOT_FOUND]")) {
65
+ if (codeOf(error) === "E_NOT_FOUND") {
66
66
  await clearUndo(absolutePath);
67
67
  return `[E_UNDO_STALE] cannot undo on ${path}: file no longer exists.`;
68
68
  }
69
69
  throw error;
70
70
  }
71
- if (currentRaw !==
72
- undo.bom + restoreEndings(undo.resultContent, undo.originalEnding)) {
71
+ if (currentRaw !== undo.bom + restoreEndings(undo.resultContent, undo.originalEnding)) {
73
72
  await clearUndo(absolutePath);
74
73
  return `[E_UNDO_STALE] cannot undo on ${path}: file modified after edit — undo would overwrite changes.`;
75
74
  }
76
75
  const { text: currentStripped } = stripBOM(currentRaw);
77
76
  const currentNormalized = toLF(currentStripped);
78
- // undo is file-global: must block hashes retired by any session, not just current session, to prevent recycling current-file-only hash - test expects global
79
- const reservations = await loadAnchorReservations(absolutePath);
77
+ // Per-session reservations: retired/ served are per (session, path) per ADR-0013; file snapshots stay global last-writer-wins
78
+ const reservations = await loadAnchorReservations(sessionKey, absolutePath);
80
79
  const currentHashes = await lineHashes(currentNormalized, absolutePath, undefined, undefined, false, reservations.reservedHashes, reservations.retiredHashes);
81
80
  const retiredOriginalHashes = new Set(undo.hashes.filter((hash) => reservations.retiredHashes.has(hash)));
82
81
  const blockedRestoreHashes = new Set(reservations.reservedHashes);
@@ -118,7 +117,7 @@ export function buildUndoTool(io, sandbox) {
118
117
  }
119
118
  parts.push("File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits.");
120
119
  if (undoDenseRows.length > 0) {
121
- await recordServedTruncated(sessionKey, absolutePath, undoDenseRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? undoDiffResult.firstChangedLine ?? 0);
120
+ await recordServedTruncated(sessionKey, absolutePath, undoDenseRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? undoDiffResult.firstChangedLine ?? 0, splitLines(undo.content).map((l) => canon(l)));
122
121
  }
123
122
  return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
124
123
  });
@@ -11,3 +11,5 @@ export declare const SERVED_TTL_MS: number;
11
11
  export declare const SERVED_ECHO_CAP = 150;
12
12
  export declare const NOOP_LOOP_THRESHOLD = 3;
13
13
  export declare const NEW_CONTENT_NOT_STRING_MSG: string;
14
+ 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,10 +2,10 @@
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_SHAPE] 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
- * single-file, atomic. batch_edit is removed.
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.
9
9
  * @module dsh-better-edit/contract
10
10
  */
11
11
  export type EditItem = {
@@ -47,7 +47,15 @@ export type NormalizedEditRequest = EditRequest & {
47
47
  };
48
48
  export declare function isNormalizedEdit(input: unknown): input is NormalizedEditRequest;
49
49
  export declare function itemFromTuple(value: unknown): EditItem | undefined;
50
+ /**
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.
55
+ */
56
+ export declare function itemFromEntry(value: unknown): EditItem | undefined;
50
57
  export declare function editRequestFrom(input: unknown): NormalizedEditRequest | undefined;
58
+ export declare function sanitizePath(value: unknown): string | null;
51
59
  export declare const EDIT_TUPLE_HINT: string;
52
60
  /**
53
61
  * Normalize `file_path` → `path` alias on the request record and tuple edits → objects.
@@ -64,7 +72,7 @@ export declare function assertReadRequest(request: unknown): asserts request is
64
72
  export declare function assertUndoRequest(request: unknown): asserts request is UndoParams;
65
73
  export declare const replacementTextSchema: {
66
74
  readonly type: "string";
67
- readonly description: "Complete replacement for the range; use \"\" to delete";
75
+ readonly description: 'Complete replacement for the range; use "" to delete';
68
76
  };
69
77
  export declare const removeFromSchema: {
70
78
  readonly type: "string";
@@ -98,12 +106,70 @@ export declare const editTupleSchema: {
98
106
  readonly description: "Last line to remove (inclusive)";
99
107
  }, {
100
108
  readonly type: "string";
101
- readonly description: "Complete replacement for the range; use \"\" to delete";
109
+ readonly description: 'Complete replacement for the range; use "" to delete';
102
110
  }];
103
111
  readonly minItems: 3;
104
112
  readonly maxItems: 3;
105
113
  readonly description: "[remove_from, remove_to, replacement_text]";
106
114
  };
115
+ export declare const editObjectSchema: {
116
+ readonly type: "object";
117
+ readonly additionalProperties: false;
118
+ readonly required: readonly ["remove_from", "remove_to", "replacement_text"];
119
+ readonly properties: {
120
+ readonly remove_from: {
121
+ readonly type: "string";
122
+ readonly description: "First line to remove (inclusive)";
123
+ };
124
+ readonly remove_to: {
125
+ readonly type: "string";
126
+ readonly description: "Last line to remove (inclusive)";
127
+ };
128
+ readonly replacement_text: {
129
+ readonly type: "string";
130
+ readonly description: 'Complete replacement for the range; use "" to delete';
131
+ };
132
+ };
133
+ readonly description: "{remove_from, remove_to, replacement_text}";
134
+ };
135
+ export declare const editItemSchema: {
136
+ readonly anyOf: readonly [{
137
+ readonly type: "array";
138
+ readonly prefixItems: readonly [{
139
+ readonly type: "string";
140
+ readonly description: "First line to remove (inclusive)";
141
+ }, {
142
+ readonly type: "string";
143
+ readonly description: "Last line to remove (inclusive)";
144
+ }, {
145
+ readonly type: "string";
146
+ readonly description: 'Complete replacement for the range; use "" to delete';
147
+ }];
148
+ readonly minItems: 3;
149
+ readonly maxItems: 3;
150
+ readonly description: "[remove_from, remove_to, replacement_text]";
151
+ }, {
152
+ readonly type: "object";
153
+ readonly additionalProperties: false;
154
+ readonly required: readonly ["remove_from", "remove_to", "replacement_text"];
155
+ readonly properties: {
156
+ readonly remove_from: {
157
+ readonly type: "string";
158
+ readonly description: "First line to remove (inclusive)";
159
+ };
160
+ readonly remove_to: {
161
+ readonly type: "string";
162
+ readonly description: "Last line to remove (inclusive)";
163
+ };
164
+ readonly replacement_text: {
165
+ readonly type: "string";
166
+ readonly description: 'Complete replacement for the range; use "" to delete';
167
+ };
168
+ };
169
+ readonly description: "{remove_from, remove_to, replacement_text}";
170
+ }];
171
+ readonly description: "Edit entry — either tuple or object form (mixed batches allowed)";
172
+ };
107
173
  export declare const editToolSchema: {
108
174
  readonly type: "object";
109
175
  readonly additionalProperties: false;
@@ -121,24 +187,46 @@ export declare const editToolSchema: {
121
187
  };
122
188
  readonly edits: {
123
189
  readonly type: "array";
124
- readonly description: "Ordered list of edit tuples";
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)";
125
191
  readonly minItems: 1;
126
192
  readonly maxItems: 32;
127
193
  readonly items: {
128
- readonly type: "array";
129
- readonly prefixItems: readonly [{
130
- readonly type: "string";
131
- readonly description: "First line to remove (inclusive)";
132
- }, {
133
- readonly type: "string";
134
- readonly description: "Last line to remove (inclusive)";
194
+ readonly anyOf: readonly [{
195
+ readonly type: "array";
196
+ readonly prefixItems: readonly [{
197
+ readonly type: "string";
198
+ readonly description: "First line to remove (inclusive)";
199
+ }, {
200
+ readonly type: "string";
201
+ readonly description: "Last line to remove (inclusive)";
202
+ }, {
203
+ readonly type: "string";
204
+ readonly description: 'Complete replacement for the range; use "" to delete';
205
+ }];
206
+ readonly minItems: 3;
207
+ readonly maxItems: 3;
208
+ readonly description: "[remove_from, remove_to, replacement_text]";
135
209
  }, {
136
- readonly type: "string";
137
- readonly description: "Complete replacement for the range; use \"\" to delete";
210
+ readonly type: "object";
211
+ readonly additionalProperties: false;
212
+ readonly required: readonly ["remove_from", "remove_to", "replacement_text"];
213
+ readonly properties: {
214
+ readonly remove_from: {
215
+ readonly type: "string";
216
+ readonly description: "First line to remove (inclusive)";
217
+ };
218
+ readonly remove_to: {
219
+ readonly type: "string";
220
+ readonly description: "Last line to remove (inclusive)";
221
+ };
222
+ readonly replacement_text: {
223
+ readonly type: "string";
224
+ readonly description: 'Complete replacement for the range; use "" to delete';
225
+ };
226
+ };
227
+ readonly description: "{remove_from, remove_to, replacement_text}";
138
228
  }];
139
- readonly minItems: 3;
140
- readonly maxItems: 3;
141
- readonly description: "[remove_from, remove_to, replacement_text]";
229
+ readonly description: "Edit entry — either tuple or object form (mixed batches allowed)";
142
230
  };
143
231
  };
144
232
  };
@@ -1,6 +1,10 @@
1
1
  import type { ServedRow } from "./hashline/anchor-pipeline.js";
2
2
  export type EditDetails = {
3
3
  diff: string;
4
+ /** Bare `E_*` code for the primary error signal, if any (no `[MODEL]` prefix). Structured counterpart to message-string codes. */
5
+ errCode?: string;
6
+ /** Disambiguator for `E_UNSERVED_RANGE`: boundary miss vs interior hole. */
7
+ unservedKind?: "boundary" | "interior";
4
8
  firstChangedLine?: number;
5
9
  snapshotId?: string;
6
10
  classification?: "noop";
@@ -35,7 +35,7 @@ export declare function hasReplacementChar(text: string): boolean;
35
35
  */
36
36
  export declare function detectWithChardet(bytes: Uint8Array, allowlist: string[]): Promise<string | undefined>;
37
37
  /**
38
- * Chardet-based Top-3 for E_NOT_TEXT (primary) and autoGuess.
38
+ * Chardet-based Top-3 for E_UNSUPPORTED_FILE (primary) and autoGuess.
39
39
  * Returns chardet candidates filtered by allowlist and decodable, else empty.
40
40
  */
41
41
  export declare function chardetTop3Candidates(bytes: Uint8Array, allowlist: string[]): Promise<Array<{
@@ -50,7 +50,7 @@ export interface DecodeForOpenOptions {
50
50
  /**
51
51
  * Deterministic admission for a raw byte buffer. No IO, no side effects
52
52
  * except Top-3 scoring. Caller owns recording the returned state via
53
- * `recordOpenState` and handling the footer vs E_NOT_TEXT split.
53
+ * `recordOpenState` and handling the footer vs E_UNSUPPORTED_FILE split.
54
54
  *
55
55
  * Order is fixed: BOM sniff always precedes strict UTF-8, which always
56
56
  * precedes guessing. Probabilistic encodings are last resort, gated by
@@ -64,6 +64,9 @@ export interface EncodeForSaveOptions {
64
64
  normalizeToUtf8?: boolean;
65
65
  currentVersion?: string | undefined;
66
66
  }
67
+ /** Shared UTF-8 BOM marker — single source for the BOM round-trip seam.
68
+ * Prefer `prepareForSave` / `stripBOM` over re-implementing this check. */
69
+ export declare const UTF8_BOM = "\uFEFF";
67
70
  /**
68
71
  * Decide what bytes (as text, since provider expects string) to write and
69
72
  * what new state to record. BOM and lineEnding are restored here when a
@@ -27,7 +27,7 @@ export declare const DEFAULT_MAX_BYTES: number;
27
27
  export interface TruncationResult {
28
28
  content: string;
29
29
  truncated: boolean;
30
- truncatedBy: 'lines' | 'bytes' | null;
30
+ truncatedBy: "lines" | "bytes" | null;
31
31
  totalLines: number;
32
32
  totalBytes: number;
33
33
  outputLines: number;
@@ -91,6 +91,11 @@ export interface ReadNormOptions {
91
91
  noPersist?: boolean;
92
92
  reservedHashes?: ReadonlySet<string>;
93
93
  retiredHashes?: ReadonlySet<string>;
94
+ previous?: {
95
+ content: string;
96
+ hashes: string[];
97
+ removedHashes?: Set<string>;
98
+ };
94
99
  }
95
100
  export declare function normFromText(input: {
96
101
  absolutePath: string;
@@ -103,6 +108,11 @@ export declare function normFromText(input: {
103
108
  reservedHashes?: ReadonlySet<string>;
104
109
  retiredHashes?: ReadonlySet<string>;
105
110
  hadUtf8DecodeErrors?: boolean;
111
+ previous?: {
112
+ content: string;
113
+ hashes: string[];
114
+ removedHashes?: Set<string>;
115
+ };
106
116
  }): Promise<NormFile>;
107
117
  export declare function readNormFile(path: string, cwd: string, options?: ReadNormOptions): Promise<NormFile>;
108
118
  export declare function formatPaginationHint(startLine: number, endLine: number, totalLines: number, nextOffset: number, byteLimit?: number): string;
@@ -136,6 +146,11 @@ export interface ReadViewOpts extends PreviewOpts {
136
146
  signal?: AbortSignal;
137
147
  reservedHashes?: ReadonlySet<string>;
138
148
  retiredHashes?: ReadonlySet<string>;
149
+ previous?: {
150
+ content: string;
151
+ hashes: string[];
152
+ removedHashes?: Set<string>;
153
+ };
139
154
  }
140
155
  export declare function preview(content: string, hashes: string[], opts?: PreviewOpts, absolutePath?: string): Promise<{
141
156
  text: string;
@@ -67,10 +67,14 @@ export interface HashStore {
67
67
  export interface ServedPersistence {
68
68
  getServed(sessionKey: string, path: string): (string | null)[];
69
69
  getServedReported(sessionKey: string, path: string): Set<string>;
70
- getAnchorReservations(path: string): AnchorReservations;
70
+ getAnchorReservations(sessionKey: string, path: string): AnchorReservations;
71
71
  getRetiredAnchors(sessionKey: string, path: string): Set<string>;
72
+ getRetiredEntries(sessionKey: string, path: string): RetiredEntry[];
72
73
  getServedCanons(sessionKey: string, path: string): (string | null)[];
73
74
  getEpochSnapshotId(sessionKey: string, path: string): string | undefined;
75
+ getCards(sessionKey: string, path: string): Set<number>;
76
+ upsertCards(sessionKey: string, path: string, cardsJson: string): void;
77
+ clearCards(sessionKey: string, path: string): void;
74
78
  upsertServed(sessionKey: string, path: string, hashesJson: string): void;
75
79
  upsertServedReported(sessionKey: string, path: string, reportedJson: string): void;
76
80
  clearServedReported(sessionKey: string, path: string): void;
@@ -89,6 +93,13 @@ export interface AnchorReservations {
89
93
  reservedHashes: Set<string>;
90
94
  retiredHashes: Set<string>;
91
95
  }
96
+ export type DeathPos = number | null;
97
+ export interface RetiredEntry {
98
+ hash: string;
99
+ deathPos: DeathPos;
100
+ }
101
+ export declare function isValidRetiredEntry(value: unknown): value is RetiredEntry;
102
+ export declare function isValidRetiredEntries(value: unknown): value is RetiredEntry[];
92
103
  export type InternalHashStore = HashStore & ServedPersistence;
93
104
  /** Load the store as served persistence — internal, for SessionView only. */
94
105
  export declare function loadServedStore(cwd?: string): Promise<ServedPersistence>;