@loro-dev/roost 0.1.3 → 0.3.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.
package/README.md CHANGED
@@ -12,9 +12,14 @@ 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.3
15
+ npm install @loro-dev/roost@0.3.0
16
16
  ```
17
17
 
18
+ This source targets the coordinated Rust/TypeScript/Native 0.3.0 release;
19
+ the registry determines npm availability. Native SQLite storage in
20
+ this release accepts fresh/v10 containers only. Preserve older databases with
21
+ their compatible runtime; there is no automatic migration or deletion.
22
+
18
23
  For source development and browser tests:
19
24
 
20
25
  ```sh
@@ -307,6 +312,24 @@ Concurrent plans retain their original processed cursor, retrying when interveni
307
312
  events invalidate their absence/revision reads. Neither this entry nor the generic
308
313
  package automatically replaces Lody runtime storage.
309
314
 
315
+ `commitHistoryBatch(batchId, commands, {recovery: 'local'})` explicitly keeps
316
+ pending command bodies in the authoritative `lody_history_local_batch_plans_v1`
317
+ journal of that owner database. Preparation creates the compact pending receipt
318
+ and journal together. Apply commits all effects, publication references, receipt
319
+ seal and an empty journal tombstone together. A lost reply therefore preserves
320
+ either recoverable pending commands or the original committed outcome. Committed
321
+ receipts and their retained updates contain no command bodies. New batches also
322
+ omit unused baseline snapshots in both modes. No historical signed data is pruned.
323
+
324
+ The default remains `recovery: 'replicated'`, preserving recovery commands in the
325
+ receipt. Retries keep the first preparation's recovery mode. Local mode requires backing up the whole owner database to move unfinished
326
+ work; exporting Turns does not export its journal. A same-owner imported pending
327
+ local receipt is observed without executing or failing it, and an explicit retry
328
+ of that unfinished batch requires its originating database. Committed publication
329
+ still rebuilds from the verified seal and target references on other replicas.
330
+ Stop older SDKs before writing local-mode pending work; use matching browser/Node
331
+ revisions. This option changes the business adapter, not core wire framing or seals.
332
+
310
333
  Imported messages now rebuild local publication membership during read-side
311
334
  catch-up or `recoverPendingBatches()` (which returns `Promise<void>`). New direct
312
335
  messages carry original Create intent; batch members and explicitly promoted
@@ -336,6 +359,45 @@ page cannot combine membership from before a batch with content from after it.
336
359
  Already published incomplete Turns expose their applied prefix. Unsealed content
337
360
  remains provisional; the projected `sealed` flag is not a verification level.
338
361
 
362
+ Node active-branch pages privately reuse sealed bodies after matching authoritative
363
+ headers, including sequence, seal and parent edges. The per-history cache keeps at
364
+ most 64 bodies and 8 MiB of source JSON UTF-16 bytes (an input budget, not exact
365
+ heap usage). Oversized and unsealed bodies are not retained. Returned bodies are
366
+ independent copies. Page membership, cursors, availability and event fences are
367
+ still checked on every read; first hydration performs the usual JSON validation.
368
+
369
+ After Node binding/publication indexes settle at one event cursor, repeated
370
+ catch-up calls still read the journal directly. They reuse the settled checkpoint
371
+ only if that fresh read finds no event. New events or failed reads retain normal
372
+ indexing, dependency wakeup and retry behavior. A publication page that adds no
373
+ work may commit its cursor and ready marker together, with the old ready/revision
374
+ in the same CAS; pending or newly discovered work keeps the full drain path.
375
+ `observedEventCursor()` returns that private settled cursor after the same fresh
376
+ event check; it needs no second persisted-cursor read. A failed event query still
377
+ rejects, and a new history handle must establish its own checkpoint.
378
+
379
+ With a matching `derived-indexes-v1` Native host, `NodeLodyHistory.commitContentBatch`
380
+ can commit edits, application receipts and private SDK checkpoints in one durable
381
+ transaction. It only plans a fast checkpoint for content-subtree edits of at most
382
+ 16 already published message Turns, with settled binding/publication checkpoints,
383
+ matching Create/binding/member records and no waiting target dependency. Other
384
+ writes keep ordinary catch-up. Callers may provide `derivedIndexPuts` for their own
385
+ cursor-fenced projections; the SDK owns all private table names and formats.
386
+ Native independently checks the entire actual event interval before installing
387
+ any derived put. `derivedIndexesApplied` is false when that proof fails; complete
388
+ catch-up still processes all events. SDK reuse is installed only after a confirmed
389
+ matching reply, and never after a lost reply. This is an additive local API;
390
+ subprocess/browser hosts retain their existing paths and advertise no new support.
391
+
392
+ After confirmed application, Node retains one private checkpoint plan (at most
393
+ 16 IDs and 256 KiB). Each subsequent eligible write still compares every original
394
+ proof row inside Native; only the committed progress values advance. An index-only
395
+ CAS change refreshes the plan once after Native proves the attempt committed no
396
+ write. Unknown outcomes clear reuse and never trigger an automatic retry.
397
+ Fresh plans are detached once from host index results and command IDs before
398
+ reuse. Every host call receives its own copied proof; subsequent private plans
399
+ can share the retained SDK evidence without copying it again after each commit.
400
+
339
401
  Use the shared cache for a live list on either adapter:
340
402
 
341
403
  ```ts
@@ -431,6 +493,17 @@ the host fetches or repairs that boundary instead of declaring shorter history.
431
493
  Generic published-message reverse
432
494
  pages include superseded messages and cannot substitute for active-branch pages.
433
495
 
496
+ For a confirmed Native linear creation, `advanceActiveBranchDirectory(page, result,
497
+ limit)` can return a directory transition with `retainedFrom`, one new `message`,
498
+ and its committed `through` cursor. Retain `page.messages.slice(retainedFrom)`
499
+ and append `message`; use the returned state/count/older cursor. This transforms
500
+ membership only, retaining the consumer's own checkpoint-bound old bodies. It is
501
+ not a fresh read or proof that no later event exists. The owner must still observe
502
+ and process subsequent events, including state/permission corrections. Results
503
+ and page state are matched against private host proofs; copied results, forks,
504
+ partial pages and uncertain intervals return undefined and require ordinary page
505
+ reads. Older cursors retain late successor segments when the window advances.
506
+
434
507
  An append preserves older cursors while adding any intervening late successors.
435
508
  A fork that removes the cursor's ancestry rejects it as `stale`; refresh the
436
509
  loaded window and obtain a new cursor. The last reverse page can contain fewer
@@ -53,6 +53,19 @@ export declare const PUBLICATION_DONE = "lody_history_publication_done_v1";
53
53
  export declare const PUBLICATION_CURSOR: IndexKey;
54
54
  export declare const publicationHex: (v: Uint8Array) => string;
55
55
  export declare const publicationBytes: (v: string) => Uint8Array<ArrayBuffer>;
56
+ export declare function publicationFence(port: PublicationPort, cursor: bigint): Promise<IndexEntry[]>;
57
+ /** Plan only the cursor-only effect of editing already published message bodies.
58
+ * The Native owner must independently certify the complete event interval before
59
+ * installing these puts. Every inspected row is compared in that transaction. */
60
+ export declare function planContentCheckpoint(port: PublicationPort, before: bigint, through: bigint, ids: Uint8Array[], owner: Uint8Array): Promise<{
61
+ expected: IndexEntry[];
62
+ puts: (IndexKey & {
63
+ value: Uint8Array;
64
+ })[];
65
+ } | undefined>;
66
+ /** Reuse only after this exact plan was confirmed applied. All original proof
67
+ * rows remain transaction preconditions; only its own four progress rows move. */
68
+ export declare function continueContentCheckpoint(applied: NonNullable<Awaited<ReturnType<typeof planContentCheckpoint>>>, through: bigint): NonNullable<Awaited<ReturnType<typeof planContentCheckpoint>>>;
56
69
  export declare function checkPublicationRefs(refs: PublicationRef[]): PublicationRef[];
57
70
  export declare function publicationValue(refs: PublicationRef[]): JsonValue;
58
71
  export declare function catchUpPublications(port: PublicationPort): Promise<void>;
@@ -1,7 +1,7 @@
1
1
  /** Private, rebuildable publication projection. All durable work uses the same
2
2
  * database as the core; no signer or outgoing operation is needed here. */
3
3
  import { blake3 } from '@noble/hashes/blake3.js';
4
- import { encodeUtf8, decodeUtf8, encodeJson } from './json.js';
4
+ import { encodeUtf8, decodeUtf8, encodeJson, decodeJson } from './json.js';
5
5
  import { StoreError } from './store.js';
6
6
  export const PUBLICATION_OBJECTS = 'lody_history_publication_objects_v1';
7
7
  export const PUBLICATION_DONE = 'lody_history_publication_done_v1';
@@ -21,10 +21,85 @@ const same = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
21
21
  const pack = (v) => encodeUtf8(JSON.stringify(v));
22
22
  const unpack = (v) => JSON.parse(decodeUtf8(v));
23
23
  const counter = (raw) => raw === null ? 0n : BigInt(decodeUtf8(raw));
24
+ export async function publicationFence(port, cursor) {
25
+ const keys = [BINDING_CURSOR, PUBLICATION_CURSOR, REVISION, READY];
26
+ const values = await port.readIndex(keys);
27
+ if (counter(values[0]) !== cursor || counter(values[1]) !== cursor || counter(values[2]) !== counter(values[3]))
28
+ throw new StoreError('stale', 'publication is not settled');
29
+ return keys.map((key, i) => ({ ...key, value: values[i] }));
30
+ }
24
31
  const row = (table, key, value) => ({ table, key, value });
25
32
  const identityKey = (ref) => JSON.stringify(['message', ref.businessId, ref.segmentId]);
26
33
  const targetKey = (key) => blake3(encodeUtf8(key));
27
34
  const waitKey = (key, id) => { const out = new Uint8Array(48); out.set(targetKey(key)); out.set(id, 32); return out; };
35
+ /** Plan only the cursor-only effect of editing already published message bodies.
36
+ * The Native owner must independently certify the complete event interval before
37
+ * installing these puts. Every inspected row is compared in that transaction. */
38
+ export async function planContentCheckpoint(port, before, through, ids, owner) {
39
+ if (!ids.length || ids.length > 16 || through <= before)
40
+ return;
41
+ const keys = [REVISION, PUBLICATION_CURSOR, BINDING_CURSOR, READY,
42
+ ...ids.map(key => ({ table: PUBLICATION_OBJECTS, key })),
43
+ ...ids.map(key => ({ table: 'lody_history_receipt_ids_v1', key }))];
44
+ const values = await port.readIndex(keys);
45
+ const [revision, cursor, bindingCursor, ready] = values;
46
+ if (!revision || !ready || !same(revision, ready) || counter(cursor) !== before || counter(bindingCursor) !== before)
47
+ return;
48
+ const expected = keys.map((key, i) => ({ ...key, value: values[i] }));
49
+ const objects = [];
50
+ for (let i = 0; i < ids.length; i++) {
51
+ const raw = values[4 + i];
52
+ if (!raw || values[4 + ids.length + i] !== null)
53
+ return;
54
+ const object = unpack(raw);
55
+ if (!object || object.kind !== 'message' || object.owner !== publicationHex(owner))
56
+ return;
57
+ const identity = JSON.parse(object.key);
58
+ if (!Array.isArray(identity) || identity.length !== 3 || identity[0] !== 'message' || typeof identity[1] !== 'string' || typeof identity[2] !== 'string')
59
+ return;
60
+ objects.push(object);
61
+ }
62
+ const checks = objects.flatMap((object, i) => [
63
+ { table: BINDINGS, key: encodeUtf8(object.key) },
64
+ { table: TARGETS, key: targetKey(object.key) },
65
+ { table: IDS, key: encodeUtf8(object.key) },
66
+ { table: MEMBERS, key: ids[i] },
67
+ ]);
68
+ const checked = await port.readIndex(checks);
69
+ for (let i = 0; i < ids.length; i++) {
70
+ const [binding, watched, publishedId, member] = checked.slice(4 * i, 4 * i + 4);
71
+ if (!binding || watched !== null || !publishedId || !same(publishedId, ids[i]) || !member)
72
+ return;
73
+ const b = unpack(binding);
74
+ const object = objects[i];
75
+ if (b.version !== 1 || b.conflict || !Array.isArray(b.turnId) || !Array.isArray(b.owner) || !Array.isArray(b.digest) ||
76
+ !same(Uint8Array.from(b.turnId), ids[i]) || publicationHex(Uint8Array.from(b.owner)) !== object.owner || publicationHex(Uint8Array.from(b.digest)) !== object.digest)
77
+ return;
78
+ const m = decodeJson(member), identity = JSON.parse(object.key);
79
+ if (!(m instanceof Map) || m.get('version') !== '2' || m.get('businessId') !== identity[1] || m.get('segmentId') !== identity[2])
80
+ return;
81
+ }
82
+ expected.push(...checks.map((key, i) => ({ ...key, value: checked[i] })));
83
+ const next = encodeUtf8((counter(revision) + 1n).toString()), end = encodeUtf8(through.toString());
84
+ return { expected, puts: [
85
+ { ...BINDING_CURSOR, value: end }, { ...PUBLICATION_CURSOR, value: end },
86
+ { ...REVISION, value: next }, { ...READY, value: next },
87
+ ] };
88
+ }
89
+ /** Reuse only after this exact plan was confirmed applied. All original proof
90
+ * rows remain transaction preconditions; only its own four progress rows move. */
91
+ export function continueContentCheckpoint(applied, through) {
92
+ const at = (a, b) => a.table === b.table && same(a.key, b.key);
93
+ const expected = applied.expected.map(entry => ({
94
+ ...entry, value: applied.puts.find(put => at(put, entry))?.value ?? entry.value,
95
+ }));
96
+ const next = encodeUtf8((counter(applied.puts.find(put => at(put, REVISION)).value) + 1n).toString());
97
+ const end = encodeUtf8(through.toString());
98
+ return { expected, puts: [
99
+ { ...BINDING_CURSOR, value: end }, { ...PUBLICATION_CURSOR, value: end },
100
+ { ...REVISION, value: next }, { ...READY, value: next },
101
+ ] };
102
+ }
28
103
  export function checkPublicationRefs(refs) {
29
104
  if (!Array.isArray(refs) || refs.length > 64 || pack(refs).length > 256 * 1024)
30
105
  throw new StoreError('invalid', 'publication reference limit');
@@ -49,7 +124,7 @@ export function publicationValue(refs) {
49
124
  /** A revision serializes ingestion, dependency wakeup and complete-batch
50
125
  * publication. Comparing the binding checkpoint rejects stale identity reads. */
51
126
  async function snapshot(port) {
52
- const keys = [REVISION, PUBLICATION_CURSOR, BINDING_CURSOR];
127
+ const keys = [REVISION, PUBLICATION_CURSOR, BINDING_CURSOR, READY];
53
128
  const values = await port.readIndex(keys);
54
129
  return { cursor: counter(values[1]), expected: keys.map((key, i) => ({ ...key, value: values[i] })),
55
130
  revision: row(REVISION.table, REVISION.key, encodeUtf8((counter(values[0]) + 1n).toString())) };
@@ -63,7 +138,7 @@ async function ingest(port) {
63
138
  const at = await snapshot(port), bound = counter(at.expected[2].value);
64
139
  const events = (await port.events(at.cursor, PAGE)).filter(record => record.cursor <= bound);
65
140
  if (!events.length)
66
- return false;
141
+ return 'idle';
67
142
  const touched = new Map();
68
143
  for (const { event } of events)
69
144
  if (event.kind === 'changed' && event.update) {
@@ -91,9 +166,15 @@ async function ingest(port) {
91
166
  for (let i = 0; i < messages.length; i++)
92
167
  if (watched[i] !== null)
93
168
  changes.push(row(WAKE, messages[i].hash, encodeUtf8(messages[i].object.key)));
94
- changes.push(row(PUBLICATION_CURSOR.table, PUBLICATION_CURSOR.key, encodeUtf8(events.at(-1).cursor.toString())));
95
- await commit(port, at, changes);
96
- return true;
169
+ const through = events.at(-1).cursor;
170
+ const priorRevision = at.expected[0].value, priorReady = at.expected[3].value;
171
+ const settled = changes.length === 0 && through === bound && priorRevision !== null &&
172
+ priorReady !== null && same(priorRevision, priorReady);
173
+ changes.push(row(PUBLICATION_CURSOR.table, PUBLICATION_CURSOR.key, encodeUtf8(through.toString())));
174
+ if (settled)
175
+ changes.push(row(READY.table, READY.key, at.revision.value));
176
+ const committed = await commit(port, at, changes);
177
+ return committed && settled ? 'settled' : 'more';
97
178
  }
98
179
  async function wake(port) {
99
180
  const at = await snapshot(port), [target] = await port.scanIndex(WAKE, EMPTY, 1);
@@ -210,7 +291,13 @@ export async function catchUpPublications(port) {
210
291
  if (ready && revision && same(ready, revision) && counter(cursor) === counter(bindingCursor))
211
292
  return;
212
293
  for (;;) {
213
- while (await ingest(port)) { /* durable bounded event pages */ }
294
+ for (;;) {
295
+ const ingested = await ingest(port);
296
+ if (ingested === 'settled')
297
+ return;
298
+ if (ingested === 'idle')
299
+ break;
300
+ }
214
301
  while (await wake(port)) { /* bounded fanout, consumed dependencies are deleted */ }
215
302
  let worked = false;
216
303
  while (await apply(port))
@@ -50,6 +50,11 @@ export type HistoryBatchResult = {
50
50
  created: boolean;
51
51
  revision: bigint;
52
52
  };
53
+ export type HistoryBatchOptions = {
54
+ /** Keep pending commands in this owner database instead of replicated Turns.
55
+ * Move unfinished work with a whole-database backup, not a Turn export. */
56
+ recovery?: 'replicated' | 'local';
57
+ };
53
58
  export type HistoryProjectedMessage = {
54
59
  businessId: string;
55
60
  segmentId: string;
@@ -143,6 +148,12 @@ export type ActiveBranchPageCursor = {
143
148
  turnId: Uint8Array;
144
149
  }[];
145
150
  };
151
+ /** Directory transition only. Retained bodies remain the caller's snapshots. */
152
+ export type ActiveBranchPageAdvance = Omit<ActiveBranchPageRead, 'messages'> & {
153
+ retainedFrom: number;
154
+ message: HistoryProjectedMessage;
155
+ through: bigint;
156
+ };
146
157
  export type RestoreActiveBranchInput = {
147
158
  viewId: string;
148
159
  expectedRevision: bigint;
@@ -223,7 +234,7 @@ export declare class LodyHistory {
223
234
  };
224
235
  location: string | undefined;
225
236
  }[]>;
226
- commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[]): Promise<HistoryBatchResult>;
237
+ commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[], options?: HistoryBatchOptions): Promise<HistoryBatchResult>;
227
238
  recoverPendingBatches(): Promise<void>;
228
239
  /** A consumer-owned cache. Call refresh on change hints (or host polling). */
229
240
  createMessageView(limit?: number): HistoryMessageView;
@@ -270,22 +281,66 @@ export type NodeHistoryRead = {
270
281
  turnId: Uint8Array;
271
282
  prefix: NodeHistoryTurn | null;
272
283
  };
284
+ type NodeHistoryPath = ({
285
+ key: string;
286
+ } | {
287
+ index: bigint;
288
+ })[];
273
289
  export type NodeHistoryOp = {
274
290
  kind: 'appendText';
275
- path: ({
276
- key: string;
277
- } | {
278
- index: bigint;
279
- })[];
291
+ path: NodeHistoryPath;
280
292
  text: string;
281
293
  } | {
282
294
  kind: 'set';
283
- path: ({
284
- key: string;
285
- } | {
286
- index: bigint;
287
- })[];
295
+ path: NodeHistoryPath;
288
296
  contentJson: string;
297
+ } | {
298
+ kind: 'remove';
299
+ path: NodeHistoryPath;
300
+ } | {
301
+ kind: 'spliceText';
302
+ path: NodeHistoryPath;
303
+ index: bigint;
304
+ delete: bigint;
305
+ text: string;
306
+ } | {
307
+ kind: 'spliceArray';
308
+ path: NodeHistoryPath;
309
+ index: bigint;
310
+ delete: bigint;
311
+ valuesJson: string;
312
+ };
313
+ export type NodeHistoryIndexPut = NodeIndexKey & {
314
+ value: Uint8Array;
315
+ onceKey?: Uint8Array;
316
+ emitEvent?: boolean;
317
+ };
318
+ export type NodeHistoryBatchOptions = {
319
+ indexPuts?: NodeHistoryIndexPut[];
320
+ expectedEventCursor?: bigint;
321
+ expectedIndexes?: NodeIndexEntry[];
322
+ receiptChecks?: NodeIndexEntry[];
323
+ commitMetadata?: {
324
+ scope: Uint8Array;
325
+ value: Uint8Array;
326
+ };
327
+ derivedIndexes?: {
328
+ through: bigint;
329
+ indexPuts: (NodeIndexKey & {
330
+ value: Uint8Array;
331
+ })[];
332
+ };
333
+ };
334
+ export type NodeHistoryBatchResult = {
335
+ updates: {
336
+ turnId: Uint8Array;
337
+ seq: bigint;
338
+ }[];
339
+ before?: bigint;
340
+ through?: bigint;
341
+ metadataAttached?: boolean;
342
+ derivedIndexesApplied?: boolean;
343
+ replayed?: boolean[];
289
344
  };
290
345
  export interface LodyNodeHost {
291
346
  eventsAfter(after: bigint, limit: bigint): Promise<{
@@ -367,16 +422,7 @@ export interface LodyNodeHost {
367
422
  kind: 'sealOnce';
368
423
  key: Uint8Array;
369
424
  expectedNextSeq: bigint;
370
- })[], options?: {
371
- indexPuts?: {
372
- table: string;
373
- key: Uint8Array;
374
- value: Uint8Array;
375
- onceKey?: Uint8Array;
376
- emitEvent?: boolean;
377
- }[];
378
- expectedEventCursor?: bigint;
379
- }): Promise<unknown>;
425
+ })[], options?: NodeHistoryBatchOptions): Promise<NodeHistoryBatchResult>;
380
426
  scanIndex(table: string, start: Uint8Array, limit: bigint): Promise<{
381
427
  key: Uint8Array;
382
428
  value: Uint8Array;
@@ -407,6 +453,16 @@ export declare class NodeLodyHistory {
407
453
  * a stale page together with every derived change. */
408
454
  indexPage(limit?: number): Promise<boolean>;
409
455
  catchUpIndex(): Promise<void>;
456
+ /** Requires a host supporting derived-indexes-v1. The SDK, never the consumer,
457
+ * owns private checkpoint formats. General/unfinished/watched writes keep the
458
+ * ordinary catch-up path. Application derived puts share the same proof. */
459
+ publicationFence(cursor: bigint): Promise<NodeIndexEntry[]>;
460
+ commitContentBatch(writes: Parameters<LodyNodeHost['writeBatch']>[0], options?: Omit<NodeHistoryBatchOptions, 'derivedIndexes'> & {
461
+ derivedIndexPuts?: (NodeIndexKey & {
462
+ value: Uint8Array;
463
+ })[];
464
+ unclaimedIdentities?: HistoryIdentity[];
465
+ }): Promise<NodeHistoryBatchResult>;
410
466
  invalidMessages(limit?: number): Promise<HistoryDiagnostic[]>;
411
467
  lookup(input: HistoryIdentity): Promise<NodeHistoryRead | undefined>;
412
468
  acceptJson(input: {
@@ -439,6 +495,7 @@ export declare class NodeLodyHistory {
439
495
  latest?: boolean;
440
496
  limit?: number;
441
497
  }): Promise<ActiveBranchPageRead>;
498
+ advanceActiveBranchDirectory(page: ActiveBranchPageRead, result: BranchMutationResult, limit?: number): ActiveBranchPageAdvance | undefined;
442
499
  respondPermission(input: {
443
500
  requestId: string;
444
501
  assistantBusinessId: string;
@@ -448,7 +505,7 @@ export declare class NodeLodyHistory {
448
505
  turnId: Uint8Array;
449
506
  created: boolean;
450
507
  }>;
451
- commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[]): Promise<HistoryBatchResult>;
508
+ commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[], options?: HistoryBatchOptions): Promise<HistoryBatchResult>;
452
509
  recoverPendingBatches(): Promise<void>;
453
510
  /** A consumer-owned cache. Call refresh on change hints (or host polling). */
454
511
  createMessageView(limit?: number): HistoryMessageView;
@@ -3,7 +3,7 @@ import { blake3 } from '@noble/hashes/blake3.js';
3
3
  import { decodeBatch, decodeFrame, encodeFrame } from './codec.js';
4
4
  import { decodeUtf8, encodeUtf8, encodeJson, decodeJson, MAX_JSON_DEPTH, U64_MAX } from './json.js';
5
5
  import { StoreError } from './store.js';
6
- import { catchUpPublications, PUBLICATION_OBJECTS, PUBLICATION_DONE, PUBLICATION_CURSOR, checkPublicationRefs, publicationValue } from './history-publication.js';
6
+ import { catchUpPublications, planContentCheckpoint, continueContentCheckpoint, publicationFence, PUBLICATION_OBJECTS, PUBLICATION_DONE, PUBLICATION_CURSOR, checkPublicationRefs, publicationValue } from './history-publication.js';
7
7
  const equal = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
8
8
  const invalid = (message) => new StoreError('invalid', message);
9
9
  function text(v) { if (typeof v !== 'string' || !v.length || encodeUtf8(v).length > 1024)
@@ -481,8 +481,8 @@ export class LodyHistory {
481
481
  // readTurn has completed its transaction before any host Promise is invoked.
482
482
  return Promise.all(identities.map(async (value) => ({ identity: value, location: await resolve(value) })));
483
483
  }
484
- async commitHistoryBatch(batchId, commands) {
485
- return commitBatch(this, batchId, commands);
484
+ async commitHistoryBatch(batchId, commands, options) {
485
+ return commitBatch(this, batchId, commands, options);
486
486
  }
487
487
  recoverPendingBatches() { return recoverBatches(this); }
488
488
  /** A consumer-owned cache. Call refresh on change hints (or host polling). */
@@ -662,6 +662,66 @@ export class NodeLodyHistory {
662
662
  return !committed || events.length === limit;
663
663
  }
664
664
  catchUpIndex() { return catchUpHistory(this); }
665
+ /** Requires a host supporting derived-indexes-v1. The SDK, never the consumer,
666
+ * owns private checkpoint formats. General/unfinished/watched writes keep the
667
+ * ordinary catch-up path. Application derived puts share the same proof. */
668
+ publicationFence(cursor) { return publicationFence(publicationPort(this), cursor); }
669
+ async commitContentBatch(writes, options = {}) {
670
+ // Planning awaits index snapshots. Own mutable operations/bytes now so the
671
+ // transaction cannot receive a different envelope edit than the one checked.
672
+ ({ writes, options } = structuredClone({ writes, options }));
673
+ const { derivedIndexPuts = [], unclaimedIdentities = [], ...ordinary } = options;
674
+ ordinary.expectedIndexes = [...(ordinary.expectedIndexes ?? []), ...unclaimedIdentities.map(identity => ({ table: NODE_BINDINGS, key: keyOf(identity), value: null }))];
675
+ const before = options.expectedEventCursor;
676
+ const eligible = before !== undefined && writes.length > 0 && writes.every(write => write.kind === 'edit' && write.ops.length > 0 && write.ops.every(op => { const root = op.path[0]; return root !== undefined && 'key' in root && root.key === 'content'; })) &&
677
+ (options.indexPuts ?? []).every(put => !put.emitEvent && put.onceKey === undefined);
678
+ const ids = new Map();
679
+ let through = before ?? 0n;
680
+ if (eligible)
681
+ for (const write of writes)
682
+ if (write.kind === 'edit') {
683
+ ids.set(hexBytes(write.turnId), write.turnId);
684
+ through += BigInt(write.ops.length);
685
+ }
686
+ const idKey = [...ids.keys()].sort().join(':');
687
+ for (let attempt = 0;; attempt++) {
688
+ const cached = attempt === 0 ? contentCheckpoints.get(this) : undefined;
689
+ const reuse = eligible && cached?.through === before && cached.ids === idKey;
690
+ const plan = eligible && through <= U64_MAX
691
+ ? reuse ? continueContentCheckpoint(cached.plan, through)
692
+ // Detach new proofs from readIndex results/arguments and command IDs
693
+ // once. Continuations share only this SDK-private owned evidence.
694
+ : structuredClone(await planContentCheckpoint(publicationPort(this), before, through, [...ids.values()], this.owner))
695
+ : undefined;
696
+ // The host only receives detached preconditions, never the retained proof.
697
+ const options = structuredClone({
698
+ ...ordinary,
699
+ ...(plan ? {
700
+ expectedIndexes: [...(ordinary.expectedIndexes ?? []), ...plan.expected],
701
+ derivedIndexes: { through, indexPuts: [...plan.puts, ...derivedIndexPuts] },
702
+ } : {}),
703
+ });
704
+ try {
705
+ const result = await this.stream.writeBatch(writes, options);
706
+ contentCheckpoints.delete(this);
707
+ if (plan && result.derivedIndexesApplied === true && result.before === before && result.through === through) {
708
+ settledNodeHistory.set(this, through);
709
+ const disjoint = [...(ordinary.indexPuts ?? []), ...derivedIndexPuts].every(put => !plan.expected.some(row => row.table === put.table && equal(row.key, put.key)));
710
+ const bytes = [...plan.expected, ...plan.puts].reduce((size, row) => size + row.key.length + (row.value?.length ?? 0), 0);
711
+ if (disjoint && bytes <= 256 * 1024)
712
+ contentCheckpoints.set(this, { through, ids: idKey, plan });
713
+ }
714
+ return result;
715
+ }
716
+ catch (error) {
717
+ contentCheckpoints.delete(this);
718
+ // Native stale proves no write committed. Refresh an index-only change
719
+ // once; unknown/transport/storage outcomes are never retried here.
720
+ if (!reuse || attempt !== 0 || errorCode(error) !== 'stale')
721
+ throw error;
722
+ }
723
+ }
724
+ }
665
725
  async invalidMessages(limit = 100) {
666
726
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
667
727
  throw invalid('diagnostic limit');
@@ -729,8 +789,13 @@ export class NodeLodyHistory {
729
789
  forkAndActivate(input) { return branchFork(this, input); }
730
790
  restoreActiveBranch(input) { return branchRestore(this, input); }
731
791
  readActiveBranch(viewId) { return readActiveBranch(this, viewId); }
732
- readActiveBranchPage(viewId, input = {}) {
733
- return readActiveBranchPage(this, viewId, input);
792
+ async readActiveBranchPage(viewId, input = {}) {
793
+ const page = await readActiveBranchPage(this, viewId, input);
794
+ rememberBranchDirectory(this, page);
795
+ return page;
796
+ }
797
+ advanceActiveBranchDirectory(page, result, limit = 40) {
798
+ return advanceBranchDirectory(this, page, result, limit);
734
799
  }
735
800
  async respondPermission(input) {
736
801
  const result = await this.accept({ businessId: text(input.requestId), segmentId: 'response', kind: 'permission_response', parents: input.parents,
@@ -750,8 +815,8 @@ export class NodeLodyHistory {
750
815
  }
751
816
  return result;
752
817
  }
753
- async commitHistoryBatch(batchId, commands) {
754
- return commitBatch(this, batchId, commands);
818
+ async commitHistoryBatch(batchId, commands, options) {
819
+ return commitBatch(this, batchId, commands, options);
755
820
  }
756
821
  recoverPendingBatches() { return recoverBatches(this); }
757
822
  /** A consumer-owned cache. Call refresh on change hints (or host polling). */
@@ -769,6 +834,11 @@ export class NodeLodyHistory {
769
834
  }
770
835
  async observedEventCursor() {
771
836
  await this.catchUpIndex();
837
+ // catchUpIndex has freshly checked for events beyond this private settled
838
+ // checkpoint. A second read of its persisted cursor adds no new evidence.
839
+ const settled = settledNodeHistory.get(this);
840
+ if (settled !== undefined)
841
+ return settled;
772
842
  const [raw] = await this.stream.readIndex([NODE_CURSOR]);
773
843
  return processedCursor(raw);
774
844
  }
@@ -805,6 +875,51 @@ export class NodeLodyHistory {
805
875
  }
806
876
  }
807
877
  }
878
+ const sealedPageBodies = new WeakMap();
879
+ const SEALED_PAGE_ROWS = 64, SEALED_PAGE_BYTES = 8 * 1024 * 1024;
880
+ function sameBranchHeader(left, right) {
881
+ return left.nextSeq === right.nextSeq && left.sealed !== null && right.sealed !== null &&
882
+ equal(left.sealed, right.sealed) && left.parents.length === right.parents.length &&
883
+ left.parents.every((parent, i) => equal(parent.id, right.parents[i].id) && equal(parent.hash, right.parents[i].hash));
884
+ }
885
+ /** Sealed content is immutable, but membership and availability are always reread. */
886
+ async function readBranchPageTurn(host, turnId, knownHeader, retained) {
887
+ if (host instanceof LodyHistory)
888
+ return readBranchTurn(host, turnId);
889
+ const header = knownHeader ?? await branchHeader(host, turnId);
890
+ if (!header)
891
+ return;
892
+ let cache = sealedPageBodies.get(host);
893
+ const key = hexBytes(turnId), cached = retained ?? cache?.rows.get(key);
894
+ if (cached && sameBranchHeader(cached, header)) {
895
+ if (cache.rows.get(key) === cached) {
896
+ cache.rows.delete(key);
897
+ cache.rows.set(key, cached);
898
+ }
899
+ return structuredClone(cached);
900
+ }
901
+ const turn = await readBranchTurn(host, turnId);
902
+ if (!turn || !sameBranchHeader(turn, header) || turn.sourceBytes === undefined || turn.sourceBytes > SEALED_PAGE_BYTES)
903
+ return turn;
904
+ cache = sealedPageBodies.get(host);
905
+ if (!cache) {
906
+ cache = { bytes: 0, rows: new Map() };
907
+ sealedPageBodies.set(host, cache);
908
+ }
909
+ const previous = cache.rows.get(key);
910
+ if (previous) {
911
+ cache.rows.delete(key);
912
+ cache.bytes -= previous.sourceBytes;
913
+ }
914
+ cache.rows.set(key, structuredClone(turn));
915
+ cache.bytes += turn.sourceBytes;
916
+ while (cache.rows.size > SEALED_PAGE_ROWS || cache.bytes > SEALED_PAGE_BYTES) {
917
+ const oldest = cache.rows.keys().next().value;
918
+ cache.bytes -= cache.rows.get(oldest).sourceBytes;
919
+ cache.rows.delete(oldest);
920
+ }
921
+ return turn;
922
+ }
808
923
  async function readBranchIndex(host, viewId) {
809
924
  const key = branchKey(viewId);
810
925
  const raw = host instanceof LodyHistory
@@ -885,6 +1000,7 @@ async function readBranchTurn(host, turnId) {
885
1000
  content: body instanceof Map ? body.get('content') : undefined,
886
1001
  nextSeq: result.turn.nextSeq,
887
1002
  sealed: result.turn.sealed?.slice() ?? null,
1003
+ sourceBytes: result.turn.contentJson.length * 2,
888
1004
  };
889
1005
  }
890
1006
  function ownInputIdentity(input) {
@@ -931,9 +1047,10 @@ async function acceptInputToView(host, input) {
931
1047
  if (prior)
932
1048
  return prior;
933
1049
  const baseTurn = input.expectedHead ? await branchTurnByIdentity(host, input.expectedHead) ?? null : null;
934
- return branchMutation(host, input, baseTurn, [], digest);
1050
+ return branchMutation(host, input, baseTurn, [], digest, true);
935
1051
  }
936
- async function branchMutation(host, input, baseTurn, supersedes, inputDigest) {
1052
+ async function branchMutation(host, input, baseTurn, supersedes, inputDigest, linearAppend = false) {
1053
+ input = ownBranchInput(input);
937
1054
  if (input.input.kind !== 'message')
938
1055
  throw invalid('active branch only accepts message Turns');
939
1056
  if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
@@ -996,8 +1113,9 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest) {
996
1113
  if (!existingBranch || existingBranch.operationId !== operationId || existingBranch.digest !== metadata.digest)
997
1114
  throw new StoreError('conflict', 'branch message identity already exists');
998
1115
  }
1116
+ let committed;
999
1117
  try {
1000
- await writeIndexed(host, [{ kind: 'createOnce', key: createKey, parents: input.input.parents, content: envelope(input.input, true, metadata) }], [
1118
+ committed = await writeIndexed(host, [{ kind: 'createOnce', key: createKey, parents: input.input.parents, content: envelope(input.input, true, metadata) }], [
1001
1119
  { table: BRANCH_TABLE, key: branchKey(viewId), value: branchValue, emitEvent: true },
1002
1120
  { table: BRANCH_OPERATIONS, key: branchOperationKey(viewId, operationId), value: operationValue },
1003
1121
  ], cursor);
@@ -1012,13 +1130,27 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest) {
1012
1130
  if (!turnId)
1013
1131
  throw new StoreError('corrupt', 'active branch replacement missing');
1014
1132
  await maybePublishAccept(host, input.input, { publish: true }, turnId);
1015
- return { operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId };
1133
+ const result = { operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId };
1134
+ if (linearAppend && !supersedes.length && host instanceof NodeLodyHistory && input.input.segmentId === 'primary' &&
1135
+ committed?.updates.length === 1 && committed.before !== undefined && committed.through !== undefined && committed.updates[0].seq === 0n &&
1136
+ equal(committed.updates[0].turnId, turnId) && committed.through - committed.before === 2n) {
1137
+ branchTransitions.set(result, {
1138
+ ownerToken: branchHandleToken(host), beforeRevision: input.expectedRevision, beforeHead: structuredClone(expectedHead),
1139
+ state: { viewId, revision: metadata.revision, head: structuredClone(metadata.head), operationId, logicalCount },
1140
+ message: { businessId: input.input.businessId, segmentId: 'primary', turnId: turnId.slice(),
1141
+ content: structuredClone(input.input.content), nextSeq: 1n, sealed: false,
1142
+ parents: structuredClone(input.input.parents), sealedHash: null },
1143
+ through: committed.through,
1144
+ });
1145
+ }
1146
+ return result;
1016
1147
  }
1017
1148
  throw new StoreError('stale', 'active branch retry budget exhausted');
1018
1149
  }
1019
1150
  async function branchAccept(host, input) {
1151
+ input = ownBranchInput(input);
1020
1152
  const baseTurn = input.expectedHead ? await branchTurnByIdentity(host, input.expectedHead) ?? null : null;
1021
- return branchMutation(host, input, baseTurn, []);
1153
+ return branchMutation(host, input, baseTurn, [], undefined, true);
1022
1154
  }
1023
1155
  async function branchFork(host, input) {
1024
1156
  if (input.input.kind !== 'message')
@@ -1149,14 +1281,17 @@ async function readActiveBranchSnapshot(host, viewId) {
1149
1281
  await visit(headId);
1150
1282
  return { state, messages: output, complete };
1151
1283
  }
1152
- async function readBranchPageMessages(host, segments) {
1284
+ async function readBranchPageMessages(host, segments, headers) {
1153
1285
  const messages = [];
1154
1286
  let complete = true;
1287
+ // Retain this page's hits before misses can evict them. A page larger than the
1288
+ // byte budget must not repeatedly evict every newer body before reaching it.
1289
+ const retained = host instanceof NodeLodyHistory ? new Map(sealedPageBodies.get(host)?.rows) : undefined;
1155
1290
  // Pages can contain up to 500 rows. Keep body requests below the Node
1156
1291
  // client's bounded queue instead of launching one request per segment.
1157
1292
  for (let offset = 0; offset < segments.length; offset += 8) {
1158
1293
  const batch = segments.slice(offset, offset + 8);
1159
- const turns = await Promise.all(batch.map(segment => readBranchTurn(host, segment.turnId)));
1294
+ const turns = await Promise.all(batch.map(segment => readBranchPageTurn(host, segment.turnId, headers?.get(hexBytes(segment.turnId)), retained?.get(hexBytes(segment.turnId)))));
1160
1295
  for (let i = 0; i < batch.length; i++) {
1161
1296
  const turn = turns[i], segment = batch[i];
1162
1297
  if (!turn || turn.identity?.kind !== 'message' || turn.content === undefined) {
@@ -1194,7 +1329,10 @@ async function branchHeader(host, turnId) {
1194
1329
  const result = await host.stream.readTurnHeader(turnId);
1195
1330
  if (result.kind !== 'found')
1196
1331
  return;
1197
- return { parents: result.turn.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })) };
1332
+ return {
1333
+ parents: result.turn.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })),
1334
+ nextSeq: result.turn.nextSeq, sealed: result.turn.sealed?.slice() ?? null,
1335
+ };
1198
1336
  }
1199
1337
  async function branchIdentityAt(host, turnId) {
1200
1338
  try {
@@ -1399,6 +1537,80 @@ async function readActiveBranchPage(host, viewId, input) {
1399
1537
  complete,
1400
1538
  };
1401
1539
  }
1540
+ // Page/result data must not retain a closed host and its body cache.
1541
+ const branchHandleTokens = new WeakMap();
1542
+ function branchHandleToken(host) {
1543
+ let token = branchHandleTokens.get(host);
1544
+ if (!token) {
1545
+ token = {};
1546
+ branchHandleTokens.set(host, token);
1547
+ }
1548
+ return token;
1549
+ }
1550
+ const branchDirectories = new WeakMap();
1551
+ const branchTransitions = new WeakMap();
1552
+ function directoryMember(row) {
1553
+ return { businessId: row.businessId, segmentId: row.segmentId, turnId: row.turnId.slice() };
1554
+ }
1555
+ function rememberBranchDirectory(host, page) {
1556
+ branchDirectories.set(page.state, {
1557
+ ownerToken: branchHandleToken(host), state: structuredClone(page.state), totalCount: page.totalCount, startPosition: page.startPosition,
1558
+ complete: page.complete, members: page.messages.map(directoryMember), cursor: structuredClone(page.cursor),
1559
+ });
1560
+ }
1561
+ /** Apply only directory membership certified by this host. No old body is read,
1562
+ * returned or certified; consumers retain their own checkpoint-bound snapshots. */
1563
+ function advanceBranchDirectory(host, page, result, limit) {
1564
+ const proof = branchDirectories.get(page.state), change = branchTransitions.get(result);
1565
+ if (!proof || !change || proof.ownerToken !== branchHandleToken(host) || change.ownerToken !== branchHandleToken(host) || !proof.complete || !page.complete ||
1566
+ !Number.isSafeInteger(limit) || limit < 1 || limit > 500 ||
1567
+ page.totalCount !== proof.totalCount || page.startPosition !== proof.startPosition ||
1568
+ page.state.viewId !== proof.state.viewId || page.state.revision !== proof.state.revision ||
1569
+ page.state.logicalCount !== proof.state.logicalCount || page.state.operationId !== proof.state.operationId || !!page.state.conflict !== !!proof.state.conflict ||
1570
+ !branchStateEqual(page.state.head, proof.state.head) ||
1571
+ change.state.viewId !== proof.state.viewId || change.beforeRevision !== proof.state.revision ||
1572
+ !branchStateEqual(change.beforeHead, proof.state.head) ||
1573
+ change.state.logicalCount !== BigInt(proof.totalCount) + 1n ||
1574
+ page.messages.length !== proof.members.length ||
1575
+ page.messages.some((row, index) => {
1576
+ const expected = proof.members[index];
1577
+ return row.businessId !== expected.businessId || row.segmentId !== expected.segmentId || !equal(row.turnId, expected.turnId);
1578
+ }))
1579
+ return;
1580
+ const businessIds = [...new Set(proof.members.map(row => row.businessId))];
1581
+ if (proof.startPosition + businessIds.length !== proof.totalCount || businessIds.includes(change.message.businessId))
1582
+ return;
1583
+ const totalCount = proof.totalCount + 1;
1584
+ if (!Number.isSafeInteger(totalCount))
1585
+ return;
1586
+ const startPosition = Math.max(0, totalCount - limit), dropped = startPosition - proof.startPosition;
1587
+ if (dropped < 0 || dropped > businessIds.length)
1588
+ return;
1589
+ const retainedIds = new Set(businessIds.slice(dropped));
1590
+ const retainedFrom = dropped === businessIds.length ? proof.members.length :
1591
+ proof.members.findIndex(row => row.businessId === businessIds[dropped]);
1592
+ let cursor = null;
1593
+ if (startPosition > 0) {
1594
+ const boundary = dropped > 0
1595
+ ? proof.members.find(row => row.businessId === businessIds[dropped - 1] && row.segmentId === 'primary')
1596
+ : proof.cursor;
1597
+ if (!boundary)
1598
+ return;
1599
+ const pending = [...proof.members, ...(proof.cursor?.pendingSegments ?? [])]
1600
+ .filter(row => !retainedIds.has(row.businessId) && compareBytes(row.turnId, boundary.turnId) > 0)
1601
+ .sort((a, b) => compareBytes(b.turnId, a.turnId));
1602
+ const unique = new Map(pending.map(row => [hexBytes(row.turnId), directoryMember(row)]));
1603
+ cursor = { viewId: change.state.viewId, revision: change.state.revision,
1604
+ position: startPosition - 1, turnId: boundary.turnId.slice(), headTurnId: change.message.turnId.slice(),
1605
+ pendingSegments: [...unique.values()] };
1606
+ }
1607
+ const state = structuredClone(change.state);
1608
+ branchDirectories.set(state, { ownerToken: branchHandleToken(host), state: structuredClone(state), totalCount, startPosition,
1609
+ complete: true, members: [...proof.members.slice(retainedFrom).map(directoryMember), directoryMember(change.message)],
1610
+ cursor: structuredClone(cursor) });
1611
+ return { state, totalCount, startPosition, complete: true, hasMoreOlder: startPosition > 0, cursor,
1612
+ retainedFrom, message: structuredClone(change.message), through: change.through };
1613
+ }
1402
1614
  async function readLinearActiveBranchPage(host, state, input, limit) {
1403
1615
  const totalBigInt = state.logicalCount ?? 0n;
1404
1616
  if (totalBigInt > BigInt(Number.MAX_SAFE_INTEGER))
@@ -1478,6 +1690,7 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
1478
1690
  collected = [...newerSuccessors, ...collected];
1479
1691
  }
1480
1692
  const selected = new Map();
1693
+ const headers = new Map();
1481
1694
  let olderCursor = null;
1482
1695
  let complete = true;
1483
1696
  const seen = new Set();
@@ -1504,6 +1717,7 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
1504
1717
  complete = false;
1505
1718
  break;
1506
1719
  }
1720
+ headers.set(turnKey, header);
1507
1721
  const expectedParent = metadata.baseTurn ? unhexBytes(metadata.baseTurn, 16) : undefined;
1508
1722
  if (header.parents.length !== (expectedParent ? 1 : 0) || (expectedParent && !equal(header.parents[0].id, expectedParent)))
1509
1723
  return undefined;
@@ -1543,7 +1757,7 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
1543
1757
  segmentGroups.set(segment.businessId, group);
1544
1758
  }
1545
1759
  const orderedSegments = [...selected].sort((a, b) => a[1] - b[1]).flatMap(([businessId]) => segmentGroups.get(businessId) ?? []);
1546
- const page = await readBranchPageMessages(host, orderedSegments);
1760
+ const page = await readBranchPageMessages(host, orderedSegments, headers);
1547
1761
  const messages = page.messages;
1548
1762
  complete &&= page.complete;
1549
1763
  const actualStart = selected.size ? Math.min(...selected.values()) : startPosition;
@@ -1659,18 +1873,26 @@ function publicationPort(host) {
1659
1873
  };
1660
1874
  }
1661
1875
  const historyCatchups = new WeakMap();
1876
+ const settledNodeHistory = new WeakMap();
1877
+ const contentCheckpoints = new WeakMap();
1662
1878
  function catchUpHistory(host) {
1663
1879
  const pending = historyCatchups.get(host);
1664
1880
  if (pending)
1665
1881
  return pending;
1666
1882
  const task = (async () => {
1883
+ const settled = host instanceof NodeLodyHistory ? settledNodeHistory.get(host) : undefined;
1884
+ if (settled !== undefined && !(await localEvents(host, settled, 1)).length)
1885
+ return;
1667
1886
  for (;;) {
1668
1887
  while (await host.indexPage()) { /* binding rows and local cursor commit together */ }
1669
1888
  await catchUpPublications(publicationPort(host));
1670
1889
  const [rawBinding, rawPublication] = await indexValues(host, [NODE_CURSOR, PUBLICATION_CURSOR]);
1671
1890
  const through = processedCursor(rawBinding);
1672
- if (through === processedCursor(rawPublication) && !(await localEvents(host, through, 1)).length)
1891
+ if (through === processedCursor(rawPublication) && !(await localEvents(host, through, 1)).length) {
1892
+ if (host instanceof NodeLodyHistory)
1893
+ settledNodeHistory.set(host, through);
1673
1894
  return;
1895
+ }
1674
1896
  }
1675
1897
  })();
1676
1898
  historyCatchups.set(host, task);
@@ -1860,9 +2082,6 @@ async function readFound(host, id) {
1860
2082
  return;
1861
2083
  return { turnId: result.turn.turnId.slice(), nextSeq: result.turn.nextSeq, sealed: !!result.turn.sealed, inner: envelope.get('content') };
1862
2084
  }
1863
- function encodeProjected(row) {
1864
- return new Map([['businessId', row.businessId], ['segmentId', row.segmentId], ['turnId', hexBytes(row.turnId)], ['nextSeq', { kind: 'u64', value: row.nextSeq }], ['sealed', row.sealed], ['content', row.content], ['parents', row.parents.map(parentValue)], ['sealedHash', row.sealedHash ? hexBytes(row.sealedHash) : null]]);
1865
- }
1866
2085
  // Membership is durable; content and revision belong to the Turn. Legacy v1
1867
2086
  // rows containing full snapshots remain readable, without a migration scan.
1868
2087
  function projectedValue(row) {
@@ -1897,7 +2116,7 @@ async function writeIndexed(host, writes, puts, expectedEventCursor) {
1897
2116
  }), puts, expectedEventCursor);
1898
2117
  return;
1899
2118
  }
1900
- await host.stream.writeBatch(writes.map((w) => {
2119
+ return host.stream.writeBatch(writes.map((w) => {
1901
2120
  if (w.kind === 'createOnce')
1902
2121
  return { kind: 'createOnce', key: w.key, parents: w.parents, contentJson: decodeUtf8(encodeJson(w.content)) };
1903
2122
  if (w.kind === 'seal')
@@ -2100,26 +2319,6 @@ async function stableRead(host, read) {
2100
2319
  }
2101
2320
  throw new StoreError('stale', 'history read retry budget exhausted');
2102
2321
  }
2103
- async function captureBases(host, commands) {
2104
- const seen = new Set(), bases = [];
2105
- for (const command of commands) {
2106
- if ((command.type !== 'setContent' && command.type !== 'finish') || command.identity.kind !== 'message')
2107
- continue;
2108
- const key = messageKey(command.identity.businessId, command.identity.segmentId);
2109
- if (seen.has(key))
2110
- continue;
2111
- seen.add(key);
2112
- const published = await lookupPublished(host, command.identity);
2113
- if (published) {
2114
- bases.push(published);
2115
- continue;
2116
- }
2117
- const found = await readFound(host, command.identity);
2118
- if (found?.inner !== undefined)
2119
- bases.push({ businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed, parents: [], sealedHash: null });
2120
- }
2121
- return bases;
2122
- }
2123
2322
  async function messageEndStates(host, commands) {
2124
2323
  const seen = new Set(), rows = [];
2125
2324
  for (const command of commands) {
@@ -2149,6 +2348,14 @@ async function markFailed(host, identity, code) {
2149
2348
  if (!found || found.sealed)
2150
2349
  return;
2151
2350
  try {
2351
+ if (found.inner instanceof Map && found.inner.get('recovery') === 'local-v1') {
2352
+ await writeIndexed(host, [
2353
+ { kind: 'editPath', turnId: found.turnId, expectedNextSeq: found.nextSeq, path: [{ key: 'content' }, { key: 'status' }], value: 'failed' },
2354
+ { kind: 'editPath', turnId: found.turnId, expectedNextSeq: found.nextSeq + 1n, path: [{ key: 'content' }, { key: 'error' }], value: code },
2355
+ { kind: 'seal', turnId: found.turnId, expectedNextSeq: found.nextSeq + 2n },
2356
+ ], [{ table: LOCAL_BATCH_PLANS, key: keyOf(identity), value: new Uint8Array() }]);
2357
+ return;
2358
+ }
2152
2359
  await patchReceipt(host, identity, [{ key: 'status' }], 'failed');
2153
2360
  await patchReceipt(host, identity, [{ key: 'error' }], code);
2154
2361
  const next = await readFound(host, identity);
@@ -2287,6 +2494,9 @@ async function collectBatchWrites(host, identity, commands, applied) {
2287
2494
  refs.push({ businessId: row.businessId, segmentId: row.segmentId, digest, nextSeq: row.nextSeq.toString(), sealed: row.sealed, ...(row.onceKey ? {} : { turnId: hexBytes(row.turnId) }) });
2288
2495
  }
2289
2496
  puts.push({ table: PUBLICATION_DONE, key: receipt.turnId, value: encodeUtf8('1') });
2497
+ if (receipt.inner instanceof Map && receipt.inner.get('recovery') === 'local-v1') {
2498
+ puts.push({ table: LOCAL_BATCH_PLANS, key: keyOf(identity), value: new Uint8Array() });
2499
+ }
2290
2500
  writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq, path: [{ key: 'content' }, { key: 'applied' }], value: { kind: 'u64', value: BigInt(commands.length) } });
2291
2501
  writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq + 1n, path: [{ key: 'content' }, { key: 'published' }], value: publicationValue(refs) });
2292
2502
  writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq + 2n, path: [{ key: 'content' }, { key: 'status' }], value: 'committed' });
@@ -2314,11 +2524,32 @@ async function runBatchCommands(host, identity, commands, applied) {
2314
2524
  }
2315
2525
  throw lastStale ?? new StoreError('stale', 'batch apply retry budget exhausted');
2316
2526
  }
2317
- async function commitBatch(host, batchId, commands) {
2527
+ const LOCAL_BATCH_PLANS = 'lody_history_local_batch_plans_v1';
2528
+ async function prepareLocalBatch(host, identity, digest, commands) {
2529
+ const content = new Map([['status', 'pending'], ['digest', hexBytes(digest)], ['recovery', 'local-v1'], ['applied', { kind: 'u64', value: 0n }]]);
2530
+ const plan = encodeJson(new Map([['version', '1'], ['digest', hexBytes(digest)], ['commands', encodeCommands(commands)]]));
2531
+ for (let attempt = 0; attempt < 4; attempt++) {
2532
+ const cursor = await host.observedEventCursor();
2533
+ if (await readFound(host, identity))
2534
+ return false;
2535
+ try {
2536
+ await writeIndexed(host, [{ kind: 'createOnce', key: keyOf(identity), parents: [], content: envelope({ ...identity, parents: [], content }) }], [{ table: LOCAL_BATCH_PLANS, key: keyOf(identity), value: plan }], cursor);
2537
+ return true;
2538
+ }
2539
+ catch (error) {
2540
+ if (errorCode(error) !== 'stale')
2541
+ throw error;
2542
+ }
2543
+ }
2544
+ throw new StoreError('stale', 'batch prepare retry budget exhausted');
2545
+ }
2546
+ async function commitBatch(host, batchId, commands, options) {
2318
2547
  if (!batchId.length || encodeUtf8(batchId).length > 1024)
2319
2548
  throw invalid('batch id');
2320
2549
  if (!commands.length || commands.length > 64)
2321
2550
  throw invalid('batch size');
2551
+ if (options?.recovery !== undefined && options.recovery !== 'replicated' && options.recovery !== 'local')
2552
+ throw invalid('batch recovery mode');
2322
2553
  for (const command of commands) {
2323
2554
  if (command.type === 'accept' || command.type === 'setContent' || command.type === 'finish') {
2324
2555
  assertWritableIdentity(command.identity);
@@ -2330,10 +2561,13 @@ async function commitBatch(host, batchId, commands) {
2330
2561
  let existing = await readFound(host, identity);
2331
2562
  let created = false;
2332
2563
  if (!existing) {
2333
- const bases = await captureBases(host, commands);
2334
- const receiptContent = new Map([['status', 'pending'], ['digest', hexBytes(digest)], ['commands', encodeCommands(commands)], ['bases', bases.map(encodeProjected)], ['applied', { kind: 'u64', value: 0n }]]);
2335
- const receipt = await host.accept({ ...identity, parents: [], content: receiptContent }, { publish: false });
2336
- created = receipt.created;
2564
+ if (options?.recovery === 'local')
2565
+ created = await prepareLocalBatch(host, identity, digest, commands);
2566
+ else {
2567
+ const receiptContent = new Map([['status', 'pending'], ['digest', hexBytes(digest)], ['commands', encodeCommands(commands)], ['applied', { kind: 'u64', value: 0n }]]);
2568
+ const receipt = await host.accept({ ...identity, parents: [], content: receiptContent }, { publish: false });
2569
+ created = receipt.created;
2570
+ }
2337
2571
  existing = await readFound(host, identity);
2338
2572
  }
2339
2573
  if (!existing)
@@ -2346,6 +2580,11 @@ async function commitBatch(host, batchId, commands) {
2346
2580
  return { batchId, created: false, revision: existing.nextSeq };
2347
2581
  if (status === 'failed')
2348
2582
  throw new StoreError('invalid', 'batch previously failed');
2583
+ if (existing.inner instanceof Map && existing.inner.get('recovery') === 'local-v1') {
2584
+ const [plan] = await indexValues(host, [{ table: LOCAL_BATCH_PLANS, key: keyOf(identity) }]);
2585
+ if (plan === null)
2586
+ throw invalid('unfinished local batch belongs to its originating owner database');
2587
+ }
2349
2588
  const applied = existing.inner instanceof Map && existing.inner.get('applied') !== undefined ? Number(seqOf(existing.inner.get('applied'))) : 0;
2350
2589
  try {
2351
2590
  await runBatchCommands(host, identity, commands, applied);
@@ -2375,7 +2614,31 @@ async function recoverBatches(host) {
2375
2614
  const status = found.inner.get('status');
2376
2615
  if (status === 'failed' || status === 'committed')
2377
2616
  continue;
2378
- const digest = found.inner.get('digest'), encoded = found.inner.get('commands');
2617
+ const digest = found.inner.get('digest');
2618
+ let encoded = found.inner.get('commands');
2619
+ if (found.inner.get('recovery') === 'local-v1') {
2620
+ const [raw] = await indexValues(host, [{ table: LOCAL_BATCH_PLANS, key: keyOf(row.identity) }]);
2621
+ // Same-owner imports have no authority to execute this database's work.
2622
+ // Only a preparation transaction in this database creates a local plan.
2623
+ if (raw === null)
2624
+ continue;
2625
+ if (raw.length === 0) {
2626
+ // Another caller may have retired the plan after our pending read.
2627
+ // Only this exceptional path rereads the compact receipt; ordinary
2628
+ // recovery and sends retain their existing reads and writes.
2629
+ const current = await readFound(host, row.identity), inner = current?.inner;
2630
+ if (!current?.sealed || !equal(current.turnId, found.turnId) ||
2631
+ !(inner instanceof Map) || typeof digest !== 'string' || inner.get('digest') !== digest ||
2632
+ inner.get('recovery') !== 'local-v1' || (inner.get('status') !== 'committed' && inner.get('status') !== 'failed')) {
2633
+ throw new StoreError('corrupt', 'retired local batch has no matching terminal receipt');
2634
+ }
2635
+ continue;
2636
+ }
2637
+ const plan = asMap(decodeJson(raw), 'local batch plan');
2638
+ if (plan.get('version') !== '1' || plan.get('digest') !== digest)
2639
+ throw new StoreError('corrupt', 'local batch recovery plan mismatch');
2640
+ encoded = plan.get('commands');
2641
+ }
2379
2642
  if (typeof digest !== 'string' || encoded === undefined) {
2380
2643
  await markFailed(host, row.identity, 'invalid');
2381
2644
  continue;
package/node/client.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** Private prototype API. Pair this client with the artifact's matching owner binary. */
2
2
  export const MAX_MESSAGE_BYTES: number;
3
3
  export class RoostHostError extends Error { readonly code: string; }
4
- export type OwnerCapability = 'history-v1' | 'create-once-v1' | 'create-once-cas-v1' | 'sync-v1' | 'host-crypto-v1' | 'index-cas-v1' | 'index-events-v1' | 'index-cas-events-v1';
4
+ export type OwnerCapability = 'history-v1' | 'create-once-v1' | 'create-once-cas-v1' | 'sync-v1' | 'host-crypto-v1' | 'index-cas-v1' | 'index-events-v1' | 'index-cas-events-v1' | 'commit-metadata-v1' | 'derived-indexes-v1' | 'receipt-checks-v1' | 'commit-observation-v1';
5
5
  export type ParentRef = { id: Uint8Array; hash: Uint8Array };
6
6
  export type UpdateRef = { turnId: Uint8Array; seq: bigint };
7
7
  export type Verification = 'notRetrieved' | 'provisional' | 'selfVerified' | 'ancestorsVerified';
package/package.json CHANGED
@@ -1,12 +1,19 @@
1
1
  {
2
2
  "name": "@loro-dev/roost",
3
- "version": "0.1.3",
3
+ "version": "0.3.0",
4
4
  "description": "Browser conversation history and sync for Loro Roost",
5
5
  "license": "MIT",
6
- "publishConfig": {
7
- "access": "public"
8
- },
6
+ "publishConfig": { "access": "public" },
9
7
  "type": "module",
8
+ "packageManager": "pnpm@12.3.4",
9
+ "scripts": {
10
+ "check": "tsc --noEmit",
11
+ "build": "tsc",
12
+ "prepack": "pnpm build",
13
+ "test": "pnpm build && node --test tests/*.test.mjs",
14
+ "pack:consumer": "pnpm build && node scripts/pack-consumer.mjs",
15
+ "check:consumer": "pnpm build && node scripts/check-consumer.mjs"
16
+ },
10
17
  "devDependencies": {
11
18
  "playwright": "1.58.2",
12
19
  "typescript": "5.9.3"
@@ -42,12 +49,5 @@
42
49
  "node/client.d.mts",
43
50
  "README.md",
44
51
  "LICENSE"
45
- ],
46
- "scripts": {
47
- "check": "tsc --noEmit",
48
- "build": "tsc",
49
- "test": "pnpm build && node --test tests/*.test.mjs",
50
- "pack:consumer": "pnpm build && node scripts/pack-consumer.mjs",
51
- "check:consumer": "pnpm build && node scripts/check-consumer.mjs"
52
- }
53
- }
52
+ ]
53
+ }