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.
@@ -48,9 +48,23 @@ export const HASH_RE = new RegExp(`^${HASH_CLASS}$`);
48
48
  export const ANCHOR_LEN = HASH_LEN;
49
49
  export const HASH_SEP = "│";
50
50
  export const HASH_SPACE = ALPH.length ** HASH_LEN;
51
+ // MAX_HASH_LINES is the anchor-space size (62³), not a line-count limit.
52
+ // File line-count limits use maxLines (e.g. 200k) and report E_LARGE_FILE;
53
+ // anchor-space exhaustion reports E_ANCHOR_SPACE_EXHAUSTED — see nextZeroBit.
51
54
  export const MAX_HASH_LINES = HASH_SPACE;
52
55
  export const HASH_PROBE_STRIDE = ALPH.length ** 2 + ALPH.length + 1;
53
- function idxToHash(idx) {
56
+ export class AnchorSpaceExhaustedError extends Error {
57
+ code = "E_ANCHOR_SPACE_EXHAUSTED";
58
+ retiredCount;
59
+ servedCount;
60
+ constructor(retiredCount, servedCount, reservedCount) {
61
+ super(`[MODEL] [E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted (retired ${retiredCount} + served ${servedCount} = ${reservedCount} of ${HASH_SPACE}); promotion will clear retired — re-read recommended, stale-anchor checks degraded until next full read.`);
62
+ this.name = "AnchorSpaceExhaustedError";
63
+ this.retiredCount = retiredCount;
64
+ this.servedCount = servedCount;
65
+ }
66
+ }
67
+ export function idxToHash(idx) {
54
68
  let out = "";
55
69
  for (let j = 0; j < HASH_LEN; j++) {
56
70
  out = ALPH[idx % ALPH.length] + out;
@@ -59,7 +73,7 @@ function idxToHash(idx) {
59
73
  return out;
60
74
  }
61
75
  const hashCache = new Map();
62
- function hashAt(idx) {
76
+ export function hashAt(idx) {
63
77
  let hash = hashCache.get(idx);
64
78
  if (hash === undefined) {
65
79
  hash = idxToHash(idx);
@@ -108,7 +122,7 @@ function nextZeroBit(bits, start) {
108
122
  if (idx >= totalBits)
109
123
  idx -= totalBits;
110
124
  }
111
- throw new Error(`[E_FILE_TOO_LARGE] Cannot allocate a unique hash anchor: the file exceeds the ${HASH_SPACE}-line limit for ${HASH_LEN}-char hashline anchors.`);
125
+ throw new Error(`[MODEL] [E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted — probing failed over ${HASH_SPACE} slots (reserved full).`);
112
126
  }
113
127
  function assignHash(used, baseIdx, hint) {
114
128
  if (!getBit(used, baseIdx)) {
@@ -121,7 +135,9 @@ function assignHash(used, baseIdx, hint) {
121
135
  hint.value = nextIdx + HASH_PROBE_STRIDE;
122
136
  return hashAt(nextIdx);
123
137
  }
124
- export function lineHashesPure(content, reservedHashes = new Set()) {
138
+ export function lineHashesPure(content, reservedHashes = new Set(),
139
+ // optional counts for richer error — when caller knows retired vs served split
140
+ retiredCount, servedCount) {
125
141
  const lines = splitLines(content);
126
142
  const hashes = new Array(lines.length);
127
143
  const used = new Uint32Array(BITSET_WORDS);
@@ -129,12 +145,24 @@ export function lineHashesPure(content, reservedHashes = new Set()) {
129
145
  markHashUsed(used, hash);
130
146
  const hint = { value: 0 };
131
147
  const canonCache = new Map();
132
- for (let i = 0; i < lines.length; i++) {
133
- const c = getCanon(canonCache, lines[i]);
134
- const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
135
- const h = assignHash(used, baseIdx, hint);
136
- hashes[i] = h;
137
- rememberHashCanon(h, c);
148
+ try {
149
+ for (let i = 0; i < lines.length; i++) {
150
+ const c = getCanon(canonCache, lines[i]);
151
+ const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
152
+ const h = assignHash(used, baseIdx, hint);
153
+ hashes[i] = h;
154
+ rememberHashCanon(h, c);
155
+ }
156
+ }
157
+ catch (e) {
158
+ const msg = e instanceof Error ? e.message : String(e);
159
+ if (msg.includes("E_ANCHOR_SPACE_EXHAUSTED") || msg.includes("Cannot allocate")) {
160
+ const rc = retiredCount ?? reservedHashes.size;
161
+ const sc = servedCount ?? 0;
162
+ const reserved = reservedHashes.size;
163
+ throw new AnchorSpaceExhaustedError(rc, sc, reserved);
164
+ }
165
+ throw e;
138
166
  }
139
167
  return hashes;
140
168
  }
@@ -165,7 +193,7 @@ function nearestNew(candidates, target) {
165
193
  }
166
194
  return right < candidates.length ? right : -1;
167
195
  }
168
- export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes, reservedHashes = new Set()) {
196
+ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes, reservedHashes = new Set(), retiredCount, servedCount) {
169
197
  const oldLines = splitLines(oldContent);
170
198
  const newLines = splitLines(newContent);
171
199
  const newHashes = new Array(newLines.length);
@@ -239,14 +267,25 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
239
267
  markUsed(entry.hash);
240
268
  rememberHashCanon(entry.hash, getCanon(canonCache, oldLines[entry.index]));
241
269
  }
242
- for (let i = 0; i < newLines.length; i++) {
243
- if (newHashes[i])
244
- continue;
245
- const c = getCanon(canonCache, newLines[i]);
246
- const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
247
- const h = assignHash(used, baseIdx, hint);
248
- newHashes[i] = h;
249
- rememberHashCanon(h, c);
270
+ try {
271
+ for (let i = 0; i < newLines.length; i++) {
272
+ if (newHashes[i])
273
+ continue;
274
+ const c = getCanon(canonCache, newLines[i]);
275
+ const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
276
+ const h = assignHash(used, baseIdx, hint);
277
+ newHashes[i] = h;
278
+ rememberHashCanon(h, c);
279
+ }
280
+ }
281
+ catch (e) {
282
+ const msg = e instanceof Error ? e.message : String(e);
283
+ if (msg.includes("E_ANCHOR_SPACE_EXHAUSTED")) {
284
+ const rc = retiredCount ?? reservedHashes.size;
285
+ const sc = servedCount ?? 0;
286
+ throw new AnchorSpaceExhaustedError(rc, sc, reservedHashes.size);
287
+ }
288
+ throw e;
250
289
  }
251
290
  return newHashes;
252
291
  }
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { splitLines } from "../utils.js";
11
11
  import { loadHashStore } from "../hash-store.js";
12
- import { contentChecksum, initHasher, HASH_RE } from "./hash-assign.js";
12
+ import { contentChecksum, initHasher, HASH_RE, AnchorSpaceExhaustedError } from "./hash-assign.js";
13
13
  import { lineHashesPure, mapStableHashes } from "./hash-assign.js";
14
14
  let defaultHashSnapshotIO;
15
15
  export function setDefaultHashSnapshotIO(io) {
@@ -54,7 +54,7 @@ export async function lineHashes(content, path, previous, ioOrStore, persist, re
54
54
  ? snapshotIOFor(ioOrStore)
55
55
  : ioOrStore ?? snapshotIOFor(undefined);
56
56
  if (previous) {
57
- const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes, reservedHashes);
57
+ const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes, reservedHashes, retiredHashes.size, previous.hashes.length);
58
58
  if (persist !== false && io) {
59
59
  try {
60
60
  await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
@@ -76,7 +76,7 @@ export async function lineHashes(content, path, previous, ioOrStore, persist, re
76
76
  }
77
77
  if (cached && !cached.some((hash) => retiredHashes.has(hash)))
78
78
  return cached;
79
- const newHashes = lineHashesPure(content, reservedHashes);
79
+ const newHashes = lineHashesPure(content, reservedHashes, retiredHashes.size, 0);
80
80
  if (persist !== false && io) {
81
81
  try {
82
82
  await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
@@ -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: `[E_BAD_SHAPE] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
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(`[E_BAD_SHAPE] Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(', ')}. Include the intended path.`);
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, input.tombstone, input.epochSnapshotId, input.curSnapshotId, input.strictPos);
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 resultHashes = noop
142
- ? input.hashes
143
- : await lineHashes(result, input.absolutePath, {
144
- content: input.content,
145
- hashes: input.hashes,
146
- removedHashes,
147
- }, input.store, input.persist, input.reservedHashes);
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 perSessionTombstone = await loadRetiredAnchors(opts.sessionKey, absolutePath);
222
- const reservedHashes = new Set(perSessionTombstone);
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: perSessionTombstone,
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 = false; // automatic resist: pos-free for exterior shift, strict via tombstone+canon for whole-span rebind
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
- tombstone: new Set([...perSessionTombstone, ...Array.from(newlyRetired)]),
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
- resultHashes = await lineHashes(result, absolutePath, {
354
- content: lastApplied.content,
355
- hashes: lastApplied.hashes,
356
- removedHashes: lastApplied.removedHashes,
357
- }, undefined, true, reservedHashes, perSessionTombstone);
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 perSessionTombstoneForNorm = await loadRetiredAnchors(sessionKeyEarly, absolutePath);
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: perSessionTombstoneForNorm,
71
- retiredHashes: perSessionTombstoneForNorm,
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 = false; // automatic resist: pos-free for exterior shift, strict via tombstone+canon (changed ∩ [L,R] handled by tombstone interior gated on canon)
83
- const tombstonePerSession = await loadRetiredAnchors(sessionKey, absolutePath);
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: perSessionTombstoneForNorm,
98
+ reservedHashes: perSessionRetiredForNorm,
99
99
  servedCanons,
100
- tombstone: tombstonePerSession,
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 the file path or `null`. `read` returns `HASH\u2502content` (e.g. `wUp\u2502 \"site\": {`) \u2014 for `edit`, " +
11
- "`remove_from`/`remove_to` are HASH anchors (bare 3-char value before `\u2502`, e.g. \"wUp\", \"AU6\"), never `HASH\u2502content` or line content. " +
12
- "`replacement_text` is bare content without `HASH\u2502`, lines joined by \\n (e.g. \" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\"); use \"\" to delete. " +
13
- "Example: read shows `wUp\u2502 \"site\": {` + `AU6\u2502 \"name\": \"old\",` \u2192 edit " +
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. " +
@@ -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 { recordServed, clearDriftReported, loadRetiredAnchors, loadServed, } from "./session-view.js";
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
- const retiredHashes = await loadRetiredAnchors(sessionKey, absolutePath);
34
+ let retiredHashes = await loadRetiredAnchors(sessionKey, absolutePath);
33
35
  const servedForNorm = await loadServed(sessionKey, absolutePath);
34
- const reservedHashes = new Set([...retiredHashes, ...servedForNorm.filter((h) => h !== null)]);
35
- const reservations = { reservedHashes, retiredHashes };
36
- const view = await readView(io, rawPath, cwd, {
37
- encoding: options.encoding,
38
- offset: options.offset,
39
- limit: options.limit,
40
- signal,
41
- reservedHashes: reservations.reservedHashes,
42
- retiredHashes: reservations.retiredHashes,
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, view.hashes, fullCanons, snapshotId);
121
+ await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length, {
122
+ hashes: view.hashes,
123
+ canons: fullCanons,
124
+ snapshotId,
125
+ });
59
126
  }
60
- await clearDriftReported(sessionKey, view.absolutePath);
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 warning = autoFooter || undefined;
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;