dsh-better-edit 0.6.1 → 0.7.1
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.
- package/CHANGELOG.md +44 -12
- package/README.md +133 -383
- package/lib/constants.js +5 -1
- package/lib/contract.js +64 -15
- package/lib/edit-response.js +5 -10
- package/lib/encoding.js +1 -1
- package/lib/file-encoding-state.js +4 -4
- package/lib/file-view.js +14 -12
- package/lib/fs-bridge.js +8 -7
- package/lib/hash-store.js +123 -25
- package/lib/hashline/anchor-pipeline.js +97 -66
- package/lib/hashline/hash-assign.js +58 -19
- package/lib/hashline/hash.js +3 -3
- package/lib/index.js +18 -21
- package/lib/mutation/engine.js +81 -20
- package/lib/mutation.js +8 -8
- package/lib/prompts.js +6 -6
- package/lib/read-and-serve.js +90 -15
- package/lib/self-heal.js +101 -0
- package/lib/session-view.js +157 -24
- package/lib/tool-edit.js +5 -4
- package/lib/tool-undo.js +6 -6
- package/lib/types/constants.d.ts +2 -0
- package/lib/types/contract.d.ts +2 -1
- package/lib/types/edit-response.d.ts +4 -0
- package/lib/types/encoding.d.ts +1 -1
- package/lib/types/file-encoding-state.d.ts +1 -1
- package/lib/types/file-view.d.ts +15 -0
- package/lib/types/hash-store.d.ts +12 -1
- package/lib/types/hashline/anchor-pipeline.d.ts +16 -6
- package/lib/types/hashline/hash-assign.d.ts +10 -2
- package/lib/types/mutation/engine.d.ts +2 -1
- package/lib/types/self-heal.d.ts +29 -0
- package/lib/types/session-view.d.ts +13 -4
- package/lib/types/utils.d.ts +7 -0
- package/lib/utils.js +22 -1
- package/lib/write-hook.js +1 -1
- package/package.json +7 -7
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
*
|
|
17
17
|
* @module dsh-better-edit/hashline/anchor-pipeline
|
|
18
18
|
*/
|
|
19
|
-
import { abortIf, splitLines, rejectUnknownFields, clipLine } from "../utils.js";
|
|
19
|
+
import { abortIf, splitLines, rejectUnknownFields, clipLine, CodedError } from "../utils.js";
|
|
20
20
|
import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HASH_SEP, ANCHOR_LEN, ALPH_RE, canon, lineHashesPure, getCanonForHash, rememberHashCanon } from "./hash-assign.js";
|
|
21
21
|
import { recordServed, servedPositionsOf } from "../session-view.js";
|
|
22
22
|
import { SERVED_ECHO_CAP } from "../constants.js";
|
|
@@ -24,10 +24,10 @@ import { NEW_CONTENT_NOT_STRING_MSG } from "../constants.js";
|
|
|
24
24
|
function diagRef(ref) {
|
|
25
25
|
const trimmed = ref.trim();
|
|
26
26
|
if (!trimmed.length) {
|
|
27
|
-
return `[
|
|
27
|
+
return `[MODEL] [E_BAD_ANCHOR] Invalid anchor. Expected a 3-char alphanumeric anchor (e.g. "aB3").`;
|
|
28
28
|
}
|
|
29
29
|
if (/^\d+/.test(trimmed)) {
|
|
30
|
-
return `[
|
|
30
|
+
return `[MODEL] [E_BAD_ANCHOR] Invalid anchor. Use the hash alone (e.g. "aB3") — no line numbers or trailing content.`;
|
|
31
31
|
}
|
|
32
32
|
if (trimmed.includes("│") && trimmed.includes("\n")) {
|
|
33
33
|
const lines = trimmed.split("\n");
|
|
@@ -39,12 +39,12 @@ function diagRef(ref) {
|
|
|
39
39
|
const firstHash = firstMatch?.[0] ?? "wUp";
|
|
40
40
|
const lastHash = lastMatch?.[0] ?? "AU6";
|
|
41
41
|
const preview = first.slice(0, 60);
|
|
42
|
-
return `[
|
|
42
|
+
return `[MODEL] [E_BAD_ANCHOR] Invalid anchor — remove_from must be a single bare 3-char hash (e.g. "wUp"), not a block with HASH│. Received ${lines.length} lines starting "${preview}…" — use only the first hash "${firstHash}" as remove_from and "${lastHash}" as remove_to, and put the new content (without HASH│) in replacement_text.`;
|
|
43
43
|
}
|
|
44
44
|
if (trimmed.includes("│")) {
|
|
45
|
-
return `[
|
|
45
|
+
return `[MODEL] [E_BAD_ANCHOR] Invalid anchor "${trimmed}". remove_from and remove_to must contain the 3-char hash only — remove everything from "│" onward.`;
|
|
46
46
|
}
|
|
47
|
-
return `[
|
|
47
|
+
return `[MODEL] [E_BAD_ANCHOR] Invalid anchor "${trimmed}". Expected a 3-char alphanumeric anchor (e.g. "aB3").`;
|
|
48
48
|
}
|
|
49
49
|
function parseRef(ref) {
|
|
50
50
|
const trimmed = ref.trim();
|
|
@@ -52,7 +52,7 @@ function parseRef(ref) {
|
|
|
52
52
|
ALPH_RE.test(trimmed)) {
|
|
53
53
|
return { hash: trimmed };
|
|
54
54
|
}
|
|
55
|
-
throw new
|
|
55
|
+
throw new CodedError("E_BAD_ANCHOR", diagRef(ref));
|
|
56
56
|
}
|
|
57
57
|
export const parseHashRef = parseRef;
|
|
58
58
|
export function parseText(edit) {
|
|
@@ -103,7 +103,7 @@ function fmtMismatchWithServes(mismatches, fileLines, fileHashes, filePath) {
|
|
|
103
103
|
const ambiguous = mismatches.filter((m) => m.kind === "ambiguous");
|
|
104
104
|
const refList = notFound.map((m) => `"${m.ref.hash}"`).join(", ");
|
|
105
105
|
if (notFound.length > 0) {
|
|
106
|
-
out.push(`[E_STALE_ANCHOR] ${notFound.length} stale anchor${notFound.length > 1 ? "s" : ""}${filePath ? ` in ${filePath}` : ""}: ${refList}. Re-read for fresh anchors.`);
|
|
106
|
+
out.push(`[MODEL] [E_STALE_ANCHOR] ${notFound.length} stale anchor${notFound.length > 1 ? "s" : ""}${filePath ? ` in ${filePath}` : ""}: ${refList}. Re-read for fresh anchors.`);
|
|
107
107
|
for (const m of notFound) {
|
|
108
108
|
const ctx = m.context;
|
|
109
109
|
if (!ctx)
|
|
@@ -122,7 +122,7 @@ function fmtMismatchWithServes(mismatches, fileLines, fileHashes, filePath) {
|
|
|
122
122
|
if (ambiguous.length > 0) {
|
|
123
123
|
if (out.length > 0)
|
|
124
124
|
out.push("");
|
|
125
|
-
out.push(`[
|
|
125
|
+
out.push(`[MODEL] [E_STALE_ANCHOR] ${ambiguous.length} ambiguous anchor${ambiguous.length > 1 ? "s" : ""}${filePath ? ` in ${filePath}` : ""}. Re-read for fresh anchors.`);
|
|
126
126
|
for (const m of ambiguous) {
|
|
127
127
|
const sample = (m.candidates ?? []).slice(0, 5);
|
|
128
128
|
const more = (m.candidates?.length ?? 0) > sample.length
|
|
@@ -144,20 +144,20 @@ const ITEM_KS = new Set(["replacement_text", "remove_from", "remove_to"]);
|
|
|
144
144
|
function assertItem(edit) {
|
|
145
145
|
rejectUnknownFields(edit, ITEM_KS, "Edit", "The edit takes only { replacement_text, remove_from, remove_to }.");
|
|
146
146
|
if ("remove_from" in edit && typeof edit.remove_from !== "string") {
|
|
147
|
-
throw new
|
|
147
|
+
throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] Field "remove_from" must be an anchor string (3-char hash).`);
|
|
148
148
|
}
|
|
149
149
|
if ("remove_to" in edit && typeof edit.remove_to !== "string") {
|
|
150
|
-
throw new
|
|
150
|
+
throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] Field "remove_to" must be an anchor string (3-char hash).`);
|
|
151
151
|
}
|
|
152
152
|
if (!("replacement_text" in edit)) {
|
|
153
|
-
throw new
|
|
153
|
+
throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] The edit requires a "replacement_text" field. Provide the replacement text (use "" to delete).`);
|
|
154
154
|
}
|
|
155
155
|
if (typeof edit.replacement_text !== "string") {
|
|
156
|
-
throw new
|
|
156
|
+
throw new CodedError("E_BAD_PAYLOAD", NEW_CONTENT_NOT_STRING_MSG);
|
|
157
157
|
}
|
|
158
158
|
if (typeof edit.remove_from !== "string" ||
|
|
159
159
|
typeof edit.remove_to !== "string") {
|
|
160
|
-
throw new
|
|
160
|
+
throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] The edit requires "remove_from" and "remove_to" anchor strings (3-char hashes from read output).`);
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
163
|
const ANCHOR_ROW_RE = new RegExp(`^([+-]?)(${HASH_CLASS})│`);
|
|
@@ -172,7 +172,7 @@ function firstHashFromBlock(block) {
|
|
|
172
172
|
}
|
|
173
173
|
return undefined;
|
|
174
174
|
}
|
|
175
|
-
export function resEdit(edit,
|
|
175
|
+
export function resEdit(edit, _warnings) {
|
|
176
176
|
assertItem(edit);
|
|
177
177
|
const editLines = parseText(edit.replacement_text);
|
|
178
178
|
const bounds = [edit.remove_from, edit.remove_to].map((ref) => {
|
|
@@ -181,24 +181,22 @@ export function resEdit(edit, warnings) {
|
|
|
181
181
|
const hash = firstHashFromBlock(trimmed);
|
|
182
182
|
if (hash) {
|
|
183
183
|
const lines = trimmed.split("\n").length;
|
|
184
|
-
|
|
185
|
-
return hash;
|
|
184
|
+
throw new CodedError("E_BAD_ANCHOR", `[MODEL] [E_BAD_ANCHOR] extracted first hash "${hash}" from ${lines}-line block — use bare "${hash}" next time`);
|
|
186
185
|
}
|
|
187
186
|
}
|
|
188
187
|
const match = trimmed.match(ANCHOR_ROW_RE);
|
|
189
188
|
if (match) {
|
|
190
189
|
let message;
|
|
191
190
|
if (match[1] === "+") {
|
|
192
|
-
message = `[
|
|
191
|
+
message = `[E_BAD_ANCHOR] stripped diff-preview marker from remove_from/remove_to "${trimmed}".`;
|
|
193
192
|
}
|
|
194
193
|
else if (match[1] === "-") {
|
|
195
|
-
message = `[
|
|
194
|
+
message = `[E_BAD_ANCHOR] stripped leading "-" marker from remove_from/remove_to "${trimmed}".`;
|
|
196
195
|
}
|
|
197
196
|
else {
|
|
198
|
-
message = `[
|
|
197
|
+
message = `[E_BAD_ANCHOR] stripped "HASH│" prefix from remove_from/remove_to "${trimmed}".`;
|
|
199
198
|
}
|
|
200
|
-
|
|
201
|
-
return match[2];
|
|
199
|
+
throw new CodedError("E_BAD_ANCHOR", `[MODEL] ${message}`);
|
|
202
200
|
}
|
|
203
201
|
return ref;
|
|
204
202
|
});
|
|
@@ -213,7 +211,7 @@ function warnUnicodeEsc(edit, warnings) {
|
|
|
213
211
|
}
|
|
214
212
|
}
|
|
215
213
|
/** @internal — private to anchor-pipeline seam; do not import directly, use anchor-pipeline.ts */
|
|
216
|
-
function stripBarePrefixes(edit, fileHashes,
|
|
214
|
+
function stripBarePrefixes(edit, fileHashes, _warnings) {
|
|
217
215
|
const fileHashSet = new Set(fileHashes);
|
|
218
216
|
const stripped = [];
|
|
219
217
|
const contentLines = edit.content_lines.map((line, lineIndex) => {
|
|
@@ -231,15 +229,12 @@ function stripBarePrefixes(edit, fileHashes, warnings) {
|
|
|
231
229
|
const matchedCount = stripped.filter((s) => s.matched).length;
|
|
232
230
|
const evidence = matchedCount === 0 ? "0 matched — verify literal 'HASH│' content" : `${matchedCount}/${stripped.length} matched`;
|
|
233
231
|
if (matchedCount === stripped.length) {
|
|
234
|
-
|
|
235
|
-
}
|
|
236
|
-
else {
|
|
237
|
-
warnings.push(`[E_BARE_HASH_PREFIX] stripped "HASH│" prefix from ${locations} (${evidence}).`);
|
|
232
|
+
throw new BadAnchorError(`[MODEL] [E_BAD_ANCHOR] stripped "HASH│" prefix from ${locations} (${evidence}) — use bare content without HASH│ next time.`, { ...edit, content_lines: contentLines });
|
|
238
233
|
}
|
|
239
|
-
|
|
234
|
+
throw new BadAnchorError(`[MODEL] [E_BAD_ANCHOR] stripped "HASH│" prefix from ${locations} (${evidence}).`, { ...edit, content_lines: contentLines });
|
|
240
235
|
}
|
|
241
236
|
/** @internal — private to anchor-pipeline seam */
|
|
242
|
-
function stripDiffPrefixes(edit,
|
|
237
|
+
function stripDiffPrefixes(edit, _warnings) {
|
|
243
238
|
const stripped = [];
|
|
244
239
|
const contentLines = edit.content_lines.map((line, lineIndex) => {
|
|
245
240
|
const plus = line.match(HL_PREFIX_PLUS_RE);
|
|
@@ -259,8 +254,7 @@ function stripDiffPrefixes(edit, warnings) {
|
|
|
259
254
|
const locations = stripped
|
|
260
255
|
.map((i) => `replacement_text line ${i + 1}`)
|
|
261
256
|
.join(", ");
|
|
262
|
-
|
|
263
|
-
return { ...edit, content_lines: contentLines };
|
|
257
|
+
throw new BadAnchorError(`[MODEL] [E_BAD_ANCHOR] stripped diff-preview marker from ${locations}.`, { ...edit, content_lines: contentLines });
|
|
264
258
|
}
|
|
265
259
|
/** @internal — private to anchor-pipeline seam */
|
|
266
260
|
function swapReversedRanges(edit, fileHashes, warnings) {
|
|
@@ -276,7 +270,7 @@ function swapReversedRanges(edit, fileHashes, warnings) {
|
|
|
276
270
|
startLine <= endLine) {
|
|
277
271
|
return edit;
|
|
278
272
|
}
|
|
279
|
-
warnings.push(`[
|
|
273
|
+
warnings.push(`[USER] [E_REVERSED_ANCHORS] reversed remove_from/remove_to (${startRef.hash} after ${endRef.hash}); swapped (healed).`);
|
|
280
274
|
return { ...edit, hash_bounds: [endRef, startRef] };
|
|
281
275
|
}
|
|
282
276
|
/** @internal — private to anchor-pipeline seam */
|
|
@@ -315,7 +309,7 @@ function valEdit(edit, fileLines, fileHashes, warnings, signal) {
|
|
|
315
309
|
return { resolved: undefined, mismatches };
|
|
316
310
|
}
|
|
317
311
|
if (startResolved.line > endResolved.line) {
|
|
318
|
-
throw new
|
|
312
|
+
throw new CodedError("E_REVERSED_ANCHORS", `[MODEL] [E_REVERSED_ANCHORS] Range start line ${startResolved.line} must be <= end line ${endResolved.line} (anchors ${edit.hash_bounds[0].hash} and ${edit.hash_bounds[1].hash}).`);
|
|
319
313
|
}
|
|
320
314
|
const endLine = endResolved.line;
|
|
321
315
|
return {
|
|
@@ -328,14 +322,16 @@ function valEdit(edit, fileLines, fileHashes, warnings, signal) {
|
|
|
328
322
|
}
|
|
329
323
|
export function findNewEdge() { return undefined; }
|
|
330
324
|
export { warnUnicodeEsc };
|
|
331
|
-
export class ServedRejectionError extends
|
|
325
|
+
export class ServedRejectionError extends CodedError {
|
|
332
326
|
code;
|
|
327
|
+
unservedKind;
|
|
333
328
|
firstOffendingLine;
|
|
334
329
|
servedRows;
|
|
335
330
|
constructor(opts) {
|
|
336
|
-
super(opts.message);
|
|
331
|
+
super(opts.code, opts.message);
|
|
337
332
|
this.name = "ServedRejectionError";
|
|
338
333
|
this.code = opts.code;
|
|
334
|
+
this.unservedKind = opts.unservedKind;
|
|
339
335
|
this.firstOffendingLine = opts.firstOffendingLine;
|
|
340
336
|
this.servedRows = opts.servedRows;
|
|
341
337
|
}
|
|
@@ -343,14 +339,25 @@ export class ServedRejectionError extends Error {
|
|
|
343
339
|
export function isServedRejection(error) {
|
|
344
340
|
return error instanceof ServedRejectionError;
|
|
345
341
|
}
|
|
346
|
-
export class AnchorMismatchError extends
|
|
342
|
+
export class AnchorMismatchError extends CodedError {
|
|
347
343
|
servedRows;
|
|
348
344
|
constructor(message, servedRows) {
|
|
349
|
-
super(message);
|
|
345
|
+
super("E_STALE_ANCHOR", message);
|
|
350
346
|
this.name = "AnchorMismatchError";
|
|
351
347
|
this.servedRows = servedRows;
|
|
352
348
|
}
|
|
353
349
|
}
|
|
350
|
+
/** Thrown when replacement_text carries anchor-syntax garbage (HASH│/diff-preview prefixes).
|
|
351
|
+
* Carries the stripped edit so applyEdit can distinguish served-echo (→ E_SERVED_ECHO
|
|
352
|
+
* denial downstream) from garbage (→ E_BAD_ANCHOR stands). */
|
|
353
|
+
export class BadAnchorError extends CodedError {
|
|
354
|
+
stripped;
|
|
355
|
+
constructor(message, stripped) {
|
|
356
|
+
super("E_BAD_ANCHOR", message);
|
|
357
|
+
this.name = "BadAnchorError";
|
|
358
|
+
this.stripped = stripped;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
354
361
|
export function isAnchorMismatch(error) {
|
|
355
362
|
return error instanceof AnchorMismatchError;
|
|
356
363
|
}
|
|
@@ -392,7 +399,7 @@ function paginationHint(nextOffset, more) {
|
|
|
392
399
|
export function verifyServedRange(args) {
|
|
393
400
|
const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath, } = args;
|
|
394
401
|
const where = filePath ? ` in ${filePath}` : "";
|
|
395
|
-
const
|
|
402
|
+
const retiredSet = args.retired ?? new Set();
|
|
396
403
|
const servedCanons = args.servedCanons;
|
|
397
404
|
const strictPos = args.strictPos ?? false;
|
|
398
405
|
const epochSnapshotId = args.epochSnapshotId;
|
|
@@ -420,18 +427,18 @@ export function verifyServedRange(args) {
|
|
|
420
427
|
// Tombstone check for boundaries (whole-span S@3==S@3)
|
|
421
428
|
// If hash was freed in this epoch, any reuse is stale even at same pos+same canon.
|
|
422
429
|
// Early reject checks canon change to avoid false positive on same line re-read.
|
|
423
|
-
if (
|
|
424
|
-
const
|
|
430
|
+
if (retiredSet.has(startHash) || retiredSet.has(endHash)) {
|
|
431
|
+
const retiredHash = retiredSet.has(startHash) ? startHash : endHash;
|
|
425
432
|
if (servedCanons) {
|
|
426
|
-
const pos = fileHashes.indexOf(
|
|
433
|
+
const pos = fileHashes.indexOf(retiredHash);
|
|
427
434
|
if (pos >= 0) {
|
|
428
|
-
const servedIdx = served.indexOf(
|
|
435
|
+
const servedIdx = served.indexOf(retiredHash);
|
|
429
436
|
const expected = servedIdx >= 0 ? servedCanons[servedIdx] : undefined;
|
|
430
437
|
const actual = canon(fileLines[pos] ?? "");
|
|
431
438
|
if (expected !== undefined && expected !== null && expected !== actual) {
|
|
432
439
|
throw new ServedRejectionError({
|
|
433
|
-
code: "
|
|
434
|
-
message: `[
|
|
440
|
+
code: "E_STALE_RANGE",
|
|
441
|
+
message: `[MODEL] [E_STALE_RANGE] anchor "${retiredHash}" was freed since last full read (retired, canon changed from "${expected}" to "${actual}"). Re-read.\nCurrent range:\n${echo}`,
|
|
435
442
|
firstOffendingLine: pos + 1,
|
|
436
443
|
servedRows: echoRows,
|
|
437
444
|
});
|
|
@@ -594,8 +601,9 @@ export function verifyServedRange(args) {
|
|
|
594
601
|
problems.push(`remove_to "${endHash}" was served at ${endPositions.length} positions`);
|
|
595
602
|
}
|
|
596
603
|
throw new ServedRejectionError({
|
|
597
|
-
code: "
|
|
598
|
-
|
|
604
|
+
code: "E_UNSERVED_RANGE",
|
|
605
|
+
unservedKind: "boundary",
|
|
606
|
+
message: `[MODEL] [E_UNSERVED_RANGE] cannot verify range against served state${where}: ${problems.join("; ")}. ` +
|
|
599
607
|
`No served span matched the current range (${currentLen} lines). ` +
|
|
600
608
|
`A full read will re-sync the served mirror — the echoed range below is current content, ` +
|
|
601
609
|
`but retrying without re-reading cannot clear a stale duplicate outside the echoed window.\n` +
|
|
@@ -614,8 +622,8 @@ export function verifyServedRange(args) {
|
|
|
614
622
|
if (expectedCanon !== undefined && expectedCanon !== actualCanon) {
|
|
615
623
|
const offendingLine = from + k + 1;
|
|
616
624
|
throw new ServedRejectionError({
|
|
617
|
-
code: "
|
|
618
|
-
message: `[
|
|
625
|
+
code: "E_STALE_RANGE",
|
|
626
|
+
message: `[MODEL] [E_STALE_RANGE] line ${offendingLine}${where} differs from what was served.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
619
627
|
firstOffendingLine: offendingLine,
|
|
620
628
|
servedRows: echoRows,
|
|
621
629
|
});
|
|
@@ -626,8 +634,9 @@ export function verifyServedRange(args) {
|
|
|
626
634
|
for (let i = from; i <= to; i++) {
|
|
627
635
|
if (served[i] === null) {
|
|
628
636
|
throw new ServedRejectionError({
|
|
629
|
-
code: "
|
|
630
|
-
|
|
637
|
+
code: "E_UNSERVED_RANGE",
|
|
638
|
+
unservedKind: "interior",
|
|
639
|
+
message: `[MODEL] [E_UNSERVED_RANGE] line ${i + 1}${where} was never served.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
631
640
|
firstOffendingLine: i + 1,
|
|
632
641
|
servedRows: echoRows,
|
|
633
642
|
});
|
|
@@ -670,8 +679,8 @@ export function verifyServedRange(args) {
|
|
|
670
679
|
}
|
|
671
680
|
if (!lenHealed) {
|
|
672
681
|
throw new ServedRejectionError({
|
|
673
|
-
code: "
|
|
674
|
-
message: `[
|
|
682
|
+
code: "E_STALE_RANGE",
|
|
683
|
+
message: `[MODEL] [E_STALE_RANGE] served span (${servedLen} lines) no longer matches current range (${currentLen} lines)${where}.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
675
684
|
firstOffendingLine: startLine,
|
|
676
685
|
servedRows: echoRows,
|
|
677
686
|
});
|
|
@@ -680,8 +689,8 @@ export function verifyServedRange(args) {
|
|
|
680
689
|
// Strict pos check for concurrency (pos-free vs strict)
|
|
681
690
|
if (strictPos && from !== startLine - 1) {
|
|
682
691
|
throw new ServedRejectionError({
|
|
683
|
-
code: "
|
|
684
|
-
message: `[
|
|
692
|
+
code: "E_STALE_RANGE",
|
|
693
|
+
message: `[MODEL] [E_STALE_RANGE] anchor was served at line ${from + 1} but now resolves to line ${startLine} (pos-restricted concurrency). Re-read.\nCurrent range:\n${echo}`,
|
|
685
694
|
firstOffendingLine: startLine,
|
|
686
695
|
servedRows: echoRows,
|
|
687
696
|
});
|
|
@@ -694,8 +703,8 @@ export function verifyServedRange(args) {
|
|
|
694
703
|
const actual = canon(fileLines[startLine - 1 + k] ?? "");
|
|
695
704
|
if (expected !== actual) {
|
|
696
705
|
throw new ServedRejectionError({
|
|
697
|
-
code: "
|
|
698
|
-
message: `[
|
|
706
|
+
code: "E_STALE_RANGE",
|
|
707
|
+
message: `[MODEL] [E_STALE_RANGE] line ${startLine + k}${where} canon differs from served (expected "${expected}" vs actual "${actual}").\nCurrent range:\n${echo}`,
|
|
699
708
|
firstOffendingLine: startLine + k,
|
|
700
709
|
servedRows: echoRows,
|
|
701
710
|
});
|
|
@@ -706,13 +715,13 @@ export function verifyServedRange(args) {
|
|
|
706
715
|
// Tombstone interior check (whole-span) — gated on canon inequality (fail-closed only for different canon)
|
|
707
716
|
for (let k = 0; k < servedLen; k++) {
|
|
708
717
|
const h = fileHashes[startLine - 1 + k];
|
|
709
|
-
if (h &&
|
|
718
|
+
if (h && retiredSet.has(h)) {
|
|
710
719
|
const expectedCanon = servedCanons?.[from + k] ?? undefined;
|
|
711
720
|
const actualCanon = canon(fileLines[startLine - 1 + k] ?? "");
|
|
712
721
|
if (expectedCanon !== undefined && expectedCanon !== null && expectedCanon !== actualCanon) {
|
|
713
722
|
throw new ServedRejectionError({
|
|
714
|
-
code: "
|
|
715
|
-
message: `[
|
|
723
|
+
code: "E_STALE_RANGE",
|
|
724
|
+
message: `[MODEL] [E_STALE_RANGE] line ${startLine + k}${where} uses retired anchor "${h}" (freed since last full read, canon changed). Re-read.\nCurrent range:\n${echo}`,
|
|
716
725
|
firstOffendingLine: startLine + k,
|
|
717
726
|
servedRows: echoRows,
|
|
718
727
|
});
|
|
@@ -723,8 +732,8 @@ export function verifyServedRange(args) {
|
|
|
723
732
|
if (served[from + k] !== fileHashes[startLine - 1 + k]) {
|
|
724
733
|
const offendingLine = startLine + k;
|
|
725
734
|
throw new ServedRejectionError({
|
|
726
|
-
code: "
|
|
727
|
-
message: `[
|
|
735
|
+
code: "E_STALE_RANGE",
|
|
736
|
+
message: `[MODEL] [E_STALE_RANGE] line ${offendingLine}${where} differs from what was served.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
728
737
|
firstOffendingLine: offendingLine,
|
|
729
738
|
servedRows: echoRows,
|
|
730
739
|
});
|
|
@@ -755,7 +764,7 @@ export function buildIdx(content) {
|
|
|
755
764
|
}
|
|
756
765
|
function assertNotEmpty(originalContent, result) {
|
|
757
766
|
if (originalContent.length > 0 && result.length === 0) {
|
|
758
|
-
throw new Error("[
|
|
767
|
+
throw new Error("[MODEL] [E_EMPTY_RANGE] Cannot empty a non-empty file via edit. Use `write` if you need to clear the file.");
|
|
759
768
|
}
|
|
760
769
|
}
|
|
761
770
|
function resToSpan(edit, content, lineIndex) {
|
|
@@ -817,13 +826,35 @@ function assemble(content, span, signal) {
|
|
|
817
826
|
abortIf(signal);
|
|
818
827
|
return (content.slice(0, span.start) + span.replacement + content.slice(span.end));
|
|
819
828
|
}
|
|
820
|
-
export function applyEdit(content, edit, signal, precomputedHashes, filePath, served, servedCanons,
|
|
829
|
+
export function applyEdit(content, edit, signal, precomputedHashes, filePath, served, servedCanons, retired, epochSnapshotId, curSnapshotId, strictPos) {
|
|
821
830
|
abortIf(signal);
|
|
822
831
|
const lineIndex = buildIdx(content);
|
|
823
832
|
const fileHashes = precomputedHashes ?? lineHashesPure(content);
|
|
824
833
|
const warnings = [];
|
|
825
834
|
const rangeFixed = swapReversedRanges(edit, fileHashes, warnings);
|
|
826
|
-
|
|
835
|
+
let prefixFixed;
|
|
836
|
+
try {
|
|
837
|
+
prefixFixed = stripDiffPrefixes(stripBarePrefixes(rangeFixed, fileHashes, warnings), warnings);
|
|
838
|
+
}
|
|
839
|
+
catch (error) {
|
|
840
|
+
if (!(error instanceof BadAnchorError) || !served)
|
|
841
|
+
throw error;
|
|
842
|
+
// Anchor-syntax garbage that is actually served-echo belongs to the
|
|
843
|
+
// E_SERVED_ECHO guard below: re-check the stripped + raw lines at the
|
|
844
|
+
// resolved start line and throw the echo denial; otherwise E_BAD_ANCHOR stands.
|
|
845
|
+
const stripped = error.stripped;
|
|
846
|
+
const lineByHash = new Map();
|
|
847
|
+
for (let i = 0; i < fileHashes.length; i++)
|
|
848
|
+
lineByHash.set(fileHashes[i], i + 1);
|
|
849
|
+
const startLine = lineByHash.get(stripped.hash_bounds[0].hash);
|
|
850
|
+
const echo = (startLine !== undefined ? findEditHashEcho(edit.content_lines, served, startLine) : undefined) ??
|
|
851
|
+
(startLine !== undefined ? findEditHashEcho(stripped.content_lines, served, startLine) : undefined);
|
|
852
|
+
if (echo) {
|
|
853
|
+
const msg = `[MODEL] [E_SERVED_ECHO] Refused edit to ${filePath ?? "(unknown file)"}: replacement line ${echo.k} begins with the exact ${echo.hash}${HASH_SEP} anchor served for this session, path, and range-relative line. Remove the copied anchors and retry. Nothing was written.`;
|
|
854
|
+
throw new EditHashEchoError(msg, []);
|
|
855
|
+
}
|
|
856
|
+
throw error;
|
|
857
|
+
}
|
|
827
858
|
const { resolved: initialResolved, mismatches, } = valEdit(prefixFixed, lineIndex.fileLines, fileHashes, warnings, signal);
|
|
828
859
|
if (mismatches.length || !initialResolved) {
|
|
829
860
|
const { message, servedRows } = fmtMismatchWithServes(mismatches, lineIndex.fileLines, fileHashes, filePath);
|
|
@@ -840,7 +871,7 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
|
|
|
840
871
|
if (!echo)
|
|
841
872
|
echo = findEditHashEcho(prefixFixed.content_lines, served, startLineEcho);
|
|
842
873
|
if (echo) {
|
|
843
|
-
const msg = `[
|
|
874
|
+
const msg = `[MODEL] [E_SERVED_ECHO] Refused edit to ${filePath ?? "(unknown file)"}: replacement line ${echo.k} begins with the exact ${echo.hash}${HASH_SEP} anchor served for this session, path, and range-relative line. Remove the copied anchors and retry. Nothing was written.`;
|
|
844
875
|
throw new EditHashEchoError(msg, []);
|
|
845
876
|
}
|
|
846
877
|
const startAnchor = resolved.hash_bounds[0];
|
|
@@ -855,7 +886,7 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
|
|
|
855
886
|
fileLines: lineIndex.fileLines,
|
|
856
887
|
filePath,
|
|
857
888
|
servedCanons,
|
|
858
|
-
|
|
889
|
+
retired,
|
|
859
890
|
epochSnapshotId,
|
|
860
891
|
curSnapshotId,
|
|
861
892
|
strictPos,
|
|
@@ -48,9 +48,23 @@ export const HASH_RE = new RegExp(`^${HASH_CLASS}$`);
|
|
|
48
48
|
export const ANCHOR_LEN = HASH_LEN;
|
|
49
49
|
export const HASH_SEP = "│";
|
|
50
50
|
export const HASH_SPACE = ALPH.length ** HASH_LEN;
|
|
51
|
+
// MAX_HASH_LINES is the anchor-space size (62³), not a line-count limit.
|
|
52
|
+
// File line-count limits use maxLines (e.g. 200k) and report E_LARGE_FILE;
|
|
53
|
+
// anchor-space exhaustion reports E_ANCHOR_SPACE_EXHAUSTED — see nextZeroBit.
|
|
51
54
|
export const MAX_HASH_LINES = HASH_SPACE;
|
|
52
55
|
export const HASH_PROBE_STRIDE = ALPH.length ** 2 + ALPH.length + 1;
|
|
53
|
-
|
|
56
|
+
export class AnchorSpaceExhaustedError extends Error {
|
|
57
|
+
code = "E_ANCHOR_SPACE_EXHAUSTED";
|
|
58
|
+
retiredCount;
|
|
59
|
+
servedCount;
|
|
60
|
+
constructor(retiredCount, servedCount, reservedCount) {
|
|
61
|
+
super(`[MODEL] [E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted (retired ${retiredCount} + served ${servedCount} = ${reservedCount} of ${HASH_SPACE}); promotion will clear retired — re-read recommended, stale-anchor checks degraded until next full read.`);
|
|
62
|
+
this.name = "AnchorSpaceExhaustedError";
|
|
63
|
+
this.retiredCount = retiredCount;
|
|
64
|
+
this.servedCount = servedCount;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export function idxToHash(idx) {
|
|
54
68
|
let out = "";
|
|
55
69
|
for (let j = 0; j < HASH_LEN; j++) {
|
|
56
70
|
out = ALPH[idx % ALPH.length] + out;
|
|
@@ -59,7 +73,7 @@ function idxToHash(idx) {
|
|
|
59
73
|
return out;
|
|
60
74
|
}
|
|
61
75
|
const hashCache = new Map();
|
|
62
|
-
function hashAt(idx) {
|
|
76
|
+
export function hashAt(idx) {
|
|
63
77
|
let hash = hashCache.get(idx);
|
|
64
78
|
if (hash === undefined) {
|
|
65
79
|
hash = idxToHash(idx);
|
|
@@ -108,7 +122,7 @@ function nextZeroBit(bits, start) {
|
|
|
108
122
|
if (idx >= totalBits)
|
|
109
123
|
idx -= totalBits;
|
|
110
124
|
}
|
|
111
|
-
throw new Error(`[
|
|
125
|
+
throw new Error(`[MODEL] [E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted — probing failed over ${HASH_SPACE} slots (reserved full).`);
|
|
112
126
|
}
|
|
113
127
|
function assignHash(used, baseIdx, hint) {
|
|
114
128
|
if (!getBit(used, baseIdx)) {
|
|
@@ -121,7 +135,9 @@ function assignHash(used, baseIdx, hint) {
|
|
|
121
135
|
hint.value = nextIdx + HASH_PROBE_STRIDE;
|
|
122
136
|
return hashAt(nextIdx);
|
|
123
137
|
}
|
|
124
|
-
export function lineHashesPure(content, reservedHashes = new Set()
|
|
138
|
+
export function lineHashesPure(content, reservedHashes = new Set(),
|
|
139
|
+
// optional counts for richer error — when caller knows retired vs served split
|
|
140
|
+
retiredCount, servedCount) {
|
|
125
141
|
const lines = splitLines(content);
|
|
126
142
|
const hashes = new Array(lines.length);
|
|
127
143
|
const used = new Uint32Array(BITSET_WORDS);
|
|
@@ -129,12 +145,24 @@ export function lineHashesPure(content, reservedHashes = new Set()) {
|
|
|
129
145
|
markHashUsed(used, hash);
|
|
130
146
|
const hint = { value: 0 };
|
|
131
147
|
const canonCache = new Map();
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
148
|
+
try {
|
|
149
|
+
for (let i = 0; i < lines.length; i++) {
|
|
150
|
+
const c = getCanon(canonCache, lines[i]);
|
|
151
|
+
const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
|
|
152
|
+
const h = assignHash(used, baseIdx, hint);
|
|
153
|
+
hashes[i] = h;
|
|
154
|
+
rememberHashCanon(h, c);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
catch (e) {
|
|
158
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
159
|
+
if (msg.includes("E_ANCHOR_SPACE_EXHAUSTED") || msg.includes("Cannot allocate")) {
|
|
160
|
+
const rc = retiredCount ?? reservedHashes.size;
|
|
161
|
+
const sc = servedCount ?? 0;
|
|
162
|
+
const reserved = reservedHashes.size;
|
|
163
|
+
throw new AnchorSpaceExhaustedError(rc, sc, reserved);
|
|
164
|
+
}
|
|
165
|
+
throw e;
|
|
138
166
|
}
|
|
139
167
|
return hashes;
|
|
140
168
|
}
|
|
@@ -165,7 +193,7 @@ function nearestNew(candidates, target) {
|
|
|
165
193
|
}
|
|
166
194
|
return right < candidates.length ? right : -1;
|
|
167
195
|
}
|
|
168
|
-
export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes, reservedHashes = new Set()) {
|
|
196
|
+
export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes, reservedHashes = new Set(), retiredCount, servedCount) {
|
|
169
197
|
const oldLines = splitLines(oldContent);
|
|
170
198
|
const newLines = splitLines(newContent);
|
|
171
199
|
const newHashes = new Array(newLines.length);
|
|
@@ -239,14 +267,25 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
|
|
|
239
267
|
markUsed(entry.hash);
|
|
240
268
|
rememberHashCanon(entry.hash, getCanon(canonCache, oldLines[entry.index]));
|
|
241
269
|
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
270
|
+
try {
|
|
271
|
+
for (let i = 0; i < newLines.length; i++) {
|
|
272
|
+
if (newHashes[i])
|
|
273
|
+
continue;
|
|
274
|
+
const c = getCanon(canonCache, newLines[i]);
|
|
275
|
+
const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
|
|
276
|
+
const h = assignHash(used, baseIdx, hint);
|
|
277
|
+
newHashes[i] = h;
|
|
278
|
+
rememberHashCanon(h, c);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
catch (e) {
|
|
282
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
283
|
+
if (msg.includes("E_ANCHOR_SPACE_EXHAUSTED")) {
|
|
284
|
+
const rc = retiredCount ?? reservedHashes.size;
|
|
285
|
+
const sc = servedCount ?? 0;
|
|
286
|
+
throw new AnchorSpaceExhaustedError(rc, sc, reservedHashes.size);
|
|
287
|
+
}
|
|
288
|
+
throw e;
|
|
250
289
|
}
|
|
251
290
|
return newHashes;
|
|
252
291
|
}
|
package/lib/hashline/hash.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { splitLines } from "../utils.js";
|
|
11
11
|
import { loadHashStore } from "../hash-store.js";
|
|
12
|
-
import { contentChecksum, initHasher, HASH_RE } from "./hash-assign.js";
|
|
12
|
+
import { contentChecksum, initHasher, HASH_RE, AnchorSpaceExhaustedError } from "./hash-assign.js";
|
|
13
13
|
import { lineHashesPure, mapStableHashes } from "./hash-assign.js";
|
|
14
14
|
let defaultHashSnapshotIO;
|
|
15
15
|
export function setDefaultHashSnapshotIO(io) {
|
|
@@ -54,7 +54,7 @@ export async function lineHashes(content, path, previous, ioOrStore, persist, re
|
|
|
54
54
|
? snapshotIOFor(ioOrStore)
|
|
55
55
|
: ioOrStore ?? snapshotIOFor(undefined);
|
|
56
56
|
if (previous) {
|
|
57
|
-
const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes, reservedHashes);
|
|
57
|
+
const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes, reservedHashes, retiredHashes.size, previous.hashes.length);
|
|
58
58
|
if (persist !== false && io) {
|
|
59
59
|
try {
|
|
60
60
|
await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
|
|
@@ -76,7 +76,7 @@ export async function lineHashes(content, path, previous, ioOrStore, persist, re
|
|
|
76
76
|
}
|
|
77
77
|
if (cached && !cached.some((hash) => retiredHashes.has(hash)))
|
|
78
78
|
return cached;
|
|
79
|
-
const newHashes = lineHashesPure(content, reservedHashes);
|
|
79
|
+
const newHashes = lineHashesPure(content, reservedHashes, retiredHashes.size, 0);
|
|
80
80
|
if (persist !== false && io) {
|
|
81
81
|
try {
|
|
82
82
|
await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
|
package/lib/index.js
CHANGED
|
@@ -1,26 +1,10 @@
|
|
|
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; scoped pre/post listeners reject copied same-line served anchors
|
|
11
|
-
* before dispatch and append a fresh hashline preview after successful writes.
|
|
12
|
-
*
|
|
13
|
-
* The four `tool:*` guidance sections resolve per agent preset from override
|
|
14
|
-
* files in the shared home (see `src/guidance.ts`); deployments without the
|
|
15
|
-
* `agentPresets` service keep the compiled defaults unchanged.
|
|
16
|
-
* @module dsh-better-edit
|
|
17
|
-
*/
|
|
18
1
|
import { ctxFsIO } from "./fs-bridge.js";
|
|
19
2
|
import { FsSandboxController } from "./sandbox.js";
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
3
|
+
import { buildReadTool } from "./tool-read.js";
|
|
4
|
+
import { buildEditTool } from "./tool-edit.js";
|
|
22
5
|
import { registerUndoTool } from "./tool-undo.js";
|
|
23
6
|
import { registerWriteHook } from "./write-hook.js";
|
|
7
|
+
import { createSelfHealWatcher } from "./self-heal.js";
|
|
24
8
|
import { initHasher } from "./hashline/hash-assign.js";
|
|
25
9
|
import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
|
|
26
10
|
import { configDir } from "./store/index.js";
|
|
@@ -80,11 +64,24 @@ function installAgentTools(rootCtx, agent) {
|
|
|
80
64
|
// exec.agent.session.header.cwd.
|
|
81
65
|
const io = ctxFsIO(rootCtx.fs, rootCtx);
|
|
82
66
|
const disposers = [];
|
|
83
|
-
disposers.push(registerReadTool(rootCtx, agent.ctx, io));
|
|
84
67
|
const sandbox = new FsSandboxController(rootCtx);
|
|
85
|
-
|
|
68
|
+
// Keep owned definitions by reference for self-heal identity check
|
|
69
|
+
const hashReadDef = buildReadTool(io);
|
|
70
|
+
disposers.push(agent.ctx.tools.register(hashReadDef));
|
|
71
|
+
const hashEditDef = buildEditTool(io, sandbox);
|
|
72
|
+
disposers.push(agent.ctx.tools.register(hashEditDef));
|
|
86
73
|
disposers.push(registerUndoTool(rootCtx, agent.ctx, io, sandbox));
|
|
87
74
|
disposers.push(registerWriteHook(rootCtx, agent.ctx, io));
|
|
75
|
+
const toolsSvc = rootCtx.get("tools");
|
|
76
|
+
disposers.push(createSelfHealWatcher({
|
|
77
|
+
agentId: agent.id,
|
|
78
|
+
rootCtx,
|
|
79
|
+
agent,
|
|
80
|
+
agentCtx: agent.ctx,
|
|
81
|
+
toolsSvc,
|
|
82
|
+
hashReadDef,
|
|
83
|
+
hashEditDef,
|
|
84
|
+
}));
|
|
88
85
|
// Shadow the preset's built-in tool guidance with the hashline
|
|
89
86
|
// contract. Same section names on the agent's own layer win over the
|
|
90
87
|
// preset's; text and order come from the per-preset resolution.
|