@loro-dev/roost 0.3.2 → 0.4.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.
@@ -0,0 +1,486 @@
1
+ import { blake3 } from '@noble/hashes/blake3.js';
2
+ import { assembleFrames, decodeFrame, MAX_BATCH, MAX_FRAME, MAX_UPDATES, splitBatch } from '../codec.js';
3
+ import { MAX_PAGE_HEADERS, StoreError, _isRetryableImportStatus } from '../store.js';
4
+ import { CoverageError, CoverageStore } from './coverage.js';
5
+ import { ExecuteError, opsOfTurn } from './execute.js';
6
+ import { LinkError } from './link.js';
7
+ import { WorkError, WorkStore } from './work.js';
8
+ /**
9
+ * Network-free local sync primitives for host-carried transports (such as
10
+ * `@loro-dev/streams-crdt/effect` `makeDurableStream({ mode: "explicit" })`),
11
+ * the IndexedDB mirror of `src/sync/explicit.rs`.
12
+ *
13
+ * Each item exchanged across the host transport is one raw Roost v1 frame
14
+ * (`encodeFrame`). Upload batches obey the exact `encodeItems` plaintext byte
15
+ * ceiling `Σ(4 + item.length) <= maxBytes`. Remote imports mark `CoverageStore`
16
+ * directly without writing to `browser_inbox_*` or `browser_replay_*`.
17
+ */
18
+ export class ExplicitSyncError extends Error {
19
+ code;
20
+ constructor(code, message = code, options) {
21
+ super(message, options);
22
+ this.code = code;
23
+ this.name = 'ExplicitSyncError';
24
+ }
25
+ }
26
+ const invalid = (message) => new ExplicitSyncError('invalid', message);
27
+ const rethrow = (e) => {
28
+ if (e instanceof ExplicitSyncError)
29
+ throw e;
30
+ if (e instanceof WorkError)
31
+ throw new ExplicitSyncError('work', `work store failure: ${e.message}`, { cause: e });
32
+ if (e instanceof CoverageError)
33
+ throw new ExplicitSyncError('coverage', `coverage failure: ${e.message}`, { cause: e });
34
+ if (e instanceof ExecuteError)
35
+ throw new ExplicitSyncError('execute', `executor failure: ${e.message}`, { cause: e });
36
+ if (e instanceof LinkError)
37
+ throw new ExplicitSyncError('link', `link failure: ${e.message}`, { cause: e });
38
+ if (e instanceof StoreError)
39
+ throw new ExplicitSyncError('store', `store failure: ${e.message}`, { cause: e });
40
+ throw e;
41
+ };
42
+ export class ExplicitSync {
43
+ #storage;
44
+ #work;
45
+ #coverage;
46
+ constructor(storage) {
47
+ this.#storage = storage;
48
+ this.#work = new WorkStore(storage);
49
+ this.#coverage = new CoverageStore(storage);
50
+ }
51
+ /** Discover pending local work and acquire the next dependency-ready batch
52
+ * of raw Roost v1 frames bounded by `options.maxBytes` and `options.maxItems`. */
53
+ async pullPendingBatch(stream, scope, options = {}) {
54
+ try {
55
+ checkScopeStream(stream, scope);
56
+ const maxBytes = options.maxBytes ?? MAX_FRAME;
57
+ const maxItems = options.maxItems ?? MAX_UPDATES;
58
+ const partial = options.partial ?? false;
59
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
60
+ throw invalid('maxBytes must be positive');
61
+ if (!Number.isSafeInteger(maxItems) || maxItems <= 0)
62
+ throw invalid('maxItems must be positive');
63
+ const plan = await this.#work.resume(scope);
64
+ for (const token of plan.confirm)
65
+ await this.#work.confirm(token, false);
66
+ if (options.turnIds !== undefined) {
67
+ await this.#discoverExplicitTurns(stream, scope, options.turnIds);
68
+ }
69
+ else if (partial) {
70
+ await this.#discoverLocalEvents(stream, scope, 100);
71
+ }
72
+ else {
73
+ await this.#discoverFull(stream, scope, 100);
74
+ }
75
+ const acquired = await this.#work.acquireBatch(scope, maxBytes, maxItems);
76
+ if (acquired.length === 0)
77
+ return null;
78
+ const items = [];
79
+ const receipt = [];
80
+ for (const task of acquired) {
81
+ let frames;
82
+ try {
83
+ frames = splitBatch(task.bytes);
84
+ }
85
+ catch (e) {
86
+ throw new WorkError('corrupt', `task frozen batch invalid: ${e instanceof Error ? e.message : e}`);
87
+ }
88
+ if (frames.length !== 1)
89
+ throw new WorkError('corrupt', 'task frozen batch must contain one frame');
90
+ items.push(frames[0]);
91
+ receipt.push({
92
+ turnId: task.token.task.turn.slice(),
93
+ seq: task.token.task.seq,
94
+ attempt: task.token.attempt,
95
+ });
96
+ }
97
+ return { items, receipt };
98
+ }
99
+ catch (e) {
100
+ return rethrow(e);
101
+ }
102
+ }
103
+ /** Atomically confirm a pulled batch in `WorkStore` + `CoverageStore` after
104
+ * the host transport receives durable server ACK. */
105
+ async confirmPendingBatch(scope, receipt) {
106
+ try {
107
+ const tokens = receipt.map(entry => ({
108
+ scope,
109
+ task: { turn: entry.turnId.slice(), seq: entry.seq },
110
+ attempt: entry.attempt,
111
+ }));
112
+ return await this.#work.confirmBatch(tokens, false);
113
+ }
114
+ catch (e) {
115
+ return rethrow(e);
116
+ }
117
+ }
118
+ /** Import raw Roost v1 frames received from the remote transport directly
119
+ * into `stream` and mark `CoverageStore` without writing to `browser_inbox_*`
120
+ * or `browser_replay_*`. */
121
+ async importRemoteBatch(stream, scope, items, partial = false) {
122
+ try {
123
+ checkScopeStream(stream, scope);
124
+ const statuses = [];
125
+ const applied = [];
126
+ const conflicts = [];
127
+ const appliedTurns = [];
128
+ const appliedSeen = new Set();
129
+ const pendingTurns = [];
130
+ const pendingSeen = new Set();
131
+ let retryQuotaExceeded = false;
132
+ let idx = 0;
133
+ while (idx < items.length) {
134
+ const head = items[idx];
135
+ if (head.length > MAX_FRAME) {
136
+ statuses.push({ kind: 'rejected', reason: 'frame too large' });
137
+ idx += 1;
138
+ continue;
139
+ }
140
+ const chunk = [];
141
+ let framesLen = 0;
142
+ while (idx < items.length && chunk.length < MAX_UPDATES) {
143
+ const frame = items[idx];
144
+ if (frame.length > MAX_FRAME)
145
+ break;
146
+ const entryLen = varintLen(frame.length) + frame.length;
147
+ const nextLen = framesLen + entryLen;
148
+ const total = 4 + varintLen(chunk.length + 1) + nextLen;
149
+ if (total > MAX_BATCH) {
150
+ if (chunk.length === 0)
151
+ throw invalid('frame exceeds batch ceiling');
152
+ break;
153
+ }
154
+ chunk.push(frame);
155
+ framesLen = nextLen;
156
+ idx += 1;
157
+ }
158
+ if (chunk.length === 0)
159
+ continue;
160
+ const batch = assembleFrames(chunk);
161
+ const coverage = this.#coverage;
162
+ // Import frames, drain unlocked pending ops, record served receipts,
163
+ // and mark CoverageStore present all in ONE IndexedDB transaction so
164
+ // a crash or abort never leaves a drained pending op unmarked in coverage.
165
+ const report = await stream.importBatchWithTx(batch, partial, function* (tx, chunkReport) {
166
+ const served = [];
167
+ const work = [];
168
+ const seenWork = new Set();
169
+ for (let i = 0; i < Math.min(chunk.length, chunkReport.statuses.length); i++) {
170
+ const status = chunkReport.statuses[i];
171
+ if (status.kind === 'rejected')
172
+ continue;
173
+ const frame = chunk[i];
174
+ try {
175
+ const update = decodeFrame(frame);
176
+ if (update.seq <= 0xffffffffn) {
177
+ served.push({
178
+ turn: update.turnId,
179
+ seq: Number(update.seq),
180
+ fp: blake3(assembleFrames([frame])),
181
+ });
182
+ if (status.kind !== 'pending') {
183
+ const key = `${hexBytes(update.turnId)}:${update.seq}`;
184
+ if (!seenWork.has(key)) {
185
+ seenWork.add(key);
186
+ work.push({ turn: update.turnId, seq: update.seq });
187
+ }
188
+ }
189
+ }
190
+ }
191
+ catch {
192
+ // Unparseable frame would have been rejected; skip defensively.
193
+ }
194
+ }
195
+ for (const reference of chunkReport.applied) {
196
+ const key = `${hexBytes(reference.turnId)}:${reference.seq}`;
197
+ if (!seenWork.has(key)) {
198
+ seenWork.add(key);
199
+ work.push({ turn: reference.turnId, seq: reference.seq });
200
+ }
201
+ }
202
+ if (served.length > 0)
203
+ yield* coverage.recordServedIn(tx, scope, served);
204
+ yield* markWorkPresentInTx(stream, tx, coverage, scope, work, seenWork, partial);
205
+ });
206
+ for (let i = 0; i < Math.min(chunk.length, report.statuses.length); i++) {
207
+ const status = report.statuses[i];
208
+ if (status.kind === 'rejected')
209
+ continue;
210
+ try {
211
+ const update = decodeFrame(chunk[i]);
212
+ const h = hexBytes(update.turnId);
213
+ if (status.kind === 'pending') {
214
+ if (!pendingSeen.has(h)) {
215
+ pendingSeen.add(h);
216
+ pendingTurns.push(update.turnId);
217
+ }
218
+ }
219
+ else if (!appliedSeen.has(h)) {
220
+ appliedSeen.add(h);
221
+ appliedTurns.push(update.turnId);
222
+ }
223
+ }
224
+ catch {
225
+ // Unparseable frame would have been rejected.
226
+ }
227
+ }
228
+ for (const reference of report.applied) {
229
+ const h = hexBytes(reference.turnId);
230
+ if (!appliedSeen.has(h)) {
231
+ appliedSeen.add(h);
232
+ appliedTurns.push(reference.turnId);
233
+ }
234
+ }
235
+ const chunkQuota = report.statuses.some(_isRetryableImportStatus);
236
+ statuses.push(...report.statuses);
237
+ applied.push(...report.applied);
238
+ conflicts.push(...report.conflicts);
239
+ if (chunkQuota) {
240
+ retryQuotaExceeded = true;
241
+ break;
242
+ }
243
+ }
244
+ const remainingPending = [];
245
+ for (const id of pendingTurns) {
246
+ if ((await stream.readTurnHeader(id)).kind === 'incomplete')
247
+ remainingPending.push(id);
248
+ }
249
+ const hasPendingDependencies = (await stream.pendingTurns(undefined, 1)).length > 0;
250
+ return {
251
+ report: { statuses, applied, conflicts },
252
+ appliedTurns,
253
+ pendingTurns: remainingPending,
254
+ hasPendingDependencies,
255
+ retryQuotaExceeded,
256
+ };
257
+ }
258
+ catch (e) {
259
+ return rethrow(e);
260
+ }
261
+ }
262
+ /** Clear `WorkStore` and `CoverageStore` state for `scope` in a single write
263
+ * transaction while preserving local stream Turns, events and indexes. */
264
+ async resetSyncState(scope) {
265
+ try {
266
+ return await this.#storage.transact(true, function* (tx) {
267
+ const workKeysRemoved = yield* WorkStore.clearScopeIn(tx, scope);
268
+ const coverageKeysRemoved = yield* CoverageStore.clearScopeIn(tx, scope);
269
+ return { workKeysRemoved, coverageKeysRemoved };
270
+ });
271
+ }
272
+ catch (e) {
273
+ return rethrow(e);
274
+ }
275
+ }
276
+ async #discoverExplicitTurns(stream, scope, turnIds) {
277
+ for (const id of turnIds) {
278
+ const res = await stream.readTurnHeader(id);
279
+ const header = readableHeaderOrNull(res);
280
+ if (header === null)
281
+ continue;
282
+ try {
283
+ const ops = await opsOfTurn(stream, header, 0);
284
+ await this.#work.discoverBatch(scope, ops, undefined);
285
+ }
286
+ catch (e) {
287
+ if (e instanceof ExecuteError && e.code === 'invalid' && (e.message.includes('not readable') || e.message.includes('not sealed'))) {
288
+ continue;
289
+ }
290
+ throw e;
291
+ }
292
+ }
293
+ }
294
+ async #discoverLocalEvents(stream, scope, pageSize) {
295
+ const clamped = Math.max(1, Math.min(pageSize, MAX_PAGE_HEADERS));
296
+ let eventCursor = await this.#work.eventCursor(scope);
297
+ for (;;) {
298
+ const events = await stream.eventsAfter(eventCursor, clamped);
299
+ if (events.length === 0)
300
+ break;
301
+ const end = events[events.length - 1].cursor;
302
+ const ops = [];
303
+ for (const record of events) {
304
+ if (record.event.kind !== 'changed' || record.event.origin !== 'local')
305
+ continue;
306
+ const update = record.event.update;
307
+ const header = requireReadableHeader(await stream.readTurnHeader(update.turnId));
308
+ const seq = u32Seq(update.seq);
309
+ ops.push(...await opsOfTurn(stream, header, seq, update.seq + 1n));
310
+ }
311
+ const res = await this.#work.discoverEventBatch(scope, ops, eventCursor, end);
312
+ if (res === undefined) {
313
+ eventCursor = await this.#work.eventCursor(scope);
314
+ continue;
315
+ }
316
+ eventCursor = end;
317
+ }
318
+ }
319
+ async #discoverFull(stream, scope, pageSize) {
320
+ const clamped = Math.max(1, Math.min(pageSize, MAX_PAGE_HEADERS));
321
+ let eventCursor = await this.#work.eventCursor(scope);
322
+ for (;;) {
323
+ const events = await stream.eventsAfter(eventCursor, clamped);
324
+ if (events.length === 0)
325
+ break;
326
+ const end = events[events.length - 1].cursor;
327
+ const ops = [];
328
+ for (const record of events) {
329
+ if (record.event.kind !== 'changed')
330
+ continue;
331
+ const update = record.event.update;
332
+ const header = requireReadableHeader(await stream.readTurnHeader(update.turnId));
333
+ const seq = u32Seq(update.seq);
334
+ ops.push(...await opsOfTurn(stream, header, seq, update.seq + 1n));
335
+ }
336
+ const res = await this.#work.discoverEventBatch(scope, ops, eventCursor, end);
337
+ if (res === undefined) {
338
+ eventCursor = await this.#work.eventCursor(scope);
339
+ continue;
340
+ }
341
+ eventCursor = end;
342
+ }
343
+ let openAfter = undefined;
344
+ for (;;) {
345
+ const open = await this.#work.openTurns(scope, openAfter, clamped);
346
+ if (open.length === 0)
347
+ break;
348
+ openAfter = open[open.length - 1].turn;
349
+ for (const entry of open) {
350
+ const header = requireReadableHeader(await stream.readTurnHeader(entry.turn));
351
+ if (BigInt(entry.offeredUpto) >= header.nextSeq)
352
+ continue;
353
+ const ops = await opsOfTurn(stream, header, entry.offeredUpto);
354
+ await this.#work.discoverBatch(scope, ops, undefined);
355
+ }
356
+ if (open.length < clamped)
357
+ break;
358
+ }
359
+ const cursor = (await this.#work.discovery(scope)).cursor;
360
+ let start = cursor;
361
+ let last = cursor;
362
+ for (;;) {
363
+ const page = await stream.turnHeadersAfter(start, clamped);
364
+ if (page.length === 0)
365
+ break;
366
+ const ops = [];
367
+ let pageLast = last;
368
+ let scanLast = start;
369
+ for (const row of page) {
370
+ const header = readableHeaderOrNull(row);
371
+ if (header !== null) {
372
+ ops.push(...await opsOfTurn(stream, header, 0));
373
+ pageLast = header.turnId;
374
+ scanLast = header.turnId;
375
+ }
376
+ else if (row.kind !== 'found') {
377
+ scanLast = row.turnId;
378
+ }
379
+ }
380
+ if (ops.length > 0 || !sameOptionalBytes(pageLast, last)) {
381
+ const result = await this.#work.discoverBatch(scope, ops, pageLast);
382
+ last = result.cursor;
383
+ }
384
+ if (page.length < clamped || sameOptionalBytes(scanLast, start))
385
+ break;
386
+ start = scanLast;
387
+ }
388
+ }
389
+ }
390
+ function checkScopeStream(stream, scope) {
391
+ if (scope.stream !== stream.id)
392
+ throw invalid('scope stream does not match stream handle');
393
+ }
394
+ function readableHeaderOrNull(result) {
395
+ if (result.kind === 'found')
396
+ return result.turn;
397
+ if (result.kind === 'incomplete' && result.prefix !== null)
398
+ return result.prefix;
399
+ return null;
400
+ }
401
+ function requireReadableHeader(result) {
402
+ const header = readableHeaderOrNull(result);
403
+ if (header === null)
404
+ throw invalid(`turn header not readable: ${result.kind}`);
405
+ return header;
406
+ }
407
+ function u32Seq(seq) {
408
+ if (seq < 0n || seq > 0xffffffffn)
409
+ throw invalid('seq overflow');
410
+ return Number(seq);
411
+ }
412
+ function varintLen(n) {
413
+ let size = 1;
414
+ while (n >= 128) {
415
+ size += 1;
416
+ n = Math.floor(n / 128);
417
+ }
418
+ return size;
419
+ }
420
+ function* markWorkPresentInTx(stream, tx, coverage, scope, work, seen, localParentsOnly) {
421
+ while (work.length > 0) {
422
+ const item = work.pop();
423
+ const seq32 = u32Seq(item.seq);
424
+ const batch = yield* stream.exportSingleUpdateIn(tx, item.turn, item.seq);
425
+ if (batch === null)
426
+ continue; // Duplicate of a frame still sitting in `pending`.
427
+ const fp = blake3(batch);
428
+ if (!(yield* coverage.wasServedIn(tx, scope, item.turn, seq32, fp)))
429
+ continue;
430
+ const header = requireReadableHeader(yield* stream.headerResult(tx, item.turn));
431
+ const parents = [];
432
+ const unresolved = [];
433
+ for (const parent of header.parents) {
434
+ const parentResult = yield* stream.headerResult(tx, parent.id);
435
+ if (parentResult.kind !== 'found') {
436
+ if (localParentsOnly) {
437
+ unresolved.push({ turn: [...parent.id], hash: [...parent.hash] });
438
+ continue;
439
+ }
440
+ throw invalid(`parent ${hexBytes(parent.id)} of turn ${hexBytes(item.turn)} not readable`);
441
+ }
442
+ const parentHeader = parentResult.turn;
443
+ if (parentHeader.sealed === null || parentHeader.nextSeq === 0n) {
444
+ if (localParentsOnly) {
445
+ unresolved.push({ turn: [...parent.id], hash: [...parent.hash] });
446
+ continue;
447
+ }
448
+ throw invalid(`parent ${hexBytes(parent.id)} of turn ${hexBytes(item.turn)} is not sealed`);
449
+ }
450
+ if (hexBytes(parentHeader.sealed) !== hexBytes(parent.hash)) {
451
+ if (localParentsOnly) {
452
+ unresolved.push({ turn: [...parent.id], hash: [...parent.hash] });
453
+ continue;
454
+ }
455
+ throw invalid('parent declaration hash mismatch');
456
+ }
457
+ const sealBatch = yield* stream.exportSingleUpdateIn(tx, parent.id, parentHeader.nextSeq - 1n);
458
+ if (sealBatch === null)
459
+ throw invalid(`parent ${hexBytes(parent.id)} seal update missing`);
460
+ parents.push({ turnId: parent.id, sealFp: blake3(sealBatch) });
461
+ }
462
+ yield* coverage.markReceivedIn(tx, scope, item.turn, seq32, fp, header.sealed !== null && item.seq === header.nextSeq - 1n, parents, unresolved);
463
+ if (header.sealed !== null) {
464
+ for (const child of yield* coverage.unresolvedChildrenIn(tx, scope, item.turn)) {
465
+ const key = `${hexBytes(child)}:0`;
466
+ if (!seen.has(key)) {
467
+ seen.add(key);
468
+ work.push({ turn: child, seq: 0n });
469
+ }
470
+ }
471
+ }
472
+ }
473
+ }
474
+ function hexBytes(bytes) {
475
+ return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
476
+ }
477
+ function sameOptionalBytes(a, b) {
478
+ if (a === undefined || b === undefined)
479
+ return a === b;
480
+ if (a.length !== b.length)
481
+ return false;
482
+ for (let i = 0; i < a.length; i++)
483
+ if (a[i] !== b[i])
484
+ return false;
485
+ return true;
486
+ }
@@ -13,5 +13,8 @@ export { PolicyStore, PolicyError, DEFAULT_MIRROR_POLICY } from './policy.js';
13
13
  export type { MirrorDirection, MirrorPolicy } from './policy.js';
14
14
  export { CryptoError } from './crypto.js';
15
15
  export type { PayloadCrypto, AsyncPayloadCrypto } from './crypto.js';
16
+ export { logicalWorkScope } from './work.js';
16
17
  export type { WorkScope } from './work.js';
18
+ export { ExplicitSync, ExplicitSyncError } from './explicit.js';
19
+ export type { BatchReceiptEntry, PulledBatch, PullOptions, RemoteImportReport, ResetSyncReport, } from './explicit.js';
17
20
  export { sealEnvelopeAsync, openEnvelopeAsync, openFirstEnvelopeAsync, openConcatenatedAsync, openConcatenatedPrefixAsync } from './crypto.js';
@@ -6,4 +6,6 @@ export { Link, LinkError, linkLimitsForSync } from './link.js';
6
6
  export { HistoryReader, HistoryError } from './history.js';
7
7
  export { PolicyStore, PolicyError, DEFAULT_MIRROR_POLICY } from './policy.js';
8
8
  export { CryptoError } from './crypto.js';
9
+ export { logicalWorkScope } from './work.js';
10
+ export { ExplicitSync, ExplicitSyncError } from './explicit.js';
9
11
  export { sealEnvelopeAsync, openEnvelopeAsync, openFirstEnvelopeAsync, openConcatenatedAsync, openConcatenatedPrefixAsync } from './crypto.js';
package/dist/sync/link.js CHANGED
@@ -624,9 +624,13 @@ async function markOnePresentInner(stream, coverage, scope, turn, seq, localPare
624
624
  if (!(await coverage.wasServed(scope, turn, Number(seq), blake3(batch))))
625
625
  return [];
626
626
  const headerResult = await stream.readTurnHeader(turn);
627
- if (headerResult.kind !== 'found')
627
+ const header = headerResult.kind === 'found'
628
+ ? headerResult.turn
629
+ : headerResult.kind === 'incomplete' && headerResult.prefix !== null
630
+ ? headerResult.prefix
631
+ : null;
632
+ if (header === null)
628
633
  throw invalid(`turn ${hex(turn)} not readable after import`);
629
- const header = headerResult.turn;
630
634
  const parents = [];
631
635
  const unresolved = [];
632
636
  for (const parent of header.parents) {
@@ -7,7 +7,7 @@ export { ARCHIVE_KEY_TAG, archivePrefix, generationIn, generationKeyFragment, ge
7
7
  export type { EndpointConfig, Generation, RemoteId, RemoteRecord } from './registry.js';
8
8
  export { CHILD_KEY_TAG, CLOSED_KEY_TAG, CONFLICT_KEY_TAG, COVERAGE_KEY_TAG, COVERAGE_SPACE, coverageKey, CoverageError, CoverageStore, closedKey, conflictKey, ISLAND_KEY_TAG, MAX_PRESENT_SEQS, RECORD_VERSION as COVERAGE_RECORD_VERSION, SEQ_KEY_TAG, SUMMARY_RECORD_VERSION, } from './coverage.js';
9
9
  export type { ClosedRecord, CoverageScope, MarkResult, ParentRef, PresentState, SealClaim } from './coverage.js';
10
- export { MAX_TASK_BYTES, MAX_TASK_DEPS, MAX_WAITERS_PER_DEP, OPEN_TURN_KEY_TAG, PREFIX_KEY_TAG, STATUS_INDEX_KEY_TAG, taskKey, TASK_KEY_TAG, WAIT_KEY_TAG, waitKey, WORK_SPACE, WorkError, WorkStore, } from './work.js';
10
+ export { logicalWorkScope, MAX_TASK_BYTES, MAX_TASK_DEPS, MAX_WAITERS_PER_DEP, OPEN_TURN_KEY_TAG, PREFIX_KEY_TAG, STATUS_INDEX_KEY_TAG, taskKey, TASK_KEY_TAG, WAIT_KEY_TAG, waitKey, WORK_SPACE, WorkError, WorkStore, } from './work.js';
11
11
  export type { AcquiredTask, AttemptToken, ConfirmResult, DepRef, DiscoverOutcome, DiscoverResult, DiscoveryState, OpenTurn, OpRef, ResumePlan, TaskInfo, TaskRef, TaskStatus, WorkScope, } from './work.js';
12
12
  export { ExecuteError, Executor, TransportError } from './execute.js';
13
13
  export type { DiscoverReport, FlushReport, ResumeReport, SendTransport } from './execute.js';
@@ -21,4 +21,6 @@ export { Link, LinkError, linkLimitsForSync } from './link.js';
21
21
  export type { BridgeReport, DownloadReport, LinkLimits, StopToken } from './link.js';
22
22
  export { HistoryError, HistoryReader } from './history.js';
23
23
  export type { BackwardByteSource, BackwardFrame, BackwardPage, HistoryReport, PrefixScan } from './history.js';
24
+ export { ExplicitSync, ExplicitSyncError } from './explicit.js';
25
+ export type { BatchReceiptEntry, PulledBatch, PullOptions, RemoteImportReport, ResetSyncReport } from './explicit.js';
24
26
  export { sealEnvelopeAsync, openEnvelopeAsync, openFirstEnvelopeAsync, openConcatenatedAsync, openConcatenatedPrefixAsync } from './crypto.js';
package/dist/sync/mod.js CHANGED
@@ -5,11 +5,12 @@
5
5
  * routing, registration and coverage state never feed the signed node hash. */
6
6
  export { ARCHIVE_KEY_TAG, archivePrefix, generationIn, generationKeyFragment, generationSourceKeyTag, GenerationSource, RECORD_KEY_TAG, RECORD_VERSION, recordKey, RegistryError, RemoteRegistry, REMOTE_SPACE, } from './registry.js';
7
7
  export { CHILD_KEY_TAG, CLOSED_KEY_TAG, CONFLICT_KEY_TAG, COVERAGE_KEY_TAG, COVERAGE_SPACE, coverageKey, CoverageError, CoverageStore, closedKey, conflictKey, ISLAND_KEY_TAG, MAX_PRESENT_SEQS, RECORD_VERSION as COVERAGE_RECORD_VERSION, SEQ_KEY_TAG, SUMMARY_RECORD_VERSION, } from './coverage.js';
8
- export { MAX_TASK_BYTES, MAX_TASK_DEPS, MAX_WAITERS_PER_DEP, OPEN_TURN_KEY_TAG, PREFIX_KEY_TAG, STATUS_INDEX_KEY_TAG, taskKey, TASK_KEY_TAG, WAIT_KEY_TAG, waitKey, WORK_SPACE, WorkError, WorkStore, } from './work.js';
8
+ export { logicalWorkScope, MAX_TASK_BYTES, MAX_TASK_DEPS, MAX_WAITERS_PER_DEP, OPEN_TURN_KEY_TAG, PREFIX_KEY_TAG, STATUS_INDEX_KEY_TAG, taskKey, TASK_KEY_TAG, WAIT_KEY_TAG, waitKey, WORK_SPACE, WorkError, WorkStore, } from './work.js';
9
9
  export { ExecuteError, Executor, TransportError } from './execute.js';
10
10
  export { SYNC_CONTENT_TYPE, StreamsTransport } from './transport.js';
11
11
  export { CryptoError, ENVELOPE_MAGIC, openConcatenated, openConcatenatedPrefix, openFirstEnvelope, openEnvelope, sealEnvelope, } from './crypto.js';
12
12
  export { DEFAULT_MIRROR_POLICY, POLICY_KEY_TAG, POLICY_SPACE, PolicyError, PolicyStore, RECORD_VERSION as POLICY_RECORD_VERSION, } from './policy.js';
13
13
  export { Link, LinkError, linkLimitsForSync } from './link.js';
14
14
  export { HistoryError, HistoryReader } from './history.js';
15
+ export { ExplicitSync, ExplicitSyncError } from './explicit.js';
15
16
  export { sealEnvelopeAsync, openEnvelopeAsync, openFirstEnvelopeAsync, openConcatenatedAsync, openConcatenatedPrefixAsync } from './crypto.js';
@@ -1,4 +1,4 @@
1
- import type { IndexedDbStorage } from '../indexeddb.js';
1
+ import type { IndexedDbStorage, KvTransaction, Step } from '../indexeddb.js';
2
2
  import type { Generation, RemoteId } from './registry.js';
3
3
  import { CoverageStore } from './coverage.js';
4
4
  import type { MarkResult } from './coverage.js';
@@ -89,7 +89,7 @@ export declare const STATUS_INDEX_MARKER_TAG = 7;
89
89
  /** Open-turn record keys (G009). */
90
90
  export declare const OPEN_TURN_KEY_TAG = 8;
91
91
  export declare const OPEN_INDEX_MARKER_TAG = 9;
92
- /** Maximum frozen bytes of one task's package. */
92
+ /** Maximum frozen bytes of one task's package (accommodates MAX_FRAME plus single-frame RST1 header). */
93
93
  export declare const MAX_TASK_BYTES: number;
94
94
  /** Maximum direct dependencies recorded on one task (cross-turn parent refs
95
95
  * plus one same-turn predecessor — never the turn's length, L010). */
@@ -104,6 +104,8 @@ export type WorkScope = {
104
104
  generation: Generation;
105
105
  stream: string;
106
106
  };
107
+ /** Build a logical host-carried sync scope with empty app-marker generation. */
108
+ export declare function logicalWorkScope(remote: RemoteId, stream: string): WorkScope;
107
109
  /** Lightweight task / dependency reference: one operation of one turn. */
108
110
  export type TaskRef = {
109
111
  turn: Uint8Array;
@@ -348,4 +350,13 @@ export declare class WorkStore {
348
350
  * — see N017 P1-C), and every direct parent of the task's turn must
349
351
  * satisfy the same check (review C follow-up). */
350
352
  private depsSatisfiedIn;
353
+ private depsSatisfiedWithBatchIn;
354
+ /** Freeze a topologically ordered batch of runnable tasks for one atomic
355
+ * host-carried append (`encodeItems` budget: `Σ(4 + rawFrame.length) <= maxBytes`). */
356
+ acquireBatch(scope: WorkScope, maxBytes: number, maxItems: number): Promise<AcquiredTask[]>;
357
+ /** Atomically confirm a batch of acquired tasks in one write transaction. */
358
+ confirmBatch(tokens: readonly AttemptToken[], checkRegistryGeneration: boolean): Promise<ConfirmResult[]>;
359
+ /** Delete every work-store record belonging to `scope` inside the caller's
360
+ * write transaction, preserving stream content and other scopes. */
361
+ static clearScopeIn(tx: KvTransaction, scope: WorkScope): Step<number>;
351
362
  }