dsh-better-edit 0.6.3 → 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 +29 -0
- package/README.md +14 -13
- 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/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/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/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 +1 -1
package/lib/hash-store.js
CHANGED
|
@@ -66,6 +66,58 @@ export function isValidServedList(value) {
|
|
|
66
66
|
function cacheKey(checksum) {
|
|
67
67
|
return `${CANON_VERSION}:${checksum}`;
|
|
68
68
|
}
|
|
69
|
+
export function isValidRetiredEntry(value) {
|
|
70
|
+
if (typeof value !== "object" || value === null)
|
|
71
|
+
return false;
|
|
72
|
+
const v = value;
|
|
73
|
+
return typeof v.hash === "string" && (v.deathPos === null || typeof v.deathPos === "number") && HASH_RE.test(v.hash);
|
|
74
|
+
}
|
|
75
|
+
export function isValidRetiredEntries(value) {
|
|
76
|
+
if (!Array.isArray(value))
|
|
77
|
+
return false;
|
|
78
|
+
for (const e of value)
|
|
79
|
+
if (!isValidRetiredEntry(e))
|
|
80
|
+
return false;
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
function coerceRetiredEntry(e) {
|
|
84
|
+
if (typeof e === "string" && HASH_RE.test(e))
|
|
85
|
+
return { hash: e, deathPos: null };
|
|
86
|
+
if (typeof e !== "object" || e === null || !("hash" in e))
|
|
87
|
+
return null;
|
|
88
|
+
const ee = e;
|
|
89
|
+
if (typeof ee.hash !== "string" || !HASH_RE.test(ee.hash))
|
|
90
|
+
return null;
|
|
91
|
+
const rawPos = ee.deathPos;
|
|
92
|
+
const deathPos = typeof rawPos === "number" && rawPos !== -1 ? rawPos : null;
|
|
93
|
+
return { hash: ee.hash, deathPos };
|
|
94
|
+
}
|
|
95
|
+
function parseRetiredJson(raw) {
|
|
96
|
+
if (raw === null || raw === undefined || raw === "")
|
|
97
|
+
return [];
|
|
98
|
+
try {
|
|
99
|
+
const parsed = JSON.parse(raw);
|
|
100
|
+
if (!Array.isArray(parsed) || parsed.length === 0)
|
|
101
|
+
return [];
|
|
102
|
+
if (isValidRetiredEntries(parsed)) {
|
|
103
|
+
return parsed.map((e) => (e.deathPos === -1 ? { hash: e.hash, deathPos: null } : e));
|
|
104
|
+
}
|
|
105
|
+
const out = [];
|
|
106
|
+
for (const e of parsed) {
|
|
107
|
+
const coerced = coerceRetiredEntry(e);
|
|
108
|
+
if (coerced)
|
|
109
|
+
out.push(coerced);
|
|
110
|
+
}
|
|
111
|
+
if (out.length > 0)
|
|
112
|
+
return out;
|
|
113
|
+
if (isValidHashList(parsed))
|
|
114
|
+
return parsed.map((h) => ({ hash: h, deathPos: null }));
|
|
115
|
+
return [];
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return [];
|
|
119
|
+
}
|
|
120
|
+
}
|
|
69
121
|
/** Load the store as served persistence — internal, for SessionView only. */
|
|
70
122
|
// SAFETY: loadHashStore returns InternalHashStore (HashStore & ServedPersistence) — cast narrows to served view, validated via ServedPersistence interface; safe because InternalHashStore extends both.
|
|
71
123
|
export function loadServedStore(cwd) {
|
|
@@ -182,6 +234,7 @@ function buildStore(db) {
|
|
|
182
234
|
"retired TEXT, " +
|
|
183
235
|
"canons TEXT, " +
|
|
184
236
|
"snapshotId TEXT, " +
|
|
237
|
+
"cards TEXT, " +
|
|
185
238
|
"updated_at INTEGER NOT NULL, " +
|
|
186
239
|
"PRIMARY KEY (session_id, path)" +
|
|
187
240
|
")");
|
|
@@ -225,6 +278,10 @@ function buildStore(db) {
|
|
|
225
278
|
if (!snapshotColumns.some((column) => column.name === "snapshotId")) {
|
|
226
279
|
db.exec("ALTER TABLE served ADD COLUMN snapshotId TEXT");
|
|
227
280
|
}
|
|
281
|
+
const cardsColumns = db.prepare("PRAGMA table_info(served)").all();
|
|
282
|
+
if (!cardsColumns.some((column) => column.name === "cards")) {
|
|
283
|
+
db.exec("ALTER TABLE served ADD COLUMN cards TEXT");
|
|
284
|
+
}
|
|
228
285
|
db
|
|
229
286
|
.prepare("INSERT INTO meta (key, value) VALUES ('version', ?) " +
|
|
230
287
|
"ON CONFLICT(key) DO UPDATE SET value = excluded.value")
|
|
@@ -240,7 +297,7 @@ function buildStore(db) {
|
|
|
240
297
|
const undoGetStmt = db.prepare("SELECT content, bom, ending, hashes, result_content FROM undo WHERE path = ?");
|
|
241
298
|
const undoDelStmt = db.prepare("DELETE FROM undo WHERE path = ?");
|
|
242
299
|
const undoPruneOlderThanStmt = db.prepare("DELETE FROM undo WHERE updated_at < ?");
|
|
243
|
-
const servedGetStmt = db.prepare("SELECT hashes, reported, retired, canons, snapshotId FROM served WHERE session_id = ? AND path = ?");
|
|
300
|
+
const servedGetStmt = db.prepare("SELECT hashes, reported, retired, canons, snapshotId, cards FROM served WHERE session_id = ? AND path = ?");
|
|
244
301
|
const servedAllForPathStmt = db.prepare("SELECT session_id, hashes, retired FROM served WHERE path = ?");
|
|
245
302
|
const servedUpsertStmt = db.prepare("INSERT INTO served (session_id, path, hashes, updated_at) VALUES (?, ?, ?, ?) " +
|
|
246
303
|
"ON CONFLICT(session_id, path) DO UPDATE SET hashes = excluded.hashes, updated_at = excluded.updated_at");
|
|
@@ -256,6 +313,9 @@ function buildStore(db) {
|
|
|
256
313
|
const servedSnapshotUpsertStmt = db.prepare("INSERT INTO served (session_id, path, hashes, snapshotId, updated_at) VALUES (?, ?, '[]', ?, ?) " +
|
|
257
314
|
"ON CONFLICT(session_id, path) DO UPDATE SET snapshotId = excluded.snapshotId, updated_at = excluded.updated_at");
|
|
258
315
|
const servedSnapshotClearStmt = db.prepare("UPDATE served SET snapshotId = NULL, updated_at = ? WHERE session_id = ? AND path = ?");
|
|
316
|
+
const servedCardsUpsertStmt = db.prepare("INSERT INTO served (session_id, path, hashes, cards, updated_at) VALUES (?, ?, '[]', ?, ?) " +
|
|
317
|
+
"ON CONFLICT(session_id, path) DO UPDATE SET cards = excluded.cards, updated_at = excluded.updated_at");
|
|
318
|
+
const servedCardsClearStmt = db.prepare("UPDATE served SET cards = NULL, updated_at = ? WHERE session_id = ? AND path = ?");
|
|
259
319
|
const servedDeleteStmt = db.prepare("DELETE FROM served WHERE session_id = ? AND path = ?");
|
|
260
320
|
const servedDeletePathStmt = db.prepare("DELETE FROM served WHERE path = ?");
|
|
261
321
|
const servedWipeStmt = db.prepare("DELETE FROM served WHERE session_id = ?");
|
|
@@ -337,6 +397,16 @@ function buildStore(db) {
|
|
|
337
397
|
servedSnapshotClearStmt.run(params[1], params[0], params[2]);
|
|
338
398
|
});
|
|
339
399
|
},
|
|
400
|
+
servedCardsUpsert: (...params) => {
|
|
401
|
+
withBusyRetry(() => {
|
|
402
|
+
servedCardsUpsertStmt.run(...params);
|
|
403
|
+
});
|
|
404
|
+
},
|
|
405
|
+
servedCardsClear: (...params) => {
|
|
406
|
+
withBusyRetry(() => {
|
|
407
|
+
servedCardsClearStmt.run(params[1], params[0], params[2]);
|
|
408
|
+
});
|
|
409
|
+
},
|
|
340
410
|
servedDelete: (...params) => {
|
|
341
411
|
withBusyRetry(() => {
|
|
342
412
|
servedDeleteStmt.run(...params);
|
|
@@ -475,31 +545,30 @@ function makeDomainStore(stmts) {
|
|
|
475
545
|
return new Set();
|
|
476
546
|
}
|
|
477
547
|
},
|
|
478
|
-
getAnchorReservations(path) {
|
|
548
|
+
getAnchorReservations(sessionKey, path) {
|
|
479
549
|
const reservedHashes = new Set();
|
|
480
550
|
const retiredHashes = new Set();
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
if (hash !== null)
|
|
492
|
-
reservedHashes.add(hash);
|
|
493
|
-
}
|
|
494
|
-
for (const hash of retired) {
|
|
551
|
+
const row = stmts.servedGet(sessionKey, path);
|
|
552
|
+
if (!row)
|
|
553
|
+
return { reservedHashes, retiredHashes };
|
|
554
|
+
try {
|
|
555
|
+
const served = JSON.parse(row.hashes);
|
|
556
|
+
if (!isValidServedList(served)) {
|
|
557
|
+
throw new TypeError("invalid stored anchor reservations");
|
|
558
|
+
}
|
|
559
|
+
for (const hash of served) {
|
|
560
|
+
if (hash !== null)
|
|
495
561
|
reservedHashes.add(hash);
|
|
496
|
-
retiredHashes.add(hash);
|
|
497
|
-
}
|
|
498
562
|
}
|
|
499
|
-
|
|
500
|
-
|
|
563
|
+
const retiredEntries = parseRetiredJson(row.retired);
|
|
564
|
+
for (const e of retiredEntries) {
|
|
565
|
+
reservedHashes.add(e.hash);
|
|
566
|
+
retiredHashes.add(e.hash);
|
|
501
567
|
}
|
|
502
568
|
}
|
|
569
|
+
catch (error) {
|
|
570
|
+
stmts.servedDelete(sessionKey, path);
|
|
571
|
+
}
|
|
503
572
|
return { reservedHashes, retiredHashes };
|
|
504
573
|
},
|
|
505
574
|
getRetiredAnchors(sessionKey, path) {
|
|
@@ -508,17 +577,26 @@ function makeDomainStore(stmts) {
|
|
|
508
577
|
return new Set();
|
|
509
578
|
}
|
|
510
579
|
try {
|
|
511
|
-
const
|
|
512
|
-
|
|
513
|
-
throw new TypeError("invalid retired anchors");
|
|
514
|
-
}
|
|
515
|
-
return new Set(parsed);
|
|
580
|
+
const entries = parseRetiredJson(row.retired);
|
|
581
|
+
return new Set(entries.map((e) => e.hash));
|
|
516
582
|
}
|
|
517
583
|
catch (error) {
|
|
518
584
|
stmts.servedDelete(sessionKey, path);
|
|
519
585
|
return new Set();
|
|
520
586
|
}
|
|
521
587
|
},
|
|
588
|
+
getRetiredEntries(sessionKey, path) {
|
|
589
|
+
const row = stmts.servedGet(sessionKey, path);
|
|
590
|
+
if (!row || row.retired === null || row.retired === undefined)
|
|
591
|
+
return [];
|
|
592
|
+
try {
|
|
593
|
+
return parseRetiredJson(row.retired);
|
|
594
|
+
}
|
|
595
|
+
catch {
|
|
596
|
+
stmts.servedDelete(sessionKey, path);
|
|
597
|
+
return [];
|
|
598
|
+
}
|
|
599
|
+
},
|
|
522
600
|
upsertServed(sessionKey, path, hashesJson) {
|
|
523
601
|
stmts.servedUpsert(sessionKey, path, hashesJson, Date.now());
|
|
524
602
|
},
|
|
@@ -567,6 +645,26 @@ function makeDomainStore(stmts) {
|
|
|
567
645
|
clearEpochSnapshotId(sessionKey, path) {
|
|
568
646
|
stmts.servedSnapshotClear(sessionKey, Date.now(), path);
|
|
569
647
|
},
|
|
648
|
+
getCards(sessionKey, path) {
|
|
649
|
+
const row = stmts.servedGet(sessionKey, path);
|
|
650
|
+
if (!row || row.cards === null || row.cards === undefined)
|
|
651
|
+
return new Set();
|
|
652
|
+
try {
|
|
653
|
+
const parsed = JSON.parse(row.cards);
|
|
654
|
+
if (!Array.isArray(parsed))
|
|
655
|
+
return new Set();
|
|
656
|
+
return new Set(parsed.filter((v) => typeof v === "number" && Number.isInteger(v) && v >= 0));
|
|
657
|
+
}
|
|
658
|
+
catch {
|
|
659
|
+
return new Set();
|
|
660
|
+
}
|
|
661
|
+
},
|
|
662
|
+
upsertCards(sessionKey, path, cardsJson) {
|
|
663
|
+
stmts.servedCardsUpsert(sessionKey, path, cardsJson, Date.now());
|
|
664
|
+
},
|
|
665
|
+
clearCards(sessionKey, path) {
|
|
666
|
+
stmts.servedCardsClear(sessionKey, Date.now(), path);
|
|
667
|
+
},
|
|
570
668
|
deleteServed(sessionKey, path) {
|
|
571
669
|
stmts.servedDelete(sessionKey, path);
|
|
572
670
|
},
|
|
@@ -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,
|