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
@@ -0,0 +1,531 @@
1
+ /**
2
+ * ServedEvidence — deep module owning what a served range can still prove.
3
+ *
4
+ * One entry point: `verifyServedRange` decides whether the anchor pair an edit
5
+ * names is still grounded in the evidence this session was served, and rejects
6
+ * with the echoed window when it is not. Every other decision here is private to
7
+ * that call — the `ServedEvidenceRoute` union answers its three route questions
8
+ * (`owesInteriorScan`, `acceptsInteriorHole`, `checksPosition`), the leased
9
+ * route's boundary interception loses identity before any content question is
10
+ * asked, and `throwUnknownOrForeign` refuses anchors the lease seam cannot place.
11
+ *
12
+ * `verifyRebasedSpan` is exported because two cells pin the leased route directly;
13
+ * it is not a second entry point. `buildRangeEcho`/`fmtServedRows`/`moreRowsHint`
14
+ * render the echo, and `ResolvedRange` is the shape both sides of the edit path
15
+ * carry, so neither side has to import the other.
16
+ *
17
+ * WHY here: the verifier is read-side evidence, but the write path calls it. Kept
18
+ * in anchor-pipeline it closed a cycle through the served mirror and the request
19
+ * contract; as a leaf (domain registry, hash-assign, constants) it closes none.
20
+ *
21
+ * @module dsh-better-edit/hashline/served-evidence
22
+ */
23
+ import { DomainError } from "../domain-errors.js";
24
+ import { HASH_SEP, canon } from "./hash-assign.js";
25
+ import { SERVED_ECHO_CAP } from "../constants.js";
26
+ export class ServedRejectionError extends DomainError {
27
+ code;
28
+ unservedKind;
29
+ constructor(opts) {
30
+ if (opts.code === "E_STALE_RANGE") {
31
+ super("E_STALE_RANGE", {
32
+ headline: opts.headline,
33
+ servedRows: opts.servedRows,
34
+ servedBlock: opts.servedBlock,
35
+ ...(opts.cause !== undefined ? { cause: opts.cause } : {}),
36
+ ...(opts.firstOffendingLine !== undefined
37
+ ? { firstOffendingLine: opts.firstOffendingLine }
38
+ : {}),
39
+ });
40
+ }
41
+ else {
42
+ super("E_UNSERVED_RANGE", {
43
+ headline: opts.headline,
44
+ servedRows: opts.servedRows,
45
+ servedBlock: opts.servedBlock,
46
+ unservedKind: opts.unservedKind,
47
+ ...(opts.firstOffendingLine !== undefined
48
+ ? { firstOffendingLine: opts.firstOffendingLine }
49
+ : {}),
50
+ });
51
+ }
52
+ this.name = "ServedRejectionError";
53
+ this.code = opts.code;
54
+ this.unservedKind = opts.code === "E_UNSERVED_RANGE" ? opts.unservedKind : undefined;
55
+ }
56
+ }
57
+ export function servedPositionsOf(served, hash) {
58
+ const out = [];
59
+ for (let i = 0; i < served.length; i++) {
60
+ if (served[i] === hash)
61
+ out.push(i);
62
+ }
63
+ return out;
64
+ }
65
+ export function buildRangeEcho(startLine, endLine, fileHashes) {
66
+ const total = endLine - startLine + 1;
67
+ const shown = Math.min(total, SERVED_ECHO_CAP);
68
+ const rows = [];
69
+ for (let ln = startLine; ln < startLine + shown; ln++) {
70
+ rows.push({ position: ln - 1, hash: fileHashes[ln - 1] });
71
+ }
72
+ return rows;
73
+ }
74
+ export function fmtServedRows(rows, fileLines) {
75
+ return rows.map((row) => `${row.hash}${HASH_SEP}${fileLines[row.position] ?? ""}`).join("\n");
76
+ }
77
+ export function moreRowsHint(count, tail) {
78
+ return `[... ${count} more — ${tail}]`;
79
+ }
80
+ function paginationHint(nextOffset, more) {
81
+ return moreRowsHint(more, `read offset=${nextOffset}`);
82
+ }
83
+ function servedEvidenceRoute(leaseSource) {
84
+ return leaseSource === undefined ? { kind: "mirror" } : { kind: "leased", source: leaseSource };
85
+ }
86
+ /**
87
+ * Question 1: does this route owe the never-served interior scan (upstream ADR-0024 decision 2)?
88
+ * On the mirror route the mirror is the only evidence, so an interior hole rejects there.
89
+ * The leased route does not scan: the identity gate owns verification — its two boundary
90
+ * leases pin the span's extent, so an interior `null` carries no identity to verify and
91
+ * `acceptsInteriorHole` admits it (decision 1, adopted; supersedes ADR-0019's decline).
92
+ * Rejecting the hole on the scan would shadow the gate and keep taxing correct edits upstream
93
+ * measured at 8/242 calls.
94
+ */
95
+ function owesInteriorScan(route) {
96
+ return route.kind === "mirror";
97
+ }
98
+ /**
99
+ * Question 2: is slot `k` of a `servedLen`-row gate window an interior hole the leased
100
+ * identity gate accepts? Upstream ADR-0024 decision 1 (adopted; supersedes ADR-0019's
101
+ * decline) narrows informed destruction to the boundaries: an unread interior row has no
102
+ * identity to check, and the two verified boundary leases already fix the span's extent, so
103
+ * refusing it only taxed a correct edit. A `null` boundary is the named anchor itself —
104
+ * unverifiable by construction — so it keeps the fail-closed diagnosis. The mirror route
105
+ * answers uniformly: `owesInteriorScan` has already rejected its holes before the gate can
106
+ * be reached.
107
+ */
108
+ function acceptsInteriorHole(route, k, servedLen) {
109
+ return route.kind === "leased" && k !== 0 && k !== servedLen - 1;
110
+ }
111
+ /**
112
+ * Question 3: does this slot take part in the position comparison? On the leased route a
113
+ * `null` slot carries no evidence to compare and the identity gate has already adjudicated
114
+ * the window (accepting an interior hole per upstream ADR-0024 decision 1); failing the
115
+ * position check on it here would re-shadow the gate. The non-leased route rejects its holes
116
+ * in the interior scan above (decision 2 keeps its interior diagnosis) and compares every
117
+ * slot as before.
118
+ */
119
+ function checksPosition(route, slot) {
120
+ return route.kind !== "leased" || slot !== null;
121
+ }
122
+ /**
123
+ * Refuses anchors the lease seam cannot place: the session holds no lease for them in this file.
124
+ * Deterministic precedence, one condition per code — a lease held for ANOTHER file
125
+ * (`E_FOREIGN_ANCHOR`) wins over holding no lease anywhere (`E_UNKNOWN_ANCHOR`). Neither
126
+ * rejection serves rows: with no lease for this file no range can be identified, so there is
127
+ * nothing trustworthy to retry with (port of upstream b92e0ec:src/hashline/lease-resolve.ts:87-118).
128
+ */
129
+ function throwUnknownOrForeign(args) {
130
+ const path = args.filePath ?? "this file";
131
+ const refused = [...new Set(args.refused)];
132
+ const homes = [...new Set(refused.flatMap((anchor) => args.source.anchorHomes(anchor)))].sort();
133
+ if (homes.length > 0) {
134
+ throw new DomainError("E_FOREIGN_ANCHOR", { path, anchors: refused, homes });
135
+ }
136
+ throw new DomainError("E_UNKNOWN_ANCHOR", { path, anchors: refused });
137
+ }
138
+ /**
139
+ * Per-lease line-identity decision (port of upstream b92e0ec:src/hashline/resolve.ts:95-110):
140
+ * a retired lease, or a live lease whose `line_id` has no coordinate in the buffer being
141
+ * edited, is `stale`; otherwise the decision names the rebased line.
142
+ */
143
+ function lineIdentityDecision(lease, source) {
144
+ if (lease.retiredAt !== null)
145
+ return { kind: "stale" };
146
+ const rebased = source.rebasedLineOf(lease.lineId);
147
+ if (rebased === undefined)
148
+ return { kind: "stale" };
149
+ return { kind: "line", line: rebased };
150
+ }
151
+ /**
152
+ * The leased-route boundary identity interception (port of upstream
153
+ * b92e0ec:src/hashline/lease-resolve.ts:120-200), running before the served-window gates:
154
+ * a boundary anchor with no lease is lost identity — unknown or foreign, never a content
155
+ * question. A stale boundary serves rows ONLY when exactly one bound is stale AND the survivor
156
+ * is live and unshifted (its rebased coordinate equals its served coordinate — evidence no
157
+ * shift occurred): that one case rejects with `E_UNVERIFIED_RANGE`, the named window echoed as
158
+ * a fresh read; every other stale case rejects with `E_TARGET_LOST`, carrying no rows.
159
+ * The named coordinates are lease-derived (`servedLineNumber`) only — content placement never
160
+ * names a window for a retired bound.
161
+ */
162
+ function interceptLeaseBoundaries(args) {
163
+ const { fileHashes, fileLines, leaseSource } = args;
164
+ const fromLease = leaseSource.leaseFor(args.startHash);
165
+ const toLease = leaseSource.leaseFor(args.endHash);
166
+ if (fromLease === undefined || toLease === undefined) {
167
+ throwUnknownOrForeign({
168
+ ...(args.filePath !== undefined ? { filePath: args.filePath } : {}),
169
+ refused: [
170
+ ...(fromLease === undefined ? [args.startHash] : []),
171
+ ...(toLease === undefined ? [args.endHash] : []),
172
+ ],
173
+ source: leaseSource,
174
+ });
175
+ }
176
+ const fromDecision = lineIdentityDecision(fromLease, leaseSource);
177
+ const toDecision = lineIdentityDecision(toLease, leaseSource);
178
+ if (fromDecision.kind === "stale" || toDecision.kind === "stale") {
179
+ const fromLiveUnshifted = fromDecision.kind === "line" && fromDecision.line === fromLease.servedLineNumber;
180
+ const toLiveUnshifted = toDecision.kind === "line" && toDecision.line === toLease.servedLineNumber;
181
+ const staleServedLine = fromDecision.kind === "stale" ? fromLease.servedLineNumber : toLease.servedLineNumber;
182
+ const exactlyOneStale = (fromDecision.kind === "stale") !== (toDecision.kind === "stale");
183
+ const survivorLiveUnshifted = fromDecision.kind === "stale" ? toLiveUnshifted : fromLiveUnshifted;
184
+ if (exactlyOneStale && survivorLiveUnshifted) {
185
+ const rawStart = Math.min(fromLease.servedLineNumber, toLease.servedLineNumber);
186
+ const rawEnd = Math.max(fromLease.servedLineNumber, toLease.servedLineNumber);
187
+ const len = fileHashes.length;
188
+ const startLine = Math.max(1, rawStart);
189
+ const endLine = Math.min(len, rawEnd);
190
+ // Collapsed-window guard: fail closed to `E_TARGET_LOST` when the named window
191
+ // collapses (e.g. served startLine 10 against a 4-line file) or misses the file.
192
+ if (len > 0 && startLine <= endLine && rawEnd >= 1 && rawStart <= len) {
193
+ const servedRows = buildRangeEcho(startLine, endLine, fileHashes);
194
+ const totalLen = endLine - startLine + 1;
195
+ const tail = servedRows.length < totalLen
196
+ ? `\n${paginationHint(startLine + servedRows.length, totalLen - servedRows.length)}`
197
+ : "";
198
+ throw new DomainError("E_UNVERIFIED_RANGE", {
199
+ servedRows,
200
+ servedBlock: fmtServedRows(servedRows, fileLines) + tail,
201
+ cause: "retirement",
202
+ firstOffendingLine: staleServedLine,
203
+ });
204
+ }
205
+ }
206
+ throw new DomainError("E_TARGET_LOST", {
207
+ servedLine: staleServedLine,
208
+ ...(args.filePath !== undefined ? { path: args.filePath } : {}),
209
+ cause: "retirement",
210
+ });
211
+ }
212
+ }
213
+ /**
214
+ * The identity gate for a served span (obligation (c)) — replaces the unconditional position check
215
+ * when a lease source is present.
216
+ *
217
+ * A **benign shift** — the intended line's bytes are unchanged and only its position moved (exterior
218
+ * drift above the served span) — passes: the served anchor's live lease resolves to the rebased
219
+ * coordinate the edit targets, so the edit applies there with no re-read. A **look-alike rebind** —
220
+ * the named line was deleted and a different line now holds the same bytes — rejects: the leased
221
+ * `line_id` no longer lives at the rebased coordinate, or is gone from the buffer's identity map
222
+ * entirely, so the anchor cannot be reconciled with the line it named.
223
+ *
224
+ * Fail-closed arms, all `E_STALE_RANGE` with the echo rows: a window length that changed because
225
+ * an external insert/delete landed strictly inside the span, a truncated mirror slot (no served row
226
+ * left to reconcile), a never-served boundary row (the named anchor itself, unverifiable without a
227
+ * served row), an unleased served row (a serve predating lease granting), a retired lease, or a
228
+ * coordinate no leased identity occupies. An interior mirror row the span never served (`null`) is
229
+ * accepted (upstream ADR-0024 decision 1, adopted; supersedes ADR-0019's decline): it carries no
230
+ * identity to verify and the two boundary leases plus the window-length check pin the span's extent.
231
+ * Throwing happens before any write, so a rejection leaves the file byte-identical.
232
+ */
233
+ export function verifyRebasedSpan(args) {
234
+ const { served, route, echo, echoRows, where } = args;
235
+ const leaseSource = route.source;
236
+ const servedLen = args.servedEnd - args.servedStart + 1;
237
+ const rebasedLen = args.rebasedEnd - args.rebasedStart + 1;
238
+ if (rebasedLen !== servedLen) {
239
+ throw new ServedRejectionError({
240
+ code: "E_STALE_RANGE",
241
+ headline: `served span (${servedLen} lines) no longer matches the rebased range (${rebasedLen} lines)${where}.`,
242
+ servedBlock: echo,
243
+ firstOffendingLine: args.rebasedStart,
244
+ servedRows: echoRows,
245
+ cause: "served-range staleness",
246
+ });
247
+ }
248
+ for (let k = 0; k < servedLen; k++) {
249
+ const servedAnchor = served[args.servedStart - 1 + k];
250
+ const currentLine = args.rebasedStart + k;
251
+ // WHY: the served window can come from the leases' own `servedLineNumber` because a truncated
252
+ // serve dropped the mirror rows it no longer covers: the lease outlives the mirror. An
253
+ // absent slot is that missing record, never "this line was never served", so the span
254
+ // fails closed on the truth (the served record cannot be reconciled) and the current
255
+ // range is served for a fresh read.
256
+ if (servedAnchor === undefined) {
257
+ throw new ServedRejectionError({
258
+ code: "E_STALE_RANGE",
259
+ headline: `line ${currentLine}${where} has no served mirror row left; the served window was truncated.`,
260
+ servedBlock: echo,
261
+ firstOffendingLine: currentLine,
262
+ servedRows: echoRows,
263
+ cause: "served-range staleness",
264
+ });
265
+ }
266
+ if (servedAnchor === null) {
267
+ // WHY: the interior-accept / boundary-reject split is the route's `acceptsInteriorHole`
268
+ // decision (upstream ADR-0024 decision 1, adopted; supersedes ADR-0019's decline) — see
269
+ // its doc for why an unread interior row passes and a `null` boundary keeps the
270
+ // fail-closed diagnosis.
271
+ if (!acceptsInteriorHole(route, k, servedLen)) {
272
+ throw new ServedRejectionError({
273
+ code: "E_STALE_RANGE",
274
+ headline: `line ${currentLine}${where} was never served.`,
275
+ servedBlock: echo,
276
+ firstOffendingLine: currentLine,
277
+ servedRows: echoRows,
278
+ cause: "never-served",
279
+ });
280
+ }
281
+ continue;
282
+ }
283
+ const lease = leaseSource.leaseFor(servedAnchor);
284
+ if (lease === undefined) {
285
+ throw new ServedRejectionError({
286
+ code: "E_STALE_RANGE",
287
+ headline: `line ${currentLine}${where} has no served line identity.`,
288
+ servedBlock: echo,
289
+ firstOffendingLine: currentLine,
290
+ servedRows: echoRows,
291
+ cause: "never-served",
292
+ });
293
+ }
294
+ // WHY: two distinct diagnoses, one per condition: a terminal lease is a `retirement` — the
295
+ // identity is gone and only a re-read revives it — while a live lease whose `lineId` no
296
+ // longer sits at its expected coordinate is drift between the served record and the
297
+ // rebased span.
298
+ if (lease.retiredAt !== null) {
299
+ throw new ServedRejectionError({
300
+ code: "E_STALE_RANGE",
301
+ headline: `line ${currentLine}${where} no longer resolves to the line identity it was served with.`,
302
+ servedBlock: echo,
303
+ firstOffendingLine: currentLine,
304
+ servedRows: echoRows,
305
+ cause: "retirement",
306
+ });
307
+ }
308
+ if (leaseSource.rebasedLineOf(lease.lineId) !== currentLine) {
309
+ throw new ServedRejectionError({
310
+ code: "E_STALE_RANGE",
311
+ headline: `line ${currentLine}${where} no longer resolves to the line identity it was served with.`,
312
+ servedBlock: echo,
313
+ firstOffendingLine: currentLine,
314
+ servedRows: echoRows,
315
+ cause: "served-range staleness",
316
+ });
317
+ }
318
+ }
319
+ }
320
+ export function verifyServedRange(args) {
321
+ const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath } = args;
322
+ // The one route construction (obligation (c)): every leased/mirror decision below consults
323
+ // this value, so the conjunction cannot drift site by site.
324
+ const route = servedEvidenceRoute(args.leaseSource);
325
+ const where = filePath ? ` in ${filePath}` : "";
326
+ const retiredSet = args.retired ?? new Set();
327
+ const servedCanons = args.servedCanons;
328
+ const echoRows = buildRangeEcho(startLine, endLine, fileHashes);
329
+ const totalLen = endLine - startLine + 1;
330
+ const tail = echoRows.length < totalLen
331
+ ? `\n${paginationHint(startLine + echoRows.length, totalLen - echoRows.length)}`
332
+ : "";
333
+ const echo = fmtServedRows(echoRows, fileLines) + tail;
334
+ // Retired-anchor check for boundaries (whole-span S@3==S@3) — the freed-hash concept, named
335
+ // `retired` here since ADR-0013 (ADR-0028 records the vocabulary ruling).
336
+ // If hash was freed in this epoch, any reuse is stale even at same pos+same canon.
337
+ // Early reject checks canon change to avoid false positive on same line re-read.
338
+ if (retiredSet.has(startHash) || retiredSet.has(endHash)) {
339
+ const retiredHash = retiredSet.has(startHash) ? startHash : endHash;
340
+ if (servedCanons) {
341
+ const pos = fileHashes.indexOf(retiredHash);
342
+ if (pos >= 0) {
343
+ const servedIdx = served.indexOf(retiredHash);
344
+ const expected = servedIdx >= 0 ? servedCanons[servedIdx] : undefined;
345
+ const actual = canon(fileLines[pos] ?? "");
346
+ if (expected !== undefined && expected !== null && expected !== actual) {
347
+ throw new ServedRejectionError({
348
+ code: "E_STALE_RANGE",
349
+ headline: `anchor "${retiredHash}" was freed since last full read (retired, canon changed from "${expected}" to "${actual}"). Re-read.`,
350
+ servedBlock: echo,
351
+ firstOffendingLine: pos + 1,
352
+ servedRows: echoRows,
353
+ });
354
+ }
355
+ }
356
+ }
357
+ }
358
+ // The leased route resolves boundaries through the lease seam FIRST (upstream
359
+ // b92e0ec:src/hashline/lease-resolve.ts:120-200): a missing or stale boundary lease rejects
360
+ // before content placement can substitute a look-alike for the lost identity. The non-leased
361
+ // route keeps mirror placement alone (upstream's non-leased analogue,
362
+ // served-verification.ts:745, is the zero-position arm below).
363
+ if (route.kind === "leased") {
364
+ interceptLeaseBoundaries({
365
+ startHash,
366
+ endHash,
367
+ fileHashes,
368
+ fileLines,
369
+ ...(filePath !== undefined ? { filePath } : {}),
370
+ leaseSource: route.source,
371
+ });
372
+ }
373
+ const startPositions = servedPositionsOf(served, startHash);
374
+ const endPositions = servedPositionsOf(served, endHash);
375
+ const currentLen = endLine - startLine + 1;
376
+ let from;
377
+ let to;
378
+ // Exact-boundary rule (ADR-0018, superseding ADR-0004): each boundary anchor must have
379
+ // EXACTLY one served position. Anything else leaves `from`/`to` undefined and rejects
380
+ // below — there is no candidate-span search that could re-bind onto a look-alike line.
381
+ if (startPositions.length === 1 && endPositions.length === 1) {
382
+ from = Math.min(startPositions[0], endPositions[0]);
383
+ to = Math.max(startPositions[0], endPositions[0]);
384
+ }
385
+ if (from === undefined || to === undefined) {
386
+ const missing = [
387
+ ...new Set([
388
+ ...(startPositions.length === 0 ? [startHash] : []),
389
+ ...(endPositions.length === 0 ? [endHash] : []),
390
+ ]),
391
+ ];
392
+ if (missing.length > 0) {
393
+ // A boundary anchor the mirror never placed was never served for this file: the
394
+ // rejection carries no rows — with nothing served there is nothing trustworthy to
395
+ // retry with, only a read restores grounding (port of upstream
396
+ // b92e0ec:src/hashline/served-verification.ts:729-749).
397
+ throw new DomainError("E_UNKNOWN_ANCHOR", {
398
+ path: filePath ?? "this file",
399
+ anchors: missing,
400
+ });
401
+ }
402
+ const problems = [];
403
+ if (startPositions.length > 1) {
404
+ problems.push(`anchor_from "${startHash}" was served at ${startPositions.length} positions`);
405
+ }
406
+ if (endPositions.length > 1) {
407
+ problems.push(`anchor_to "${endHash}" was served at ${endPositions.length} positions`);
408
+ }
409
+ throw new ServedRejectionError({
410
+ code: "E_UNSERVED_RANGE",
411
+ unservedKind: "boundary",
412
+ headline: `cannot verify range against served state${where}: ${problems.join("; ")}. ` +
413
+ `Each boundary anchor must have exactly one served position — no served span is searched ` +
414
+ `for a look-alike line. A full read will re-sync the served mirror; the echoed range below ` +
415
+ `is current content.`,
416
+ servedBlock: echo,
417
+ servedRows: echoRows,
418
+ });
419
+ }
420
+ // The never-served interior scan is the mirror route's evidence rule (upstream ADR-0024
421
+ // decision 2); the leased route skips it because the identity gate owns interior holes
422
+ // there (decision 1) — the full rationale lives on `owesInteriorScan`.
423
+ if (owesInteriorScan(route)) {
424
+ for (let i = from; i <= to; i++) {
425
+ if (served[i] === null) {
426
+ throw new ServedRejectionError({
427
+ code: "E_UNSERVED_RANGE",
428
+ unservedKind: "interior",
429
+ headline: `line ${i + 1}${where} was never served.`,
430
+ servedBlock: echo,
431
+ firstOffendingLine: i + 1,
432
+ servedRows: echoRows,
433
+ });
434
+ }
435
+ }
436
+ }
437
+ const servedLen = to - from + 1;
438
+ if (servedLen !== currentLen) {
439
+ throw new ServedRejectionError({
440
+ code: "E_STALE_RANGE",
441
+ headline: `served span (${servedLen} lines) no longer matches current range (${currentLen} lines)${where}. Re-read.`,
442
+ servedBlock: echo,
443
+ firstOffendingLine: startLine,
444
+ servedRows: echoRows,
445
+ });
446
+ }
447
+ // Position check or identity gate — the seam is opt-in (obligation (c)).
448
+ //
449
+ // With a lease source, identity decides: `verifyRebasedSpan` checks the whole served window by
450
+ // the leases its anchors were served with, so a benign shift (same bytes, moved position —
451
+ // exterior drift above the span) applies at its rebased coordinate with no re-read, while a
452
+ // look-alike rebind (the named line was deleted and another line now holds its bytes) rejects.
453
+ //
454
+ // Without a lease source the unconditional position check below stands: identity only, never a
455
+ // weaker position check. The pos-free route is REACHABLE on a normal session route (a windowed
456
+ // read never pinned the epoch; a preview/no-store edit carries no leases), which is why this
457
+ // fallback cannot be dropped.
458
+ if (route.kind === "leased") {
459
+ verifyRebasedSpan({
460
+ served,
461
+ servedStart: from + 1,
462
+ servedEnd: to + 1,
463
+ rebasedStart: startLine,
464
+ rebasedEnd: endLine,
465
+ route,
466
+ echo,
467
+ echoRows,
468
+ where,
469
+ });
470
+ }
471
+ else if (from !== startLine - 1) {
472
+ throw new ServedRejectionError({
473
+ code: "E_STALE_RANGE",
474
+ headline: `anchor was served at line ${from + 1} but now resolves to line ${startLine}. Re-read.`,
475
+ servedBlock: echo,
476
+ firstOffendingLine: startLine,
477
+ servedRows: echoRows,
478
+ });
479
+ }
480
+ // Canon check for same-pos different content (collision)
481
+ if (servedCanons) {
482
+ for (let k = 0; k < servedLen; k++) {
483
+ const expected = servedCanons[from + k];
484
+ if (expected !== null && expected !== undefined) {
485
+ const actual = canon(fileLines[startLine - 1 + k] ?? "");
486
+ if (expected !== actual) {
487
+ throw new ServedRejectionError({
488
+ code: "E_STALE_RANGE",
489
+ headline: `line ${startLine + k}${where} canon differs from served (expected "${expected}" vs actual "${actual}").`,
490
+ servedBlock: echo,
491
+ firstOffendingLine: startLine + k,
492
+ servedRows: echoRows,
493
+ });
494
+ }
495
+ }
496
+ }
497
+ }
498
+ // Retired-anchor interior check (whole-span) — gated on canon inequality (fail-closed only for different canon)
499
+ for (let k = 0; k < servedLen; k++) {
500
+ const h = fileHashes[startLine - 1 + k];
501
+ if (h && retiredSet.has(h)) {
502
+ const expectedCanon = servedCanons?.[from + k] ?? undefined;
503
+ const actualCanon = canon(fileLines[startLine - 1 + k] ?? "");
504
+ if (expectedCanon !== undefined && expectedCanon !== null && expectedCanon !== actualCanon) {
505
+ throw new ServedRejectionError({
506
+ code: "E_STALE_RANGE",
507
+ headline: `line ${startLine + k}${where} uses retired anchor "${h}" (freed since last full read, canon changed). Re-read.`,
508
+ servedBlock: echo,
509
+ firstOffendingLine: startLine + k,
510
+ servedRows: echoRows,
511
+ });
512
+ }
513
+ }
514
+ }
515
+ for (let k = 0; k < servedLen; k++) {
516
+ // The leased route's `null` skip is `checksPosition`'s decision (the identity gate already
517
+ // adjudicated the hole); the mirror route's holes rejected in the scan above.
518
+ if (!checksPosition(route, served[from + k]))
519
+ continue;
520
+ if (served[from + k] !== fileHashes[startLine - 1 + k]) {
521
+ const offendingLine = startLine + k;
522
+ throw new ServedRejectionError({
523
+ code: "E_STALE_RANGE",
524
+ headline: `line ${offendingLine}${where} differs from what was served. Re-read.`,
525
+ servedBlock: echo,
526
+ firstOffendingLine: offendingLine,
527
+ servedRows: echoRows,
528
+ });
529
+ }
530
+ }
531
+ }