dsh-better-edit 0.5.1 → 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.
Files changed (42) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/lib/edit-engine.js +4 -454
  3. package/lib/edit-response.js +24 -2
  4. package/lib/file-encoding-state.js +263 -0
  5. package/lib/file-view.js +5 -1
  6. package/lib/fs-bridge.js +94 -251
  7. package/lib/hash-store.js +180 -2
  8. package/lib/hashline/anchor-pipeline.js +94 -166
  9. package/lib/hashline/hash-assign.js +15 -27
  10. package/lib/hashline/hash.js +5 -5
  11. package/lib/index.js +2 -2
  12. package/lib/mutation/engine.js +415 -0
  13. package/lib/mutation.js +105 -11
  14. package/lib/paths.js +1 -1
  15. package/lib/read-and-serve.js +25 -3
  16. package/lib/session-view.js +107 -58
  17. package/lib/store/index.js +28 -0
  18. package/lib/store-lifecycle.js +1 -1
  19. package/lib/tool-edit.js +2 -2
  20. package/lib/tool-read.js +2 -2
  21. package/lib/tool-undo.js +21 -8
  22. package/lib/types/edit-diff.d.ts +1 -1
  23. package/lib/types/edit-engine.d.ts +4 -176
  24. package/lib/types/edit-response.d.ts +1 -1
  25. package/lib/types/file-encoding-state.d.ts +77 -0
  26. package/lib/types/file-view.d.ts +7 -1
  27. package/lib/types/fs-bridge.d.ts +4 -11
  28. package/lib/types/hash-store.d.ts +15 -0
  29. package/lib/types/hashline/anchor-pipeline.d.ts +12 -21
  30. package/lib/types/hashline/hash-assign.d.ts +2 -2
  31. package/lib/types/hashline/hash.d.ts +1 -1
  32. package/lib/types/hashline/index.d.ts +1 -1
  33. package/lib/types/mutation/engine.d.ts +149 -0
  34. package/lib/types/mutation.d.ts +30 -5
  35. package/lib/types/paths.d.ts +1 -1
  36. package/lib/types/read-and-serve.d.ts +1 -1
  37. package/lib/types/session-view.d.ts +25 -31
  38. package/lib/types/store/index.d.ts +25 -0
  39. package/lib/types/workspace-context.d.ts +23 -0
  40. package/lib/workspace-context.js +44 -0
  41. package/lib/write-hook.js +2 -1
  42. package/package.json +1 -1
package/lib/hash-store.js CHANGED
@@ -19,7 +19,7 @@ import { dirname, join } from "node:path";
19
19
  import { DatabaseSync } from "node:sqlite";
20
20
  import { hashStorePath } from "./store-tenancy.js";
21
21
  import { onStoreOpen, setStoresGetter } from "./store-lifecycle.js";
22
- import { workspaceCwd } from "./workspace.js";
22
+ import { workspaceCwd } from "./workspace-context.js";
23
23
  import { errCode, splitLines } from "./utils.js";
24
24
  import { initHasher, contentChecksum, HASH_RE, CANON_VERSION, } from "./hashline/hash-assign.js";
25
25
  import { HASH_STORE_VERSION, HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS, } from "./constants.js";
@@ -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
  },
@@ -2,25 +2,23 @@
2
2
  * AnchorPipeline — deep module owning the anchor autofix chain.
3
3
  *
4
4
  * Single ordering invariant (private):
5
- * swapReversed → stripBare → stripDiff → valEdit → boundaryDups splice → valEdit → verifyServed → resToSpan
5
+ * swapReversed → stripBare → stripDiff → valEdit → verifyServed → resToSpan
6
6
  *
7
- * Detection (valEdit → boundaryDups[]) and correction (splice + second valEdit)
8
- * were split across resolve.ts / apply.ts with an implicit coupling.
9
- * This seam co-locates that invariant. Public surface is two functions:
7
+ * This seam co-locates the ordering invariant. Public surface is two functions:
10
8
  * resEdit — pre-validation (tool-layer, no file state)
11
9
  * applyEdit — full pipeline (file + hashes + served verification)
12
10
  *
13
11
  * Private to this seam (not re-exported): stripBarePrefixes, stripDiffPrefixes,
14
- * swapReversedRanges, valEdit, boundaryDups helpers, warnUnicodeEsc, findNewEdge,
12
+ * swapReversedRanges, valEdit, warnUnicodeEsc,
15
13
  * resAnchorFromMap, assertAligned, etc. They remain exported from resolve.ts
16
14
  * for backwards compat but are marked @internal and should be imported via this
17
15
  * module only.
18
16
  *
19
17
  * @module dsh-better-edit/hashline/anchor-pipeline
20
18
  */
21
- import { abortIf, splitLines, rejectUnknownFields, firstNonEmptyIndex, lastNonEmptyIndex, clipLine } from "../utils.js";
19
+ import { abortIf, splitLines, rejectUnknownFields, clipLine } from "../utils.js";
22
20
  import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HASH_SEP, ANCHOR_LEN, ALPH_RE, canon, lineHashesPure, getCanonForHash, rememberHashCanon } from "./hash-assign.js";
23
- import { recordServed, servedPositionsOf } from "../served-store.js";
21
+ import { recordServed, servedPositionsOf } from "../session-view.js";
24
22
  import { SERVED_ECHO_CAP } from "../constants.js";
25
23
  import { NEW_CONTENT_NOT_STRING_MSG } from "../constants.js";
26
24
  function diagRef(ref) {
@@ -281,126 +279,10 @@ function swapReversedRanges(edit, fileHashes, warnings) {
281
279
  warnings.push(`[E_BAD_OP] reversed remove_from/remove_to (${startRef.hash} after ${endRef.hash}); swapped.`);
282
280
  return { ...edit, hash_bounds: [endRef, startRef] };
283
281
  }
284
- function trailingDups(contentLines, fileLines, endLine) {
285
- const start = lastNonEmptyIndex(contentLines);
286
- if (start < 0)
287
- return [];
288
- const dups = [];
289
- const maxK = Math.min(start + 1, fileLines.length - endLine);
290
- for (let k = 0; k < maxK; k++) {
291
- if (contentLines[start - k] !== fileLines[endLine + k])
292
- break;
293
- dups.push({ kind: "trailing", replacementLineIndex: start - k });
294
- }
295
- return dups;
296
- }
297
- function leadingDups(contentLines, fileLines, startLine) {
298
- const start = firstNonEmptyIndex(contentLines);
299
- if (start < 0)
300
- return [];
301
- const dups = [];
302
- const maxK = Math.min(contentLines.length - start, startLine - 1);
303
- for (let k = 0; k < maxK; k++) {
304
- if (contentLines[start + k] !== fileLines[startLine - 2 - k])
305
- break;
306
- dups.push({ kind: "leading", replacementLineIndex: start + k });
307
- }
308
- return dups;
309
- }
310
- function sectionIsUnique(canonLines, start, length) {
311
- let count = 0;
312
- for (let i = 0; i + length <= canonLines.length; i++) {
313
- let k = 0;
314
- while (k < length && canonLines[i + k] === canonLines[start + k])
315
- k++;
316
- if (k < length)
317
- continue;
318
- count++;
319
- if (count > 1)
320
- return false;
321
- }
322
- return true;
323
- }
324
- function firstNewAfterDups(contentLines, rangeLines, canonLines, endLine) {
325
- const firstNew = findNewEdge(contentLines, rangeLines, false);
326
- if (!firstNew)
327
- return [];
328
- const maxK = Math.min(contentLines.length - firstNew.index, canonLines.length - endLine);
329
- let runLen = 0;
330
- while (runLen < maxK &&
331
- canon(contentLines[firstNew.index + runLen]) ===
332
- canonLines[endLine + runLen]) {
333
- runLen++;
334
- }
335
- if (runLen === 0 || !sectionIsUnique(canonLines, endLine, runLen))
336
- return [];
337
- const dups = [];
338
- for (let k = 0; k < runLen; k++) {
339
- dups.push({
340
- kind: "first-new-after",
341
- replacementLineIndex: firstNew.index + k,
342
- });
343
- }
344
- return dups;
345
- }
346
- function lastNewBeforeDups(contentLines, rangeLines, canonLines, startLine) {
347
- const lastNew = findNewEdge(contentLines, rangeLines, true);
348
- if (!lastNew)
349
- return [];
350
- const maxK = Math.min(lastNew.index + 1, startLine - 1);
351
- let runLen = 0;
352
- while (runLen < maxK &&
353
- canon(contentLines[lastNew.index - runLen]) ===
354
- canonLines[startLine - 2 - runLen]) {
355
- runLen++;
356
- }
357
- if (runLen === 0)
358
- return [];
359
- const sectionStart = startLine - 1 - runLen;
360
- if (!sectionIsUnique(canonLines, sectionStart, runLen))
361
- return [];
362
- const dups = [];
363
- for (let k = 0; k < runLen; k++) {
364
- dups.push({
365
- kind: "last-new-before",
366
- replacementLineIndex: lastNew.index - k,
367
- });
368
- }
369
- return dups;
370
- }
371
- function canonCounts(lines) {
372
- const counts = new Map();
373
- for (const line of lines) {
374
- const key = canon(line);
375
- counts.set(key, (counts.get(key) ?? 0) + 1);
376
- }
377
- return counts;
378
- }
379
282
  /** @internal — private to anchor-pipeline seam */
380
- export function findNewEdge(contentLines, rangeLines, fromEnd) {
381
- const multiset = canonCounts(rangeLines);
382
- const step = fromEnd ? -1 : 1;
383
- const start = fromEnd ? contentLines.length - 1 : 0;
384
- for (let i = start; i >= 0 && i < contentLines.length; i += step) {
385
- const line = contentLines[i];
386
- if (line.length === 0)
387
- continue;
388
- const key = canon(line);
389
- const count = multiset.get(key) ?? 0;
390
- if (count > 0) {
391
- multiset.set(key, count - 1);
392
- }
393
- else {
394
- return { index: i, line };
395
- }
396
- }
397
- return undefined;
398
- }
399
- /** @internal — private to anchor-pipeline seam: detection + boundaryDups belongs to AnchorPipeline ordering */
400
283
  function valEdit(edit, fileLines, fileHashes, warnings, signal) {
401
284
  assertAligned(fileLines, fileHashes, "valEdit");
402
285
  const mismatches = [];
403
- const boundaryDups = [];
404
286
  const hashIndex = new Map();
405
287
  for (let i = 0; i < fileHashes.length; i++) {
406
288
  const h = fileHashes[i];
@@ -430,24 +312,21 @@ function valEdit(edit, fileLines, fileHashes, warnings, signal) {
430
312
  if (endMismatch && endMismatch.kind === "not_found")
431
313
  endMismatch.context = startResolved;
432
314
  }
433
- return { resolved: undefined, mismatches, boundaryDups };
315
+ return { resolved: undefined, mismatches };
434
316
  }
435
317
  if (startResolved.line > endResolved.line) {
436
318
  throw new Error(`[E_BAD_OP] Range start line ${startResolved.line} must be <= end line ${endResolved.line} (anchors ${edit.hash_bounds[0].hash} and ${edit.hash_bounds[1].hash}).`);
437
319
  }
438
320
  const endLine = endResolved.line;
439
- const rangeLines = fileLines.slice(startResolved.line - 1, endLine);
440
- const canonLines = fileLines.map((line) => canon(line));
441
- boundaryDups.push(...trailingDups(edit.content_lines, fileLines, endLine), ...leadingDups(edit.content_lines, fileLines, startResolved.line), ...firstNewAfterDups(edit.content_lines, rangeLines, canonLines, endLine), ...lastNewBeforeDups(edit.content_lines, rangeLines, canonLines, startResolved.line));
442
321
  return {
443
322
  resolved: {
444
323
  content_lines: edit.content_lines,
445
324
  hash_bounds: [startResolved, endResolved],
446
325
  },
447
326
  mismatches,
448
- boundaryDups,
449
327
  };
450
328
  }
329
+ export function findNewEdge() { return undefined; }
451
330
  export { warnUnicodeEsc };
452
331
  export class ServedRejectionError extends Error {
453
332
  code;
@@ -513,6 +392,11 @@ function paginationHint(nextOffset, more) {
513
392
  export function verifyServedRange(args) {
514
393
  const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath, } = args;
515
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;
516
400
  let isHealed = false;
517
401
  for (let i = 0; i < fileHashes.length; i++) {
518
402
  const h = fileHashes[i];
@@ -533,6 +417,28 @@ export function verifyServedRange(args) {
533
417
  ? `\n${paginationHint(startLine + echoRows.length, totalLen - echoRows.length)}`
534
418
  : "";
535
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
+ }
536
442
  const startPositions = servedPositionsOf(served, startHash);
537
443
  const endPositions = servedPositionsOf(served, endHash);
538
444
  const currentLen = endLine - startLine + 1;
@@ -771,6 +677,48 @@ export function verifyServedRange(args) {
771
677
  });
772
678
  }
773
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
+ }
774
722
  for (let k = 0; k < servedLen; k++) {
775
723
  if (served[from + k] !== fileHashes[startLine - 1 + k]) {
776
724
  const offendingLine = startLine + k;
@@ -869,54 +817,20 @@ function assemble(content, span, signal) {
869
817
  abortIf(signal);
870
818
  return (content.slice(0, span.start) + span.replacement + content.slice(span.end));
871
819
  }
872
- export function applyEdit(content, edit, signal, precomputedHashes, filePath, served) {
820
+ export function applyEdit(content, edit, signal, precomputedHashes, filePath, served, servedCanons, tombstone, epochSnapshotId, curSnapshotId, strictPos) {
873
821
  abortIf(signal);
874
822
  const lineIndex = buildIdx(content);
875
823
  const fileHashes = precomputedHashes ?? lineHashesPure(content);
876
824
  const warnings = [];
877
825
  const rangeFixed = swapReversedRanges(edit, fileHashes, warnings);
878
826
  const prefixFixed = stripDiffPrefixes(stripBarePrefixes(rangeFixed, fileHashes, warnings), warnings);
879
- const { resolved: initialResolved, mismatches, boundaryDups, } = valEdit(prefixFixed, lineIndex.fileLines, fileHashes, warnings, signal);
827
+ const { resolved: initialResolved, mismatches, } = valEdit(prefixFixed, lineIndex.fileLines, fileHashes, warnings, signal);
880
828
  if (mismatches.length || !initialResolved) {
881
829
  const { message, servedRows } = fmtMismatchWithServes(mismatches, lineIndex.fileLines, fileHashes, filePath);
882
830
  throw new AnchorMismatchError(message, servedRows);
883
831
  }
884
832
  warnUnicodeEsc(prefixFixed, warnings);
885
- let resolved = initialResolved;
886
- let autoFixes;
887
- if (boundaryDups.length > 0) {
888
- autoFixes = [];
889
- const correctedEdit = {
890
- ...prefixFixed,
891
- content_lines: [...prefixFixed.content_lines],
892
- };
893
- const seen = new Set();
894
- const uniqueDups = [];
895
- for (const dup of boundaryDups) {
896
- if (seen.has(dup.replacementLineIndex))
897
- continue;
898
- seen.add(dup.replacementLineIndex);
899
- uniqueDups.push(dup);
900
- }
901
- const dupsByIndex = uniqueDups.sort((a, b) => b.replacementLineIndex - a.replacementLineIndex);
902
- for (const dup of dupsByIndex) {
903
- const idx = dup.replacementLineIndex;
904
- if (idx < 0 || idx >= correctedEdit.content_lines.length)
905
- continue;
906
- const removed = correctedEdit.content_lines.splice(idx, 1)[0];
907
- autoFixes.push({
908
- kind: dup.kind,
909
- removedLine: removed,
910
- removedLineIndex: idx,
911
- });
912
- }
913
- const correctedResult = valEdit(correctedEdit, lineIndex.fileLines, fileHashes, warnings, signal);
914
- if (correctedResult.mismatches.length || !correctedResult.resolved) {
915
- const { message, servedRows } = fmtMismatchWithServes(correctedResult.mismatches, lineIndex.fileLines, fileHashes, filePath);
916
- throw new AnchorMismatchError(message, servedRows);
917
- }
918
- resolved = correctedResult.resolved;
919
- }
833
+ const resolved = initialResolved;
920
834
  if (served) {
921
835
  const startLineEcho = resolved.hash_bounds[0].line;
922
836
  const rawEcho = findEditHashEcho(edit.content_lines, served, startLineEcho);
@@ -940,6 +854,11 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
940
854
  fileHashes,
941
855
  fileLines: lineIndex.fileLines,
942
856
  filePath,
857
+ servedCanons,
858
+ tombstone,
859
+ epochSnapshotId,
860
+ curSnapshotId,
861
+ strictPos,
943
862
  });
944
863
  }
945
864
  const spanResult = resToSpan(resolved, content, lineIndex);
@@ -965,7 +884,6 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
965
884
  lastChangedLine: changed?.lastChangedLine,
966
885
  range: resolvedRange(resolved),
967
886
  ...(warnings.length ? { warnings } : {}),
968
- ...(autoFixes ? { autoFixes } : {}),
969
887
  };
970
888
  }
971
889
  function resolvedRange(resolved) {
@@ -1019,3 +937,13 @@ export function changedRange(original, result) {
1019
937
  lastChangedLine: Math.max(first, lastRes) + 1,
1020
938
  };
1021
939
  }
940
+ // ---------------------------------------------------------------------------
941
+ // Sealed seam — single public entry for hashline (Candidate 5)
942
+ // HashAssign allocation + hash persistence re-exported here so callers import
943
+ // only from anchor-pipeline. Private modules (hash-assign, hash, hasher,
944
+ // alphabet, pure, parse, apply, resolve, served) are @internal and guarded
945
+ // by biome noRestrictedImports. Deleting this re-export block would scatter
946
+ // the hashline surface again — it concentrates (deep).
947
+ // ---------------------------------------------------------------------------
948
+ export { HASH_RE, HASH_CLASS, HASH_SEP, ANCHOR_LEN, ALPH_RE, ALPH, HASH_LEN, HASH_SPACE, MAX_HASH_LINES, HASH_PROBE_STRIDE, CANON_VERSION, canon, lineHashesPure, mapStableHashes, initHasher, contentChecksum, getCanonForHash, rememberHashCanon, } from "./hash-assign.js";
949
+ export { lineHashes } from "./hash.js";