@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,276 @@
1
+ import type { IndexedDbStorage, KvTransaction, Step } from '../indexeddb.js';
2
+ import type { Generation, RemoteId } 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 declare 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 declare 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 declare const SUMMARY_RECORD_VERSION = 2;
66
+ /** Coverage record keys start with this tag. */
67
+ export declare const COVERAGE_KEY_TAG = 1;
68
+ /** Closed record keys start with this tag. */
69
+ export declare const CLOSED_KEY_TAG = 2;
70
+ /** Conflict diagnostic keys start with this tag. */
71
+ export declare const CONFLICT_KEY_TAG = 3;
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 declare const CHILD_KEY_TAG = 4;
78
+ /** Per-seq fingerprint record keys start with this tag (chunked layout, W5). */
79
+ export declare const SEQ_KEY_TAG = 5;
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 declare const ISLAND_KEY_TAG = 6;
83
+ /** Maximum distinct seqs tracked per turn (islands and prefix together). */
84
+ export declare const MAX_PRESENT_SEQS: number;
85
+ /** Full scope of every coverage key: one remote target's view of one stream
86
+ * generation. Queries and writes for different scopes are independent truths;
87
+ * a generation mismatch is simply a different scope, never inherited. */
88
+ export type CoverageScope = {
89
+ remote: RemoteId;
90
+ generation: Generation;
91
+ stream: string;
92
+ };
93
+ /** Lightweight direct-dependency reference: a parent turn's closed assertion
94
+ * is identified by the parent's seal fingerprint. */
95
+ export type ParentRef = {
96
+ turnId: Uint8Array;
97
+ sealFp: Uint8Array;
98
+ };
99
+ /** The persisted seal claim of one turn: the first `isSeal = true` mark wins
100
+ * and stays; a later mark claiming a different seal seq is rejected. */
101
+ export type SealClaim = {
102
+ seq: number;
103
+ fp: Uint8Array;
104
+ };
105
+ /** The durable `closed` assertion of one turn on one target (T5). */
106
+ export type ClosedRecord = {
107
+ sealSeq: number;
108
+ sealFp: Uint8Array;
109
+ };
110
+ /** The present-state of one turn on one target, recomputed on read from the
111
+ * persisted records. `fingerprints` maps each present seq to every distinct
112
+ * content fingerprint observed there (both copies of a conflict). */
113
+ export type PresentState = {
114
+ prefixLen: number;
115
+ holes: number[];
116
+ seal: SealClaim | null;
117
+ parents: ParentRef[];
118
+ fingerprints: Map<number, Uint8Array[]>;
119
+ };
120
+ /** Outcome of one `CoverageStore.markPresent` call. */
121
+ export type MarkResult = {
122
+ kind: 'stored';
123
+ } | {
124
+ kind: 'closed';
125
+ } | {
126
+ kind: 'duplicate';
127
+ } | {
128
+ kind: 'contentConflict';
129
+ existing: Uint8Array;
130
+ };
131
+ /** Errors returned by CoverageStore. `code` mirrors the Rust CoverageError
132
+ * variants; `cause` carries structured fields where the Rust variant has
133
+ * them. Native IDB failures propagate as DOMExceptions, as in the registry. */
134
+ export declare class CoverageError extends Error {
135
+ readonly code: 'storage' | 'corrupt' | 'unsupportedVersion' | 'invalid' | 'sealConflict' | 'generationConflict';
136
+ constructor(code: 'storage' | 'corrupt' | 'unsupportedVersion' | 'invalid' | 'sealConflict' | 'generationConflict', message?: string, options?: ErrorOptions);
137
+ }
138
+ type ParentDto = {
139
+ turn: number[];
140
+ seal_fp: number[];
141
+ };
142
+ export type DeclaredParent = {
143
+ turn: number[];
144
+ hash: number[];
145
+ };
146
+ /** Coverage record key: `[COVERAGE_KEY_TAG] || scope || turn[16]`. */
147
+ export declare function coverageKey(scope: CoverageScope, turn: Uint8Array): Uint8Array;
148
+ /** Closed record key: `[CLOSED_KEY_TAG] || scope || turn[16]`. */
149
+ export declare function closedKey(scope: CoverageScope, turn: Uint8Array): Uint8Array;
150
+ /** Conflict diagnostic key: `[CONFLICT_KEY_TAG] || scope || turn[16] || seq[4 BE]`. */
151
+ export declare function conflictKey(scope: CoverageScope, turn: Uint8Array, seq: number): Uint8Array;
152
+ /**
153
+ * Coverage store over a shared IndexedDbStorage owner.
154
+ *
155
+ * Construct with the same IndexedDbStorage the host's Store and
156
+ * RemoteRegistry use, so coverage, registration and stream content commit
157
+ * through one fixed owner. The store never opens its own connection and
158
+ * never touches the network.
159
+ *
160
+ * Calling contract: every `markPresent` for one turn must carry that turn's
161
+ * complete direct parent list; the first non-empty list is persisted in the
162
+ * coverage record, so the closed assertion cannot be completed by a later
163
+ * call that forgot them.
164
+ */
165
+ export declare class CoverageStore {
166
+ readonly storage: IndexedDbStorage;
167
+ constructor(storage: IndexedDbStorage);
168
+ /** Record one confirmed operation of `turn` on this target in a single
169
+ * write transaction: idempotent duplicates, content-conflict retention,
170
+ * coverage update and — when `0..=seal_seq` completes and every direct
171
+ * dependency is already closed — the `closed` assertion, all atomic (T5).
172
+ * A throw inside the program aborts the native IDB transaction, so a
173
+ * rejected mark commits nothing as a whole. */
174
+ processedReports(scope: CoverageScope, source: string): Promise<bigint>;
175
+ finishReport(scope: CoverageScope, source: string, sequence: bigint): Promise<void>;
176
+ recordServed(scope: CoverageScope, entries: {
177
+ turn: Uint8Array;
178
+ seq: number;
179
+ fp: Uint8Array;
180
+ }[]): Promise<void>;
181
+ wasServed(scope: CoverageScope, turn: Uint8Array, seq: number, fp: Uint8Array): Promise<boolean>;
182
+ unresolvedChildren(scope: CoverageScope, parent: Uint8Array): Promise<Uint8Array[]>;
183
+ markReceived(scope: CoverageScope, turn: Uint8Array, seq: number, fp: Uint8Array, isSeal: boolean, parents: ParentRef[], unresolved: DeclaredParent[]): Promise<MarkResult>;
184
+ markPresent(scope: CoverageScope, turn: Uint8Array, seq: number, fingerprint: Uint8Array, isSeal: boolean, parents: ParentRef[]): Promise<MarkResult>;
185
+ /** The mark-present logic inside a caller's transaction (the composition
186
+ * point for atomic multi-store operations, T3 — the Rust
187
+ * `mark_present_in`): the caller must run this inside a single write
188
+ * transaction of the shared owner. A turn whose record predates the
189
+ * chunked layout is converted inside this same transaction first (per-seq
190
+ * rows, island rows, summary), so a crash rolls the conversion back with
191
+ * the mark and the next mark retries it. */
192
+ markPresentIn(tx: KvTransaction, scope: CoverageScope, turn: Uint8Array, seq: number, fp: Uint8Array, isSeal: boolean, parentDtos: ParentDto[]): Step<MarkResult>;
193
+ /** Convert a legacy whole-turn record to the chunked layout inside the
194
+ * caller's transaction: one per-seq row per distinct seq (both copies of
195
+ * a conflict), one island row per out-of-prefix seq, and the summary
196
+ * written last. Purely deterministic from the legacy record. */
197
+ private convertLegacy;
198
+ /** Whether seq `seq` of `turn` is confirmed present on this target
199
+ * (inside the prefix or an explicit island), regardless of fingerprint. */
200
+ isPresent(scope: CoverageScope, turn: Uint8Array, seq: number): Promise<boolean>;
201
+ /** The full present state of `turn` on this target, or undefined when the
202
+ * turn was never marked in this scope. This is the full-read path: for
203
+ * the chunked layout it scans the turn's per-seq and island rows and
204
+ * re-computes every stored invariant instead of trusting them. */
205
+ presentState(scope: CoverageScope, turn: Uint8Array): Promise<PresentState | undefined>;
206
+ /** The persisted `closed` assertion of `turn` on this target, or
207
+ * undefined when the turn is not closed here. Only the small closed
208
+ * record is read — never ancestor bodies. */
209
+ isClosed(scope: CoverageScope, turn: Uint8Array): Promise<ClosedRecord | undefined>;
210
+ /** Declare that `remote` moves from `oldGeneration` to `newGeneration`.
211
+ * Coverage is scoped per generation in every key, so the new generation
212
+ * already starts empty and the old records stay in place, readable only
213
+ * through the old generation. This call only enforces the ordering
214
+ * contract with RemoteRegistry.rebind: archive before any new-generation
215
+ * write, never after. It commits nothing. */
216
+ archiveGeneration(remote: RemoteId, oldGeneration: Generation, newGeneration: Generation): Promise<void>;
217
+ /** Exact presence of one operation's content — `(turn, seq, fingerprint)`
218
+ * — inside a caller's transaction (the composition point for a
219
+ * scheduler's per-operation dependency gate; the Rust
220
+ * `present_exact_in`). Same-position different-content never satisfies
221
+ * this check. The hot path is one small per-seq read; a turn whose record
222
+ * predates the chunked layout answers from its legacy record until its
223
+ * next mark converts it. */
224
+ presentExactIn(tx: KvTransaction, scope: CoverageScope, turn: Uint8Array, seq: number, fingerprint: Uint8Array): Step<boolean>;
225
+ /** Whether `turn`'s persisted closed assertion exists and matches
226
+ * `sealFp`, inside a caller's transaction (the Rust `closed_matches_in`).
227
+ * A closed record asserts the full `0..=seal_seq` range and every direct
228
+ * dependency, so matching its seal fingerprint binds the exact sealed
229
+ * ancestry (T5). */
230
+ closedMatchesIn(tx: KvTransaction, scope: CoverageScope, turn: Uint8Array, sealFp: Uint8Array): Step<boolean>;
231
+ /** Whether this target demonstrably holds the *complete* operation range
232
+ * of `turn` (`0..=seal_seq`, with `sealFp` at the seal position) without
233
+ * asserting anything about `turn`'s own ancestors — the direct
234
+ * precondition for admitting a child of `turn`. `closedMatchesIn` implies
235
+ * it; the converse does not hold, and the direct form is what a
236
+ * reverse-history window honestly establishes for a partial replica
237
+ * (N017 P1-C). Mirror of `complete_matches_in` in src/sync/coverage.rs. */
238
+ completeMatchesIn(tx: KvTransaction, scope: CoverageScope, turn: Uint8Array, sealFp: Uint8Array): Step<boolean>;
239
+ /** Whether a task depending on `turn` (a cross-turn parent bound to
240
+ * `sealFp`) may be sent to this target: the recursive `closed` assertion,
241
+ * or the direct complete-turn evidence a reverse-history window
242
+ * establishes. */
243
+ parentAdmissibleIn(tx: KvTransaction, scope: CoverageScope, turn: Uint8Array, sealFp: Uint8Array): Step<boolean>;
244
+ /** Persist the parent→child reverse edges declared by `parents` for
245
+ * `turn`, inside the caller's transaction (idempotent; missing rows of
246
+ * already-persisted edges are healed here). */
247
+ private ensureParentEdges;
248
+ /** Re-evaluate closure for every turn that declared `turn` as a direct
249
+ * parent, recursively, inside the caller's transaction (T5 extension,
250
+ * RS2-04): closed records are persisted assertions, so a turn whose marks
251
+ * completed before its parent closed must still close once the parent
252
+ * does — mark arrival order must not decide liveness. Each turn closes at
253
+ * most once, so the walk is bounded by the number of newly closed turns
254
+ * and never rewrites an existing closed record. Children whose records
255
+ * predate the chunked layout are evaluated from their legacy record (they
256
+ * convert on their own next mark, never here). */
257
+ private cascadeClosed;
258
+ /** Write the closed record when a chunked-layout turn just became
259
+ * eligible; returns whether a new closed record was written. Eligibility:
260
+ * a persisted seal claim whose fingerprint is present (one per-seq read),
261
+ * the full prefix `0..=seal_seq` present (the O(1) island check,
262
+ * CASE-05), and every direct dependency closed. */
263
+ private maybeCloseSummary;
264
+ /** Write the closed record when a legacy-record turn just became eligible
265
+ * (the cascade re-evaluates children regardless of their layout). */
266
+ private maybeCloseLegacy;
267
+ /** The shared tail of the closed check: every direct dependency
268
+ * (persisted parents plus this call's, deduped) must be closed with a
269
+ * matching seal fingerprint; then the closed record is written once and
270
+ * never changed. */
271
+ private closeWithDeps;
272
+ /** Append both fingerprints of a content conflict to the diagnostic
273
+ * record of one `(turn, seq)`; diagnostics are observability only. */
274
+ private recordConflict;
275
+ }
276
+ export {};