dsh-better-edit 0.3.0 → 0.3.2

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 (74) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +9 -5
  3. package/README.zh.md +1 -2
  4. package/lib/constants.js +3 -1
  5. package/lib/contract.js +133 -76
  6. package/lib/drift.js +5 -98
  7. package/lib/dsh-context.js +2 -24
  8. package/lib/edit-engine.js +6 -5
  9. package/lib/edit-pipeline.js +3 -121
  10. package/lib/edit-response.js +16 -8
  11. package/lib/file-kind.js +6 -121
  12. package/lib/file-reader.js +4 -77
  13. package/lib/file-view.js +446 -23
  14. package/lib/fs-bridge.js +39 -1
  15. package/lib/guidance/materialize.js +25 -4
  16. package/lib/guidance/resolve.js +3 -9
  17. package/lib/hash-store.js +6 -3
  18. package/lib/hashline/alphabet.js +2 -6
  19. package/lib/hashline/anchor-pipeline.js +770 -7
  20. package/lib/hashline/apply.js +2 -223
  21. package/lib/hashline/hash-assign.js +248 -13
  22. package/lib/hashline/hash.js +67 -29
  23. package/lib/hashline/hasher.js +2 -23
  24. package/lib/hashline/index.js +7 -1
  25. package/lib/hashline/parse.js +2 -35
  26. package/lib/hashline/pure.js +2 -213
  27. package/lib/hashline/resolve.js +3 -366
  28. package/lib/hashline/served.js +2 -120
  29. package/lib/index.js +0 -2
  30. package/lib/mutation.js +218 -10
  31. package/lib/noop-guard.js +20 -0
  32. package/lib/preview-controller.js +65 -0
  33. package/lib/prompts.js +14 -20
  34. package/lib/read-render.js +3 -139
  35. package/lib/served-store.js +2 -216
  36. package/lib/session-view.js +309 -11
  37. package/lib/tool-edit.js +71 -125
  38. package/lib/tool-undo.js +11 -5
  39. package/lib/truncate.js +3 -95
  40. package/lib/types/constants.d.ts +2 -0
  41. package/lib/types/contract.d.ts +102 -28
  42. package/lib/types/drift.d.ts +5 -29
  43. package/lib/types/dsh-context.d.ts +2 -20
  44. package/lib/types/edit-pipeline.d.ts +3 -44
  45. package/lib/types/file-kind.d.ts +6 -18
  46. package/lib/types/file-reader.d.ts +4 -45
  47. package/lib/types/file-view.d.ts +99 -34
  48. package/lib/types/guidance/materialize.d.ts +3 -3
  49. package/lib/types/guidance/resolve.d.ts +2 -2
  50. package/lib/types/hashline/alphabet.d.ts +1 -5
  51. package/lib/types/hashline/anchor-pipeline.d.ts +111 -10
  52. package/lib/types/hashline/apply.d.ts +1 -22
  53. package/lib/types/hashline/hash-assign.d.ts +25 -19
  54. package/lib/types/hashline/hash.d.ts +8 -9
  55. package/lib/types/hashline/hasher.d.ts +1 -8
  56. package/lib/types/hashline/index.d.ts +7 -1
  57. package/lib/types/hashline/parse.d.ts +1 -7
  58. package/lib/types/hashline/pure.d.ts +1 -26
  59. package/lib/types/hashline/resolve.d.ts +1 -63
  60. package/lib/types/hashline/served.d.ts +1 -43
  61. package/lib/types/mutation.d.ts +63 -10
  62. package/lib/types/noop-guard.d.ts +29 -0
  63. package/lib/types/preview-controller.d.ts +33 -0
  64. package/lib/types/prompts.d.ts +9 -9
  65. package/lib/types/read-render.d.ts +3 -18
  66. package/lib/types/served-store.d.ts +2 -81
  67. package/lib/types/session-view.d.ts +68 -9
  68. package/lib/types/tool-edit.d.ts +3 -14
  69. package/lib/types/truncate.d.ts +3 -29
  70. package/lib/types/validation.d.ts +6 -7
  71. package/lib/types/workspace.d.ts +2 -21
  72. package/lib/validation.js +6 -33
  73. package/lib/workspace.js +2 -27
  74. package/package.json +2 -2
@@ -11,13 +11,776 @@
11
11
  * applyEdit — full pipeline (file + hashes + served verification)
12
12
  *
13
13
  * Private to this seam (not re-exported): stripBarePrefixes, stripDiffPrefixes,
14
- * swapReversedRanges, valEdit, boundaryDups helpers, warnUnicodeEsc, findNewEdge.
15
- * They remain exported from resolve.ts for backwards compat but are marked
16
- * @internal and should be imported via this module only.
14
+ * swapReversedRanges, valEdit, boundaryDups helpers, warnUnicodeEsc, findNewEdge,
15
+ * resAnchorFromMap, assertAligned, etc. They remain exported from resolve.ts
16
+ * for backwards compat but are marked @internal and should be imported via this
17
+ * module only.
17
18
  *
18
19
  * @module dsh-better-edit/hashline/anchor-pipeline
19
20
  */
20
- export { resEdit } from "./resolve.js";
21
- export { applyEdit, fmtRegion, changedRange, buildIdx } from "./apply.js";
22
- export { parseHashRef, parseText } from "./parse.js";
23
- export { ServedRejectionError, AnchorMismatchError, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, recordEchoServes, } from "./served.js";
21
+ import { abortIf, splitLines, rejectUnknownFields, firstNonEmptyIndex, lastNonEmptyIndex, clipLine } from "../utils.js";
22
+ import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HASH_SEP, ANCHOR_LEN, ALPH_RE, canon, lineHashesPure } from "./hash-assign.js";
23
+ import { recordServed, servedPositionsOf } from "../served-store.js";
24
+ import { SERVED_ECHO_CAP } from "../constants.js";
25
+ import { NEW_CONTENT_NOT_STRING_MSG } from "../constants.js";
26
+ function diagRef(ref) {
27
+ const trimmed = ref.trim();
28
+ if (!trimmed.length) {
29
+ return `[E_BAD_REF] Invalid anchor. Expected a 3-char alphanumeric anchor (e.g. "aB3").`;
30
+ }
31
+ if (/^\d+/.test(trimmed)) {
32
+ return `[E_BAD_REF] Invalid anchor. Use the hash alone (e.g. "aB3") — no line numbers or trailing content.`;
33
+ }
34
+ if (trimmed.includes("│")) {
35
+ return `[E_BAD_REF] Invalid anchor "${trimmed}". remove_from and remove_to must contain the 3-char hash only — remove everything from "│" onward.`;
36
+ }
37
+ return `[E_BAD_REF] Invalid anchor "${trimmed}". Expected a 3-char alphanumeric anchor (e.g. "aB3").`;
38
+ }
39
+ function parseRef(ref) {
40
+ const trimmed = ref.trim();
41
+ if (trimmed.length === ANCHOR_LEN &&
42
+ ALPH_RE.test(trimmed)) {
43
+ return { hash: trimmed };
44
+ }
45
+ throw new Error(diagRef(ref));
46
+ }
47
+ export const parseHashRef = parseRef;
48
+ export function parseText(edit) {
49
+ if (typeof edit !== "string") {
50
+ throw new Error(NEW_CONTENT_NOT_STRING_MSG);
51
+ }
52
+ const normalized = edit.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
53
+ if (normalized === "")
54
+ return [];
55
+ if (/^\n+$/.test(normalized))
56
+ return new Array(normalized.length).fill("");
57
+ return normalized.split("\n");
58
+ }
59
+ function resAnchorFromMap(ref, hashIndex) {
60
+ const hashMatches = hashIndex.get(ref.hash);
61
+ if (!hashMatches || hashMatches.length === 0) {
62
+ return { ref, kind: "not_found" };
63
+ }
64
+ if (hashMatches.length === 1) {
65
+ return {
66
+ line: hashMatches[0],
67
+ hash: ref.hash,
68
+ hashMatched: true,
69
+ };
70
+ }
71
+ return { ref, kind: "ambiguous", candidates: hashMatches };
72
+ }
73
+ function assertAligned(fileLines, fileHashes, ctx) {
74
+ if (fileHashes.length !== fileLines.length) {
75
+ throw new Error(`${ctx}: fileHashes.length (${fileHashes.length}) must match fileLines.length (${fileLines.length}).`);
76
+ }
77
+ }
78
+ function fmtMismatchWithServes(mismatches, fileLines, fileHashes, filePath) {
79
+ assertAligned(fileLines, fileHashes, "fmtMismatch");
80
+ const out = [];
81
+ const servedRows = [];
82
+ const seen = new Set();
83
+ const pushRow = (ln) => {
84
+ if (ln < 1 || ln > fileLines.length)
85
+ return;
86
+ const position = ln - 1;
87
+ if (seen.has(position))
88
+ return;
89
+ seen.add(position);
90
+ servedRows.push({ position, hash: fileHashes[ln - 1] });
91
+ };
92
+ const notFound = mismatches.filter((m) => m.kind === "not_found");
93
+ const ambiguous = mismatches.filter((m) => m.kind === "ambiguous");
94
+ const refList = notFound.map((m) => `"${m.ref.hash}"`).join(", ");
95
+ if (notFound.length > 0) {
96
+ out.push(`[E_STALE_ANCHOR] ${notFound.length} stale anchor${notFound.length > 1 ? "s" : ""}${filePath ? ` in ${filePath}` : ""}: ${refList}. Re-read for fresh anchors.`);
97
+ for (const m of notFound) {
98
+ const ctx = m.context;
99
+ if (!ctx)
100
+ continue;
101
+ const from = Math.max(1, ctx.line - 1);
102
+ const to = Math.min(fileLines.length, ctx.line + 1);
103
+ const rows = [];
104
+ for (let ln = from; ln <= to; ln++) {
105
+ rows.push(` ${ln}: ${fileHashes[ln - 1]}│${clipLine(fileLines[ln - 1] ?? "")}`);
106
+ pushRow(ln);
107
+ }
108
+ out.push("");
109
+ out.push(` Current context around resolved anchor "${ctx.hash}" (line ${ctx.line}):\n${rows.join("\n")}`);
110
+ }
111
+ }
112
+ if (ambiguous.length > 0) {
113
+ if (out.length > 0)
114
+ out.push("");
115
+ out.push(`[E_AMBIGUOUS_ANCHOR] ${ambiguous.length} ambiguous anchor${ambiguous.length > 1 ? "s" : ""}${filePath ? ` in ${filePath}` : ""}. Re-read for fresh anchors.`);
116
+ for (const m of ambiguous) {
117
+ const sample = (m.candidates ?? []).slice(0, 5);
118
+ const more = (m.candidates?.length ?? 0) > sample.length
119
+ ? `, ... (+${(m.candidates?.length ?? 0) - sample.length} more)`
120
+ : "";
121
+ const lines = sample
122
+ .map((line) => {
123
+ const content = clipLine(fileLines[line - 1] ?? "");
124
+ pushRow(line);
125
+ return ` ${line}: ${fileHashes[line - 1]}│${content}`;
126
+ })
127
+ .join("\n");
128
+ out.push(` Hash "${m.ref.hash}" matches lines ${sample.join(", ")}${more}.\n${lines}`);
129
+ }
130
+ }
131
+ return { message: out.join("\n"), servedRows };
132
+ }
133
+ const ITEM_KS = new Set(["replacement_text", "remove_from", "remove_to"]);
134
+ function assertItem(edit) {
135
+ rejectUnknownFields(edit, ITEM_KS, "Edit", "The edit takes only { replacement_text, remove_from, remove_to }.");
136
+ if ("remove_from" in edit && typeof edit.remove_from !== "string") {
137
+ throw new Error(`[E_BAD_SHAPE] Field "remove_from" must be an anchor string (3-char hash).`);
138
+ }
139
+ if ("remove_to" in edit && typeof edit.remove_to !== "string") {
140
+ throw new Error(`[E_BAD_SHAPE] Field "remove_to" must be an anchor string (3-char hash).`);
141
+ }
142
+ if (!("replacement_text" in edit)) {
143
+ throw new Error(`[E_BAD_SHAPE] The edit requires a "replacement_text" field. Provide the replacement text (use "" to delete).`);
144
+ }
145
+ if (typeof edit.replacement_text !== "string") {
146
+ throw new Error(NEW_CONTENT_NOT_STRING_MSG);
147
+ }
148
+ if (typeof edit.remove_from !== "string" ||
149
+ typeof edit.remove_to !== "string") {
150
+ throw new Error(`[E_BAD_SHAPE] The edit requires "remove_from" and "remove_to" anchor strings (3-char hashes from read output).`);
151
+ }
152
+ }
153
+ const ANCHOR_ROW_RE = new RegExp(`^([+-]?)(${HASH_CLASS})│`);
154
+ export function resEdit(edit, warnings) {
155
+ assertItem(edit);
156
+ const editLines = parseText(edit.replacement_text);
157
+ const bounds = [edit.remove_from, edit.remove_to].map((ref) => {
158
+ const trimmed = ref.trim();
159
+ const match = trimmed.match(ANCHOR_ROW_RE);
160
+ if (match) {
161
+ let message;
162
+ if (match[1] === "+") {
163
+ message = `[E_BAD_REF] stripped diff-preview marker from remove_from/remove_to "${trimmed}".`;
164
+ }
165
+ else if (match[1] === "-") {
166
+ message = `[E_BAD_REF] stripped leading "-" marker from remove_from/remove_to "${trimmed}".`;
167
+ }
168
+ else {
169
+ message = `[E_BAD_REF] stripped "HASH│" prefix from remove_from/remove_to "${trimmed}".`;
170
+ }
171
+ warnings?.push(message);
172
+ return match[2];
173
+ }
174
+ return ref;
175
+ });
176
+ return {
177
+ content_lines: editLines,
178
+ hash_bounds: [parseHashRef(bounds[0]), parseHashRef(bounds[1])],
179
+ };
180
+ }
181
+ function warnUnicodeEsc(edit, warnings) {
182
+ if (edit.content_lines.some((line) => /\\uDDDD/i.test(line))) {
183
+ warnings.push("Detected literal \\uDDDD in edit content; no autocorrection applied. Verify whether this should be a real Unicode escape or plain text.");
184
+ }
185
+ }
186
+ /** @internal — private to anchor-pipeline seam; do not import directly, use anchor-pipeline.ts */
187
+ function stripBarePrefixes(edit, fileHashes, warnings) {
188
+ const fileHashSet = new Set(fileHashes);
189
+ const stripped = [];
190
+ const contentLines = edit.content_lines.map((line, lineIndex) => {
191
+ const match = line.match(HL_BARE_PREFIX_RE);
192
+ if (!match)
193
+ return line;
194
+ stripped.push({ lineIndex, matched: fileHashSet.has(match[1]) });
195
+ return line.slice(match[0].length);
196
+ });
197
+ if (stripped.length === 0)
198
+ return edit;
199
+ const locations = stripped
200
+ .map((s) => `replacement_text line ${s.lineIndex + 1}`)
201
+ .join(", ");
202
+ const matchedCount = stripped.filter((s) => s.matched).length;
203
+ const evidence = matchedCount === 0 ? "0 matched — verify literal 'HASH│' content" : `${matchedCount}/${stripped.length} matched`;
204
+ warnings.push(`[E_BARE_HASH_PREFIX] stripped "HASH│" prefix from ${locations} (${evidence}).`);
205
+ return { ...edit, content_lines: contentLines };
206
+ }
207
+ /** @internal — private to anchor-pipeline seam */
208
+ function stripDiffPrefixes(edit, warnings) {
209
+ const stripped = [];
210
+ const contentLines = edit.content_lines.map((line, lineIndex) => {
211
+ const plus = line.match(HL_PREFIX_PLUS_RE);
212
+ if (plus) {
213
+ stripped.push(lineIndex);
214
+ return line.slice(plus[0].length);
215
+ }
216
+ const minus = line.match(HL_PREFIX_MINUS_RE);
217
+ if (minus) {
218
+ stripped.push(lineIndex);
219
+ return line.slice(minus[0].length);
220
+ }
221
+ return line;
222
+ });
223
+ if (stripped.length === 0)
224
+ return edit;
225
+ const locations = stripped
226
+ .map((i) => `replacement_text line ${i + 1}`)
227
+ .join(", ");
228
+ warnings.push(`[E_INVALID_PATCH] stripped diff-preview marker from ${locations}.`);
229
+ return { ...edit, content_lines: contentLines };
230
+ }
231
+ /** @internal — private to anchor-pipeline seam */
232
+ function swapReversedRanges(edit, fileHashes, warnings) {
233
+ const lineByHash = new Map();
234
+ for (let i = 0; i < fileHashes.length; i++) {
235
+ lineByHash.set(fileHashes[i], i + 1);
236
+ }
237
+ const [startRef, endRef] = edit.hash_bounds;
238
+ const startLine = lineByHash.get(startRef.hash);
239
+ const endLine = lineByHash.get(endRef.hash);
240
+ if (startLine === undefined ||
241
+ endLine === undefined ||
242
+ startLine <= endLine) {
243
+ return edit;
244
+ }
245
+ warnings.push(`[E_BAD_OP] reversed remove_from/remove_to (${startRef.hash} after ${endRef.hash}); swapped.`);
246
+ return { ...edit, hash_bounds: [endRef, startRef] };
247
+ }
248
+ function trailingDups(contentLines, fileLines, endLine) {
249
+ const start = lastNonEmptyIndex(contentLines);
250
+ if (start < 0)
251
+ return [];
252
+ const dups = [];
253
+ const maxK = Math.min(start + 1, fileLines.length - endLine);
254
+ for (let k = 0; k < maxK; k++) {
255
+ if (contentLines[start - k] !== fileLines[endLine + k])
256
+ break;
257
+ dups.push({ kind: "trailing", replacementLineIndex: start - k });
258
+ }
259
+ return dups;
260
+ }
261
+ function leadingDups(contentLines, fileLines, startLine) {
262
+ const start = firstNonEmptyIndex(contentLines);
263
+ if (start < 0)
264
+ return [];
265
+ const dups = [];
266
+ const maxK = Math.min(contentLines.length - start, startLine - 1);
267
+ for (let k = 0; k < maxK; k++) {
268
+ if (contentLines[start + k] !== fileLines[startLine - 2 - k])
269
+ break;
270
+ dups.push({ kind: "leading", replacementLineIndex: start + k });
271
+ }
272
+ return dups;
273
+ }
274
+ function sectionIsUnique(canonLines, start, length) {
275
+ let count = 0;
276
+ for (let i = 0; i + length <= canonLines.length; i++) {
277
+ let k = 0;
278
+ while (k < length && canonLines[i + k] === canonLines[start + k])
279
+ k++;
280
+ if (k < length)
281
+ continue;
282
+ count++;
283
+ if (count > 1)
284
+ return false;
285
+ }
286
+ return true;
287
+ }
288
+ function firstNewAfterDups(contentLines, rangeLines, canonLines, endLine) {
289
+ const firstNew = findNewEdge(contentLines, rangeLines, false);
290
+ if (!firstNew)
291
+ return [];
292
+ const maxK = Math.min(contentLines.length - firstNew.index, canonLines.length - endLine);
293
+ let runLen = 0;
294
+ while (runLen < maxK &&
295
+ canon(contentLines[firstNew.index + runLen]) ===
296
+ canonLines[endLine + runLen]) {
297
+ runLen++;
298
+ }
299
+ if (runLen === 0 || !sectionIsUnique(canonLines, endLine, runLen))
300
+ return [];
301
+ const dups = [];
302
+ for (let k = 0; k < runLen; k++) {
303
+ dups.push({
304
+ kind: "first-new-after",
305
+ replacementLineIndex: firstNew.index + k,
306
+ });
307
+ }
308
+ return dups;
309
+ }
310
+ function lastNewBeforeDups(contentLines, rangeLines, canonLines, startLine) {
311
+ const lastNew = findNewEdge(contentLines, rangeLines, true);
312
+ if (!lastNew)
313
+ return [];
314
+ const maxK = Math.min(lastNew.index + 1, startLine - 1);
315
+ let runLen = 0;
316
+ while (runLen < maxK &&
317
+ canon(contentLines[lastNew.index - runLen]) ===
318
+ canonLines[startLine - 2 - runLen]) {
319
+ runLen++;
320
+ }
321
+ if (runLen === 0)
322
+ return [];
323
+ const sectionStart = startLine - 1 - runLen;
324
+ if (!sectionIsUnique(canonLines, sectionStart, runLen))
325
+ return [];
326
+ const dups = [];
327
+ for (let k = 0; k < runLen; k++) {
328
+ dups.push({
329
+ kind: "last-new-before",
330
+ replacementLineIndex: lastNew.index - k,
331
+ });
332
+ }
333
+ return dups;
334
+ }
335
+ function canonCounts(lines) {
336
+ const counts = new Map();
337
+ for (const line of lines) {
338
+ const key = canon(line);
339
+ counts.set(key, (counts.get(key) ?? 0) + 1);
340
+ }
341
+ return counts;
342
+ }
343
+ /** @internal — private to anchor-pipeline seam */
344
+ export function findNewEdge(contentLines, rangeLines, fromEnd) {
345
+ const multiset = canonCounts(rangeLines);
346
+ const step = fromEnd ? -1 : 1;
347
+ const start = fromEnd ? contentLines.length - 1 : 0;
348
+ for (let i = start; i >= 0 && i < contentLines.length; i += step) {
349
+ const line = contentLines[i];
350
+ if (line.length === 0)
351
+ continue;
352
+ const key = canon(line);
353
+ const count = multiset.get(key) ?? 0;
354
+ if (count > 0) {
355
+ multiset.set(key, count - 1);
356
+ }
357
+ else {
358
+ return { index: i, line };
359
+ }
360
+ }
361
+ return undefined;
362
+ }
363
+ /** @internal — private to anchor-pipeline seam: detection + boundaryDups belongs to AnchorPipeline ordering */
364
+ function valEdit(edit, fileLines, fileHashes, warnings, signal) {
365
+ assertAligned(fileLines, fileHashes, "valEdit");
366
+ const mismatches = [];
367
+ const boundaryDups = [];
368
+ const hashIndex = new Map();
369
+ for (let i = 0; i < fileHashes.length; i++) {
370
+ const h = fileHashes[i];
371
+ const list = hashIndex.get(h) ?? [];
372
+ list.push(i + 1);
373
+ hashIndex.set(h, list);
374
+ }
375
+ const tryResolve = (ref) => {
376
+ const result = resAnchorFromMap(ref, hashIndex);
377
+ if ("kind" in result) {
378
+ mismatches.push(result);
379
+ return undefined;
380
+ }
381
+ return result;
382
+ };
383
+ abortIf(signal);
384
+ const startResolved = tryResolve(edit.hash_bounds[0]);
385
+ const endResolved = tryResolve(edit.hash_bounds[1]);
386
+ if (!startResolved || !endResolved) {
387
+ if (!startResolved && endResolved) {
388
+ const startMismatch = mismatches.findLast((m) => m.ref === edit.hash_bounds[0]);
389
+ if (startMismatch && startMismatch.kind === "not_found")
390
+ startMismatch.context = endResolved;
391
+ }
392
+ else if (startResolved && !endResolved) {
393
+ const endMismatch = mismatches.findLast((m) => m.ref === edit.hash_bounds[1]);
394
+ if (endMismatch && endMismatch.kind === "not_found")
395
+ endMismatch.context = startResolved;
396
+ }
397
+ return { resolved: undefined, mismatches, boundaryDups };
398
+ }
399
+ if (startResolved.line > endResolved.line) {
400
+ 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}).`);
401
+ }
402
+ const endLine = endResolved.line;
403
+ const rangeLines = fileLines.slice(startResolved.line - 1, endLine);
404
+ const canonLines = fileLines.map((line) => canon(line));
405
+ 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));
406
+ return {
407
+ resolved: {
408
+ content_lines: edit.content_lines,
409
+ hash_bounds: [startResolved, endResolved],
410
+ },
411
+ mismatches,
412
+ boundaryDups,
413
+ };
414
+ }
415
+ export { warnUnicodeEsc };
416
+ export class ServedRejectionError extends Error {
417
+ code;
418
+ firstOffendingLine;
419
+ servedRows;
420
+ constructor(opts) {
421
+ super(opts.message);
422
+ this.name = "ServedRejectionError";
423
+ this.code = opts.code;
424
+ this.firstOffendingLine = opts.firstOffendingLine;
425
+ this.servedRows = opts.servedRows;
426
+ }
427
+ }
428
+ export function isServedRejection(error) {
429
+ return error instanceof ServedRejectionError;
430
+ }
431
+ export class AnchorMismatchError extends Error {
432
+ servedRows;
433
+ constructor(message, servedRows) {
434
+ super(message);
435
+ this.name = "AnchorMismatchError";
436
+ this.servedRows = servedRows;
437
+ }
438
+ }
439
+ export function isAnchorMismatch(error) {
440
+ return error instanceof AnchorMismatchError;
441
+ }
442
+ export function buildRangeEcho(startLine, endLine, fileHashes) {
443
+ const total = endLine - startLine + 1;
444
+ const shown = Math.min(total, SERVED_ECHO_CAP);
445
+ const rows = [];
446
+ for (let ln = startLine; ln < startLine + shown; ln++) {
447
+ rows.push({ position: ln - 1, hash: fileHashes[ln - 1] });
448
+ }
449
+ return rows;
450
+ }
451
+ export function fmtServedRows(rows, fileLines) {
452
+ return rows
453
+ .map((row) => `${row.hash}${HASH_SEP}${fileLines[row.position] ?? ""}`)
454
+ .join("\n");
455
+ }
456
+ function retryHint() {
457
+ return "Retry with these anchors (no read needed).";
458
+ }
459
+ function paginationHint(nextOffset, more) {
460
+ return `[... ${more} more — read offset=${nextOffset}]`;
461
+ }
462
+ export function verifyServedRange(args) {
463
+ const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath, } = args;
464
+ const where = filePath ? ` in ${filePath}` : "";
465
+ const echoRows = buildRangeEcho(startLine, endLine, fileHashes);
466
+ const totalLen = endLine - startLine + 1;
467
+ const tail = echoRows.length < totalLen
468
+ ? `\n${paginationHint(startLine + echoRows.length, totalLen - echoRows.length)}`
469
+ : "";
470
+ const echo = fmtServedRows(echoRows, fileLines) + tail;
471
+ const startPositions = servedPositionsOf(served, startHash);
472
+ const endPositions = servedPositionsOf(served, endHash);
473
+ const currentLen = endLine - startLine + 1;
474
+ let from;
475
+ let to;
476
+ if (startPositions.length === 1 && endPositions.length === 1) {
477
+ from = Math.min(startPositions[0], endPositions[0]);
478
+ to = Math.max(startPositions[0], endPositions[0]);
479
+ }
480
+ else {
481
+ const candidates = [];
482
+ for (const s of startPositions) {
483
+ for (const e of endPositions) {
484
+ const candFrom = Math.min(s, e);
485
+ const candTo = Math.max(s, e);
486
+ if (candTo - candFrom + 1 !== currentLen)
487
+ continue;
488
+ let ok = true;
489
+ for (let k = 0; k < currentLen; k++) {
490
+ if (served[candFrom + k] !== fileHashes[startLine - 1 + k]) {
491
+ ok = false;
492
+ break;
493
+ }
494
+ }
495
+ if (ok)
496
+ candidates.push({ from: candFrom, to: candTo });
497
+ }
498
+ }
499
+ if (candidates.length === 1) {
500
+ from = candidates[0].from;
501
+ to = candidates[0].to;
502
+ }
503
+ else if (candidates.length > 1) {
504
+ candidates.sort((a, b) => Math.abs(a.from - (startLine - 1)) - Math.abs(b.from - (startLine - 1)));
505
+ from = candidates[0].from;
506
+ to = candidates[0].to;
507
+ }
508
+ }
509
+ if (from === undefined || to === undefined) {
510
+ const problems = [];
511
+ if (startPositions.length === 0) {
512
+ problems.push(`remove_from "${startHash}" has no served position`);
513
+ }
514
+ else if (startPositions.length > 1) {
515
+ problems.push(`remove_from "${startHash}" was served at ${startPositions.length} positions`);
516
+ }
517
+ if (endPositions.length === 0) {
518
+ problems.push(`remove_to "${endHash}" has no served position`);
519
+ }
520
+ else if (endPositions.length > 1) {
521
+ problems.push(`remove_to "${endHash}" was served at ${endPositions.length} positions`);
522
+ }
523
+ throw new ServedRejectionError({
524
+ code: "E_RANGE_UNVERIFIED",
525
+ message: `[E_RANGE_UNVERIFIED] cannot verify range against served state${where}: ${problems.join("; ")}. ` +
526
+ `Current range:
527
+ ${echo}
528
+ ${retryHint()}`,
529
+ servedRows: echoRows,
530
+ });
531
+ }
532
+ for (let i = from; i <= to; i++) {
533
+ if (served[i] === null) {
534
+ throw new ServedRejectionError({
535
+ code: "E_RANGE_UNSERVED",
536
+ message: `[E_RANGE_UNSERVED] line ${i + 1}${where} was never served.\nCurrent range:\n${echo}\n${retryHint()}`,
537
+ firstOffendingLine: i + 1,
538
+ servedRows: echoRows,
539
+ });
540
+ }
541
+ }
542
+ const servedLen = to - from + 1;
543
+ if (servedLen !== currentLen) {
544
+ throw new ServedRejectionError({
545
+ code: "E_RANGE_STALE",
546
+ message: `[E_RANGE_STALE] served span (${servedLen} lines) no longer matches current range (${currentLen} lines)${where}.\nCurrent range:\n${echo}\n${retryHint()}`,
547
+ firstOffendingLine: startLine,
548
+ servedRows: echoRows,
549
+ });
550
+ }
551
+ for (let k = 0; k < servedLen; k++) {
552
+ if (served[from + k] !== fileHashes[startLine - 1 + k]) {
553
+ const offendingLine = startLine + k;
554
+ throw new ServedRejectionError({
555
+ code: "E_RANGE_STALE",
556
+ 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()}`,
557
+ firstOffendingLine: offendingLine,
558
+ servedRows: echoRows,
559
+ });
560
+ }
561
+ }
562
+ }
563
+ export async function recordEchoServes(sessionKey, path, rows, policy, lineCount) {
564
+ if (policy !== "live")
565
+ return;
566
+ await recordServed(sessionKey, path, rows, lineCount);
567
+ }
568
+ export function buildIdx(content) {
569
+ const fileLines = splitLines(content);
570
+ const lineStarts = [];
571
+ let offset = 0;
572
+ for (let index = 0; index < fileLines.length; index++) {
573
+ lineStarts.push(offset);
574
+ offset += fileLines[index].length;
575
+ if (index < fileLines.length - 1) {
576
+ offset += 1;
577
+ }
578
+ }
579
+ return {
580
+ fileLines,
581
+ lineStarts,
582
+ };
583
+ }
584
+ function assertNotEmpty(originalContent, result) {
585
+ if (originalContent.length > 0 && result.length === 0) {
586
+ throw new Error("[E_WOULD_EMPTY] Cannot empty a non-empty file via edit. Use `write` if you need to clear the file.");
587
+ }
588
+ }
589
+ function resToSpan(edit, content, lineIndex) {
590
+ const { fileLines, lineStarts } = lineIndex;
591
+ const startLine = edit.hash_bounds[0].line;
592
+ const endLine = edit.hash_bounds[1].line;
593
+ const originalLines = fileLines.slice(startLine - 1, endLine);
594
+ if (originalLines.length === edit.content_lines.length &&
595
+ originalLines.every((line, lineIndex) => line === edit.content_lines[lineIndex])) {
596
+ return {
597
+ kind: "noop",
598
+ loc: edit.hash_bounds[0].hash,
599
+ currentContent: originalLines.join("\n"),
600
+ };
601
+ }
602
+ if (edit.content_lines.length > 0) {
603
+ return {
604
+ kind: "replace",
605
+ start: lineStarts[startLine - 1],
606
+ end: lineStarts[endLine - 1] + fileLines[endLine - 1].length,
607
+ replacement: edit.content_lines.join("\n"),
608
+ };
609
+ }
610
+ if (startLine === 1 && endLine === fileLines.length) {
611
+ return {
612
+ kind: "replace",
613
+ start: 0,
614
+ end: content.length,
615
+ replacement: "",
616
+ };
617
+ }
618
+ if (endLine < fileLines.length) {
619
+ return {
620
+ kind: "replace",
621
+ start: lineStarts[startLine - 1],
622
+ end: lineStarts[endLine],
623
+ replacement: "",
624
+ };
625
+ }
626
+ if (content.endsWith("\n")) {
627
+ return {
628
+ kind: "replace",
629
+ start: lineStarts[startLine - 1],
630
+ end: content.length,
631
+ replacement: "",
632
+ };
633
+ }
634
+ const prevLine = startLine >= 2 ? fileLines[startLine - 2] : undefined;
635
+ return {
636
+ kind: "replace",
637
+ start: prevLine !== undefined && prevLine.length === 0
638
+ ? lineStarts[startLine - 1]
639
+ : Math.max(0, lineStarts[startLine - 1] - 1),
640
+ end: content.length,
641
+ replacement: "",
642
+ };
643
+ }
644
+ function assemble(content, span, signal) {
645
+ abortIf(signal);
646
+ return (content.slice(0, span.start) + span.replacement + content.slice(span.end));
647
+ }
648
+ export function applyEdit(content, edit, signal, precomputedHashes, filePath, served) {
649
+ abortIf(signal);
650
+ const lineIndex = buildIdx(content);
651
+ const fileHashes = precomputedHashes ?? lineHashesPure(content);
652
+ const warnings = [];
653
+ const rangeFixed = swapReversedRanges(edit, fileHashes, warnings);
654
+ const prefixFixed = stripDiffPrefixes(stripBarePrefixes(rangeFixed, fileHashes, warnings), warnings);
655
+ const { resolved: initialResolved, mismatches, boundaryDups, } = valEdit(prefixFixed, lineIndex.fileLines, fileHashes, warnings, signal);
656
+ if (mismatches.length || !initialResolved) {
657
+ const { message, servedRows } = fmtMismatchWithServes(mismatches, lineIndex.fileLines, fileHashes, filePath);
658
+ throw new AnchorMismatchError(message, servedRows);
659
+ }
660
+ warnUnicodeEsc(prefixFixed, warnings);
661
+ let resolved = initialResolved;
662
+ let autoFixes;
663
+ if (boundaryDups.length > 0) {
664
+ autoFixes = [];
665
+ const correctedEdit = {
666
+ ...prefixFixed,
667
+ content_lines: [...prefixFixed.content_lines],
668
+ };
669
+ const seen = new Set();
670
+ const uniqueDups = [];
671
+ for (const dup of boundaryDups) {
672
+ if (seen.has(dup.replacementLineIndex))
673
+ continue;
674
+ seen.add(dup.replacementLineIndex);
675
+ uniqueDups.push(dup);
676
+ }
677
+ const dupsByIndex = uniqueDups.sort((a, b) => b.replacementLineIndex - a.replacementLineIndex);
678
+ for (const dup of dupsByIndex) {
679
+ const idx = dup.replacementLineIndex;
680
+ if (idx < 0 || idx >= correctedEdit.content_lines.length)
681
+ continue;
682
+ const removed = correctedEdit.content_lines.splice(idx, 1)[0];
683
+ autoFixes.push({
684
+ kind: dup.kind,
685
+ removedLine: removed,
686
+ removedLineIndex: idx,
687
+ });
688
+ }
689
+ const correctedResult = valEdit(correctedEdit, lineIndex.fileLines, fileHashes, warnings, signal);
690
+ if (correctedResult.mismatches.length || !correctedResult.resolved) {
691
+ const { message, servedRows } = fmtMismatchWithServes(correctedResult.mismatches, lineIndex.fileLines, fileHashes, filePath);
692
+ throw new AnchorMismatchError(message, servedRows);
693
+ }
694
+ resolved = correctedResult.resolved;
695
+ }
696
+ if (served) {
697
+ const startAnchor = resolved.hash_bounds[0];
698
+ const endAnchor = resolved.hash_bounds[1];
699
+ verifyServedRange({
700
+ served,
701
+ startHash: startAnchor.hash,
702
+ endHash: endAnchor.hash,
703
+ startLine: startAnchor.line,
704
+ endLine: endAnchor.line,
705
+ fileHashes,
706
+ fileLines: lineIndex.fileLines,
707
+ filePath,
708
+ });
709
+ }
710
+ const spanResult = resToSpan(resolved, content, lineIndex);
711
+ if (spanResult.kind === "noop") {
712
+ return {
713
+ content,
714
+ firstChangedLine: undefined,
715
+ lastChangedLine: undefined,
716
+ range: resolvedRange(resolved),
717
+ ...(warnings.length ? { warnings } : {}),
718
+ noopEdit: {
719
+ loc: spanResult.loc,
720
+ currentContent: spanResult.currentContent,
721
+ },
722
+ };
723
+ }
724
+ const result = assemble(content, spanResult, signal);
725
+ assertNotEmpty(content, result);
726
+ const changed = changedRange(content, result);
727
+ return {
728
+ content: result,
729
+ firstChangedLine: changed?.firstChangedLine,
730
+ lastChangedLine: changed?.lastChangedLine,
731
+ range: resolvedRange(resolved),
732
+ ...(warnings.length ? { warnings } : {}),
733
+ ...(autoFixes ? { autoFixes } : {}),
734
+ };
735
+ }
736
+ function resolvedRange(resolved) {
737
+ const [start, end] = resolved.hash_bounds;
738
+ return {
739
+ startLine: start.line,
740
+ endLine: end.line,
741
+ startHash: start.hash,
742
+ endHash: end.hash,
743
+ delta: resolved.content_lines.length - (Math.abs(end.line - start.line) + 1),
744
+ };
745
+ }
746
+ export function fmtRegion(hashes, lines) {
747
+ if (hashes.length !== lines.length) {
748
+ throw new Error(`fmtRegion: hashes.length (${hashes.length}) must match lines.length (${lines.length}).`);
749
+ }
750
+ return lines
751
+ .map((line, index) => `${hashes[index]}${HASH_SEP}${line}`)
752
+ .join("\n");
753
+ }
754
+ export function changedRange(original, result) {
755
+ if (original === result)
756
+ return null;
757
+ if (original.length === 0) {
758
+ return {
759
+ firstChangedLine: 1,
760
+ lastChangedLine: splitLines(result).length,
761
+ };
762
+ }
763
+ const originalLines = splitLines(original);
764
+ const resultLines = splitLines(result);
765
+ if (originalLines.length === resultLines.length &&
766
+ originalLines.every((line, index) => line === resultLines[index])) {
767
+ return null;
768
+ }
769
+ const minLen = Math.min(originalLines.length, resultLines.length);
770
+ let first = 0;
771
+ while (first < minLen && originalLines[first] === resultLines[first]) {
772
+ first++;
773
+ }
774
+ let lastOrig = originalLines.length - 1;
775
+ let lastRes = resultLines.length - 1;
776
+ while (lastOrig >= first &&
777
+ lastRes >= first &&
778
+ originalLines[lastOrig] === resultLines[lastRes]) {
779
+ lastOrig--;
780
+ lastRes--;
781
+ }
782
+ return {
783
+ firstChangedLine: first + 1,
784
+ lastChangedLine: Math.max(first, lastRes) + 1,
785
+ };
786
+ }