@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,321 @@
1
+ import { blake3 } from '@noble/hashes/blake3.js';
2
+ import { MAX_PAGE_HEADERS } from '../store.js';
3
+ import { WorkError, WorkStore } from './work.js';
4
+ /** Typed transport outcomes the scheduler distinguishes. */
5
+ export class TransportError extends Error {
6
+ code;
7
+ constructor(code, message = code) {
8
+ super(message);
9
+ this.code = code;
10
+ this.name = 'TransportError';
11
+ }
12
+ }
13
+ /** Errors of executor operations. Semantic rejections roll their transaction
14
+ * back; nothing is half-committed. */
15
+ export class ExecuteError extends Error {
16
+ code;
17
+ constructor(code, message = code, options) {
18
+ super(message, options);
19
+ this.code = code;
20
+ this.name = 'ExecuteError';
21
+ }
22
+ }
23
+ function u32(value, what) {
24
+ if (value < 0n || value > 0xffffffffn)
25
+ throw new ExecuteError('invalid', `${what} overflows u32`);
26
+ return Number(value);
27
+ }
28
+ /** The backfill executor: a stateless composition over the device's single
29
+ * storage owner; all progress lives in the work store. */
30
+ export class Executor {
31
+ storage;
32
+ #work;
33
+ constructor(storage) {
34
+ this.storage = storage;
35
+ this.#work = new WorkStore(storage);
36
+ }
37
+ /** Host access to the underlying work store (e.g. `fillBytes` for
38
+ * locally-fetched packages or direct task inspection). */
39
+ workStore() {
40
+ return this.#work;
41
+ }
42
+ /** The work scope of one registered remote and stream, bound to the
43
+ * registry's current generation. */
44
+ async scope(registry, remote, stream) {
45
+ const record = await registry.get(remote);
46
+ if (record === undefined)
47
+ throw new ExecuteError('invalid', 'remote not registered');
48
+ if (!record.enabled)
49
+ throw new ExecuteError('invalid', 'remote is disabled');
50
+ return { remote: record.id, generation: record.generation, stream };
51
+ }
52
+ /** Startup recovery: the work store's resume (including the prefix
53
+ * watermark rebuild for pre-watermark databases and the open-turn set
54
+ * rebuild for pre-G009 databases) followed by an automatic,
55
+ * byte-idempotent replay of every persisted `acked_local` confirm (F2).
56
+ * Each replay runs the same atomic confirm as the send loop, with the
57
+ * registry generation re-read inside the confirm transaction. */
58
+ async resume(scope) {
59
+ const plan = await this.#work.resume(scope);
60
+ const replayed = [];
61
+ for (const token of plan.confirm) {
62
+ await this.#work.confirm(token, true);
63
+ replayed.push(token.task);
64
+ }
65
+ return { plan, replayed };
66
+ }
67
+ /** Drain local event pages, then repair explicitly seeded/legacy work
68
+ * through open-turn tracking and forward header pages. Tasks and the
69
+ * event checkpoint commit atomically. Page size bounds each read/commit,
70
+ * not the total work of a catch-up cycle. */
71
+ async discoverCycle(stream, scope, pageSize) {
72
+ const page = Math.min(Math.max(1, pageSize), MAX_PAGE_HEADERS);
73
+ let turnsScanned = 0;
74
+ let tasksCreated = 0;
75
+ // Local commit order also discovers newly imported older
76
+ // IDs. Freeze only each event's op and its immediate predecessor,
77
+ // never the entire history of a long streaming turn.
78
+ let eventCursor = await this.#work.eventCursor(scope);
79
+ for (;;) {
80
+ const events = await stream.eventsAfter(eventCursor, page);
81
+ if (!events.length)
82
+ break;
83
+ const end = events[events.length - 1].cursor;
84
+ const ops = [];
85
+ for (const { event } of events) {
86
+ if (event.kind !== 'changed')
87
+ continue;
88
+ const result = await stream.readTurnHeader(event.update.turnId);
89
+ if (result.kind !== 'found')
90
+ throw new ExecuteError('invalid', 'event turn not readable');
91
+ const seq = u32(event.update.seq, 'seq');
92
+ ops.push(...await opsOfTurn(stream, result.turn, seq, event.update.seq + 1n));
93
+ turnsScanned++;
94
+ }
95
+ const discovered = await this.#work.discoverEventBatch(scope, ops, eventCursor, end);
96
+ if (discovered === undefined) {
97
+ eventCursor = await this.#work.eventCursor(scope);
98
+ continue;
99
+ }
100
+ tasksCreated += discovered.outcomes.filter(o => o.kind === 'created' || o.kind === 'adopted').length;
101
+ eventCursor = end;
102
+ }
103
+ // Phase 1: streaming turns tracked by the durable open-turn set.
104
+ let openAfter = undefined;
105
+ for (;;) {
106
+ const open = await this.#work.openTurns(scope, openAfter, page);
107
+ if (!open.length)
108
+ break;
109
+ openAfter = open[open.length - 1].turn;
110
+ for (const entry of open) {
111
+ // Header-only: the projection is never read here (G026).
112
+ const result = await stream.readTurnHeader(entry.turn);
113
+ if (result.kind !== 'found')
114
+ throw new ExecuteError('invalid', 'tracked open turn not readable');
115
+ turnsScanned++;
116
+ if (BigInt(entry.offeredUpto) >= result.turn.nextSeq)
117
+ // No new ops since the last offer. A sealed snapshot here
118
+ // is unreachable (persisting the seal op deletes the
119
+ // record in the same transaction), so nothing to do.
120
+ continue;
121
+ const ops = await opsOfTurn(stream, result.turn, entry.offeredUpto);
122
+ const discovered = await this.#work.discoverBatch(scope, ops, undefined);
123
+ tasksCreated += discovered.outcomes.filter(o => o.kind === 'created' || o.kind === 'adopted').length;
124
+ }
125
+ if (open.length < page)
126
+ break;
127
+ }
128
+ // Phase 2: forward keyset scan over newly appeared turns.
129
+ let start = (await this.#work.discovery(scope)).cursor;
130
+ let last = start;
131
+ for (;;) {
132
+ // Exclusive start: the cursor row is never re-read (while open it
133
+ // is covered by phase 1); a full page never ends a continuation
134
+ // early (the port's clamp bounds returned rows, G026 follow-up).
135
+ const pageRows = await stream.turnHeadersAfter(start, page);
136
+ if (!pageRows.length)
137
+ break;
138
+ const ops = [];
139
+ let pageLast = last;
140
+ for (const row of pageRows) {
141
+ if (row.kind !== 'found')
142
+ throw new ExecuteError('invalid', 'discovery scan returned a non-found turn');
143
+ ops.push(...await opsOfTurn(stream, row.turn, 0));
144
+ turnsScanned++;
145
+ pageLast = row.turn.turnId;
146
+ }
147
+ const discovered = await this.#work.discoverBatch(scope, ops, pageLast);
148
+ tasksCreated += discovered.outcomes.filter(o => o.kind === 'created' || o.kind === 'adopted').length;
149
+ last = discovered.cursor;
150
+ if (pageRows.length < page)
151
+ break;
152
+ start = pageLast;
153
+ }
154
+ return { turnsScanned, tasksCreated, cursor: last };
155
+ }
156
+ /** Optional directed discovery. Ordinary late P2P/server imports are
157
+ * already picked up by the event journal in `discoverCycle`.
158
+ * Targeted discovery never advances the global cursor (G009): a directed
159
+ * id above the cursor must not make the scan skip unenumerated history —
160
+ * the regular cycle still walks past the position later and the per-op
161
+ * dedupe absorbs the overlap. */
162
+ async discoverTurns(stream, scope, ids) {
163
+ const ops = [];
164
+ for (const id of ids) {
165
+ const result = await stream.readTurnHeader(id);
166
+ if (result.kind !== 'found')
167
+ throw new ExecuteError('invalid', 'turn not readable for compensation discovery');
168
+ ops.push(...await opsOfTurn(stream, result.turn, 0));
169
+ }
170
+ return this.#work.discoverBatch(scope, ops, undefined);
171
+ }
172
+ /** Send everything runnable, bounded by `maxSend`: sweep the ungated
173
+ * candidates in (Turn ID, seq) keyset order and let `acquire` re-check the dependency
174
+ * gate per task (T2); gate failures collect into a straggler list that is
175
+ * retried after each sweep round while progress is made. A transport
176
+ * error stops the round with a typed report; the failed task stays
177
+ * `inflight` and a later flush retries the identical frozen bytes. */
178
+ async flush(scope, transport, maxSend) {
179
+ const SWEEP_PAGE = 1000;
180
+ const report = { sent: [], confirmed: [], transportError: undefined, waitingLocal: [] };
181
+ let stragglers = [];
182
+ let after = undefined;
183
+ // One attempt at a task: acquire (gate re-check), append, ack,
184
+ // confirm. Returns true when sent, false on a gate straggler.
185
+ const attempt = async (task) => {
186
+ let acquired;
187
+ try {
188
+ acquired = await this.#work.acquire(scope, task);
189
+ }
190
+ catch (e) {
191
+ if (e instanceof WorkError && e.code === 'unsatisfiedDeps')
192
+ return false;
193
+ throw e;
194
+ }
195
+ let body;
196
+ if (acquired.wire !== undefined)
197
+ body = acquired.wire;
198
+ else {
199
+ const sealed = transport.seal === undefined ? acquired.bytes : await transport.seal(acquired.bytes);
200
+ if (sealed.length !== acquired.bytes.length || sealed.some((b, i) => b !== acquired.bytes[i]))
201
+ await this.#work.bindWire(acquired.token, sealed);
202
+ body = sealed;
203
+ }
204
+ if (transport.appendWire !== undefined)
205
+ await transport.appendWire(body);
206
+ else
207
+ await transport.append(body);
208
+ report.sent.push(task);
209
+ await this.#work.ack(acquired.token);
210
+ // The registry generation is re-read inside the confirm's own
211
+ // transaction (G009): a rebind committed between the append and
212
+ // this point surfaces a typed generationConflict and the
213
+ // old-generation task is never confirmed.
214
+ const done = await this.#work.confirm(acquired.token, true);
215
+ report.confirmed.push({ task, coverage: done.coverage });
216
+ return true;
217
+ };
218
+ try {
219
+ while (report.sent.length < maxSend) {
220
+ let progress = false;
221
+ // Forward sweep over fresh candidates.
222
+ for (;;) {
223
+ if (report.sent.length >= maxSend)
224
+ break;
225
+ const page = await this.#work.candidatesByTurnAfter(scope, after, Math.min(SWEEP_PAGE, maxSend - report.sent.length));
226
+ if (!page.length)
227
+ break;
228
+ after = page[page.length - 1].task;
229
+ for (const info of page) {
230
+ if (report.sent.length >= maxSend)
231
+ break;
232
+ if (await attempt(info.task))
233
+ progress = true;
234
+ else
235
+ stragglers.push(info.task);
236
+ }
237
+ }
238
+ // Retry the stragglers this flush may have unblocked.
239
+ if (!stragglers.length || report.sent.length >= maxSend)
240
+ break;
241
+ const retry = stragglers;
242
+ stragglers = [];
243
+ for (const task of retry) {
244
+ if (report.sent.length >= maxSend)
245
+ break;
246
+ if (await attempt(task))
247
+ progress = true;
248
+ else
249
+ stragglers.push(task);
250
+ }
251
+ if (!progress)
252
+ break;
253
+ }
254
+ }
255
+ catch (e) {
256
+ // A transport error is a typed report, not an executor failure.
257
+ if (e instanceof TransportError) {
258
+ report.transportError = e;
259
+ }
260
+ else
261
+ throw e;
262
+ }
263
+ report.waitingLocal = (await this.#work.pendingLocal(scope)).map(info => info.task);
264
+ return report;
265
+ }
266
+ }
267
+ /** Build the OpRef list of one turn from the stream's real frames: seqs
268
+ * `fromSeq..nextSeq` (`fromSeq = 0` offers the whole turn; a higher `fromSeq`
269
+ * is the open-turn re-scan offering only newly appended ops, G009), frozen
270
+ * bytes = the exact `exportUpdates` frame, fingerprint = blake3 of the frame;
271
+ * seq 0 carries the turn's parent seals as cross-turn deps, later seqs carry
272
+ * exactly the direct predecessor (transitive closure is the prefix
273
+ * watermark's job). The predecessor fingerprint chain is recomputed from the
274
+ * frame just below the offered range, so a partial offer keeps its deps exact
275
+ * without re-offering persisted ops. Parents are resolved through
276
+ * `readTurnHeader` — a parent is always a sealed turn and never read beyond
277
+ * its header plus its raw seal frame. */
278
+ async function opsOfTurn(stream, header, fromSeq, toSeq = header.nextSeq) {
279
+ if (toSeq > header.nextSeq || toSeq <= BigInt(fromSeq))
280
+ throw new ExecuteError('invalid', 'invalid discovery op range');
281
+ const parents = [];
282
+ for (const parent of header.parents) {
283
+ // Header-only: only the parent's seal position is needed, never its
284
+ // content (G026); the seal frame below is the raw op-log row.
285
+ const snapshot = await stream.readTurnHeader(parent.id);
286
+ if (snapshot.kind !== 'found')
287
+ throw new ExecuteError('invalid', 'parent turn not readable');
288
+ if (snapshot.turn.sealed === null || snapshot.turn.nextSeq === 0n)
289
+ throw new ExecuteError('invalid', 'parent turn is not sealed');
290
+ const sealSeq = snapshot.turn.nextSeq - 1n;
291
+ const frame = await stream.exportUpdates(parent.id, sealSeq, 1);
292
+ parents.push({ turn: parent.id, sealSeq: u32(sealSeq, 'parent seal seq'), sealFp: blake3(frame) });
293
+ }
294
+ const nextSeq = u32(header.nextSeq, 'next seq');
295
+ const ops = [];
296
+ let predecessorFp = undefined;
297
+ for (let seq = Math.max(fromSeq - 1, 0); BigInt(seq) < toSeq; seq++) {
298
+ const frame = await stream.exportUpdates(header.turnId, BigInt(seq), 1);
299
+ const fingerprint = blake3(frame);
300
+ if (seq < fromSeq) {
301
+ // Only recomputes the offered range's predecessor fingerprint.
302
+ predecessorFp = fingerprint;
303
+ continue;
304
+ }
305
+ const deps = seq === 0
306
+ ? parents.map(parent => ({ turn: parent.turn, seq: parent.sealSeq, fingerprint: parent.sealFp }))
307
+ : [{ turn: header.turnId, seq: seq - 1, fingerprint: predecessorFp }];
308
+ ops.push({
309
+ turn: header.turnId,
310
+ seq,
311
+ fingerprint,
312
+ deps,
313
+ isSeal: header.sealed !== null && seq === nextSeq - 1,
314
+ parents: parents.map(parent => ({ turnId: parent.turn, sealFp: parent.sealFp })),
315
+ bytesLen: frame.length,
316
+ bytes: frame,
317
+ });
318
+ predecessorFp = fingerprint;
319
+ }
320
+ return ops;
321
+ }
@@ -0,0 +1,214 @@
1
+ import { Inbox } from '../inbox.js';
2
+ import type { IndexedDbStorage } from '../indexeddb.js';
3
+ import { DurableReplay } from '../replay.js';
4
+ import type { Stream } from '../store.js';
5
+ import { CoverageStore } from './coverage.js';
6
+ import type { AsyncPayloadCrypto } from './crypto.js';
7
+ import type { LinkLimits, StopToken } from './link.js';
8
+ import { PolicyStore } from './policy.js';
9
+ import type { WorkScope } from './work.js';
10
+ /**
11
+ * On-demand reverse history (N2, small-scale through-path), the IndexedDB
12
+ * mirror of src/sync/history.rs: fetch the LATEST window of a remote's
13
+ * durable log without downloading it whole, layered on the same
14
+ * Inbox/Replay durable machinery as the live link.
15
+ *
16
+ * # Provider contract (the only backend-coupled seam)
17
+ *
18
+ * `BackwardByteSource` is an injectable, pure-byte primitive: return the
19
+ * ≤`limitBytes` immediately before an opaque offset (or before the tail).
20
+ * **No response ever exceeds `limitBytes`** — a message larger than the
21
+ * page budget is simply paged over (more requests, each bounded), never a
22
+ * budget exception. The interface carries no message-boundary information
23
+ * (the byte-level Durable-Streams protocol exposes none for
24
+ * `application/octet-stream`, and the backend audit (N008) confirms
25
+ * offsets are cumulative byte positions, not message ordinals); batch
26
+ * boundaries come from the provider itself (N011): every page carries a
27
+ * verifiable span list — one span per intersected message, tiling the
28
+ * payload exactly, each giving the message's total length and this
29
+ * fragment's offset within it. A magic/marker scan over the bytes is NOT
30
+ * a boundary proof (payloads may legitimately contain batch-looking
31
+ * bytes, and signature verification proves content authenticity, not
32
+ * server-side boundaries); that approach was abandoned and is kept only
33
+ * as a failure-study record in the goal log (N011). The client
34
+ * reassembles a message from its fragments (contiguity by
35
+ * msgOffset/messageLen arithmetic) and only hands COMPLETE messages to
36
+ * the codec — a fragment is transport state, never framed on spec.
37
+ *
38
+ * # Intake model: collect during the walk, receive forward at its end
39
+ *
40
+ * The walk only collects complete batches (newest pages first, chains
41
+ * prepended). After the byte budget, a Turn that appeared in that
42
+ * window but is missing Create or a contiguous seq prefix may keep
43
+ * paging for at most another `pageLimitBytes`, and only messages of those
44
+ * window turns are kept — intervening history is neither imported nor
45
+ * scanned without bound. If the prefix is still incomplete, the turn
46
+ * stays pending (honest missing-prefix). Receipts are written afterwards,
47
+ * oldest-first. Receipt order
48
+ * is therefore independent of page geometry and walk depth, and imports
49
+ * run in causal order (the pending machinery resolves whatever a window
50
+ * edge still lacks). A crash during the walk loses nothing durable (no
51
+ * receipts were written yet); a crash during the receive phase is healed
52
+ * by the ledger's content addressing: cursors are `0x03 || blake3(batch)`,
53
+ * so re-received batches are exact Inbox duplicates by construction and
54
+ * `Inbox.containsCursor` skips already-held batches without touching the
55
+ * receipt chain — identical batch bytes in the log twice (an op both
56
+ * bridged and self-uploaded) are received once, which is semantically
57
+ * sufficient (the import dedupes regardless). Coverage is marked
58
+ * present-exact from the local store for every admitted op through the
59
+ * same shared path as the live link.
60
+ *
61
+ * # Report honesty (Spec §8)
62
+ *
63
+ * The report states the byte range actually fetched and the turns actually
64
+ * applied or still pending — the log's tail, the globally latest TurnId
65
+ * and a complete local history are three different things, and nothing
66
+ * here claims the latter two.
67
+ */
68
+ /** Errors of history reads. Semantic rejections roll their transaction
69
+ * back; nothing is half-committed. */
70
+ export declare class HistoryError extends Error {
71
+ readonly code: 'invalid' | 'transport' | 'inbox' | 'replay' | 'retryQuota' | 'coverage' | 'store' | 'link' | 'policyDenied' | 'policy';
72
+ constructor(code: 'invalid' | 'transport' | 'inbox' | 'replay' | 'retryQuota' | 'coverage' | 'store' | 'link' | 'policyDenied' | 'policy', message?: string, options?: ErrorOptions);
73
+ }
74
+ /** One message's span within a `BackwardPage` (N011 provider contract):
75
+ * the verifiable boundary of one intersected message. */
76
+ export type MessageSpan = {
77
+ /** Fragment range within the page payload (`payload.subarray(relStart,
78
+ * relEnd)` are this message's bytes). Spans tile the payload ascending
79
+ * without gaps or overlaps — the client verifies this. */
80
+ relStart: number;
81
+ /** See `relStart`. */
82
+ relEnd: number;
83
+ /** The message's opaque absolute start offset (fragments of one
84
+ * message share it across pages; never parsed). */
85
+ messageStart: string;
86
+ /** Total byte length of the COMPLETE message. */
87
+ messageLen: number;
88
+ /** This fragment's byte offset WITHIN the message (`msgOffset +
89
+ * (relEnd - relStart) <= messageLen`): reassembly contiguity is plain
90
+ * arithmetic on these two integers. */
91
+ msgOffset: number;
92
+ };
93
+ /** One bounded backward page from `BackwardByteSource.readBackward`. */
94
+ export type BackwardPage = {
95
+ /** The raw log bytes immediately before `from` (or before the tail):
96
+ * ≤ the requested `limitBytes`, always — a message larger than the
97
+ * limit is fragmented across pages, never a budget exception. */
98
+ payload: Uint8Array;
99
+ /** The opaque offset at which `payload` ends (exclusive). */
100
+ endOffset: string;
101
+ /** The opaque offset at which `payload` starts: the `from` for the
102
+ * next (older) page. */
103
+ prevOffset: string;
104
+ /** True when no bytes exist before `prevOffset` (the log's start). */
105
+ reachedStart: boolean;
106
+ /** One span per message intersecting the payload, oldest first;
107
+ * verified to tile the payload (see `MessageSpan`). */
108
+ messages: MessageSpan[];
109
+ };
110
+ /** The injectable backward byte source (N2's only backend-coupled seam).
111
+ * Implementations perform no retries of their own and never run inside a
112
+ * database transaction; the reader owns resume and idempotency. */
113
+ export interface BackwardByteSource {
114
+ /** Return the ≤`limitBytes` immediately before `from` (omitted reads
115
+ * before the tail). `limitBytes` is a hard cap on every response. */
116
+ readBackward(from: string | undefined, limitBytes: number): Promise<BackwardPage>;
117
+ }
118
+ /** Result of one `HistoryReader.fetchWindow`. */
119
+ export type HistoryReport = {
120
+ /** Backward pages fetched. */
121
+ pages: number;
122
+ /** Complete batches newly received this cycle (already-held batches
123
+ * skipped by content hash are not counted). */
124
+ batches: number;
125
+ /** Bytes fetched from the source this cycle (network-side accounting:
126
+ * a crash or a repeated cycle re-fetches window bytes, which is
127
+ * counted here honestly). */
128
+ bytesFetched: number;
129
+ /** The byte range actually fetched, as opaque offsets `[oldest,
130
+ * tail]`: the honest extent of what this device holds from this walk —
131
+ * never a completeness claim. */
132
+ fetchedRange: [string, string] | undefined;
133
+ /** Turns the import applied (deduped, in application order). */
134
+ appliedTurns: Uint8Array[];
135
+ /** Turns received but pended by the import (a declared parent is not
136
+ * local yet, deduped): they wait for their parent's source and are
137
+ * reported, never faked as verified. */
138
+ pendingTurns: Uint8Array[];
139
+ /** The walk reached the log's start (the whole log fits the window). */
140
+ reachedStart: boolean;
141
+ /** The stop token was observed; the cycle halted cleanly (collected
142
+ * batches are still received) and makes no window-completeness
143
+ * claim. */
144
+ stopped: boolean;
145
+ };
146
+ /** Durable reverse-scan position for incomplete window-turn prefixes. */
147
+ export type PrefixScan = {
148
+ from: string;
149
+ wanted: Uint8Array[];
150
+ };
151
+ /** The on-demand reverse-history reader for one (stream,
152
+ * remote-generation) scope. Opened over the device's single storage owner;
153
+ * the ledger namespace embeds the scope's full generation identity, so a
154
+ * rebound generation starts a fresh ledger while the old one stays
155
+ * retained. */
156
+ export declare class HistoryReader {
157
+ #private;
158
+ readonly scope: WorkScope;
159
+ readonly stream: Stream;
160
+ readonly inbox: Inbox;
161
+ readonly replay: DurableReplay;
162
+ readonly coverage: CoverageStore;
163
+ readonly policy: PolicyStore;
164
+ readonly maxBatchBytes: number;
165
+ /** The intake is the partial-replica path (N3). Coverage marks use
166
+ * the exact local frames and bind a declared parent only where that
167
+ * parent's seal frame is local (N017 P1-C). A window turn whose
168
+ * parent sits below the window is still applied, but carries no
169
+ * mark — writing one without its parent edge would fabricate
170
+ * closure. */
171
+ readonly partial: boolean;
172
+ readonly storage: IndexedDbStorage;
173
+ private constructor();
174
+ /** Open the reader for one (stream, remote-generation) scope (the scope
175
+ * comes from `Executor.scope`). Reuses the link's wire-derived ledger
176
+ * limits; `limits.inbox.maxBatchBytes` also bounds the
177
+ * boundary-discovery buffer (a missing chain past it is typed
178
+ * corruption). */
179
+ static open(storage: IndexedDbStorage, stream: Stream, scope: WorkScope, limits: LinkLimits): HistoryReader;
180
+ /** The partial-replica intake (N3): receipts import through the
181
+ * partial path — parents are declared references and seals verify
182
+ * this turn only, so a reverse-history window becomes displayable
183
+ * `selfVerified` content (with honest `notRetrieved` parent markers
184
+ * below the window) instead of pending forever. */
185
+ static openPartial(storage: IndexedDbStorage, stream: Stream, scope: WorkScope, limits: LinkLimits): HistoryReader;
186
+ /** Decrypt complete stream messages with the same host crypto the
187
+ * upload path used. Never called inside a database transaction. */
188
+ withCrypto(crypto: AsyncPayloadCrypto): this;
189
+ /** Fetch the latest window of the remote's log: page backward from the
190
+ * tail until `budgetBytes` have been fetched this cycle, the log's
191
+ * start, or the stop token. A Turn that appears in that byte window
192
+ * but is missing Create or a contiguous seq prefix (the window cut
193
+ * through Edit/Seal) may keep paging for at most one more
194
+ * `pageLimitBytes` response — and only messages of those window turns
195
+ * are collected.
196
+ * Intervening turns are not imported; if the prefix is still
197
+ * incomplete the turn stays pending. Then receive the collected
198
+ * batches oldest-first, skipping any the ledger already holds by
199
+ * content hash.
200
+ * `pageLimitBytes` is the hard per-response cap of every provider call.
201
+ * Network, receipt persistence, import and coverage marks are atomic
202
+ * per batch; the walk's buffer is never persisted (a crash re-walks:
203
+ * the fetch cost is visible in `bytesFetched`, the ledger absorbs every
204
+ * re-receipt). */
205
+ fetchWindow(source: BackwardByteSource, budgetBytes: number, pageLimitBytes: number, stop: StopToken): Promise<HistoryReport>;
206
+ /** The durable reverse-scan position for incomplete window-turn prefixes. */
207
+ prefixScan(): Promise<PrefixScan | undefined>;
208
+ /** Resume the reverse scan for pending window-turn prefixes. Each call
209
+ * fetches at most `budgetBytes` and keeps only messages of those
210
+ * pending turns. Sequential providers still deliver intervening bytes;
211
+ * recovering a Create G bytes behind the window takes about G bytes
212
+ * across calls. Does not re-read the tail window. */
213
+ completePrefixes(source: BackwardByteSource, budgetBytes: number, pageLimitBytes: number, stop: StopToken): Promise<HistoryReport>;
214
+ }