@loro-dev/roost 0.2.0 → 0.3.1

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.
@@ -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)
@@ -33,11 +33,11 @@ function branchIdentity(value, label) {
33
33
  return null;
34
34
  if (!(value instanceof Map))
35
35
  throw invalid(label);
36
- return decodeIdentity(value);
36
+ return decodeIdentity(value, true);
37
37
  }
38
38
  function branchMetadataValue(value) {
39
39
  const metadata = new Map([
40
- ['version', '1'],
40
+ ['version', value.membershipBase || value.head?.kind === 'branch_state' || value.previousHead?.kind === 'branch_state' ? '2' : '1'],
41
41
  ['viewId', value.viewId],
42
42
  ['revision', { kind: 'u64', value: value.revision }],
43
43
  ['operationId', value.operationId],
@@ -49,16 +49,22 @@ function branchMetadataValue(value) {
49
49
  ]);
50
50
  if (value.logicalCount !== undefined)
51
51
  metadata.set('logicalCount', { kind: 'u64', value: value.logicalCount });
52
+ if (value.membershipBase)
53
+ metadata.set('membershipBase', identityValue(value.membershipBase));
54
+ if (value.prepared)
55
+ metadata.set('prepared', true);
52
56
  return metadata;
53
57
  }
54
58
  function parseBranchMetadata(value) {
55
59
  if (value === undefined)
56
60
  return;
57
- if (!(value instanceof Map) || value.get('version') !== '1')
61
+ if (!(value instanceof Map) || (value.get('version') !== '1' && value.get('version') !== '2'))
58
62
  throw invalid('history branch metadata');
59
63
  const viewId = value.get('viewId'), operationId = value.get('operationId'), revision = value.get('revision');
60
64
  const baseTurn = value.get('baseTurn'), digest = value.get('digest'), supersedes = value.get('supersedes');
61
65
  const logicalCount = value.get('logicalCount');
66
+ if (value.has('prepared') && value.get('prepared') !== true)
67
+ throw invalid('history prepared branch metadata');
62
68
  if (typeof viewId !== 'string' || typeof operationId !== 'string' || typeof baseTurn !== 'string' && baseTurn !== null ||
63
69
  typeof digest !== 'string' || !revision || typeof revision !== 'object' || Array.isArray(revision) || revision instanceof Map || revision.kind !== 'u64' ||
64
70
  !Array.isArray(supersedes))
@@ -69,12 +75,16 @@ function parseBranchMetadata(value) {
69
75
  viewId: text(viewId), revision: revision.value, operationId: text(operationId),
70
76
  previousHead, head, baseTurn,
71
77
  ...(logicalCount === undefined ? {} : { logicalCount: seqOf(logicalCount) }),
78
+ ...(value.has('membershipBase') ? { membershipBase: decodeIdentity(value.get('membershipBase'), true) } : {}),
79
+ ...(value.get('prepared') === true ? { prepared: true } : {}),
72
80
  supersedes: supersedes.map(item => decodeIdentity(item)), digest,
73
81
  };
74
- if (parsed.revision < 1n || (parsed.head !== null && parsed.head.kind !== 'message') || (parsed.previousHead !== null && parsed.previousHead.kind !== 'message') || parsed.supersedes.some(item => item.kind !== 'message'))
82
+ if (parsed.revision < 1n || (parsed.head !== null && parsed.head.kind !== 'message' && parsed.head.kind !== 'branch_state') || (parsed.previousHead !== null && parsed.previousHead.kind !== 'message' && parsed.previousHead.kind !== 'branch_state') || parsed.supersedes.some(item => item.kind !== 'message'))
75
83
  throw invalid('history branch metadata');
76
84
  if (!/^[0-9a-f]{64}$/.test(parsed.digest))
77
85
  throw invalid('history branch digest');
86
+ if (parsed.membershipBase && parsed.membershipBase.kind !== 'branch_state')
87
+ throw invalid('history membership root');
78
88
  if (parsed.baseTurn !== null && !/^[0-9a-f]{32}$/.test(parsed.baseTurn))
79
89
  throw invalid('history branch base turn');
80
90
  return parsed;
@@ -97,7 +107,7 @@ function parseBranchState(raw) {
97
107
  if (!metadata)
98
108
  throw new StoreError('corrupt', 'invalid history branch state');
99
109
  const previous = value instanceof Map ? value.get('conflict') : undefined;
100
- return { viewId: metadata.viewId, revision: metadata.revision, head: metadata.head, operationId: metadata.operationId, digest: metadata.digest, ...(metadata.logicalCount !== undefined ? { logicalCount: metadata.logicalCount } : {}), ...(previous === true ? { conflict: true } : {}) };
110
+ return { viewId: metadata.viewId, revision: metadata.revision, head: metadata.head, operationId: metadata.operationId, digest: metadata.digest, ...(metadata.membershipBase ? { membershipBase: metadata.membershipBase } : {}), ...(metadata.logicalCount !== undefined ? { logicalCount: metadata.logicalCount } : {}), ...(previous === true ? { conflict: true } : {}) };
101
111
  }
102
112
  function branchOperationValue(result, digest, inputDigest) {
103
113
  return encodeJson(new Map([
@@ -119,7 +129,7 @@ function parseBranchOperation(raw) {
119
129
  const inputDigest = value.get('inputDigest');
120
130
  if (inputDigest !== undefined && (typeof inputDigest !== 'string' || !/^[0-9a-f]{64}$/.test(inputDigest)))
121
131
  throw new StoreError('corrupt', 'invalid input acceptance digest');
122
- if ((newHead !== null && newHead.kind !== 'message') || (oldHead !== null && oldHead.kind !== 'message'))
132
+ if ((newHead !== null && newHead.kind !== 'message' && newHead.kind !== 'branch_state') || (oldHead !== null && oldHead.kind !== 'message' && oldHead.kind !== 'branch_state'))
123
133
  throw new StoreError('corrupt', 'invalid history branch operation head');
124
134
  if ((turnId !== null && !/^[0-9a-f]{32}$/.test(turnId)) || !/^[0-9a-f]{64}$/.test(digest))
125
135
  throw new StoreError('corrupt', 'invalid history branch operation encoding');
@@ -128,7 +138,8 @@ function parseBranchOperation(raw) {
128
138
  function branchMetadataFromContent(content) {
129
139
  if (!(content instanceof Map))
130
140
  return;
131
- return parseBranchMetadata(content.get('lodyBranch'));
141
+ const metadata = parseBranchMetadata(content.get('lodyBranch'));
142
+ return metadata?.prepared ? undefined : metadata;
132
143
  }
133
144
  function branchStateEqual(a, b) {
134
145
  if (a === null || b === null)
@@ -574,41 +585,60 @@ export class NodeLodyHistory {
574
585
  touched.set(hexBytes(update.turnId), update.turnId);
575
586
  if (update.seq !== 0n)
576
587
  continue;
577
- const [u] = decodeBatch(await this.stream.exportUpdates(update.turnId, 0n, 1n));
578
- if (!u || u.operation.kind !== 'create')
579
- throw new StoreError('corrupt', 'history create event has no operation');
588
+ let turnId = update.turnId, owner, content, digest;
589
+ if (this.stream.fieldReads && this.stream.readCreateFields) {
590
+ const selected = await this.stream.readCreateFields(turnId, ['lodyHistory', 'lodyBranch', 'lodyPublication'].map(key => ({ path: [{ key }] })), ['lodyBranch', 'lodyPublication']);
591
+ const envelope = new Map();
592
+ for (const [index, field] of selected.fields.entries()) {
593
+ if (field.state === 'ready')
594
+ envelope.set(['lodyHistory', 'lodyBranch', 'lodyPublication'][index], decodeJson(encodeUtf8(field.contentJson)));
595
+ }
596
+ owner = selected.owner;
597
+ content = envelope;
598
+ digest = envelope.has('lodyBranch') || envelope.get('lodyPublication') === 'direct' || envelope.get('lodyPublication') === 'private'
599
+ ? selected.filteredDigest : selected.digest;
600
+ }
601
+ else {
602
+ const [u] = decodeBatch(await this.stream.exportUpdates(turnId, 0n, 1n));
603
+ if (!u || u.operation.kind !== 'create')
604
+ throw new StoreError('corrupt', 'history create event has no operation');
605
+ turnId = u.turnId;
606
+ owner = u.owner;
607
+ content = u.operation.content;
608
+ digest = createDigest(owner, u.operation.parents, content);
609
+ }
580
610
  let id;
581
611
  try {
582
- id = identityOf(u.operation.content);
612
+ id = identityOf(content);
583
613
  }
584
614
  catch (error) {
585
615
  if (!(error instanceof StoreError) || error.code !== 'invalid')
586
616
  throw error;
587
- changes.push({ table: NODE_INVALID, key: u.turnId, value: encodeUtf8('invalid_envelope') });
617
+ changes.push({ table: NODE_INVALID, key: turnId, value: encodeUtf8('invalid_envelope') });
588
618
  }
589
619
  if (!id) {
590
- changes.push({ table: PUBLICATION_OBJECTS, key: u.turnId, value: encodeUtf8('null') });
620
+ changes.push({ table: PUBLICATION_OBJECTS, key: turnId, value: encodeUtf8('null') });
591
621
  continue;
592
622
  }
593
623
  let branch;
594
624
  try {
595
- branch = branchMetadataFromContent(u.operation.content);
625
+ branch = branchMetadataFromContent(content);
596
626
  }
597
627
  catch (error) {
598
628
  if (errorCode(error) !== 'invalid')
599
629
  throw error;
600
- changes.push({ table: NODE_INVALID, key: u.turnId, value: encodeUtf8('invalid_envelope') });
601
- changes.push({ table: PUBLICATION_OBJECTS, key: u.turnId, value: encodeUtf8('null') });
630
+ changes.push({ table: NODE_INVALID, key: turnId, value: encodeUtf8('invalid_envelope') });
631
+ changes.push({ table: PUBLICATION_OBJECTS, key: turnId, value: encodeUtf8('null') });
602
632
  continue;
603
633
  }
604
634
  if (branch)
605
635
  branchRows.push({ key: branchKey(branch.viewId), value: branchStateValue(branch) });
606
636
  const key = keyOf(id);
607
- rows.push({ key, value: { version: 1, turnId: [...u.turnId], owner: [...u.owner], digest: [...createDigest(u.owner, u.operation.parents, u.operation.content)] } });
608
- changes.push({ table: PUBLICATION_OBJECTS, key: u.turnId, value: encodeUtf8(JSON.stringify(publicationObject(u.owner, u.operation.parents, u.operation.content))) });
637
+ rows.push({ key, value: { version: 1, turnId: [...turnId], owner: [...owner], digest: [...digest] } });
638
+ changes.push({ table: PUBLICATION_OBJECTS, key: turnId, value: encodeUtf8(JSON.stringify({ key: decodeUtf8(key), owner: hexBytes(owner), digest: hexBytes(digest), kind: id.kind, direct: id.kind === 'message' && content instanceof Map && content.get('lodyPublication') === 'direct' })) });
609
639
  if (id.kind === 'batch_receipt') {
610
- receipts.set(hexBytes(u.turnId), { id: u.turnId, key });
611
- changes.push({ table: NODE_RECEIPTS, key: u.turnId, value: key });
640
+ receipts.set(hexBytes(turnId), { id: turnId, key });
641
+ changes.push({ table: NODE_RECEIPTS, key: turnId, value: key });
612
642
  }
613
643
  }
614
644
  const previous = await this.stream.readIndex(rows.map(row => ({ table: NODE_BINDINGS, key: row.key })));
@@ -662,6 +692,66 @@ export class NodeLodyHistory {
662
692
  return !committed || events.length === limit;
663
693
  }
664
694
  catchUpIndex() { return catchUpHistory(this); }
695
+ /** Requires a host supporting derived-indexes-v1. The SDK, never the consumer,
696
+ * owns private checkpoint formats. General/unfinished/watched writes keep the
697
+ * ordinary catch-up path. Application derived puts share the same proof. */
698
+ publicationFence(cursor) { return publicationFence(publicationPort(this), cursor); }
699
+ async commitContentBatch(writes, options = {}) {
700
+ // Planning awaits index snapshots. Own mutable operations/bytes now so the
701
+ // transaction cannot receive a different envelope edit than the one checked.
702
+ ({ writes, options } = structuredClone({ writes, options }));
703
+ const { derivedIndexPuts = [], unclaimedIdentities = [], ...ordinary } = options;
704
+ ordinary.expectedIndexes = [...(ordinary.expectedIndexes ?? []), ...unclaimedIdentities.map(identity => ({ table: NODE_BINDINGS, key: keyOf(identity), value: null }))];
705
+ const before = options.expectedEventCursor;
706
+ 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'; })) &&
707
+ (options.indexPuts ?? []).every(put => !put.emitEvent && put.onceKey === undefined);
708
+ const ids = new Map();
709
+ let through = before ?? 0n;
710
+ if (eligible)
711
+ for (const write of writes)
712
+ if (write.kind === 'edit') {
713
+ ids.set(hexBytes(write.turnId), write.turnId);
714
+ through += BigInt(write.ops.length);
715
+ }
716
+ const idKey = [...ids.keys()].sort().join(':');
717
+ for (let attempt = 0;; attempt++) {
718
+ const cached = attempt === 0 ? contentCheckpoints.get(this) : undefined;
719
+ const reuse = eligible && cached?.through === before && cached.ids === idKey;
720
+ const plan = eligible && through <= U64_MAX
721
+ ? reuse ? continueContentCheckpoint(cached.plan, through)
722
+ // Detach new proofs from readIndex results/arguments and command IDs
723
+ // once. Continuations share only this SDK-private owned evidence.
724
+ : structuredClone(await planContentCheckpoint(publicationPort(this), before, through, [...ids.values()], this.owner))
725
+ : undefined;
726
+ // The host only receives detached preconditions, never the retained proof.
727
+ const options = structuredClone({
728
+ ...ordinary,
729
+ ...(plan ? {
730
+ expectedIndexes: [...(ordinary.expectedIndexes ?? []), ...plan.expected],
731
+ derivedIndexes: { through, indexPuts: [...plan.puts, ...derivedIndexPuts] },
732
+ } : {}),
733
+ });
734
+ try {
735
+ const result = await this.stream.writeBatch(writes, options);
736
+ contentCheckpoints.delete(this);
737
+ if (plan && result.derivedIndexesApplied === true && result.before === before && result.through === through) {
738
+ settledNodeHistory.set(this, through);
739
+ const disjoint = [...(ordinary.indexPuts ?? []), ...derivedIndexPuts].every(put => !plan.expected.some(row => row.table === put.table && equal(row.key, put.key)));
740
+ const bytes = [...plan.expected, ...plan.puts].reduce((size, row) => size + row.key.length + (row.value?.length ?? 0), 0);
741
+ if (disjoint && bytes <= 256 * 1024)
742
+ contentCheckpoints.set(this, { through, ids: idKey, plan });
743
+ }
744
+ return result;
745
+ }
746
+ catch (error) {
747
+ contentCheckpoints.delete(this);
748
+ // Native stale proves no write committed. Refresh an index-only change
749
+ // once; unknown/transport/storage outcomes are never retried here.
750
+ if (!reuse || attempt !== 0 || errorCode(error) !== 'stale')
751
+ throw error;
752
+ }
753
+ }
754
+ }
665
755
  async invalidMessages(limit = 100) {
666
756
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
667
757
  throw invalid('diagnostic limit');
@@ -729,8 +819,44 @@ export class NodeLodyHistory {
729
819
  forkAndActivate(input) { return branchFork(this, input); }
730
820
  restoreActiveBranch(input) { return branchRestore(this, input); }
731
821
  readActiveBranch(viewId) { return readActiveBranch(this, viewId); }
732
- readActiveBranchPage(viewId, input = {}) {
733
- return readActiveBranchPage(this, viewId, input);
822
+ async readActiveBranchPage(viewId, input = {}) {
823
+ const page = await readActiveBranchPage(this, viewId, input);
824
+ rememberBranchDirectory(this, page);
825
+ return page;
826
+ }
827
+ readActiveBranchMembers(viewId, input = {}) {
828
+ return readActiveBranchMembers(this, viewId, input);
829
+ }
830
+ /** Resolve an identity to its Turn header. */
831
+ async lookupMember(identity) {
832
+ return (await stableRead(this, async () => {
833
+ const id = await branchTurnIdByIdentity(this, identity);
834
+ if (!id)
835
+ return;
836
+ const header = await branchHeader(this, id);
837
+ if (!header)
838
+ throw new StoreError('pending', 'history member is incomplete');
839
+ return { turnId: id.slice(), nextSeq: header.nextSeq, sealed: header.sealed !== null };
840
+ })).value;
841
+ }
842
+ replaceActiveBranchMembers(input) {
843
+ return replaceBranchMembers(this, input);
844
+ }
845
+ async readActiveBranchMessages(viewId, businessIds) {
846
+ const ids = new Set(businessIds);
847
+ return (await stableRead(this, async () => {
848
+ const directory = await readActiveBranchDirectory(this, viewId);
849
+ if (!directory.complete)
850
+ throw new StoreError('pending', 'active branch is incomplete');
851
+ const selected = directory.rows.filter(row => ids.has(row.businessId)).flatMap(row => row.segments);
852
+ const result = await readBranchPageMessages(this, selected);
853
+ if (!result.complete)
854
+ throw new StoreError('pending', 'active members are incomplete');
855
+ return result.messages;
856
+ })).value;
857
+ }
858
+ advanceActiveBranchDirectory(page, result, limit = 40) {
859
+ return advanceBranchDirectory(this, page, result, limit);
734
860
  }
735
861
  async respondPermission(input) {
736
862
  const result = await this.accept({ businessId: text(input.requestId), segmentId: 'response', kind: 'permission_response', parents: input.parents,
@@ -769,6 +895,11 @@ export class NodeLodyHistory {
769
895
  }
770
896
  async observedEventCursor() {
771
897
  await this.catchUpIndex();
898
+ // catchUpIndex has freshly checked for events beyond this private settled
899
+ // checkpoint. A second read of its persisted cursor adds no new evidence.
900
+ const settled = settledNodeHistory.get(this);
901
+ if (settled !== undefined)
902
+ return settled;
772
903
  const [raw] = await this.stream.readIndex([NODE_CURSOR]);
773
904
  return processedCursor(raw);
774
905
  }
@@ -805,6 +936,51 @@ export class NodeLodyHistory {
805
936
  }
806
937
  }
807
938
  }
939
+ const sealedPageBodies = new WeakMap();
940
+ const SEALED_PAGE_ROWS = 64, SEALED_PAGE_BYTES = 8 * 1024 * 1024;
941
+ function sameBranchHeader(left, right) {
942
+ return left.nextSeq === right.nextSeq && left.sealed !== null && right.sealed !== null &&
943
+ equal(left.sealed, right.sealed) && left.parents.length === right.parents.length &&
944
+ left.parents.every((parent, i) => equal(parent.id, right.parents[i].id) && equal(parent.hash, right.parents[i].hash));
945
+ }
946
+ /** Sealed content is immutable, but membership and availability are always reread. */
947
+ async function readBranchPageTurn(host, turnId, knownHeader, retained) {
948
+ if (host instanceof LodyHistory)
949
+ return readBranchTurn(host, turnId);
950
+ const header = knownHeader ?? await branchHeader(host, turnId);
951
+ if (!header)
952
+ return;
953
+ let cache = sealedPageBodies.get(host);
954
+ const key = hexBytes(turnId), cached = retained ?? cache?.rows.get(key);
955
+ if (cached && sameBranchHeader(cached, header)) {
956
+ if (cache.rows.get(key) === cached) {
957
+ cache.rows.delete(key);
958
+ cache.rows.set(key, cached);
959
+ }
960
+ return structuredClone(cached);
961
+ }
962
+ const turn = await readBranchTurn(host, turnId);
963
+ if (!turn || !sameBranchHeader(turn, header) || turn.sourceBytes === undefined || turn.sourceBytes > SEALED_PAGE_BYTES)
964
+ return turn;
965
+ cache = sealedPageBodies.get(host);
966
+ if (!cache) {
967
+ cache = { bytes: 0, rows: new Map() };
968
+ sealedPageBodies.set(host, cache);
969
+ }
970
+ const previous = cache.rows.get(key);
971
+ if (previous) {
972
+ cache.rows.delete(key);
973
+ cache.bytes -= previous.sourceBytes;
974
+ }
975
+ cache.rows.set(key, structuredClone(turn));
976
+ cache.bytes += turn.sourceBytes;
977
+ while (cache.rows.size > SEALED_PAGE_ROWS || cache.bytes > SEALED_PAGE_BYTES) {
978
+ const oldest = cache.rows.keys().next().value;
979
+ cache.bytes -= cache.rows.get(oldest).sourceBytes;
980
+ cache.rows.delete(oldest);
981
+ }
982
+ return turn;
983
+ }
808
984
  async function readBranchIndex(host, viewId) {
809
985
  const key = branchKey(viewId);
810
986
  const raw = host instanceof LodyHistory
@@ -885,6 +1061,7 @@ async function readBranchTurn(host, turnId) {
885
1061
  content: body instanceof Map ? body.get('content') : undefined,
886
1062
  nextSeq: result.turn.nextSeq,
887
1063
  sealed: result.turn.sealed?.slice() ?? null,
1064
+ sourceBytes: result.turn.contentJson.length * 2,
888
1065
  };
889
1066
  }
890
1067
  function ownInputIdentity(input) {
@@ -931,9 +1108,10 @@ async function acceptInputToView(host, input) {
931
1108
  if (prior)
932
1109
  return prior;
933
1110
  const baseTurn = input.expectedHead ? await branchTurnByIdentity(host, input.expectedHead) ?? null : null;
934
- return branchMutation(host, input, baseTurn, [], digest);
1111
+ return branchMutation(host, input, baseTurn, [], digest, true);
935
1112
  }
936
- async function branchMutation(host, input, baseTurn, supersedes, inputDigest) {
1113
+ async function branchMutation(host, input, baseTurn, supersedes, inputDigest, linearAppend = false) {
1114
+ input = ownBranchInput(input);
937
1115
  if (input.input.kind !== 'message')
938
1116
  throw invalid('active branch only accepts message Turns');
939
1117
  if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
@@ -943,7 +1121,7 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest) {
943
1121
  if (baseTurn !== null && baseTurn.length !== 16)
944
1122
  throw invalid('branch base Turn');
945
1123
  if (expectedHead) {
946
- if (expectedHead.kind !== 'message')
1124
+ if (expectedHead.kind !== 'message' && expectedHead.kind !== 'branch_state')
947
1125
  throw invalid('branch head kind');
948
1126
  keyOf(expectedHead);
949
1127
  }
@@ -954,9 +1132,13 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest) {
954
1132
  }
955
1133
  if (!branchParentMatches(baseTurn, input.input.parents))
956
1134
  throw invalid('branch base parent');
957
- const baseCount = await branchLogicalCountAt(host, viewId, baseTurn);
1135
+ const inherited = await readBranchIndex(host, viewId);
1136
+ const rooted = inherited?.membershipBase && inherited.revision === input.expectedRevision && branchStateEqual(inherited.head, expectedHead) && linearAppend;
1137
+ const baseCount = rooted ? inherited.logicalCount : await branchLogicalCountAt(host, viewId, baseTurn);
958
1138
  const logicalCount = baseCount + (input.input.segmentId === 'primary' ? 1n : 0n);
959
1139
  const metadata = branchMetadataFor({ ...input, viewId, operationId, expectedHead }, owner, expectedHead, baseTurn, supersedes, logicalCount);
1140
+ if (rooted)
1141
+ metadata.membershipBase = inherited.membershipBase;
960
1142
  const createKey = keyOf(input.input);
961
1143
  const branchValue = branchStateValue(metadata);
962
1144
  const operationValue = branchOperationValue({ operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId: null }, metadata.digest, inputDigest);
@@ -996,8 +1178,9 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest) {
996
1178
  if (!existingBranch || existingBranch.operationId !== operationId || existingBranch.digest !== metadata.digest)
997
1179
  throw new StoreError('conflict', 'branch message identity already exists');
998
1180
  }
1181
+ let committed;
999
1182
  try {
1000
- await writeIndexed(host, [{ kind: 'createOnce', key: createKey, parents: input.input.parents, content: envelope(input.input, true, metadata) }], [
1183
+ committed = await writeIndexed(host, [{ kind: 'createOnce', key: createKey, parents: input.input.parents, content: envelope(input.input, true, metadata) }], [
1001
1184
  { table: BRANCH_TABLE, key: branchKey(viewId), value: branchValue, emitEvent: true },
1002
1185
  { table: BRANCH_OPERATIONS, key: branchOperationKey(viewId, operationId), value: operationValue },
1003
1186
  ], cursor);
@@ -1012,19 +1195,62 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest) {
1012
1195
  if (!turnId)
1013
1196
  throw new StoreError('corrupt', 'active branch replacement missing');
1014
1197
  await maybePublishAccept(host, input.input, { publish: true }, turnId);
1015
- return { operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId };
1198
+ const result = { operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId };
1199
+ if (linearAppend && !supersedes.length && host instanceof NodeLodyHistory && input.input.segmentId === 'primary' &&
1200
+ committed?.updates.length === 1 && committed.before !== undefined && committed.through !== undefined && committed.updates[0].seq === 0n &&
1201
+ equal(committed.updates[0].turnId, turnId) && committed.through - committed.before === 2n) {
1202
+ branchTransitions.set(result, {
1203
+ ownerToken: branchHandleToken(host), beforeRevision: input.expectedRevision, beforeHead: structuredClone(expectedHead),
1204
+ state: { viewId, revision: metadata.revision, head: structuredClone(metadata.head), operationId, logicalCount, ...(metadata.membershipBase ? { membershipBase: metadata.membershipBase } : {}) },
1205
+ message: { businessId: input.input.businessId, segmentId: 'primary', turnId: turnId.slice(),
1206
+ content: structuredClone(input.input.content), nextSeq: 1n, sealed: false,
1207
+ parents: structuredClone(input.input.parents), sealedHash: null },
1208
+ through: committed.through,
1209
+ });
1210
+ }
1211
+ return result;
1016
1212
  }
1017
1213
  throw new StoreError('stale', 'active branch retry budget exhausted');
1018
1214
  }
1019
1215
  async function branchAccept(host, input) {
1216
+ input = ownBranchInput(input);
1020
1217
  const baseTurn = input.expectedHead ? await branchTurnByIdentity(host, input.expectedHead) ?? null : null;
1021
- return branchMutation(host, input, baseTurn, []);
1218
+ return branchMutation(host, input, baseTurn, [], undefined, true);
1022
1219
  }
1023
1220
  async function branchFork(host, input) {
1024
1221
  if (input.input.kind !== 'message')
1025
1222
  throw invalid('active branch only accepts message replacements');
1026
1223
  if (input.baseTurn && input.baseTurn.length !== 16)
1027
1224
  throw invalid('branch base Turn');
1225
+ input = structuredClone(input);
1226
+ const expectedId = input.expectedHead ? await branchTurnIdByIdentity(host, input.expectedHead) : undefined;
1227
+ const expected = expectedId ? await branchMetadataAt(host, expectedId) : undefined;
1228
+ if (expected?.membershipBase && expected.viewId === input.viewId) {
1229
+ if (!(host instanceof NodeLodyHistory))
1230
+ throw invalid('membership forks require a Native author');
1231
+ if (!branchParentMatches(input.baseTurn, input.input.parents))
1232
+ throw invalid('branch base parent');
1233
+ const cursor = await host.observedEventCursor();
1234
+ const directory = await readRootedBranchDirectory(host, { viewId: input.viewId, revision: input.expectedRevision, head: input.expectedHead,
1235
+ operationId: expected.operationId, membershipBase: expected.membershipBase, ...(expected.logicalCount === undefined ? {} : { logicalCount: expected.logicalCount }) });
1236
+ if (!directory.complete)
1237
+ throw new StoreError('pending', 'fork membership is incomplete');
1238
+ const members = directory.rows.flatMap(row => row.segments);
1239
+ const boundary = input.baseTurn ? members.findIndex(row => equal(row.turnId, input.baseTurn)) : -1;
1240
+ if (input.baseTurn && boundary < 0)
1241
+ throw new StoreError('stale', 'fork base is not active');
1242
+ const prefix = members.slice(0, boundary + 1).map(row => ({ identity: { kind: 'message', businessId: row.businessId, segmentId: row.physicalSegmentId ?? row.segmentId }, segmentId: row.segmentId }));
1243
+ const result = await host.replaceActiveBranchMembers({ viewId: input.viewId, expectedRevision: input.expectedRevision,
1244
+ expectedHead: input.expectedHead, operationId: input.operationId, expectedEventCursor: cursor,
1245
+ members: [...prefix, { identity: input.input, segmentId: input.input.segmentId }],
1246
+ messages: [{ identity: input.input, content: input.input.content, parents: input.input.parents, attachments: input.input.attachments, sealed: false }], supersedes: input.supersedes });
1247
+ if (!result.newHead)
1248
+ throw invalid('fork root missing');
1249
+ const physical = await host.lookupMember(input.input);
1250
+ if (!physical)
1251
+ throw new StoreError('pending', 'fork replacement missing');
1252
+ return { ...result, newHead: result.newHead, turnId: physical.turnId };
1253
+ }
1028
1254
  return branchMutation(host, input, input.baseTurn, input.supersedes);
1029
1255
  }
1030
1256
  function branchRestoreDigest(input) {
@@ -1042,12 +1268,12 @@ async function branchRestore(host, input) {
1042
1268
  throw invalid('branch revision');
1043
1269
  const viewId = text(input.viewId), operationId = text(input.operationId), digest = branchRestoreDigest(input);
1044
1270
  if (input.expectedHead) {
1045
- if (input.expectedHead.kind !== 'message')
1271
+ if (input.expectedHead.kind !== 'message' && input.expectedHead.kind !== 'branch_state')
1046
1272
  throw invalid('branch expected head kind');
1047
1273
  keyOf(input.expectedHead);
1048
1274
  }
1049
1275
  if (input.restoreHead) {
1050
- if (input.restoreHead.kind !== 'message')
1276
+ if (input.restoreHead.kind !== 'message' && input.restoreHead.kind !== 'branch_state')
1051
1277
  throw invalid('branch restore head kind');
1052
1278
  keyOf(input.restoreHead);
1053
1279
  }
@@ -1077,12 +1303,14 @@ async function branchRestore(host, input) {
1077
1303
  if (input.restoreHead && !restoreTurnId)
1078
1304
  throw new StoreError('corrupt', 'restore branch head missing');
1079
1305
  const logicalCount = await branchLogicalCountAt(host, viewId, restoreTurnId ?? null);
1306
+ const restoredMetadata = restoreTurnId ? await branchMetadataAt(host, restoreTurnId) : undefined;
1080
1307
  const metadata = {
1081
1308
  viewId,
1082
1309
  revision: input.expectedRevision + 1n,
1083
1310
  operationId,
1084
1311
  previousHead: input.expectedHead,
1085
1312
  head: input.restoreHead,
1313
+ ...(restoredMetadata?.membershipBase ? { membershipBase: restoredMetadata.membershipBase } : {}),
1086
1314
  baseTurn: null,
1087
1315
  logicalCount,
1088
1316
  supersedes: [],
@@ -1123,6 +1351,11 @@ async function readActiveBranchSnapshot(host, viewId) {
1123
1351
  return { state: { viewId: text(viewId), revision: 0n, head: null, operationId: null }, messages: [], complete: true };
1124
1352
  if (state.conflict)
1125
1353
  throw new StoreError('conflict', 'active branch has conflicting revisions');
1354
+ if (state.membershipBase) {
1355
+ const directory = await readActiveBranchDirectory(host, viewId);
1356
+ const page = await readBranchPageMessages(host, directory.rows.flatMap(row => row.segments));
1357
+ return { state, messages: page.messages, complete: directory.complete && page.complete };
1358
+ }
1126
1359
  if (state.head === null)
1127
1360
  return { state, messages: [], complete: true };
1128
1361
  const headId = await branchTurnByIdentity(host, state.head);
@@ -1149,22 +1382,26 @@ async function readActiveBranchSnapshot(host, viewId) {
1149
1382
  await visit(headId);
1150
1383
  return { state, messages: output, complete };
1151
1384
  }
1152
- async function readBranchPageMessages(host, segments) {
1385
+ async function readBranchPageMessages(host, segments, headers) {
1153
1386
  const messages = [];
1154
1387
  let complete = true;
1388
+ // Retain this page's hits before misses can evict them. A page larger than the
1389
+ // byte budget must not repeatedly evict every newer body before reaching it.
1390
+ const retained = host instanceof NodeLodyHistory ? new Map(sealedPageBodies.get(host)?.rows) : undefined;
1155
1391
  // Pages can contain up to 500 rows. Keep body requests below the Node
1156
1392
  // client's bounded queue instead of launching one request per segment.
1157
1393
  for (let offset = 0; offset < segments.length; offset += 8) {
1158
1394
  const batch = segments.slice(offset, offset + 8);
1159
- const turns = await Promise.all(batch.map(segment => readBranchTurn(host, segment.turnId)));
1395
+ const turns = await Promise.all(batch.map(segment => readBranchPageTurn(host, segment.turnId, headers?.get(hexBytes(segment.turnId)), retained?.get(hexBytes(segment.turnId)))));
1160
1396
  for (let i = 0; i < batch.length; i++) {
1161
1397
  const turn = turns[i], segment = batch[i];
1162
- if (!turn || turn.identity?.kind !== 'message' || turn.content === undefined) {
1398
+ if (!turn || turn.identity?.kind !== 'message' || turn.identity.businessId !== segment.businessId || turn.identity.segmentId !== (segment.physicalSegmentId ?? segment.segmentId) || turn.content === undefined) {
1163
1399
  complete = false;
1164
1400
  continue;
1165
1401
  }
1166
1402
  messages.push({
1167
- businessId: segment.businessId, segmentId: segment.segmentId, turnId: turn.turnId,
1403
+ businessId: segment.businessId, segmentId: segment.segmentId,
1404
+ ...(segment.physicalSegmentId ? { physicalSegmentId: segment.physicalSegmentId } : {}), turnId: turn.turnId,
1168
1405
  content: turn.content, nextSeq: turn.nextSeq, sealed: turn.sealed !== null,
1169
1406
  parents: turn.parents, sealedHash: turn.sealed,
1170
1407
  });
@@ -1172,9 +1409,239 @@ async function readBranchPageMessages(host, segments) {
1172
1409
  }
1173
1410
  return { messages, complete };
1174
1411
  }
1412
+ async function readRootedBranchDirectory(host, state) {
1413
+ const root = state.membershipBase;
1414
+ const rootId = await branchTurnIdByIdentity(host, root);
1415
+ if (!rootId)
1416
+ return { state, rows: [], complete: false };
1417
+ const header = await branchHeader(host, rootId);
1418
+ if (!header?.sealed)
1419
+ return { state, rows: [], complete: false };
1420
+ const rootMeta = await branchMetadataAt(host, rootId);
1421
+ if (!rootMeta || rootMeta.viewId !== state.viewId || !branchStateEqual(rootMeta.membershipBase ?? null, root))
1422
+ throw invalid('membership root metadata');
1423
+ const content = asMap(await publicationField(host, rootId, [{ key: 'content' }]), 'membership root');
1424
+ const raw = content.get('members');
1425
+ if (content.get('version') !== '1' || !Array.isArray(raw))
1426
+ throw invalid('membership root members');
1427
+ const refs = raw.map(value => {
1428
+ const row = asMap(value, 'membership member');
1429
+ const identity = decodeIdentity(row.get('identity'));
1430
+ const segmentId = row.get('segmentId');
1431
+ if (identity.kind !== 'message' || typeof segmentId !== 'string')
1432
+ throw invalid('membership member identity');
1433
+ if (segmentId !== identity.segmentId && (segmentId !== 'primary' || !identity.segmentId.startsWith('primary:')))
1434
+ throw invalid('membership segment alias');
1435
+ return { identity, segmentId: text(segmentId) };
1436
+ });
1437
+ const rows = [], byId = new Map();
1438
+ let complete = true;
1439
+ const seen = new Set();
1440
+ const add = (ref, turnId) => {
1441
+ const key = hexBytes(turnId);
1442
+ if (seen.has(key))
1443
+ throw invalid('duplicate membership member');
1444
+ seen.add(key);
1445
+ let row = byId.get(ref.identity.businessId);
1446
+ if (!row) {
1447
+ row = { businessId: ref.identity.businessId, segments: [] };
1448
+ byId.set(row.businessId, row);
1449
+ rows.push(row);
1450
+ }
1451
+ row.segments.push({ businessId: row.businessId, segmentId: ref.segmentId, turnId: turnId.slice(),
1452
+ ...(ref.identity.segmentId === ref.segmentId ? {} : { physicalSegmentId: ref.identity.segmentId }) });
1453
+ };
1454
+ for (const ref of refs) {
1455
+ const turnId = await branchTurnIdByIdentity(host, ref.identity);
1456
+ if (!turnId || !await branchHeader(host, turnId)) {
1457
+ complete = false;
1458
+ continue;
1459
+ }
1460
+ add(ref, turnId);
1461
+ }
1462
+ const boundary = rootMeta.head ? await branchTurnIdByIdentity(host, rootMeta.head) : undefined;
1463
+ let current = state.head ? await branchTurnIdByIdentity(host, state.head) : undefined;
1464
+ const suffix = [], walked = new Set();
1465
+ while (current && (!boundary || !equal(current, boundary))) {
1466
+ const id = hexBytes(current);
1467
+ if (walked.has(id))
1468
+ throw invalid('membership suffix cycle');
1469
+ walked.add(id);
1470
+ const metadata = await branchMetadataAt(host, current);
1471
+ if (!metadata) {
1472
+ complete = false;
1473
+ break;
1474
+ }
1475
+ if (metadata.viewId !== state.viewId || !branchStateEqual(metadata.membershipBase ?? null, root) || !metadata.head)
1476
+ throw invalid('membership suffix metadata');
1477
+ suffix.push({ identity: metadata.head, turnId: current });
1478
+ current = metadata.baseTurn ? unhexBytes(metadata.baseTurn, 16) : undefined;
1479
+ }
1480
+ if (boundary && (!current || !equal(current, boundary)))
1481
+ complete = false;
1482
+ for (const ref of suffix.reverse())
1483
+ add({ identity: ref.identity, segmentId: ref.identity.segmentId }, ref.turnId);
1484
+ if (state.logicalCount !== undefined && BigInt(rows.length) !== state.logicalCount)
1485
+ complete = false;
1486
+ return { state, rows, complete };
1487
+ }
1488
+ async function replaceBranchMembers(host, input) {
1489
+ if (!host.stream.exclusiveBatches)
1490
+ throw invalid('membership requires exclusive-batch-v1');
1491
+ input = structuredClone(input);
1492
+ const { viewId, operationId } = input;
1493
+ text(viewId);
1494
+ text(operationId);
1495
+ if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
1496
+ throw invalid('branch revision');
1497
+ if (typeof input.expectedEventCursor !== 'bigint' || input.expectedEventCursor < 0n || input.expectedEventCursor > U64_MAX)
1498
+ throw invalid('membership event cursor');
1499
+ for (const superseded of input.supersedes ?? []) {
1500
+ if (superseded.kind !== 'message')
1501
+ throw invalid('branch superseded kind');
1502
+ keyOf(superseded);
1503
+ }
1504
+ const owner = host.owner;
1505
+ const identity = { kind: 'branch_state', businessId: viewId, segmentId: operationId };
1506
+ const newHead = identity;
1507
+ const messageKeys = new Set((input.messages ?? []).map(row => decodeUtf8(keyOf(row.identity))));
1508
+ const memberKeys = new Set(), logicalIds = new Set(), primaryIds = new Set();
1509
+ for (const member of input.members) {
1510
+ if (member.identity.kind !== 'message' || typeof member.segmentId !== 'string')
1511
+ throw invalid('membership identity');
1512
+ text(member.segmentId);
1513
+ const key = decodeUtf8(keyOf(member.identity));
1514
+ if (memberKeys.has(key))
1515
+ throw invalid('duplicate membership identity');
1516
+ memberKeys.add(key);
1517
+ logicalIds.add(member.identity.businessId);
1518
+ if (member.segmentId === 'primary') {
1519
+ if (primaryIds.has(member.identity.businessId))
1520
+ throw invalid('duplicate membership primary');
1521
+ primaryIds.add(member.identity.businessId);
1522
+ }
1523
+ if (member.segmentId !== member.identity.segmentId && (member.segmentId !== 'primary' || !member.identity.segmentId.startsWith('primary:')))
1524
+ throw invalid('membership segment alias');
1525
+ }
1526
+ if (primaryIds.size !== logicalIds.size)
1527
+ throw invalid('membership primary missing');
1528
+ const members = input.members.map(row => new Map([['identity', identityValue(row.identity)], ['segmentId', row.segmentId]]));
1529
+ const messages = input.messages ?? [];
1530
+ if (messages.some(row => row.identity.kind !== 'message' || !memberKeys.has(decodeUtf8(keyOf(row.identity)))) || messageKeys.size !== messages.length)
1531
+ throw invalid('membership messages');
1532
+ if (messages.some(row => row.sealed !== undefined && typeof row.sealed !== 'boolean'))
1533
+ throw invalid('membership sealing flag');
1534
+ const receipts = input.receipts ?? [];
1535
+ const digest = hexBytes(blake3(encodeJson(new Map([
1536
+ ['viewId', viewId], ['operationId', operationId], ['revision', { kind: 'u64', value: input.expectedRevision }],
1537
+ ['expectedHead', input.expectedHead ? identityValue(input.expectedHead) : null], ['members', members],
1538
+ ['messages', messages.map(row => [hexBytes(createDigest(owner, row.parents ?? [], envelope({ ...row.identity, parents: row.parents ?? [], content: row.content, attachments: row.attachments }))), row.sealed !== false])],
1539
+ ['receipts', encodeCommands(receipts)], ['supersedes', (input.supersedes ?? []).map(identityValue)],
1540
+ ]))));
1541
+ const prior = await readBranchOperation(host, viewId, operationId);
1542
+ if (prior) {
1543
+ if (prior.digest !== digest)
1544
+ throw new StoreError('conflict', 'membership operation changed');
1545
+ return { operationId, created: false, oldHead: prior.oldHead, newHead: prior.newHead, revision: prior.revision, turnId: prior.turnId };
1546
+ }
1547
+ let cursor = await branchCursor(host);
1548
+ if (cursor !== input.expectedEventCursor)
1549
+ throw new StoreError('stale', 'membership observation changed');
1550
+ const state = await readBranchIndex(host, viewId);
1551
+ if (state?.conflict)
1552
+ throw new StoreError('conflict', 'active branch has conflicting revisions');
1553
+ if ((state?.revision ?? 0n) !== input.expectedRevision || !branchStateEqual(state?.head ?? null, input.expectedHead))
1554
+ throw new StoreError('stale', 'active branch changed');
1555
+ for (const member of input.members)
1556
+ if (!messageKeys.has(decodeUtf8(keyOf(member.identity)))) {
1557
+ const turnId = await branchTurnIdByIdentity(host, member.identity);
1558
+ if (!turnId || !await branchHeader(host, turnId))
1559
+ throw new StoreError('pending', 'membership reference missing');
1560
+ }
1561
+ if (!host.stream.exclusiveBatches)
1562
+ throw invalid('membership requires exclusive-batch-v1');
1563
+ const writes = [];
1564
+ for (const row of messages) {
1565
+ const prior = await host.lookupMember(row.identity);
1566
+ if (prior && (prior.sealed ? prior.nextSeq !== 2n || row.sealed === false : prior.nextSeq !== 1n))
1567
+ throw new StoreError('conflict', 'prepared membership message changed');
1568
+ writes.push({ kind: 'createOnce', key: keyOf(row.identity), parents: row.parents ?? [], content: envelope({ ...row.identity, parents: row.parents ?? [], content: row.content, attachments: row.attachments }, false) });
1569
+ if (row.sealed !== false && !prior?.sealed)
1570
+ writes.push({ kind: 'sealOnce', key: keyOf(row.identity), expectedNextSeq: 1n });
1571
+ }
1572
+ const receiptWrites = [];
1573
+ for (const receipt of receipts) {
1574
+ assertWritableIdentity(receipt.identity);
1575
+ receiptWrites.push({ kind: 'createOnce', key: keyOf(receipt.identity), parents: receipt.parents, content: envelope({ ...receipt.identity, parents: receipt.parents, content: receipt.content, attachments: receipt.attachments }, false) });
1576
+ }
1577
+ if (receiptWrites.length > 4094)
1578
+ throw invalid('membership receipt limit');
1579
+ // Prepare messages in exclusive groups; author receipts during activation.
1580
+ for (let offset = 0; offset < writes.length; offset += 64) {
1581
+ const commit = await writeIndexed(host, writes.slice(offset, offset + 64), [], cursor, true);
1582
+ if (commit?.through === undefined)
1583
+ throw invalid('membership requires fenced Native writes');
1584
+ cursor = commit.through;
1585
+ }
1586
+ const metadata = { viewId, operationId, revision: input.expectedRevision + 1n,
1587
+ previousHead: input.expectedHead, head: newHead, baseTurn: null, membershipBase: identity,
1588
+ logicalCount: BigInt(logicalIds.size), supersedes: input.supersedes ?? [], digest };
1589
+ // Append manifest chunks under a fixed intent digest and resume an exact prefix.
1590
+ const root = { ...identity, parents: [], content: new Map([['version', '1'], ['intentDigest', digest], ['members', []]]) };
1591
+ const createdRoot = await writeIndexed(host, [
1592
+ { kind: 'createOnce', key: keyOf(identity), parents: [], content: envelope(root, false, { ...metadata, prepared: true }) },
1593
+ ], [], cursor, true);
1594
+ if (createdRoot?.through === undefined)
1595
+ throw invalid('membership requires fenced Native writes');
1596
+ cursor = createdRoot.through;
1597
+ await host.catchUpIndex();
1598
+ const rootId = await branchTurnIdByIdentity(host, identity);
1599
+ if (!rootId)
1600
+ throw new StoreError('corrupt', 'prepared membership root missing');
1601
+ let rootHeader = await branchHeader(host, rootId);
1602
+ if (!rootHeader)
1603
+ throw new StoreError('corrupt', 'prepared membership root header missing');
1604
+ const prepared = await publicationField(host, rootId, [{ key: 'content' }, { key: 'members' }]);
1605
+ if (!Array.isArray(prepared) || prepared.length > members.length || prepared.some((value, i) => !equal(encodeJson(value), encodeJson(members[i]))))
1606
+ throw new StoreError('conflict', 'prepared membership prefix changed');
1607
+ if (rootHeader.sealed && prepared.length !== members.length)
1608
+ throw new StoreError('conflict', 'prepared membership root incomplete');
1609
+ for (let offset = prepared.length; offset < members.length; offset += 128) {
1610
+ const commit = await host.stream.writeBatch([{
1611
+ kind: 'edit', turnId: rootId, expectedNextSeq: rootHeader.nextSeq,
1612
+ ops: [{ kind: 'spliceArray', path: [{ key: 'content' }, { key: 'members' }], index: BigInt(offset), delete: 0n,
1613
+ valuesJson: decodeUtf8(encodeJson(members.slice(offset, offset + 128))) }],
1614
+ }], { expectedEventCursor: cursor, requireLocalInterval: true });
1615
+ if (commit.through === undefined)
1616
+ throw invalid('membership requires fenced Native writes');
1617
+ cursor = commit.through;
1618
+ rootHeader = { ...rootHeader, nextSeq: rootHeader.nextSeq + 1n };
1619
+ }
1620
+ if (!rootHeader.sealed) {
1621
+ const commit = await writeIndexed(host, [{ kind: 'seal', turnId: rootId, expectedNextSeq: rootHeader.nextSeq }], [], cursor, true);
1622
+ if (commit?.through === undefined)
1623
+ throw invalid('membership requires fenced Native writes');
1624
+ cursor = commit.through;
1625
+ rootHeader = (await branchHeader(host, rootId));
1626
+ }
1627
+ if (!rootHeader.sealed)
1628
+ throw new StoreError('corrupt', 'prepared membership root not sealed');
1629
+ const activation = { kind: 'branch_state', businessId: viewId, segmentId: `activation:${digest}`,
1630
+ parents: [{ id: rootId, hash: rootHeader.sealed }], content: null };
1631
+ const result = { operationId, created: true, oldHead: input.expectedHead, newHead, revision: metadata.revision, turnId: null };
1632
+ await writeIndexed(host, [
1633
+ ...receiptWrites,
1634
+ { kind: 'createOnce', key: keyOf(activation), parents: activation.parents, content: envelope(activation, false, metadata) },
1635
+ { kind: 'sealOnce', key: keyOf(activation), expectedNextSeq: 1n },
1636
+ ], [
1637
+ { table: BRANCH_TABLE, key: branchKey(viewId), value: branchStateValue(metadata), emitEvent: true },
1638
+ { table: BRANCH_OPERATIONS, key: branchOperationKey(viewId, operationId), value: branchOperationValue(result, digest) },
1639
+ ], cursor, true);
1640
+ return result;
1641
+ }
1175
1642
  const activeBranchDirectoryCache = new WeakMap();
1176
1643
  function branchDirectoryKey(state) {
1177
- return `${state.revision}:${state.head ? decodeUtf8(keyOf(state.head)) : ''}`;
1644
+ return `${state.revision}:${state.head ? decodeUtf8(keyOf(state.head)) : ''}:${state.membershipBase ? decodeUtf8(keyOf(state.membershipBase)) : ''}`;
1178
1645
  }
1179
1646
  async function branchTurnIdByIdentity(host, identity) {
1180
1647
  const key = keyOf(identity);
@@ -1194,7 +1661,10 @@ async function branchHeader(host, turnId) {
1194
1661
  const result = await host.stream.readTurnHeader(turnId);
1195
1662
  if (result.kind !== 'found')
1196
1663
  return;
1197
- return { parents: result.turn.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })) };
1664
+ return {
1665
+ parents: result.turn.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })),
1666
+ nextSeq: result.turn.nextSeq, sealed: result.turn.sealed?.slice() ?? null,
1667
+ };
1198
1668
  }
1199
1669
  async function branchIdentityAt(host, turnId) {
1200
1670
  try {
@@ -1212,7 +1682,7 @@ async function readActiveBranchDirectory(host, viewId) {
1212
1682
  await host.catchUpIndex();
1213
1683
  const state = await readBranchIndex(host, viewId);
1214
1684
  const publicState = state
1215
- ? { viewId: state.viewId, revision: state.revision, head: state.head, operationId: state.operationId, ...(state.conflict ? { conflict: true } : {}) }
1685
+ ? { viewId: state.viewId, revision: state.revision, head: state.head, operationId: state.operationId, ...(state.logicalCount !== undefined ? { logicalCount: state.logicalCount } : {}), ...(state.membershipBase ? { membershipBase: state.membershipBase } : {}), ...(state.conflict ? { conflict: true } : {}) }
1216
1686
  : { viewId: text(viewId), revision: 0n, head: null, operationId: null };
1217
1687
  const key = branchDirectoryKey(publicState);
1218
1688
  const cached = activeBranchDirectoryCache.get(host)?.get(viewId);
@@ -1222,7 +1692,7 @@ async function readActiveBranchDirectory(host, viewId) {
1222
1692
  const { value } = await stableRead(host, async () => {
1223
1693
  const current = await readBranchIndex(host, viewId);
1224
1694
  const currentState = current
1225
- ? { viewId: current.viewId, revision: current.revision, head: current.head, operationId: current.operationId, ...(current.conflict ? { conflict: true } : {}) }
1695
+ ? { viewId: current.viewId, revision: current.revision, head: current.head, operationId: current.operationId, ...(current.logicalCount !== undefined ? { logicalCount: current.logicalCount } : {}), ...(current.membershipBase ? { membershipBase: current.membershipBase } : {}), ...(current.conflict ? { conflict: true } : {}) }
1226
1696
  : { viewId: text(viewId), revision: 0n, head: null, operationId: null };
1227
1697
  if (branchDirectoryKey(currentState) !== key)
1228
1698
  throw new StoreError('stale', 'active branch changed during directory read');
@@ -1230,6 +1700,8 @@ async function readActiveBranchDirectory(host, viewId) {
1230
1700
  throw new StoreError('conflict', 'active branch has conflicting revisions');
1231
1701
  if (!current?.head)
1232
1702
  return { state: currentState, rows: [], complete: true };
1703
+ if (current.membershipBase)
1704
+ return readRootedBranchDirectory(host, current);
1233
1705
  const headId = await branchTurnIdByIdentity(host, current.head);
1234
1706
  if (!headId)
1235
1707
  return { state: currentState, rows: [], complete: false };
@@ -1268,7 +1740,8 @@ async function readActiveBranchDirectory(host, viewId) {
1268
1740
  byView = new Map();
1269
1741
  activeBranchDirectoryCache.set(host, byView);
1270
1742
  }
1271
- byView.set(viewId, { key, value });
1743
+ if (value.complete)
1744
+ byView.set(viewId, { key, value });
1272
1745
  return value;
1273
1746
  }
1274
1747
  catch (error) {
@@ -1280,6 +1753,38 @@ async function readActiveBranchDirectory(host, viewId) {
1280
1753
  throw new StoreError('stale', 'active branch directory retry budget exhausted');
1281
1754
  }
1282
1755
  async function readActiveBranchPage(host, viewId, input) {
1756
+ return (await stableRead(host, async () => {
1757
+ const { segments, headers, ...selected } = await readActiveBranchSelection(host, viewId, input);
1758
+ const page = await readBranchPageMessages(host, segments, headers);
1759
+ return { ...selected, messages: page.messages, complete: selected.complete && page.complete };
1760
+ })).value;
1761
+ }
1762
+ async function readActiveBranchMembers(host, viewId, input) {
1763
+ return (await stableRead(host, async () => {
1764
+ const { segments, headers: _headers, ...selected } = await readActiveBranchSelection(host, viewId, input);
1765
+ return { ...selected, members: segments.map(segment => ({ ...segment, turnId: segment.turnId.slice() })) };
1766
+ })).value;
1767
+ }
1768
+ async function activeCursorHead(host, directory, head) {
1769
+ if (!directory.state.membershipBase)
1770
+ return directory.rows.some(row => row.segments.some(segment => equal(segment.turnId, head)));
1771
+ const root = await branchTurnIdByIdentity(host, directory.state.membershipBase);
1772
+ let current = directory.state.head ? await branchTurnIdByIdentity(host, directory.state.head) : undefined;
1773
+ const seen = new Set();
1774
+ while (current && !seen.has(hexBytes(current))) {
1775
+ if (equal(current, head))
1776
+ return true;
1777
+ if (root && equal(current, root))
1778
+ return false;
1779
+ seen.add(hexBytes(current));
1780
+ const metadata = await branchMetadataAt(host, current);
1781
+ if (!metadata || metadata.viewId !== directory.state.viewId || !branchStateEqual(metadata.membershipBase ?? null, directory.state.membershipBase))
1782
+ return false;
1783
+ current = metadata.baseTurn ? unhexBytes(metadata.baseTurn, 16) : undefined;
1784
+ }
1785
+ return false;
1786
+ }
1787
+ async function readActiveBranchSelection(host, viewId, input) {
1283
1788
  const limit = input.limit ?? 40;
1284
1789
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
1285
1790
  throw invalid('active branch page limit');
@@ -1296,6 +1801,7 @@ async function readActiveBranchPage(host, viewId, input) {
1296
1801
  revision: indexed.revision,
1297
1802
  head: indexed.head,
1298
1803
  operationId: indexed.operationId,
1804
+ ...(indexed.membershipBase ? { membershipBase: indexed.membershipBase } : {}),
1299
1805
  ...(indexed.logicalCount !== undefined ? { logicalCount: indexed.logicalCount } : {}),
1300
1806
  ...(indexed.conflict ? { conflict: true } : {}),
1301
1807
  }
@@ -1312,6 +1818,7 @@ async function readActiveBranchPage(host, viewId, input) {
1312
1818
  revision: current.revision,
1313
1819
  head: current.head,
1314
1820
  operationId: current.operationId,
1821
+ ...(current.membershipBase ? { membershipBase: current.membershipBase } : {}),
1315
1822
  ...(current.logicalCount !== undefined ? { logicalCount: current.logicalCount } : {}),
1316
1823
  ...(current.conflict ? { conflict: true } : {}),
1317
1824
  }
@@ -1340,7 +1847,7 @@ async function readActiveBranchPage(host, viewId, input) {
1340
1847
  if (before.viewId !== directory.state.viewId || before.revision > directory.state.revision ||
1341
1848
  before.position < 0 || before.turnId.length !== 16 || before.headTurnId.length !== 16 ||
1342
1849
  !cursorRow?.segments.some(segment => equal(segment.turnId, before.turnId)) ||
1343
- !directory.rows.some(row => row.segments.some(segment => equal(segment.turnId, before.headTurnId))))
1850
+ !await activeCursorHead(host, directory, before.headTurnId))
1344
1851
  throw new StoreError('stale', 'active branch changed before older page was read');
1345
1852
  }
1346
1853
  const startPosition = input.before
@@ -1351,16 +1858,12 @@ async function readActiveBranchPage(host, viewId, input) {
1351
1858
  const endPosition = Math.min(totalCount, input.before ? input.before.position + 1 : totalCount, startPosition + limit);
1352
1859
  const selectedIds = new Set(directory.rows.slice(startPosition, endPosition).map(row => row.businessId));
1353
1860
  const segments = directory.rows.filter(row => selectedIds.has(row.businessId)).flatMap(row => row.segments);
1354
- let complete = directory.complete;
1355
- const page = await readBranchPageMessages(host, segments);
1356
- const messages = page.messages;
1357
- complete &&= page.complete;
1861
+ const complete = directory.complete;
1358
1862
  let cursor = null;
1359
1863
  if (startPosition > 0) {
1360
1864
  if (input.before) {
1361
1865
  const headId = directory.state.head ? await branchTurnIdByIdentity(host, directory.state.head) : undefined;
1362
- const activeIds = new Set(directory.rows.flatMap(row => row.segments.map(segment => hexBytes(segment.turnId))));
1363
- if (!headId || !activeIds.has(hexBytes(input.before.headTurnId))) {
1866
+ if (!headId || !await activeCursorHead(host, directory, input.before.headTurnId)) {
1364
1867
  throw new StoreError('stale', 'active branch changed before older page was read');
1365
1868
  }
1366
1869
  const olderRow = directory.rows[startPosition - 1];
@@ -1393,13 +1896,89 @@ async function readActiveBranchPage(host, viewId, input) {
1393
1896
  state: directory.state,
1394
1897
  totalCount,
1395
1898
  startPosition,
1396
- messages,
1899
+ segments,
1397
1900
  hasMoreOlder: startPosition > 0,
1398
1901
  cursor,
1399
1902
  complete,
1400
1903
  };
1401
1904
  }
1905
+ // Page/result data must not retain a closed host and its body cache.
1906
+ const branchHandleTokens = new WeakMap();
1907
+ function branchHandleToken(host) {
1908
+ let token = branchHandleTokens.get(host);
1909
+ if (!token) {
1910
+ token = {};
1911
+ branchHandleTokens.set(host, token);
1912
+ }
1913
+ return token;
1914
+ }
1915
+ const branchDirectories = new WeakMap();
1916
+ const branchTransitions = new WeakMap();
1917
+ function directoryMember(row) {
1918
+ return { businessId: row.businessId, segmentId: row.segmentId, turnId: row.turnId.slice() };
1919
+ }
1920
+ function rememberBranchDirectory(host, page) {
1921
+ branchDirectories.set(page.state, {
1922
+ ownerToken: branchHandleToken(host), state: structuredClone(page.state), totalCount: page.totalCount, startPosition: page.startPosition,
1923
+ complete: page.complete, members: page.messages.map(directoryMember), cursor: structuredClone(page.cursor),
1924
+ });
1925
+ }
1926
+ /** Apply only directory membership certified by this host. No old body is read,
1927
+ * returned or certified; consumers retain their own checkpoint-bound snapshots. */
1928
+ function advanceBranchDirectory(host, page, result, limit) {
1929
+ const proof = branchDirectories.get(page.state), change = branchTransitions.get(result);
1930
+ if (!proof || !change || proof.ownerToken !== branchHandleToken(host) || change.ownerToken !== branchHandleToken(host) || !proof.complete || !page.complete ||
1931
+ !Number.isSafeInteger(limit) || limit < 1 || limit > 500 ||
1932
+ page.totalCount !== proof.totalCount || page.startPosition !== proof.startPosition ||
1933
+ page.state.viewId !== proof.state.viewId || page.state.revision !== proof.state.revision ||
1934
+ page.state.logicalCount !== proof.state.logicalCount || page.state.operationId !== proof.state.operationId || !!page.state.conflict !== !!proof.state.conflict ||
1935
+ !branchStateEqual(page.state.head, proof.state.head) ||
1936
+ change.state.viewId !== proof.state.viewId || change.beforeRevision !== proof.state.revision ||
1937
+ !branchStateEqual(change.beforeHead, proof.state.head) ||
1938
+ change.state.logicalCount !== BigInt(proof.totalCount) + 1n ||
1939
+ page.messages.length !== proof.members.length ||
1940
+ page.messages.some((row, index) => {
1941
+ const expected = proof.members[index];
1942
+ return row.businessId !== expected.businessId || row.segmentId !== expected.segmentId || !equal(row.turnId, expected.turnId);
1943
+ }))
1944
+ return;
1945
+ const businessIds = [...new Set(proof.members.map(row => row.businessId))];
1946
+ if (proof.startPosition + businessIds.length !== proof.totalCount || businessIds.includes(change.message.businessId))
1947
+ return;
1948
+ const totalCount = proof.totalCount + 1;
1949
+ if (!Number.isSafeInteger(totalCount))
1950
+ return;
1951
+ const startPosition = Math.max(0, totalCount - limit), dropped = startPosition - proof.startPosition;
1952
+ if (dropped < 0 || dropped > businessIds.length)
1953
+ return;
1954
+ const retainedIds = new Set(businessIds.slice(dropped));
1955
+ const retainedFrom = dropped === businessIds.length ? proof.members.length :
1956
+ proof.members.findIndex(row => row.businessId === businessIds[dropped]);
1957
+ let cursor = null;
1958
+ if (startPosition > 0) {
1959
+ const boundary = dropped > 0
1960
+ ? proof.members.find(row => row.businessId === businessIds[dropped - 1] && row.segmentId === 'primary')
1961
+ : proof.cursor;
1962
+ if (!boundary)
1963
+ return;
1964
+ const pending = [...proof.members, ...(proof.cursor?.pendingSegments ?? [])]
1965
+ .filter(row => !retainedIds.has(row.businessId) && compareBytes(row.turnId, boundary.turnId) > 0)
1966
+ .sort((a, b) => compareBytes(b.turnId, a.turnId));
1967
+ const unique = new Map(pending.map(row => [hexBytes(row.turnId), directoryMember(row)]));
1968
+ cursor = { viewId: change.state.viewId, revision: change.state.revision,
1969
+ position: startPosition - 1, turnId: boundary.turnId.slice(), headTurnId: change.message.turnId.slice(),
1970
+ pendingSegments: [...unique.values()] };
1971
+ }
1972
+ const state = structuredClone(change.state);
1973
+ branchDirectories.set(state, { ownerToken: branchHandleToken(host), state: structuredClone(state), totalCount, startPosition,
1974
+ complete: true, members: [...proof.members.slice(retainedFrom).map(directoryMember), directoryMember(change.message)],
1975
+ cursor: structuredClone(cursor) });
1976
+ return { state, totalCount, startPosition, complete: true, hasMoreOlder: startPosition > 0, cursor,
1977
+ retainedFrom, message: structuredClone(change.message), through: change.through };
1978
+ }
1402
1979
  async function readLinearActiveBranchPage(host, state, input, limit) {
1980
+ if (state.membershipBase)
1981
+ return undefined;
1403
1982
  const totalBigInt = state.logicalCount ?? 0n;
1404
1983
  if (totalBigInt > BigInt(Number.MAX_SAFE_INTEGER))
1405
1984
  throw new StoreError('invalid', 'active branch is too large to index');
@@ -1407,11 +1986,11 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
1407
1986
  const headId = state.head ? await branchTurnIdByIdentity(host, state.head) : undefined;
1408
1987
  if (state.head && !headId)
1409
1988
  return {
1410
- state, totalCount, startPosition: Math.max(0, totalCount - limit), messages: [],
1989
+ state, totalCount, startPosition: Math.max(0, totalCount - limit), segments: [],
1411
1990
  hasMoreOlder: totalCount > limit, cursor: null, complete: false,
1412
1991
  };
1413
1992
  if (!headId)
1414
- return { state, totalCount, startPosition: 0, messages: [], hasMoreOlder: false, cursor: null, complete: true };
1993
+ return { state, totalCount, startPosition: 0, segments: [], hasMoreOlder: false, cursor: null, complete: true };
1415
1994
  let startPosition = input.before
1416
1995
  ? Math.max(0, input.before.position - limit + 1)
1417
1996
  : Math.max(0, totalCount - limit);
@@ -1478,6 +2057,7 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
1478
2057
  collected = [...newerSuccessors, ...collected];
1479
2058
  }
1480
2059
  const selected = new Map();
2060
+ const headers = new Map();
1481
2061
  let olderCursor = null;
1482
2062
  let complete = true;
1483
2063
  const seen = new Set();
@@ -1504,6 +2084,7 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
1504
2084
  complete = false;
1505
2085
  break;
1506
2086
  }
2087
+ headers.set(turnKey, header);
1507
2088
  const expectedParent = metadata.baseTurn ? unhexBytes(metadata.baseTurn, 16) : undefined;
1508
2089
  if (header.parents.length !== (expectedParent ? 1 : 0) || (expectedParent && !equal(header.parents[0].id, expectedParent)))
1509
2090
  return undefined;
@@ -1543,16 +2124,14 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
1543
2124
  segmentGroups.set(segment.businessId, group);
1544
2125
  }
1545
2126
  const orderedSegments = [...selected].sort((a, b) => a[1] - b[1]).flatMap(([businessId]) => segmentGroups.get(businessId) ?? []);
1546
- const page = await readBranchPageMessages(host, orderedSegments);
1547
- const messages = page.messages;
1548
- complete &&= page.complete;
1549
2127
  const actualStart = selected.size ? Math.min(...selected.values()) : startPosition;
1550
2128
  const cursor = olderCursor && actualStart > 0 ? olderCursor : null;
1551
2129
  return {
1552
2130
  state,
1553
2131
  totalCount,
1554
2132
  startPosition: actualStart,
1555
- messages,
2133
+ segments: orderedSegments,
2134
+ headers,
1556
2135
  hasMoreOlder: cursor !== null || (!complete && actualStart > 0),
1557
2136
  cursor,
1558
2137
  complete,
@@ -1659,18 +2238,26 @@ function publicationPort(host) {
1659
2238
  };
1660
2239
  }
1661
2240
  const historyCatchups = new WeakMap();
2241
+ const settledNodeHistory = new WeakMap();
2242
+ const contentCheckpoints = new WeakMap();
1662
2243
  function catchUpHistory(host) {
1663
2244
  const pending = historyCatchups.get(host);
1664
2245
  if (pending)
1665
2246
  return pending;
1666
2247
  const task = (async () => {
2248
+ const settled = host instanceof NodeLodyHistory ? settledNodeHistory.get(host) : undefined;
2249
+ if (settled !== undefined && !(await localEvents(host, settled, 1)).length)
2250
+ return;
1667
2251
  for (;;) {
1668
2252
  while (await host.indexPage()) { /* binding rows and local cursor commit together */ }
1669
2253
  await catchUpPublications(publicationPort(host));
1670
2254
  const [rawBinding, rawPublication] = await indexValues(host, [NODE_CURSOR, PUBLICATION_CURSOR]);
1671
2255
  const through = processedCursor(rawBinding);
1672
- if (through === processedCursor(rawPublication) && !(await localEvents(host, through, 1)).length)
2256
+ if (through === processedCursor(rawPublication) && !(await localEvents(host, through, 1)).length) {
2257
+ if (host instanceof NodeLodyHistory)
2258
+ settledNodeHistory.set(host, through);
1673
2259
  return;
2260
+ }
1674
2261
  }
1675
2262
  })();
1676
2263
  historyCatchups.set(host, task);
@@ -1746,13 +2333,14 @@ function identityValue(id) {
1746
2333
  function parentValue(parent) {
1747
2334
  return new Map([['id', hexBytes(parent.id)], ['hash', hexBytes(parent.hash)]]);
1748
2335
  }
1749
- function decodeIdentity(value) {
2336
+ function decodeIdentity(value, reserved = false) {
1750
2337
  const row = asMap(value, 'command identity');
1751
2338
  const kind = row.get('kind'), businessId = row.get('businessId'), segmentId = row.get('segmentId');
1752
2339
  if (typeof kind !== 'string' || !knownKind(kind) || typeof businessId !== 'string' || typeof segmentId !== 'string')
1753
2340
  throw invalid('command identity');
1754
2341
  const identity = { kind, businessId, segmentId };
1755
- assertWritableIdentity(identity);
2342
+ if (!reserved)
2343
+ assertWritableIdentity(identity);
1756
2344
  keyOf(identity);
1757
2345
  return identity;
1758
2346
  }
@@ -1875,7 +2463,7 @@ function publishedIdentity(raw, id) {
1875
2463
  return { businessId: text(businessId), segmentId: text(segmentId), turnId: id.slice() };
1876
2464
  }
1877
2465
  function messageKey(businessId, segmentId) { return decodeUtf8(keyOf({ kind: 'message', businessId, segmentId })); }
1878
- async function writeIndexed(host, writes, puts, expectedEventCursor) {
2466
+ async function writeIndexed(host, writes, puts, expectedEventCursor, requireLocalInterval = false) {
1879
2467
  if (!writes.length && !puts.length)
1880
2468
  return;
1881
2469
  if (host instanceof LodyHistory) {
@@ -1894,7 +2482,7 @@ async function writeIndexed(host, writes, puts, expectedEventCursor) {
1894
2482
  }), puts, expectedEventCursor);
1895
2483
  return;
1896
2484
  }
1897
- await host.stream.writeBatch(writes.map((w) => {
2485
+ return host.stream.writeBatch(writes.map((w) => {
1898
2486
  if (w.kind === 'createOnce')
1899
2487
  return { kind: 'createOnce', key: w.key, parents: w.parents, contentJson: decodeUtf8(encodeJson(w.content)) };
1900
2488
  if (w.kind === 'seal')
@@ -1906,7 +2494,7 @@ async function writeIndexed(host, writes, puts, expectedEventCursor) {
1906
2494
  if (w.kind === 'editPath')
1907
2495
  return { kind: 'edit', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: w.path, contentJson: decodeUtf8(encodeJson(w.value)) }] };
1908
2496
  return { kind: 'edit', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: [{ key: 'content' }], contentJson: decodeUtf8(encodeJson(w.value)) }] };
1909
- }), { indexPuts: puts, expectedEventCursor });
2497
+ }), { indexPuts: puts, expectedEventCursor, ...(requireLocalInterval ? { requireLocalInterval: true } : {}) });
1910
2498
  }
1911
2499
  async function maybePublishAccept(host, input, options, turnId) {
1912
2500
  if (options?.publish === false || input.kind !== 'message')