dsh-better-edit 0.6.0 → 0.6.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 CHANGED
@@ -1,3 +1,22 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.6.1] - 2026-09-01
4
+
5
+ ### Fixed
6
+
7
+ - **hashline:** eliminate remaining P2s for zero-issue review
8
+ - **hashline:** make read path per-session reserved for ADR-0013
9
+ - **hashline:** polish P2s for ADR-0013 automatic fallback
10
+ - **hashline:** implement per-session tombstone and epoch-aware strict pos
11
+ - **hashline:** add per-session canons, epoch and strict pos for ADR-0013
12
+ - **hashline:** prevent freed anchor reuse (#31)
13
+
14
+ ### Documentation
15
+
16
+ - **adr:** clarify single vs multi-session pos-free trade-off
17
+ - **adr:** refine ADR-0013 to automatic fallback (no config)
18
+ - **adr:** add ADR-0013 pos-free roundtrip with concurrency fallback (#31)
19
+
1
20
  ## [0.6.0](https://github.com/Rianico/dsh-better-edit/compare/v0.5.1...v0.6.0) (2026-08-31)
2
21
 
3
22
  ### Features
package/lib/file-view.js CHANGED
@@ -290,7 +290,7 @@ export async function normFromText(input) {
290
290
  throw new Error(`[E_FILE_TOO_LARGE] ${displayPath} has ${lineCount} lines, exceeding the ${input.maxLines}-line edit limit. Hashline editing targets source-sized files; for very large files use write or a non-line-based approach.`);
291
291
  }
292
292
  }
293
- const fileHashes = await lineHashes(normalized, absolutePath, undefined, input.store, input.noPersist !== true);
293
+ const fileHashes = await lineHashes(normalized, absolutePath, undefined, input.store, input.noPersist !== true, input.reservedHashes, input.retiredHashes);
294
294
  return {
295
295
  absolutePath,
296
296
  normalized,
@@ -322,6 +322,8 @@ export async function readNormFile(path, cwd, options) {
322
322
  maxLines: options?.maxLines,
323
323
  store: options?.store,
324
324
  noPersist: options?.noPersist,
325
+ reservedHashes: options?.reservedHashes,
326
+ retiredHashes: options?.retiredHashes,
325
327
  hadUtf8DecodeErrors: file.hadUtf8DecodeErrors,
326
328
  });
327
329
  }
@@ -469,6 +471,8 @@ export async function readView(io, path, cwd, opts = {}) {
469
471
  displayPath: path,
470
472
  signal,
471
473
  maxLines: MAX_HASH_LINES,
474
+ reservedHashes: opts.reservedHashes,
475
+ retiredHashes: opts.retiredHashes,
472
476
  });
473
477
  const r = await fmtReadPreview(normalized, { offset: opts.offset, limit: opts.limit }, fileHashes, absolutePath);
474
478
  return {
package/lib/hash-store.js CHANGED
@@ -41,6 +41,17 @@ export function isValidSnapshot(value) {
41
41
  return isValidHashList(v.hashes);
42
42
  }
43
43
  /** A served-row array: per-position hash, or null for never-served slots. */
44
+ export function isValidCanonsList(value) {
45
+ if (!Array.isArray(value))
46
+ return false;
47
+ for (const entry of value) {
48
+ if (entry === null)
49
+ continue;
50
+ if (typeof entry !== "string")
51
+ return false;
52
+ }
53
+ return true;
54
+ }
44
55
  export function isValidServedList(value) {
45
56
  if (!Array.isArray(value))
46
57
  return false;
@@ -168,9 +179,52 @@ function buildStore(db) {
168
179
  "path TEXT NOT NULL, " +
169
180
  "hashes TEXT NOT NULL, " +
170
181
  "reported TEXT, " +
182
+ "retired TEXT, " +
183
+ "canons TEXT, " +
184
+ "snapshotId TEXT, " +
171
185
  "updated_at INTEGER NOT NULL, " +
172
186
  "PRIMARY KEY (session_id, path)" +
173
187
  ")");
188
+ const currentServedColumns = db.prepare("PRAGMA table_info(served)").all();
189
+ if (!currentServedColumns.some((column) => column.name === "retired")) {
190
+ let migrationOpen = false;
191
+ try {
192
+ db.exec("BEGIN IMMEDIATE");
193
+ migrationOpen = true;
194
+ const migrationColumns = db
195
+ .prepare("PRAGMA table_info(served)")
196
+ .all();
197
+ if (!migrationColumns.some((column) => column.name === "retired")) {
198
+ db.exec("ALTER TABLE served ADD COLUMN retired TEXT");
199
+ // Pre-fix snapshots and undo entries may already bind a remembered
200
+ // anchor to the wrong position. Preserve served rows, but rebuild
201
+ // every source that could restore the rebound anchor.
202
+ db.exec("DELETE FROM snapshots");
203
+ db.exec("DELETE FROM undo");
204
+ }
205
+ db.exec("COMMIT");
206
+ migrationOpen = false;
207
+ }
208
+ catch (error) {
209
+ if (migrationOpen) {
210
+ try {
211
+ db.exec("ROLLBACK");
212
+ }
213
+ catch (rollbackError) {
214
+ console.warn(rollbackError);
215
+ }
216
+ }
217
+ throw error;
218
+ }
219
+ }
220
+ const canonsColumns = db.prepare("PRAGMA table_info(served)").all();
221
+ if (!canonsColumns.some((column) => column.name === "canons")) {
222
+ db.exec("ALTER TABLE served ADD COLUMN canons TEXT");
223
+ }
224
+ const snapshotColumns = db.prepare("PRAGMA table_info(served)").all();
225
+ if (!snapshotColumns.some((column) => column.name === "snapshotId")) {
226
+ db.exec("ALTER TABLE served ADD COLUMN snapshotId TEXT");
227
+ }
174
228
  db
175
229
  .prepare("INSERT INTO meta (key, value) VALUES ('version', ?) " +
176
230
  "ON CONFLICT(key) DO UPDATE SET value = excluded.value")
@@ -186,12 +240,22 @@ function buildStore(db) {
186
240
  const undoGetStmt = db.prepare("SELECT content, bom, ending, hashes, result_content FROM undo WHERE path = ?");
187
241
  const undoDelStmt = db.prepare("DELETE FROM undo WHERE path = ?");
188
242
  const undoPruneOlderThanStmt = db.prepare("DELETE FROM undo WHERE updated_at < ?");
189
- const servedGetStmt = db.prepare("SELECT hashes, reported FROM served WHERE session_id = ? AND path = ?");
243
+ const servedGetStmt = db.prepare("SELECT hashes, reported, retired, canons, snapshotId FROM served WHERE session_id = ? AND path = ?");
244
+ const servedAllForPathStmt = db.prepare("SELECT session_id, hashes, retired FROM served WHERE path = ?");
190
245
  const servedUpsertStmt = db.prepare("INSERT INTO served (session_id, path, hashes, updated_at) VALUES (?, ?, ?, ?) " +
191
246
  "ON CONFLICT(session_id, path) DO UPDATE SET hashes = excluded.hashes, updated_at = excluded.updated_at");
192
247
  const servedReportedUpsertStmt = db.prepare("INSERT INTO served (session_id, path, hashes, reported, updated_at) VALUES (?, ?, '[]', ?, ?) " +
193
248
  "ON CONFLICT(session_id, path) DO UPDATE SET reported = excluded.reported, updated_at = excluded.updated_at");
194
249
  const servedReportedClearStmt = db.prepare("UPDATE served SET reported = NULL, updated_at = ? WHERE session_id = ? AND path = ?");
250
+ const servedRetiredUpsertStmt = db.prepare("INSERT INTO served (session_id, path, hashes, retired, updated_at) VALUES (?, ?, '[]', ?, ?) " +
251
+ "ON CONFLICT(session_id, path) DO UPDATE SET retired = excluded.retired, updated_at = excluded.updated_at");
252
+ const servedRetiredClearStmt = db.prepare("UPDATE served SET retired = NULL, updated_at = ? WHERE session_id = ? AND path = ?");
253
+ const servedCanonsUpsertStmt = db.prepare("INSERT INTO served (session_id, path, hashes, canons, updated_at) VALUES (?, ?, '[]', ?, ?) " +
254
+ "ON CONFLICT(session_id, path) DO UPDATE SET canons = excluded.canons, updated_at = excluded.updated_at");
255
+ const servedCanonsClearStmt = db.prepare("UPDATE served SET canons = NULL, updated_at = ? WHERE session_id = ? AND path = ?");
256
+ const servedSnapshotUpsertStmt = db.prepare("INSERT INTO served (session_id, path, hashes, snapshotId, updated_at) VALUES (?, ?, '[]', ?, ?) " +
257
+ "ON CONFLICT(session_id, path) DO UPDATE SET snapshotId = excluded.snapshotId, updated_at = excluded.updated_at");
258
+ const servedSnapshotClearStmt = db.prepare("UPDATE served SET snapshotId = NULL, updated_at = ? WHERE session_id = ? AND path = ?");
195
259
  const servedDeleteStmt = db.prepare("DELETE FROM served WHERE session_id = ? AND path = ?");
196
260
  const servedDeletePathStmt = db.prepare("DELETE FROM served WHERE path = ?");
197
261
  const servedWipeStmt = db.prepare("DELETE FROM served WHERE session_id = ?");
@@ -227,6 +291,7 @@ function buildStore(db) {
227
291
  });
228
292
  },
229
293
  servedGet: (...params) => servedGetStmt.get(...params),
294
+ servedAllForPath: (...params) => servedAllForPathStmt.all(...params),
230
295
  servedUpsert: (...params) => {
231
296
  withBusyRetry(() => {
232
297
  servedUpsertStmt.run(...params);
@@ -242,6 +307,36 @@ function buildStore(db) {
242
307
  servedReportedClearStmt.run(params[1], params[0], params[2]);
243
308
  });
244
309
  },
310
+ servedRetiredUpsert: (...params) => {
311
+ withBusyRetry(() => {
312
+ servedRetiredUpsertStmt.run(...params);
313
+ });
314
+ },
315
+ servedRetiredClear: (...params) => {
316
+ withBusyRetry(() => {
317
+ servedRetiredClearStmt.run(params[1], params[0], params[2]);
318
+ });
319
+ },
320
+ servedCanonsUpsert: (...params) => {
321
+ withBusyRetry(() => {
322
+ servedCanonsUpsertStmt.run(...params);
323
+ });
324
+ },
325
+ servedCanonsClear: (...params) => {
326
+ withBusyRetry(() => {
327
+ servedCanonsClearStmt.run(params[1], params[0], params[2]);
328
+ });
329
+ },
330
+ servedSnapshotUpsert: (...params) => {
331
+ withBusyRetry(() => {
332
+ servedSnapshotUpsertStmt.run(...params);
333
+ });
334
+ },
335
+ servedSnapshotClear: (...params) => {
336
+ withBusyRetry(() => {
337
+ servedSnapshotClearStmt.run(params[1], params[0], params[2]);
338
+ });
339
+ },
245
340
  servedDelete: (...params) => {
246
341
  withBusyRetry(() => {
247
342
  servedDeleteStmt.run(...params);
@@ -380,6 +475,50 @@ function makeDomainStore(stmts) {
380
475
  return new Set();
381
476
  }
382
477
  },
478
+ getAnchorReservations(path) {
479
+ const reservedHashes = new Set();
480
+ const retiredHashes = new Set();
481
+ for (const row of stmts.servedAllForPath(path)) {
482
+ try {
483
+ const served = JSON.parse(row.hashes);
484
+ const retired = row.retired === null || row.retired === undefined
485
+ ? []
486
+ : JSON.parse(row.retired);
487
+ if (!isValidServedList(served) || !isValidHashList(retired)) {
488
+ throw new TypeError("invalid stored anchor reservations");
489
+ }
490
+ for (const hash of served) {
491
+ if (hash !== null)
492
+ reservedHashes.add(hash);
493
+ }
494
+ for (const hash of retired) {
495
+ reservedHashes.add(hash);
496
+ retiredHashes.add(hash);
497
+ }
498
+ }
499
+ catch (error) {
500
+ stmts.servedDelete(row.session_id, path);
501
+ }
502
+ }
503
+ return { reservedHashes, retiredHashes };
504
+ },
505
+ getRetiredAnchors(sessionKey, path) {
506
+ const row = stmts.servedGet(sessionKey, path);
507
+ if (!row || row.retired === null || row.retired === undefined) {
508
+ return new Set();
509
+ }
510
+ try {
511
+ const parsed = JSON.parse(row.retired);
512
+ if (!isValidHashList(parsed)) {
513
+ throw new TypeError("invalid retired anchors");
514
+ }
515
+ return new Set(parsed);
516
+ }
517
+ catch (error) {
518
+ stmts.servedDelete(sessionKey, path);
519
+ return new Set();
520
+ }
521
+ },
383
522
  upsertServed(sessionKey, path, hashesJson) {
384
523
  stmts.servedUpsert(sessionKey, path, hashesJson, Date.now());
385
524
  },
@@ -389,6 +528,45 @@ function makeDomainStore(stmts) {
389
528
  clearServedReported(sessionKey, path) {
390
529
  stmts.servedReportedClear(sessionKey, Date.now(), path);
391
530
  },
531
+ upsertRetiredAnchors(sessionKey, path, hashesJson) {
532
+ stmts.servedRetiredUpsert(sessionKey, path, hashesJson, Date.now());
533
+ },
534
+ clearRetiredAnchors(sessionKey, path) {
535
+ stmts.servedRetiredClear(sessionKey, Date.now(), path);
536
+ },
537
+ getServedCanons(sessionKey, path) {
538
+ const row = stmts.servedGet(sessionKey, path);
539
+ if (!row || row.canons === null || row.canons === undefined)
540
+ return [];
541
+ try {
542
+ const parsed = JSON.parse(row.canons);
543
+ if (!isValidCanonsList(parsed))
544
+ throw new TypeError("invalid canons");
545
+ return parsed;
546
+ }
547
+ catch {
548
+ stmts.servedDelete(sessionKey, path);
549
+ return [];
550
+ }
551
+ },
552
+ getEpochSnapshotId(sessionKey, path) {
553
+ const row = stmts.servedGet(sessionKey, path);
554
+ if (!row || row.snapshotId === null || row.snapshotId === undefined)
555
+ return undefined;
556
+ return row.snapshotId;
557
+ },
558
+ upsertServedCanons(sessionKey, path, canonsJson) {
559
+ stmts.servedCanonsUpsert(sessionKey, path, canonsJson, Date.now());
560
+ },
561
+ clearServedCanons(sessionKey, path) {
562
+ stmts.servedCanonsClear(sessionKey, Date.now(), path);
563
+ },
564
+ upsertEpochSnapshotId(sessionKey, path, snapshotId) {
565
+ stmts.servedSnapshotUpsert(sessionKey, path, snapshotId, Date.now());
566
+ },
567
+ clearEpochSnapshotId(sessionKey, path) {
568
+ stmts.servedSnapshotClear(sessionKey, Date.now(), path);
569
+ },
392
570
  deleteServed(sessionKey, path) {
393
571
  stmts.servedDelete(sessionKey, path);
394
572
  },
@@ -392,6 +392,11 @@ function paginationHint(nextOffset, more) {
392
392
  export function verifyServedRange(args) {
393
393
  const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath, } = args;
394
394
  const where = filePath ? ` in ${filePath}` : "";
395
+ const tombstone = args.tombstone ?? new Set();
396
+ const servedCanons = args.servedCanons;
397
+ const strictPos = args.strictPos ?? false;
398
+ const epochSnapshotId = args.epochSnapshotId;
399
+ const curSnapshotId = args.curSnapshotId;
395
400
  let isHealed = false;
396
401
  for (let i = 0; i < fileHashes.length; i++) {
397
402
  const h = fileHashes[i];
@@ -412,6 +417,28 @@ export function verifyServedRange(args) {
412
417
  ? `\n${paginationHint(startLine + echoRows.length, totalLen - echoRows.length)}`
413
418
  : "";
414
419
  const echo = fmtServedRows(echoRows, fileLines) + tail;
420
+ // Tombstone check for boundaries (whole-span S@3==S@3)
421
+ // If hash was freed in this epoch, any reuse is stale even at same pos+same canon.
422
+ // Early reject checks canon change to avoid false positive on same line re-read.
423
+ if (tombstone.has(startHash) || tombstone.has(endHash)) {
424
+ const tombstonedHash = tombstone.has(startHash) ? startHash : endHash;
425
+ if (servedCanons) {
426
+ const pos = fileHashes.indexOf(tombstonedHash);
427
+ if (pos >= 0) {
428
+ const servedIdx = served.indexOf(tombstonedHash);
429
+ const expected = servedIdx >= 0 ? servedCanons[servedIdx] : undefined;
430
+ const actual = canon(fileLines[pos] ?? "");
431
+ if (expected !== undefined && expected !== null && expected !== actual) {
432
+ throw new ServedRejectionError({
433
+ code: "E_RANGE_STALE",
434
+ message: `[E_RANGE_STALE] anchor "${tombstonedHash}" was freed since last full read (tombstoned, canon changed from "${expected}" to "${actual}"). Re-read.\nCurrent range:\n${echo}`,
435
+ firstOffendingLine: pos + 1,
436
+ servedRows: echoRows,
437
+ });
438
+ }
439
+ }
440
+ }
441
+ }
415
442
  const startPositions = servedPositionsOf(served, startHash);
416
443
  const endPositions = servedPositionsOf(served, endHash);
417
444
  const currentLen = endLine - startLine + 1;
@@ -650,6 +677,48 @@ export function verifyServedRange(args) {
650
677
  });
651
678
  }
652
679
  }
680
+ // Strict pos check for concurrency (pos-free vs strict)
681
+ if (strictPos && from !== startLine - 1) {
682
+ throw new ServedRejectionError({
683
+ code: "E_RANGE_STALE",
684
+ message: `[E_RANGE_STALE] anchor was served at line ${from + 1} but now resolves to line ${startLine} (pos-restricted concurrency). Re-read.\nCurrent range:\n${echo}`,
685
+ firstOffendingLine: startLine,
686
+ servedRows: echoRows,
687
+ });
688
+ }
689
+ // Canon check for same-pos different content (collision)
690
+ if (servedCanons) {
691
+ for (let k = 0; k < servedLen; k++) {
692
+ const expected = servedCanons[from + k];
693
+ if (expected !== null && expected !== undefined) {
694
+ const actual = canon(fileLines[startLine - 1 + k] ?? "");
695
+ if (expected !== actual) {
696
+ throw new ServedRejectionError({
697
+ code: "E_RANGE_STALE",
698
+ message: `[E_RANGE_STALE] line ${startLine + k}${where} canon differs from served (expected "${expected}" vs actual "${actual}").\nCurrent range:\n${echo}`,
699
+ firstOffendingLine: startLine + k,
700
+ servedRows: echoRows,
701
+ });
702
+ }
703
+ }
704
+ }
705
+ }
706
+ // Tombstone interior check (whole-span) — gated on canon inequality (fail-closed only for different canon)
707
+ for (let k = 0; k < servedLen; k++) {
708
+ const h = fileHashes[startLine - 1 + k];
709
+ if (h && tombstone.has(h)) {
710
+ const expectedCanon = servedCanons?.[from + k] ?? undefined;
711
+ const actualCanon = canon(fileLines[startLine - 1 + k] ?? "");
712
+ if (expectedCanon !== undefined && expectedCanon !== null && expectedCanon !== actualCanon) {
713
+ throw new ServedRejectionError({
714
+ code: "E_RANGE_STALE",
715
+ message: `[E_RANGE_STALE] line ${startLine + k}${where} uses tombstoned anchor "${h}" (freed since last full read, canon changed). Re-read.\nCurrent range:\n${echo}`,
716
+ firstOffendingLine: startLine + k,
717
+ servedRows: echoRows,
718
+ });
719
+ }
720
+ }
721
+ }
653
722
  for (let k = 0; k < servedLen; k++) {
654
723
  if (served[from + k] !== fileHashes[startLine - 1 + k]) {
655
724
  const offendingLine = startLine + k;
@@ -748,7 +817,7 @@ function assemble(content, span, signal) {
748
817
  abortIf(signal);
749
818
  return (content.slice(0, span.start) + span.replacement + content.slice(span.end));
750
819
  }
751
- export function applyEdit(content, edit, signal, precomputedHashes, filePath, served) {
820
+ export function applyEdit(content, edit, signal, precomputedHashes, filePath, served, servedCanons, tombstone, epochSnapshotId, curSnapshotId, strictPos) {
752
821
  abortIf(signal);
753
822
  const lineIndex = buildIdx(content);
754
823
  const fileHashes = precomputedHashes ?? lineHashesPure(content);
@@ -785,6 +854,11 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
785
854
  fileHashes,
786
855
  fileLines: lineIndex.fileLines,
787
856
  filePath,
857
+ servedCanons,
858
+ tombstone,
859
+ epochSnapshotId,
860
+ curSnapshotId,
861
+ strictPos,
788
862
  });
789
863
  }
790
864
  const spanResult = resToSpan(resolved, content, lineIndex);
@@ -121,10 +121,12 @@ function assignHash(used, baseIdx, hint) {
121
121
  hint.value = nextIdx + HASH_PROBE_STRIDE;
122
122
  return hashAt(nextIdx);
123
123
  }
124
- export function lineHashesPure(content) {
124
+ export function lineHashesPure(content, reservedHashes = new Set()) {
125
125
  const lines = splitLines(content);
126
126
  const hashes = new Array(lines.length);
127
127
  const used = new Uint32Array(BITSET_WORDS);
128
+ for (const hash of reservedHashes)
129
+ markHashUsed(used, hash);
128
130
  const hint = { value: 0 };
129
131
  const canonCache = new Map();
130
132
  for (let i = 0; i < lines.length; i++) {
@@ -163,7 +165,7 @@ function nearestNew(candidates, target) {
163
165
  }
164
166
  return right < candidates.length ? right : -1;
165
167
  }
166
- export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes) {
168
+ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes, reservedHashes = new Set()) {
167
169
  const oldLines = splitLines(oldContent);
168
170
  const newLines = splitLines(newContent);
169
171
  const newHashes = new Array(newLines.length);
@@ -171,6 +173,9 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
171
173
  const hint = { value: 0 };
172
174
  const canonCache = new Map();
173
175
  const removed = removedHashes ?? new Set();
176
+ const blocked = new Set(reservedHashes);
177
+ for (const hash of removed)
178
+ blocked.add(hash);
174
179
  const oldHashIndex = new Map();
175
180
  for (let i = 0; i < oldHashes.length; i++) {
176
181
  const hash = oldHashes[i];
@@ -185,6 +190,8 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
185
190
  if (idx !== undefined)
186
191
  removedIndexes.add(idx);
187
192
  }
193
+ for (const hash of blocked)
194
+ markHashUsed(used, hash);
188
195
  let spanStart = oldLines.length;
189
196
  let spanEnd = -1;
190
197
  for (const idx of removedIndexes) {
@@ -197,12 +204,9 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
197
204
  const replacementLen = newLines.length - oldLines.length + spanLen;
198
205
  const shiftAfterSpan = spanEnd >= spanStart ? replacementLen - spanLen : 0;
199
206
  const survivors = [];
200
- const removedEntries = [];
201
207
  for (let i = 0; i < oldLines.length; i++) {
202
208
  const entry = { index: i, hash: oldHashes[i] };
203
- if (removedIndexes.has(i))
204
- removedEntries.push(entry);
205
- else
209
+ if (!removedIndexes.has(i))
206
210
  survivors.push(entry);
207
211
  }
208
212
  const newByContent = new Map();
@@ -235,27 +239,6 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
235
239
  markUsed(entry.hash);
236
240
  rememberHashCanon(entry.hash, getCanon(canonCache, oldLines[entry.index]));
237
241
  }
238
- const removedByContent = new Map();
239
- for (const entry of removedEntries) {
240
- const key = getCanon(canonCache, oldLines[entry.index]);
241
- let queue = removedByContent.get(key);
242
- if (!queue) {
243
- queue = { hashes: [], pos: 0 };
244
- removedByContent.set(key, queue);
245
- }
246
- queue.hashes.push(entry.hash);
247
- }
248
- for (let i = 0; i < newLines.length; i++) {
249
- if (newHashes[i])
250
- continue;
251
- const queue = removedByContent.get(getCanon(canonCache, newLines[i]));
252
- if (!queue || queue.pos >= queue.hashes.length)
253
- continue;
254
- const h = queue.hashes[queue.pos];
255
- newHashes[i] = h;
256
- queue.pos += 1;
257
- rememberHashCanon(h, getCanon(canonCache, newLines[i]));
258
- }
259
242
  for (let i = 0; i < newLines.length; i++) {
260
243
  if (newHashes[i])
261
244
  continue;
@@ -267,4 +250,9 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
267
250
  }
268
251
  return newHashes;
269
252
  }
253
+ function markHashUsed(used, hash) {
254
+ const idx = hashToIndex(hash);
255
+ if (idx >= 0)
256
+ setBit(used, idx);
257
+ }
270
258
  // --- persistence wrapper (from hash.ts) ---
@@ -45,16 +45,16 @@ export function isValidHashList(value) {
45
45
  }
46
46
  return true;
47
47
  }
48
- export async function lineHashes(content, path, previous, ioOrStore, persist) {
48
+ export async function lineHashes(content, path, previous, ioOrStore, persist, reservedHashes = new Set(), retiredHashes = new Set()) {
49
49
  await initHasher();
50
50
  if (!path)
51
- return lineHashesPure(content);
51
+ return lineHashesPure(content, reservedHashes);
52
52
  // Back-compat: caller may pass HashStore as 4th arg; adapt to IO.
53
53
  const io = ioOrStore && "getSnapshot" in ioOrStore
54
54
  ? snapshotIOFor(ioOrStore)
55
55
  : ioOrStore ?? snapshotIOFor(undefined);
56
56
  if (previous) {
57
- const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes);
57
+ const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes, reservedHashes);
58
58
  if (persist !== false && io) {
59
59
  try {
60
60
  await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
@@ -74,9 +74,9 @@ export async function lineHashes(content, path, previous, ioOrStore, persist) {
74
74
  console.error("Failed to read hash store snapshot:", e);
75
75
  }
76
76
  }
77
- if (cached)
77
+ if (cached && !cached.some((hash) => retiredHashes.has(hash)))
78
78
  return cached;
79
- const newHashes = lineHashesPure(content);
79
+ const newHashes = lineHashesPure(content, reservedHashes);
80
80
  if (persist !== false && io) {
81
81
  try {
82
82
  await io.upsert(path, contentChecksum(content), splitLines(content).length, newHashes);
@@ -11,8 +11,11 @@
11
11
  * reject-and-serve records the same echo serves.
12
12
  * @module dsh-better-edit/mutation/engine
13
13
  */
14
+ import { loadConfig } from "../store-config.js";
15
+ import { canon } from "../hashline/hash-assign.js";
16
+ import { fileSnap } from "../file-view.js";
14
17
  import { normFromText } from "../file-reader.js";
15
- import { scanDrift, loadServed } from "../session-view.js";
18
+ import { scanDrift, loadServed, loadServedCanons, loadEpochSnapshotId, loadRetiredAnchors, retireAnchors, } from "../session-view.js";
16
19
  import { applyEdit, resEdit, parseHashRef, } from "../hashline/anchor-pipeline.js";
17
20
  import { lineHashes } from "../hashline/hash.js";
18
21
  import { MAX_HASH_LINES } from "../hashline/hash-assign.js";
@@ -121,7 +124,7 @@ export async function applyOne(input, onReject) {
121
124
  }
122
125
  let anchorResult;
123
126
  try {
124
- anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served);
127
+ anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served, input.servedCanons, input.tombstone, input.epochSnapshotId, input.curSnapshotId, input.strictPos);
125
128
  }
126
129
  catch (error) {
127
130
  if (error instanceof AnchorMismatchError ||
@@ -141,7 +144,7 @@ export async function applyOne(input, onReject) {
141
144
  content: input.content,
142
145
  hashes: input.hashes,
143
146
  removedHashes,
144
- }, input.store, input.persist);
147
+ }, input.store, input.persist, input.reservedHashes);
145
148
  const { totalAddedLines, totalRemovedLines } = countLineChanges(edit, input.countHashes ?? input.hashes, noop, 0);
146
149
  return {
147
150
  result,
@@ -215,6 +218,8 @@ export async function runFileEdits(io, items, opts) {
215
218
  const first = items[0];
216
219
  abortIf(opts.signal);
217
220
  const absolutePath = first.absolutePath;
221
+ const perSessionTombstone = await loadRetiredAnchors(opts.sessionKey, absolutePath);
222
+ const reservedHashes = new Set(perSessionTombstone);
218
223
  const rawText = await io.readText(absolutePath, opts.signal);
219
224
  const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
220
225
  absolutePath,
@@ -222,8 +227,18 @@ export async function runFileEdits(io, items, opts) {
222
227
  displayPath: first.path,
223
228
  signal: opts.signal,
224
229
  maxLines: MAX_HASH_LINES,
230
+ reservedHashes,
231
+ retiredHashes: perSessionTombstone,
225
232
  });
226
233
  const served = await loadServed(opts.sessionKey, absolutePath);
234
+ const servedCanons = await loadServedCanons(opts.sessionKey, absolutePath);
235
+ const epochSnapshotId = await loadEpochSnapshotId(opts.sessionKey, absolutePath);
236
+ let curSnapshotId;
237
+ try {
238
+ curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
239
+ }
240
+ catch { }
241
+ const strictPos = false; // automatic resist: pos-free for exterior shift, strict via tombstone+canon for whole-span rebind
227
242
  const warnings = [];
228
243
  let currentContent = originalNormalized;
229
244
  let currentHashes = originalHashes;
@@ -236,6 +251,7 @@ export async function runFileEdits(io, items, opts) {
236
251
  let unionStartHash = "";
237
252
  let unionEndHash = "";
238
253
  let lastApplied;
254
+ const newlyRetired = new Set();
239
255
  for (const item of items) {
240
256
  abortIf(opts.signal);
241
257
  const applied = await applyOne({
@@ -251,6 +267,12 @@ export async function runFileEdits(io, items, opts) {
251
267
  warnings,
252
268
  countHashes: originalHashes,
253
269
  persist: false,
270
+ reservedHashes,
271
+ servedCanons,
272
+ tombstone: new Set([...perSessionTombstone, ...Array.from(newlyRetired)]),
273
+ epochSnapshotId,
274
+ curSnapshotId,
275
+ strictPos,
254
276
  }, async (error, edit) => {
255
277
  if (error instanceof AnchorMismatchError ||
256
278
  error instanceof ServedRejectionError) {
@@ -308,6 +330,10 @@ export async function runFileEdits(io, items, opts) {
308
330
  }
309
331
  appliedCount += 1;
310
332
  const removedHashes = applied.removedHashes;
333
+ for (const hash of removedHashes) {
334
+ reservedHashes.add(hash);
335
+ newlyRetired.add(hash);
336
+ }
311
337
  totalAddedLines += applied.totalAddedLines;
312
338
  totalRemovedLines += applied.totalRemovedLines;
313
339
  lastApplied = {
@@ -328,7 +354,8 @@ export async function runFileEdits(io, items, opts) {
328
354
  content: lastApplied.content,
329
355
  hashes: lastApplied.hashes,
330
356
  removedHashes: lastApplied.removedHashes,
331
- }, undefined, true);
357
+ }, undefined, true, reservedHashes, perSessionTombstone);
358
+ await retireAnchors(opts.sessionKey, absolutePath, newlyRetired);
332
359
  }
333
360
  if (hadUtf8DecodeErrors) {
334
361
  warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
package/lib/mutation.js CHANGED
@@ -24,13 +24,15 @@
24
24
  *
25
25
  * @module dsh-better-edit/mutation
26
26
  */
27
+ import { loadConfig } from "./store-config.js";
28
+ import { canon } from "./hashline/hash-assign.js";
27
29
  import { normFromText, fileSnap } from "./file-reader.js";
28
30
  import { toCwd } from "./paths.js";
29
31
  import { resEdit } from "./hashline/anchor-pipeline.js";
30
32
  import { MAX_HASH_LINES } from "./hashline/hash-assign.js";
31
33
  import { AnchorMismatchError, ServedRejectionError, recordEchoServes, } from "./hashline/anchor-pipeline.js";
32
34
  import { sessionKeyFor } from "./workspace-context.js";
33
- import { loadServed, scanDrift, recordServedTruncated } from "./session-view.js";
35
+ import { loadServed, loadServedCanons, loadEpochSnapshotId, loadRetiredAnchors, scanDrift, recordServedTruncated, } from "./session-view.js";
34
36
  import { abortIf, splitLines } from "./utils.js";
35
37
  import { applyOne } from "./mutation/engine.js";
36
38
  import { runFileEdits, resolveMissingPath, } from "./mutation/engine.js";
@@ -54,6 +56,8 @@ export async function execPipeline(io, params, cwd, options) {
54
56
  const signal = options?.signal;
55
57
  abortIf(signal);
56
58
  const absolutePath = await io.resolve(path, cwd, signal);
59
+ const sessionKeyEarly = options?.sessionKey ?? sessionKeyFor(undefined);
60
+ const perSessionTombstoneForNorm = await loadRetiredAnchors(sessionKeyEarly, absolutePath);
57
61
  const rawText = await io.readText(absolutePath, signal);
58
62
  const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
59
63
  absolutePath,
@@ -63,9 +67,20 @@ export async function execPipeline(io, params, cwd, options) {
63
67
  maxLines: MAX_HASH_LINES,
64
68
  store: hashStore,
65
69
  noPersist: options?.noPersist,
70
+ reservedHashes: perSessionTombstoneForNorm,
71
+ retiredHashes: perSessionTombstoneForNorm,
66
72
  });
67
73
  const sessionKey = options?.sessionKey ?? sessionKeyFor(undefined);
68
74
  const served = await loadServed(sessionKey, absolutePath);
75
+ const servedCanons = await loadServedCanons(sessionKey, absolutePath);
76
+ const epochSnapshotId = await loadEpochSnapshotId(sessionKey, absolutePath);
77
+ let curSnapshotId;
78
+ try {
79
+ curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
80
+ }
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);
69
84
  const policy = options?.noPersist === true ? 'preview' : 'live';
70
85
  const applied = await applyOne({
71
86
  content: originalNormalized,
@@ -80,6 +95,12 @@ export async function execPipeline(io, params, cwd, options) {
80
95
  warnings: editWarnings,
81
96
  store: hashStore,
82
97
  persist: options?.noPersist !== true,
98
+ reservedHashes: perSessionTombstoneForNorm,
99
+ servedCanons,
100
+ tombstone: tombstonePerSession,
101
+ epochSnapshotId,
102
+ curSnapshotId,
103
+ strictPos,
83
104
  edit,
84
105
  }, async (error) => {
85
106
  if (error instanceof AnchorMismatchError ||
@@ -8,9 +8,11 @@
8
8
  * @module dsh-better-edit/read-and-serve
9
9
  */
10
10
  import { abortIf } from "./utils.js";
11
- import { readView } from "./file-view.js";
11
+ import { readView, fileSnap } from "./file-view.js";
12
+ import { canon } from "./hashline/hash-assign.js";
13
+ import { splitLines } from "./utils.js";
12
14
  import { getAutoGuessFooter } from "./fs-bridge.js";
13
- import { recordServed, clearDriftReported } from "./session-view.js";
15
+ import { recordServed, clearDriftReported, loadRetiredAnchors, loadServed, } from "./session-view.js";
14
16
  /** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
15
17
  export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
16
18
  /**
@@ -26,14 +28,34 @@ export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewr
26
28
  export async function readAndServe(io, rawPath, cwd, options) {
27
29
  const { sessionKey, signal } = options;
28
30
  abortIf(signal);
31
+ const absolutePath = await io.resolve(rawPath, cwd, signal);
32
+ const retiredHashes = await loadRetiredAnchors(sessionKey, absolutePath);
33
+ const servedForNorm = await loadServed(sessionKey, absolutePath);
34
+ const reservedHashes = new Set([...retiredHashes, ...servedForNorm.filter((h) => h !== null)]);
35
+ const reservations = { reservedHashes, retiredHashes };
29
36
  const view = await readView(io, rawPath, cwd, {
30
37
  encoding: options.encoding,
31
38
  offset: options.offset,
32
39
  limit: options.limit,
33
40
  signal,
41
+ reservedHashes: reservations.reservedHashes,
42
+ retiredHashes: reservations.retiredHashes,
34
43
  });
35
44
  if (view.served.length > 0) {
36
- await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length);
45
+ const canons = splitLines(view.normalized).map((l) => canon(l));
46
+ const canonServed = canons.map((canonText) => canonText);
47
+ // For full read, compute snapshotId
48
+ let snapshotId;
49
+ try {
50
+ snapshotId = (await fileSnap(view.absolutePath)).snapshotId;
51
+ }
52
+ catch { }
53
+ // Pad or trim canons to served length? For now use canons for full file
54
+ const fullCanons = [];
55
+ for (let i = 0; i < view.hashes.length; i++) {
56
+ fullCanons.push(canons[i] ?? null);
57
+ }
58
+ await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length, view.hashes, fullCanons, snapshotId);
37
59
  }
38
60
  await clearDriftReported(sessionKey, view.absolutePath);
39
61
  const autoFooter = getAutoGuessFooter(view.absolutePath) ?? getAutoGuessFooter(rawPath) ?? getAutoGuessFooter(view.absolutePath.replace(/\\/g, "/")) ?? "";
@@ -22,7 +22,7 @@
22
22
  * @module dsh-better-edit/session-view
23
23
  */
24
24
  import { HASH_RE } from "./hashline/hash-assign.js";
25
- import { loadHashStore, loadServedStore, withStore } from "./hash-store.js";
25
+ import { loadHashStore, loadServedStore, withStore, } from "./hash-store.js";
26
26
  import { SERVED_ECHO_CAP } from "./constants.js";
27
27
  import { fmtServedRows } from "./hashline/anchor-pipeline.js";
28
28
  // --- hash-store re-export (persistence note) ---
@@ -91,17 +91,99 @@ export async function loadServed(sessionKey, path) {
91
91
  const store = await loadServedStore();
92
92
  return store.getServed(sessionKey, path);
93
93
  }
94
- export async function recordServed(sessionKey, path, rows, lineCount) {
94
+ /** Anchors that must not be allocated while any session can still remember them. */
95
+ export async function loadAnchorReservations(path) {
96
+ const store = await loadServedStore();
97
+ return store.getAnchorReservations(path);
98
+ }
99
+ export async function loadServedCanons(sessionKey, path) {
100
+ const store = await loadServedStore();
101
+ return store.getServedCanons(sessionKey, path);
102
+ }
103
+ export async function loadEpochSnapshotId(sessionKey, path) {
104
+ const store = await loadServedStore();
105
+ return store.getEpochSnapshotId(sessionKey, path);
106
+ }
107
+ export async function loadRetiredAnchors(sessionKey, path) {
108
+ const store = await loadServedStore();
109
+ return store.getRetiredAnchors(sessionKey, path);
110
+ }
111
+ function addRetiredAnchors(store, sessionKey, path, hashes) {
112
+ const additions = [...hashes];
113
+ if (additions.length === 0)
114
+ return;
115
+ const retired = store.getRetiredAnchors(sessionKey, path);
116
+ for (const hash of additions) {
117
+ if (!HASH_RE.test(hash)) {
118
+ throw new TypeError(`Invalid retired hash: ${hash}`);
119
+ }
120
+ retired.add(hash);
121
+ }
122
+ store.upsertRetiredAnchors(sessionKey, path, JSON.stringify([...retired]));
123
+ }
124
+ function displacedHashes(current, updated) {
125
+ const remaining = new Set(updated.filter((hash) => hash !== null));
126
+ return new Set(current.filter((hash) => hash !== null && !remaining.has(hash)));
127
+ }
128
+ /** Keep freed anchors dead for this session until it has seen the whole file again. */
129
+ export async function retireAnchors(sessionKey, path, hashes) {
130
+ const additions = [...hashes];
131
+ if (additions.length === 0)
132
+ return;
133
+ const store = await loadServedStore();
134
+ withStore(() => {
135
+ addRetiredAnchors(store, sessionKey, path, additions);
136
+ });
137
+ }
138
+ export async function recordServed(sessionKey, path, rows, lineCount, fullReadHashes, fullReadCanons, fullReadSnapshotId) {
95
139
  if (rows.length === 0)
96
140
  return;
97
141
  try {
98
142
  const store = await loadServedStore();
143
+ const isFullRead = fullReadHashes !== undefined &&
144
+ rows.length === fullReadHashes.length &&
145
+ rows.every((row, index) => row.position === index && row.hash === fullReadHashes[index]);
99
146
  withStore(() => {
100
147
  const current = store.getServed(sessionKey, path);
101
148
  const updated = _mergeServedRows(current, rows, lineCount === undefined ? undefined : { truncateTo: lineCount });
102
- if (current.length === updated.length && current.every((v, i) => v === updated[i]))
103
- return;
104
- store.upsertServed(sessionKey, path, JSON.stringify(updated));
149
+ if (current.length !== updated.length || current.some((v, i) => v !== updated[i])) {
150
+ store.upsertServed(sessionKey, path, JSON.stringify(updated));
151
+ }
152
+ if (isFullRead) {
153
+ store.clearRetiredAnchors(sessionKey, path);
154
+ if (fullReadCanons)
155
+ store.upsertServedCanons(sessionKey, path, JSON.stringify(fullReadCanons));
156
+ if (fullReadSnapshotId)
157
+ store.upsertEpochSnapshotId(sessionKey, path, fullReadSnapshotId);
158
+ }
159
+ else {
160
+ // For partial reads, update canons for the served rows via hash-to-canon map (robust for partial views)
161
+ if (fullReadCanons && fullReadHashes) {
162
+ const canonByHash = new Map();
163
+ for (let i = 0; i < fullReadHashes.length; i++) {
164
+ const h = fullReadHashes[i];
165
+ const c = fullReadCanons[i] ?? null;
166
+ if (h)
167
+ canonByHash.set(h, c);
168
+ }
169
+ const currentCanons = store.getServedCanons(sessionKey, path);
170
+ const updatedCanons = currentCanons.slice();
171
+ while (updatedCanons.length < (lineCount ?? 0))
172
+ updatedCanons.push(null);
173
+ for (const row of rows) {
174
+ while (updatedCanons.length <= row.position)
175
+ updatedCanons.push(null);
176
+ const canonVal = row.hash ? (canonByHash.get(row.hash) ?? null) : null;
177
+ updatedCanons[row.position] = canonVal;
178
+ }
179
+ while (updatedCanons.length > 0 && updatedCanons[updatedCanons.length - 1] === null)
180
+ updatedCanons.pop();
181
+ store.upsertServedCanons(sessionKey, path, JSON.stringify(updatedCanons));
182
+ }
183
+ if (fullReadSnapshotId)
184
+ store.upsertEpochSnapshotId(sessionKey, path, fullReadSnapshotId);
185
+ addRetiredAnchors(store, sessionKey, path, displacedHashes(current, updated));
186
+ }
105
187
  });
106
188
  }
107
189
  catch (error) {
@@ -116,10 +198,10 @@ export async function recordServedTruncated(sessionKey, path, rows, lineCount, c
116
198
  withStore(() => {
117
199
  const current = store.getServed(sessionKey, path);
118
200
  const updated = _mergeServedRows(current, rows, { truncateTo: lineCount, clearFrom });
119
- // Avoid no-op writes (perf: O(1) check, no extra I/O beyond current read)
120
- if (current.length === updated.length && current.every((v, i) => v === updated[i]))
121
- return;
122
- store.upsertServed(sessionKey, path, JSON.stringify(updated));
201
+ if (current.length !== updated.length || current.some((v, i) => v !== updated[i])) {
202
+ store.upsertServed(sessionKey, path, JSON.stringify(updated));
203
+ }
204
+ addRetiredAnchors(store, sessionKey, path, displacedHashes(current, updated));
123
205
  });
124
206
  }
125
207
  catch (error) {
package/lib/tool-undo.js CHANGED
@@ -14,7 +14,7 @@ import { contentChecksum } from "./hashline/hash-assign.js";
14
14
  import { lineHashes } from "./hashline/hash.js";
15
15
  import { changedRange } from "./hashline/anchor-pipeline.js";
16
16
  import { getUndo, clearUndo } from "./undo-edit.js";
17
- import { recordServedTruncated } from "./session-view.js";
17
+ import { loadAnchorReservations, recordServedTruncated, retireAnchors, } from "./session-view.js";
18
18
  import { UNDO_DESCRIPTION } from "./prompts.js";
19
19
  import { execCwd, execSessionKey } from "./workspace-context.js";
20
20
  import { withWorkspace } from "./workspace-context.js";
@@ -75,17 +75,30 @@ export function buildUndoTool(io, sandbox) {
75
75
  }
76
76
  const { text: currentStripped } = stripBOM(currentRaw);
77
77
  const currentNormalized = toLF(currentStripped);
78
- const currentHashes = await lineHashes(currentNormalized, absolutePath);
78
+ // undo is file-global: must block hashes retired by any session, not just current session, to prevent recycling current-file-only hash - test expects global
79
+ const reservations = await loadAnchorReservations(absolutePath);
80
+ const currentHashes = await lineHashes(currentNormalized, absolutePath, undefined, undefined, false, reservations.reservedHashes, reservations.retiredHashes);
81
+ const retiredOriginalHashes = new Set(undo.hashes.filter((hash) => reservations.retiredHashes.has(hash)));
82
+ const blockedRestoreHashes = new Set(reservations.reservedHashes);
83
+ for (const hash of currentHashes)
84
+ blockedRestoreHashes.add(hash);
85
+ const restoredHashes = await lineHashes(undo.content, absolutePath, {
86
+ content: undo.content,
87
+ hashes: undo.hashes,
88
+ removedHashes: retiredOriginalHashes,
89
+ }, undefined, false, blockedRestoreHashes, reservations.retiredHashes);
79
90
  const diffResult = genDiff(undo.content, currentNormalized, 0, undefined, undo.hashes);
80
91
  const linesAddedByEdit = cntDiff(diffResult.diff, "+");
81
92
  const linesRemovedByEdit = cntDiff(diffResult.diff, "-");
82
- const undoDiffResult = genDiff(currentNormalized, undo.content, 1, undo.hashes, currentHashes);
93
+ const undoDiffResult = genDiff(currentNormalized, undo.content, 1, restoredHashes, currentHashes);
83
94
  const undoDiff = undoDiffResult.diff;
84
95
  const undoDenseRows = [];
85
- for (let i = 0; i < undo.hashes.length; i++) {
86
- undoDenseRows.push({ position: i, hash: undo.hashes[i] });
96
+ for (let i = 0; i < restoredHashes.length; i++) {
97
+ undoDenseRows.push({ position: i, hash: restoredHashes[i] });
87
98
  }
88
99
  const restoredRange = changedRange(currentNormalized, undo.content);
100
+ const restoredSet = new Set(restoredHashes);
101
+ await retireAnchors(sessionKey, absolutePath, currentHashes.filter((hash) => !restoredSet.has(hash)));
89
102
  try {
90
103
  await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal, exec, sandboxPolicy);
91
104
  }
@@ -93,7 +106,7 @@ export function buildUndoTool(io, sandbox) {
93
106
  throw sandbox.mapError(error, sandboxPolicy);
94
107
  }
95
108
  try {
96
- await upsertSnapshotFor(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, undo.hashes);
109
+ await upsertSnapshotFor(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, restoredHashes);
97
110
  }
98
111
  catch (error) {
99
112
  console.error("Failed to restore hash store snapshot after undo:", error);
@@ -89,6 +89,8 @@ export interface ReadNormOptions {
89
89
  maxLines?: number;
90
90
  store?: HashStore;
91
91
  noPersist?: boolean;
92
+ reservedHashes?: ReadonlySet<string>;
93
+ retiredHashes?: ReadonlySet<string>;
92
94
  }
93
95
  export declare function normFromText(input: {
94
96
  absolutePath: string;
@@ -98,6 +100,8 @@ export declare function normFromText(input: {
98
100
  maxLines?: number;
99
101
  store?: HashStore;
100
102
  noPersist?: boolean;
103
+ reservedHashes?: ReadonlySet<string>;
104
+ retiredHashes?: ReadonlySet<string>;
101
105
  hadUtf8DecodeErrors?: boolean;
102
106
  }): Promise<NormFile>;
103
107
  export declare function readNormFile(path: string, cwd: string, options?: ReadNormOptions): Promise<NormFile>;
@@ -130,6 +134,8 @@ export interface PreviewOpts {
130
134
  export interface ReadViewOpts extends PreviewOpts {
131
135
  encoding?: string;
132
136
  signal?: AbortSignal;
137
+ reservedHashes?: ReadonlySet<string>;
138
+ retiredHashes?: ReadonlySet<string>;
133
139
  }
134
140
  export declare function preview(content: string, hashes: string[], opts?: PreviewOpts, absolutePath?: string): Promise<{
135
141
  text: string;
@@ -21,6 +21,7 @@ export interface LegacySnapshot {
21
21
  export declare function isValidHashList(value: unknown): value is string[];
22
22
  export declare function isValidSnapshot(value: unknown): value is LegacySnapshot;
23
23
  /** A served-row array: per-position hash, or null for never-served slots. */
24
+ export declare function isValidCanonsList(value: unknown): value is (string | null)[];
24
25
  export declare function isValidServedList(value: unknown): value is (string | null)[];
25
26
  /** The undo row contract shared by undo-edit and the store. */
26
27
  export interface UndoRecord {
@@ -66,14 +67,28 @@ export interface HashStore {
66
67
  export interface ServedPersistence {
67
68
  getServed(sessionKey: string, path: string): (string | null)[];
68
69
  getServedReported(sessionKey: string, path: string): Set<string>;
70
+ getAnchorReservations(path: string): AnchorReservations;
71
+ getRetiredAnchors(sessionKey: string, path: string): Set<string>;
72
+ getServedCanons(sessionKey: string, path: string): (string | null)[];
73
+ getEpochSnapshotId(sessionKey: string, path: string): string | undefined;
69
74
  upsertServed(sessionKey: string, path: string, hashesJson: string): void;
70
75
  upsertServedReported(sessionKey: string, path: string, reportedJson: string): void;
71
76
  clearServedReported(sessionKey: string, path: string): void;
77
+ upsertRetiredAnchors(sessionKey: string, path: string, hashesJson: string): void;
78
+ clearRetiredAnchors(sessionKey: string, path: string): void;
79
+ upsertServedCanons(sessionKey: string, path: string, canonsJson: string): void;
80
+ clearServedCanons(sessionKey: string, path: string): void;
81
+ upsertEpochSnapshotId(sessionKey: string, path: string, snapshotId: string): void;
82
+ clearEpochSnapshotId(sessionKey: string, path: string): void;
72
83
  deleteServed(sessionKey: string, path: string): void;
73
84
  deleteServedByPath(path: string): void;
74
85
  wipeServed(sessionKey: string): void;
75
86
  pruneServedOlderThan(ts: number): void;
76
87
  }
88
+ export interface AnchorReservations {
89
+ reservedHashes: Set<string>;
90
+ retiredHashes: Set<string>;
91
+ }
77
92
  export type InternalHashStore = HashStore & ServedPersistence;
78
93
  /** Load the store as served persistence — internal, for SessionView only. */
79
94
  export declare function loadServedStore(cwd?: string): Promise<ServedPersistence>;
@@ -88,6 +88,11 @@ export declare function verifyServedRange(args: {
88
88
  fileHashes: string[];
89
89
  fileLines: string[];
90
90
  filePath?: string;
91
+ servedCanons?: (string | null)[];
92
+ tombstone?: ReadonlySet<string>;
93
+ epochSnapshotId?: string;
94
+ curSnapshotId?: string;
95
+ strictPos?: boolean;
91
96
  }): void;
92
97
  export interface ResolvedRange {
93
98
  startLine: number;
@@ -103,7 +108,7 @@ type LIdx = {
103
108
  lineStarts: number[];
104
109
  };
105
110
  export declare function buildIdx(content: string): LIdx;
106
- export declare function applyEdit(content: string, edit: HEdit, signal?: AbortSignal, precomputedHashes?: string[], filePath?: string, served?: (string | null)[]): {
111
+ export declare function applyEdit(content: string, edit: HEdit, signal?: AbortSignal, precomputedHashes?: string[], filePath?: string, served?: (string | null)[], servedCanons?: (string | null)[], tombstone?: ReadonlySet<string>, epochSnapshotId?: string, curSnapshotId?: string, strictPos?: boolean): {
107
112
  content: string;
108
113
  firstChangedLine: number | undefined;
109
114
  lastChangedLine: number | undefined;
@@ -23,5 +23,5 @@ export declare const HL_PREFIX_MINUS_RE: RegExp;
23
23
  export declare const HL_BARE_PREFIX_RE: RegExp;
24
24
  export declare const CANON_VERSION = 2;
25
25
  export declare function canon(line: string): string;
26
- export declare function lineHashesPure(content: string): string[];
27
- export declare function mapStableHashes(oldContent: string, oldHashes: string[], newContent: string, removedHashes?: Set<string>): string[];
26
+ export declare function lineHashesPure(content: string, reservedHashes?: ReadonlySet<string>): string[];
27
+ export declare function mapStableHashes(oldContent: string, oldHashes: string[], newContent: string, removedHashes?: Set<string>, reservedHashes?: ReadonlySet<string>): string[];
@@ -10,4 +10,4 @@ export declare function lineHashes(content: string, path?: string, previous?: {
10
10
  content: string;
11
11
  hashes: string[];
12
12
  removedHashes?: Set<string>;
13
- }, ioOrStore?: HashStore | HashSnapshotIO, persist?: boolean): Promise<string[]>;
13
+ }, ioOrStore?: HashStore | HashSnapshotIO, persist?: boolean, reservedHashes?: ReadonlySet<string>, retiredHashes?: ReadonlySet<string>): Promise<string[]>;
@@ -79,6 +79,12 @@ export interface ApplyOneInput {
79
79
  countHashes?: string[];
80
80
  store?: HashStore;
81
81
  persist: boolean;
82
+ reservedHashes?: ReadonlySet<string>;
83
+ servedCanons?: (string | null)[];
84
+ tombstone?: ReadonlySet<string>;
85
+ epochSnapshotId?: string;
86
+ curSnapshotId?: string;
87
+ strictPos?: boolean;
82
88
  /** Pre-resolved edit (single path keeps resEdit before IO for error order). */
83
89
  edit?: HEdit;
84
90
  }
@@ -21,6 +21,7 @@
21
21
  *
22
22
  * @module dsh-better-edit/session-view
23
23
  */
24
+ import { type AnchorReservations } from "./hash-store.js";
24
25
  import type { ServedRow, ResolvedRange } from "./hashline/anchor-pipeline.js";
25
26
  export { loadHashStore, loadServedStore, shutdownHashStore, withStore } from "./hash-store.js";
26
27
  export type { HashStore } from "./hash-store.js";
@@ -40,7 +41,14 @@ export declare function _mergeServedRows(current: (string | null)[], rows: Serve
40
41
  clearFrom?: number;
41
42
  }): (string | null)[];
42
43
  export declare function loadServed(sessionKey: string, path: string): Promise<(string | null)[]>;
43
- export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[], lineCount?: number): Promise<void>;
44
+ /** Anchors that must not be allocated while any session can still remember them. */
45
+ export declare function loadAnchorReservations(path: string): Promise<AnchorReservations>;
46
+ export declare function loadServedCanons(sessionKey: string, path: string): Promise<(string | null)[]>;
47
+ export declare function loadEpochSnapshotId(sessionKey: string, path: string): Promise<string | undefined>;
48
+ export declare function loadRetiredAnchors(sessionKey: string, path: string): Promise<Set<string>>;
49
+ /** Keep freed anchors dead for this session until it has seen the whole file again. */
50
+ export declare function retireAnchors(sessionKey: string, path: string, hashes: Iterable<string>): Promise<void>;
51
+ export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[], lineCount?: number, fullReadHashes?: readonly string[], fullReadCanons?: readonly (string | null)[], fullReadSnapshotId?: string): Promise<void>;
44
52
  export declare function recordServedTruncated(sessionKey: string, path: string, rows: ServedEntry[], lineCount: number, clearFrom?: number): Promise<void>;
45
53
  export declare function driftReported(sessionKey: string, path: string): Promise<Set<string>>;
46
54
  export declare function markDriftReported(sessionKey: string, path: string, hashes: string[]): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-better-edit",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
5
  "description": "Hash-anchored read/edit/undo_last_edit tools for DeepSeek Harness (dsh). Every line gets a unique 3-char hash (A-Za-z0-9) that stays stable across edits; stale or ambiguous anchors are rejected, never fuzzy-matched. Undo persists across restarts.",
6
6
  "main": "lib/index.js",