dsh-better-edit 0.6.0 → 0.6.3

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/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);
package/lib/index.js CHANGED
@@ -1,26 +1,10 @@
1
- /**
2
- * dsh-better-edit — hash-anchored read/edit/batch_edit/undo_last_edit for
3
- * DeepSeek Harness, a dsh port of pi-hashline-edit-lsz.
4
- *
5
- * Cordis host-plane plugin (mounted by the bundle's cordis.patch.yml). On
6
- * `agent/session-start` it registers the hashline tools and prompt sections on
7
- * the AGENT's own scope layer, so they shadow the preset's built-in `read` /
8
- * `edit` for that agent (nearest layer wins in dsh's tool registry) and unwind
9
- * automatically when the agent is disposed. The built-in `write` stays in
10
- * place; scoped pre/post listeners reject copied same-line served anchors
11
- * before dispatch and append a fresh hashline preview after successful writes.
12
- *
13
- * The four `tool:*` guidance sections resolve per agent preset from override
14
- * files in the shared home (see `src/guidance.ts`); deployments without the
15
- * `agentPresets` service keep the compiled defaults unchanged.
16
- * @module dsh-better-edit
17
- */
18
1
  import { ctxFsIO } from "./fs-bridge.js";
19
2
  import { FsSandboxController } from "./sandbox.js";
20
- import { registerReadTool } from "./tool-read.js";
21
- import { registerEditTool } from "./tool-edit.js";
3
+ import { buildReadTool } from "./tool-read.js";
4
+ import { buildEditTool } from "./tool-edit.js";
22
5
  import { registerUndoTool } from "./tool-undo.js";
23
6
  import { registerWriteHook } from "./write-hook.js";
7
+ import { createSelfHealWatcher } from "./self-heal.js";
24
8
  import { initHasher } from "./hashline/hash-assign.js";
25
9
  import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
26
10
  import { configDir } from "./store/index.js";
@@ -80,11 +64,24 @@ function installAgentTools(rootCtx, agent) {
80
64
  // exec.agent.session.header.cwd.
81
65
  const io = ctxFsIO(rootCtx.fs, rootCtx);
82
66
  const disposers = [];
83
- disposers.push(registerReadTool(rootCtx, agent.ctx, io));
84
67
  const sandbox = new FsSandboxController(rootCtx);
85
- disposers.push(registerEditTool(rootCtx, agent.ctx, io, sandbox));
68
+ // Keep owned definitions by reference for self-heal identity check
69
+ const hashReadDef = buildReadTool(io);
70
+ disposers.push(agent.ctx.tools.register(hashReadDef));
71
+ const hashEditDef = buildEditTool(io, sandbox);
72
+ disposers.push(agent.ctx.tools.register(hashEditDef));
86
73
  disposers.push(registerUndoTool(rootCtx, agent.ctx, io, sandbox));
87
74
  disposers.push(registerWriteHook(rootCtx, agent.ctx, io));
75
+ const toolsSvc = rootCtx.get("tools");
76
+ disposers.push(createSelfHealWatcher({
77
+ agentId: agent.id,
78
+ rootCtx,
79
+ agent,
80
+ agentCtx: agent.ctx,
81
+ toolsSvc,
82
+ hashReadDef,
83
+ hashEditDef,
84
+ }));
88
85
  // Shadow the preset's built-in tool guidance with the hashline
89
86
  // contract. Same section names on the agent's own layer win over the
90
87
  // preset's; text and order come from the per-preset resolution.
@@ -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.");