@loro-dev/roost 0.1.0

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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +397 -0
  3. package/dist/codec.d.ts +66 -0
  4. package/dist/codec.js +275 -0
  5. package/dist/crypto.d.ts +21 -0
  6. package/dist/crypto.js +103 -0
  7. package/dist/durable-framing.d.ts +44 -0
  8. package/dist/durable-framing.js +207 -0
  9. package/dist/framing.d.ts +28 -0
  10. package/dist/framing.js +144 -0
  11. package/dist/history-publication.d.ts +58 -0
  12. package/dist/history-publication.js +234 -0
  13. package/dist/identity.d.ts +14 -0
  14. package/dist/identity.js +62 -0
  15. package/dist/inbox.d.ts +69 -0
  16. package/dist/inbox.js +262 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +6 -0
  19. package/dist/indexeddb.d.ts +38 -0
  20. package/dist/indexeddb.js +299 -0
  21. package/dist/json.d.ts +23 -0
  22. package/dist/json.js +221 -0
  23. package/dist/lody-history.d.ts +397 -0
  24. package/dist/lody-history.js +1559 -0
  25. package/dist/projection.d.ts +53 -0
  26. package/dist/projection.js +543 -0
  27. package/dist/replay.d.ts +63 -0
  28. package/dist/replay.js +201 -0
  29. package/dist/sender.d.ts +26 -0
  30. package/dist/sender.js +67 -0
  31. package/dist/store.d.ts +384 -0
  32. package/dist/store.js +1437 -0
  33. package/dist/sync/coverage.d.ts +276 -0
  34. package/dist/sync/coverage.js +1084 -0
  35. package/dist/sync/crypto.d.ts +64 -0
  36. package/dist/sync/crypto.js +155 -0
  37. package/dist/sync/execute.d.ts +142 -0
  38. package/dist/sync/execute.js +321 -0
  39. package/dist/sync/history.d.ts +214 -0
  40. package/dist/sync/history.js +786 -0
  41. package/dist/sync/index.d.ts +17 -0
  42. package/dist/sync/index.js +9 -0
  43. package/dist/sync/link.d.ts +192 -0
  44. package/dist/sync/link.js +663 -0
  45. package/dist/sync/mod.d.ts +24 -0
  46. package/dist/sync/mod.js +15 -0
  47. package/dist/sync/policy.d.ts +62 -0
  48. package/dist/sync/policy.js +128 -0
  49. package/dist/sync/registry.d.ts +129 -0
  50. package/dist/sync/registry.js +333 -0
  51. package/dist/sync/transport.d.ts +91 -0
  52. package/dist/sync/transport.js +162 -0
  53. package/dist/sync/work.d.ts +351 -0
  54. package/dist/sync/work.js +1344 -0
  55. package/package.json +47 -0
@@ -0,0 +1,1084 @@
1
+ import { decodeUtf8, encodeUtf8 } from '../json.js';
2
+ import { generationKeyFragment } from './registry.js';
3
+ /**
4
+ * Durable per-remote operation coverage and closed assertions (RS2-01), the
5
+ * IndexedDB mirror of src/sync/coverage.rs. Records, per remote target,
6
+ * exactly which operations of a stream have been confirmed present on that
7
+ * target — a contiguous prefix plus out-of-prefix islands, matched by content
8
+ * fingerprint — and persists the derived `closed` assertion in the same write
9
+ * transaction that completes it (T5). Closed never skips a hole (CASE-05),
10
+ * conflicting content at one position is kept in both copies (CASE-06), and a
11
+ * new generation starts empty while old generations stay readable but sealed
12
+ * off (CASE-07). Coverage state is per-target truth only; it never feeds the
13
+ * signed node hash and never echoes to any outbox.
14
+ *
15
+ * Storage layout (private to this module, not a wire format) — byte-for-byte
16
+ * the Rust layout, so one physical database is readable from both ends.
17
+ * Chunked per-turn layout (v2, W5): the pre-v2 record kept every seq
18
+ * fingerprint of a turn in its `[0x01]` value, so each mark rewrote O(seqs)
19
+ * bytes — O(seqs²) per long turn. The chunked layout keeps per-mark writes
20
+ * O(1):
21
+ *
22
+ * | Keys | Value |
23
+ * | --- | --- |
24
+ * | `[0x01] \|\| scope \|\| turn[16]` | per-turn summary (v2): prefix length, seal claim, parent refs, distinct-seq count, island summary `{count,min,max}`. A version-1 value is the legacy whole-turn record: still readable everywhere, converted transactionally inside the turn's first mark |
25
+ * | `[0x02] \|\| same scope prefix \|\| turn[16]` | `closed` record `{seal_seq, seal_fp}` (v1, format unchanged) |
26
+ * | `[0x03] \|\| same scope prefix \|\| turn[16] \|\| seq[4 BE]` | conflict diagnostic `{fps}` (v1, format unchanged) |
27
+ * | `[0x04] \|\| scope \|\| parent_turn[16] \|\| child_turn[16]` | parent→child reverse index (RS2-04, empty value) |
28
+ * | `[0x05] \|\| scope \|\| turn[16] \|\| seq[4 BE]` | per-seq fingerprints `{fps}` (v2), sorted and deduped — both copies of a conflict |
29
+ * | `[0x06] \|\| scope \|\| turn[16] \|\| seq[4 BE]` | island marker (v2, empty value): a present seq beyond the contiguous prefix; created on the out-of-prefix mark, deleted when the prefix absorbs it |
30
+ *
31
+ * The prefix advances incrementally (each seq crosses it at most once); the
32
+ * full-prefix check is O(1) from the island summary: `0..=sealSeq` is fully
33
+ * present iff `sealSeq < prefix_len`, or the islands form exactly the
34
+ * contiguous range `prefix_len..=sealSeq` (`count == max - min + 1` with
35
+ * `min == prefix_len` and `max == sealSeq`).
36
+ *
37
+ * Validation scope, stated explicitly (mirrors the Rust module): summary and
38
+ * per-seq reads perform O(1) self-consistency checks; the full per-turn
39
+ * invariant recomputation runs on the `presentState` full-read path. Legacy
40
+ * version-1 records keep their whole-record validation on every read.
41
+ *
42
+ * Values are `[version byte] || serde_json` with a fixed DTO field order, so
43
+ * the encoding is deterministic and identical to the Rust serde encoding. The
44
+ * leading version byte is authoritative: a mismatch is `unsupportedVersion`
45
+ * and never silently decoded, including the inner `"v"` tag. Every multi-step
46
+ * mutation runs in one IDB transaction; a throw aborts the native transaction,
47
+ * so a rejected mark commits nothing (T5). This module performs no network
48
+ * I/O and never awaits inside a transaction.
49
+ */
50
+ /** KV space holding all coverage keys (same name as the Rust space). */
51
+ export const COVERAGE_SPACE = 'rsync_cov';
52
+ /** Record version of the unchanged small-record families (closed records,
53
+ * conflict diagnostics) and of the legacy whole-turn `[0x01]` record. */
54
+ export const RECORD_VERSION = 1;
55
+ /** Record version of the chunked layout (W5): the `[0x01]` per-turn summary
56
+ * and the `[0x05]` per-seq fingerprint records. */
57
+ /** V3 summaries append unresolved [{turn,hash}] declarations and can be complete
58
+ * but never closed. Only genuine local ID/hash/seal binding restores v2. Old
59
+ * readers reject v3. Tag7 stores scope+turn16+seq4BE+frameFp32 served receipts;
60
+ * tag8 indexes unresolved parent16+child16, both empty values. Tag9 stores the
61
+ * per-Inbox-source processing cursor (`source_len[4 BE] || source`, 8 BE next
62
+ * report sequence; absent means 0). History and live sources never share it.
63
+ * Raw Inbox data remains authoritative and retained; per-operation extra storage
64
+ * is O(1). */
65
+ export const SUMMARY_RECORD_VERSION = 2;
66
+ /** Coverage record keys start with this tag. */
67
+ export const COVERAGE_KEY_TAG = 0x01;
68
+ /** Closed record keys start with this tag. */
69
+ export const CLOSED_KEY_TAG = 0x02;
70
+ /** Conflict diagnostic keys start with this tag. */
71
+ export const CONFLICT_KEY_TAG = 0x03;
72
+ /** Parent→child reverse index keys start with this tag (RS2-04): one row per
73
+ * declared parent edge, so a newly closed turn can re-evaluate the closure of
74
+ * the turns that declared it as parent — closed records are persisted
75
+ * assertions and without the cascade their creation would depend on mark
76
+ * arrival order. */
77
+ export const CHILD_KEY_TAG = 0x04;
78
+ /** Per-seq fingerprint record keys start with this tag (chunked layout, W5). */
79
+ export const SEQ_KEY_TAG = 0x05;
80
+ /** Island marker keys start with this tag (chunked layout, W5): one row per
81
+ * present seq beyond the turn's contiguous prefix. */
82
+ export const ISLAND_KEY_TAG = 0x06;
83
+ /** Maximum distinct seqs tracked per turn (islands and prefix together). */
84
+ export const MAX_PRESENT_SEQS = 1 << 20;
85
+ /** Errors returned by CoverageStore. `code` mirrors the Rust CoverageError
86
+ * variants; `cause` carries structured fields where the Rust variant has
87
+ * them. Native IDB failures propagate as DOMExceptions, as in the registry. */
88
+ export class CoverageError extends Error {
89
+ code;
90
+ constructor(code, message = code, options) {
91
+ super(message, options);
92
+ this.code = code;
93
+ this.name = 'CoverageError';
94
+ }
95
+ }
96
+ const invalid = (message) => new CoverageError('invalid', message);
97
+ const corrupt = (message) => new CoverageError('corrupt', message);
98
+ const ALL = Number.MAX_SAFE_INTEGER;
99
+ function compareBytes(a, b) {
100
+ for (let i = 0; i < Math.min(a.length, b.length); i++)
101
+ if (a[i] !== b[i])
102
+ return a[i] - b[i];
103
+ return a.length - b.length;
104
+ }
105
+ function equalBytes(a, b) { return compareBytes(a, b) === 0; }
106
+ function cat(...parts) {
107
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
108
+ let n = 0;
109
+ for (const p of parts) {
110
+ out.set(p, n);
111
+ n += p.length;
112
+ }
113
+ return out;
114
+ }
115
+ /** Smallest byte string strictly greater than `key`, or undefined when `key`
116
+ * is all `0xff` (its range then extends to the end of the space). */
117
+ function successor(key) {
118
+ const out = key.slice();
119
+ for (let i = out.length - 1; i >= 0; i--)
120
+ if (out[i] !== 255) {
121
+ out[i] = out[i] + 1;
122
+ return out.slice(0, i + 1);
123
+ }
124
+ return undefined;
125
+ }
126
+ function byteArray(value, what) {
127
+ if (!Array.isArray(value) || value.some(v => !Number.isInteger(v) || v < 0 || v > 255))
128
+ throw corrupt(`record JSON: ${what} must be a byte array`);
129
+ return value;
130
+ }
131
+ function u32Array(value, what) {
132
+ if (!Array.isArray(value) || value.some(v => !Number.isInteger(v) || v < 0 || v > 0xFFFFFFFF))
133
+ throw corrupt(`record JSON: ${what} must be a u32 array`);
134
+ return value;
135
+ }
136
+ function idCopy(id, what) {
137
+ if (!(id instanceof Uint8Array) || id.length !== 16)
138
+ throw invalid(`${what} must be a 16-byte Uint8Array`);
139
+ return id.slice();
140
+ }
141
+ function fp32(fp) {
142
+ if (!(fp instanceof Uint8Array) || fp.length !== 32)
143
+ throw invalid('fingerprint must be a 32-byte Uint8Array');
144
+ return fp.slice();
145
+ }
146
+ function u32(value, what) {
147
+ if (!Number.isInteger(value) || value < 0 || value > 0xFFFFFFFF)
148
+ throw invalid(`${what} must be a u32`);
149
+ return value;
150
+ }
151
+ function u32be(n) {
152
+ const out = new Uint8Array(4);
153
+ new DataView(out.buffer).setUint32(0, n);
154
+ return out;
155
+ }
156
+ /** The big-endian u32 at the end of a key (corrupt when absent). */
157
+ function keyU32(key) {
158
+ if (key.length < 4)
159
+ throw corrupt('key too short for a trailing seq');
160
+ return new DataView(key.buffer, key.byteOffset + key.length - 4, 4).getUint32(0);
161
+ }
162
+ /** `[version byte] || JSON` with a fixed DTO field order, byte-identical to
163
+ * the Rust serde encoding. */
164
+ function encodeWith(version, dto) {
165
+ return cat(Uint8Array.of(version), encodeUtf8(JSON.stringify(dto)));
166
+ }
167
+ /** The unchanged small-record families (closed, conflict) encode at v1. */
168
+ function encode(dto) {
169
+ return encodeWith(RECORD_VERSION, dto);
170
+ }
171
+ /** Version-byte check + JSON parse; shape errors are corruption, a version
172
+ * mismatch is `unsupportedVersion`, never silently decoded. */
173
+ function checkVersionWith(bytes, expected) {
174
+ if (!bytes.length)
175
+ throw corrupt('empty record');
176
+ const version = bytes[0];
177
+ if (version !== expected)
178
+ throw new CoverageError('unsupportedVersion', `unsupported coverage record version: ${version}`);
179
+ try {
180
+ const parsed = JSON.parse(decodeUtf8(bytes.slice(1)));
181
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
182
+ throw Error('record must be an object');
183
+ return parsed;
184
+ }
185
+ catch (e) {
186
+ if (e instanceof CoverageError)
187
+ throw e;
188
+ throw corrupt(`record JSON: ${e instanceof Error ? e.message : String(e)}`);
189
+ }
190
+ }
191
+ function checkInnerV(v, expected) {
192
+ if (v !== expected)
193
+ throw new CoverageError('unsupportedVersion', `unsupported coverage record version: ${String(v)}`);
194
+ }
195
+ function toSealDto(value, what) {
196
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
197
+ throw Error(`${what} must be an object`);
198
+ const o = value;
199
+ if (!Number.isInteger(o.seq))
200
+ throw Error(`${what}.seq must be a u32`);
201
+ return { seq: o.seq, fp: byteArray(o.fp, `${what}.fp`) };
202
+ }
203
+ function toParentDto(value) {
204
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
205
+ throw Error('parent must be an object');
206
+ const o = value;
207
+ return { turn: byteArray(o.turn, 'parent.turn'), seal_fp: byteArray(o.seal_fp, 'parent.seal_fp') };
208
+ }
209
+ function toSeqFpDto(value) {
210
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
211
+ throw Error('seq entry must be an object');
212
+ const o = value;
213
+ if (!Number.isInteger(o.seq))
214
+ throw Error('seq entry seq must be a u32');
215
+ return { seq: o.seq, fp: byteArray(o.fp, 'seq entry fp') };
216
+ }
217
+ function toCoverageDto(raw) {
218
+ let dto;
219
+ try {
220
+ if (!Number.isInteger(raw.v) || !Number.isInteger(raw.prefix_len) || !Array.isArray(raw.parents) || !Array.isArray(raw.seqs))
221
+ throw Error('coverage fields');
222
+ dto = {
223
+ v: raw.v,
224
+ prefix_len: raw.prefix_len,
225
+ holes: u32Array(raw.holes, 'holes'),
226
+ seal: raw.seal === null || raw.seal === undefined ? null : toSealDto(raw.seal, 'seal'),
227
+ parents: raw.parents.map(toParentDto),
228
+ seqs: raw.seqs.map(toSeqFpDto),
229
+ };
230
+ }
231
+ catch (e) {
232
+ if (e instanceof CoverageError)
233
+ throw e;
234
+ throw corrupt(`record JSON: ${e instanceof Error ? e.message : String(e)}`);
235
+ }
236
+ checkInnerV(dto.v, RECORD_VERSION);
237
+ if (dto.seal && dto.seal.fp.length !== 32)
238
+ throw corrupt('record JSON: seal fp must be 32 bytes');
239
+ for (const parent of dto.parents) {
240
+ if (parent.turn.length !== 16 || parent.seal_fp.length !== 32)
241
+ throw corrupt('record JSON: parent turn/seal_fp size');
242
+ }
243
+ for (const entry of dto.seqs)
244
+ if (entry.fp.length !== 32)
245
+ throw corrupt('record JSON: seq fp must be 32 bytes');
246
+ return dto;
247
+ }
248
+ function toSummaryDto(raw, version = SUMMARY_RECORD_VERSION) {
249
+ let dto;
250
+ try {
251
+ if (!Number.isInteger(raw.v) || !Number.isInteger(raw.prefix_len) || !Number.isInteger(raw.seqs) || !Array.isArray(raw.parents))
252
+ throw Error('summary fields');
253
+ const islands = raw.islands === null || raw.islands === undefined ? null : (() => {
254
+ if (typeof raw.islands !== 'object' || Array.isArray(raw.islands))
255
+ throw Error('islands must be an object');
256
+ const o = raw.islands;
257
+ if (!Number.isInteger(o.count) || !Number.isInteger(o.min) || !Number.isInteger(o.max))
258
+ throw Error('islands fields');
259
+ return { count: o.count, min: o.min, max: o.max };
260
+ })();
261
+ dto = {
262
+ v: raw.v,
263
+ prefix_len: raw.prefix_len,
264
+ seal: raw.seal === null || raw.seal === undefined ? null : toSealDto(raw.seal, 'seal'),
265
+ parents: raw.parents.map(toParentDto),
266
+ seqs: raw.seqs,
267
+ islands,
268
+ ...(raw.unresolved === undefined ? {} : { unresolved: raw.unresolved.map(value => {
269
+ const p = value;
270
+ const turn = [...byteArray(p.turn, 'unresolved turn')], hash = [...byteArray(p.hash, 'unresolved hash')];
271
+ if (turn.length !== 16 || hash.length !== 32)
272
+ throw Error('unresolved parent size');
273
+ return { turn, hash };
274
+ }) }),
275
+ };
276
+ }
277
+ catch (e) {
278
+ if (e instanceof CoverageError)
279
+ throw e;
280
+ throw corrupt(`record JSON: ${e instanceof Error ? e.message : String(e)}`);
281
+ }
282
+ checkInnerV(dto.v, version);
283
+ if ((dto.v !== 2 && dto.v !== 3) || ((dto.v === 3) !== !!dto.unresolved?.length))
284
+ throw corrupt('unresolved summary version mismatch');
285
+ if (dto.seal && dto.seal.fp.length !== 32)
286
+ throw corrupt('record JSON: seal fp must be 32 bytes');
287
+ for (const parent of dto.parents) {
288
+ if (parent.turn.length !== 16 || parent.seal_fp.length !== 32)
289
+ throw corrupt('record JSON: parent turn/seal_fp size');
290
+ }
291
+ checkSummary(dto);
292
+ return dto;
293
+ }
294
+ /** O(1) self-consistency checks of a v2 summary (the full per-turn
295
+ * recomputation lives on the `presentState` path — see the module docs). */
296
+ function checkSummary(dto) {
297
+ if (dto.islands !== null) {
298
+ const islands = dto.islands;
299
+ if (islands.count === 0)
300
+ throw corrupt('empty island summary');
301
+ if (islands.min > islands.max)
302
+ throw corrupt('island min above max');
303
+ if (islands.min < dto.prefix_len)
304
+ throw corrupt('island below the prefix');
305
+ if (islands.count > islands.max - islands.min + 1)
306
+ throw corrupt('island count exceeds range');
307
+ }
308
+ const islandCount = dto.islands?.count ?? 0;
309
+ if (dto.seqs < dto.prefix_len + islandCount)
310
+ throw corrupt('seq count below prefix plus islands');
311
+ }
312
+ function toSeqDto(raw) {
313
+ let dto;
314
+ try {
315
+ if (!Number.isInteger(raw.v) || !Array.isArray(raw.fps))
316
+ throw Error('seq record fields');
317
+ dto = { v: raw.v, fps: raw.fps.map((fp, i) => byteArray(fp, `fps[${i}]`)) };
318
+ }
319
+ catch (e) {
320
+ if (e instanceof CoverageError)
321
+ throw e;
322
+ throw corrupt(`record JSON: ${e instanceof Error ? e.message : String(e)}`);
323
+ }
324
+ checkInnerV(dto.v, SUMMARY_RECORD_VERSION);
325
+ for (const fp of dto.fps)
326
+ if (fp.length !== 32)
327
+ throw corrupt('record JSON: per-seq fp must be 32 bytes');
328
+ return dto;
329
+ }
330
+ function toClosedDto(raw) {
331
+ let dto;
332
+ try {
333
+ if (!Number.isInteger(raw.v) || !Number.isInteger(raw.seal_seq))
334
+ throw Error('closed fields');
335
+ dto = { v: raw.v, seal_seq: raw.seal_seq, seal_fp: byteArray(raw.seal_fp, 'seal_fp') };
336
+ }
337
+ catch (e) {
338
+ if (e instanceof CoverageError)
339
+ throw e;
340
+ throw corrupt(`record JSON: ${e instanceof Error ? e.message : String(e)}`);
341
+ }
342
+ checkInnerV(dto.v, RECORD_VERSION);
343
+ if (dto.seal_fp.length !== 32)
344
+ throw corrupt('record JSON: seal_fp must be 32 bytes');
345
+ return dto;
346
+ }
347
+ function toConflictDto(raw) {
348
+ let dto;
349
+ try {
350
+ if (!Number.isInteger(raw.v) || !Array.isArray(raw.fps))
351
+ throw Error('conflict fields');
352
+ dto = { v: raw.v, fps: raw.fps.map((fp, i) => byteArray(fp, `fps[${i}]`)) };
353
+ }
354
+ catch (e) {
355
+ if (e instanceof CoverageError)
356
+ throw e;
357
+ throw corrupt(`record JSON: ${e instanceof Error ? e.message : String(e)}`);
358
+ }
359
+ checkInnerV(dto.v, RECORD_VERSION);
360
+ for (const fp of dto.fps)
361
+ if (fp.length !== 32)
362
+ throw corrupt('record JSON: conflict fp must be 32 bytes');
363
+ return dto;
364
+ }
365
+ /** Decode and fully re-validate a legacy (version-1) whole-turn record: its
366
+ * prefix/holes must agree with its own seq set, the seqs must be sorted and
367
+ * deduped, and a seal claim must have a matching fingerprint. */
368
+ function decodeCoverage(bytes) {
369
+ const dto = toCoverageDto(checkVersionWith(bytes, RECORD_VERSION));
370
+ if (!seqsSortedDeduped(dto.seqs))
371
+ throw corrupt('seqs not sorted or deduped');
372
+ const present = new Set(dto.seqs.map(entry => entry.seq));
373
+ let prefixLen = 0;
374
+ while (present.has(prefixLen))
375
+ prefixLen++;
376
+ const holes = [...present].sort((a, b) => a - b).filter(seq => seq >= prefixLen);
377
+ if (prefixLen !== dto.prefix_len || holes.length !== dto.holes.length || holes.some((seq, i) => seq !== dto.holes[i]))
378
+ throw corrupt('prefix/holes disagree with seq set');
379
+ if (dto.seal && !dto.seqs.some(entry => entry.seq === dto.seal.seq && equalBytes(entry.fp, dto.seal.fp)))
380
+ throw corrupt('seal claim without matching fingerprint');
381
+ return dto;
382
+ }
383
+ /** Decode a per-seq fingerprint record (v2 only) and check its sorted,
384
+ * deduped invariant. */
385
+ function decodeSeqRecord(bytes) {
386
+ const dto = toSeqDto(checkVersionWith(bytes, SUMMARY_RECORD_VERSION));
387
+ for (let i = 1; i < dto.fps.length; i++)
388
+ if (compareBytes(dto.fps[i - 1], dto.fps[i]) >= 0)
389
+ throw corrupt('per-seq fingerprints not sorted or deduped');
390
+ return dto;
391
+ }
392
+ /** Decode a `[0x01]` record of either supported version. */
393
+ function decodeTurnRecord(bytes) {
394
+ if (!bytes.length)
395
+ throw corrupt('empty record');
396
+ const version = bytes[0];
397
+ if (version === RECORD_VERSION)
398
+ return { kind: 'legacy', dto: decodeCoverage(bytes) };
399
+ if (version === SUMMARY_RECORD_VERSION || version === 3)
400
+ return { kind: 'summary', dto: toSummaryDto(checkVersionWith(bytes, version), version) };
401
+ throw new CoverageError('unsupportedVersion', `unsupported coverage record version: ${version}`);
402
+ }
403
+ /** Strictly ascending by (seq, fp): exactly the sorted-deduped invariant. */
404
+ function seqsSortedDeduped(seqs) {
405
+ for (let i = 1; i < seqs.length; i++) {
406
+ const prev = seqs[i - 1], next = seqs[i];
407
+ if (prev.seq > next.seq || (prev.seq === next.seq && compareBytes(prev.fp, next.fp) >= 0))
408
+ return false;
409
+ }
410
+ return true;
411
+ }
412
+ /** Whether `0..=sealSeq` is fully present in a legacy record: either inside
413
+ * the prefix, or the holes form exactly the contiguous range
414
+ * `prefix_len..=sealSeq`. */
415
+ function prefixCompleteLegacy(dto, sealSeq) {
416
+ if (sealSeq < dto.prefix_len)
417
+ return true;
418
+ const need = sealSeq - dto.prefix_len + 1;
419
+ return need === dto.holes.length
420
+ && dto.holes[0] === dto.prefix_len
421
+ && dto.holes[dto.holes.length - 1] === sealSeq;
422
+ }
423
+ /** The O(1) full-prefix check of the chunked layout (module docs): the
424
+ * islands are exactly the contiguous range `prefix_len..=sealSeq`. */
425
+ function prefixCompleteSummary(dto, sealSeq) {
426
+ if (sealSeq < dto.prefix_len)
427
+ return true;
428
+ const islands = dto.islands;
429
+ if (islands === null)
430
+ return false;
431
+ const need = sealSeq - dto.prefix_len + 1;
432
+ return islands.count === need && islands.min === dto.prefix_len && islands.max === sealSeq;
433
+ }
434
+ /** The scope bytes shared by every key of one `(remote, generation, stream)`:
435
+ * `remote[16] || generationKeyFragment || stream_len[4 BE] || stream[..]`,
436
+ * where the fragment is `gen_len[1] || gen[..] || gen_source[1]`. */
437
+ function scopeBytes(scope) {
438
+ if (!scope.stream.length)
439
+ throw invalid('empty stream');
440
+ const stream = encodeUtf8(scope.stream);
441
+ if (stream.length > 0xFFFFFFFF)
442
+ throw invalid('stream name too long');
443
+ return cat(idCopy(scope.remote, 'remote id'), generationKeyFragment(scope.generation), u32be(stream.length), stream);
444
+ }
445
+ function processingKey(scope, source) {
446
+ const bytes = encodeUtf8(source);
447
+ return cat(Uint8Array.of(9), scopeBytes(scope), u32be(bytes.length), bytes);
448
+ }
449
+ function processingValue(bytes) {
450
+ if (bytes === undefined)
451
+ return 0n;
452
+ if (bytes.length !== 8)
453
+ throw corrupt('coverage report cursor length');
454
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getBigUint64(0, false);
455
+ }
456
+ /** Coverage record key: `[COVERAGE_KEY_TAG] || scope || turn[16]`. */
457
+ export function coverageKey(scope, turn) {
458
+ return cat(Uint8Array.of(COVERAGE_KEY_TAG), scopeBytes(scope), idCopy(turn, 'turn id'));
459
+ }
460
+ /** Closed record key: `[CLOSED_KEY_TAG] || scope || turn[16]`. */
461
+ export function closedKey(scope, turn) {
462
+ return cat(Uint8Array.of(CLOSED_KEY_TAG), scopeBytes(scope), idCopy(turn, 'turn id'));
463
+ }
464
+ /** Conflict diagnostic key: `[CONFLICT_KEY_TAG] || scope || turn[16] || seq[4 BE]`. */
465
+ export function conflictKey(scope, turn, seq) {
466
+ return cat(Uint8Array.of(CONFLICT_KEY_TAG), scopeBytes(scope), idCopy(turn, 'turn id'), u32be(u32(seq, 'seq')));
467
+ }
468
+ /** Parent→child reverse index row prefix:
469
+ * `[CHILD_KEY_TAG] || scope || parent_turn[16]`; a full row key appends
470
+ * `child_turn[16]`. Values are empty; the key is the edge. */
471
+ function childPrefix(scope, parent) {
472
+ return cat(Uint8Array.of(CHILD_KEY_TAG), scopeBytes(scope), idCopy(parent, 'parent turn id'));
473
+ }
474
+ /** Parent→child reverse index key: `childPrefix(parent) || child_turn[16]`. */
475
+ function childKey(scope, parent, child) {
476
+ return cat(childPrefix(scope, parent), idCopy(child, 'child turn id'));
477
+ }
478
+ /** Per-seq record row prefix: `[SEQ_KEY_TAG] || scope || turn[16]`; a full
479
+ * row key appends `seq[4 BE]`. */
480
+ function seqPrefix(scope, turn) {
481
+ return cat(Uint8Array.of(SEQ_KEY_TAG), scopeBytes(scope), idCopy(turn, 'turn id'));
482
+ }
483
+ /** Per-seq fingerprint record key: `seqPrefix(turn) || seq[4 BE]`. */
484
+ function seqKey(scope, turn, seq) {
485
+ return cat(seqPrefix(scope, turn), u32be(u32(seq, 'seq')));
486
+ }
487
+ /** Island marker row prefix: `[ISLAND_KEY_TAG] || scope || turn[16]`; a full
488
+ * row key appends `seq[4 BE]`. Values are empty; the key is the island. */
489
+ function islandPrefix(scope, turn) {
490
+ return cat(Uint8Array.of(ISLAND_KEY_TAG), scopeBytes(scope), idCopy(turn, 'turn id'));
491
+ }
492
+ /** Island marker key: `islandPrefix(turn) || seq[4 BE]`. */
493
+ function islandKey(scope, turn, seq) {
494
+ return cat(islandPrefix(scope, turn), u32be(u32(seq, 'seq')));
495
+ }
496
+ /** Key prefix covering one remote+generation across all streams for one tag:
497
+ * `[tag] || remote[16] || generationKeyFragment`. */
498
+ function remoteGenPrefix(tag, remote, generation) {
499
+ return cat(Uint8Array.of(tag), idCopy(remote, 'remote id'), generationKeyFragment(generation));
500
+ }
501
+ function sameGeneration(a, b) {
502
+ return a.source === b.source && equalBytes(a.bytes, b.bytes);
503
+ }
504
+ function parentsToDto(parents) {
505
+ return parents.map(parent => ({
506
+ turn: [...idCopy(parent.turnId, 'parent turn id')],
507
+ seal_fp: [...fp32(parent.sealFp)],
508
+ }));
509
+ }
510
+ function freshSummary() {
511
+ return { v: SUMMARY_RECORD_VERSION, prefix_len: 0, seal: null, parents: [], seqs: 0, islands: null };
512
+ }
513
+ /**
514
+ * Coverage store over a shared IndexedDbStorage owner.
515
+ *
516
+ * Construct with the same IndexedDbStorage the host's Store and
517
+ * RemoteRegistry use, so coverage, registration and stream content commit
518
+ * through one fixed owner. The store never opens its own connection and
519
+ * never touches the network.
520
+ *
521
+ * Calling contract: every `markPresent` for one turn must carry that turn's
522
+ * complete direct parent list; the first non-empty list is persisted in the
523
+ * coverage record, so the closed assertion cannot be completed by a later
524
+ * call that forgot them.
525
+ */
526
+ export class CoverageStore {
527
+ storage;
528
+ constructor(storage) {
529
+ this.storage = storage;
530
+ }
531
+ /** Record one confirmed operation of `turn` on this target in a single
532
+ * write transaction: idempotent duplicates, content-conflict retention,
533
+ * coverage update and — when `0..=seal_seq` completes and every direct
534
+ * dependency is already closed — the `closed` assertion, all atomic (T5).
535
+ * A throw inside the program aborts the native IDB transaction, so a
536
+ * rejected mark commits nothing as a whole. */
537
+ async processedReports(scope, source) {
538
+ const key = processingKey(scope, source);
539
+ return this.storage.transact(false, function* (tx) { return processingValue(yield* tx.get(COVERAGE_SPACE, key)); });
540
+ }
541
+ async finishReport(scope, source, sequence) {
542
+ if (sequence < 0n || sequence >= 0xffffffffffffffffn)
543
+ throw corrupt('coverage report sequence overflow');
544
+ const key = processingKey(scope, source);
545
+ return this.storage.transact(true, function* (tx) {
546
+ const current = processingValue(yield* tx.get(COVERAGE_SPACE, key));
547
+ if (current < sequence)
548
+ throw corrupt('coverage report gap');
549
+ if (current === sequence) {
550
+ const value = new Uint8Array(8);
551
+ new DataView(value.buffer).setBigUint64(0, sequence + 1n, false);
552
+ yield* tx.put(COVERAGE_SPACE, key, value);
553
+ }
554
+ });
555
+ }
556
+ async recordServed(scope, entries) {
557
+ return this.storage.transact(true, function* (tx) {
558
+ for (const e of entries) {
559
+ const key = cat(Uint8Array.of(7), scopeBytes(scope), e.turn, u32be(e.seq), e.fp);
560
+ if ((yield* tx.get(COVERAGE_SPACE, key)) === undefined)
561
+ yield* tx.put(COVERAGE_SPACE, key, new Uint8Array());
562
+ }
563
+ });
564
+ }
565
+ async wasServed(scope, turn, seq, fp) {
566
+ return this.storage.transact(false, function* (tx) {
567
+ return (yield* tx.get(COVERAGE_SPACE, cat(Uint8Array.of(7), scopeBytes(scope), turn, u32be(seq), fp))) !== undefined;
568
+ });
569
+ }
570
+ async unresolvedChildren(scope, parent) {
571
+ return this.storage.transact(false, function* (tx) {
572
+ const prefix = cat(Uint8Array.of(8), scopeBytes(scope), parent);
573
+ return (yield* tx.scan(COVERAGE_SPACE, prefix, successor(prefix), Number.MAX_SAFE_INTEGER)).map(([key]) => key.slice(-16));
574
+ });
575
+ }
576
+ async markReceived(scope, turn, seq, fp, isSeal, parents, unresolved) {
577
+ const self = this;
578
+ return this.storage.transact(true, function* (tx) {
579
+ const key = coverageKey(scope, turn), raw = yield* tx.get(COVERAGE_SPACE, key);
580
+ let dto;
581
+ if (raw === undefined)
582
+ dto = freshSummary();
583
+ else {
584
+ const record = decodeTurnRecord(raw);
585
+ dto = record.kind === 'summary' ? record.dto : yield* self.convertLegacy(tx, scope, turn, record.dto);
586
+ }
587
+ for (const p of dto.unresolved ?? []) {
588
+ const other = unresolved.find(x => compareBytes(x.turn, p.turn) === 0);
589
+ if (other && compareBytes(other.hash, p.hash) !== 0)
590
+ throw new CoverageError('invalid', 'parent declaration changed');
591
+ if (!other && !parents.some(x => compareBytes(x.turnId, p.turn) === 0))
592
+ throw new CoverageError('invalid', 'parent resolution omitted');
593
+ yield* tx.delete(COVERAGE_SPACE, cat(Uint8Array.of(8), scopeBytes(scope), Uint8Array.from(p.turn), turn));
594
+ }
595
+ if (unresolved.length)
596
+ dto.unresolved = unresolved;
597
+ else
598
+ delete dto.unresolved;
599
+ dto.v = unresolved.length ? 3 : 2;
600
+ for (const p of parentsToDto(parents)) {
601
+ const old = dto.parents.find(x => compareBytes(x.turn, p.turn) === 0);
602
+ if (old && compareBytes(old.seal_fp, p.seal_fp) !== 0)
603
+ throw new CoverageError('invalid', 'parent binding changed');
604
+ if (!old)
605
+ dto.parents.push(p);
606
+ }
607
+ dto.parents.sort((a, b) => compareBytes(a.turn, b.turn));
608
+ for (const p of unresolved)
609
+ yield* tx.put(COVERAGE_SPACE, cat(Uint8Array.of(8), scopeBytes(scope), Uint8Array.from(p.turn), turn), new Uint8Array());
610
+ yield* tx.put(COVERAGE_SPACE, key, encodeWith(dto.v, dto));
611
+ return yield* self.markPresentIn(tx, scope, turn, seq, fp, isSeal, parentsToDto(parents));
612
+ });
613
+ }
614
+ async markPresent(scope, turn, seq, fingerprint, isSeal, parents) {
615
+ const turnCopy = idCopy(turn, 'turn id');
616
+ const fp = fp32(fingerprint);
617
+ u32(seq, 'seq');
618
+ const parentDtos = parentsToDto(parents);
619
+ return this.storage.transact(true, (tx) => this.markPresentIn(tx, scope, turnCopy, seq, fp, isSeal, parentDtos));
620
+ }
621
+ /** The mark-present logic inside a caller's transaction (the composition
622
+ * point for atomic multi-store operations, T3 — the Rust
623
+ * `mark_present_in`): the caller must run this inside a single write
624
+ * transaction of the shared owner. A turn whose record predates the
625
+ * chunked layout is converted inside this same transaction first (per-seq
626
+ * rows, island rows, summary), so a crash rolls the conversion back with
627
+ * the mark and the next mark retries it. */
628
+ *markPresentIn(tx, scope, turn, seq, fp, isSeal, parentDtos) {
629
+ const key = coverageKey(scope, turn);
630
+ const raw = yield* tx.get(COVERAGE_SPACE, key);
631
+ let summary;
632
+ if (raw === undefined)
633
+ summary = freshSummary();
634
+ else {
635
+ const record = decodeTurnRecord(raw);
636
+ summary = record.kind === 'summary'
637
+ ? record.dto
638
+ : yield* this.convertLegacy(tx, scope, turn, record.dto);
639
+ }
640
+ // The parent→child reverse index follows the persisted parent
641
+ // list, so closure can cascade regardless of mark arrival order
642
+ // (RS2-04); edges persisted before the index existed are healed
643
+ // here on the child's next mark.
644
+ yield* this.ensureParentEdges(tx, scope, turn, summary.parents);
645
+ yield* this.ensureParentEdges(tx, scope, turn, parentDtos);
646
+ // The persisted seal claim is authoritative: sealed turns are
647
+ // immutable, so a mark claiming a different seal seq is rejected
648
+ // before anything is written.
649
+ if (isSeal && summary.seal && summary.seal.seq !== seq)
650
+ throw new CoverageError('sealConflict', `seal conflict: persisted seal seq ${summary.seal.seq}, claimed seq ${seq}`, { cause: { existingSeq: summary.seal.seq, claimedSeq: seq } });
651
+ const skey = seqKey(scope, turn, seq);
652
+ const seqRaw = yield* tx.get(COVERAGE_SPACE, skey);
653
+ const seqFps = seqRaw === undefined ? undefined : decodeSeqRecord(seqRaw).fps;
654
+ if (seqFps?.some(existing => equalBytes(existing, fp))) {
655
+ // Exact duplicate: nothing is rewritten. The closed check still
656
+ // runs (dependencies may have closed since) but an identical
657
+ // persisted closed record is not rewritten.
658
+ const closed = yield* this.maybeCloseSummary(tx, scope, turn, summary, parentDtos);
659
+ if (closed) {
660
+ yield* this.cascadeClosed(tx, scope, turn);
661
+ return { kind: 'closed' };
662
+ }
663
+ return { kind: 'duplicate' };
664
+ }
665
+ if (seqFps !== undefined) {
666
+ // Content conflict at this position (CASE-06): keep both
667
+ // fingerprints, never overwrite, and leave a diagnostic.
668
+ const existing = seqFps[0];
669
+ const fps = [...seqFps, [...fp]];
670
+ fps.sort(compareBytes);
671
+ yield* tx.put(COVERAGE_SPACE, skey, encodeWith(SUMMARY_RECORD_VERSION, { v: SUMMARY_RECORD_VERSION, fps }));
672
+ if (!summary.parents.length && parentDtos.length) {
673
+ summary.parents = parentDtos;
674
+ yield* tx.put(COVERAGE_SPACE, key, encodeWith(summary.v, summary));
675
+ }
676
+ yield* this.recordConflict(tx, scope, turn, seq, existing, fp);
677
+ return { kind: 'contentConflict', existing: Uint8Array.from(existing) };
678
+ }
679
+ // A genuinely new seq.
680
+ if (summary.seqs >= MAX_PRESENT_SEQS)
681
+ throw invalid(`turn coverage seq limit ${MAX_PRESENT_SEQS} reached`);
682
+ yield* tx.put(COVERAGE_SPACE, skey, encodeWith(SUMMARY_RECORD_VERSION, { v: SUMMARY_RECORD_VERSION, fps: [[...fp]] }));
683
+ summary.seqs += 1;
684
+ if (isSeal && summary.seal === null)
685
+ summary.seal = { seq, fp: [...fp] };
686
+ if (!summary.parents.length && parentDtos.length)
687
+ summary.parents = parentDtos;
688
+ if (seq === summary.prefix_len) {
689
+ // The prefix advances and drains the absorbed islands; each seq
690
+ // crosses the prefix at most once (amortized O(1) per op).
691
+ summary.prefix_len += 1;
692
+ while ((yield* tx.get(COVERAGE_SPACE, seqKey(scope, turn, summary.prefix_len))) !== undefined) {
693
+ yield* tx.delete(COVERAGE_SPACE, islandKey(scope, turn, summary.prefix_len));
694
+ if (summary.islands)
695
+ summary.islands.count -= 1;
696
+ summary.prefix_len += 1;
697
+ }
698
+ if (summary.islands) {
699
+ if (summary.islands.count === 0)
700
+ summary.islands = null;
701
+ else {
702
+ const prefix = islandPrefix(scope, turn);
703
+ if (summary.islands.min < summary.prefix_len) {
704
+ // The minimum was absorbed: the new minimum is the
705
+ // first remaining island row at or past the prefix.
706
+ const rows = yield* tx.scan(COVERAGE_SPACE, cat(prefix, u32be(summary.prefix_len)), successor(prefix), 1);
707
+ if (!rows.length)
708
+ throw corrupt('island summary without island rows');
709
+ summary.islands = { ...summary.islands, min: keyU32(rows[0][0]) };
710
+ }
711
+ if (summary.islands.max < summary.prefix_len)
712
+ // Unreachable in correct operation (the drain counted
713
+ // every absorbed island); anything else is corruption.
714
+ throw corrupt('island max below the prefix with islands remaining');
715
+ }
716
+ }
717
+ }
718
+ else if (seq > summary.prefix_len) {
719
+ // A new island beyond the contiguous prefix.
720
+ yield* tx.put(COVERAGE_SPACE, islandKey(scope, turn, seq), new Uint8Array(0));
721
+ summary.islands = summary.islands === null
722
+ ? { count: 1, min: seq, max: seq }
723
+ : { count: summary.islands.count + 1, min: Math.min(summary.islands.min, seq), max: Math.max(summary.islands.max, seq) };
724
+ }
725
+ else
726
+ // A new seq below the prefix contradicts the layout invariant
727
+ // (every seq below the prefix is present, hence has a record).
728
+ throw corrupt('new seq below the covered prefix');
729
+ yield* tx.put(COVERAGE_SPACE, key, encodeWith(summary.v, summary));
730
+ const closed = yield* this.maybeCloseSummary(tx, scope, turn, summary, parentDtos);
731
+ if (closed) {
732
+ yield* this.cascadeClosed(tx, scope, turn);
733
+ return { kind: 'closed' };
734
+ }
735
+ return { kind: 'stored' };
736
+ }
737
+ /** Convert a legacy whole-turn record to the chunked layout inside the
738
+ * caller's transaction: one per-seq row per distinct seq (both copies of
739
+ * a conflict), one island row per out-of-prefix seq, and the summary
740
+ * written last. Purely deterministic from the legacy record. */
741
+ *convertLegacy(tx, scope, turn, legacy) {
742
+ const bySeq = new Map();
743
+ for (const entry of legacy.seqs) {
744
+ let list = bySeq.get(entry.seq);
745
+ if (!list)
746
+ bySeq.set(entry.seq, list = []);
747
+ list.push(entry.fp);
748
+ }
749
+ for (const [seq, fps] of bySeq)
750
+ yield* tx.put(COVERAGE_SPACE, seqKey(scope, turn, seq), encodeWith(SUMMARY_RECORD_VERSION, { v: SUMMARY_RECORD_VERSION, fps }));
751
+ for (const hole of legacy.holes)
752
+ yield* tx.put(COVERAGE_SPACE, islandKey(scope, turn, hole), new Uint8Array(0));
753
+ const summary = {
754
+ v: SUMMARY_RECORD_VERSION,
755
+ prefix_len: legacy.prefix_len,
756
+ seal: legacy.seal,
757
+ parents: legacy.parents,
758
+ seqs: bySeq.size,
759
+ islands: legacy.holes.length
760
+ ? { count: legacy.holes.length, min: legacy.holes[0], max: legacy.holes[legacy.holes.length - 1] }
761
+ : null,
762
+ };
763
+ yield* tx.put(COVERAGE_SPACE, coverageKey(scope, turn), encodeWith(summary.v, summary));
764
+ return summary;
765
+ }
766
+ /** Whether seq `seq` of `turn` is confirmed present on this target
767
+ * (inside the prefix or an explicit island), regardless of fingerprint. */
768
+ async isPresent(scope, turn, seq) {
769
+ u32(seq, 'seq');
770
+ const turnCopy = idCopy(turn, 'turn id');
771
+ return this.storage.transact(false, function* (tx) {
772
+ // A present seq of a chunked turn always has its per-seq record.
773
+ if ((yield* tx.get(COVERAGE_SPACE, seqKey(scope, turnCopy, seq))) !== undefined)
774
+ return true;
775
+ const raw = yield* tx.get(COVERAGE_SPACE, coverageKey(scope, turnCopy));
776
+ if (raw === undefined)
777
+ return false;
778
+ const record = decodeTurnRecord(raw);
779
+ if (record.kind === 'summary')
780
+ return seq < record.dto.prefix_len;
781
+ const dto = record.dto;
782
+ if (seq < dto.prefix_len)
783
+ return true;
784
+ let low = 0, high = dto.holes.length;
785
+ while (low < high) {
786
+ const mid = (low + high) >> 1;
787
+ if (dto.holes[mid] < seq)
788
+ low = mid + 1;
789
+ else
790
+ high = mid;
791
+ }
792
+ return low < dto.holes.length && dto.holes[low] === seq;
793
+ });
794
+ }
795
+ /** The full present state of `turn` on this target, or undefined when the
796
+ * turn was never marked in this scope. This is the full-read path: for
797
+ * the chunked layout it scans the turn's per-seq and island rows and
798
+ * re-computes every stored invariant instead of trusting them. */
799
+ async presentState(scope, turn) {
800
+ const key = coverageKey(scope, turn);
801
+ return this.storage.transact(false, function* (tx) {
802
+ const raw = yield* tx.get(COVERAGE_SPACE, key);
803
+ if (raw === undefined)
804
+ return undefined;
805
+ const record = decodeTurnRecord(raw);
806
+ if (record.kind === 'legacy') {
807
+ const dto = record.dto;
808
+ const fingerprints = new Map();
809
+ for (const entry of dto.seqs) {
810
+ let list = fingerprints.get(entry.seq);
811
+ if (!list)
812
+ fingerprints.set(entry.seq, list = []);
813
+ list.push(Uint8Array.from(entry.fp));
814
+ }
815
+ for (const list of fingerprints.values())
816
+ list.sort(compareBytes);
817
+ return {
818
+ prefixLen: dto.prefix_len,
819
+ holes: dto.holes,
820
+ seal: dto.seal ? { seq: dto.seal.seq, fp: Uint8Array.from(dto.seal.fp) } : null,
821
+ parents: dto.parents.map(parent => ({ turnId: Uint8Array.from(parent.turn), sealFp: Uint8Array.from(parent.seal_fp) })),
822
+ fingerprints,
823
+ };
824
+ }
825
+ const summary = record.dto;
826
+ // Scan the per-seq records and the island markers.
827
+ const sprefix = seqPrefix(scope, turn);
828
+ const seqRows = yield* tx.scan(COVERAGE_SPACE, sprefix, successor(sprefix), ALL);
829
+ const fingerprints = new Map();
830
+ for (const [rowKey, rowValue] of seqRows)
831
+ fingerprints.set(keyU32(rowKey), decodeSeqRecord(rowValue).fps.map(fp => Uint8Array.from(fp)));
832
+ const iprefix = islandPrefix(scope, turn);
833
+ const islandRows = yield* tx.scan(COVERAGE_SPACE, iprefix, successor(iprefix), ALL);
834
+ const holes = islandRows.map(([rowKey]) => keyU32(rowKey));
835
+ // Recompute and cross-check every stored invariant.
836
+ const presentSeqs = [...fingerprints.keys()].sort((a, b) => a - b);
837
+ let prefixLen = 0;
838
+ const presentSet = new Set(presentSeqs);
839
+ while (presentSet.has(prefixLen))
840
+ prefixLen++;
841
+ if (prefixLen !== summary.prefix_len)
842
+ throw corrupt('summary prefix disagrees with per-seq records');
843
+ const recomputedHoles = presentSeqs.filter(seq => seq >= prefixLen);
844
+ if (recomputedHoles.length !== holes.length || recomputedHoles.some((seq, i) => seq !== holes[i]))
845
+ throw corrupt('island rows disagree with per-seq records');
846
+ if (summary.seqs !== presentSeqs.length)
847
+ throw corrupt('summary seq count disagrees with per-seq records');
848
+ if (summary.islands === null) {
849
+ if (holes.length)
850
+ throw corrupt('island rows without an island summary');
851
+ }
852
+ else {
853
+ const islands = summary.islands;
854
+ if (islands.count !== holes.length || islands.min !== holes[0] || islands.max !== holes[holes.length - 1])
855
+ throw corrupt('island summary disagrees with island rows');
856
+ }
857
+ if (summary.seal && !(fingerprints.get(summary.seal.seq)?.some(fp => equalBytes(fp, summary.seal.fp)) ?? false))
858
+ throw corrupt('seal claim without matching fingerprint');
859
+ return {
860
+ prefixLen: summary.prefix_len,
861
+ holes,
862
+ seal: summary.seal ? { seq: summary.seal.seq, fp: Uint8Array.from(summary.seal.fp) } : null,
863
+ parents: summary.parents.map(parent => ({ turnId: Uint8Array.from(parent.turn), sealFp: Uint8Array.from(parent.seal_fp) })),
864
+ fingerprints,
865
+ };
866
+ });
867
+ }
868
+ /** The persisted `closed` assertion of `turn` on this target, or
869
+ * undefined when the turn is not closed here. Only the small closed
870
+ * record is read — never ancestor bodies. */
871
+ async isClosed(scope, turn) {
872
+ const key = closedKey(scope, turn);
873
+ return this.storage.transact(false, function* (tx) {
874
+ const raw = yield* tx.get(COVERAGE_SPACE, key);
875
+ if (raw === undefined)
876
+ return undefined;
877
+ const dto = toClosedDto(checkVersionWith(raw, RECORD_VERSION));
878
+ return { sealSeq: dto.seal_seq, sealFp: Uint8Array.from(dto.seal_fp) };
879
+ });
880
+ }
881
+ /** Declare that `remote` moves from `oldGeneration` to `newGeneration`.
882
+ * Coverage is scoped per generation in every key, so the new generation
883
+ * already starts empty and the old records stay in place, readable only
884
+ * through the old generation. This call only enforces the ordering
885
+ * contract with RemoteRegistry.rebind: archive before any new-generation
886
+ * write, never after. It commits nothing. */
887
+ async archiveGeneration(remote, oldGeneration, newGeneration) {
888
+ if (sameGeneration(oldGeneration, newGeneration))
889
+ throw invalid('cannot archive a generation onto itself');
890
+ const remoteCopy = idCopy(remote, 'remote id');
891
+ await this.storage.transact(false, function* (tx) {
892
+ for (const tag of [COVERAGE_KEY_TAG, CLOSED_KEY_TAG, SEQ_KEY_TAG, ISLAND_KEY_TAG]) {
893
+ const prefix = remoteGenPrefix(tag, remoteCopy, newGeneration);
894
+ const rows = yield* tx.scan(COVERAGE_SPACE, prefix, successor(prefix), 1);
895
+ if (rows.length)
896
+ throw new CoverageError('generationConflict', 'generation already has coverage records', { cause: { generation: newGeneration } });
897
+ }
898
+ });
899
+ }
900
+ /** Exact presence of one operation's content — `(turn, seq, fingerprint)`
901
+ * — inside a caller's transaction (the composition point for a
902
+ * scheduler's per-operation dependency gate; the Rust
903
+ * `present_exact_in`). Same-position different-content never satisfies
904
+ * this check. The hot path is one small per-seq read; a turn whose record
905
+ * predates the chunked layout answers from its legacy record until its
906
+ * next mark converts it. */
907
+ *presentExactIn(tx, scope, turn, seq, fingerprint) {
908
+ const raw = yield* tx.get(COVERAGE_SPACE, seqKey(scope, turn, seq));
909
+ if (raw !== undefined)
910
+ return decodeSeqRecord(raw).fps.some(fp => equalBytes(fp, fingerprint));
911
+ const recordRaw = yield* tx.get(COVERAGE_SPACE, coverageKey(scope, turn));
912
+ if (recordRaw === undefined)
913
+ return false;
914
+ const record = decodeTurnRecord(recordRaw);
915
+ if (record.kind === 'summary')
916
+ // A present seq of a chunked turn always has its per-seq record.
917
+ return false;
918
+ return record.dto.seqs.some(entry => entry.seq === seq && equalBytes(entry.fp, fingerprint));
919
+ }
920
+ /** Whether `turn`'s persisted closed assertion exists and matches
921
+ * `sealFp`, inside a caller's transaction (the Rust `closed_matches_in`).
922
+ * A closed record asserts the full `0..=seal_seq` range and every direct
923
+ * dependency, so matching its seal fingerprint binds the exact sealed
924
+ * ancestry (T5). */
925
+ *closedMatchesIn(tx, scope, turn, sealFp) {
926
+ const raw = yield* tx.get(COVERAGE_SPACE, closedKey(scope, turn));
927
+ if (raw === undefined)
928
+ return false;
929
+ const dto = toClosedDto(checkVersionWith(raw, RECORD_VERSION));
930
+ return equalBytes(dto.seal_fp, sealFp);
931
+ }
932
+ /** Whether this target demonstrably holds the *complete* operation range
933
+ * of `turn` (`0..=seal_seq`, with `sealFp` at the seal position) without
934
+ * asserting anything about `turn`'s own ancestors — the direct
935
+ * precondition for admitting a child of `turn`. `closedMatchesIn` implies
936
+ * it; the converse does not hold, and the direct form is what a
937
+ * reverse-history window honestly establishes for a partial replica
938
+ * (N017 P1-C). Mirror of `complete_matches_in` in src/sync/coverage.rs. */
939
+ *completeMatchesIn(tx, scope, turn, sealFp) {
940
+ const raw = yield* tx.get(COVERAGE_SPACE, coverageKey(scope, turn));
941
+ if (raw === undefined)
942
+ return false;
943
+ const record = decodeTurnRecord(raw);
944
+ const seal = record.dto.seal;
945
+ if (seal === null)
946
+ return false;
947
+ const complete = record.kind === 'summary'
948
+ ? prefixCompleteSummary(record.dto, seal.seq)
949
+ : prefixCompleteLegacy(record.dto, seal.seq);
950
+ if (!complete)
951
+ return false;
952
+ const sealFpAt = Uint8Array.from(seal.fp);
953
+ if (!equalBytes(sealFpAt, sealFp))
954
+ return false;
955
+ // The persisted claim must still be backed by the exact frame: the
956
+ // per-seq row keeps every fingerprint observed at that position.
957
+ const seqRaw = yield* tx.get(COVERAGE_SPACE, seqKey(scope, turn, seal.seq));
958
+ if (seqRaw === undefined)
959
+ return false;
960
+ return decodeSeqRecord(seqRaw).fps.some(fp => equalBytes(fp, sealFpAt));
961
+ }
962
+ /** Whether a task depending on `turn` (a cross-turn parent bound to
963
+ * `sealFp`) may be sent to this target: the recursive `closed` assertion,
964
+ * or the direct complete-turn evidence a reverse-history window
965
+ * establishes. */
966
+ *parentAdmissibleIn(tx, scope, turn, sealFp) {
967
+ if (yield* this.closedMatchesIn(tx, scope, turn, sealFp))
968
+ return true;
969
+ return yield* this.completeMatchesIn(tx, scope, turn, sealFp);
970
+ }
971
+ /** Persist the parent→child reverse edges declared by `parents` for
972
+ * `turn`, inside the caller's transaction (idempotent; missing rows of
973
+ * already-persisted edges are healed here). */
974
+ *ensureParentEdges(tx, scope, turn, parents) {
975
+ for (const parent of parents) {
976
+ const key = childKey(scope, Uint8Array.from(parent.turn), turn);
977
+ const existing = yield* tx.get(COVERAGE_SPACE, key);
978
+ if (existing === undefined)
979
+ yield* tx.put(COVERAGE_SPACE, key, new Uint8Array(0));
980
+ }
981
+ }
982
+ /** Re-evaluate closure for every turn that declared `turn` as a direct
983
+ * parent, recursively, inside the caller's transaction (T5 extension,
984
+ * RS2-04): closed records are persisted assertions, so a turn whose marks
985
+ * completed before its parent closed must still close once the parent
986
+ * does — mark arrival order must not decide liveness. Each turn closes at
987
+ * most once, so the walk is bounded by the number of newly closed turns
988
+ * and never rewrites an existing closed record. Children whose records
989
+ * predate the chunked layout are evaluated from their legacy record (they
990
+ * convert on their own next mark, never here). */
991
+ *cascadeClosed(tx, scope, turn) {
992
+ const stack = [turn];
993
+ while (stack.length) {
994
+ const closedTurn = stack.pop();
995
+ const prefix = childPrefix(scope, closedTurn);
996
+ const rows = yield* tx.scan(COVERAGE_SPACE, prefix, successor(prefix), ALL);
997
+ for (const [key] of rows) {
998
+ const child = key.slice(key.length - 16);
999
+ const closedRaw = yield* tx.get(COVERAGE_SPACE, closedKey(scope, child));
1000
+ if (closedRaw !== undefined)
1001
+ continue;
1002
+ const raw = yield* tx.get(COVERAGE_SPACE, coverageKey(scope, child));
1003
+ if (raw === undefined)
1004
+ throw corrupt('child index row without a coverage record');
1005
+ const record = decodeTurnRecord(raw);
1006
+ const closed = record.kind === 'legacy'
1007
+ ? yield* this.maybeCloseLegacy(tx, scope, child, record.dto, [])
1008
+ : yield* this.maybeCloseSummary(tx, scope, child, record.dto, []);
1009
+ if (closed)
1010
+ stack.push(child);
1011
+ }
1012
+ }
1013
+ }
1014
+ /** Write the closed record when a chunked-layout turn just became
1015
+ * eligible; returns whether a new closed record was written. Eligibility:
1016
+ * a persisted seal claim whose fingerprint is present (one per-seq read),
1017
+ * the full prefix `0..=seal_seq` present (the O(1) island check,
1018
+ * CASE-05), and every direct dependency closed. */
1019
+ *maybeCloseSummary(tx, scope, turn, dto, parents) {
1020
+ if (dto.unresolved?.length)
1021
+ return false;
1022
+ const seal = dto.seal;
1023
+ if (seal === null)
1024
+ return false;
1025
+ const raw = yield* tx.get(COVERAGE_SPACE, seqKey(scope, turn, seal.seq));
1026
+ const sealFpPresent = raw !== undefined && decodeSeqRecord(raw).fps.some(fp => equalBytes(fp, seal.fp));
1027
+ if (!sealFpPresent || !prefixCompleteSummary(dto, seal.seq))
1028
+ return false;
1029
+ return yield* this.closeWithDeps(tx, scope, turn, dto.parents, parents, seal);
1030
+ }
1031
+ /** Write the closed record when a legacy-record turn just became eligible
1032
+ * (the cascade re-evaluates children regardless of their layout). */
1033
+ *maybeCloseLegacy(tx, scope, turn, dto, parents) {
1034
+ const seal = dto.seal;
1035
+ if (seal === null)
1036
+ return false;
1037
+ const sealFpPresent = dto.seqs.some(entry => entry.seq === seal.seq && equalBytes(entry.fp, seal.fp));
1038
+ if (!sealFpPresent || !prefixCompleteLegacy(dto, seal.seq))
1039
+ return false;
1040
+ return yield* this.closeWithDeps(tx, scope, turn, dto.parents, parents, seal);
1041
+ }
1042
+ /** The shared tail of the closed check: every direct dependency
1043
+ * (persisted parents plus this call's, deduped) must be closed with a
1044
+ * matching seal fingerprint; then the closed record is written once and
1045
+ * never changed. */
1046
+ *closeWithDeps(tx, scope, turn, persistedParents, parents, seal) {
1047
+ const deps = [];
1048
+ for (const parent of [...persistedParents, ...parents]) {
1049
+ if (!deps.some(dep => equalBytes(dep.turn, parent.turn) && equalBytes(dep.seal_fp, parent.seal_fp)))
1050
+ deps.push(parent);
1051
+ }
1052
+ for (const dep of deps) {
1053
+ const raw = yield* tx.get(COVERAGE_SPACE, closedKey(scope, Uint8Array.from(dep.turn)));
1054
+ if (raw === undefined)
1055
+ return false;
1056
+ const closed = toClosedDto(checkVersionWith(raw, RECORD_VERSION));
1057
+ if (!equalBytes(closed.seal_fp, dep.seal_fp))
1058
+ return false;
1059
+ }
1060
+ const key = closedKey(scope, turn);
1061
+ const value = encode({ v: RECORD_VERSION, seal_seq: seal.seq, seal_fp: seal.fp });
1062
+ const existing = yield* tx.get(COVERAGE_SPACE, key);
1063
+ if (existing !== undefined) {
1064
+ if (equalBytes(existing, value))
1065
+ return false;
1066
+ throw corrupt('closed record changed after being persisted');
1067
+ }
1068
+ yield* tx.put(COVERAGE_SPACE, key, value);
1069
+ return true;
1070
+ }
1071
+ /** Append both fingerprints of a content conflict to the diagnostic
1072
+ * record of one `(turn, seq)`; diagnostics are observability only. */
1073
+ *recordConflict(tx, scope, turn, seq, existing, fresh) {
1074
+ const key = conflictKey(scope, turn, seq);
1075
+ const raw = yield* tx.get(COVERAGE_SPACE, key);
1076
+ const fps = raw === undefined ? [] : toConflictDto(checkVersionWith(raw, RECORD_VERSION)).fps.map(fp => [...fp]);
1077
+ for (const fp of [existing, [...fresh]]) {
1078
+ if (!fps.some(entry => equalBytes(entry, fp)))
1079
+ fps.push(fp);
1080
+ }
1081
+ fps.sort(compareBytes);
1082
+ yield* tx.put(COVERAGE_SPACE, key, encode({ v: RECORD_VERSION, fps }));
1083
+ }
1084
+ }