@loro-dev/roost 0.1.1 → 0.1.2

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.
package/README.md CHANGED
@@ -12,7 +12,7 @@ The `Inbox` module adds atomic raw receipt/cursor storage, without authenticatin
12
12
  or applying those bytes.
13
13
 
14
14
  ```sh
15
- npm install @loro-dev/roost@0.1.0
15
+ npm install @loro-dev/roost@0.1.2
16
16
  ```
17
17
 
18
18
  For source development and browser tests:
@@ -271,6 +271,14 @@ the core outbox. Discovery page size bounds each page, while `maxSend` bounds on
271
271
  sends. Partial replicas keep directed `Link.bridgeTurns` and its `waitingParent`
272
272
  result for missing dependencies. See the discovery and upgrade contract.
273
273
 
274
+ Browser `HistoryReader.fetchWindow(source, budgetBytes, pageLimitBytes, stop,
275
+ { before, completePrefixes: false })` resumes at the previous window's complete
276
+ message boundary. This option stops at the byte budget without filtering extra
277
+ prefix-repair pages into the window range. Use explicit `completePrefixes` to
278
+ repair pending window turns. Persist the oldest contiguous boundary only after
279
+ intake commits, and initialize `Link.catchUpAt` from the original window tail,
280
+ never a later `head()` result. The Node window API is unchanged.
281
+
274
282
  `pnpm pack:consumer -- /absolute/output/directory` builds the npm tarball and
275
283
  checks its public entries. It depends on the exact registry release
276
284
  `@loro-dev/streams-client@0.8.0`, with no bundled SDK. `pnpm check:consumer`
@@ -384,21 +392,36 @@ different input under that ID is a conflict. `LodyHistory` and `NodeLodyHistory`
384
392
  expose the same contract. The caller still owns queue, steer and ACP lifecycle
385
393
  decisions.
386
394
 
395
+ `LodyHistory.readOnly(stream)` indexes and projects admitted native history without
396
+ a signing identity; authoring through that instance rejects. The host still owns
397
+ stream authorization and seal verification. `restoreActiveBranch` is available in
398
+ both browser and Node adapters: it atomically creates and seals a non-message
399
+ `branch_state` record with its local branch/operation indexes. Remote indexers
400
+ reconstruct the rollback, including an empty restored view, from that native
401
+ record. `branch_state` is readable as an internal history identity but is excluded
402
+ from `HistoryWriteIdentity`, `AcceptHistory` and batch commands; generic authoring
403
+ rejects it at runtime as well. Use `restoreActiveBranch` as the only write path. It
404
+ does not edit sealed Turns or change the Rust state machine/wire.
405
+
387
406
  Active-branch pages return `startPosition`, `totalCount`, `hasMoreOlder`, and an
388
407
  opaque ancestry cursor alongside the selected messages. Positions/counts refer
389
408
  to logical `businessId` rows: use `primary` for the initial segment and distinct
390
409
  successor IDs for late output. Project all returned segments of a business ID
391
410
  into one row. Linear branches written with this metadata read a bounded page;
392
411
  legacy/nonlinear ancestry may rebuild a complete directory. `readActiveBranch`
393
- remains available for explicit full snapshots. Generic published-message reverse
412
+ remains available for explicit full snapshots, fenced by the durable event cursor
413
+ so a concurrent import cannot mix branch membership and bodies. A partial replica
414
+ missing an older boundary reports incomplete and preserves the logical count;
415
+ the host fetches or repairs that boundary instead of declaring shorter history.
416
+ Generic published-message reverse
394
417
  pages include superseded messages and cannot substitute for active-branch pages.
395
418
 
396
419
  An append preserves older cursors while adding any intervening late successors.
397
420
  A fork that removes the cursor's ancestry rejects it as `stale`; refresh the
398
421
  loaded window and obtain a new cursor. The last reverse page can contain fewer
399
- than `limit` rows and never extends past the cursor. These APIs are currently
400
- used by Lody's local Node owner integration; that does not imply a separate
401
- browser replica or remote synchronization acceptance.
422
+ than `limit` rows and never extends past the cursor. Lody uses these APIs in its
423
+ Node owner and read-only browser replica. Static checks of that composition do
424
+ not establish live-service synchronization or product performance acceptance.
402
425
 
403
426
  New records in the private `lody_history_published_v1` table have a `version: "2"`
404
427
  membership-only value. Current readers also accept legacy full-snapshot values;
@@ -10,26 +10,29 @@ import { type ContentOp, type ParentRef } from './codec.js';
10
10
  import { type JsonValue } from './json.js';
11
11
  import { Identity } from './identity.js';
12
12
  import { Stream, type TurnReadResult } from './store.js';
13
- type Kind = 'message' | 'permission_response' | 'dispatch_intent' | 'batch_receipt' | 'publication';
13
+ type Kind = 'message' | 'permission_response' | 'dispatch_intent' | 'batch_receipt' | 'publication' | 'branch_state';
14
14
  export type HistoryIdentity = {
15
15
  businessId: string;
16
16
  segmentId: string;
17
17
  kind: Kind;
18
18
  };
19
+ export type HistoryWriteIdentity = Omit<HistoryIdentity, 'kind'> & {
20
+ kind: Exclude<Kind, 'branch_state'>;
21
+ };
19
22
  export type HistoryBatchCommand = {
20
23
  type: 'accept';
21
- identity: HistoryIdentity;
24
+ identity: HistoryWriteIdentity;
22
25
  parents: ParentRef[];
23
26
  content: JsonValue;
24
27
  attachments?: AttachmentIdentity[];
25
28
  } | {
26
29
  type: 'setContent';
27
- identity: HistoryIdentity;
30
+ identity: HistoryWriteIdentity;
28
31
  expectedNextSeq: bigint;
29
32
  content: JsonValue;
30
33
  } | {
31
34
  type: 'finish';
32
- identity: HistoryIdentity;
35
+ identity: HistoryWriteIdentity;
33
36
  expectedNextSeq: bigint;
34
37
  } | {
35
38
  type: 'permission';
@@ -70,7 +73,7 @@ export type AttachmentIdentity = {
70
73
  name: string;
71
74
  size: bigint;
72
75
  };
73
- export type AcceptHistory = HistoryIdentity & {
76
+ export type AcceptHistory = HistoryWriteIdentity & {
74
77
  parents: ParentRef[];
75
78
  content: JsonValue;
76
79
  attachments?: AttachmentIdentity[];
@@ -160,8 +163,12 @@ type Binding = {
160
163
  * never replaces an older signature. Dispatch/Flock and locations are host-owned. */
161
164
  export declare class LodyHistory {
162
165
  readonly stream: Stream;
163
- readonly identity: Identity;
164
- constructor(stream: Stream, identity: Identity);
166
+ private readonly signingIdentity?;
167
+ constructor(stream: Stream, signingIdentity?: Identity | undefined);
168
+ /** A replica can project admitted history without owning a signing key.
169
+ * Index maintenance is local; authoring through this instance is rejected. */
170
+ static readOnly(stream: Stream): LodyHistory;
171
+ get identity(): Identity;
165
172
  private get space();
166
173
  private get cursorSpace();
167
174
  indexPage(limit?: number): Promise<boolean>;
@@ -178,6 +185,7 @@ export declare class LodyHistory {
178
185
  acceptToView(input: BranchAcceptInput): Promise<BranchMutationResult>;
179
186
  /** Create a replacement Turn and switch the same logical view to it. */
180
187
  forkAndActivate(input: ForkAndActivateInput): Promise<BranchMutationResult>;
188
+ restoreActiveBranch(input: RestoreActiveBranchInput): Promise<RestoreActiveBranchResult>;
181
189
  readActiveBranch(viewId: string): Promise<ActiveBranchRead>;
182
190
  readActiveBranchPage(viewId: string, input?: {
183
191
  before?: ActiveBranchPageCursor;
@@ -9,13 +9,19 @@ const invalid = (message) => new StoreError('invalid', message);
9
9
  function text(v) { if (typeof v !== 'string' || !v.length || encodeUtf8(v).length > 1024)
10
10
  throw invalid('history identity size'); return v; }
11
11
  function knownKind(kind) {
12
- return kind === 'message' || kind === 'permission_response' || kind === 'dispatch_intent' || kind === 'batch_receipt' || kind === 'publication';
12
+ return kind === 'message' || kind === 'permission_response' || kind === 'dispatch_intent' || kind === 'batch_receipt' || kind === 'publication' || kind === 'branch_state';
13
13
  }
14
14
  function keyOf(v) {
15
15
  if (!knownKind(v.kind))
16
16
  throw invalid('history kind');
17
17
  return encodeUtf8(JSON.stringify([v.kind, text(v.businessId), text(v.segmentId)]));
18
18
  }
19
+ function assertWritableIdentity(value) {
20
+ if (!value || typeof value !== 'object' || !knownKind(value.kind))
21
+ throw invalid('history kind');
22
+ if (value.kind === 'branch_state')
23
+ throw invalid('branch_state is reserved for restoreActiveBranch');
24
+ }
19
25
  const BRANCH_TABLE = 'lody_history_branches_v1';
20
26
  const BRANCH_OPERATIONS = 'lody_history_branch_operations_v1';
21
27
  function branchKey(viewId) { return encodeUtf8(text(viewId)); }
@@ -256,10 +262,18 @@ function binding(raw) {
256
262
  * never replaces an older signature. Dispatch/Flock and locations are host-owned. */
257
263
  export class LodyHistory {
258
264
  stream;
259
- identity;
260
- constructor(stream, identity) {
265
+ signingIdentity;
266
+ constructor(stream, signingIdentity) {
261
267
  this.stream = stream;
262
- this.identity = identity;
268
+ this.signingIdentity = signingIdentity;
269
+ }
270
+ /** A replica can project admitted history without owning a signing key.
271
+ * Index maintenance is local; authoring through this instance is rejected. */
272
+ static readOnly(stream) { return new LodyHistory(stream); }
273
+ get identity() {
274
+ if (!this.signingIdentity)
275
+ throw invalid('read-only history cannot author Turns');
276
+ return this.signingIdentity;
263
277
  }
264
278
  get space() { return this.stream.space('lody_history_bindings_v1'); }
265
279
  get cursorSpace() { return this.stream.space('lody_history_index_v1'); }
@@ -363,6 +377,7 @@ export class LodyHistory {
363
377
  async accept(input, options) {
364
378
  // Own every input before the first await. The original Create fingerprint is
365
379
  // stable even after edits; a retry must not compare against the current body.
380
+ assertWritableIdentity(input);
366
381
  const key = keyOf(input), owner = this.identity.owner();
367
382
  const rawInput = canonicalCreate(owner, input.parents, envelope(input, options?.publish !== false)), fingerprint = createDigest(owner, input.parents, envelope(input));
368
383
  const copied = decodeFrame(rawInput);
@@ -403,6 +418,9 @@ export class LodyHistory {
403
418
  forkAndActivate(input) {
404
419
  return branchFork(this, input);
405
420
  }
421
+ restoreActiveBranch(input) {
422
+ return branchRestore(this, input);
423
+ }
406
424
  readActiveBranch(viewId) {
407
425
  return readActiveBranch(this, viewId);
408
426
  }
@@ -664,6 +682,7 @@ export class NodeLodyHistory {
664
682
  }
665
683
  async finish(id, seq) { await this.stream.seal(id, seq); }
666
684
  async accept(input, options) {
685
+ assertWritableIdentity(input);
667
686
  const key = keyOf(input), raw = canonicalCreate(this.owner, input.parents, envelope(input, options?.publish !== false)), digest = createDigest(this.owner, input.parents, envelope(input));
668
687
  const copied = decodeFrame(raw);
669
688
  if (copied.operation.kind !== 'create')
@@ -805,7 +824,7 @@ async function branchMetadataAt(host, turnId) {
805
824
  return parseBranchMetadata(await publicationField(host, turnId, [{ key: 'lodyBranch' }]));
806
825
  }
807
826
  catch (error) {
808
- if (errorCode(error) === 'invalid')
827
+ if (errorCode(error) === 'invalid' || errorCode(error) === 'pending')
809
828
  return undefined;
810
829
  throw error;
811
830
  }
@@ -882,7 +901,9 @@ async function branchMutation(host, input, baseTurn, supersedes) {
882
901
  const branchValue = branchStateValue(metadata);
883
902
  const operationValue = branchOperationValue({ operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId: null }, metadata.digest);
884
903
  for (let attempt = 0; attempt < 4; attempt++) {
885
- await host.catchUpIndex();
904
+ // Fence every state read below, not only the final write. A concurrent
905
+ // branch mutation after these checks must invalidate this attempt.
906
+ const cursor = await branchCursor(host);
886
907
  const [state, priorOperation] = await Promise.all([
887
908
  readBranchIndex(host, viewId),
888
909
  readBranchOperation(host, viewId, operationId),
@@ -910,7 +931,6 @@ async function branchMutation(host, input, baseTurn, supersedes) {
910
931
  if (!existingBranch || existingBranch.operationId !== operationId || existingBranch.digest !== metadata.digest)
911
932
  throw new StoreError('conflict', 'branch message identity already exists');
912
933
  }
913
- const cursor = await branchCursor(host);
914
934
  try {
915
935
  await writeIndexed(host, [{ kind: 'createOnce', key: createKey, parents: input.input.parents, content: envelope(input.input, true, metadata) }], [
916
936
  { table: BRANCH_TABLE, key: branchKey(viewId), value: branchValue, emitEvent: true },
@@ -952,6 +972,7 @@ function branchRestoreDigest(input) {
952
972
  ]))));
953
973
  }
954
974
  async function branchRestore(host, input) {
975
+ await branchOwner(host);
955
976
  if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
956
977
  throw invalid('branch revision');
957
978
  const viewId = text(input.viewId), operationId = text(input.operationId), digest = branchRestoreDigest(input);
@@ -966,7 +987,7 @@ async function branchRestore(host, input) {
966
987
  keyOf(input.restoreHead);
967
988
  }
968
989
  for (let attempt = 0; attempt < 4; attempt++) {
969
- await host.catchUpIndex();
990
+ const cursor = await branchCursor(host);
970
991
  const [state, priorOperation] = await Promise.all([
971
992
  readBranchIndex(host, viewId),
972
993
  readBranchOperation(host, viewId, operationId),
@@ -1002,9 +1023,19 @@ async function branchRestore(host, input) {
1002
1023
  supersedes: [],
1003
1024
  digest,
1004
1025
  };
1005
- const cursor = await branchCursor(host);
1026
+ // The branch index is only a projection. A signed native record makes a
1027
+ // rollback visible to remote replicas, including an empty restored view.
1028
+ // It is not a message and is never included in the visible transcript.
1029
+ const record = {
1030
+ kind: 'branch_state', businessId: viewId, segmentId: operationId, parents: [],
1031
+ content: new Map([['operation', 'restore']]),
1032
+ };
1033
+ const recordKey = keyOf(record);
1006
1034
  try {
1007
- await writeIndexed(host, [], [
1035
+ await writeIndexed(host, [
1036
+ { kind: 'createOnce', key: recordKey, parents: [], content: envelope(record, false, metadata) },
1037
+ { kind: 'sealOnce', key: recordKey, expectedNextSeq: 1n },
1038
+ ], [
1008
1039
  { table: BRANCH_TABLE, key: branchKey(viewId), value: branchStateValue(metadata), emitEvent: true },
1009
1040
  { table: BRANCH_OPERATIONS, key: branchOperationKey(viewId, operationId), value: branchOperationValue({ operationId, created: true, oldHead: input.expectedHead, newHead: input.restoreHead, revision: metadata.revision, turnId: restoreTurnId ?? null }, digest) },
1010
1041
  ], cursor);
@@ -1019,7 +1050,9 @@ async function branchRestore(host, input) {
1019
1050
  throw new StoreError('stale', 'active branch restore retry budget exhausted');
1020
1051
  }
1021
1052
  async function readActiveBranch(host, viewId) {
1022
- await host.catchUpIndex();
1053
+ return (await stableRead(host, () => readActiveBranchSnapshot(host, viewId))).value;
1054
+ }
1055
+ async function readActiveBranchSnapshot(host, viewId) {
1023
1056
  const state = await readBranchIndex(host, viewId);
1024
1057
  if (!state)
1025
1058
  return { state: { viewId: text(viewId), revision: 0n, head: null, operationId: null }, messages: [], complete: true };
@@ -1104,7 +1137,7 @@ async function branchIdentityAt(host, turnId) {
1104
1137
  return decodeIdentity(value);
1105
1138
  }
1106
1139
  catch (error) {
1107
- if (errorCode(error) === 'invalid')
1140
+ if (errorCode(error) === 'invalid' || errorCode(error) === 'pending')
1108
1141
  return undefined;
1109
1142
  throw error;
1110
1143
  }
@@ -1391,7 +1424,13 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
1391
1424
  }
1392
1425
  seen.add(turnKey);
1393
1426
  const metadata = await branchMetadataAt(host, currentId);
1394
- if (!metadata || metadata.viewId !== state.viewId || !metadata.head || metadata.head.kind !== 'message')
1427
+ // A partial replica stops at its fetched boundary. Do not turn that into
1428
+ // a full-directory fallback (and a false, shorter logical count).
1429
+ if (!metadata) {
1430
+ complete = false;
1431
+ break;
1432
+ }
1433
+ if (metadata.viewId !== state.viewId || !metadata.head || metadata.head.kind !== 'message')
1395
1434
  return undefined;
1396
1435
  if (metadata.logicalCount === undefined)
1397
1436
  return undefined;
@@ -1428,7 +1467,7 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
1428
1467
  const endPosition = Math.min(totalCount, input.before ? input.before.position + 1 : totalCount);
1429
1468
  const expectedRows = Math.max(0, Math.min(limit, endPosition - startPosition));
1430
1469
  if (selected.size !== expectedRows)
1431
- return undefined;
1470
+ complete = false;
1432
1471
  const selectedIds = new Set(selected.keys());
1433
1472
  const segmentGroups = new Map();
1434
1473
  for (const segment of [...collected].reverse()) {
@@ -1449,7 +1488,7 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
1449
1488
  totalCount,
1450
1489
  startPosition: actualStart,
1451
1490
  messages,
1452
- hasMoreOlder: cursor !== null,
1491
+ hasMoreOlder: cursor !== null || (!complete && actualStart > 0),
1453
1492
  cursor,
1454
1493
  complete,
1455
1494
  };
@@ -1648,6 +1687,7 @@ function decodeIdentity(value) {
1648
1687
  if (typeof kind !== 'string' || !knownKind(kind) || typeof businessId !== 'string' || typeof segmentId !== 'string')
1649
1688
  throw invalid('command identity');
1650
1689
  const identity = { kind, businessId, segmentId };
1690
+ assertWritableIdentity(identity);
1651
1691
  keyOf(identity);
1652
1692
  return identity;
1653
1693
  }
@@ -2214,6 +2254,11 @@ async function commitBatch(host, batchId, commands) {
2214
2254
  throw invalid('batch id');
2215
2255
  if (!commands.length || commands.length > 64)
2216
2256
  throw invalid('batch size');
2257
+ for (const command of commands) {
2258
+ if (command.type === 'accept' || command.type === 'setContent' || command.type === 'finish') {
2259
+ assertWritableIdentity(command.identity);
2260
+ }
2261
+ }
2217
2262
  await host.catchUpIndex();
2218
2263
  const digest = commandDigest(batchId, commands);
2219
2264
  const identity = { kind: 'batch_receipt', businessId: batchId, segmentId: 'v1' };
@@ -201,8 +201,14 @@ export declare class HistoryReader {
201
201
  * Network, receipt persistence, import and coverage marks are atomic
202
202
  * per batch; the walk's buffer is never persisted (a crash re-walks:
203
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>;
204
+ * re-receipt). `before` continues an older window at a previously returned
205
+ * complete-message boundary. With `completePrefixes: false`, the report's
206
+ * range is a contiguous imported suffix: prefix repair is deferred to
207
+ * `completePrefixes`, so a pagination cursor never skips filtered messages. */
208
+ fetchWindow(source: BackwardByteSource, budgetBytes: number, pageLimitBytes: number, stop: StopToken, options?: {
209
+ before?: string;
210
+ completePrefixes?: boolean;
211
+ }): Promise<HistoryReport>;
206
212
  /** The durable reverse-scan position for incomplete window-turn prefixes. */
207
213
  prefixScan(): Promise<PrefixScan | undefined>;
208
214
  /** Resume the reverse scan for pending window-turn prefixes. Each call
@@ -257,16 +257,19 @@ export class HistoryReader {
257
257
  * Network, receipt persistence, import and coverage marks are atomic
258
258
  * per batch; the walk's buffer is never persisted (a crash re-walks:
259
259
  * the fetch cost is visible in `bytesFetched`, the ledger absorbs every
260
- * re-receipt). */
261
- async fetchWindow(source, budgetBytes, pageLimitBytes, stop) {
260
+ * re-receipt). `before` continues an older window at a previously returned
261
+ * complete-message boundary. With `completePrefixes: false`, the report's
262
+ * range is a contiguous imported suffix: prefix repair is deferred to
263
+ * `completePrefixes`, so a pagination cursor never skips filtered messages. */
264
+ async fetchWindow(source, budgetBytes, pageLimitBytes, stop, options = {}) {
262
265
  try {
263
- return await this.#fetchWindow(source, budgetBytes, pageLimitBytes, stop);
266
+ return await this.#fetchWindow(source, budgetBytes, pageLimitBytes, stop, options);
264
267
  }
265
268
  catch (e) {
266
269
  return rethrow(e);
267
270
  }
268
271
  }
269
- async #fetchWindow(source, budgetBytes, pageLimitBytes, stop) {
272
+ async #fetchWindow(source, budgetBytes, pageLimitBytes, stop, options) {
270
273
  if (!await this.policy.allowsDownload(this.scope))
271
274
  throw new HistoryError('policyDenied', 'mirror policy denies download for this scope');
272
275
  if (pageLimitBytes === 0 || budgetBytes === 0)
@@ -288,7 +291,7 @@ export class HistoryReader {
288
291
  // bytes so far, and the message offset the NEXT (older) fragment
289
292
  // must end at.
290
293
  let partial;
291
- let from;
294
+ let from = options.before;
292
295
  let tail;
293
296
  let oldestBoundary;
294
297
  // Turns that appeared in the budget-bounded window. After the
@@ -308,6 +311,8 @@ export class HistoryReader {
308
311
  windowTurns = await turnsInWindow(this.#crypto, collected);
309
312
  await this.#includePriorWanted(windowTurns);
310
313
  }
314
+ if (options.completePrefixes === false)
315
+ break;
311
316
  if (windowTurns.size === 0 || await prefixesComplete(this.#crypto, collected, windowTurns)
312
317
  || extraFetched >= pageLimitBytes)
313
318
  break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loro-dev/roost",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Browser conversation history and sync for Loro Roost",
5
5
  "license": "MIT",
6
6
  "publishConfig": { "access": "public" },