dsh-better-edit 1.2.4 → 1.2.5

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 (97) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/lib/domain-errors.js +11 -9
  3. package/lib/edit-mode.js +11 -0
  4. package/lib/encoding.js +2 -0
  5. package/lib/file-encoding-state.js +42 -25
  6. package/lib/file-view.js +26 -205
  7. package/lib/fs-bridge.js +14 -49
  8. package/lib/hashline/anchor-pipeline.js +8 -499
  9. package/lib/hashline/hash-assign.js +55 -4
  10. package/lib/hashline/index.js +5 -2
  11. package/lib/hashline/served-evidence.js +531 -0
  12. package/lib/index.js +176 -47
  13. package/lib/mutation/engine.js +10 -13
  14. package/lib/mutation.js +36 -100
  15. package/lib/noop-guard.js +24 -39
  16. package/lib/paths.js +9 -5
  17. package/lib/read-and-serve.js +51 -53
  18. package/lib/reclaim.js +65 -0
  19. package/lib/self-heal.js +6 -10
  20. package/lib/session-view.js +61 -21
  21. package/lib/store/index.js +14 -14
  22. package/lib/store-config.js +4 -5
  23. package/lib/store-lifecycle.js +1 -1
  24. package/lib/tool-edit.js +0 -3
  25. package/lib/tool-read.js +2 -8
  26. package/lib/tool-str-replace-editor.js +3 -10
  27. package/lib/tool-undo.js +5 -13
  28. package/lib/types/contract.d.ts +2 -1
  29. package/lib/types/domain-errors.d.ts +8 -9
  30. package/lib/types/edit-mode.d.ts +11 -0
  31. package/lib/types/encoding.d.ts +1 -0
  32. package/lib/types/file-encoding-state.d.ts +10 -10
  33. package/lib/types/file-view.d.ts +18 -56
  34. package/lib/types/hashline/anchor-pipeline.d.ts +6 -128
  35. package/lib/types/hashline/hash-assign.d.ts +40 -0
  36. package/lib/types/hashline/index.d.ts +6 -4
  37. package/lib/types/hashline/served-evidence.d.ts +152 -0
  38. package/lib/types/mutation/engine.d.ts +4 -2
  39. package/lib/types/mutation.d.ts +9 -57
  40. package/lib/types/noop-guard.d.ts +2 -33
  41. package/lib/types/paths.d.ts +0 -1
  42. package/lib/types/reclaim.d.ts +36 -0
  43. package/lib/types/session-view.d.ts +28 -8
  44. package/lib/types/store/index.d.ts +12 -11
  45. package/lib/types/store-config.d.ts +1 -1
  46. package/lib/types/store-lifecycle.d.ts +12 -2
  47. package/lib/types/tool-edit.d.ts +0 -2
  48. package/lib/types/tool-read.d.ts +0 -5
  49. package/lib/types/tool-str-replace-editor.d.ts +0 -6
  50. package/lib/types/tool-undo.d.ts +0 -5
  51. package/package.json +3 -2
  52. package/lib/drift.js +0 -5
  53. package/lib/dsh-context.js +0 -5
  54. package/lib/edit-engine.js +0 -7
  55. package/lib/edit-normalize.js +0 -9
  56. package/lib/edit-pipeline.js +0 -6
  57. package/lib/file-kind.js +0 -6
  58. package/lib/file-reader.js +0 -6
  59. package/lib/guidance/index.js +0 -8
  60. package/lib/hashline/alphabet.js +0 -2
  61. package/lib/hashline/apply.js +0 -2
  62. package/lib/hashline/hasher.js +0 -2
  63. package/lib/hashline/parse.js +0 -2
  64. package/lib/hashline/pure.js +0 -2
  65. package/lib/hashline/resolve.js +0 -3
  66. package/lib/hashline/served.js +0 -2
  67. package/lib/preview-controller.js +0 -65
  68. package/lib/read-render.js +0 -6
  69. package/lib/schema.js +0 -24
  70. package/lib/served-store.js +0 -5
  71. package/lib/tool-batch-edit.js +0 -190
  72. package/lib/truncate.js +0 -6
  73. package/lib/types/drift.d.ts +0 -5
  74. package/lib/types/dsh-context.d.ts +0 -5
  75. package/lib/types/edit-engine.d.ts +0 -7
  76. package/lib/types/edit-normalize.d.ts +0 -1
  77. package/lib/types/edit-pipeline.d.ts +0 -6
  78. package/lib/types/file-kind.d.ts +0 -6
  79. package/lib/types/file-reader.d.ts +0 -6
  80. package/lib/types/guidance/index.d.ts +0 -8
  81. package/lib/types/hashline/alphabet.d.ts +0 -1
  82. package/lib/types/hashline/apply.d.ts +0 -1
  83. package/lib/types/hashline/hasher.d.ts +0 -1
  84. package/lib/types/hashline/parse.d.ts +0 -1
  85. package/lib/types/hashline/pure.d.ts +0 -1
  86. package/lib/types/hashline/resolve.d.ts +0 -1
  87. package/lib/types/hashline/served.d.ts +0 -1
  88. package/lib/types/preview-controller.d.ts +0 -33
  89. package/lib/types/read-render.d.ts +0 -6
  90. package/lib/types/schema.d.ts +0 -25
  91. package/lib/types/served-store.d.ts +0 -5
  92. package/lib/types/tool-batch-edit.d.ts +0 -25
  93. package/lib/types/truncate.d.ts +0 -6
  94. package/lib/types/validation.d.ts +0 -6
  95. package/lib/types/workspace.d.ts +0 -5
  96. package/lib/validation.js +0 -6
  97. package/lib/workspace.js +0 -5
@@ -14,14 +14,16 @@
14
14
  * for backwards compat but are marked @internal and should be imported via this
15
15
  * module only.
16
16
  *
17
+ * The served-evidence verdict lives in served-evidence.ts (ADR-0037): this seam
18
+ * calls `verifyServedRange` and owns nothing it decides.
19
+ *
17
20
  * @module dsh-better-edit/hashline/anchor-pipeline
18
21
  */
19
22
  import { abortIf, splitLines, rejectUnknownFields, clipLine } from "../utils.js";
20
- import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HASH_SEP, ANCHOR_LEN, ALPH_RE, canon, lineHashesPure, } from "./hash-assign.js";
21
- import { servedPositionsOf } from "../session-view.js";
22
- import { SERVED_ECHO_CAP } from "../constants.js";
23
+ import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HASH_SEP, ANCHOR_LEN, ALPH_RE, lineHashesPure, } from "./hash-assign.js";
23
24
  import { NEW_CONTENT_NOT_STRING_MSG, NEW_CONTENT_BODY } from "../constants.js";
24
25
  import { DomainError, formatWarning, numericAnchorNote } from "../domain-errors.js";
26
+ import { fmtServedRows, verifyServedRange } from "./served-evidence.js";
25
27
  import { buildServedEditPrefixNote, findNeverServedAnchorShapes, findServedPrefixMismatches, } from "./served-guard.js";
26
28
  function diagRef(ref) {
27
29
  const trimmed = ref.trim();
@@ -332,37 +334,6 @@ function valEdit(edit, fileLines, fileHashes, _warnings, signal) {
332
334
  mismatches,
333
335
  };
334
336
  }
335
- export class ServedRejectionError extends DomainError {
336
- code;
337
- unservedKind;
338
- constructor(opts) {
339
- if (opts.code === "E_STALE_RANGE") {
340
- super("E_STALE_RANGE", {
341
- headline: opts.headline,
342
- servedRows: opts.servedRows,
343
- servedBlock: opts.servedBlock,
344
- ...(opts.cause !== undefined ? { cause: opts.cause } : {}),
345
- ...(opts.firstOffendingLine !== undefined
346
- ? { firstOffendingLine: opts.firstOffendingLine }
347
- : {}),
348
- });
349
- }
350
- else {
351
- super("E_UNSERVED_RANGE", {
352
- headline: opts.headline,
353
- servedRows: opts.servedRows,
354
- servedBlock: opts.servedBlock,
355
- unservedKind: opts.unservedKind,
356
- ...(opts.firstOffendingLine !== undefined
357
- ? { firstOffendingLine: opts.firstOffendingLine }
358
- : {}),
359
- });
360
- }
361
- this.name = "ServedRejectionError";
362
- this.code = opts.code;
363
- this.unservedKind = opts.code === "E_UNSERVED_RANGE" ? opts.unservedKind : undefined;
364
- }
365
- }
366
337
  // F8: narrowed to the codes the reject-and-serve branches actually handle —
367
338
  // the class's meaning is type-enforced instead of carried by convention.
368
339
  export class AnchorMismatchError extends DomainError {
@@ -410,470 +381,6 @@ export class EditHashEchoError extends AnchorMismatchError {
410
381
  this.name = "EditHashEchoError";
411
382
  }
412
383
  }
413
- export function buildRangeEcho(startLine, endLine, fileHashes) {
414
- const total = endLine - startLine + 1;
415
- const shown = Math.min(total, SERVED_ECHO_CAP);
416
- const rows = [];
417
- for (let ln = startLine; ln < startLine + shown; ln++) {
418
- rows.push({ position: ln - 1, hash: fileHashes[ln - 1] });
419
- }
420
- return rows;
421
- }
422
- export function fmtServedRows(rows, fileLines) {
423
- return rows.map((row) => `${row.hash}${HASH_SEP}${fileLines[row.position] ?? ""}`).join("\n");
424
- }
425
- function paginationHint(nextOffset, more) {
426
- return `[... ${more} more — read offset=${nextOffset}]`;
427
- }
428
- function servedEvidenceRoute(leaseSource) {
429
- return leaseSource === undefined ? { kind: "mirror" } : { kind: "leased", source: leaseSource };
430
- }
431
- /**
432
- * Question 1: does this route owe the never-served interior scan (upstream ADR-0024 decision 2)?
433
- * On the mirror route the mirror is the only evidence, so an interior hole rejects there.
434
- * The leased route does not scan: the identity gate owns verification — its two boundary
435
- * leases pin the span's extent, so an interior `null` carries no identity to verify and
436
- * `acceptsInteriorHole` admits it (decision 1, adopted; supersedes ADR-0019's decline).
437
- * Rejecting the hole on the scan would shadow the gate and keep taxing correct edits upstream
438
- * measured at 8/242 calls.
439
- */
440
- function owesInteriorScan(route) {
441
- return route.kind === "mirror";
442
- }
443
- /**
444
- * Question 2: is slot `k` of a `servedLen`-row gate window an interior hole the leased
445
- * identity gate accepts? Upstream ADR-0024 decision 1 (adopted; supersedes ADR-0019's
446
- * decline) narrows informed destruction to the boundaries: an unread interior row has no
447
- * identity to check, and the two verified boundary leases already fix the span's extent, so
448
- * refusing it only taxed a correct edit. A `null` boundary is the named anchor itself —
449
- * unverifiable by construction — so it keeps the fail-closed diagnosis. The mirror route
450
- * answers uniformly: `owesInteriorScan` has already rejected its holes before the gate can
451
- * be reached.
452
- */
453
- function acceptsInteriorHole(route, k, servedLen) {
454
- return route.kind === "leased" && k !== 0 && k !== servedLen - 1;
455
- }
456
- /**
457
- * Question 3: does this slot take part in the position comparison? On the leased route a
458
- * `null` slot carries no evidence to compare and the identity gate has already adjudicated
459
- * the window (accepting an interior hole per upstream ADR-0024 decision 1); failing the
460
- * position check on it here would re-shadow the gate. The non-leased route rejects its holes
461
- * in the interior scan above (decision 2 keeps its interior diagnosis) and compares every
462
- * slot as before.
463
- */
464
- function checksPosition(route, slot) {
465
- return route.kind !== "leased" || slot !== null;
466
- }
467
- /**
468
- * Refuses anchors the lease seam cannot place: the session holds no lease for them in this file.
469
- * Deterministic precedence, one condition per code — a lease held for ANOTHER file
470
- * (`E_FOREIGN_ANCHOR`) wins over holding no lease anywhere (`E_UNKNOWN_ANCHOR`). Neither
471
- * rejection serves rows: with no lease for this file no range can be identified, so there is
472
- * nothing trustworthy to retry with (port of upstream b92e0ec:src/hashline/lease-resolve.ts:87-118).
473
- */
474
- function throwUnknownOrForeign(args) {
475
- const path = args.filePath ?? "this file";
476
- const refused = [...new Set(args.refused)];
477
- const homes = [...new Set(refused.flatMap((anchor) => args.source.anchorHomes(anchor)))].sort();
478
- if (homes.length > 0) {
479
- throw new DomainError("E_FOREIGN_ANCHOR", { path, anchors: refused, homes });
480
- }
481
- throw new DomainError("E_UNKNOWN_ANCHOR", { path, anchors: refused });
482
- }
483
- /**
484
- * Per-lease line-identity decision (port of upstream b92e0ec:src/hashline/resolve.ts:95-110):
485
- * a retired lease, or a live lease whose `line_id` has no coordinate in the buffer being
486
- * edited, is `stale`; otherwise the decision names the rebased line.
487
- */
488
- function lineIdentityDecision(lease, source) {
489
- if (lease.retiredAt !== null)
490
- return { kind: "stale" };
491
- const rebased = source.rebasedLineOf(lease.lineId);
492
- if (rebased === undefined)
493
- return { kind: "stale" };
494
- return { kind: "line", line: rebased };
495
- }
496
- /**
497
- * The leased-route boundary identity interception (port of upstream
498
- * b92e0ec:src/hashline/lease-resolve.ts:120-200), running before the served-window gates:
499
- * a boundary anchor with no lease is lost identity — unknown or foreign, never a content
500
- * question. A stale boundary serves rows ONLY when exactly one bound is stale AND the survivor
501
- * is live and unshifted (its rebased coordinate equals its served coordinate — evidence no
502
- * shift occurred): that one case rejects with `E_UNVERIFIED_RANGE`, the named window echoed as
503
- * a fresh read; every other stale case rejects with `E_TARGET_LOST`, carrying no rows.
504
- * The named coordinates are lease-derived (`servedLineNumber`) only — content placement never
505
- * names a window for a retired bound.
506
- */
507
- function interceptLeaseBoundaries(args) {
508
- const { fileHashes, fileLines, leaseSource } = args;
509
- const fromLease = leaseSource.leaseFor(args.startHash);
510
- const toLease = leaseSource.leaseFor(args.endHash);
511
- if (fromLease === undefined || toLease === undefined) {
512
- throwUnknownOrForeign({
513
- ...(args.filePath !== undefined ? { filePath: args.filePath } : {}),
514
- refused: [
515
- ...(fromLease === undefined ? [args.startHash] : []),
516
- ...(toLease === undefined ? [args.endHash] : []),
517
- ],
518
- source: leaseSource,
519
- });
520
- }
521
- const fromDecision = lineIdentityDecision(fromLease, leaseSource);
522
- const toDecision = lineIdentityDecision(toLease, leaseSource);
523
- if (fromDecision.kind === "stale" || toDecision.kind === "stale") {
524
- const fromLiveUnshifted = fromDecision.kind === "line" && fromDecision.line === fromLease.servedLineNumber;
525
- const toLiveUnshifted = toDecision.kind === "line" && toDecision.line === toLease.servedLineNumber;
526
- const staleServedLine = fromDecision.kind === "stale" ? fromLease.servedLineNumber : toLease.servedLineNumber;
527
- const exactlyOneStale = (fromDecision.kind === "stale") !== (toDecision.kind === "stale");
528
- const survivorLiveUnshifted = fromDecision.kind === "stale" ? toLiveUnshifted : fromLiveUnshifted;
529
- if (exactlyOneStale && survivorLiveUnshifted) {
530
- const rawStart = Math.min(fromLease.servedLineNumber, toLease.servedLineNumber);
531
- const rawEnd = Math.max(fromLease.servedLineNumber, toLease.servedLineNumber);
532
- const len = fileHashes.length;
533
- const startLine = Math.max(1, rawStart);
534
- const endLine = Math.min(len, rawEnd);
535
- // Collapsed-window guard: fail closed to `E_TARGET_LOST` when the named window
536
- // collapses (e.g. served startLine 10 against a 4-line file) or misses the file.
537
- if (len > 0 && startLine <= endLine && rawEnd >= 1 && rawStart <= len) {
538
- const servedRows = buildRangeEcho(startLine, endLine, fileHashes);
539
- const totalLen = endLine - startLine + 1;
540
- const tail = servedRows.length < totalLen
541
- ? `\n${paginationHint(startLine + servedRows.length, totalLen - servedRows.length)}`
542
- : "";
543
- throw new DomainError("E_UNVERIFIED_RANGE", {
544
- servedRows,
545
- servedBlock: fmtServedRows(servedRows, fileLines) + tail,
546
- cause: "retirement",
547
- firstOffendingLine: staleServedLine,
548
- });
549
- }
550
- }
551
- throw new DomainError("E_TARGET_LOST", {
552
- servedLine: staleServedLine,
553
- ...(args.filePath !== undefined ? { path: args.filePath } : {}),
554
- cause: "retirement",
555
- });
556
- }
557
- }
558
- /**
559
- * The identity gate for a served span (obligation (c)) — replaces the unconditional position check
560
- * when a lease source is present.
561
- *
562
- * A **benign shift** — the intended line's bytes are unchanged and only its position moved (exterior
563
- * drift above the served span) — passes: the served anchor's live lease resolves to the rebased
564
- * coordinate the edit targets, so the edit applies there with no re-read. A **look-alike rebind** —
565
- * the named line was deleted and a different line now holds the same bytes — rejects: the leased
566
- * `line_id` no longer lives at the rebased coordinate, or is gone from the buffer's identity map
567
- * entirely, so the anchor cannot be reconciled with the line it named.
568
- *
569
- * Fail-closed arms, all `E_STALE_RANGE` with the echo rows: a window length that changed because
570
- * an external insert/delete landed strictly inside the span, a truncated mirror slot (no served row
571
- * left to reconcile), a never-served boundary row (the named anchor itself, unverifiable without a
572
- * served row), an unleased served row (a serve predating lease granting), a retired lease, or a
573
- * coordinate no leased identity occupies. An interior mirror row the span never served (`null`) is
574
- * accepted (upstream ADR-0024 decision 1, adopted; supersedes ADR-0019's decline): it carries no
575
- * identity to verify and the two boundary leases plus the window-length check pin the span's extent.
576
- * Throwing happens before any write, so a rejection leaves the file byte-identical.
577
- */
578
- export function verifyRebasedSpan(args) {
579
- const { served, route, echo, echoRows, where } = args;
580
- const leaseSource = route.source;
581
- const servedLen = args.servedEnd - args.servedStart + 1;
582
- const rebasedLen = args.rebasedEnd - args.rebasedStart + 1;
583
- if (rebasedLen !== servedLen) {
584
- throw new ServedRejectionError({
585
- code: "E_STALE_RANGE",
586
- headline: `served span (${servedLen} lines) no longer matches the rebased range (${rebasedLen} lines)${where}.`,
587
- servedBlock: echo,
588
- firstOffendingLine: args.rebasedStart,
589
- servedRows: echoRows,
590
- cause: "served-range staleness",
591
- });
592
- }
593
- for (let k = 0; k < servedLen; k++) {
594
- const servedAnchor = served[args.servedStart - 1 + k];
595
- const currentLine = args.rebasedStart + k;
596
- // WHY: the served window can come from the leases' own `servedLineNumber` because a truncated
597
- // serve dropped the mirror rows it no longer covers: the lease outlives the mirror. An
598
- // absent slot is that missing record, never "this line was never served", so the span
599
- // fails closed on the truth (the served record cannot be reconciled) and the current
600
- // range is served for a fresh read.
601
- if (servedAnchor === undefined) {
602
- throw new ServedRejectionError({
603
- code: "E_STALE_RANGE",
604
- headline: `line ${currentLine}${where} has no served mirror row left; the served window was truncated.`,
605
- servedBlock: echo,
606
- firstOffendingLine: currentLine,
607
- servedRows: echoRows,
608
- cause: "served-range staleness",
609
- });
610
- }
611
- if (servedAnchor === null) {
612
- // WHY: the interior-accept / boundary-reject split is the route's `acceptsInteriorHole`
613
- // decision (upstream ADR-0024 decision 1, adopted; supersedes ADR-0019's decline) — see
614
- // its doc for why an unread interior row passes and a `null` boundary keeps the
615
- // fail-closed diagnosis.
616
- if (!acceptsInteriorHole(route, k, servedLen)) {
617
- throw new ServedRejectionError({
618
- code: "E_STALE_RANGE",
619
- headline: `line ${currentLine}${where} was never served.`,
620
- servedBlock: echo,
621
- firstOffendingLine: currentLine,
622
- servedRows: echoRows,
623
- cause: "never-served",
624
- });
625
- }
626
- continue;
627
- }
628
- const lease = leaseSource.leaseFor(servedAnchor);
629
- if (lease === undefined) {
630
- throw new ServedRejectionError({
631
- code: "E_STALE_RANGE",
632
- headline: `line ${currentLine}${where} has no served line identity.`,
633
- servedBlock: echo,
634
- firstOffendingLine: currentLine,
635
- servedRows: echoRows,
636
- cause: "never-served",
637
- });
638
- }
639
- // WHY: two distinct diagnoses, one per condition: a terminal lease is a `retirement` — the
640
- // identity is gone and only a re-read revives it — while a live lease whose `lineId` no
641
- // longer sits at its expected coordinate is drift between the served record and the
642
- // rebased span.
643
- if (lease.retiredAt !== null) {
644
- throw new ServedRejectionError({
645
- code: "E_STALE_RANGE",
646
- headline: `line ${currentLine}${where} no longer resolves to the line identity it was served with.`,
647
- servedBlock: echo,
648
- firstOffendingLine: currentLine,
649
- servedRows: echoRows,
650
- cause: "retirement",
651
- });
652
- }
653
- if (leaseSource.rebasedLineOf(lease.lineId) !== currentLine) {
654
- throw new ServedRejectionError({
655
- code: "E_STALE_RANGE",
656
- headline: `line ${currentLine}${where} no longer resolves to the line identity it was served with.`,
657
- servedBlock: echo,
658
- firstOffendingLine: currentLine,
659
- servedRows: echoRows,
660
- cause: "served-range staleness",
661
- });
662
- }
663
- }
664
- }
665
- export function verifyServedRange(args) {
666
- const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath } = args;
667
- // The one route construction (obligation (c)): every leased/mirror decision below consults
668
- // this value, so the conjunction cannot drift site by site.
669
- const route = servedEvidenceRoute(args.leaseSource);
670
- const where = filePath ? ` in ${filePath}` : "";
671
- const retiredSet = args.retired ?? new Set();
672
- const servedCanons = args.servedCanons;
673
- const echoRows = buildRangeEcho(startLine, endLine, fileHashes);
674
- const totalLen = endLine - startLine + 1;
675
- const tail = echoRows.length < totalLen
676
- ? `\n${paginationHint(startLine + echoRows.length, totalLen - echoRows.length)}`
677
- : "";
678
- const echo = fmtServedRows(echoRows, fileLines) + tail;
679
- // Retired-anchor check for boundaries (whole-span S@3==S@3) — the freed-hash concept, named
680
- // `retired` here since ADR-0013 (ADR-0028 records the vocabulary ruling).
681
- // If hash was freed in this epoch, any reuse is stale even at same pos+same canon.
682
- // Early reject checks canon change to avoid false positive on same line re-read.
683
- if (retiredSet.has(startHash) || retiredSet.has(endHash)) {
684
- const retiredHash = retiredSet.has(startHash) ? startHash : endHash;
685
- if (servedCanons) {
686
- const pos = fileHashes.indexOf(retiredHash);
687
- if (pos >= 0) {
688
- const servedIdx = served.indexOf(retiredHash);
689
- const expected = servedIdx >= 0 ? servedCanons[servedIdx] : undefined;
690
- const actual = canon(fileLines[pos] ?? "");
691
- if (expected !== undefined && expected !== null && expected !== actual) {
692
- throw new ServedRejectionError({
693
- code: "E_STALE_RANGE",
694
- headline: `anchor "${retiredHash}" was freed since last full read (retired, canon changed from "${expected}" to "${actual}"). Re-read.`,
695
- servedBlock: echo,
696
- firstOffendingLine: pos + 1,
697
- servedRows: echoRows,
698
- });
699
- }
700
- }
701
- }
702
- }
703
- // The leased route resolves boundaries through the lease seam FIRST (upstream
704
- // b92e0ec:src/hashline/lease-resolve.ts:120-200): a missing or stale boundary lease rejects
705
- // before content placement can substitute a look-alike for the lost identity. The non-leased
706
- // route keeps mirror placement alone (upstream's non-leased analogue,
707
- // served-verification.ts:745, is the zero-position arm below).
708
- if (route.kind === "leased") {
709
- interceptLeaseBoundaries({
710
- startHash,
711
- endHash,
712
- fileHashes,
713
- fileLines,
714
- ...(filePath !== undefined ? { filePath } : {}),
715
- leaseSource: route.source,
716
- });
717
- }
718
- const startPositions = servedPositionsOf(served, startHash);
719
- const endPositions = servedPositionsOf(served, endHash);
720
- const currentLen = endLine - startLine + 1;
721
- let from;
722
- let to;
723
- // Exact-boundary rule (ADR-0018, superseding ADR-0004): each boundary anchor must have
724
- // EXACTLY one served position. Anything else leaves `from`/`to` undefined and rejects
725
- // below — there is no candidate-span search that could re-bind onto a look-alike line.
726
- if (startPositions.length === 1 && endPositions.length === 1) {
727
- from = Math.min(startPositions[0], endPositions[0]);
728
- to = Math.max(startPositions[0], endPositions[0]);
729
- }
730
- if (from === undefined || to === undefined) {
731
- const missing = [
732
- ...new Set([
733
- ...(startPositions.length === 0 ? [startHash] : []),
734
- ...(endPositions.length === 0 ? [endHash] : []),
735
- ]),
736
- ];
737
- if (missing.length > 0) {
738
- // A boundary anchor the mirror never placed was never served for this file: the
739
- // rejection carries no rows — with nothing served there is nothing trustworthy to
740
- // retry with, only a read restores grounding (port of upstream
741
- // b92e0ec:src/hashline/served-verification.ts:729-749).
742
- throw new DomainError("E_UNKNOWN_ANCHOR", {
743
- path: filePath ?? "this file",
744
- anchors: missing,
745
- });
746
- }
747
- const problems = [];
748
- if (startPositions.length > 1) {
749
- problems.push(`anchor_from "${startHash}" was served at ${startPositions.length} positions`);
750
- }
751
- if (endPositions.length > 1) {
752
- problems.push(`anchor_to "${endHash}" was served at ${endPositions.length} positions`);
753
- }
754
- throw new ServedRejectionError({
755
- code: "E_UNSERVED_RANGE",
756
- unservedKind: "boundary",
757
- headline: `cannot verify range against served state${where}: ${problems.join("; ")}. ` +
758
- `Each boundary anchor must have exactly one served position — no served span is searched ` +
759
- `for a look-alike line. A full read will re-sync the served mirror; the echoed range below ` +
760
- `is current content.`,
761
- servedBlock: echo,
762
- servedRows: echoRows,
763
- });
764
- }
765
- // The never-served interior scan is the mirror route's evidence rule (upstream ADR-0024
766
- // decision 2); the leased route skips it because the identity gate owns interior holes
767
- // there (decision 1) — the full rationale lives on `owesInteriorScan`.
768
- if (owesInteriorScan(route)) {
769
- for (let i = from; i <= to; i++) {
770
- if (served[i] === null) {
771
- throw new ServedRejectionError({
772
- code: "E_UNSERVED_RANGE",
773
- unservedKind: "interior",
774
- headline: `line ${i + 1}${where} was never served.`,
775
- servedBlock: echo,
776
- firstOffendingLine: i + 1,
777
- servedRows: echoRows,
778
- });
779
- }
780
- }
781
- }
782
- const servedLen = to - from + 1;
783
- if (servedLen !== currentLen) {
784
- throw new ServedRejectionError({
785
- code: "E_STALE_RANGE",
786
- headline: `served span (${servedLen} lines) no longer matches current range (${currentLen} lines)${where}. Re-read.`,
787
- servedBlock: echo,
788
- firstOffendingLine: startLine,
789
- servedRows: echoRows,
790
- });
791
- }
792
- // Position check or identity gate — the seam is opt-in (obligation (c)).
793
- //
794
- // With a lease source, identity decides: `verifyRebasedSpan` checks the whole served window by
795
- // the leases its anchors were served with, so a benign shift (same bytes, moved position —
796
- // exterior drift above the span) applies at its rebased coordinate with no re-read, while a
797
- // look-alike rebind (the named line was deleted and another line now holds its bytes) rejects.
798
- //
799
- // Without a lease source the unconditional position check below stands: identity only, never a
800
- // weaker position check. The pos-free route is REACHABLE on a normal session route (a windowed
801
- // read never pinned the epoch; a preview/no-store edit carries no leases), which is why this
802
- // fallback cannot be dropped.
803
- if (route.kind === "leased") {
804
- verifyRebasedSpan({
805
- served,
806
- servedStart: from + 1,
807
- servedEnd: to + 1,
808
- rebasedStart: startLine,
809
- rebasedEnd: endLine,
810
- route,
811
- echo,
812
- echoRows,
813
- where,
814
- });
815
- }
816
- else if (from !== startLine - 1) {
817
- throw new ServedRejectionError({
818
- code: "E_STALE_RANGE",
819
- headline: `anchor was served at line ${from + 1} but now resolves to line ${startLine}. Re-read.`,
820
- servedBlock: echo,
821
- firstOffendingLine: startLine,
822
- servedRows: echoRows,
823
- });
824
- }
825
- // Canon check for same-pos different content (collision)
826
- if (servedCanons) {
827
- for (let k = 0; k < servedLen; k++) {
828
- const expected = servedCanons[from + k];
829
- if (expected !== null && expected !== undefined) {
830
- const actual = canon(fileLines[startLine - 1 + k] ?? "");
831
- if (expected !== actual) {
832
- throw new ServedRejectionError({
833
- code: "E_STALE_RANGE",
834
- headline: `line ${startLine + k}${where} canon differs from served (expected "${expected}" vs actual "${actual}").`,
835
- servedBlock: echo,
836
- firstOffendingLine: startLine + k,
837
- servedRows: echoRows,
838
- });
839
- }
840
- }
841
- }
842
- }
843
- // Retired-anchor interior check (whole-span) — gated on canon inequality (fail-closed only for different canon)
844
- for (let k = 0; k < servedLen; k++) {
845
- const h = fileHashes[startLine - 1 + k];
846
- if (h && retiredSet.has(h)) {
847
- const expectedCanon = servedCanons?.[from + k] ?? undefined;
848
- const actualCanon = canon(fileLines[startLine - 1 + k] ?? "");
849
- if (expectedCanon !== undefined && expectedCanon !== null && expectedCanon !== actualCanon) {
850
- throw new ServedRejectionError({
851
- code: "E_STALE_RANGE",
852
- headline: `line ${startLine + k}${where} uses retired anchor "${h}" (freed since last full read, canon changed). Re-read.`,
853
- servedBlock: echo,
854
- firstOffendingLine: startLine + k,
855
- servedRows: echoRows,
856
- });
857
- }
858
- }
859
- }
860
- for (let k = 0; k < servedLen; k++) {
861
- // The leased route's `null` skip is `checksPosition`'s decision (the identity gate already
862
- // adjudicated the hole); the mirror route's holes rejected in the scan above.
863
- if (!checksPosition(route, served[from + k]))
864
- continue;
865
- if (served[from + k] !== fileHashes[startLine - 1 + k]) {
866
- const offendingLine = startLine + k;
867
- throw new ServedRejectionError({
868
- code: "E_STALE_RANGE",
869
- headline: `line ${offendingLine}${where} differs from what was served. Re-read.`,
870
- servedBlock: echo,
871
- firstOffendingLine: offendingLine,
872
- servedRows: echoRows,
873
- });
874
- }
875
- }
876
- }
877
384
  export function buildIdx(content) {
878
385
  const fileLines = splitLines(content);
879
386
  const lineStarts = [];
@@ -1120,7 +627,9 @@ export function fmtRegion(hashes, lines) {
1120
627
  if (hashes.length !== lines.length) {
1121
628
  throw new Error(`fmtRegion: hashes.length (${hashes.length}) must match lines.length (${lines.length}).`);
1122
629
  }
1123
- return lines.map((line, index) => `${hashes[index]}${HASH_SEP}${line}`).join("\n");
630
+ // One renderer (ADR-0037): the guard above is this entry point's own fail-loud invariant; the
631
+ // row kernel lives in served-evidence so the read echo and the region render cannot drift.
632
+ return fmtServedRows(hashes.map((hash, index) => ({ position: index, hash })), lines);
1124
633
  }
1125
634
  export function changedRange(original, result) {
1126
635
  if (original === result)
@@ -24,6 +24,8 @@ export function getH() {
24
24
  }
25
25
  const hasherP = xxhash()
26
26
  .then((h) => {
27
+ // SAFETY: `xxhash()` resolves the package's own hasher object, whose declaration types the
28
+ // wider lazy-loaded API surface; the assertion narrows it to the two methods `getH()` exposes.
27
29
  hasher = h;
28
30
  return hasher;
29
31
  })
@@ -69,6 +71,55 @@ export class AnchorSpaceExhaustedError extends DomainError {
69
71
  this.servedCount = servedCount;
70
72
  }
71
73
  }
74
+ /**
75
+ * The ONE anchor-space-exhaustion test, owned by the error's own module: "is this
76
+ * exhaustion?" (a typing question).
77
+ *
78
+ * WHY single: the classification lives beside the error it classifies, and no site keeps a private
79
+ * copy — the two translate blocks below ask exactly this question, and the promotion sites ask its
80
+ * strict subset (`isPromotableAnchorSpaceExhaustion`). Each of the five sites used to carry its own
81
+ * copy (or an inline variant) of the test; a rewording of the allocator's probe message in one copy
82
+ * would silently change a decision at the others, and the failure mode is a raw `Error` reaching
83
+ * the model instead of the typed refusal.
84
+ *
85
+ * Members: the typed `AnchorSpaceExhaustedError` (already translated), the allocator wording
86
+ * `nextZeroBit` raises when the probe wraps the whole space ("probing failed over"), and that
87
+ * same refusal's formatted headline ("Cannot allocate a unique hash anchor", which survives a
88
+ * re-wrap that costs the error its class).
89
+ */
90
+ export function isAnchorSpaceExhaustion(e) {
91
+ if (e instanceof AnchorSpaceExhaustedError)
92
+ return true;
93
+ return (e instanceof Error &&
94
+ (e.message.includes("probing failed over") || e.message.includes("Cannot allocate")));
95
+ }
96
+ /**
97
+ * Promotion's narrower question: is this an exhaustion that clearing retired anchors and
98
+ * retrying could actually cure?
99
+ *
100
+ * WHY a second predicate, not the one above: `isAnchorSpaceExhaustion` answers "is this
101
+ * exhaustion" — a typing question, asked by the two translate blocks that must turn any
102
+ * allocator wording into the typed `E_LARGE_FILE`. Promotion asks a different question, and the
103
+ * two answers differ on every refusal whose subject is the file's line count rather than the
104
+ * anchor space: exhaustion and the line cap are the same diagnosis (a file too long to hash),
105
+ * but promotion cannot out-grow the line cap, because the retry re-reads the same oversized file
106
+ * and throws the identical error — with this `(session, path)`'s retired anchors now cleared, so
107
+ * the failed read has also degraded its own stale-anchor checks. "Can promotion help?" is
108
+ * therefore the strict subset: the probe wrapping the whole space.
109
+ *
110
+ * The line cap is a capacity refusal, never an identity one, and its wording is not the hash-space
111
+ * one: `eLargeFileMsg` formats with `limitKind: "lines"` ("<path> has N lines, exceeding the
112
+ * N-line limit"), so `isAnchorSpaceExhaustion` already declines it; "Cannot allocate a unique hash
113
+ * anchor" is `AnchorSpaceExhaustedError`'s own headline, reachable as message-only text on a
114
+ * re-wrap. Declining both keeps promotion off every refusal a retry cannot out-grow, and leaves
115
+ * the line cap free to be re-formatted through the hash-space wording without promotion silently
116
+ * becoming a hazard-clear.
117
+ */
118
+ export function isPromotableAnchorSpaceExhaustion(e) {
119
+ if (e instanceof AnchorSpaceExhaustedError)
120
+ return true;
121
+ return e instanceof Error && e.message.includes("probing failed over");
122
+ }
72
123
  export function idxToHash(idx) {
73
124
  let out = "";
74
125
  for (let j = 0; j < HASH_LEN; j++) {
@@ -155,10 +206,10 @@ retiredCount, servedCount) {
155
206
  }
156
207
  }
157
208
  catch (e) {
158
- const msg = e instanceof Error ? e.message : String(e);
209
+ // Rethrow identity: an already-typed exhaustion keeps its counts untouched.
159
210
  if (e instanceof AnchorSpaceExhaustedError)
160
211
  throw e;
161
- if (msg.includes("probing failed over") || msg.includes("Cannot allocate")) {
212
+ if (isAnchorSpaceExhaustion(e)) {
162
213
  const rc = retiredCount ?? reservedHashes.size;
163
214
  const sc = servedCount ?? 0;
164
215
  throw new AnchorSpaceExhaustedError(rc, sc);
@@ -279,10 +330,10 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
279
330
  }
280
331
  }
281
332
  catch (e) {
282
- const msg = e instanceof Error ? e.message : String(e);
333
+ // Rethrow identity: an already-typed exhaustion keeps its counts untouched.
283
334
  if (e instanceof AnchorSpaceExhaustedError)
284
335
  throw e;
285
- if (msg.includes("probing failed over") || msg.includes("Cannot allocate")) {
336
+ if (isAnchorSpaceExhaustion(e)) {
286
337
  const rc = retiredCount ?? reservedHashes.size;
287
338
  const sc = servedCount ?? 0;
288
339
  throw new AnchorSpaceExhaustedError(rc, sc);
@@ -5,6 +5,9 @@
5
5
  */
6
6
  export { CANON_VERSION, ANCHOR_LEN, HASH_SEP, HASH_SPACE, HASH_PROBE_STRIDE, MAX_HASH_LINES, HASH_LEN, HASH_CLASS, HASH_RE, ALPH_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HL_BARE_PREFIX_RE, canon, lineHashesPure, mapStableHashes, initHasher, contentChecksum, } from "./hash-assign.js";
7
7
  export { lineHashes } from "./hash.js";
8
- export { parseHashRef, parseText } from "./parse.js";
8
+ export { parseHashRef, parseText } from "./anchor-pipeline.js";
9
9
  export { resEdit } from "./anchor-pipeline.js";
10
- export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, EditHashEchoError, findEditHashEcho, isAnchorMismatch, verifyServedRange, verifyRebasedSpan, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
10
+ export { applyEdit, fmtRegion, changedRange, buildIdx, AnchorMismatchError, EditHashEchoError, findEditHashEcho, isAnchorMismatch, } from "./anchor-pipeline.js";
11
+ // Read-side served evidence (ADR-0037) — re-exported here so the barrel stays the one
12
+ // external surface; `ServedRow` keeps coming from anchor-pipeline's domain-errors re-export.
13
+ export { ServedRejectionError, verifyServedRange, verifyRebasedSpan, buildRangeEcho, fmtServedRows, moreRowsHint, } from "./served-evidence.js";