dsh-better-edit 0.6.3 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +59 -15
- package/README.md +78 -71
- package/README.zh.md +83 -83
- package/lib/canonical-path.js +4 -1
- package/lib/constants.js +5 -1
- package/lib/contract.js +127 -33
- package/lib/edit-diff.js +1 -5
- package/lib/edit-response.js +5 -10
- package/lib/encoding.js +23 -6
- package/lib/file-encoding-state.js +54 -15
- package/lib/file-view.js +42 -53
- package/lib/fs-bridge.js +27 -16
- package/lib/fs-write.js +1 -1
- package/lib/guidance/materialize.js +1 -6
- package/lib/guidance/resolve.js +1 -1
- package/lib/hash-store.js +133 -43
- package/lib/hashline/anchor-pipeline.js +124 -93
- package/lib/hashline/hash-assign.js +65 -23
- package/lib/hashline/hash.js +6 -6
- package/lib/index.js +6 -0
- package/lib/mutation/engine.js +89 -31
- package/lib/mutation.js +14 -13
- package/lib/prompts.js +12 -11
- package/lib/read-and-serve.js +105 -19
- package/lib/render-text-warning.js +21 -0
- package/lib/sandbox.js +2 -5
- package/lib/self-heal.js +30 -27
- package/lib/session-view.js +161 -24
- package/lib/store-config.js +7 -2
- package/lib/store-lifecycle.js +7 -2
- package/lib/tool-edit.js +10 -6
- package/lib/tool-read.js +6 -9
- package/lib/tool-str-replace-editor.js +274 -0
- package/lib/tool-undo.js +8 -9
- package/lib/types/constants.d.ts +2 -0
- package/lib/types/contract.d.ts +106 -18
- 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 +4 -1
- package/lib/types/file-view.d.ts +16 -1
- 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/hashline/index.d.ts +1 -1
- package/lib/types/mutation/engine.d.ts +2 -1
- package/lib/types/render-text-warning.d.ts +22 -0
- package/lib/types/self-heal.d.ts +2 -0
- package/lib/types/session-view.d.ts +13 -4
- package/lib/types/tool-str-replace-editor.d.ts +27 -0
- package/lib/types/undo-edit.d.ts +1 -1
- package/lib/types/utils.d.ts +7 -0
- package/lib/types/write-hook.d.ts +2 -2
- package/lib/undo-edit.js +6 -8
- package/lib/utils.js +23 -3
- package/lib/workspace-context.js +1 -1
- package/lib/write-hook.js +20 -23
- package/package.json +63 -57
|
@@ -16,18 +16,18 @@
|
|
|
16
16
|
*
|
|
17
17
|
* @module dsh-better-edit/hashline/anchor-pipeline
|
|
18
18
|
*/
|
|
19
|
-
import { abortIf, splitLines, rejectUnknownFields, clipLine } from "../utils.js";
|
|
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";
|
|
19
|
+
import { abortIf, splitLines, rejectUnknownFields, clipLine, CodedError } from "../utils.js";
|
|
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";
|
|
23
23
|
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,20 +39,19 @@ 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();
|
|
51
|
-
if (trimmed.length === ANCHOR_LEN &&
|
|
52
|
-
ALPH_RE.test(trimmed)) {
|
|
51
|
+
if (trimmed.length === ANCHOR_LEN && ALPH_RE.test(trimmed)) {
|
|
53
52
|
return { hash: trimmed };
|
|
54
53
|
}
|
|
55
|
-
throw new
|
|
54
|
+
throw new CodedError("E_BAD_ANCHOR", diagRef(ref));
|
|
56
55
|
}
|
|
57
56
|
export const parseHashRef = parseRef;
|
|
58
57
|
export function parseText(edit) {
|
|
@@ -103,7 +102,7 @@ function fmtMismatchWithServes(mismatches, fileLines, fileHashes, filePath) {
|
|
|
103
102
|
const ambiguous = mismatches.filter((m) => m.kind === "ambiguous");
|
|
104
103
|
const refList = notFound.map((m) => `"${m.ref.hash}"`).join(", ");
|
|
105
104
|
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.`);
|
|
105
|
+
out.push(`[MODEL] [E_STALE_ANCHOR] ${notFound.length} stale anchor${notFound.length > 1 ? "s" : ""}${filePath ? ` in ${filePath}` : ""}: ${refList}. Re-read for fresh anchors.`);
|
|
107
106
|
for (const m of notFound) {
|
|
108
107
|
const ctx = m.context;
|
|
109
108
|
if (!ctx)
|
|
@@ -122,7 +121,7 @@ function fmtMismatchWithServes(mismatches, fileLines, fileHashes, filePath) {
|
|
|
122
121
|
if (ambiguous.length > 0) {
|
|
123
122
|
if (out.length > 0)
|
|
124
123
|
out.push("");
|
|
125
|
-
out.push(`[
|
|
124
|
+
out.push(`[MODEL] [E_STALE_ANCHOR] ${ambiguous.length} ambiguous anchor${ambiguous.length > 1 ? "s" : ""}${filePath ? ` in ${filePath}` : ""}. Re-read for fresh anchors.`);
|
|
126
125
|
for (const m of ambiguous) {
|
|
127
126
|
const sample = (m.candidates ?? []).slice(0, 5);
|
|
128
127
|
const more = (m.candidates?.length ?? 0) > sample.length
|
|
@@ -144,20 +143,19 @@ const ITEM_KS = new Set(["replacement_text", "remove_from", "remove_to"]);
|
|
|
144
143
|
function assertItem(edit) {
|
|
145
144
|
rejectUnknownFields(edit, ITEM_KS, "Edit", "The edit takes only { replacement_text, remove_from, remove_to }.");
|
|
146
145
|
if ("remove_from" in edit && typeof edit.remove_from !== "string") {
|
|
147
|
-
throw new
|
|
146
|
+
throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] Field "remove_from" must be an anchor string (3-char hash).`);
|
|
148
147
|
}
|
|
149
148
|
if ("remove_to" in edit && typeof edit.remove_to !== "string") {
|
|
150
|
-
throw new
|
|
149
|
+
throw new CodedError("E_BAD_PAYLOAD", `[MODEL] [E_BAD_PAYLOAD] Field "remove_to" must be an anchor string (3-char hash).`);
|
|
151
150
|
}
|
|
152
151
|
if (!("replacement_text" in edit)) {
|
|
153
|
-
throw new
|
|
152
|
+
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
153
|
}
|
|
155
154
|
if (typeof edit.replacement_text !== "string") {
|
|
156
|
-
throw new
|
|
155
|
+
throw new CodedError("E_BAD_PAYLOAD", NEW_CONTENT_NOT_STRING_MSG);
|
|
157
156
|
}
|
|
158
|
-
if (typeof edit.remove_from !== "string" ||
|
|
159
|
-
|
|
160
|
-
throw new Error(`[E_BAD_SHAPE] The edit requires "remove_from" and "remove_to" anchor strings (3-char hashes from read output).`);
|
|
157
|
+
if (typeof edit.remove_from !== "string" || typeof edit.remove_to !== "string") {
|
|
158
|
+
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
159
|
}
|
|
162
160
|
}
|
|
163
161
|
const ANCHOR_ROW_RE = new RegExp(`^([+-]?)(${HASH_CLASS})│`);
|
|
@@ -172,7 +170,7 @@ function firstHashFromBlock(block) {
|
|
|
172
170
|
}
|
|
173
171
|
return undefined;
|
|
174
172
|
}
|
|
175
|
-
export function resEdit(edit,
|
|
173
|
+
export function resEdit(edit, _warnings) {
|
|
176
174
|
assertItem(edit);
|
|
177
175
|
const editLines = parseText(edit.replacement_text);
|
|
178
176
|
const bounds = [edit.remove_from, edit.remove_to].map((ref) => {
|
|
@@ -181,24 +179,22 @@ export function resEdit(edit, warnings) {
|
|
|
181
179
|
const hash = firstHashFromBlock(trimmed);
|
|
182
180
|
if (hash) {
|
|
183
181
|
const lines = trimmed.split("\n").length;
|
|
184
|
-
|
|
185
|
-
return hash;
|
|
182
|
+
throw new CodedError("E_BAD_ANCHOR", `[MODEL] [E_BAD_ANCHOR] extracted first hash "${hash}" from ${lines}-line block — use bare "${hash}" next time`);
|
|
186
183
|
}
|
|
187
184
|
}
|
|
188
185
|
const match = trimmed.match(ANCHOR_ROW_RE);
|
|
189
186
|
if (match) {
|
|
190
187
|
let message;
|
|
191
188
|
if (match[1] === "+") {
|
|
192
|
-
message = `[
|
|
189
|
+
message = `[E_BAD_ANCHOR] stripped diff-preview marker from remove_from/remove_to "${trimmed}".`;
|
|
193
190
|
}
|
|
194
191
|
else if (match[1] === "-") {
|
|
195
|
-
message = `[
|
|
192
|
+
message = `[E_BAD_ANCHOR] stripped leading "-" marker from remove_from/remove_to "${trimmed}".`;
|
|
196
193
|
}
|
|
197
194
|
else {
|
|
198
|
-
message = `[
|
|
195
|
+
message = `[E_BAD_ANCHOR] stripped "HASH│" prefix from remove_from/remove_to "${trimmed}".`;
|
|
199
196
|
}
|
|
200
|
-
|
|
201
|
-
return match[2];
|
|
197
|
+
throw new CodedError("E_BAD_ANCHOR", `[MODEL] ${message}`);
|
|
202
198
|
}
|
|
203
199
|
return ref;
|
|
204
200
|
});
|
|
@@ -213,7 +209,7 @@ function warnUnicodeEsc(edit, warnings) {
|
|
|
213
209
|
}
|
|
214
210
|
}
|
|
215
211
|
/** @internal — private to anchor-pipeline seam; do not import directly, use anchor-pipeline.ts */
|
|
216
|
-
function stripBarePrefixes(edit, fileHashes,
|
|
212
|
+
function stripBarePrefixes(edit, fileHashes, _warnings) {
|
|
217
213
|
const fileHashSet = new Set(fileHashes);
|
|
218
214
|
const stripped = [];
|
|
219
215
|
const contentLines = edit.content_lines.map((line, lineIndex) => {
|
|
@@ -225,21 +221,18 @@ function stripBarePrefixes(edit, fileHashes, warnings) {
|
|
|
225
221
|
});
|
|
226
222
|
if (stripped.length === 0)
|
|
227
223
|
return edit;
|
|
228
|
-
const locations = stripped
|
|
229
|
-
.map((s) => `replacement_text line ${s.lineIndex + 1}`)
|
|
230
|
-
.join(", ");
|
|
224
|
+
const locations = stripped.map((s) => `replacement_text line ${s.lineIndex + 1}`).join(", ");
|
|
231
225
|
const matchedCount = stripped.filter((s) => s.matched).length;
|
|
232
|
-
const evidence = matchedCount === 0
|
|
226
|
+
const evidence = matchedCount === 0
|
|
227
|
+
? "0 matched — verify literal 'HASH│' content"
|
|
228
|
+
: `${matchedCount}/${stripped.length} matched`;
|
|
233
229
|
if (matchedCount === stripped.length) {
|
|
234
|
-
|
|
235
|
-
}
|
|
236
|
-
else {
|
|
237
|
-
warnings.push(`[E_BARE_HASH_PREFIX] stripped "HASH│" prefix from ${locations} (${evidence}).`);
|
|
230
|
+
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
231
|
}
|
|
239
|
-
|
|
232
|
+
throw new BadAnchorError(`[MODEL] [E_BAD_ANCHOR] stripped "HASH│" prefix from ${locations} (${evidence}).`, { ...edit, content_lines: contentLines });
|
|
240
233
|
}
|
|
241
234
|
/** @internal — private to anchor-pipeline seam */
|
|
242
|
-
function stripDiffPrefixes(edit,
|
|
235
|
+
function stripDiffPrefixes(edit, _warnings) {
|
|
243
236
|
const stripped = [];
|
|
244
237
|
const contentLines = edit.content_lines.map((line, lineIndex) => {
|
|
245
238
|
const plus = line.match(HL_PREFIX_PLUS_RE);
|
|
@@ -256,11 +249,8 @@ function stripDiffPrefixes(edit, warnings) {
|
|
|
256
249
|
});
|
|
257
250
|
if (stripped.length === 0)
|
|
258
251
|
return edit;
|
|
259
|
-
const locations = stripped
|
|
260
|
-
|
|
261
|
-
.join(", ");
|
|
262
|
-
warnings.push(`[E_INVALID_PATCH] stripped diff-preview marker from ${locations}.`);
|
|
263
|
-
return { ...edit, content_lines: contentLines };
|
|
252
|
+
const locations = stripped.map((i) => `replacement_text line ${i + 1}`).join(", ");
|
|
253
|
+
throw new BadAnchorError(`[MODEL] [E_BAD_ANCHOR] stripped diff-preview marker from ${locations}.`, { ...edit, content_lines: contentLines });
|
|
264
254
|
}
|
|
265
255
|
/** @internal — private to anchor-pipeline seam */
|
|
266
256
|
function swapReversedRanges(edit, fileHashes, warnings) {
|
|
@@ -271,12 +261,10 @@ function swapReversedRanges(edit, fileHashes, warnings) {
|
|
|
271
261
|
const [startRef, endRef] = edit.hash_bounds;
|
|
272
262
|
const startLine = lineByHash.get(startRef.hash);
|
|
273
263
|
const endLine = lineByHash.get(endRef.hash);
|
|
274
|
-
if (startLine === undefined ||
|
|
275
|
-
endLine === undefined ||
|
|
276
|
-
startLine <= endLine) {
|
|
264
|
+
if (startLine === undefined || endLine === undefined || startLine <= endLine) {
|
|
277
265
|
return edit;
|
|
278
266
|
}
|
|
279
|
-
warnings.push(`[
|
|
267
|
+
warnings.push(`[USER] [E_REVERSED_ANCHORS] reversed remove_from/remove_to (${startRef.hash} after ${endRef.hash}); swapped (healed).`);
|
|
280
268
|
return { ...edit, hash_bounds: [endRef, startRef] };
|
|
281
269
|
}
|
|
282
270
|
/** @internal — private to anchor-pipeline seam */
|
|
@@ -315,7 +303,7 @@ function valEdit(edit, fileLines, fileHashes, warnings, signal) {
|
|
|
315
303
|
return { resolved: undefined, mismatches };
|
|
316
304
|
}
|
|
317
305
|
if (startResolved.line > endResolved.line) {
|
|
318
|
-
throw new
|
|
306
|
+
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
307
|
}
|
|
320
308
|
const endLine = endResolved.line;
|
|
321
309
|
return {
|
|
@@ -326,16 +314,20 @@ function valEdit(edit, fileLines, fileHashes, warnings, signal) {
|
|
|
326
314
|
mismatches,
|
|
327
315
|
};
|
|
328
316
|
}
|
|
329
|
-
export function findNewEdge() {
|
|
317
|
+
export function findNewEdge() {
|
|
318
|
+
return undefined;
|
|
319
|
+
}
|
|
330
320
|
export { warnUnicodeEsc };
|
|
331
|
-
export class ServedRejectionError extends
|
|
321
|
+
export class ServedRejectionError extends CodedError {
|
|
332
322
|
code;
|
|
323
|
+
unservedKind;
|
|
333
324
|
firstOffendingLine;
|
|
334
325
|
servedRows;
|
|
335
326
|
constructor(opts) {
|
|
336
|
-
super(opts.message);
|
|
327
|
+
super(opts.code, opts.message);
|
|
337
328
|
this.name = "ServedRejectionError";
|
|
338
329
|
this.code = opts.code;
|
|
330
|
+
this.unservedKind = opts.unservedKind;
|
|
339
331
|
this.firstOffendingLine = opts.firstOffendingLine;
|
|
340
332
|
this.servedRows = opts.servedRows;
|
|
341
333
|
}
|
|
@@ -343,21 +335,34 @@ export class ServedRejectionError extends Error {
|
|
|
343
335
|
export function isServedRejection(error) {
|
|
344
336
|
return error instanceof ServedRejectionError;
|
|
345
337
|
}
|
|
346
|
-
export class AnchorMismatchError extends
|
|
338
|
+
export class AnchorMismatchError extends CodedError {
|
|
347
339
|
servedRows;
|
|
348
340
|
constructor(message, servedRows) {
|
|
349
|
-
super(message);
|
|
341
|
+
super("E_STALE_ANCHOR", message);
|
|
350
342
|
this.name = "AnchorMismatchError";
|
|
351
343
|
this.servedRows = servedRows;
|
|
352
344
|
}
|
|
353
345
|
}
|
|
346
|
+
/** Thrown when replacement_text carries anchor-syntax garbage (HASH│/diff-preview prefixes).
|
|
347
|
+
* Carries the stripped edit so applyEdit can distinguish served-echo (→ E_SERVED_ECHO
|
|
348
|
+
* denial downstream) from garbage (→ E_BAD_ANCHOR stands). */
|
|
349
|
+
export class BadAnchorError extends CodedError {
|
|
350
|
+
stripped;
|
|
351
|
+
constructor(message, stripped) {
|
|
352
|
+
super("E_BAD_ANCHOR", message);
|
|
353
|
+
this.name = "BadAnchorError";
|
|
354
|
+
this.stripped = stripped;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
354
357
|
export function isAnchorMismatch(error) {
|
|
355
358
|
return error instanceof AnchorMismatchError;
|
|
356
359
|
}
|
|
357
360
|
export function findEditHashEcho(replacementLines, served, startLine) {
|
|
358
361
|
for (let k = 0; k < replacementLines.length; k++) {
|
|
359
362
|
const pos = startLine + k - 1;
|
|
360
|
-
if (pos < served.length &&
|
|
363
|
+
if (pos < served.length &&
|
|
364
|
+
served[pos] !== null &&
|
|
365
|
+
replacementLines[k].startsWith(served[pos] + HASH_SEP)) {
|
|
361
366
|
return { k: k + 1, hash: served[pos] };
|
|
362
367
|
}
|
|
363
368
|
}
|
|
@@ -379,9 +384,7 @@ export function buildRangeEcho(startLine, endLine, fileHashes) {
|
|
|
379
384
|
return rows;
|
|
380
385
|
}
|
|
381
386
|
export function fmtServedRows(rows, fileLines) {
|
|
382
|
-
return rows
|
|
383
|
-
.map((row) => `${row.hash}${HASH_SEP}${fileLines[row.position] ?? ""}`)
|
|
384
|
-
.join("\n");
|
|
387
|
+
return rows.map((row) => `${row.hash}${HASH_SEP}${fileLines[row.position] ?? ""}`).join("\n");
|
|
385
388
|
}
|
|
386
389
|
function retryHint() {
|
|
387
390
|
return "Retry with these anchors (no read needed).";
|
|
@@ -390,9 +393,9 @@ function paginationHint(nextOffset, more) {
|
|
|
390
393
|
return `[... ${more} more — read offset=${nextOffset}]`;
|
|
391
394
|
}
|
|
392
395
|
export function verifyServedRange(args) {
|
|
393
|
-
const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath
|
|
396
|
+
const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath } = args;
|
|
394
397
|
const where = filePath ? ` in ${filePath}` : "";
|
|
395
|
-
const
|
|
398
|
+
const retiredSet = args.retired ?? new Set();
|
|
396
399
|
const servedCanons = args.servedCanons;
|
|
397
400
|
const strictPos = args.strictPos ?? false;
|
|
398
401
|
const epochSnapshotId = args.epochSnapshotId;
|
|
@@ -420,18 +423,18 @@ export function verifyServedRange(args) {
|
|
|
420
423
|
// Tombstone check for boundaries (whole-span S@3==S@3)
|
|
421
424
|
// If hash was freed in this epoch, any reuse is stale even at same pos+same canon.
|
|
422
425
|
// Early reject checks canon change to avoid false positive on same line re-read.
|
|
423
|
-
if (
|
|
424
|
-
const
|
|
426
|
+
if (retiredSet.has(startHash) || retiredSet.has(endHash)) {
|
|
427
|
+
const retiredHash = retiredSet.has(startHash) ? startHash : endHash;
|
|
425
428
|
if (servedCanons) {
|
|
426
|
-
const pos = fileHashes.indexOf(
|
|
429
|
+
const pos = fileHashes.indexOf(retiredHash);
|
|
427
430
|
if (pos >= 0) {
|
|
428
|
-
const servedIdx = served.indexOf(
|
|
431
|
+
const servedIdx = served.indexOf(retiredHash);
|
|
429
432
|
const expected = servedIdx >= 0 ? servedCanons[servedIdx] : undefined;
|
|
430
433
|
const actual = canon(fileLines[pos] ?? "");
|
|
431
434
|
if (expected !== undefined && expected !== null && expected !== actual) {
|
|
432
435
|
throw new ServedRejectionError({
|
|
433
|
-
code: "
|
|
434
|
-
message: `[
|
|
436
|
+
code: "E_STALE_RANGE",
|
|
437
|
+
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
438
|
firstOffendingLine: pos + 1,
|
|
436
439
|
servedRows: echoRows,
|
|
437
440
|
});
|
|
@@ -594,8 +597,9 @@ export function verifyServedRange(args) {
|
|
|
594
597
|
problems.push(`remove_to "${endHash}" was served at ${endPositions.length} positions`);
|
|
595
598
|
}
|
|
596
599
|
throw new ServedRejectionError({
|
|
597
|
-
code: "
|
|
598
|
-
|
|
600
|
+
code: "E_UNSERVED_RANGE",
|
|
601
|
+
unservedKind: "boundary",
|
|
602
|
+
message: `[MODEL] [E_UNSERVED_RANGE] cannot verify range against served state${where}: ${problems.join("; ")}. ` +
|
|
599
603
|
`No served span matched the current range (${currentLen} lines). ` +
|
|
600
604
|
`A full read will re-sync the served mirror — the echoed range below is current content, ` +
|
|
601
605
|
`but retrying without re-reading cannot clear a stale duplicate outside the echoed window.\n` +
|
|
@@ -614,8 +618,8 @@ export function verifyServedRange(args) {
|
|
|
614
618
|
if (expectedCanon !== undefined && expectedCanon !== actualCanon) {
|
|
615
619
|
const offendingLine = from + k + 1;
|
|
616
620
|
throw new ServedRejectionError({
|
|
617
|
-
code: "
|
|
618
|
-
message: `[
|
|
621
|
+
code: "E_STALE_RANGE",
|
|
622
|
+
message: `[MODEL] [E_STALE_RANGE] line ${offendingLine}${where} differs from what was served.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
619
623
|
firstOffendingLine: offendingLine,
|
|
620
624
|
servedRows: echoRows,
|
|
621
625
|
});
|
|
@@ -626,8 +630,9 @@ export function verifyServedRange(args) {
|
|
|
626
630
|
for (let i = from; i <= to; i++) {
|
|
627
631
|
if (served[i] === null) {
|
|
628
632
|
throw new ServedRejectionError({
|
|
629
|
-
code: "
|
|
630
|
-
|
|
633
|
+
code: "E_UNSERVED_RANGE",
|
|
634
|
+
unservedKind: "interior",
|
|
635
|
+
message: `[MODEL] [E_UNSERVED_RANGE] line ${i + 1}${where} was never served.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
631
636
|
firstOffendingLine: i + 1,
|
|
632
637
|
servedRows: echoRows,
|
|
633
638
|
});
|
|
@@ -670,8 +675,8 @@ export function verifyServedRange(args) {
|
|
|
670
675
|
}
|
|
671
676
|
if (!lenHealed) {
|
|
672
677
|
throw new ServedRejectionError({
|
|
673
|
-
code: "
|
|
674
|
-
message: `[
|
|
678
|
+
code: "E_STALE_RANGE",
|
|
679
|
+
message: `[MODEL] [E_STALE_RANGE] served span (${servedLen} lines) no longer matches current range (${currentLen} lines)${where}.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
675
680
|
firstOffendingLine: startLine,
|
|
676
681
|
servedRows: echoRows,
|
|
677
682
|
});
|
|
@@ -680,8 +685,8 @@ export function verifyServedRange(args) {
|
|
|
680
685
|
// Strict pos check for concurrency (pos-free vs strict)
|
|
681
686
|
if (strictPos && from !== startLine - 1) {
|
|
682
687
|
throw new ServedRejectionError({
|
|
683
|
-
code: "
|
|
684
|
-
message: `[
|
|
688
|
+
code: "E_STALE_RANGE",
|
|
689
|
+
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
690
|
firstOffendingLine: startLine,
|
|
686
691
|
servedRows: echoRows,
|
|
687
692
|
});
|
|
@@ -694,8 +699,8 @@ export function verifyServedRange(args) {
|
|
|
694
699
|
const actual = canon(fileLines[startLine - 1 + k] ?? "");
|
|
695
700
|
if (expected !== actual) {
|
|
696
701
|
throw new ServedRejectionError({
|
|
697
|
-
code: "
|
|
698
|
-
message: `[
|
|
702
|
+
code: "E_STALE_RANGE",
|
|
703
|
+
message: `[MODEL] [E_STALE_RANGE] line ${startLine + k}${where} canon differs from served (expected "${expected}" vs actual "${actual}").\nCurrent range:\n${echo}`,
|
|
699
704
|
firstOffendingLine: startLine + k,
|
|
700
705
|
servedRows: echoRows,
|
|
701
706
|
});
|
|
@@ -706,13 +711,15 @@ export function verifyServedRange(args) {
|
|
|
706
711
|
// Tombstone interior check (whole-span) — gated on canon inequality (fail-closed only for different canon)
|
|
707
712
|
for (let k = 0; k < servedLen; k++) {
|
|
708
713
|
const h = fileHashes[startLine - 1 + k];
|
|
709
|
-
if (h &&
|
|
714
|
+
if (h && retiredSet.has(h)) {
|
|
710
715
|
const expectedCanon = servedCanons?.[from + k] ?? undefined;
|
|
711
716
|
const actualCanon = canon(fileLines[startLine - 1 + k] ?? "");
|
|
712
|
-
if (expectedCanon !== undefined &&
|
|
717
|
+
if (expectedCanon !== undefined &&
|
|
718
|
+
expectedCanon !== null &&
|
|
719
|
+
expectedCanon !== actualCanon) {
|
|
713
720
|
throw new ServedRejectionError({
|
|
714
|
-
code: "
|
|
715
|
-
message: `[
|
|
721
|
+
code: "E_STALE_RANGE",
|
|
722
|
+
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
723
|
firstOffendingLine: startLine + k,
|
|
717
724
|
servedRows: echoRows,
|
|
718
725
|
});
|
|
@@ -723,8 +730,8 @@ export function verifyServedRange(args) {
|
|
|
723
730
|
if (served[from + k] !== fileHashes[startLine - 1 + k]) {
|
|
724
731
|
const offendingLine = startLine + k;
|
|
725
732
|
throw new ServedRejectionError({
|
|
726
|
-
code: "
|
|
727
|
-
message: `[
|
|
733
|
+
code: "E_STALE_RANGE",
|
|
734
|
+
message: `[MODEL] [E_STALE_RANGE] line ${offendingLine}${where} differs from what was served.\nCurrent range:\n${echo}\n${retryHint()}`,
|
|
728
735
|
firstOffendingLine: offendingLine,
|
|
729
736
|
servedRows: echoRows,
|
|
730
737
|
});
|
|
@@ -755,7 +762,7 @@ export function buildIdx(content) {
|
|
|
755
762
|
}
|
|
756
763
|
function assertNotEmpty(originalContent, result) {
|
|
757
764
|
if (originalContent.length > 0 && result.length === 0) {
|
|
758
|
-
throw new Error("[
|
|
765
|
+
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
766
|
}
|
|
760
767
|
}
|
|
761
768
|
function resToSpan(edit, content, lineIndex) {
|
|
@@ -815,16 +822,42 @@ function resToSpan(edit, content, lineIndex) {
|
|
|
815
822
|
}
|
|
816
823
|
function assemble(content, span, signal) {
|
|
817
824
|
abortIf(signal);
|
|
818
|
-
return
|
|
825
|
+
return content.slice(0, span.start) + span.replacement + content.slice(span.end);
|
|
819
826
|
}
|
|
820
|
-
export function applyEdit(content, edit, signal, precomputedHashes, filePath, served, servedCanons,
|
|
827
|
+
export function applyEdit(content, edit, signal, precomputedHashes, filePath, served, servedCanons, retired, epochSnapshotId, curSnapshotId, strictPos) {
|
|
821
828
|
abortIf(signal);
|
|
822
829
|
const lineIndex = buildIdx(content);
|
|
823
830
|
const fileHashes = precomputedHashes ?? lineHashesPure(content);
|
|
824
831
|
const warnings = [];
|
|
825
832
|
const rangeFixed = swapReversedRanges(edit, fileHashes, warnings);
|
|
826
|
-
|
|
827
|
-
|
|
833
|
+
let prefixFixed;
|
|
834
|
+
try {
|
|
835
|
+
prefixFixed = stripDiffPrefixes(stripBarePrefixes(rangeFixed, fileHashes, warnings), warnings);
|
|
836
|
+
}
|
|
837
|
+
catch (error) {
|
|
838
|
+
if (!(error instanceof BadAnchorError) || !served)
|
|
839
|
+
throw error;
|
|
840
|
+
// Anchor-syntax garbage that is actually served-echo belongs to the
|
|
841
|
+
// E_SERVED_ECHO guard below: re-check the stripped + raw lines at the
|
|
842
|
+
// resolved start line and throw the echo denial; otherwise E_BAD_ANCHOR stands.
|
|
843
|
+
const stripped = error.stripped;
|
|
844
|
+
const lineByHash = new Map();
|
|
845
|
+
for (let i = 0; i < fileHashes.length; i++)
|
|
846
|
+
lineByHash.set(fileHashes[i], i + 1);
|
|
847
|
+
const startLine = lineByHash.get(stripped.hash_bounds[0].hash);
|
|
848
|
+
const echo = (startLine !== undefined
|
|
849
|
+
? findEditHashEcho(edit.content_lines, served, startLine)
|
|
850
|
+
: undefined) ??
|
|
851
|
+
(startLine !== undefined
|
|
852
|
+
? findEditHashEcho(stripped.content_lines, served, startLine)
|
|
853
|
+
: undefined);
|
|
854
|
+
if (echo) {
|
|
855
|
+
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.`;
|
|
856
|
+
throw new EditHashEchoError(msg, []);
|
|
857
|
+
}
|
|
858
|
+
throw error;
|
|
859
|
+
}
|
|
860
|
+
const { resolved: initialResolved, mismatches } = valEdit(prefixFixed, lineIndex.fileLines, fileHashes, warnings, signal);
|
|
828
861
|
if (mismatches.length || !initialResolved) {
|
|
829
862
|
const { message, servedRows } = fmtMismatchWithServes(mismatches, lineIndex.fileLines, fileHashes, filePath);
|
|
830
863
|
throw new AnchorMismatchError(message, servedRows);
|
|
@@ -840,7 +873,7 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
|
|
|
840
873
|
if (!echo)
|
|
841
874
|
echo = findEditHashEcho(prefixFixed.content_lines, served, startLineEcho);
|
|
842
875
|
if (echo) {
|
|
843
|
-
const msg = `[
|
|
876
|
+
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
877
|
throw new EditHashEchoError(msg, []);
|
|
845
878
|
}
|
|
846
879
|
const startAnchor = resolved.hash_bounds[0];
|
|
@@ -855,7 +888,7 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
|
|
|
855
888
|
fileLines: lineIndex.fileLines,
|
|
856
889
|
filePath,
|
|
857
890
|
servedCanons,
|
|
858
|
-
|
|
891
|
+
retired,
|
|
859
892
|
epochSnapshotId,
|
|
860
893
|
curSnapshotId,
|
|
861
894
|
strictPos,
|
|
@@ -900,9 +933,7 @@ export function fmtRegion(hashes, lines) {
|
|
|
900
933
|
if (hashes.length !== lines.length) {
|
|
901
934
|
throw new Error(`fmtRegion: hashes.length (${hashes.length}) must match lines.length (${lines.length}).`);
|
|
902
935
|
}
|
|
903
|
-
return lines
|
|
904
|
-
.map((line, index) => `${hashes[index]}${HASH_SEP}${line}`)
|
|
905
|
-
.join("\n");
|
|
936
|
+
return lines.map((line, index) => `${hashes[index]}${HASH_SEP}${line}`).join("\n");
|
|
906
937
|
}
|
|
907
938
|
export function changedRange(original, result) {
|
|
908
939
|
if (original === result)
|
|
@@ -21,10 +21,12 @@ export function getH() {
|
|
|
21
21
|
return hasher;
|
|
22
22
|
throw new Error("xxhash-wasm hasher not initialized; await initHasher() before calling hashline APIs.");
|
|
23
23
|
}
|
|
24
|
-
const hasherP = xxhash()
|
|
24
|
+
const hasherP = xxhash()
|
|
25
|
+
.then((h) => {
|
|
25
26
|
hasher = h;
|
|
26
27
|
return hasher;
|
|
27
|
-
})
|
|
28
|
+
})
|
|
29
|
+
.catch((err) => {
|
|
28
30
|
console.error("xxhash-wasm initialization failed:", err);
|
|
29
31
|
throw err;
|
|
30
32
|
});
|
|
@@ -48,9 +50,23 @@ export const HASH_RE = new RegExp(`^${HASH_CLASS}$`);
|
|
|
48
50
|
export const ANCHOR_LEN = HASH_LEN;
|
|
49
51
|
export const HASH_SEP = "│";
|
|
50
52
|
export const HASH_SPACE = ALPH.length ** HASH_LEN;
|
|
53
|
+
// MAX_HASH_LINES is the anchor-space size (62³), not a line-count limit.
|
|
54
|
+
// File line-count limits use maxLines (e.g. 200k) and report E_LARGE_FILE;
|
|
55
|
+
// anchor-space exhaustion reports E_ANCHOR_SPACE_EXHAUSTED — see nextZeroBit.
|
|
51
56
|
export const MAX_HASH_LINES = HASH_SPACE;
|
|
52
57
|
export const HASH_PROBE_STRIDE = ALPH.length ** 2 + ALPH.length + 1;
|
|
53
|
-
|
|
58
|
+
export class AnchorSpaceExhaustedError extends Error {
|
|
59
|
+
code = "E_ANCHOR_SPACE_EXHAUSTED";
|
|
60
|
+
retiredCount;
|
|
61
|
+
servedCount;
|
|
62
|
+
constructor(retiredCount, servedCount, reservedCount) {
|
|
63
|
+
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.`);
|
|
64
|
+
this.name = "AnchorSpaceExhaustedError";
|
|
65
|
+
this.retiredCount = retiredCount;
|
|
66
|
+
this.servedCount = servedCount;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export function idxToHash(idx) {
|
|
54
70
|
let out = "";
|
|
55
71
|
for (let j = 0; j < HASH_LEN; j++) {
|
|
56
72
|
out = ALPH[idx % ALPH.length] + out;
|
|
@@ -59,7 +75,7 @@ function idxToHash(idx) {
|
|
|
59
75
|
return out;
|
|
60
76
|
}
|
|
61
77
|
const hashCache = new Map();
|
|
62
|
-
function hashAt(idx) {
|
|
78
|
+
export function hashAt(idx) {
|
|
63
79
|
let hash = hashCache.get(idx);
|
|
64
80
|
if (hash === undefined) {
|
|
65
81
|
hash = idxToHash(idx);
|
|
@@ -93,7 +109,7 @@ function getCanon(cache, line) {
|
|
|
93
109
|
}
|
|
94
110
|
const BITSET_WORDS = Math.ceil(HASH_SPACE / 32);
|
|
95
111
|
function getBit(bits, idx) {
|
|
96
|
-
return (bits[idx >>> 5] >>> (idx & 31) & 1) !== 0;
|
|
112
|
+
return ((bits[idx >>> 5] >>> (idx & 31)) & 1) !== 0;
|
|
97
113
|
}
|
|
98
114
|
function setBit(bits, idx) {
|
|
99
115
|
bits[idx >>> 5] |= 1 << (idx & 31);
|
|
@@ -108,7 +124,7 @@ function nextZeroBit(bits, start) {
|
|
|
108
124
|
if (idx >= totalBits)
|
|
109
125
|
idx -= totalBits;
|
|
110
126
|
}
|
|
111
|
-
throw new Error(`[
|
|
127
|
+
throw new Error(`[MODEL] [E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted — probing failed over ${HASH_SPACE} slots (reserved full).`);
|
|
112
128
|
}
|
|
113
129
|
function assignHash(used, baseIdx, hint) {
|
|
114
130
|
if (!getBit(used, baseIdx)) {
|
|
@@ -121,7 +137,9 @@ function assignHash(used, baseIdx, hint) {
|
|
|
121
137
|
hint.value = nextIdx + HASH_PROBE_STRIDE;
|
|
122
138
|
return hashAt(nextIdx);
|
|
123
139
|
}
|
|
124
|
-
export function lineHashesPure(content, reservedHashes = new Set()
|
|
140
|
+
export function lineHashesPure(content, reservedHashes = new Set(),
|
|
141
|
+
// optional counts for richer error — when caller knows retired vs served split
|
|
142
|
+
retiredCount, servedCount) {
|
|
125
143
|
const lines = splitLines(content);
|
|
126
144
|
const hashes = new Array(lines.length);
|
|
127
145
|
const used = new Uint32Array(BITSET_WORDS);
|
|
@@ -129,12 +147,24 @@ export function lineHashesPure(content, reservedHashes = new Set()) {
|
|
|
129
147
|
markHashUsed(used, hash);
|
|
130
148
|
const hint = { value: 0 };
|
|
131
149
|
const canonCache = new Map();
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
150
|
+
try {
|
|
151
|
+
for (let i = 0; i < lines.length; i++) {
|
|
152
|
+
const c = getCanon(canonCache, lines[i]);
|
|
153
|
+
const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
|
|
154
|
+
const h = assignHash(used, baseIdx, hint);
|
|
155
|
+
hashes[i] = h;
|
|
156
|
+
rememberHashCanon(h, c);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
catch (e) {
|
|
160
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
161
|
+
if (msg.includes("E_ANCHOR_SPACE_EXHAUSTED") || msg.includes("Cannot allocate")) {
|
|
162
|
+
const rc = retiredCount ?? reservedHashes.size;
|
|
163
|
+
const sc = servedCount ?? 0;
|
|
164
|
+
const reserved = reservedHashes.size;
|
|
165
|
+
throw new AnchorSpaceExhaustedError(rc, sc, reserved);
|
|
166
|
+
}
|
|
167
|
+
throw e;
|
|
138
168
|
}
|
|
139
169
|
return hashes;
|
|
140
170
|
}
|
|
@@ -160,12 +190,13 @@ function nearestNew(candidates, target) {
|
|
|
160
190
|
}
|
|
161
191
|
const left = lo - 1;
|
|
162
192
|
const right = lo;
|
|
163
|
-
if (left >= 0 &&
|
|
193
|
+
if (left >= 0 &&
|
|
194
|
+
(right >= candidates.length || target - candidates[left] <= candidates[right] - target)) {
|
|
164
195
|
return left;
|
|
165
196
|
}
|
|
166
197
|
return right < candidates.length ? right : -1;
|
|
167
198
|
}
|
|
168
|
-
export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes, reservedHashes = new Set()) {
|
|
199
|
+
export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes, reservedHashes = new Set(), retiredCount, servedCount) {
|
|
169
200
|
const oldLines = splitLines(oldContent);
|
|
170
201
|
const newLines = splitLines(newContent);
|
|
171
202
|
const newHashes = new Array(newLines.length);
|
|
@@ -239,14 +270,25 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
|
|
|
239
270
|
markUsed(entry.hash);
|
|
240
271
|
rememberHashCanon(entry.hash, getCanon(canonCache, oldLines[entry.index]));
|
|
241
272
|
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
273
|
+
try {
|
|
274
|
+
for (let i = 0; i < newLines.length; i++) {
|
|
275
|
+
if (newHashes[i])
|
|
276
|
+
continue;
|
|
277
|
+
const c = getCanon(canonCache, newLines[i]);
|
|
278
|
+
const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
|
|
279
|
+
const h = assignHash(used, baseIdx, hint);
|
|
280
|
+
newHashes[i] = h;
|
|
281
|
+
rememberHashCanon(h, c);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
catch (e) {
|
|
285
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
286
|
+
if (msg.includes("E_ANCHOR_SPACE_EXHAUSTED")) {
|
|
287
|
+
const rc = retiredCount ?? reservedHashes.size;
|
|
288
|
+
const sc = servedCount ?? 0;
|
|
289
|
+
throw new AnchorSpaceExhaustedError(rc, sc, reservedHashes.size);
|
|
290
|
+
}
|
|
291
|
+
throw e;
|
|
250
292
|
}
|
|
251
293
|
return newHashes;
|
|
252
294
|
}
|