dsh-better-edit 0.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 (82) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +188 -0
  3. package/cordis.patch.yml +8 -0
  4. package/lib/constants.js +12 -0
  5. package/lib/drift.js +98 -0
  6. package/lib/dsh-context.js +27 -0
  7. package/lib/edit-diff.js +121 -0
  8. package/lib/edit-normalize.js +9 -0
  9. package/lib/edit-pipeline.js +199 -0
  10. package/lib/edit-response.js +172 -0
  11. package/lib/file-kind.js +121 -0
  12. package/lib/file-reader.js +80 -0
  13. package/lib/fs-bridge.js +106 -0
  14. package/lib/fs-write.js +151 -0
  15. package/lib/hash-store.js +380 -0
  16. package/lib/hashline/alphabet.js +6 -0
  17. package/lib/hashline/apply.js +223 -0
  18. package/lib/hashline/hash.js +241 -0
  19. package/lib/hashline/hasher.js +23 -0
  20. package/lib/hashline/index.js +4 -0
  21. package/lib/hashline/parse.js +35 -0
  22. package/lib/hashline/resolve.js +365 -0
  23. package/lib/hashline/served.js +120 -0
  24. package/lib/index.js +91 -0
  25. package/lib/noop-guard.js +15 -0
  26. package/lib/paths.js +37 -0
  27. package/lib/prompts.js +54 -0
  28. package/lib/read-render.js +142 -0
  29. package/lib/schema.js +24 -0
  30. package/lib/served-state.js +34 -0
  31. package/lib/served-store.js +230 -0
  32. package/lib/snapshot-store.js +108 -0
  33. package/lib/tool-batch-edit.js +434 -0
  34. package/lib/tool-edit.js +152 -0
  35. package/lib/tool-read.js +86 -0
  36. package/lib/tool-undo.js +118 -0
  37. package/lib/truncate.js +98 -0
  38. package/lib/types/constants.d.ts +11 -0
  39. package/lib/types/drift.d.ts +29 -0
  40. package/lib/types/dsh-context.d.ts +23 -0
  41. package/lib/types/edit-diff.d.ts +14 -0
  42. package/lib/types/edit-normalize.d.ts +1 -0
  43. package/lib/types/edit-pipeline.d.ts +54 -0
  44. package/lib/types/edit-response.d.ts +107 -0
  45. package/lib/types/file-kind.d.ts +18 -0
  46. package/lib/types/file-reader.d.ts +47 -0
  47. package/lib/types/fs-bridge.d.ts +32 -0
  48. package/lib/types/fs-write.d.ts +2 -0
  49. package/lib/types/hash-store.d.ts +33 -0
  50. package/lib/types/hashline/alphabet.d.ts +5 -0
  51. package/lib/types/hashline/apply.d.ts +22 -0
  52. package/lib/types/hashline/hash.d.ts +19 -0
  53. package/lib/types/hashline/hasher.d.ts +8 -0
  54. package/lib/types/hashline/index.d.ts +4 -0
  55. package/lib/types/hashline/parse.d.ts +7 -0
  56. package/lib/types/hashline/resolve.d.ts +59 -0
  57. package/lib/types/hashline/served.d.ts +43 -0
  58. package/lib/types/index.d.ts +23 -0
  59. package/lib/types/noop-guard.d.ts +5 -0
  60. package/lib/types/paths.d.ts +11 -0
  61. package/lib/types/prompts.d.ts +17 -0
  62. package/lib/types/read-render.d.ts +21 -0
  63. package/lib/types/schema.d.ts +39 -0
  64. package/lib/types/served-state.d.ts +3 -0
  65. package/lib/types/served-store.d.ts +53 -0
  66. package/lib/types/snapshot-store.d.ts +14 -0
  67. package/lib/types/tool-batch-edit.d.ts +21 -0
  68. package/lib/types/tool-edit.d.ts +22 -0
  69. package/lib/types/tool-read.d.ts +21 -0
  70. package/lib/types/tool-undo.d.ts +20 -0
  71. package/lib/types/truncate.d.ts +32 -0
  72. package/lib/types/undo-edit.d.ts +32 -0
  73. package/lib/types/undo-store.d.ts +14 -0
  74. package/lib/types/utils.d.ts +13 -0
  75. package/lib/types/validation.d.ts +7 -0
  76. package/lib/types/write-hook.d.ts +21 -0
  77. package/lib/undo-edit.js +83 -0
  78. package/lib/undo-store.js +43 -0
  79. package/lib/utils.js +76 -0
  80. package/lib/validation.js +33 -0
  81. package/lib/write-hook.js +72 -0
  82. package/package.json +87 -0
@@ -0,0 +1,365 @@
1
+ import { abortIf, rejectUnknownFields, firstNonEmptyIndex, lastNonEmptyIndex, clipLine, } from "../utils.js";
2
+ import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, canon, } from "./hash.js";
3
+ import { parseHashRef, parseText } from "./parse.js";
4
+ import { NEW_CONTENT_NOT_STRING_MSG } from "../constants.js";
5
+ function resAnchorFromMap(ref, hashIndex) {
6
+ const hashMatches = hashIndex.get(ref.hash);
7
+ if (!hashMatches || hashMatches.length === 0) {
8
+ return { ref, kind: "not_found" };
9
+ }
10
+ if (hashMatches.length === 1) {
11
+ return {
12
+ line: hashMatches[0],
13
+ hash: ref.hash,
14
+ hashMatched: true,
15
+ };
16
+ }
17
+ return { ref, kind: "ambiguous", candidates: hashMatches };
18
+ }
19
+ function assertAligned(fileLines, fileHashes, ctx) {
20
+ if (fileHashes.length !== fileLines.length) {
21
+ throw new Error(`${ctx}: fileHashes.length (${fileHashes.length}) must match fileLines.length (${fileLines.length}).`);
22
+ }
23
+ }
24
+ export function fmtMismatch(mismatches, fileLines, fileHashes, filePath) {
25
+ return fmtMismatchWithServes(mismatches, fileLines, fileHashes, filePath)
26
+ .message;
27
+ }
28
+ export function fmtMismatchWithServes(mismatches, fileLines, fileHashes, filePath) {
29
+ assertAligned(fileLines, fileHashes, "fmtMismatch");
30
+ const out = [];
31
+ const servedRows = [];
32
+ const seen = new Set();
33
+ const pushRow = (ln) => {
34
+ if (ln < 1 || ln > fileLines.length)
35
+ return;
36
+ const position = ln - 1;
37
+ if (seen.has(position))
38
+ return;
39
+ seen.add(position);
40
+ servedRows.push({ position, hash: fileHashes[ln - 1] });
41
+ };
42
+ const notFound = mismatches.filter((m) => m.kind === "not_found");
43
+ const ambiguous = mismatches.filter((m) => m.kind === "ambiguous");
44
+ const refList = notFound.map((m) => `"${m.ref.hash}"`).join(", ");
45
+ if (notFound.length > 0) {
46
+ out.push(`[E_STALE_ANCHOR] ${notFound.length} stale anchor${notFound.length > 1 ? "s" : ""}${filePath ? ` in ${filePath}` : ""}: ${refList}. The file content has changed since those anchors were read. Call read() to get fresh anchors, then copy the 3-char HASH of the start and end of the range you are editing into remove_from and remove_to of your next edit call.`);
47
+ for (const m of notFound) {
48
+ const ctx = m.context;
49
+ if (!ctx)
50
+ continue;
51
+ const from = Math.max(1, ctx.line - 1);
52
+ const to = Math.min(fileLines.length, ctx.line + 1);
53
+ const rows = [];
54
+ for (let ln = from; ln <= to; ln++) {
55
+ rows.push(` ${ln}: ${fileHashes[ln - 1]}│${clipLine(fileLines[ln - 1] ?? "")}`);
56
+ pushRow(ln);
57
+ }
58
+ out.push("");
59
+ out.push(` Current context around resolved anchor "${ctx.hash}" (line ${ctx.line}):\n${rows.join("\n")}`);
60
+ }
61
+ }
62
+ if (ambiguous.length > 0) {
63
+ if (out.length > 0)
64
+ out.push("");
65
+ out.push(`[E_AMBIGUOUS_ANCHOR] ${ambiguous.length} ambiguous anchor${ambiguous.length > 1 ? "s" : ""}${filePath ? ` in ${filePath}` : ""}. Call read() to get fresh anchors, then copy the 3-char HASH of the start and end of the range you are editing into remove_from and remove_to of your next edit call.`);
66
+ for (const m of ambiguous) {
67
+ const sample = (m.candidates ?? []).slice(0, 5);
68
+ const more = (m.candidates?.length ?? 0) > sample.length
69
+ ? `, ... (+${(m.candidates?.length ?? 0) - sample.length} more)`
70
+ : "";
71
+ const lines = sample
72
+ .map((line) => {
73
+ const content = clipLine(fileLines[line - 1] ?? "");
74
+ pushRow(line);
75
+ return ` ${line}: ${fileHashes[line - 1]}│${content}`;
76
+ })
77
+ .join("\n");
78
+ out.push(` Hash "${m.ref.hash}" matches lines ${sample.join(", ")}${more}.\n${lines}`);
79
+ }
80
+ }
81
+ return { message: out.join("\n"), servedRows };
82
+ }
83
+ const ITEM_KS = new Set(["replacement_text", "remove_from", "remove_to"]);
84
+ function assertItem(edit) {
85
+ rejectUnknownFields(edit, ITEM_KS, "Edit", "The edit takes only { replacement_text, remove_from, remove_to }.");
86
+ if ("remove_from" in edit && typeof edit.remove_from !== "string") {
87
+ throw new Error(`[E_BAD_SHAPE] Field "remove_from" must be an anchor string (3-char hash).`);
88
+ }
89
+ if ("remove_to" in edit && typeof edit.remove_to !== "string") {
90
+ throw new Error(`[E_BAD_SHAPE] Field "remove_to" must be an anchor string (3-char hash).`);
91
+ }
92
+ if (!("replacement_text" in edit)) {
93
+ throw new Error(`[E_BAD_SHAPE] The edit requires a "replacement_text" field. Provide the replacement text (use "" to delete).`);
94
+ }
95
+ if (typeof edit.replacement_text !== "string") {
96
+ throw new Error(NEW_CONTENT_NOT_STRING_MSG);
97
+ }
98
+ if (typeof edit.remove_from !== "string" ||
99
+ typeof edit.remove_to !== "string") {
100
+ throw new Error(`[E_BAD_SHAPE] The edit requires "remove_from" and "remove_to" anchor strings (3-char hashes from read output).`);
101
+ }
102
+ }
103
+ const ANCHOR_ROW_RE = new RegExp(`^([+-]?)(${HASH_CLASS})│`);
104
+ export function resEdit(edit, warnings) {
105
+ assertItem(edit);
106
+ const editLines = parseText(edit.replacement_text);
107
+ const bounds = [edit.remove_from, edit.remove_to].map((ref) => {
108
+ const trimmed = ref.trim();
109
+ const match = trimmed.match(ANCHOR_ROW_RE);
110
+ if (match) {
111
+ let message;
112
+ if (match[1] === "+") {
113
+ message = `[E_BAD_REF] Autocorrected: stripped diff-preview marker copied from the diff preview in remove_from/remove_to entry "${trimmed}".`;
114
+ }
115
+ else if (match[1] === "-") {
116
+ message = `[E_BAD_REF] Autocorrected: stripped leading "-" marker in remove_from/remove_to entry "${trimmed}".`;
117
+ }
118
+ else {
119
+ message = `[E_BAD_REF] Autocorrected: stripped "HASH│" prefix copied from read output in remove_from/remove_to entry "${trimmed}".`;
120
+ }
121
+ warnings?.push(message);
122
+ return match[2];
123
+ }
124
+ return ref;
125
+ });
126
+ return {
127
+ content_lines: editLines,
128
+ hash_bounds: [parseHashRef(bounds[0]), parseHashRef(bounds[1])],
129
+ };
130
+ }
131
+ function warnUnicodeEsc(edit, warnings) {
132
+ if (edit.content_lines.some((line) => /\\uDDDD/i.test(line))) {
133
+ warnings.push("Detected literal \\uDDDD in edit content; no autocorrection applied. Verify whether this should be a real Unicode escape or plain text.");
134
+ }
135
+ }
136
+ export function stripBarePrefixes(edit, fileHashes, warnings) {
137
+ const fileHashSet = new Set(fileHashes);
138
+ const stripped = [];
139
+ const contentLines = edit.content_lines.map((line, lineIndex) => {
140
+ const match = line.match(HL_BARE_PREFIX_RE);
141
+ if (!match)
142
+ return line;
143
+ stripped.push({ lineIndex, matched: fileHashSet.has(match[1]) });
144
+ return line.slice(match[0].length);
145
+ });
146
+ if (stripped.length === 0)
147
+ return edit;
148
+ const locations = stripped
149
+ .map((s) => `replacement_text line ${s.lineIndex + 1}`)
150
+ .join(", ");
151
+ const matchedCount = stripped.filter((s) => s.matched).length;
152
+ const evidence = matchedCount === 0
153
+ ? "none of the stripped hashes match current file lines"
154
+ : `${matchedCount} of ${stripped.length} stripped hash(es) match current file lines`;
155
+ const guidance = matchedCount === 0
156
+ ? " Verify that these lines were pasted from read output; literal content starting with 'HASH│' would be altered by this strip."
157
+ : "";
158
+ warnings.push(`[E_BARE_HASH_PREFIX] Autocorrected: stripped "HASH│" prefix copied from read output in ${locations} (${evidence}).${guidance}`);
159
+ return { ...edit, content_lines: contentLines };
160
+ }
161
+ export function stripDiffPrefixes(edit, warnings) {
162
+ const stripped = [];
163
+ const contentLines = edit.content_lines.map((line, lineIndex) => {
164
+ const plus = line.match(HL_PREFIX_PLUS_RE);
165
+ if (plus) {
166
+ stripped.push(lineIndex);
167
+ return line.slice(plus[0].length);
168
+ }
169
+ const minus = line.match(HL_PREFIX_MINUS_RE);
170
+ if (minus) {
171
+ stripped.push(lineIndex);
172
+ return line.slice(minus[0].length);
173
+ }
174
+ return line;
175
+ });
176
+ if (stripped.length === 0)
177
+ return edit;
178
+ const locations = stripped
179
+ .map((i) => `replacement_text line ${i + 1}`)
180
+ .join(", ");
181
+ warnings.push(`[E_INVALID_PATCH] Autocorrected: stripped diff-preview marker copied from the diff preview in ${locations}.`);
182
+ return { ...edit, content_lines: contentLines };
183
+ }
184
+ export function swapReversedRanges(edit, fileHashes, warnings) {
185
+ const lineByHash = new Map();
186
+ for (let i = 0; i < fileHashes.length; i++) {
187
+ lineByHash.set(fileHashes[i], i + 1);
188
+ }
189
+ const [startRef, endRef] = edit.hash_bounds;
190
+ const startLine = lineByHash.get(startRef.hash);
191
+ const endLine = lineByHash.get(endRef.hash);
192
+ if (startLine === undefined ||
193
+ endLine === undefined ||
194
+ startLine <= endLine) {
195
+ return edit;
196
+ }
197
+ warnings.push(`[E_BAD_OP] Autocorrected: remove_from and remove_to were reversed (remove_from ${startRef.hash} is after remove_to ${endRef.hash}); swapped the pair.`);
198
+ return { ...edit, hash_bounds: [endRef, startRef] };
199
+ }
200
+ function trailingDups(contentLines, fileLines, endLine) {
201
+ const start = lastNonEmptyIndex(contentLines);
202
+ if (start < 0)
203
+ return [];
204
+ const dups = [];
205
+ const maxK = Math.min(start + 1, fileLines.length - endLine);
206
+ for (let k = 0; k < maxK; k++) {
207
+ if (contentLines[start - k] !== fileLines[endLine + k])
208
+ break;
209
+ dups.push({ kind: "trailing", replacementLineIndex: start - k });
210
+ }
211
+ return dups;
212
+ }
213
+ function leadingDups(contentLines, fileLines, startLine) {
214
+ const start = firstNonEmptyIndex(contentLines);
215
+ if (start < 0)
216
+ return [];
217
+ const dups = [];
218
+ const maxK = Math.min(contentLines.length - start, startLine - 1);
219
+ for (let k = 0; k < maxK; k++) {
220
+ if (contentLines[start + k] !== fileLines[startLine - 2 - k])
221
+ break;
222
+ dups.push({ kind: "leading", replacementLineIndex: start + k });
223
+ }
224
+ return dups;
225
+ }
226
+ function sectionIsUnique(canonLines, start, length) {
227
+ let count = 0;
228
+ for (let i = 0; i + length <= canonLines.length; i++) {
229
+ let k = 0;
230
+ while (k < length && canonLines[i + k] === canonLines[start + k])
231
+ k++;
232
+ if (k < length)
233
+ continue;
234
+ count++;
235
+ if (count > 1)
236
+ return false;
237
+ }
238
+ return true;
239
+ }
240
+ function firstNewAfterDups(contentLines, rangeLines, canonLines, endLine) {
241
+ const firstNew = findNewEdge(contentLines, rangeLines, false);
242
+ if (!firstNew)
243
+ return [];
244
+ const maxK = Math.min(contentLines.length - firstNew.index, canonLines.length - endLine);
245
+ let runLen = 0;
246
+ while (runLen < maxK &&
247
+ canon(contentLines[firstNew.index + runLen]) ===
248
+ canonLines[endLine + runLen]) {
249
+ runLen++;
250
+ }
251
+ if (runLen === 0 || !sectionIsUnique(canonLines, endLine, runLen))
252
+ return [];
253
+ const dups = [];
254
+ for (let k = 0; k < runLen; k++) {
255
+ dups.push({
256
+ kind: "first-new-after",
257
+ replacementLineIndex: firstNew.index + k,
258
+ });
259
+ }
260
+ return dups;
261
+ }
262
+ function lastNewBeforeDups(contentLines, rangeLines, canonLines, startLine) {
263
+ const lastNew = findNewEdge(contentLines, rangeLines, true);
264
+ if (!lastNew)
265
+ return [];
266
+ const maxK = Math.min(lastNew.index + 1, startLine - 1);
267
+ let runLen = 0;
268
+ while (runLen < maxK &&
269
+ canon(contentLines[lastNew.index - runLen]) ===
270
+ canonLines[startLine - 2 - runLen]) {
271
+ runLen++;
272
+ }
273
+ if (runLen === 0)
274
+ return [];
275
+ const sectionStart = startLine - 1 - runLen;
276
+ if (!sectionIsUnique(canonLines, sectionStart, runLen))
277
+ return [];
278
+ const dups = [];
279
+ for (let k = 0; k < runLen; k++) {
280
+ dups.push({
281
+ kind: "last-new-before",
282
+ replacementLineIndex: lastNew.index - k,
283
+ });
284
+ }
285
+ return dups;
286
+ }
287
+ function canonCounts(lines) {
288
+ const counts = new Map();
289
+ for (const line of lines) {
290
+ const key = canon(line);
291
+ counts.set(key, (counts.get(key) ?? 0) + 1);
292
+ }
293
+ return counts;
294
+ }
295
+ export function findNewEdge(contentLines, rangeLines, fromEnd) {
296
+ const multiset = canonCounts(rangeLines);
297
+ const step = fromEnd ? -1 : 1;
298
+ const start = fromEnd ? contentLines.length - 1 : 0;
299
+ for (let i = start; i >= 0 && i < contentLines.length; i += step) {
300
+ const line = contentLines[i];
301
+ if (line.length === 0)
302
+ continue;
303
+ const key = canon(line);
304
+ const count = multiset.get(key) ?? 0;
305
+ if (count > 0) {
306
+ multiset.set(key, count - 1);
307
+ }
308
+ else {
309
+ return { index: i, line };
310
+ }
311
+ }
312
+ return undefined;
313
+ }
314
+ export function valEdit(edit, fileLines, fileHashes, warnings, signal) {
315
+ assertAligned(fileLines, fileHashes, "valEdit");
316
+ const mismatches = [];
317
+ const boundaryDups = [];
318
+ const hashIndex = new Map();
319
+ for (let i = 0; i < fileHashes.length; i++) {
320
+ const h = fileHashes[i];
321
+ const list = hashIndex.get(h) ?? [];
322
+ list.push(i + 1);
323
+ hashIndex.set(h, list);
324
+ }
325
+ const tryResolve = (ref) => {
326
+ const result = resAnchorFromMap(ref, hashIndex);
327
+ if ("kind" in result) {
328
+ mismatches.push(result);
329
+ return undefined;
330
+ }
331
+ return result;
332
+ };
333
+ abortIf(signal);
334
+ const startResolved = tryResolve(edit.hash_bounds[0]);
335
+ const endResolved = tryResolve(edit.hash_bounds[1]);
336
+ if (!startResolved || !endResolved) {
337
+ if (!startResolved && endResolved) {
338
+ const startMismatch = mismatches.findLast((m) => m.ref === edit.hash_bounds[0]);
339
+ if (startMismatch && startMismatch.kind === "not_found")
340
+ startMismatch.context = endResolved;
341
+ }
342
+ else if (startResolved && !endResolved) {
343
+ const endMismatch = mismatches.findLast((m) => m.ref === edit.hash_bounds[1]);
344
+ if (endMismatch && endMismatch.kind === "not_found")
345
+ endMismatch.context = startResolved;
346
+ }
347
+ return { resolved: undefined, mismatches, boundaryDups };
348
+ }
349
+ if (startResolved.line > endResolved.line) {
350
+ throw new Error(`[E_BAD_OP] Range start line ${startResolved.line} must be <= end line ${endResolved.line} (anchors ${edit.hash_bounds[0].hash} and ${edit.hash_bounds[1].hash}).`);
351
+ }
352
+ const endLine = endResolved.line;
353
+ const rangeLines = fileLines.slice(startResolved.line - 1, endLine);
354
+ const canonLines = fileLines.map((line) => canon(line));
355
+ boundaryDups.push(...trailingDups(edit.content_lines, fileLines, endLine), ...leadingDups(edit.content_lines, fileLines, startResolved.line), ...firstNewAfterDups(edit.content_lines, rangeLines, canonLines, endLine), ...lastNewBeforeDups(edit.content_lines, rangeLines, canonLines, startResolved.line));
356
+ return {
357
+ resolved: {
358
+ content_lines: edit.content_lines,
359
+ hash_bounds: [startResolved, endResolved],
360
+ },
361
+ mismatches,
362
+ boundaryDups,
363
+ };
364
+ }
365
+ export { warnUnicodeEsc };
@@ -0,0 +1,120 @@
1
+ import { HASH_SEP } from "./hash.js";
2
+ import { recordServed, servedPositionsOf } from "../served-state.js";
3
+ import { SERVED_ECHO_CAP } from "../constants.js";
4
+ export class ServedRejectionError extends Error {
5
+ code;
6
+ firstOffendingLine;
7
+ servedRows;
8
+ constructor(opts) {
9
+ super(opts.message);
10
+ this.name = "ServedRejectionError";
11
+ this.code = opts.code;
12
+ this.firstOffendingLine = opts.firstOffendingLine;
13
+ this.servedRows = opts.servedRows;
14
+ }
15
+ }
16
+ export function isServedRejection(error) {
17
+ return error instanceof ServedRejectionError;
18
+ }
19
+ export class AnchorMismatchError extends Error {
20
+ servedRows;
21
+ constructor(message, servedRows) {
22
+ super(message);
23
+ this.name = "AnchorMismatchError";
24
+ this.servedRows = servedRows;
25
+ }
26
+ }
27
+ export function isAnchorMismatch(error) {
28
+ return error instanceof AnchorMismatchError;
29
+ }
30
+ export function buildRangeEcho(startLine, endLine, fileHashes) {
31
+ const total = endLine - startLine + 1;
32
+ const shown = Math.min(total, SERVED_ECHO_CAP);
33
+ const rows = [];
34
+ for (let ln = startLine; ln < startLine + shown; ln++) {
35
+ rows.push({ position: ln - 1, hash: fileHashes[ln - 1] });
36
+ }
37
+ return rows;
38
+ }
39
+ export function fmtServedRows(rows, fileLines) {
40
+ return rows
41
+ .map((row) => `${row.hash}${HASH_SEP}${fileLines[row.position] ?? ""}`)
42
+ .join("\n");
43
+ }
44
+ function retryHint() {
45
+ return "Retry the edit with remove_from/remove_to copied from these fresh rows (no read needed).";
46
+ }
47
+ function paginationHint(nextOffset, more) {
48
+ return `[... ${more} more lines — use read with offset=${nextOffset} to see the rest]`;
49
+ }
50
+ export function verifyServedRange(args) {
51
+ const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath, } = args;
52
+ const where = filePath ? ` in ${filePath}` : "";
53
+ const echoRows = buildRangeEcho(startLine, endLine, fileHashes);
54
+ const totalLen = endLine - startLine + 1;
55
+ const tail = echoRows.length < totalLen
56
+ ? `\n${paginationHint(startLine + echoRows.length, totalLen - echoRows.length)}`
57
+ : "";
58
+ const echo = fmtServedRows(echoRows, fileLines) + tail;
59
+ const startPositions = servedPositionsOf(served, startHash);
60
+ const endPositions = servedPositionsOf(served, endHash);
61
+ if (startPositions.length !== 1 || endPositions.length !== 1) {
62
+ const problems = [];
63
+ if (startPositions.length === 0) {
64
+ problems.push(`remove_from "${startHash}" has no served position`);
65
+ }
66
+ else if (startPositions.length > 1) {
67
+ problems.push(`remove_from "${startHash}" was served at ${startPositions.length} positions`);
68
+ }
69
+ if (endPositions.length === 0) {
70
+ problems.push(`remove_to "${endHash}" has no served position`);
71
+ }
72
+ else if (endPositions.length > 1) {
73
+ problems.push(`remove_to "${endHash}" was served at ${endPositions.length} positions`);
74
+ }
75
+ throw new ServedRejectionError({
76
+ code: "E_RANGE_UNVERIFIED",
77
+ message: `[E_RANGE_UNVERIFIED] Cannot verify the range against served state${where}: ${problems.join("; ")}. ` +
78
+ `The tool only verifies what it delivered to the model's context; a boundary anchor that cannot be verified is never guessed at. Current range:\n${echo}\n${retryHint()}`,
79
+ servedRows: echoRows,
80
+ });
81
+ }
82
+ const from = Math.min(startPositions[0], endPositions[0]);
83
+ const to = Math.max(startPositions[0], endPositions[0]);
84
+ for (let i = from; i <= to; i++) {
85
+ if (served[i] === null) {
86
+ throw new ServedRejectionError({
87
+ code: "E_RANGE_UNSERVED",
88
+ message: `[E_RANGE_UNSERVED] Line ${i + 1}${where} was never served to the model — the range includes lines the model has not seen. Current range:\n${echo}\n${retryHint()}`,
89
+ firstOffendingLine: i + 1,
90
+ servedRows: echoRows,
91
+ });
92
+ }
93
+ }
94
+ const servedLen = to - from + 1;
95
+ const currentLen = endLine - startLine + 1;
96
+ if (servedLen !== currentLen) {
97
+ throw new ServedRejectionError({
98
+ code: "E_RANGE_STALE",
99
+ message: `[E_RANGE_STALE] The served span (${servedLen} lines) no longer matches the current range (${currentLen} lines)${where}. Current range:\n${echo}\n${retryHint()}`,
100
+ firstOffendingLine: startLine,
101
+ servedRows: echoRows,
102
+ });
103
+ }
104
+ for (let k = 0; k < servedLen; k++) {
105
+ if (served[from + k] !== fileHashes[startLine - 1 + k]) {
106
+ const offendingLine = startLine + k;
107
+ throw new ServedRejectionError({
108
+ code: "E_RANGE_STALE",
109
+ message: `[E_RANGE_STALE] Line ${offendingLine}${where} differs from what you were served — the file changed on disk since it was read. Current range:\n${echo}\n${retryHint()}`,
110
+ firstOffendingLine: offendingLine,
111
+ servedRows: echoRows,
112
+ });
113
+ }
114
+ }
115
+ }
116
+ export async function recordEchoServes(sessionKey, path, rows, policy) {
117
+ if (policy !== "live")
118
+ return;
119
+ await recordServed(sessionKey, path, rows);
120
+ }
package/lib/index.js ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * dsh-better-edit — hash-anchored read/edit/batch_edit/undo_last_edit for
3
+ * DeepSeek Harness, a dsh port of pi-hashline-edit-lsz.
4
+ *
5
+ * Cordis host-plane plugin (mounted by the bundle's cordis.patch.yml). On
6
+ * `agent/session-start` it registers the hashline tools and prompt sections on
7
+ * the AGENT's own scope layer, so they shadow the preset's built-in `read` /
8
+ * `edit` for that agent (nearest layer wins in dsh's tool registry) and unwind
9
+ * automatically when the agent is disposed. The built-in `write` stays in
10
+ * place; a scoped `tools/post-execute` listener appends the fresh hashline
11
+ * preview to write results.
12
+ * @module dsh-better-edit
13
+ */
14
+ import { ctxFsIO } from './fs-bridge.js';
15
+ import { registerReadTool } from './tool-read.js';
16
+ import { registerEditTool } from './tool-edit.js';
17
+ import { registerBatchEditTool } from './tool-batch-edit.js';
18
+ import { registerUndoTool } from './tool-undo.js';
19
+ import { registerWriteHook } from './write-hook.js';
20
+ import { initHasher } from './hashline/hasher.js';
21
+ import { pruneMissingAll } from './snapshot-store.js';
22
+ import { EDIT_DESCRIPTION, EDIT_GUIDELINES, READ_GUIDELINES, BATCH_EDIT_GUIDELINES, UNDO_GUIDELINES, } from './prompts.js';
23
+ /** Cordis plugin name used by loader diagnostics. */
24
+ export const name = 'dsh-better-edit';
25
+ function installAgentTools(rootCtx, agent) {
26
+ return agent.ctx.effect(() => {
27
+ const io = ctxFsIO(agent.ctx.fs, agent.ctx);
28
+ const disposers = [];
29
+ disposers.push(registerReadTool(rootCtx, agent.ctx, io));
30
+ disposers.push(registerEditTool(rootCtx, agent.ctx, io));
31
+ disposers.push(registerBatchEditTool(rootCtx, agent.ctx, io));
32
+ disposers.push(registerUndoTool(rootCtx, agent.ctx, io));
33
+ disposers.push(registerWriteHook(rootCtx, agent.ctx, io));
34
+ // Shadow the preset's built-in tool guidance with the hashline contract.
35
+ // Same section names on the agent's own layer win over the preset's.
36
+ disposers.push(agent.ctx.systemPrompt.section({
37
+ name: 'tool:edit',
38
+ order: 102,
39
+ text: [
40
+ EDIT_DESCRIPTION,
41
+ '',
42
+ EDIT_GUIDELINES.map((line) => `- ${line}`).join('\n'),
43
+ ].join('\n'),
44
+ }));
45
+ disposers.push(agent.ctx.systemPrompt.section({
46
+ name: 'tool:read',
47
+ order: 100,
48
+ text: [
49
+ 'Use the read tool — not shell commands like cat — to inspect text files.',
50
+ '',
51
+ READ_GUIDELINES.map((line) => `- ${line}`).join('\n'),
52
+ ].join('\n'),
53
+ }));
54
+ disposers.push(agent.ctx.systemPrompt.section({
55
+ name: 'tool:batch_edit',
56
+ order: 103,
57
+ text: BATCH_EDIT_GUIDELINES.map((line) => `- ${line}`).join('\n'),
58
+ }));
59
+ disposers.push(agent.ctx.systemPrompt.section({
60
+ name: 'tool:undo_last_edit',
61
+ order: 104,
62
+ text: UNDO_GUIDELINES.map((line) => `- ${line}`).join('\n'),
63
+ }));
64
+ return () => {
65
+ for (const dispose of disposers)
66
+ dispose();
67
+ };
68
+ });
69
+ }
70
+ /** Mount the bundle: initialize the store, then install tools per agent. */
71
+ export function apply(rootCtx) {
72
+ // Warm the hasher and prune missing snapshots once; failures are non-fatal
73
+ // (each store operation retries on demand).
74
+ initHasher()
75
+ .then(() => pruneMissingAll())
76
+ .catch((error) => {
77
+ rootCtx.logger.warn(`dsh-better-edit: hash-store warm-up failed: ${error instanceof Error ? error.message : String(error)}`);
78
+ });
79
+ const registered = new WeakSet();
80
+ rootCtx.on('agent/session-start', ({ agent }) => {
81
+ if (registered.has(agent))
82
+ return;
83
+ registered.add(agent);
84
+ try {
85
+ installAgentTools(rootCtx, agent);
86
+ }
87
+ catch (error) {
88
+ rootCtx.logger.warn(`dsh-better-edit: failed to install tools for agent ${agent.id}: ${error instanceof Error ? error.message : String(error)}`);
89
+ }
90
+ });
91
+ }
@@ -0,0 +1,15 @@
1
+ import { NOOP_LOOP_THRESHOLD } from "./constants.js";
2
+ const noopLoopTracker = new Map();
3
+ export function noopPayloadKey(absolutePath, removeFrom, removeTo, replacementText) {
4
+ return JSON.stringify([absolutePath, removeFrom, removeTo, replacementText]);
5
+ }
6
+ export function trackNoopPayload(absolutePath, payload) {
7
+ const existing = noopLoopTracker.get(absolutePath);
8
+ const count = existing && existing.payload === payload ? existing.count + 1 : 1;
9
+ noopLoopTracker.set(absolutePath, { payload, count });
10
+ return count;
11
+ }
12
+ export function clearNoopLoop(absolutePath) {
13
+ noopLoopTracker.delete(absolutePath);
14
+ }
15
+ export { NOOP_LOOP_THRESHOLD };
package/lib/paths.js ADDED
@@ -0,0 +1,37 @@
1
+ import { homedir } from "node:os";
2
+ import { isAbsolute, resolve as resolvePath, join, dirname } from "node:path";
3
+ import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
4
+ /**
5
+ * On-disk home for dsh-better-edit state, under the DeepSeek Harness home
6
+ * ($DSH_HOME, defaulting to ~/.dsh). The hashline hash snapshots, served-state
7
+ * rows, and undo history live under a plugin-owned subdirectory so multiple
8
+ * dsh installs on one machine share one coherent store keyed by absolute path.
9
+ */
10
+ export function configDir() {
11
+ return join(resolveDshHome(), "plugins", "dsh-better-edit");
12
+ }
13
+ export function hashStorePath() {
14
+ return join(configDir(), "hash-store.sqlite");
15
+ }
16
+ export function legacyHashStorePath() {
17
+ return join(configDir(), "hash-store.json");
18
+ }
19
+ export function hashStoreDir() {
20
+ return dirname(hashStorePath());
21
+ }
22
+ function homeBase() {
23
+ const envHome = process.env.HOME;
24
+ return envHome && envHome.length > 0 ? envHome : homedir();
25
+ }
26
+ function expand(filePath) {
27
+ const home = homeBase();
28
+ if (filePath === "~")
29
+ return home;
30
+ if (filePath.startsWith("~/"))
31
+ return home + filePath.slice(1);
32
+ return filePath;
33
+ }
34
+ export function toCwd(filePath, cwd) {
35
+ const expanded = expand(filePath);
36
+ return isAbsolute(expanded) ? expanded : resolvePath(cwd, expanded);
37
+ }