@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,663 @@
1
+ import { blake3 } from '@noble/hashes/blake3.js';
2
+ import { decodeFrame, encodeBatch, splitBatch } from '../codec.js';
3
+ import { BatchFramer, FRAMING_WINDOW } from '../framing.js';
4
+ import { Inbox, InboxError } from '../inbox.js';
5
+ import { DurableReplay, ReplayError } from '../replay.js';
6
+ import { StoreError } from '../store.js';
7
+ import { CoverageError, CoverageStore } from './coverage.js';
8
+ import { ExecuteError, Executor, TransportError } from './execute.js';
9
+ import { PolicyError, PolicyStore } from './policy.js';
10
+ import { generationKeyFragment } from './registry.js';
11
+ import { WorkError } from './work.js';
12
+ import { openFirstEnvelopeAsync } from './crypto.js';
13
+ import { CryptoError } from './crypto.js';
14
+ /**
15
+ * One bidirectional sync link between a local stream and one remote (N1),
16
+ * the IndexedDB mirror of src/sync/link.rs: the download loop that reads
17
+ * the remote's durable log into the local store, layered on the existing
18
+ * Inbox/Replay durable machinery, plus a thin upload-cycle convenience over
19
+ * the RS2-03 executor.
20
+ *
21
+ * # Download contract (T4)
22
+ *
23
+ * Catch-up pages are fetched OUTSIDE every transaction
24
+ * (`ReadTransport.readOnce`). Each complete RST1 batch the page carries is
25
+ * durably received into the per-(stream, remote-generation) Inbox ledger
26
+ * with a cursor-chained receipt — cursor
27
+ * `0x01 || fetch_len[1] || fetch_offset || next_len[1] || next_offset ||
28
+ * byte_skip[4 BE] || page_len[4 BE]` — so a crash mid-page resumes from the
29
+ * head receipt's fetch offset, skips the received prefix, and re-receives
30
+ * the rest (exact retries are deduped by the Inbox). The Replay runner then
31
+ * imports each receipt in order through the real store (full
32
+ * seal/signature/dependency verification — nothing is trusted from the
33
+ * transport), and the frames it admitted (Applied/Duplicate/Pending — never
34
+ * Rejected) are marked present-exact on this remote's coverage scope: the
35
+ * K(remote) lower bound includes what the remote demonstrably serves, which
36
+ * is also what stops a mirrored backfill from re-uploading it. Remote
37
+ * imports never echo into the application outbox (the core's standing rule)
38
+ * and never mark coverage from bytes the store refused.
39
+ *
40
+ * Network, receipt persistence, import and coverage marks are all atomic
41
+ * per batch; the durable download position never advances past received
42
+ * work, and a stopped cycle reports itself instead of faking completion.
43
+ */
44
+ /** Errors of link operations. Semantic rejections roll their transaction
45
+ * back; nothing is half-committed. */
46
+ export class LinkError extends Error {
47
+ code;
48
+ constructor(code, message = code, options) {
49
+ super(message, options);
50
+ this.code = code;
51
+ this.name = 'LinkError';
52
+ }
53
+ }
54
+ const invalid = (message) => new LinkError('invalid', message);
55
+ /** Re-throw a failure of one of the composed stores as its typed LinkError
56
+ * (the mirror of the Rust `#[from]` conversions), leaving LinkErrors and
57
+ * unknown throws untouched. */
58
+ const rethrow = (e) => {
59
+ if (e instanceof LinkError)
60
+ throw e;
61
+ if (e instanceof TransportError)
62
+ throw new LinkError('transport', `transport failure: ${e.message}`, { cause: e });
63
+ if (e instanceof InboxError)
64
+ throw new LinkError('inbox', `inbox failure: ${e.message}`, { cause: e });
65
+ if (e instanceof ReplayError)
66
+ throw new LinkError('replay', `replay failure: ${e.message}`, { cause: e });
67
+ if (e instanceof CoverageError)
68
+ throw new LinkError('coverage', `coverage failure: ${e.message}`, { cause: e });
69
+ if (e instanceof PolicyError)
70
+ throw new LinkError('policy', `policy failure: ${e.message}`, { cause: e });
71
+ if (e instanceof ExecuteError)
72
+ throw new LinkError('execute', `execute failure: ${e.message}`, { cause: e });
73
+ if (e instanceof WorkError)
74
+ throw new LinkError('work', `work failure: ${e.message}`, { cause: e });
75
+ if (e instanceof StoreError)
76
+ throw new LinkError('store', `store failure: ${e.message}`, { cause: e });
77
+ throw e;
78
+ };
79
+ /** Wire-derived limits: a receipt is one complete RST1 batch (bounded by the
80
+ * wire ceiling); cursors carry two offsets and an index; ledgers are retained
81
+ * without GC, so the record/byte caps are corruption tripwires, not product
82
+ * budgets. */
83
+ export const linkLimitsForSync = () => ({
84
+ inbox: {
85
+ maxBatchBytes: 64 * 1024 * 1024 + 64,
86
+ maxCursorBytes: 1024,
87
+ maxNamespaceBytes: 256,
88
+ maxRecords: 1n << 40n,
89
+ maxRetainedBytes: 1n << 46n,
90
+ maxPageRecords: 1 << 20,
91
+ },
92
+ replay: {
93
+ maxBatchBytes: 64 * 1024 * 1024 + 64,
94
+ maxReportBytes: 64 * 1024 * 1024 + 64,
95
+ maxRetainedReportBytes: 1n << 46n,
96
+ maxPageRecords: 1 << 20,
97
+ },
98
+ });
99
+ const ASCII = /^[\x00-\x7F]*$/;
100
+ /** Cursor codec for the download receipts (opaque to the Inbox):
101
+ * `0x01 || fetch_len[1] || fetch_offset || next_len[1] || next_offset ||
102
+ * byte_skip[4 BE] || page_len[4 BE]`. `fetchOffset` is the offset the page
103
+ * was fetched AT (the resume point); `nextOffset` the page's end;
104
+ * `byteSkip` is how many bytes of the page are already consumed into
105
+ * received batches (always a batch boundary, so a spanning batch is never
106
+ * lost on resume); `pageLen` is the page's payload length, letting the
107
+ * position report the page end once it is fully received. */
108
+ function encodeCursor(fetchOffset, nextOffset, byteSkip, pageLen) {
109
+ for (const offset of [fetchOffset, nextOffset]) {
110
+ if (offset.length === 0 || offset.length > 255)
111
+ throw invalid(`offset length ${offset.length} out of cursor budget`);
112
+ if (!ASCII.test(offset))
113
+ throw invalid('offset must be ASCII');
114
+ }
115
+ if (!Number.isSafeInteger(byteSkip) || byteSkip < 0 || byteSkip > 0xFFFFFFFF)
116
+ throw invalid('byte skip');
117
+ if (!Number.isSafeInteger(pageLen) || pageLen < 0 || pageLen > 0xFFFFFFFF)
118
+ throw invalid('page length');
119
+ const out = new Uint8Array(11 + fetchOffset.length + nextOffset.length);
120
+ const view = new DataView(out.buffer);
121
+ out[0] = 0x01;
122
+ out[1] = fetchOffset.length;
123
+ for (let i = 0; i < fetchOffset.length; i++)
124
+ out[2 + i] = fetchOffset.charCodeAt(i);
125
+ out[2 + fetchOffset.length] = nextOffset.length;
126
+ for (let i = 0; i < nextOffset.length; i++)
127
+ out[3 + fetchOffset.length + i] = nextOffset.charCodeAt(i);
128
+ view.setUint32(out.length - 8, byteSkip, false);
129
+ view.setUint32(out.length - 4, pageLen, false);
130
+ return out;
131
+ }
132
+ function decodeCursor(cursor) {
133
+ const fail = () => invalid('corrupt download cursor');
134
+ if (cursor.length < 11 || cursor[0] !== 0x01)
135
+ throw fail();
136
+ const fetchLen = cursor[1];
137
+ const nextLenAt = 2 + fetchLen;
138
+ if (cursor.length < nextLenAt + 9)
139
+ throw fail();
140
+ const nextLen = cursor[nextLenAt];
141
+ if (cursor.length !== nextLenAt + 1 + nextLen + 8)
142
+ throw fail();
143
+ const text = new TextDecoder('utf-8', { fatal: true });
144
+ let fetch, next;
145
+ try {
146
+ fetch = text.decode(cursor.subarray(2, nextLenAt));
147
+ next = text.decode(cursor.subarray(nextLenAt + 1, nextLenAt + 1 + nextLen));
148
+ }
149
+ catch {
150
+ throw fail();
151
+ }
152
+ const view = new DataView(cursor.buffer, cursor.byteOffset, cursor.byteLength);
153
+ const byteSkip = view.getUint32(cursor.length - 8, false);
154
+ const pageLen = view.getUint32(cursor.length - 4, false);
155
+ if (byteSkip > pageLen)
156
+ throw fail();
157
+ return [fetch, next, byteSkip, pageLen];
158
+ }
159
+ const hex = (bytes) => Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
160
+ /** Push a turn id onto a report list at most once (Uint8Array identity is by
161
+ * content, not reference). */
162
+ function pushUnique(list, seen, id) {
163
+ const key = hex(id);
164
+ if (!seen.has(key)) {
165
+ seen.add(key);
166
+ list.push(id);
167
+ }
168
+ }
169
+ /** One bidirectional link between a local stream and one remote scope.
170
+ * Opened over the device's single storage owner; the download ledger
171
+ * namespace embeds the scope's full generation identity, so a rebound
172
+ * generation starts a fresh ledger while the old one stays retained. */
173
+ export class Link {
174
+ scope;
175
+ stream;
176
+ inbox;
177
+ replay;
178
+ coverage;
179
+ executor;
180
+ policy;
181
+ constructor(scope, stream, inbox, replay, coverage, executor, policy) {
182
+ this.scope = scope;
183
+ this.stream = stream;
184
+ this.inbox = inbox;
185
+ this.replay = replay;
186
+ this.coverage = coverage;
187
+ this.executor = executor;
188
+ this.policy = policy;
189
+ }
190
+ /** Open the link for one (stream, remote-generation) scope. The scope
191
+ * comes from `Executor.scope`; the executor it shares is created here
192
+ * over the same storage owner. */
193
+ static open(storage, stream, scope, limits) {
194
+ return Link.openWithReplay(storage, stream, scope, limits, false);
195
+ }
196
+ /** The partial-replica live path (N3/N019): receipts import through
197
+ * `importPartialBatch`, so a reverse-history window can keep catching
198
+ * up without requiring the ancestor chain. Coverage marks bind parents
199
+ * only where they are local. Mirror of `Link::open_partial`. */
200
+ static openPartial(storage, stream, scope, limits) {
201
+ return Link.openWithReplay(storage, stream, scope, limits, true);
202
+ }
203
+ static openWithReplay(storage, stream, scope, limits, partial) {
204
+ let fragment;
205
+ try {
206
+ fragment = generationKeyFragment(scope.generation);
207
+ }
208
+ catch (e) {
209
+ throw invalid(`generation key: ${e instanceof Error ? e.message : e}`);
210
+ }
211
+ const source = `remote:${hex(scope.remote)}/gen:${hex(fragment)}`;
212
+ const inbox = Inbox.open(storage, scope.stream, source, limits.inbox);
213
+ const replay = partial ? DurableReplay.openPartial(inbox, stream, limits.replay) : DurableReplay.open(inbox, stream, limits.replay);
214
+ return new Link(scope, stream, inbox, replay, new CoverageStore(storage), new Executor(storage), new PolicyStore(storage));
215
+ }
216
+ /** The durable fetch position of the next read (from the head receipt). */
217
+ async position() {
218
+ return (await this.#positionIn())?.fetchOffset;
219
+ }
220
+ /** Start live catch-up at `offset` without importing the prefix.
221
+ * Used after a reverse-history window. Does not mark coverage and
222
+ * does not claim that prefix. Idempotent at the same offset;
223
+ * a different established position is a typed error. Mirror of
224
+ * `Link::catch_up_at`. `offset` is the tail observed when the window
225
+ * was fetched — a later head skips concurrent appends. */
226
+ async catchUpAt(offset) {
227
+ const position = await this.#positionIn();
228
+ if (position !== undefined) {
229
+ if (position.fetchOffset !== offset)
230
+ throw invalid(`live position already at ${position.fetchOffset}, not ${offset}`);
231
+ const report = { pages: 0, batches: 0, appliedTurns: [], pendingTurns: [], upToDate: false, closed: false, stopped: false, position: undefined };
232
+ await this.#replayDrain(report, new Set(), new Set());
233
+ return;
234
+ }
235
+ const cursor = encodeCursor(offset, offset, 0, 0);
236
+ await this.inbox.receive(null, cursor, encodeBatch([]));
237
+ const report = { pages: 0, batches: 0, appliedTurns: [], pendingTurns: [], upToDate: false, closed: false, stopped: false, position: undefined };
238
+ await this.#replayDrain(report, new Set(), new Set());
239
+ }
240
+ async #positionIn() {
241
+ const state = await this.inbox.state();
242
+ if (state.cursor === null)
243
+ return undefined;
244
+ const [fetch, next, byteSkip, pageLen] = decodeCursor(state.cursor);
245
+ const exhausted = byteSkip >= pageLen;
246
+ return {
247
+ fetchOffset: exhausted ? next : fetch,
248
+ priorCursor: state.cursor,
249
+ skipBytes: exhausted ? 0 : byteSkip,
250
+ };
251
+ }
252
+ /** One bounded download cycle: keep fetching catch-up pages until the
253
+ * remote's tail (up-to-date or closed), a page cap, or the stop token —
254
+ * each completed batch received and replayed atomically before the next.
255
+ * The durable position is a batch-boundary byte skip, so a batch spanning
256
+ * two pages is never lost on resume (HTTP responses may split or coalesce
257
+ * appends arbitrarily). The page cap bounds completed pages; a batch
258
+ * spanning into the next page is always completed first (bounded by the
259
+ * wire ceiling), so a page-limited host always makes progress.
260
+ * `pageLimit === 0` reads to the tail in one call. */
261
+ async downloadCycle(transport, pageLimit, stop) {
262
+ try {
263
+ return await this.#downloadCycle(transport, pageLimit, stop);
264
+ }
265
+ catch (e) {
266
+ return rethrow(e);
267
+ }
268
+ }
269
+ async #downloadCycle(transport, pageLimit, stop) {
270
+ if (!await this.policy.allowsDownload(this.scope))
271
+ throw new LinkError('policyDenied', 'mirror policy denies download for this scope');
272
+ const report = {
273
+ pages: 0, batches: 0, appliedTurns: [], pendingTurns: [],
274
+ upToDate: false, closed: false, stopped: false, position: undefined,
275
+ };
276
+ const appliedSeen = new Set(), pendingSeen = new Set();
277
+ // A crash between a committed receipt and its replay left durable
278
+ // work behind: drain before any new fetch, or a log already at its
279
+ // tail would leave the leftover receipt unimported and unmarked
280
+ // forever (the runner is idle when caught up).
281
+ await this.#replayDrain(report, appliedSeen, pendingSeen);
282
+ // The durable resume position, read once: the head receipt's cursor,
283
+ // or the log's beginning sentinel before the first receipt.
284
+ const start = await this.#positionIn();
285
+ let offset = start?.fetchOffset ?? '-1';
286
+ let skip = start?.skipBytes ?? 0;
287
+ let priorCursor = start?.priorCursor ?? null;
288
+ const framer = new BatchFramer();
289
+ // The framer holds a partial batch from the previous page: the cycle
290
+ // must fetch past the page cap to complete it (bounded by the wire
291
+ // ceiling), or the durable position would pin the same fetch offset
292
+ // forever — a batch larger than one capped page can never complete
293
+ // across cycles that each drop the framer (Root review regression 1).
294
+ // Encrypted leftover is the same contract: skip/page_len stay on
295
+ // WIRE bytes so a crash can replay a trailing fragment.
296
+ let spanning = false;
297
+ const crypto = transport.payloadCrypto;
298
+ let envLeftover = new Uint8Array();
299
+ for (;;) {
300
+ if (pageLimit !== 0 && report.pages >= pageLimit && !spanning)
301
+ break;
302
+ if (stop.stopped) {
303
+ report.stopped = true;
304
+ break;
305
+ }
306
+ // Network outside every transaction. Payload is wire bytes.
307
+ const page = await transport.readOnce(offset);
308
+ report.pages++;
309
+ if (skip > page.payload.length)
310
+ throw invalid('resume skip exceeds the catch-up page');
311
+ let parseError;
312
+ let batchesThisPage = 0;
313
+ let needMore = false;
314
+ if (crypto !== undefined) {
315
+ const buf = new Uint8Array(envLeftover.length + page.payload.length - skip);
316
+ buf.set(envLeftover, 0);
317
+ buf.set(page.payload.subarray(skip), envLeftover.length);
318
+ const pageOrigin = envLeftover.length;
319
+ envLeftover = new Uint8Array();
320
+ let pos = 0;
321
+ while (pos < buf.length && parseError === undefined && !report.stopped) {
322
+ let opened;
323
+ try {
324
+ opened = await openFirstEnvelopeAsync(crypto, buf.subarray(pos));
325
+ }
326
+ catch (e) {
327
+ const message = e instanceof Error ? e.message : String(e);
328
+ parseError = new LinkError('transport', message, { cause: e instanceof CryptoError || e instanceof Error ? e : undefined });
329
+ break;
330
+ }
331
+ if (opened === undefined) {
332
+ envLeftover = Uint8Array.from(buf.subarray(pos));
333
+ break;
334
+ }
335
+ let fed = 0;
336
+ while (fed < opened.plaintext.length && parseError === undefined && !report.stopped) {
337
+ const end = Math.min(fed + FRAMING_WINDOW, opened.plaintext.length);
338
+ const pushed = framer.push(opened.plaintext.subarray(fed, end));
339
+ if (pushed.kind === 'batch') {
340
+ if (stop.stopped) {
341
+ report.stopped = true;
342
+ break;
343
+ }
344
+ const envEnd = pos + opened.wireLen;
345
+ const consumedPage = envEnd > pageOrigin ? envEnd - pageOrigin : 0;
346
+ const byteSkip = skip + consumedPage;
347
+ const cursor = encodeCursor(offset, page.nextOffset, byteSkip, page.payload.length);
348
+ await this.inbox.receive(priorCursor, cursor, pushed.bytes);
349
+ priorCursor = cursor;
350
+ await this.#replayDrain(report, appliedSeen, pendingSeen);
351
+ report.batches++;
352
+ batchesThisPage++;
353
+ fed += pushed.consumed;
354
+ needMore = false;
355
+ }
356
+ else if (pushed.kind === 'needMore') {
357
+ fed += pushed.consumed;
358
+ needMore = true;
359
+ }
360
+ else {
361
+ fed += pushed.consumed;
362
+ parseError = invalid(`catch-up page is not well-framed at byte ${fed}: ${pushed.reason}`);
363
+ }
364
+ }
365
+ pos += opened.wireLen;
366
+ }
367
+ if (pos < buf.length && envLeftover.length === 0 && parseError === undefined)
368
+ envLeftover = Uint8Array.from(buf.subarray(pos));
369
+ if (envLeftover.length !== 0 && (page.upToDate || page.closed))
370
+ throw new LinkError('transport', 'truncated envelope at stream tail (refusing plaintext fallback)');
371
+ }
372
+ else {
373
+ let fed = skip;
374
+ while (fed < page.payload.length && parseError === undefined && !report.stopped) {
375
+ const end = Math.min(fed + FRAMING_WINDOW, page.payload.length);
376
+ const pushed = framer.push(page.payload.subarray(fed, end));
377
+ if (pushed.kind === 'batch') {
378
+ if (stop.stopped) {
379
+ report.stopped = true;
380
+ break;
381
+ }
382
+ const byteSkip = fed + pushed.consumed;
383
+ const cursor = encodeCursor(offset, page.nextOffset, byteSkip, page.payload.length);
384
+ await this.inbox.receive(priorCursor, cursor, pushed.bytes);
385
+ priorCursor = cursor;
386
+ await this.#replayDrain(report, appliedSeen, pendingSeen);
387
+ report.batches++;
388
+ batchesThisPage++;
389
+ fed = byteSkip;
390
+ needMore = false;
391
+ }
392
+ else if (pushed.kind === 'needMore') {
393
+ fed += pushed.consumed;
394
+ needMore = true;
395
+ }
396
+ else {
397
+ fed += pushed.consumed;
398
+ parseError = invalid(`catch-up page is not well-framed at byte ${fed}: ${pushed.reason}`);
399
+ }
400
+ }
401
+ }
402
+ skip = 0;
403
+ spanning = (needMore || envLeftover.length !== 0) && !report.stopped;
404
+ if (parseError !== undefined)
405
+ throw parseError;
406
+ if (report.stopped)
407
+ break;
408
+ if (page.upToDate || page.closed) {
409
+ const finished = framer.finish();
410
+ if (finished.kind === 'end') {
411
+ report.upToDate = page.upToDate;
412
+ report.closed = page.closed;
413
+ }
414
+ else {
415
+ throw invalid(`the remote log ends mid-batch at its tail: ${finished.reason}`);
416
+ }
417
+ break;
418
+ }
419
+ if (page.nextOffset === offset && batchesThisPage === 0 && envLeftover.length === 0)
420
+ throw invalid('catch-up page made no progress');
421
+ offset = page.nextOffset;
422
+ }
423
+ report.position = await this.position();
424
+ return report;
425
+ }
426
+ /** Drain the replay runner to idle, marking coverage from every receipt
427
+ * it imports. A retryable import (pending quota) surfaces typed (the
428
+ * receipt stays unprocessed until the host resolves and retries). */
429
+ async #replayDrain(report, appliedSeen, pendingSeen) {
430
+ const source = intakeSource(this.scope, 'remote');
431
+ for (;;) {
432
+ const next = await this.coverage.processedReports(this.scope, source);
433
+ const record = (await this.replay.records(next === 0n ? null : next - 1n, 1))[0];
434
+ if (record) {
435
+ const receipt = await replayReceipt(this.inbox, record.sequence);
436
+ await recordServedBatch(receipt.bytes, this.coverage, this.scope);
437
+ if (record.outcome.kind === 'imported')
438
+ await this.#markFromBatch(receipt.bytes, report, record.outcome.report.statuses, record.outcome.report.applied, appliedSeen, pendingSeen);
439
+ await this.coverage.finishReport(this.scope, source, record.sequence);
440
+ continue;
441
+ }
442
+ await recordNextServed(this.inbox, this.replay, this.coverage, this.scope);
443
+ const step = await this.replay.step();
444
+ if (step.kind === 'idle')
445
+ return;
446
+ if (step.kind === 'raced')
447
+ throw invalid('a second replay runner checkpointed first');
448
+ if (step.kind === 'retry')
449
+ throw new LinkError('retryQuota', 'pending quota exceeded; a receipt remains unprocessed until the host resolves dependencies or capacity and retries');
450
+ }
451
+ }
452
+ /** Mark present-exact on this link's coverage scope from the LOCAL
453
+ * store, for every op the import admitted (Applied/Duplicate, plus any
454
+ * older pending the import unlocked): the fingerprints are the exact
455
+ * exported frame batches — byte-identical to what the upload path
456
+ * discovers — and parents resolve to the parent's seal frame batch, so
457
+ * closure and later adoption behave exactly as if these ops had been
458
+ * confirmed by this device's own upload. Rejected and still-pending
459
+ * frames are never marked: diagnostics and later unlocks only. */
460
+ async #markFromBatch(batch, report, statuses, applied, appliedSeen, pendingSeen) {
461
+ const scope = { remote: this.scope.remote, generation: this.scope.generation, stream: this.scope.stream };
462
+ const mark = this.replay.importMode === 'partial' ? markAdmittedFromBatchLocalParents : markAdmittedFromBatch;
463
+ await mark(this.stream, this.coverage, scope, batch, statuses, applied, report.appliedTurns, appliedSeen, report.pendingTurns, pendingSeen);
464
+ }
465
+ /** One upload cycle through the shared executor (resume → one discovery
466
+ * cycle → one bounded flush). Convenience over `Executor` keeping the
467
+ * host loop symmetrical with `downloadCycle`. */
468
+ async uploadCycle(stream, transport, maxSend) {
469
+ try {
470
+ if (!await this.policy.allowsUpload(this.scope))
471
+ throw new LinkError('policyDenied', 'mirror policy denies upload for this scope');
472
+ await this.executor.resume(this.scope);
473
+ const discovery = await this.executor.discoverCycle(stream, this.scope, 100);
474
+ const flushed = await this.executor.flush(this.scope, transport, maxSend);
475
+ return { discovery, flushed };
476
+ }
477
+ catch (e) {
478
+ return rethrow(e);
479
+ }
480
+ }
481
+ /** Offer downloaded turns to another scope's upload discovery. Turns
482
+ * whose parents are not local are collected into `waitingParent`
483
+ * (retryable, never fatal), so a bridge cycle never permanently stalls
484
+ * behind a missing Create (RS3-02/CASE-15). */
485
+ async bridgeTurns(stream, scope, ids) {
486
+ try {
487
+ const report = { discovered: [], waitingParent: [] };
488
+ for (const id of ids) {
489
+ try {
490
+ await this.executor.discoverTurns(stream, scope, [id]);
491
+ report.discovered.push(id);
492
+ }
493
+ catch (e) {
494
+ if (e instanceof ExecuteError && e.code === 'invalid'
495
+ && (e.message.includes('not readable') || e.message.includes('not sealed'))) {
496
+ report.waitingParent.push(id);
497
+ continue;
498
+ }
499
+ throw e;
500
+ }
501
+ }
502
+ return report;
503
+ }
504
+ catch (e) {
505
+ return rethrow(e);
506
+ }
507
+ }
508
+ }
509
+ /** Mark present-exact on a coverage scope from the LOCAL store, for every
510
+ * op the import admitted (Applied/Duplicate, plus any older pending the
511
+ * import unlocked): the fingerprints are the exact exported frame batches —
512
+ * byte-identical to what the upload path discovers — and parents resolve to
513
+ * the parent's seal frame batch, so closure and later adoption behave
514
+ * exactly as if these ops had been confirmed by this device's own upload.
515
+ * Rejected and still-pending frames are never marked: diagnostics and later
516
+ * unlocks only. Shared by the link's download loop and the history reader
517
+ * (N2): anything a remote demonstrably serves is present on it. The mirror
518
+ * of `mark_admitted_from_batch` in src/sync/link.rs. */
519
+ export async function markAdmittedFromBatch(stream, coverage, scope, batch, statuses, applied, appliedTurns, appliedSeen, pendingTurns, pendingSeen) {
520
+ await markAdmittedFromBatchInner(stream, coverage, scope, batch, statuses, applied, appliedTurns, appliedSeen, pendingTurns, pendingSeen, false);
521
+ }
522
+ /** The partial-replica intake's marking (N017 P1-C): real coverage evidence
523
+ * for the window's frames, with declared parents bound only where they are
524
+ * local. Mirror of `mark_admitted_from_batch_local_parents` in
525
+ * src/sync/link.rs. */
526
+ export async function markAdmittedFromBatchLocalParents(stream, coverage, scope, batch, statuses, applied, appliedTurns, appliedSeen, pendingTurns, pendingSeen) {
527
+ await markAdmittedFromBatchInner(stream, coverage, scope, batch, statuses, applied, appliedTurns, appliedSeen, pendingTurns, pendingSeen, true);
528
+ }
529
+ async function markAdmittedFromBatchInner(stream, coverage, scope, batch, statuses, applied, appliedTurns, appliedSeen, pendingTurns, pendingSeen, localParentsOnly) {
530
+ let frames;
531
+ try {
532
+ frames = splitBatch(batch);
533
+ }
534
+ catch (e) {
535
+ throw invalid(`received batch resplit: ${e instanceof Error ? e.message : e}`);
536
+ }
537
+ // The report lists what the import did (it applied the turn), which is a
538
+ // different question from what coverage could be marked for it: under
539
+ // `localParentsOnly` an admitted turn with an unbindable parent is still
540
+ // applied and displayable, it just carries no mark.
541
+ for (let i = 0; i < Math.min(frames.length, statuses.length); i++) {
542
+ const status = statuses[i];
543
+ if (status.kind === 'pending') {
544
+ // Pending bytes are real and retained; their turn waits for its
545
+ // parent's source. The mark comes when the dependency lands (a
546
+ // later report's `appliedTurns`).
547
+ const update = decodeFrame(frames[i]);
548
+ pushUnique(pendingTurns, pendingSeen, update.turnId);
549
+ continue;
550
+ }
551
+ if (status.kind === 'rejected')
552
+ // Rejected frames are diagnostics, never evidence.
553
+ continue;
554
+ const update = decodeFrame(frames[i]);
555
+ pushUnique(appliedTurns, appliedSeen, update.turnId);
556
+ await markOnePresent(stream, coverage, scope, update.turnId, update.seq, localParentsOnly);
557
+ }
558
+ for (const reference of applied) {
559
+ pushUnique(appliedTurns, appliedSeen, reference.turnId);
560
+ await markOnePresent(stream, coverage, scope, reference.turnId, reference.seq, localParentsOnly);
561
+ }
562
+ }
563
+ /** Mark one op present-exact from the local store (the import already
564
+ * committed it, so its dependencies are locally resolvable). With
565
+ * `localParentsOnly` a turn whose declared parent is not local is skipped
566
+ * entirely — no partial claim is written, so no closure is fabricated. */
567
+ export async function recordNextServed(inbox, replay, coverage, scope) {
568
+ const next = (await replay.state()).nextSequence;
569
+ const receipt = (await inbox.records(next === 0n ? null : next - 1n, 1))[0];
570
+ if (!receipt)
571
+ return;
572
+ await recordServedBatch(receipt.bytes, coverage, scope);
573
+ }
574
+ export function intakeSource(scope, kind) {
575
+ return `${kind}:${hex(scope.remote)}/gen:${hex(generationKeyFragment(scope.generation))}`;
576
+ }
577
+ export async function replayReceipt(inbox, sequence) {
578
+ const receipt = (await inbox.records(sequence === 0n ? null : sequence - 1n, 1))[0];
579
+ if (!receipt || receipt.sequence !== sequence)
580
+ throw invalid('replay record without matching receipt');
581
+ return receipt;
582
+ }
583
+ export async function recordServedBatch(bytes, coverage, scope) {
584
+ let frames;
585
+ try {
586
+ frames = splitBatch(bytes);
587
+ }
588
+ catch {
589
+ return;
590
+ }
591
+ const entries = [];
592
+ for (const frame of frames) {
593
+ try {
594
+ const update = decodeFrame(frame);
595
+ if (update.seq > 0xffffffffn)
596
+ continue;
597
+ // Rewrap the received frame; canonical codec preserves exact bytes.
598
+ const batch = encodeBatch([update]);
599
+ if (hex(splitBatch(batch)[0]) !== hex(frame))
600
+ continue;
601
+ entries.push({ turn: update.turnId, seq: Number(update.seq), fp: blake3(batch) });
602
+ }
603
+ catch {
604
+ continue;
605
+ }
606
+ }
607
+ await coverage.recordServed(scope, entries);
608
+ }
609
+ async function markOnePresent(stream, coverage, scope, turn, seq, localParentsOnly) {
610
+ const work = [{ turn, seq }], seen = new Set();
611
+ while (work.length) {
612
+ const item = work.pop(), key = hex(item.turn) + ':' + item.seq;
613
+ if (seen.has(key))
614
+ continue;
615
+ seen.add(key);
616
+ for (const child of await markOnePresentInner(stream, coverage, scope, item.turn, item.seq, localParentsOnly))
617
+ work.push({ turn: child, seq: 0n });
618
+ }
619
+ }
620
+ async function markOnePresentInner(stream, coverage, scope, turn, seq, localParentsOnly) {
621
+ const batch = await stream.exportUpdates(turn, seq, 1);
622
+ if (seq < 0n || seq > 0xffffffffn)
623
+ throw invalid('frame seq overflows u32');
624
+ if (!(await coverage.wasServed(scope, turn, Number(seq), blake3(batch))))
625
+ return [];
626
+ const headerResult = await stream.readTurnHeader(turn);
627
+ if (headerResult.kind !== 'found')
628
+ throw invalid(`turn ${hex(turn)} not readable after import`);
629
+ const header = headerResult.turn;
630
+ const parents = [];
631
+ const unresolved = [];
632
+ for (const parent of header.parents) {
633
+ const parentResult = await stream.readTurnHeader(parent.id);
634
+ if (parentResult.kind !== 'found') {
635
+ if (localParentsOnly) {
636
+ unresolved.push({ turn: [...parent.id], hash: [...parent.hash] });
637
+ continue;
638
+ }
639
+ throw invalid(`parent ${hex(parent.id)} of turn ${hex(turn)} not readable`);
640
+ }
641
+ const parentHeader = parentResult.turn;
642
+ if (parentHeader.sealed === null || parentHeader.nextSeq === 0n) {
643
+ if (localParentsOnly) {
644
+ unresolved.push({ turn: [...parent.id], hash: [...parent.hash] });
645
+ continue;
646
+ }
647
+ throw invalid(`parent ${hex(parent.id)} of turn ${hex(turn)} is not sealed`);
648
+ }
649
+ if (hex(parentHeader.sealed) !== hex(parent.hash)) {
650
+ if (localParentsOnly) {
651
+ unresolved.push({ turn: [...parent.id], hash: [...parent.hash] });
652
+ continue;
653
+ }
654
+ throw invalid('parent declaration hash mismatch');
655
+ }
656
+ const sealBatch = await stream.exportUpdates(parent.id, parentHeader.nextSeq - 1n, 1);
657
+ parents.push({ turnId: parent.id, sealFp: blake3(sealBatch) });
658
+ }
659
+ if (seq < 0n || seq > 0xffffffffn)
660
+ throw invalid('frame seq overflows u32');
661
+ await coverage.markReceived(scope, turn, Number(seq), blake3(batch), header.sealed !== null && seq === header.nextSeq - 1n, parents, unresolved);
662
+ return header.sealed !== null ? coverage.unresolvedChildren(scope, turn) : [];
663
+ }