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
package/lib/mutation/engine.js
CHANGED
|
@@ -18,6 +18,39 @@ import { normFromText } from "../file-reader.js";
|
|
|
18
18
|
import { scanDrift, loadServed, loadServedCanons, loadEpochSnapshotId, loadRetiredAnchors, retireAnchors, } from "../session-view.js";
|
|
19
19
|
import { applyEdit, resEdit, parseHashRef, } from "../hashline/anchor-pipeline.js";
|
|
20
20
|
import { lineHashes } from "../hashline/hash.js";
|
|
21
|
+
import { AnchorSpaceExhaustedError, HASH_SPACE } from "../hashline/hash-assign.js";
|
|
22
|
+
function isAnchorSpaceExhausted(e) {
|
|
23
|
+
return e instanceof AnchorSpaceExhaustedError || (e instanceof Error && e.message.includes("E_ANCHOR_SPACE_EXHAUSTED"));
|
|
24
|
+
}
|
|
25
|
+
function promotionWarning(retiredSize, servedLen) {
|
|
26
|
+
return `[E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted (retired ${retiredSize} + served ${servedLen} of ${HASH_SPACE}); promotion cleared retired — re-read recommended, stale-anchor checks degraded until next full read.`;
|
|
27
|
+
}
|
|
28
|
+
async function clearRetiredForPromotion(sessionKey, absolutePath) {
|
|
29
|
+
try {
|
|
30
|
+
const { loadServedStore } = await import("../hash-store.js");
|
|
31
|
+
const store = await loadServedStore();
|
|
32
|
+
store.clearRetiredAnchors(sessionKey ?? "", absolutePath);
|
|
33
|
+
try {
|
|
34
|
+
store.clearCards(sessionKey ?? "", absolutePath);
|
|
35
|
+
}
|
|
36
|
+
catch { }
|
|
37
|
+
}
|
|
38
|
+
catch { }
|
|
39
|
+
}
|
|
40
|
+
async function retryLineHashesWithPromotion(sessionKey, absolutePath, retired, served, warnings, fn) {
|
|
41
|
+
await clearRetiredForPromotion(sessionKey, absolutePath);
|
|
42
|
+
const servedLen = served?.filter((h) => h !== null).length ?? 0;
|
|
43
|
+
warnings.push(promotionWarning(retired?.size ?? 0, servedLen));
|
|
44
|
+
const recomputed = new Set((served?.filter((h) => h !== null) ?? []));
|
|
45
|
+
try {
|
|
46
|
+
return await fn(recomputed, new Set());
|
|
47
|
+
}
|
|
48
|
+
catch (e2) {
|
|
49
|
+
if (isAnchorSpaceExhausted(e2))
|
|
50
|
+
throw new Error(`[MODEL] [E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted even after promotion (served ${servedLen} of ${HASH_SPACE}); file too large for hashline — use write.`);
|
|
51
|
+
throw e2;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
21
54
|
import { MAX_HASH_LINES } from "../hashline/hash-assign.js";
|
|
22
55
|
import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "../hashline/anchor-pipeline.js";
|
|
23
56
|
import { findSnapshotPathsByHashes } from "../hash-store.js";
|
|
@@ -57,11 +90,11 @@ export async function resolveMissingPath(request) {
|
|
|
57
90
|
if (matches.length === 1) {
|
|
58
91
|
return {
|
|
59
92
|
path: matches[0],
|
|
60
|
-
warning: `[
|
|
93
|
+
warning: `[MODEL] [E_BAD_PAYLOAD] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
|
|
61
94
|
};
|
|
62
95
|
}
|
|
63
96
|
if (matches.length > 1) {
|
|
64
|
-
throw new Error(`[
|
|
97
|
+
throw new Error(`[MODEL] [E_BAD_PAYLOAD] Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(', ')}. Include the intended path.`);
|
|
65
98
|
}
|
|
66
99
|
return undefined;
|
|
67
100
|
}
|
|
@@ -122,9 +155,10 @@ export async function applyOne(input, onReject) {
|
|
|
122
155
|
return onReject(error, undefined);
|
|
123
156
|
}
|
|
124
157
|
}
|
|
158
|
+
const retiredForApply = input.retired;
|
|
125
159
|
let anchorResult;
|
|
126
160
|
try {
|
|
127
|
-
anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served, input.servedCanons,
|
|
161
|
+
anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served, input.servedCanons, retiredForApply, input.epochSnapshotId, input.curSnapshotId, input.strictPos);
|
|
128
162
|
}
|
|
129
163
|
catch (error) {
|
|
130
164
|
if (error instanceof AnchorMismatchError ||
|
|
@@ -138,13 +172,29 @@ export async function applyOne(input, onReject) {
|
|
|
138
172
|
const removedHashes = noop
|
|
139
173
|
? undefined
|
|
140
174
|
: collectRemovedHashes(edit, input.hashes);
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
175
|
+
const retiredForHash = input.retired;
|
|
176
|
+
let resultHashes;
|
|
177
|
+
if (noop) {
|
|
178
|
+
resultHashes = input.hashes;
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
try {
|
|
182
|
+
resultHashes = await lineHashes(result, input.absolutePath, {
|
|
183
|
+
content: input.content,
|
|
184
|
+
hashes: input.hashes,
|
|
185
|
+
removedHashes,
|
|
186
|
+
}, input.store, input.persist, input.reservedHashes, retiredForHash);
|
|
187
|
+
}
|
|
188
|
+
catch (e) {
|
|
189
|
+
if (!isAnchorSpaceExhausted(e))
|
|
190
|
+
throw e;
|
|
191
|
+
resultHashes = await retryLineHashesWithPromotion(input.sessionKey, input.absolutePath, retiredForHash, input.served, input.warnings ?? [], (recomputed, emptyRetired) => lineHashes(result, input.absolutePath, {
|
|
192
|
+
content: input.content,
|
|
193
|
+
hashes: input.hashes,
|
|
194
|
+
removedHashes,
|
|
195
|
+
}, input.store, input.persist, recomputed, emptyRetired));
|
|
196
|
+
}
|
|
197
|
+
}
|
|
148
198
|
const { totalAddedLines, totalRemovedLines } = countLineChanges(edit, input.countHashes ?? input.hashes, noop, 0);
|
|
149
199
|
return {
|
|
150
200
|
result,
|
|
@@ -218,8 +268,8 @@ export async function runFileEdits(io, items, opts) {
|
|
|
218
268
|
const first = items[0];
|
|
219
269
|
abortIf(opts.signal);
|
|
220
270
|
const absolutePath = first.absolutePath;
|
|
221
|
-
const
|
|
222
|
-
const reservedHashes = new Set(
|
|
271
|
+
const perSessionRetired = await loadRetiredAnchors(opts.sessionKey, absolutePath);
|
|
272
|
+
const reservedHashes = new Set(perSessionRetired);
|
|
223
273
|
const rawText = await io.readText(absolutePath, opts.signal);
|
|
224
274
|
const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
|
|
225
275
|
absolutePath,
|
|
@@ -228,7 +278,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
228
278
|
signal: opts.signal,
|
|
229
279
|
maxLines: MAX_HASH_LINES,
|
|
230
280
|
reservedHashes,
|
|
231
|
-
retiredHashes:
|
|
281
|
+
retiredHashes: perSessionRetired,
|
|
232
282
|
});
|
|
233
283
|
const served = await loadServed(opts.sessionKey, absolutePath);
|
|
234
284
|
const servedCanons = await loadServedCanons(opts.sessionKey, absolutePath);
|
|
@@ -238,7 +288,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
238
288
|
curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
|
|
239
289
|
}
|
|
240
290
|
catch { }
|
|
241
|
-
const strictPos =
|
|
291
|
+
const strictPos = epochSnapshotId !== undefined && curSnapshotId !== undefined && epochSnapshotId !== curSnapshotId; // automatic: strict when epoch mismatch (conservative, future: changed∩[L,R] refined)
|
|
242
292
|
const warnings = [];
|
|
243
293
|
let currentContent = originalNormalized;
|
|
244
294
|
let currentHashes = originalHashes;
|
|
@@ -269,7 +319,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
269
319
|
persist: false,
|
|
270
320
|
reservedHashes,
|
|
271
321
|
servedCanons,
|
|
272
|
-
|
|
322
|
+
retired: new Set([...perSessionRetired, ...Array.from(newlyRetired)]),
|
|
273
323
|
epochSnapshotId,
|
|
274
324
|
curSnapshotId,
|
|
275
325
|
strictPos,
|
|
@@ -350,11 +400,22 @@ export async function runFileEdits(io, items, opts) {
|
|
|
350
400
|
const result = currentContent;
|
|
351
401
|
let resultHashes = currentHashes;
|
|
352
402
|
if (appliedCount > 0 && lastApplied) {
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
403
|
+
try {
|
|
404
|
+
resultHashes = await lineHashes(result, absolutePath, {
|
|
405
|
+
content: lastApplied.content,
|
|
406
|
+
hashes: lastApplied.hashes,
|
|
407
|
+
removedHashes: lastApplied.removedHashes,
|
|
408
|
+
}, undefined, true, reservedHashes, perSessionRetired);
|
|
409
|
+
}
|
|
410
|
+
catch (e) {
|
|
411
|
+
if (!isAnchorSpaceExhausted(e))
|
|
412
|
+
throw e;
|
|
413
|
+
resultHashes = await retryLineHashesWithPromotion(opts.sessionKey, absolutePath, perSessionRetired, served, warnings, (recomputed, emptyRetired) => lineHashes(result, absolutePath, {
|
|
414
|
+
content: lastApplied.content,
|
|
415
|
+
hashes: lastApplied.hashes,
|
|
416
|
+
removedHashes: lastApplied.removedHashes,
|
|
417
|
+
}, undefined, true, recomputed, emptyRetired));
|
|
418
|
+
}
|
|
358
419
|
await retireAnchors(opts.sessionKey, absolutePath, newlyRetired);
|
|
359
420
|
}
|
|
360
421
|
if (hadUtf8DecodeErrors) {
|
package/lib/mutation.js
CHANGED
|
@@ -57,7 +57,7 @@ export async function execPipeline(io, params, cwd, options) {
|
|
|
57
57
|
abortIf(signal);
|
|
58
58
|
const absolutePath = await io.resolve(path, cwd, signal);
|
|
59
59
|
const sessionKeyEarly = options?.sessionKey ?? sessionKeyFor(undefined);
|
|
60
|
-
const
|
|
60
|
+
const perSessionRetiredForNorm = await loadRetiredAnchors(sessionKeyEarly, absolutePath);
|
|
61
61
|
const rawText = await io.readText(absolutePath, signal);
|
|
62
62
|
const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
|
|
63
63
|
absolutePath,
|
|
@@ -67,8 +67,8 @@ export async function execPipeline(io, params, cwd, options) {
|
|
|
67
67
|
maxLines: MAX_HASH_LINES,
|
|
68
68
|
store: hashStore,
|
|
69
69
|
noPersist: options?.noPersist,
|
|
70
|
-
reservedHashes:
|
|
71
|
-
retiredHashes:
|
|
70
|
+
reservedHashes: perSessionRetiredForNorm,
|
|
71
|
+
retiredHashes: perSessionRetiredForNorm,
|
|
72
72
|
});
|
|
73
73
|
const sessionKey = options?.sessionKey ?? sessionKeyFor(undefined);
|
|
74
74
|
const served = await loadServed(sessionKey, absolutePath);
|
|
@@ -79,8 +79,8 @@ export async function execPipeline(io, params, cwd, options) {
|
|
|
79
79
|
curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
|
|
80
80
|
}
|
|
81
81
|
catch { }
|
|
82
|
-
const strictPos =
|
|
83
|
-
const
|
|
82
|
+
const strictPos = epochSnapshotId !== undefined && curSnapshotId !== undefined && epochSnapshotId !== curSnapshotId; // automatic: strict when epoch mismatch (conservative, future: changed∩[L,R] refined)
|
|
83
|
+
const retiredPerSession = await loadRetiredAnchors(sessionKey, absolutePath);
|
|
84
84
|
const policy = options?.noPersist === true ? 'preview' : 'live';
|
|
85
85
|
const applied = await applyOne({
|
|
86
86
|
content: originalNormalized,
|
|
@@ -95,9 +95,9 @@ export async function execPipeline(io, params, cwd, options) {
|
|
|
95
95
|
warnings: editWarnings,
|
|
96
96
|
store: hashStore,
|
|
97
97
|
persist: options?.noPersist !== true,
|
|
98
|
-
reservedHashes:
|
|
98
|
+
reservedHashes: perSessionRetiredForNorm,
|
|
99
99
|
servedCanons,
|
|
100
|
-
|
|
100
|
+
retired: retiredPerSession,
|
|
101
101
|
epochSnapshotId,
|
|
102
102
|
curSnapshotId,
|
|
103
103
|
strictPos,
|
|
@@ -274,7 +274,7 @@ export async function execute(opts) {
|
|
|
274
274
|
if (built.details.servedRows && built.details.servedRows.length > 0) {
|
|
275
275
|
const entry = built.details.servedByPath?.[0];
|
|
276
276
|
if (entry) {
|
|
277
|
-
await recordServedTruncated(sessionKey, fileResult.absolutePath, entry.servedRows, splitLines(fileResult.result).length, fileResult.range.startLine - 1);
|
|
277
|
+
await recordServedTruncated(sessionKey, fileResult.absolutePath, entry.servedRows, splitLines(fileResult.result).length, fileResult.range.startLine - 1, splitLines(fileResult.result).map((l) => canon(l)));
|
|
278
278
|
}
|
|
279
279
|
}
|
|
280
280
|
};
|
package/lib/prompts.js
CHANGED
|
@@ -7,12 +7,10 @@
|
|
|
7
7
|
* @module dsh-better-edit/prompts
|
|
8
8
|
*/
|
|
9
9
|
export const EDIT_DESCRIPTION = "Edit a range of lines in a text file with `{ \"path\": path, \"edits\": [[remove_from, remove_to, replacement_text], ...] }`. " +
|
|
10
|
-
"`path` is
|
|
11
|
-
"`remove_from`/`remove_to`
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"`{\"path\":\"scrape.py\",\"edits\":[[\"wUp\",\"AU6\",\" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\"]]}`. " +
|
|
15
|
-
"Edits in one call apply atomically; after success reuse `HASH\u2502content` from the returned diff for the next edit (no re-read needed). On failure follow the error hint.";
|
|
10
|
+
"`path` is file path or null. `read` shows `HASH\u2502content` (e.g. `wUp\u2502 \"site\": {`) \u2014 use bare 3-char HASH anchors for " +
|
|
11
|
+
"`remove_from`/`remove_to` (e.g. \"wUp\"), never `HASH\u2502content`. `replacement_text` is bare content, \\n joins lines, \"\" deletes. " +
|
|
12
|
+
"Example: `{\"path\":\"a.py\",\"edits\":[[\"wUp\",\"AU6\",\"new\"]]}`. Edits are atomic; reuse `HASH\u2502content` from the diff after success. " +
|
|
13
|
+
"On failure follow the error hint: `[MODEL]` errors need a retry with fresh anchors, `[USER]` notices are human-only.";
|
|
16
14
|
export const EDIT_GUIDANCE = {
|
|
17
15
|
intro: "Edit a range of lines via a bare 3-char HASH anchor \u2014 payload is { path, edits: [[hash,hash,text]] } (single-file atomic, null path infers).",
|
|
18
16
|
lines: [
|
|
@@ -22,6 +20,8 @@ export const EDIT_GUIDANCE = {
|
|
|
22
20
|
"`edit`: every `\\n` in `replacement_text` separates lines; mirror trailing blank lines explicitly (use \"\" to delete a range).",
|
|
23
21
|
"`edit`: after a successful edit the returned diff shows fresh anchors (`HASH\u2502content`) \u2014 copy new `HASH` values from there for the next edit; no need to re-read.",
|
|
24
22
|
"`edit`: `remove_from`/`remove_to` are inclusive; batch multiple edits to the same file only when independent \u2014 they apply atomically (fail \u2192 nothing written).",
|
|
23
|
+
"`edit`: `[MODEL]` errors (e.g. `E_STALE_*`, `E_UNSERVED_*`, `E_BAD_PAYLOAD`, `E_SERVED_ECHO`) need a retry \u2014 `[USER]` warnings/`drift:` notices are human-only.",
|
|
24
|
+
"`edit`: on `E_STALE_RANGE`/`E_UNSERVED_RANGE` retry from the echoed fresh anchors (no re-read needed); on `E_STALE_ANCHOR` re-read.",
|
|
25
25
|
],
|
|
26
26
|
};
|
|
27
27
|
export const READ_DESCRIPTION = "Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. " +
|
package/lib/read-and-serve.js
CHANGED
|
@@ -12,7 +12,9 @@ import { readView, fileSnap } from "./file-view.js";
|
|
|
12
12
|
import { canon } from "./hashline/hash-assign.js";
|
|
13
13
|
import { splitLines } from "./utils.js";
|
|
14
14
|
import { getAutoGuessFooter } from "./fs-bridge.js";
|
|
15
|
-
import {
|
|
15
|
+
import { AnchorSpaceExhaustedError, HASH_SPACE } from "./hashline/hash-assign.js";
|
|
16
|
+
import { recordServed, clearDriftReported, loadRetiredAnchors, loadServed, loadServedCanons, loadEpochSnapshotId, } from "./session-view.js";
|
|
17
|
+
import { loadServedStore } from "./hash-store.js";
|
|
16
18
|
/** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
|
|
17
19
|
export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
|
|
18
20
|
/**
|
|
@@ -29,18 +31,79 @@ export async function readAndServe(io, rawPath, cwd, options) {
|
|
|
29
31
|
const { sessionKey, signal } = options;
|
|
30
32
|
abortIf(signal);
|
|
31
33
|
const absolutePath = await io.resolve(rawPath, cwd, signal);
|
|
32
|
-
|
|
34
|
+
let retiredHashes = await loadRetiredAnchors(sessionKey, absolutePath);
|
|
33
35
|
const servedForNorm = await loadServed(sessionKey, absolutePath);
|
|
34
|
-
const
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
36
|
+
const servedCanons = await loadServedCanons(sessionKey, absolutePath);
|
|
37
|
+
const epochSnapshotId = await loadEpochSnapshotId(sessionKey, absolutePath);
|
|
38
|
+
// Build previous for stable reuse (S): served filtered + canons reconstruction
|
|
39
|
+
let previous;
|
|
40
|
+
if (servedForNorm.some((h) => h !== null)) {
|
|
41
|
+
const filteredHashes = [];
|
|
42
|
+
const filteredCanons = [];
|
|
43
|
+
for (let i = 0; i < servedForNorm.length; i++) {
|
|
44
|
+
const h = servedForNorm[i];
|
|
45
|
+
if (h !== null) {
|
|
46
|
+
filteredHashes.push(h);
|
|
47
|
+
filteredCanons.push(servedCanons[i] ?? "");
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (filteredHashes.length > 0) {
|
|
51
|
+
// Reconstruct previous content from canons — canon is idempotent and whitespace-insensitive (ADR-0002: canon strips ASCII whitespace, so "a b" and "a b" share canon and hash). Joining filteredCanons preserves reuse correctness for mapStableHashes nearest-canon matching; byte-fidelity of whitespace is not required for anchor stability, only canon equality.
|
|
52
|
+
const prevContent = filteredCanons.join("\n");
|
|
53
|
+
previous = { content: prevContent, hashes: filteredHashes, removedHashes: new Set(retiredHashes) };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
let reservedHashes = new Set([...retiredHashes, ...servedForNorm.filter((h) => h !== null)]);
|
|
57
|
+
let reservations = { reservedHashes, retiredHashes };
|
|
58
|
+
let promotionWarning;
|
|
59
|
+
let view;
|
|
60
|
+
try {
|
|
61
|
+
view = await readView(io, rawPath, cwd, {
|
|
62
|
+
encoding: options.encoding,
|
|
63
|
+
offset: options.offset,
|
|
64
|
+
limit: options.limit,
|
|
65
|
+
signal,
|
|
66
|
+
reservedHashes: reservations.reservedHashes,
|
|
67
|
+
retiredHashes: reservations.retiredHashes,
|
|
68
|
+
previous,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
catch (e) {
|
|
72
|
+
if (e instanceof AnchorSpaceExhaustedError || (e instanceof Error && e.message.includes("E_ANCHOR_SPACE_EXHAUSTED"))) {
|
|
73
|
+
const retiredCount = retiredHashes.size;
|
|
74
|
+
const servedCount = servedForNorm.filter((h) => h !== null).length;
|
|
75
|
+
const reservedCount = retiredCount + servedCount;
|
|
76
|
+
// Major GC promotion: clear retired for this (session,path), keep served/canons
|
|
77
|
+
try {
|
|
78
|
+
const store = await loadServedStore();
|
|
79
|
+
store.clearRetiredAnchors(sessionKey, absolutePath);
|
|
80
|
+
try {
|
|
81
|
+
store.clearCards(sessionKey, absolutePath);
|
|
82
|
+
}
|
|
83
|
+
catch { }
|
|
84
|
+
}
|
|
85
|
+
catch { }
|
|
86
|
+
promotionWarning = `[E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted (retired ${retiredCount} + served ${servedCount} = ${reservedCount} of ${HASH_SPACE}); promotion cleared retired — re-read recommended, stale-anchor checks degraded until next full read.`;
|
|
87
|
+
// Retry ignoring retired (served only) — also drop removedHashes from previous
|
|
88
|
+
retiredHashes = new Set();
|
|
89
|
+
reservedHashes = new Set([...servedForNorm.filter((h) => h !== null)]);
|
|
90
|
+
reservations = { reservedHashes, retiredHashes };
|
|
91
|
+
if (previous)
|
|
92
|
+
previous = { content: previous.content, hashes: previous.hashes };
|
|
93
|
+
view = await readView(io, rawPath, cwd, {
|
|
94
|
+
encoding: options.encoding,
|
|
95
|
+
offset: options.offset,
|
|
96
|
+
limit: options.limit,
|
|
97
|
+
signal,
|
|
98
|
+
reservedHashes: reservations.reservedHashes,
|
|
99
|
+
retiredHashes: reservations.retiredHashes,
|
|
100
|
+
previous,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
throw e;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
44
107
|
if (view.served.length > 0) {
|
|
45
108
|
const canons = splitLines(view.normalized).map((l) => canon(l));
|
|
46
109
|
const canonServed = canons.map((canonText) => canonText);
|
|
@@ -55,11 +118,23 @@ export async function readAndServe(io, rawPath, cwd, options) {
|
|
|
55
118
|
for (let i = 0; i < view.hashes.length; i++) {
|
|
56
119
|
fullCanons.push(canons[i] ?? null);
|
|
57
120
|
}
|
|
58
|
-
await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length,
|
|
121
|
+
await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length, {
|
|
122
|
+
hashes: view.hashes,
|
|
123
|
+
canons: fullCanons,
|
|
124
|
+
snapshotId,
|
|
125
|
+
});
|
|
59
126
|
}
|
|
60
|
-
|
|
127
|
+
// #69: epoch lifecycle belongs to full reads — a partial (paged or
|
|
128
|
+
// truncated) read merges window rows only and must not clear the
|
|
129
|
+
// drift-reported marks; only a full read resets them.
|
|
130
|
+
const isFullRead = options.offset === undefined &&
|
|
131
|
+
options.limit === undefined &&
|
|
132
|
+
!view.truncation?.truncated;
|
|
133
|
+
if (isFullRead)
|
|
134
|
+
await clearDriftReported(sessionKey, view.absolutePath);
|
|
61
135
|
const autoFooter = getAutoGuessFooter(view.absolutePath) ?? getAutoGuessFooter(rawPath) ?? getAutoGuessFooter(view.absolutePath.replace(/\\/g, "/")) ?? "";
|
|
62
|
-
const
|
|
136
|
+
const autoWarning = autoFooter || undefined;
|
|
137
|
+
const warning = promotionWarning ? (autoWarning ? `${promotionWarning}\n${autoWarning}` : promotionWarning) : autoWarning;
|
|
63
138
|
const text = view.hadUtf8DecodeErrors
|
|
64
139
|
? `${view.text}\n\n${UTF8_REWRITE_NOTE}`
|
|
65
140
|
: view.text;
|
package/lib/self-heal.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-healing watcher for hash-anchored tools.
|
|
3
|
+
* Restores `read`/`edit` on the agent's own scope layer if an external
|
|
4
|
+
* preset deletes them (e.g. router-standard stage advance).
|
|
5
|
+
* See Rianico/dsh-better-edit#43.
|
|
6
|
+
* @module dsh-better-edit/self-heal
|
|
7
|
+
*/
|
|
8
|
+
export function createSelfHealWatcher(options) {
|
|
9
|
+
const { agentId, rootCtx, agent, agentCtx, toolsSvc, hashReadDef, hashEditDef, healMinIntervalMs = 1000, } = options;
|
|
10
|
+
let lastHealAt = 0;
|
|
11
|
+
let healCount = 0;
|
|
12
|
+
let selfHealDisabled = false;
|
|
13
|
+
const stop = agentCtx.on("tools/change", () => {
|
|
14
|
+
try {
|
|
15
|
+
if (selfHealDisabled)
|
|
16
|
+
return;
|
|
17
|
+
// SAFETY: toolsSvc is the DSH tools service — shape is `layers.scoped: Map<agent, {tools}>` per cordis internals; narrow at boundary
|
|
18
|
+
const layer = toolsSvc
|
|
19
|
+
?.layers?.scoped?.get?.(agent)?.tools;
|
|
20
|
+
if (!layer)
|
|
21
|
+
return;
|
|
22
|
+
const currentRead = layer?.get?.("read") ?? layer?.data?.get?.("read");
|
|
23
|
+
const currentEdit = layer?.get?.("edit") ?? layer?.data?.get?.("edit");
|
|
24
|
+
const readOk = currentRead === hashReadDef;
|
|
25
|
+
const editOk = currentEdit === hashEditDef;
|
|
26
|
+
if (readOk && editOk)
|
|
27
|
+
return;
|
|
28
|
+
const now = Date.now();
|
|
29
|
+
if (now - lastHealAt < healMinIntervalMs)
|
|
30
|
+
return;
|
|
31
|
+
if (healCount >= 2) {
|
|
32
|
+
selfHealDisabled = true;
|
|
33
|
+
try {
|
|
34
|
+
rootCtx.logger.error(`dsh-better-edit: repeated takeover of edit detected; self-heal disabled for agent ${agentId} \u2014 edit will remain built-in for this session \u2014 see Rianico/dsh-better-edit#43`);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// ignore — logger may throw in mock
|
|
38
|
+
}
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
healCount++;
|
|
42
|
+
lastHealAt = now;
|
|
43
|
+
const restoreRead = !readOk;
|
|
44
|
+
const restoreEdit = !editOk;
|
|
45
|
+
const restoreCount = healCount;
|
|
46
|
+
queueMicrotask(() => {
|
|
47
|
+
try {
|
|
48
|
+
// SAFETY: re-read layer inside microtask — same shape as above
|
|
49
|
+
const currentLayer = toolsSvc
|
|
50
|
+
?.layers?.scoped?.get?.(agent)?.tools;
|
|
51
|
+
if (!currentLayer)
|
|
52
|
+
return;
|
|
53
|
+
if (restoreEdit) {
|
|
54
|
+
try {
|
|
55
|
+
currentLayer?.data?.delete?.("edit");
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// ignore — best-effort delete of intruding entry
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
agentCtx.tools.register(hashEditDef);
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${e instanceof Error ? e.message : String(e)} \u2014 see Rianico/dsh-better-edit#43`);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
rootCtx.logger.warn(`dsh-better-edit: restored hash-anchored edit after external takeover \u2014 agent ${agentId} (${restoreCount}/2) \u2014 see Rianico/dsh-better-edit#43`);
|
|
68
|
+
}
|
|
69
|
+
if (restoreRead) {
|
|
70
|
+
try {
|
|
71
|
+
currentLayer?.data?.delete?.("read");
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// ignore — best-effort delete of intruding entry
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
agentCtx.tools.register(hashReadDef);
|
|
78
|
+
}
|
|
79
|
+
catch (e) {
|
|
80
|
+
rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${e instanceof Error ? e.message : String(e)} \u2014 see Rianico/dsh-better-edit#43`);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
rootCtx.logger.warn(`dsh-better-edit: restored hash-anchored read after external takeover \u2014 agent ${agentId} (${restoreCount}/2) \u2014 see Rianico/dsh-better-edit#43`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${error instanceof Error ? error.message : String(error)} \u2014 see Rianico/dsh-better-edit#43`);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
try {
|
|
93
|
+
rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${error instanceof Error ? error.message : String(error)} \u2014 see Rianico/dsh-better-edit#43`);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
// ignore — logger may throw in mock
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
return stop;
|
|
101
|
+
}
|