@agentshouse/mdruntime 0.1.0-c1db74d14e5fa → 0.1.0-c24132a516ded

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/AGENTS.md +246 -242
  2. package/README.md +9 -8
  3. package/dist/adapter.d.ts +53 -23
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/attached-model.d.ts +4 -1
  6. package/dist/attached-model.d.ts.map +1 -1
  7. package/dist/attached-model.js +13 -3
  8. package/dist/bootstrap.d.ts +2 -1
  9. package/dist/bootstrap.d.ts.map +1 -1
  10. package/dist/bootstrap.js +62 -27
  11. package/dist/change-set.d.ts +5 -2
  12. package/dist/change-set.d.ts.map +1 -1
  13. package/dist/change-set.js +10 -8
  14. package/dist/change.d.ts +31 -1
  15. package/dist/change.d.ts.map +1 -1
  16. package/dist/change.js +10 -1
  17. package/dist/chat/earlier.d.ts +10 -0
  18. package/dist/chat/earlier.d.ts.map +1 -0
  19. package/dist/chat/earlier.js +54 -0
  20. package/dist/chat/house.d.ts +25 -0
  21. package/dist/chat/house.d.ts.map +1 -0
  22. package/dist/chat/house.js +38 -0
  23. package/dist/chat/input.d.ts +3 -1
  24. package/dist/chat/input.d.ts.map +1 -1
  25. package/dist/chat/input.js +11 -18
  26. package/dist/chat/kit.d.ts +2 -1
  27. package/dist/chat/kit.d.ts.map +1 -1
  28. package/dist/chat/kit.js +3 -3
  29. package/dist/chat/list.d.ts +3 -1
  30. package/dist/chat/list.d.ts.map +1 -1
  31. package/dist/chat/list.js +47 -6
  32. package/dist/chat/markdown.d.ts +1 -0
  33. package/dist/chat/markdown.d.ts.map +1 -1
  34. package/dist/chat/markdown.js +78 -20
  35. package/dist/chat/message.d.ts +1 -0
  36. package/dist/chat/message.d.ts.map +1 -1
  37. package/dist/chat/message.js +55 -10
  38. package/dist/chat/messages.d.ts +9 -1
  39. package/dist/chat/messages.d.ts.map +1 -1
  40. package/dist/chat/messages.js +67 -28
  41. package/dist/chat/name.d.ts +1 -0
  42. package/dist/chat/name.d.ts.map +1 -1
  43. package/dist/chat/name.js +1 -1
  44. package/dist/chat/opened.d.ts +1 -0
  45. package/dist/chat/opened.d.ts.map +1 -1
  46. package/dist/chat/opened.js +2 -0
  47. package/dist/chat/overlay.d.ts +1 -0
  48. package/dist/chat/overlay.d.ts.map +1 -1
  49. package/dist/chat/overlay.js +11 -5
  50. package/dist/chat/parts.d.ts +1 -0
  51. package/dist/chat/parts.d.ts.map +1 -1
  52. package/dist/chat/parts.js +3 -2
  53. package/dist/chat/pieces.d.ts +62 -0
  54. package/dist/chat/pieces.d.ts.map +1 -0
  55. package/dist/chat/pieces.js +1110 -0
  56. package/dist/chat/provider.d.ts +7 -2
  57. package/dist/chat/provider.d.ts.map +1 -1
  58. package/dist/chat/provider.js +104 -105
  59. package/dist/chat/question.d.ts +1 -1
  60. package/dist/chat/question.d.ts.map +1 -1
  61. package/dist/chat/question.js +7 -18
  62. package/dist/chat/ready.d.ts +5 -1
  63. package/dist/chat/ready.d.ts.map +1 -1
  64. package/dist/chat/ready.js +7 -5
  65. package/dist/chat/room-file.d.ts +8 -0
  66. package/dist/chat/room-file.d.ts.map +1 -0
  67. package/dist/chat/room-file.js +67 -0
  68. package/dist/chat/steady.d.ts +3 -0
  69. package/dist/chat/steady.d.ts.map +1 -0
  70. package/dist/chat/steady.js +26 -0
  71. package/dist/chat/style.d.ts.map +1 -1
  72. package/dist/chat/style.js +5 -1
  73. package/dist/chat.d.ts +3 -2
  74. package/dist/chat.d.ts.map +1 -1
  75. package/dist/chat.js +2 -2
  76. package/dist/client.d.ts +11 -3
  77. package/dist/client.d.ts.map +1 -1
  78. package/dist/client.js +19 -5
  79. package/dist/collection.d.ts +6 -5
  80. package/dist/collection.d.ts.map +1 -1
  81. package/dist/collection.js +166 -85
  82. package/dist/connection.d.ts +17 -5
  83. package/dist/connection.d.ts.map +1 -1
  84. package/dist/connection.js +1212 -368
  85. package/dist/conversation.d.ts +15 -2
  86. package/dist/conversation.d.ts.map +1 -1
  87. package/dist/conversation.js +278 -74
  88. package/dist/digest.d.ts +2 -0
  89. package/dist/digest.d.ts.map +1 -0
  90. package/dist/digest.js +100 -0
  91. package/dist/durability.d.ts +1 -1
  92. package/dist/entry.d.ts +2 -1
  93. package/dist/entry.d.ts.map +1 -1
  94. package/dist/entry.js +5 -4
  95. package/dist/file.d.ts +2 -10
  96. package/dist/file.d.ts.map +1 -1
  97. package/dist/file.js +3 -120
  98. package/dist/host.d.ts +9 -7
  99. package/dist/host.d.ts.map +1 -1
  100. package/dist/host.js +67 -14
  101. package/dist/index.d.ts +11 -7
  102. package/dist/index.d.ts.map +1 -1
  103. package/dist/index.js +4 -0
  104. package/dist/memory.d.ts +7 -3
  105. package/dist/memory.d.ts.map +1 -1
  106. package/dist/memory.js +33 -16
  107. package/dist/model.d.ts +3 -2
  108. package/dist/model.d.ts.map +1 -1
  109. package/dist/model.js +1 -1
  110. package/dist/name.d.ts +4 -0
  111. package/dist/name.d.ts.map +1 -0
  112. package/dist/name.js +122 -0
  113. package/dist/observation.d.ts +2 -0
  114. package/dist/observation.d.ts.map +1 -1
  115. package/dist/observation.js +9 -3
  116. package/dist/outcome.d.ts +27 -2
  117. package/dist/outcome.d.ts.map +1 -1
  118. package/dist/outcome.js +25 -0
  119. package/dist/overlay.d.ts +6 -5
  120. package/dist/overlay.d.ts.map +1 -1
  121. package/dist/overlay.js +223 -134
  122. package/dist/query.d.ts +30 -2
  123. package/dist/query.d.ts.map +1 -1
  124. package/dist/query.js +37 -7
  125. package/dist/reach.d.ts +6 -3
  126. package/dist/reach.d.ts.map +1 -1
  127. package/dist/reach.js +156 -38
  128. package/dist/react.d.ts +3 -3
  129. package/dist/react.d.ts.map +1 -1
  130. package/dist/react.js +7 -17
  131. package/dist/read-side.d.ts +6 -4
  132. package/dist/read-side.d.ts.map +1 -1
  133. package/dist/read-side.js +755 -215
  134. package/dist/readiness.d.ts +1 -1
  135. package/dist/readiness.d.ts.map +1 -1
  136. package/dist/reads.d.ts +11 -0
  137. package/dist/reads.d.ts.map +1 -0
  138. package/dist/reads.js +98 -0
  139. package/dist/recovery.d.ts +2 -2
  140. package/dist/recovery.d.ts.map +1 -1
  141. package/dist/recovery.js +8 -7
  142. package/dist/refresh.d.ts +4 -4
  143. package/dist/refresh.d.ts.map +1 -1
  144. package/dist/refresh.js +41 -16
  145. package/dist/replica.d.ts +12 -7
  146. package/dist/replica.d.ts.map +1 -1
  147. package/dist/replica.js +133 -74
  148. package/dist/room-draft.d.ts +16 -2
  149. package/dist/room-draft.d.ts.map +1 -1
  150. package/dist/room-draft.js +32 -25
  151. package/dist/rows.d.ts +3 -1
  152. package/dist/rows.d.ts.map +1 -1
  153. package/dist/rows.js +8 -1
  154. package/dist/save.d.ts +47 -9
  155. package/dist/save.d.ts.map +1 -1
  156. package/dist/save.js +501 -165
  157. package/dist/search.d.ts +29 -8
  158. package/dist/search.d.ts.map +1 -1
  159. package/dist/search.js +150 -17
  160. package/dist/seed.d.ts +16 -0
  161. package/dist/seed.d.ts.map +1 -0
  162. package/dist/seed.js +75 -0
  163. package/dist/shared.d.ts +9 -1
  164. package/dist/shared.d.ts.map +1 -1
  165. package/dist/shared.js +134 -41
  166. package/dist/store.d.ts +30 -17
  167. package/dist/store.d.ts.map +1 -1
  168. package/dist/store.js +489 -430
  169. package/dist/tables.d.ts +181 -0
  170. package/dist/tables.d.ts.map +1 -0
  171. package/dist/tables.js +309 -0
  172. package/dist/turn.d.ts +5 -3
  173. package/dist/turn.d.ts.map +1 -1
  174. package/dist/turn.js +35 -13
  175. package/dist/windows.d.ts +21 -0
  176. package/dist/windows.d.ts.map +1 -0
  177. package/dist/windows.js +84 -0
  178. package/dist/wire.d.ts +159 -33
  179. package/dist/wire.d.ts.map +1 -1
  180. package/dist/wire.js +53 -32
  181. package/package.json +6 -2
  182. package/dist/acquisition.d.ts +0 -14
  183. package/dist/acquisition.d.ts.map +0 -1
  184. package/dist/acquisition.js +0 -24
@@ -1,36 +1,48 @@
1
- import { attachedModel } from './attached-model.js';
1
+ import { roomTarget, target } from '@agentshouse/mdmodel';
2
+ import { attachedModel, NO_ROOM_TYPES, roomTypesOf } from './attached-model.js';
2
3
  import { cached, modelTypes, NO_MODEL, sameModel, } from './model.js';
3
- import { observing } from './observation.js';
4
- import { filterOf, identityOf, planOf, } from './query.js';
4
+ import { observing, whole } from './observation.js';
5
+ import { filterOf, identityOf, planOf, plain, queryKey, } from './query.js';
5
6
  import { createReadSide } from './read-side.js';
6
- import { markdownPath, roomOfKey } from './rows.js';
7
+ import { seededResult } from './seed.js';
8
+ import { documentKey, markdownPath, roomOfKey } from './rows.js';
7
9
  import { createSearchIndex, searchPlanOf, } from './search.js';
10
+ import { capped, MAXIMUM_WINDOW } from './windows.js';
8
11
  import { bootstrapRoom } from './bootstrap.js';
9
- import { changeSet, entering, mergeChangeSets } from './change-set.js';
12
+ import { changeSet, changing, entering, mergeChangeSets } from './change-set.js';
10
13
  import { createConversationStore, } from './conversation.js';
11
- import { queuedFile } from './change.js';
14
+ import { leaving as leavingIn, partnerOf, queuedFile, } from './change.js';
12
15
  import { indexReferrers, referencesIndexed, validRoot, } from './collection.js';
13
16
  import { runtimeError } from './failure.js';
14
17
  import { createLog } from './log.js';
15
18
  import { binaryRecord } from './binary.js';
16
- import { absentBinary, binaryAnswer, calledResult, failure, historyAnswer, undeclared, UNCERTAIN, } from './outcome.js';
19
+ import { ABSENT_TARGET, absentBinary, binaryAnswer, binaryLinkAnswer, calledResult, failure, historyAnswer, LOCKED_UNREADABLE, lockedRoom, undeclared, UNCERTAIN, UNREADABLE, } from './outcome.js';
17
20
  import { createRecovery } from './recovery.js';
21
+ import { doorReads } from './reads.js';
18
22
  import { refreshRoom } from './refresh.js';
19
- import { buildBatch, joined, limitedIn, requeued } from './save.js';
20
- import { applyReturned, compositionOf, confirmedOf, landed, readReclassified, replicaOf, sameMembership, withdrawals, } from './replica.js';
21
- import { binaryBase, changedParts, changesOf, held, heldFile, joinedDraft, readParts, returnedBy, returnedInto, staleWrite, underneath, withdrawnDrafts, } from './room-draft.js';
23
+ import { buildBatch, buildMove, joined, limiting, queuedDocuments, requeuing, } from './save.js';
24
+ import { applyReturned, compositionOf, confirmedOf, landed, readReclassified, replicating, sameMembership, standing, } from './replica.js';
25
+ import { binaryBase, changedParts, changesOf, held, heldFile, joinedDraft, moveTarget, readParts, returnedBy, returnedInto, staleWrite, underneath, withdrawnDrafts, } from './room-draft.js';
22
26
  import { same, saving, STARTING, transferring, } from './status.js';
23
27
  import { detectStorageLoss, nextGeneration } from './durability.js';
24
- import { demanded, narrower, WHOLE_DEMAND, wider } from './acquisition.js';
25
28
  import { readinessOf, SETTLED_ROOMS, } from './readiness.js';
26
29
  import { FencedMap } from './fence.js';
27
- import { tally } from './shared.js';
28
- import { inChunks, ROW_WEIGHT, yielded } from './turn.js';
30
+ import { keysIn, tallying } from './shared.js';
31
+ import { finished, inChunks, ROW_WEIGHT, stepped, yielded } from './turn.js';
29
32
  import { identityTime, roomDraftRevision } from './identity.js';
30
33
  import { beneath, normalize } from './paths.js';
31
34
  import { openRuntimeStore, } from './store.js';
32
35
  import { unconfirmed } from './transfer.js';
33
36
  import { governs, holds, narrowed, planReach, } from './reach.js';
37
+ function roomsAlone(plan) {
38
+ return (plan.reach === null &&
39
+ plan.root.types === null &&
40
+ plan.root.where === null &&
41
+ plan.root.pathPrefix === null &&
42
+ plan.paths === null &&
43
+ plan.hop === null &&
44
+ plan.backlinks === null);
45
+ }
34
46
  function within(root, path) {
35
47
  return root === '' || beneath(root, path);
36
48
  }
@@ -48,6 +60,12 @@ const OPENING_LANE = 'opening';
48
60
  const CONVERSATION_LANE = 'conversations';
49
61
  const ROOM_READS = 256;
50
62
  const ROOM_ATTEMPTS = 16;
63
+ // A Room that locks offline stays readable this long after the connection drops, so a laptop waking or changing network keeps working while a disconnected device locks soon after.
64
+ const LOCK_GRACE_MS = 120_000;
65
+ function operationOf(input) {
66
+ const operation = input?.operation_id;
67
+ return typeof operation === 'string' ? operation : null;
68
+ }
51
69
  const outside = new Map();
52
70
  function outsideOf(roots) {
53
71
  const key = JSON.stringify(roots);
@@ -73,8 +91,12 @@ function abandonedOn(signal) {
73
91
  function roomLane(locator) {
74
92
  return `room ${locator}`;
75
93
  }
94
+ function pendingKey(locator, id) {
95
+ return `${locator}\u0000${id}`;
96
+ }
76
97
  export function composeRuntime(options) {
77
98
  const localSaves = options.adapter.localSaves === true;
99
+ const roomTypes = roomTypesOf(options.adapter.roomTypes);
78
100
  let authorization = options.authorization;
79
101
  let opening;
80
102
  let store;
@@ -87,6 +109,8 @@ export function composeRuntime(options) {
87
109
  const replicas = new FencedMap(isFenced);
88
110
  const queuesWithoutReplica = new FencedMap(isFenced);
89
111
  const pendings = new Map();
112
+ const seeds = new Map();
113
+ const seedWatchers = new Map();
90
114
  const roomDrafts = new FencedMap(isFenced);
91
115
  const presentations = new Map();
92
116
  let limits = [];
@@ -99,6 +123,7 @@ export function composeRuntime(options) {
99
123
  const liveModels = new FencedMap(isModelFenced);
100
124
  const invalidModels = new Set();
101
125
  const discovered = new Map();
126
+ const reads = doorReads(options.adapter, (locator) => discovered.get(locator), () => generation);
102
127
  let roomsListed = false;
103
128
  const scopedRefusals = new Map();
104
129
  const sourceRefusals = new Map();
@@ -135,6 +160,7 @@ export function composeRuntime(options) {
135
160
  let handed = false;
136
161
  const recovery = (options.recovery ?? createRecovery()).scope(ROOM_ATTEMPTS);
137
162
  const repairing = new Set();
163
+ const calling = new Set();
138
164
  const repairable = new Map();
139
165
  let outcomeRetention = null;
140
166
  const answering = new Map();
@@ -145,6 +171,7 @@ export function composeRuntime(options) {
145
171
  let discovering = null;
146
172
  let opened = null;
147
173
  const owed = new Set();
174
+ const reloadsDue = new Map();
148
175
  const lanes = new Map();
149
176
  let roomReads = { generation, free: ROOM_READS, waiting: [] };
150
177
  const working = new Set();
@@ -160,6 +187,9 @@ export function composeRuntime(options) {
160
187
  let withdrawConversations;
161
188
  let currencyQueued = null;
162
189
  let socketOpen = false;
190
+ const confirmed = new Set();
191
+ let lockGrace = null;
192
+ const lockListeners = new Set();
163
193
  let serviceMode = 'open';
164
194
  let haltedRefusal = false;
165
195
  let openSignals = 0;
@@ -171,8 +201,6 @@ export function composeRuntime(options) {
171
201
  const unpreparedDemand = new Set();
172
202
  const unindexable = new Set();
173
203
  let preparing = false;
174
- let demand = WHOLE_DEMAND;
175
- let narrowing = null;
176
204
  let targets = {};
177
205
  let persistence = options.shell.persistence;
178
206
  let capacity = null;
@@ -189,7 +217,7 @@ export function composeRuntime(options) {
189
217
  durably,
190
218
  stream: () => options.adapter.conversations,
191
219
  publish: publishChangeSet,
192
- online: () => !status.providerUnreachable && refusal === null,
220
+ online: () => connectionOf() !== 'unreachable' && refusal === null,
193
221
  closed: () => closed,
194
222
  unanswered: resendLater,
195
223
  expired: (operation) => pastHorizon(operation),
@@ -255,6 +283,15 @@ export function composeRuntime(options) {
255
283
  const value = presentations.get(app);
256
284
  return value === undefined ? null : structuredClone(value);
257
285
  }
286
+ function keepPresentation(app, next) {
287
+ return exclusive(async () => {
288
+ const local = await openLocal();
289
+ const stored = next(presentations.get(app));
290
+ await local.present({ app, value: stored });
291
+ presentations.set(app, stored);
292
+ publishChangeSet(changeSet('', null, null, { presentation: app }));
293
+ });
294
+ }
258
295
  function emitPresentation(app) {
259
296
  if (closed)
260
297
  return;
@@ -304,20 +341,74 @@ export function composeRuntime(options) {
304
341
  }
305
342
  function documentsIn(locator) {
306
343
  const replica = replicas.get(locator);
307
- if (replica === undefined)
308
- return 0;
309
- const roots = replica.confirmed.record.typedSelection?.roots ?? [];
310
- const weighed = outsideOf(roots);
311
- return (tally(replica.visible.documents, weighed.documents) +
312
- tally(replica.visible.binaries, weighed.binaries));
344
+ return replica === undefined ? 0 : finished(counting(replica));
345
+ }
346
+ function* counting(replica) {
347
+ const weighed = outsideOf(replica.confirmed.record.typedSelection?.roots ?? []);
348
+ return ((yield* tallying(replica.visible.documents, weighed.documents)) +
349
+ (yield* tallying(replica.visible.binaries, weighed.binaries)));
313
350
  }
314
351
  function listed() {
315
352
  return structuredClone([...rooms.values()].map((room) => {
316
353
  const documents = documentsIn(room.locator);
317
354
  counted.set(room.locator, documents);
318
- return { ...room, documents };
355
+ return locked(room.locator)
356
+ ? {
357
+ ...room,
358
+ model: modelTypes(NO_MODEL),
359
+ typedSelection: null,
360
+ documents: 0,
361
+ locked: true,
362
+ }
363
+ : { ...room, documents, locked: false };
319
364
  }));
320
365
  }
366
+ function locked(locator) {
367
+ return rooms.get(locator)?.replica.offline === 'locked' && !confirmed.has(locator);
368
+ }
369
+ function lockedRooms() {
370
+ return [...rooms.keys()].filter(locked).sort();
371
+ }
372
+ function relocked(before) {
373
+ const after = lockedRooms();
374
+ if (JSON.stringify(after) === JSON.stringify(before))
375
+ return;
376
+ journal.record(`locked ${after.length}`);
377
+ emitRooms();
378
+ for (const notify of [...lockListeners])
379
+ notify();
380
+ }
381
+ function confirmLocks(listed) {
382
+ if (!socketOpen)
383
+ return;
384
+ for (const room of listed) {
385
+ if (room.replica.admission === 'admitted')
386
+ confirmed.add(room.locator);
387
+ }
388
+ }
389
+ function connectionLost() {
390
+ if (lockGrace !== null || closed)
391
+ return;
392
+ lockGrace = setTimeout(() => {
393
+ lockGrace = null;
394
+ if (socketOpen || closed)
395
+ return;
396
+ const before = lockedRooms();
397
+ confirmed.clear();
398
+ relocked(before);
399
+ }, LOCK_GRACE_MS);
400
+ }
401
+ function connectionLive() {
402
+ if (lockGrace !== null)
403
+ clearTimeout(lockGrace);
404
+ lockGrace = null;
405
+ }
406
+ function watchLocks(notify) {
407
+ lockListeners.add(notify);
408
+ return () => {
409
+ lockListeners.delete(notify);
410
+ };
411
+ }
321
412
  function roomFacts(reach = null) {
322
413
  const held = [...rooms.values()]
323
414
  .filter((room) => holds(reach, room.locator))
@@ -366,7 +457,7 @@ export function composeRuntime(options) {
366
457
  if (closed)
367
458
  return;
368
459
  queueReadiness();
369
- const next = status.state === 'synced' && demand.conversations && !conversations.current()
460
+ const next = status.state === 'synced' && !conversations.current()
370
461
  ? { ...status, state: 'syncing' }
371
462
  : status;
372
463
  if (same(shown, next))
@@ -375,17 +466,17 @@ export function composeRuntime(options) {
375
466
  for (const listener of statusListeners)
376
467
  listener(shown);
377
468
  }
378
- function entryOf(batch) {
469
+ function entryOf(locator, batch) {
379
470
  if (localSaves)
380
471
  return Object.freeze({ batch, state: 'local' });
381
- const state = pendings.get(batch.id);
472
+ const state = pendings.get(pendingKey(locator, batch.id));
382
473
  if (state?.accepted !== undefined) {
383
474
  return Object.freeze({ batch, state: 'accepted', roomVersion: state.accepted });
384
475
  }
385
476
  return Object.freeze({ batch, ...(state?.submission ?? { state: 'waiting' }) });
386
477
  }
387
478
  function entriesOf(locator) {
388
- return (replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? []).map(entryOf);
479
+ return (replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? []).map((batch) => entryOf(locator, batch));
389
480
  }
390
481
  function emitQueue(locator) {
391
482
  const entries = entriesOf(locator);
@@ -399,8 +490,12 @@ export function composeRuntime(options) {
399
490
  ...set,
400
491
  documents: set.documents.filter(({ locator }) => prepared.has(locator) || projecting.has(locator)),
401
492
  };
402
- readSide.apply(held);
403
- searchIndex.changed(held);
493
+ const applied = readSide.apply(held, () => searchIndex.changed(held));
494
+ if (applied instanceof Promise)
495
+ void applied.catch(unpublished);
496
+ }
497
+ function unpublished(error) {
498
+ journal.record(`publication failed ${error instanceof Error ? error.name : 'unknown'}`);
404
499
  }
405
500
  async function referenced(locator) {
406
501
  for (;;) {
@@ -420,19 +515,16 @@ export function composeRuntime(options) {
420
515
  if (replica === undefined || closed || prepared.has(locator))
421
516
  return;
422
517
  const visible = replica.visible;
423
- const paths = [
424
- ...new Set([...Object.keys(visible.documents), ...Object.keys(visible.binaries)]),
425
- ];
426
518
  const entered = [];
427
519
  projecting.add(locator);
428
520
  try {
429
- await inChunks(paths, (path) => ROW_WEIGHT + (visible.documents[path]?.length ?? 0), (chunk) => {
521
+ await inChunks(await stepped(keysIn(visible.documents, visible.binaries)), (path) => ROW_WEIGHT + (visible.documents[path]?.length ?? 0), (chunk) => {
430
522
  const current = replicas.get(locator);
431
523
  if (current === undefined || closed)
432
524
  return;
433
525
  const set = entering(locator, current, chunk);
434
- readSide.apply(set);
435
526
  entered.push(set);
527
+ return readSide.apply(set);
436
528
  });
437
529
  if (!replicas.has(locator) || closed)
438
530
  return;
@@ -474,17 +566,22 @@ export function composeRuntime(options) {
474
566
  }
475
567
  })();
476
568
  }
569
+ function roomsOfReach(reach) {
570
+ return new Set([...reach.rooms, ...reach.documents.map(roomOfKey)]);
571
+ }
477
572
  function reachedRooms(plan) {
478
- const reach = plan.reach;
479
- const reached = reach === null ? null : new Set([...reach.rooms, ...reach.documents.map(roomOfKey)]);
573
+ const reached = plan.reach === null ? null : roomsOfReach(plan.reach);
480
574
  const named = plan.rooms ??
481
575
  (reached === null
482
576
  ? [...new Set([...rooms.keys(), ...replicas.keys(), ...queuesWithoutReplica.keys()])]
483
577
  : [...reached]);
484
- return [...new Set(named)].filter((locator) => reached === null || reached.has(locator)).sort();
578
+ return [...new Set(named)]
579
+ .filter((locator) => (reached === null || reached.has(locator)) && !plan.locked.includes(locator))
580
+ .sort();
485
581
  }
486
582
  function awaited(locator) {
487
- return rooms.has(locator) || !roomsListed;
583
+ return (!roomsListed ||
584
+ (rooms.has(locator) && discovered.get(locator)?.replica.admission === 'admitted'));
488
585
  }
489
586
  function covered(plan) {
490
587
  const locators = reachedRooms(plan);
@@ -524,61 +621,11 @@ export function composeRuntime(options) {
524
621
  if (waiting.length > 0)
525
622
  prepare(waiting.map(({ room }) => room));
526
623
  }
527
- function acquires(room) {
528
- return (demanded(demand, room) ||
529
- (replicas.get(room.locator)?.queue.length ?? 0) > 0 ||
530
- queuesWithoutReplica.has(room.locator));
531
- }
532
- function acquiredLocators() {
533
- return [...discovered.values()]
534
- .filter(acquires)
535
- .map((room) => room.locator)
536
- .sort();
537
- }
538
- function heldDemand(acquired) {
539
- if (demand.whole)
540
- return null;
541
- return { rooms: acquired.map((room) => room.locator), conversations: demand.conversations };
542
- }
543
- function applyDemand(next) {
544
- const before = acquiredLocators();
545
- const conversed = demand.conversations;
546
- demand = next;
547
- const after = acquiredLocators();
548
- queueReadiness();
549
- if (!conversed && next.conversations)
550
- scheduleCurrency();
551
- if (JSON.stringify(before) === JSON.stringify(after) && conversed === next.conversations)
552
- return;
553
- journal.record(`acquisition ${next.whole ? 'whole' : after.length}`);
554
- if (options.adapter.roomStream === undefined)
555
- void sync('unstreamed');
556
- else if (socketOpen)
557
- options.adapter.roomStream.reopen();
558
- }
559
- function acquire(next) {
560
- if (closed)
561
- return;
562
- if (narrowing !== null)
563
- clearTimeout(narrowing);
564
- narrowing = null;
565
- const widening = wider(next, demand);
566
- if (!widening && !narrower(next, demand))
567
- return;
568
- if (widening || !roomsListed) {
569
- applyDemand(next);
570
- return;
571
- }
572
- // A narrower demand waits five seconds, so a tab that reloads returns before the stream reopens twice.
573
- narrowing = setTimeout(() => {
574
- narrowing = null;
575
- applyDemand(next);
576
- }, 5_000);
577
- }
578
- function requiredRooms(reach) {
624
+ function requiredRooms(given) {
625
+ const reach = planReach(given);
579
626
  if (reach === null)
580
627
  return { listed: roomsListed, rooms: [...rooms.keys()].sort() };
581
- const named = [...new Set(reach.rooms)].sort();
628
+ const named = [...roomsOfReach(reach)].sort();
582
629
  if (roomsListed)
583
630
  return { listed: true, rooms: named.filter((room) => rooms.has(room)) };
584
631
  return { listed: named.every((room) => replicas.has(room)), rooms: named };
@@ -643,8 +690,7 @@ export function composeRuntime(options) {
643
690
  }
644
691
  function readinessFor(port, reach) {
645
692
  const required = requiredRooms(reach);
646
- const target = targets[port.target];
647
- const search = target?.search === true;
693
+ const search = port.search === 'required';
648
694
  const coverage = required.rooms.map((room) => ({ room, state: roomState(room, search) }));
649
695
  const building = (state) => coverage
650
696
  .filter((room) => room.state === state && !unindexable.has(room.room))
@@ -672,15 +718,11 @@ export function composeRuntime(options) {
672
718
  : port.capacity,
673
719
  refused: refusedIn(required.rooms),
674
720
  lost: storageLoss !== null,
675
- established: target?.established === true,
721
+ established: targets[port.target]?.established === true,
676
722
  });
677
723
  }
678
- function keepTarget(name, change) {
679
- const held = targets[name] ?? { established: false, search: false };
680
- const next = { ...held, ...change };
681
- if (next.established === held.established && next.search === held.search)
682
- return;
683
- targets = { ...targets, [name]: next };
724
+ function establish(name) {
725
+ targets = { ...targets, [name]: { established: true } };
684
726
  queueReadiness();
685
727
  void durably((local) => local.keepTargets(targets)).catch(() => {
686
728
  journal.record(`target record failed ${name}`);
@@ -691,7 +733,7 @@ export function composeRuntime(options) {
691
733
  return;
692
734
  const readiness = readinessFor(watch.port, watch.reach);
693
735
  if (readiness.ready && targets[watch.port.target]?.established !== true) {
694
- keepTarget(watch.port.target, { established: true });
736
+ establish(watch.port.target);
695
737
  }
696
738
  const shown = JSON.stringify(readiness);
697
739
  if (shown === watch.last)
@@ -719,10 +761,6 @@ export function composeRuntime(options) {
719
761
  readinessWatches.delete(watch);
720
762
  };
721
763
  }
722
- function searching(target) {
723
- if (targets[target]?.search !== true)
724
- keepTarget(target, { search: true });
725
- }
726
764
  function layerBytes(layer) {
727
765
  let bytes = 0;
728
766
  for (const [path, text] of Object.entries(layer.documents))
@@ -742,7 +780,7 @@ export function composeRuntime(options) {
742
780
  }
743
781
  async function estimated() {
744
782
  const estimate = options.shell.estimate === undefined ? null : await options.shell.estimate();
745
- return estimate === null ? null : Math.max(0, estimate.quota - estimate.usage);
783
+ return estimate === null ? null : Math.max(0, estimate.total - estimate.usage);
746
784
  }
747
785
  function pause(locator, cause) {
748
786
  paused.add(locator);
@@ -763,7 +801,8 @@ export function composeRuntime(options) {
763
801
  const available = await estimated().catch(() => null);
764
802
  if (available === null || available < (held.needed ?? 0))
765
803
  return;
766
- if (held.cause === 'quota-exceeded' && (held.available === null || available <= held.available))
804
+ if (held.cause === 'storage-exceeded' &&
805
+ (held.available === null || available <= held.available))
767
806
  return;
768
807
  resume();
769
808
  }
@@ -781,10 +820,7 @@ export function composeRuntime(options) {
781
820
  void sync('unstreamed');
782
821
  }
783
822
  async function reclaimed(local) {
784
- const unreferenced = [...transfers.keys()].filter((locator) => {
785
- const room = discovered.get(locator);
786
- return room === undefined || !acquires(room);
787
- });
823
+ const unreferenced = [...transfers.keys()].filter((locator) => !discovered.has(locator));
788
824
  for (const locator of unreferenced) {
789
825
  await local.abandon(locator);
790
826
  transfers.delete(locator);
@@ -808,20 +844,56 @@ export function composeRuntime(options) {
808
844
  }
809
845
  async function exceededOn(locator, bytes) {
810
846
  const available = await estimated().catch(() => null);
811
- pause(locator, { cause: 'quota-exceeded', needed: bytes, available });
847
+ pause(locator, { cause: 'storage-exceeded', needed: bytes, available });
848
+ }
849
+ function seedRoomHeld(room, version) {
850
+ return prepared.has(room) && reachedBy(room, version);
851
+ }
852
+ function seedHeld(at) {
853
+ return Object.entries(at).every(([room, version]) => (roomsListed && !rooms.has(room)) || seedRoomHeld(room, version));
854
+ }
855
+ function seedApplies(plan) {
856
+ const seed = seeds.get(plan.key);
857
+ if (seed === undefined)
858
+ return null;
859
+ if (!seedHeld(seed.at))
860
+ return seed;
861
+ seeds.delete(plan.key);
862
+ return null;
863
+ }
864
+ function seedBehind(plan, cover) {
865
+ const seed = seedApplies(plan);
866
+ if (seed === null || 'pending' in cover)
867
+ return cover;
868
+ return {
869
+ pending: Object.entries(seed.at)
870
+ .filter(([room, version]) => !seedRoomHeld(room, version))
871
+ .map(([room]) => ({ room, awaits: 'acquisition' })),
872
+ };
873
+ }
874
+ function seed(entry) {
875
+ if (seedHeld(entry.at))
876
+ return;
877
+ for (const { query, rows } of entry.queries) {
878
+ const key = queryKey(query);
879
+ seeds.set(key, { rows, at: entry.at });
880
+ for (const shown of seedWatchers.get(key) ?? [])
881
+ shown();
882
+ }
812
883
  }
813
884
  async function rowsQuery(plan) {
814
885
  const before = covered(plan);
815
886
  awaitPreparation(before);
887
+ const seeded = seedApplies(plan);
888
+ if (seeded !== null)
889
+ return seededResult(seeded).result;
816
890
  if ('pending' in before)
817
891
  return before;
818
892
  const { rows, at: cover } = await readSide.query(plan, () => covered(plan));
819
893
  awaitPreparation(cover);
820
894
  if ('pending' in cover)
821
895
  return cover;
822
- return 'groups' in rows
823
- ? { groups: rows.groups, coverage: cover.coverage }
824
- : { documents: rows.documents, coverage: cover.coverage };
896
+ return { ...rows, coverage: cover.coverage };
825
897
  }
826
898
  async function indexConversation(conversation) {
827
899
  searchIndex.indexMessages(conversation, [], false);
@@ -909,17 +981,22 @@ export function composeRuntime(options) {
909
981
  models.set(key, revoked);
910
982
  liveModels.delete(key);
911
983
  }
912
- const changed = [];
913
- for (const [locator, room] of rooms) {
984
+ const revocations = [];
985
+ for (const locator of [...rooms.keys()]) {
914
986
  const before = replicas.get(locator) ?? null;
915
- if (before !== null) {
916
- const record = {
917
- ...before.confirmed.record,
918
- model: revoked,
919
- selectionModel: revoked,
920
- };
921
- replicas.set(locator, replicaOf(confirmedOf(record, before.confirmed), before.queue, before));
922
- }
987
+ const after = before === null
988
+ ? null
989
+ : await stepped(replicating(await confirmedOf({ ...before.confirmed.record, model: revoked, selectionModel: revoked }, before.confirmed), before.queue, before));
990
+ const set = await stepped(changing(locator, before, after, { room: true }));
991
+ revocations.push([locator, before, after, set]);
992
+ }
993
+ const changed = [];
994
+ for (const [locator, before, after, set] of revocations) {
995
+ const room = rooms.get(locator);
996
+ if (room === undefined || (replicas.get(locator) ?? null) !== before)
997
+ continue;
998
+ if (after !== null)
999
+ replicas.set(locator, after);
923
1000
  rooms.set(locator, {
924
1001
  ...room,
925
1002
  model: modelTypes(revoked),
@@ -927,7 +1004,7 @@ export function composeRuntime(options) {
927
1004
  ? null
928
1005
  : { ...room.typedSelection, model: modelTypes(revoked) },
929
1006
  });
930
- changed.push(changeSet(locator, before, replicas.get(locator) ?? null, { room: true }));
1007
+ changed.push(set);
931
1008
  }
932
1009
  publishChangeSet(mergeChangeSets(changed));
933
1010
  });
@@ -965,20 +1042,28 @@ export function composeRuntime(options) {
965
1042
  refusal: scopedRefusals.get(room.locator) ?? sourceRefusals.get(room.locator) ?? null,
966
1043
  });
967
1044
  }
968
- async function applyDiscovery(found, started) {
1045
+ async function applyDiscovery(found, started, covered) {
1046
+ const lockedBefore = lockedRooms();
969
1047
  for (const room of found) {
970
1048
  const fence = fences.get(room.locator);
971
1049
  if (fence !== undefined && fence.erased && fence.at < started)
972
1050
  fences.delete(room.locator);
973
1051
  }
1052
+ await loseRooms(found
1053
+ .filter((room) => room.replica.admission !== 'admitted' && heldLocally(room.locator))
1054
+ .map((room) => room.locator));
974
1055
  const listed = found.filter((room) => !fences.has(room.locator));
975
1056
  const listedLocators = new Set(listed.map((room) => room.locator));
976
1057
  for (const locator of listedLocators)
977
1058
  scopedRefusals.delete(locator);
978
- discovered.clear();
1059
+ if (covered === undefined)
1060
+ discovered.clear();
1061
+ else
1062
+ for (const locator of covered)
1063
+ discovered.delete(locator);
979
1064
  for (const room of listed)
980
1065
  discovered.set(room.locator, room);
981
- const unlisted = unlistedHeld(new Set(found.map((room) => room.locator)));
1066
+ const unlisted = unlistedHeld(new Set(found.map((room) => room.locator))).filter((locator) => covered === undefined || covered.includes(locator));
982
1067
  if (options.adapter.exhaustiveDiscovery === true)
983
1068
  await loseRooms(unlisted);
984
1069
  else
@@ -991,10 +1076,18 @@ export function composeRuntime(options) {
991
1076
  }
992
1077
  list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));
993
1078
  }
1079
+ confirmLocks(listed);
994
1080
  roomsListed = true;
995
1081
  emitRooms();
1082
+ relocked(lockedBefore);
996
1083
  return listed;
997
1084
  }
1085
+ function heldLocally(locator) {
1086
+ return (replicas.has(locator) ||
1087
+ roomDrafts.has(locator) ||
1088
+ transfers.has(locator) ||
1089
+ queuesWithoutReplica.has(locator));
1090
+ }
998
1091
  function unlistedHeld(listed) {
999
1092
  return [
1000
1093
  ...new Set([
@@ -1016,16 +1109,17 @@ export function composeRuntime(options) {
1016
1109
  }
1017
1110
  function fence(locators) {
1018
1111
  const fresh = [...new Set(locators)].filter((locator) => !fences.has(locator));
1019
- const removed = fresh.map((locator) => changeSet(locator, replicas.get(locator) ?? null, null, {
1020
- room: true,
1021
- queue: true,
1112
+ const removed = fresh.map((locator) => ({
1113
+ locator,
1114
+ shown: prepared.has(locator) || projecting.has(locator) ? (replicas.get(locator) ?? null) : null,
1022
1115
  drafts: [...(roomDrafts.get(locator)?.keys() ?? [])],
1023
1116
  }));
1024
1117
  for (const locator of fresh) {
1025
1118
  fences.set(locator, { at: discoveries, erased: false });
1026
1119
  lastFenced.set(locator, ++fencings);
1120
+ confirmed.delete(locator);
1027
1121
  for (const batch of replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? [])
1028
- pendings.delete(batch.id);
1122
+ pendings.delete(pendingKey(locator, batch.id));
1029
1123
  replicas.delete(locator);
1030
1124
  queuesWithoutReplica.delete(locator);
1031
1125
  rooms.delete(locator);
@@ -1039,6 +1133,7 @@ export function composeRuntime(options) {
1039
1133
  repairable.delete(locator);
1040
1134
  unindexable.delete(locator);
1041
1135
  paused.delete(locator);
1136
+ prepared.delete(locator);
1042
1137
  scopedRefusals.delete(locator);
1043
1138
  sourceRefusals.delete(locator);
1044
1139
  declarationRefusals.delete(locator);
@@ -1052,14 +1147,21 @@ export function composeRuntime(options) {
1052
1147
  }
1053
1148
  if (fresh.length === 0)
1054
1149
  return fresh;
1055
- publishChangeSet(mergeChangeSets(removed));
1056
- for (const locator of fresh)
1057
- prepared.delete(locator);
1058
1150
  searchIndex.forget(fresh);
1151
+ const withdrawn = readSide.apply(stepped(withdrawing(removed)), (set) => conversations.changed(set));
1152
+ if (withdrawn instanceof Promise)
1153
+ void withdrawn.catch(unpublished);
1154
+ publishChangeSet(mergeChangeSets(removed.map(({ locator, drafts }) => changeSet(locator, null, null, { room: true, queue: true, drafts }))));
1059
1155
  readSide.recover();
1060
1156
  moveTo({ ...status, ...attention() });
1061
1157
  return fresh;
1062
1158
  }
1159
+ function* withdrawing(removed) {
1160
+ const sets = [];
1161
+ for (const { locator, shown } of removed)
1162
+ sets.push(yield* changing(locator, shown, null));
1163
+ return mergeChangeSets(sets);
1164
+ }
1063
1165
  async function erased(local, locators) {
1064
1166
  await local.erase(locators);
1065
1167
  for (const locator of locators) {
@@ -1070,8 +1172,12 @@ export function composeRuntime(options) {
1070
1172
  }
1071
1173
  async function loseRooms(locators) {
1072
1174
  const fresh = fence(locators);
1073
- if (fresh.length > 0)
1074
- await durably((local) => erased(local, fresh));
1175
+ if (fresh.length === 0)
1176
+ return;
1177
+ await durably(async (local) => {
1178
+ await erased(local, fresh);
1179
+ await unpair(local);
1180
+ });
1075
1181
  }
1076
1182
  function restored(key, persisted) {
1077
1183
  const prior = models.get(key);
@@ -1106,6 +1212,22 @@ export function composeRuntime(options) {
1106
1212
  opened.transfers(),
1107
1213
  opened.targets(),
1108
1214
  ]);
1215
+ const queuedBatches = new Map(queues.map((queue) => [queue.locator, queue.pending.map(({ batch }) => batch)]));
1216
+ const previousReplicas = new Map(replicas);
1217
+ const read = new Map();
1218
+ for (const record of records) {
1219
+ const model = restored(modelKey(record.locator, 'collection'), record.model);
1220
+ const selectionModel = restored(modelKey(record.locator, 'typed-selection'), record.selectionModel);
1221
+ const prior = previousReplicas.get(record.locator);
1222
+ const confirmed = await confirmedOf({ ...record, model, selectionModel }, prior?.confirmed);
1223
+ const replica = await stepped(replicating(confirmed, queuedBatches.get(record.locator) ?? [], prior));
1224
+ await stepped(counting(replica));
1225
+ read.set(record.locator, replica);
1226
+ }
1227
+ const sets = new Map();
1228
+ for (const locator of new Set([...previousReplicas.keys(), ...read.keys()])) {
1229
+ sets.set(locator, await stepped(changing(locator, previousReplicas.get(locator) ?? null, read.get(locator) ?? null)));
1230
+ }
1109
1231
  targets = heldTargets;
1110
1232
  transfers.clear();
1111
1233
  for (const record of staged)
@@ -1120,26 +1242,24 @@ export function composeRuntime(options) {
1120
1242
  for (const record of presented)
1121
1243
  presentations.set(record.app, record.value);
1122
1244
  conversations.hydrate(held, chatDrafts);
1123
- const queuedBatches = new Map(queues.map((queue) => [queue.locator, queue.pending.map(({ batch }) => batch)]));
1124
1245
  pendings.clear();
1125
1246
  for (const queue of queues) {
1126
- for (const { batch, state } of queue.pending)
1127
- pendings.set(batch.id, state);
1247
+ for (const { batch, state } of queue.pending) {
1248
+ pendings.set(pendingKey(queue.locator, batch.id), state);
1249
+ }
1128
1250
  }
1129
- const previousReplicas = new Map(replicas);
1130
1251
  replicas.clear();
1131
1252
  queuesWithoutReplica.clear();
1132
- const replicated = new Set(records.map((record) => record.locator));
1133
1253
  for (const [locator, queue] of queuedBatches) {
1134
- if (!replicated.has(locator))
1254
+ if (!read.has(locator))
1135
1255
  queuesWithoutReplica.set(locator, queue);
1136
1256
  }
1137
1257
  for (const record of records) {
1138
- const model = restored(modelKey(record.locator, 'collection'), record.model);
1139
- const selectionModel = restored(modelKey(record.locator, 'typed-selection'), record.selectionModel);
1140
- const prior = previousReplicas.get(record.locator);
1141
- const confirmed = confirmedOf({ ...record, model, selectionModel }, prior?.confirmed);
1142
- replicas.set(record.locator, replicaOf(confirmed, queuedBatches.get(record.locator) ?? [], prior));
1258
+ if (fences.has(record.locator))
1259
+ continue;
1260
+ const replica = read.get(record.locator);
1261
+ const { model, selectionModel } = replica.confirmed.record;
1262
+ replicas.set(record.locator, replica);
1143
1263
  const existing = rooms.get(record.locator);
1144
1264
  if (existing === undefined)
1145
1265
  list(record, false);
@@ -1162,7 +1282,7 @@ export function composeRuntime(options) {
1162
1282
  return {
1163
1283
  lastCompleted,
1164
1284
  locators: new Set([...queuedBatches.keys(), ...replicas.keys()]),
1165
- read: mergeChangeSets([...new Set([...previousReplicas.keys(), ...replicas.keys()])].map((locator) => changeSet(locator, previousReplicas.get(locator) ?? null, replicas.get(locator) ?? null))),
1285
+ read: mergeChangeSets([...sets].flatMap(([locator, set]) => (fences.has(locator) ? [] : [set]))),
1166
1286
  };
1167
1287
  }
1168
1288
  async function readState(opened) {
@@ -1181,7 +1301,7 @@ export function composeRuntime(options) {
1181
1301
  async function open() {
1182
1302
  if (closed)
1183
1303
  throw new Error('runtime closed');
1184
- const opened = await openRuntimeStore(isFenced);
1304
+ const opened = await openRuntimeStore(isFenced, options.database);
1185
1305
  store = opened;
1186
1306
  const interrupted = await opened.fences();
1187
1307
  for (const locator of interrupted) {
@@ -1204,6 +1324,9 @@ export function composeRuntime(options) {
1204
1324
  if (interrupted.length > 0)
1205
1325
  await erased(opened, interrupted);
1206
1326
  moveTo({ ...status, lastCompleted, ...attention() });
1327
+ void exclusive(() => unpair(opened)).catch(() => {
1328
+ journal.record('unpair failed');
1329
+ });
1207
1330
  return opened;
1208
1331
  }
1209
1332
  function durably(work) {
@@ -1224,27 +1347,92 @@ export function composeRuntime(options) {
1224
1347
  mutations = next.then(() => undefined, () => undefined);
1225
1348
  return next;
1226
1349
  }
1227
- function withdrawable(batch) {
1228
- const state = pendings.get(batch.id);
1229
- return state !== undefined && state.submission.state !== 'submitted' && !state.lost;
1350
+ function withdrawable(locator) {
1351
+ return (batch) => {
1352
+ const state = pendings.get(pendingKey(locator, batch.id));
1353
+ return state !== undefined && state.submission.state !== 'submitted' && !state.lost;
1354
+ };
1355
+ }
1356
+ function landedWhole(locator, batch, confirmed, current) {
1357
+ if (!landed(batch, confirmed, current))
1358
+ return false;
1359
+ const partner = partnerOf(batch, locator);
1360
+ if (partner === null)
1361
+ return true;
1362
+ const other = replicas.get(partner);
1363
+ const half = other?.queue.find((one) => one.id === batch.id);
1364
+ return other !== undefined && half !== undefined && landed(half, other.confirmed);
1365
+ }
1366
+ function carriedBack(locator, unlanded, written) {
1367
+ const back = new Map();
1368
+ const taken = [];
1369
+ for (const batch of unlanded) {
1370
+ const between = batch.between;
1371
+ if (between === undefined)
1372
+ continue;
1373
+ const source = between.source.room;
1374
+ const destination = between.destination.room;
1375
+ for (const { path: to } of pendings.get(pendingKey(destination, batch.id))?.drafts ?? []) {
1376
+ const record = roomDrafts.get(destination)?.get(to);
1377
+ const path = between.moves.find((move) => move.to === to)?.path;
1378
+ if (record === undefined || path === undefined)
1379
+ continue;
1380
+ const [into, key] = source === locator ? [written, path] : [back, documentKey(source, path)];
1381
+ const existing = into.get(key) ?? roomDrafts.get(source)?.get(path);
1382
+ taken.push({ locator: destination, path: to });
1383
+ into.set(key, {
1384
+ locator: source,
1385
+ path,
1386
+ revision: roomDraftRevision(),
1387
+ parts: returnedInto(existing?.parts, record.parts),
1388
+ returned: existing?.returned ?? null,
1389
+ });
1390
+ }
1391
+ }
1392
+ const records = [...back.values()];
1393
+ const elsewhere = taken.filter((one) => one.locator !== locator);
1394
+ const rooms = new Set([...records, ...elsewhere].map((one) => one.locator));
1395
+ return {
1396
+ taken: taken.filter((one) => one.locator === locator).map(({ path }) => path),
1397
+ writes: [...rooms].map((room) => ({
1398
+ locator: room,
1399
+ roomDrafts: records.filter((record) => record.locator === room),
1400
+ consumedRoomDrafts: elsewhere.filter((one) => one.locator === room).map(({ path }) => path),
1401
+ })),
1402
+ changes: [...rooms].map((room) => changeSet(room, null, null, {
1403
+ drafts: [...records, ...elsewhere]
1404
+ .filter((one) => one.locator === room)
1405
+ .map(({ path }) => path),
1406
+ })),
1407
+ remember() {
1408
+ for (const one of taken)
1409
+ forgetRoomDraft(one.locator, one.path);
1410
+ for (const record of records)
1411
+ rememberRoomDraft(record);
1412
+ },
1413
+ };
1230
1414
  }
1231
1415
  async function settle(local, locator, before, confirmed, queue, settling = {}) {
1232
1416
  const previousQueue = before?.queue ?? queuesWithoutReplica.get(locator) ?? [];
1233
- const withdrawn = withdrawals(confirmed, queue, withdrawable, localSaves);
1234
- const kept = queue.filter((batch) => !withdrawn.includes(batch));
1417
+ const { withdrawn, kept } = await stepped(standing(confirmed, queue, withdrawable(locator), localSaves));
1418
+ const founded = kept.filter((batch) => !queue.includes(batch));
1419
+ const queueChanged = kept.length !== previousQueue.length || founded.length > 0;
1235
1420
  const unqueued = withdrawn.map((batch) => ({
1236
1421
  batch,
1237
- returned: localSaves || landed(batch, confirmed) ? null : returnedBy('withdrawn'),
1422
+ landed: landedWhole(locator, batch, confirmed),
1238
1423
  }));
1239
1424
  const returning = [
1240
- ...[...unqueued].reverse(),
1425
+ ...[...unqueued].reverse().map(({ batch, landed }) => ({
1426
+ batch,
1427
+ returned: localSaves || landed ? null : returnedBy('withdrawn'),
1428
+ })),
1241
1429
  ...(settling.leaving === undefined ? [] : [settling.leaving]),
1242
1430
  ];
1243
1431
  const written = new Map();
1244
1432
  for (const { batch, returned } of returning) {
1245
- if (returned === null)
1433
+ if (returned === null || batch.between?.destination.room === locator)
1246
1434
  continue;
1247
- for (const saved of pendings.get(batch.id)?.drafts ?? []) {
1435
+ for (const saved of pendings.get(pendingKey(locator, batch.id))?.drafts ?? []) {
1248
1436
  const existing = written.get(saved.path) ?? roomDrafts.get(locator)?.get(saved.path);
1249
1437
  written.set(saved.path, {
1250
1438
  locator,
@@ -1255,13 +1443,28 @@ export function composeRuntime(options) {
1255
1443
  });
1256
1444
  }
1257
1445
  }
1258
- await local.keepAuthored({ locator, queue: kept, roomDrafts: [...written.values()] });
1446
+ const carried = carriedBack(locator, [
1447
+ ...[...unqueued].reverse().flatMap(({ batch, landed }) => (landed ? [] : [batch])),
1448
+ ...(settling.leaving === undefined || settling.leaving.returned === null
1449
+ ? []
1450
+ : [settling.leaving.batch]),
1451
+ ], written);
1452
+ await local.keepAuthored({
1453
+ locator,
1454
+ queue: kept,
1455
+ founded,
1456
+ roomDrafts: [...written.values()],
1457
+ consumedRoomDrafts: carried.taken,
1458
+ }, ...carried.writes);
1459
+ const staying = new Set(kept.map((batch) => batch.id));
1259
1460
  for (const batch of previousQueue) {
1260
- if (!kept.includes(batch))
1261
- pendings.delete(batch.id);
1461
+ if (!staying.has(batch.id))
1462
+ pendings.delete(pendingKey(locator, batch.id));
1262
1463
  }
1263
1464
  for (const record of written.values())
1264
1465
  rememberRoomDraft(record);
1466
+ carried.remember();
1467
+ const drafts = [...written.keys(), ...carried.taken];
1265
1468
  try {
1266
1469
  await local.write({
1267
1470
  next: confirmed.record,
@@ -1270,34 +1473,39 @@ export function composeRuntime(options) {
1270
1473
  });
1271
1474
  }
1272
1475
  catch (error) {
1273
- const held = before === undefined ? null : replicaOf(before.confirmed, kept, before);
1476
+ const held = before === undefined ? null : await stepped(replicating(before.confirmed, kept, before));
1477
+ const set = await stepped(changing(locator, before ?? null, held, { queue: queueChanged, drafts }));
1274
1478
  if (held !== null)
1275
1479
  replicas.set(locator, held);
1276
1480
  else if (kept.length > 0)
1277
1481
  queuesWithoutReplica.set(locator, kept);
1278
1482
  else
1279
1483
  queuesWithoutReplica.delete(locator);
1280
- publishChangeSet(changeSet(locator, before ?? null, held, {
1281
- queue: kept.length !== previousQueue.length,
1282
- drafts: [...written.keys()],
1283
- }));
1484
+ publishChangeSet(mergeChangeSets([set, ...carried.changes]));
1284
1485
  moveTo({ ...status, ...attention() });
1285
1486
  throw error;
1286
1487
  }
1488
+ const changed = { room: settling.room, queue: queueChanged, drafts };
1489
+ const next = await stepped(replicating(confirmed, kept, before));
1490
+ await stepped(counting(next));
1491
+ const set = await stepped(changing(locator, before ?? null, next, changed));
1287
1492
  return () => {
1288
1493
  queuesWithoutReplica.delete(locator);
1289
- for (const { batch, returned } of unqueued) {
1290
- const outcome = localSaves ? 'dropped' : returned === null ? 'landed' : 'withdrawn';
1494
+ for (const { batch, landed } of unqueued) {
1495
+ const outcome = localSaves ? 'dropped' : landed ? 'landed' : 'withdrawn';
1291
1496
  journal.record(`outcome ${locator} ${batch.id} ${outcome}`);
1292
1497
  }
1293
- replicas.set(locator, replicaOf(confirmed, kept, before));
1294
- return changeSet(locator, before ?? null, replicas.get(locator) ?? null, {
1295
- room: settling.room,
1296
- queue: kept.length !== previousQueue.length,
1297
- drafts: [...written.keys()],
1298
- });
1498
+ replicas.set(locator, next);
1499
+ return mergeChangeSets([
1500
+ heldChange(locator, before ?? null, next, set, changed),
1501
+ ...carried.changes,
1502
+ ]);
1299
1503
  };
1300
1504
  }
1505
+ function heldChange(locator, before, next, set, changed) {
1506
+ const held = replicas.get(locator) ?? null;
1507
+ return held === next ? set : changeSet(locator, before, held, changed);
1508
+ }
1301
1509
  function adoptModels(locator, record) {
1302
1510
  for (const [attached, model] of [
1303
1511
  ['collection', record.model],
@@ -1316,7 +1524,7 @@ export function composeRuntime(options) {
1316
1524
  const taken = (answer, previous, attached) => {
1317
1525
  if (answer === undefined)
1318
1526
  return previous;
1319
- const { state, refused } = attachedModel(answer, previous);
1527
+ const { state, refused } = attachedModel(answer, previous, attached === 'collection' ? roomTypes : NO_ROOM_TYPES);
1320
1528
  if (refused !== null) {
1321
1529
  const where = refused.location === undefined ? '' : ` ${refused.location}`;
1322
1530
  journal.record(`model invalid ${locator} ${attached} ${refused.identity} ${refused.rule}${where}`);
@@ -1349,7 +1557,7 @@ export function composeRuntime(options) {
1349
1557
  const queue = prior?.queue ?? queuesWithoutReplica.get(room.locator) ?? [];
1350
1558
  const roomVersion = confirmed.record.roomVersion;
1351
1559
  const accepted = queue.filter((batch) => {
1352
- const accepted = pendings.get(batch.id)?.accepted;
1560
+ const accepted = pendings.get(pendingKey(room.locator, batch.id))?.accepted;
1353
1561
  return (accepted !== undefined && options.adapter.reached(room.locator, roomVersion, accepted));
1354
1562
  });
1355
1563
  let settled;
@@ -1369,7 +1577,7 @@ export function composeRuntime(options) {
1369
1577
  catching.delete(room.locator);
1370
1578
  }
1371
1579
  for (const batch of accepted)
1372
- pendings.delete(batch.id);
1580
+ pendings.delete(pendingKey(room.locator, batch.id));
1373
1581
  stale.delete(room.locator);
1374
1582
  unindexable.delete(room.locator);
1375
1583
  if (unreadable.delete(room.locator))
@@ -1380,12 +1588,16 @@ export function composeRuntime(options) {
1380
1588
  if (prior === undefined)
1381
1589
  prepared.add(room.locator);
1382
1590
  publishChangeSet(set);
1591
+ await unpair(local);
1383
1592
  moveTo({ ...status, ...attention() });
1384
1593
  options.adapter.roomStream?.published(room.locator, roomVersion);
1594
+ if (accepted.length > 0 && (replicas.get(room.locator)?.queue.length ?? 0) > 0) {
1595
+ submitLater(room.locator);
1596
+ }
1385
1597
  return true;
1386
1598
  });
1387
1599
  }
1388
- async function saveRoomDrafts(locator, named, writtenBy) {
1600
+ async function savedRoom(locator) {
1389
1601
  const local = await openLocal();
1390
1602
  await referenced(locator);
1391
1603
  const replica = replicas.get(locator);
@@ -1393,6 +1605,10 @@ export function composeRuntime(options) {
1393
1605
  if (replica === undefined || room === undefined) {
1394
1606
  throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
1395
1607
  }
1608
+ return { local, replica, room };
1609
+ }
1610
+ async function saveRoomDrafts(locator, named, writtenBy) {
1611
+ const target = await savedRoom(locator);
1396
1612
  const saved = [];
1397
1613
  for (const { path, revision } of named) {
1398
1614
  const record = roomDrafts.get(locator)?.get(path);
@@ -1402,12 +1618,180 @@ export function composeRuntime(options) {
1402
1618
  if (!saved.some((draft) => draft.path === path))
1403
1619
  saved.push({ path, parts: record.parts });
1404
1620
  }
1621
+ return committed(locator, target, saved, new Set(saved.map(({ path }) => path)), writtenBy);
1622
+ }
1623
+ async function saveParts(locator, named, writtenBy) {
1624
+ const read = named.map(({ path, parts }) => ({ path, parts: readParts(parts) }));
1625
+ if (read.some(({ path }, at) => path === '' ||
1626
+ normalize(path) !== path ||
1627
+ read.findIndex((one) => one.path === path) !== at)) {
1628
+ throw runtimeError('room-draft-malformed');
1629
+ }
1630
+ const target = await savedRoom(locator);
1631
+ const saved = [];
1632
+ const files = [];
1633
+ for (const { path, parts } of read) {
1634
+ const file = parts.file === undefined
1635
+ ? undefined
1636
+ : await heldFile(parts.file.blob, binaryBase(target.replica.visible, path));
1637
+ if (parts.file !== undefined && file !== undefined) {
1638
+ files.push({ key: file.localId, blob: parts.file.blob });
1639
+ }
1640
+ saved.push({ path, parts: held(undefined, parts, file) });
1641
+ }
1642
+ return committed(locator, target, saved, new Set(), writtenBy, files);
1643
+ }
1644
+ function carriedDrafts(locator, saved, consumed) {
1645
+ const holding = roomDrafts.get(locator);
1646
+ return new Map(saved.flatMap(({ path, parts }) => {
1647
+ const record = holding?.get(path);
1648
+ if (parts.move === undefined || record === undefined || consumed.has(path))
1649
+ return [];
1650
+ const to = moveTarget(parts.move);
1651
+ if (to === path || holding?.has(to) === true)
1652
+ return [];
1653
+ return [[path, { ...record, path: to, revision: roomDraftRevision() }]];
1654
+ }));
1655
+ }
1656
+ function sideOf(locator, replica, room) {
1657
+ const record = replica.confirmed.record;
1658
+ return {
1659
+ room: locator,
1660
+ handle: room.handle,
1661
+ baseRoomVersion: record.roomVersion,
1662
+ composition: compositionFor(record),
1663
+ operations: room.operations,
1664
+ providerOwnedPaths: room.providerOwnedPaths,
1665
+ visible: replica.visible,
1666
+ queued: queuedDocuments(replica.queue),
1667
+ clean: {
1668
+ text: record.documents,
1669
+ binaries: record.binaries,
1670
+ composition: compositionOf(record),
1671
+ },
1672
+ };
1673
+ }
1674
+ function movedInto(locator, saved) {
1675
+ const into = saved.find(({ parts }) => parts.move?.room !== undefined && parts.move.room !== locator);
1676
+ return into?.parts.move?.room ?? null;
1677
+ }
1678
+ async function committedMove(locator, destination, { local, replica, room }, saved, consumed, writtenBy, files) {
1679
+ const mixed = saved.find(({ parts }) => Object.keys(parts).length !== 1 || parts.move?.room !== destination);
1680
+ if (mixed !== undefined) {
1681
+ return { outcome: 'refused', code: 'mixed-room-move', retryable: false, file: mixed.path };
1682
+ }
1683
+ const changed = saved.flatMap(({ path, parts }) => changedParts(path, underneath(parts, path, replica.visible)));
1684
+ if (changed.length > 0)
1685
+ return { outcome: 'refused', code: 'changed-underneath', retryable: false, parts: changed };
1686
+ await referenced(destination);
1687
+ const target = replicas.get(destination);
1688
+ const listedRoom = rooms.get(destination);
1689
+ if (target === undefined || listedRoom === undefined) {
1690
+ throw runtimeError('room-not-held', `No Local Replica for ${destination}`);
1691
+ }
1692
+ const built = await buildMove({
1693
+ source: sideOf(locator, replica, room),
1694
+ destination: sideOf(destination, target, listedRoom),
1695
+ moves: saved.map(({ path, parts }) => ({ path, to: moveTarget(parts.move) })),
1696
+ providerLimits: limits,
1697
+ local: localSaves,
1698
+ ...(writtenBy === undefined ? {} : { writtenBy }),
1699
+ });
1700
+ if (built.kind === 'refused')
1701
+ return { outcome: 'refused', ...built.refusal };
1702
+ const id = built.leaving.id;
1703
+ const carrying = saved.flatMap(({ path, parts }) => {
1704
+ const record = roomDrafts.get(locator)?.get(path);
1705
+ const to = moveTarget(parts.move);
1706
+ if (record === undefined || consumed.has(path) || roomDrafts.get(destination)?.has(to)) {
1707
+ return [];
1708
+ }
1709
+ const moved = {
1710
+ ...record,
1711
+ locator: destination,
1712
+ path: to,
1713
+ revision: roomDraftRevision(),
1714
+ };
1715
+ return [{ from: path, record: moved }];
1716
+ });
1717
+ const carried = carrying.map(({ record }) => record);
1718
+ const marked = carried.map(({ path }) => ({ path, parts: {} }));
1719
+ const left = [...consumed, ...carrying.map(({ from }) => from)];
1720
+ const leavingQueue = [...replica.queue, built.leaving];
1721
+ const arrivingQueue = [...target.queue, built.arriving];
1722
+ let fencedRoom;
1723
+ try {
1724
+ fencedRoom = await local.saveAuthored(files, {
1725
+ locator,
1726
+ queue: leavingQueue,
1727
+ saved: new Map([[id, saved]]),
1728
+ consumedRoomDrafts: left,
1729
+ }, {
1730
+ locator: destination,
1731
+ queue: arrivingQueue,
1732
+ saved: new Map([[id, marked]]),
1733
+ roomDrafts: carried,
1734
+ });
1735
+ }
1736
+ catch {
1737
+ return { outcome: 'refused', code: 'durable-write', retryable: true };
1738
+ }
1739
+ if (fencedRoom !== null) {
1740
+ throw runtimeError('room-not-held', `No Local Replica for ${fencedRoom}`);
1741
+ }
1742
+ const nextSource = await stepped(replicating(replica.confirmed, leavingQueue, replica));
1743
+ const nextDestination = await stepped(replicating(target.confirmed, arrivingQueue, target));
1744
+ const sets = [
1745
+ await stepped(changing(locator, replica, nextSource, { queue: true, drafts: left })),
1746
+ await stepped(changing(destination, target, nextDestination, {
1747
+ queue: true,
1748
+ drafts: carried.map(({ path }) => path),
1749
+ })),
1750
+ ];
1751
+ if (fences.has(locator) || fences.has(destination)) {
1752
+ throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
1753
+ }
1754
+ pendings.set(pendingKey(locator, id), {
1755
+ drafts: saved,
1756
+ submission: { state: 'waiting' },
1757
+ lost: false,
1758
+ });
1759
+ pendings.set(pendingKey(destination, id), {
1760
+ drafts: marked,
1761
+ submission: { state: 'waiting' },
1762
+ lost: false,
1763
+ });
1764
+ for (const path of left)
1765
+ forgetRoomDraft(locator, path);
1766
+ for (const record of carried)
1767
+ rememberRoomDraft(record);
1768
+ replicas.set(locator, nextSource);
1769
+ replicas.set(destination, nextDestination);
1770
+ publishChangeSet(mergeChangeSets(sets));
1771
+ queuedSave(locator);
1772
+ return { outcome: 'saved', identifier: id };
1773
+ }
1774
+ function queuedSave(locator) {
1775
+ if (!localSaves)
1776
+ recorded = false;
1777
+ moveTo({ ...(localSaves ? status : saving(status)), ...attention() });
1778
+ submitLater(locator);
1779
+ }
1780
+ async function committed(locator, target, saved, consumed, writtenBy, files = []) {
1781
+ const into = movedInto(locator, saved);
1782
+ if (into !== null) {
1783
+ return committedMove(locator, into, target, saved, consumed, writtenBy, files);
1784
+ }
1785
+ const { local, replica, room } = target;
1405
1786
  const changed = saved.flatMap(({ path, parts }) => changedParts(path, underneath(parts, path, replica.visible)));
1406
1787
  if (changed.length > 0)
1407
1788
  return { outcome: 'refused', code: 'changed-underneath', retryable: false, parts: changed };
1408
1789
  const parts = saved.map(({ path, parts }) => changesOf(path, parts));
1409
1790
  const changes = parts.flatMap(({ changes }) => changes);
1410
- const requeue = requeued(replica.queue, changes, replica.visible, withdrawable, (queue) => replicaOf(replica.confirmed, queue, replica).visible);
1791
+ const visibleOver = function* (queue) {
1792
+ return (yield* replicating(replica.confirmed, queue, replica)).visible;
1793
+ };
1794
+ const requeue = await stepped(requeuing(replica.queue, changes, replica.visible, withdrawable(locator), visibleOver));
1411
1795
  if (requeue.kind === 'refused')
1412
1796
  return { outcome: 'refused', ...requeue.refusal };
1413
1797
  const foreign = [...requeue.withdrawn.keys()].some((origin) => {
@@ -1434,6 +1818,7 @@ export function composeRuntime(options) {
1434
1818
  visible: replica.visible,
1435
1819
  changes,
1436
1820
  bases: parts.flatMap(({ bases }) => bases),
1821
+ queued: queuedDocuments(replica.queue),
1437
1822
  writtenBy,
1438
1823
  clean: {
1439
1824
  text: replica.confirmed.record.documents,
@@ -1441,7 +1826,9 @@ export function composeRuntime(options) {
1441
1826
  composition: compositionOf(replica.confirmed.record),
1442
1827
  },
1443
1828
  };
1444
- const checked = withdrawing ? buildBatch({ ...input, queued: requeue.queued }) : null;
1829
+ const checked = withdrawing
1830
+ ? await buildBatch({ ...input, queued: new Set([...input.queued, ...requeue.queued]) })
1831
+ : null;
1445
1832
  if (checked?.kind === 'refused')
1446
1833
  return { outcome: 'refused', ...checked.refusal };
1447
1834
  const owners = [...requeue.owners].flatMap((origin) => {
@@ -1457,13 +1844,15 @@ export function composeRuntime(options) {
1457
1844
  };
1458
1845
  }
1459
1846
  const built = !withdrawing
1460
- ? buildBatch(input)
1847
+ ? await buildBatch(input)
1461
1848
  : requeue.changes.length === 0
1462
1849
  ? null
1463
- : buildBatch({
1850
+ : await buildBatch({
1464
1851
  ...input,
1465
- visible: replicaOf(replica.confirmed, requeue.queue, replica).visible,
1852
+ visible: (await stepped(replicating(replica.confirmed, requeue.queue, replica)))
1853
+ .visible,
1466
1854
  changes: requeue.changes,
1855
+ queued: queuedDocuments(requeue.queue),
1467
1856
  });
1468
1857
  if (built?.kind === 'refused')
1469
1858
  return { outcome: 'refused', ...built.refusal };
@@ -1480,7 +1869,7 @@ export function composeRuntime(options) {
1480
1869
  for (const [origin, replaced] of withdrawn) {
1481
1870
  if (replaced === null)
1482
1871
  continue;
1483
- const carried = withdrawnDrafts(pendings.get(origin)?.drafts ?? [], changes);
1872
+ const carried = withdrawnDrafts(pendings.get(pendingKey(locator, origin))?.drafts ?? [], changes);
1484
1873
  drafted.set(replaced.id, replaced === join?.batch
1485
1874
  ? [
1486
1875
  ...carried.map((held) => joinedDraft(held, saved)),
@@ -1494,59 +1883,74 @@ export function composeRuntime(options) {
1494
1883
  for (const replaced of withdrawn.values()) {
1495
1884
  if (replaced === null || !batches.includes(replaced))
1496
1885
  continue;
1497
- const limited = limitedIn(batches, replaced, limits, (queue) => replicaOf(replica.confirmed, queue, replica).visible);
1886
+ const limited = await stepped(limiting(batches, replaced, limits, visibleOver));
1498
1887
  if (limited !== null)
1499
1888
  return { outcome: 'refused', ...limited };
1500
1889
  }
1501
- const consumed = saved.map(({ path }) => path);
1890
+ const carried = carriedDrafts(locator, saved, consumed);
1891
+ const left = [...consumed, ...carried.keys()];
1892
+ const arrived = [...carried.values()];
1893
+ let fencedRoom;
1502
1894
  try {
1503
- await local.keepAuthored({
1895
+ fencedRoom = await local.saveAuthored(files, {
1504
1896
  locator,
1505
1897
  queue: batches,
1506
1898
  saved: drafted,
1507
- consumedRoomDrafts: consumed,
1899
+ consumedRoomDrafts: left,
1900
+ roomDrafts: arrived,
1508
1901
  });
1509
1902
  }
1510
1903
  catch {
1511
1904
  return { outcome: 'refused', code: 'durable-write', retryable: true };
1512
1905
  }
1906
+ if (fencedRoom !== null) {
1907
+ throw runtimeError('room-not-held', `No Local Replica for ${fencedRoom}`);
1908
+ }
1909
+ const next = await stepped(replicating(replica.confirmed, batches, replica));
1910
+ const set = await stepped(changing(locator, replica, next, {
1911
+ queue: true,
1912
+ drafts: [...left, ...arrived.map(({ path }) => path)],
1913
+ }));
1513
1914
  if (fences.has(locator))
1514
1915
  throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
1515
1916
  for (const origin of withdrawn.keys())
1516
- pendings.delete(origin);
1917
+ pendings.delete(pendingKey(locator, origin));
1517
1918
  for (const [id, drafts] of drafted) {
1518
- pendings.set(id, { drafts, submission: { state: 'waiting' }, lost: false });
1919
+ pendings.set(pendingKey(locator, id), {
1920
+ drafts,
1921
+ submission: { state: 'waiting' },
1922
+ lost: false,
1923
+ });
1519
1924
  }
1520
- if (!localSaves)
1521
- recorded = false;
1522
- for (const path of consumed)
1925
+ for (const path of left)
1523
1926
  forgetRoomDraft(locator, path);
1524
- replicas.set(locator, replicaOf(replica.confirmed, batches, replica));
1525
- publishChangeSet(changeSet(locator, replica, replicas.get(locator) ?? null, {
1526
- queue: true,
1527
- drafts: consumed,
1528
- }));
1529
- moveTo({ ...(localSaves ? status : saving(status)), ...attention() });
1530
- submitLater(locator);
1927
+ for (const record of arrived)
1928
+ rememberRoomDraft(record);
1929
+ replicas.set(locator, next);
1930
+ publishChangeSet(set);
1931
+ queuedSave(locator);
1531
1932
  const identifier = join?.batch.id ??
1532
1933
  built?.batch.id ??
1533
1934
  [...requeue.withdrawn].map(([origin, replaced]) => replaced?.id ?? origin).at(-1);
1534
1935
  return { outcome: 'saved', identifier };
1535
1936
  }
1536
- async function mark(local, locator, identifier, submission, lost) {
1537
- const state = pendings.get(identifier);
1538
- if (!continuing() ||
1539
- state === undefined ||
1540
- (JSON.stringify(state.submission) === JSON.stringify(submission) && state.lost === lost)) {
1541
- return;
1937
+ async function mark(local, locator, batch, submission, lost) {
1938
+ const partner = partnerOf(batch, locator);
1939
+ for (const held of partner === null ? [locator] : [locator, partner]) {
1940
+ const state = pendings.get(pendingKey(held, batch.id));
1941
+ if (!continuing() ||
1942
+ state === undefined ||
1943
+ (JSON.stringify(state.submission) === JSON.stringify(submission) && state.lost === lost)) {
1944
+ continue;
1945
+ }
1946
+ await local.submit(held, batch.id, submission, lost);
1947
+ if (fences.has(held))
1948
+ continue;
1949
+ pendings.set(pendingKey(held, batch.id), { ...state, submission, lost });
1950
+ const replica = replicas.get(held);
1951
+ if (replica !== undefined)
1952
+ publishChangeSet(changeSet(held, replica, replica, { queue: true }));
1542
1953
  }
1543
- await local.submit(locator, identifier, submission, lost);
1544
- if (fences.has(locator))
1545
- return;
1546
- pendings.set(identifier, { ...state, submission, lost });
1547
- const replica = replicas.get(locator);
1548
- if (replica !== undefined)
1549
- publishChangeSet(changeSet(locator, replica, replica, { queue: true }));
1550
1954
  moveTo({ ...status, ...attention() });
1551
1955
  }
1552
1956
  async function keepUpload(local, locator, identifier, upload) {
@@ -1555,7 +1959,8 @@ export function composeRuntime(options) {
1555
1959
  await local.keepUpload(locator, identifier, upload);
1556
1960
  if (fences.has(locator))
1557
1961
  throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
1558
- pendings.set(identifier, { ...pendings.get(identifier), upload });
1962
+ const key = pendingKey(locator, identifier);
1963
+ pendings.set(key, { ...pendings.get(key), upload });
1559
1964
  if (!continuing())
1560
1965
  throw new Error('connection refused');
1561
1966
  }
@@ -1601,21 +2006,63 @@ export function composeRuntime(options) {
1601
2006
  return UNCERTAIN;
1602
2007
  }
1603
2008
  }
1604
- function queuedBlob(locator, path, localId) {
2009
+ function located(room, path, destination) {
2010
+ const crossing = roomTarget(destination);
2011
+ if (crossing === null) {
2012
+ const named = target(path, destination);
2013
+ return named === null || !rooms.has(room) ? null : { room, path: named };
2014
+ }
2015
+ const held = [...rooms.values()].find((listed) => listed.handle === crossing.handle);
2016
+ return held === undefined ? null : { room: held.locator, path: crossing.path };
2017
+ }
2018
+ async function resolveReference(room, path, destination) {
2019
+ if (roomTarget(destination) === null && target(path, destination) === null) {
2020
+ return ABSENT_TARGET;
2021
+ }
2022
+ const at = located(room, path, destination);
2023
+ if (at === null)
2024
+ return UNREADABLE;
2025
+ if (locked(at.room))
2026
+ return LOCKED_UNREADABLE;
2027
+ const visible = replicas.get(at.room)?.visible;
2028
+ if (visible?.documents[at.path] !== undefined || visible?.binaries[at.path] !== undefined) {
2029
+ return { kind: 'document', ...at };
2030
+ }
2031
+ const history = await readHistory(at.room, at.path);
2032
+ if (history.kind === 'no-history' || history.kind === 'revision')
2033
+ return ABSENT_TARGET;
2034
+ if (history.kind !== 'history')
2035
+ return history;
2036
+ const [last] = history.revisions;
2037
+ if (last === undefined)
2038
+ return ABSENT_TARGET;
2039
+ return history.deleted === true
2040
+ ? { kind: 'deleted', ...at, revision: last }
2041
+ : { kind: 'document', ...at };
2042
+ }
2043
+ async function queuedBlob(locator, path, localId) {
1605
2044
  for (const batch of replicas.get(locator)?.queue ?? []) {
1606
2045
  const change = batch.changes[queuedFile(batch, path, localId)];
1607
2046
  if (change?.kind === 'binary')
1608
- return change.blob;
2047
+ return (await openLocal()).file(localId, change.mediaType);
1609
2048
  }
1610
- return null;
2049
+ const drafted = roomDrafts.get(locator)?.get(path)?.parts.file;
2050
+ return drafted?.localId === localId
2051
+ ? (await openLocal()).file(localId, drafted.mediaType)
2052
+ : null;
2053
+ }
2054
+ function batchFile(batch) {
2055
+ return async (localId) => {
2056
+ const change = batch.changes.find((held) => held.kind === 'binary' && held.localId === localId);
2057
+ return (await openLocal()).file(localId, change?.kind === 'binary' ? change.mediaType : '');
2058
+ };
1611
2059
  }
1612
2060
  function binaryRoom(request) {
1613
2061
  if (request.kind === 'path')
1614
2062
  return request.locator;
1615
- const scope = options.adapter.referrerScope(request.referrer);
1616
- return scope?.kind === 'room' ? scope.locator : null;
2063
+ return options.adapter.referrerScope(request.referrer)?.locator ?? null;
1617
2064
  }
1618
- async function readBinary(request) {
2065
+ async function transferBinary(request, transfer, answer) {
1619
2066
  if (closed || refusal !== null)
1620
2067
  return UNCERTAIN;
1621
2068
  try {
@@ -1631,40 +2078,41 @@ export function composeRuntime(options) {
1631
2078
  ? `transfer binary ${request.locator} ${request.path}`
1632
2079
  : `transfer binary ${request.fileRef}`);
1633
2080
  try {
1634
- const result = await options.adapter.binary(authorization, request);
1635
- journal.record(`outcome binary ${result.kind}`);
2081
+ const result = await transfer(authorization);
2082
+ const settled = result;
2083
+ journal.record(`outcome binary ${settled.kind}`);
1636
2084
  const locator = binaryRoom(request);
1637
2085
  if (locator !== null && fencedSince(locator, since))
1638
2086
  return failure({ kind: 'room-not-readable', locator });
1639
- if (result.kind === 'scoped-refusal') {
1640
- const room = replicas.get(result.locator)?.confirmed.record;
2087
+ if (settled.kind === 'scoped-refusal') {
2088
+ const room = replicas.get(settled.locator)?.confirmed.record;
1641
2089
  if (room !== undefined)
1642
- await scoped(result, room, await openLocal());
2090
+ await scoped(settled, room, await openLocal());
1643
2091
  }
1644
- if (result.kind === 'revoked-authorization')
2092
+ if (settled.kind === 'revoked-authorization')
1645
2093
  await refuse('revoked-authorization');
1646
- return binaryAnswer(result);
2094
+ return answer(result);
1647
2095
  }
1648
2096
  catch {
1649
2097
  journal.record('outcome binary transport-uncertainty');
1650
2098
  return UNCERTAIN;
1651
2099
  }
1652
2100
  }
1653
- async function readBinaryPath(locator, path, revision) {
1654
- await ready;
2101
+ function readBinary(request) {
2102
+ return transferBinary(request, (held) => options.adapter.binary(held, request), binaryAnswer);
2103
+ }
2104
+ function binaryPath(locator, path, revision) {
1655
2105
  if (revision !== undefined)
1656
- return readBinary({ kind: 'path', locator, path, revision });
2106
+ return { kind: 'path', locator, path, revision };
1657
2107
  const visible = replicas.get(locator)?.visible;
1658
2108
  const held = visible?.binaries[path];
1659
2109
  if (visible === undefined || held === undefined)
1660
- return absentBinary(path);
1661
- if (held.state === 'pending') {
1662
- const blob = queuedBlob(locator, path, held.localId);
1663
- return blob === null ? absentBinary(path) : { kind: 'binary', blob };
1664
- }
2110
+ return null;
2111
+ if (held.state === 'pending')
2112
+ return { kind: 'pending', localId: held.localId };
1665
2113
  const record = binaryRecord(path, held, visible.revisions[path]);
1666
2114
  if (record.state !== 'accepted')
1667
- return absentBinary(path);
2115
+ return null;
1668
2116
  const replica = replicas.get(locator);
1669
2117
  const queued = (replica?.queue ?? []).flatMap((batch) => batch.changes);
1670
2118
  const holds = (at) => {
@@ -1679,13 +2127,34 @@ export function composeRuntime(options) {
1679
2127
  if (change.kind === 'move' && change.to === confirmed)
1680
2128
  confirmed = change.path;
1681
2129
  }
1682
- return readBinary({
2130
+ return {
1683
2131
  kind: 'path',
1684
2132
  locator,
1685
2133
  path: confirmed,
1686
2134
  revision: record.revision,
1687
2135
  fileRef: record.fileRef,
1688
- });
2136
+ };
2137
+ }
2138
+ async function readBinaryPath(locator, path, revision) {
2139
+ await ready;
2140
+ const drafted = roomDrafts.get(locator)?.get(path)?.parts.file;
2141
+ const asked = drafted !== undefined && drafted.localId === revision
2142
+ ? { kind: 'pending', localId: revision }
2143
+ : binaryPath(locator, path, revision);
2144
+ if (asked === null)
2145
+ return absentBinary(path);
2146
+ if (asked.kind === 'pending') {
2147
+ const blob = await queuedBlob(locator, path, asked.localId);
2148
+ return blob === null ? absentBinary(path) : { kind: 'binary', blob };
2149
+ }
2150
+ return readBinary(asked);
2151
+ }
2152
+ async function linkBinaryPath(locator, path, revision) {
2153
+ await ready;
2154
+ const asked = binaryPath(locator, path, revision);
2155
+ if (asked === null || asked.kind === 'pending')
2156
+ return absentBinary(path);
2157
+ return transferBinary(asked, (held) => options.adapter.link(held, asked), binaryLinkAnswer);
1689
2158
  }
1690
2159
  async function readBinaryReference(reference) {
1691
2160
  await ready;
@@ -1711,7 +2180,14 @@ export function composeRuntime(options) {
1711
2180
  }
1712
2181
  return undefined;
1713
2182
  }
1714
- async function invokeAction(name, input) {
2183
+ function calledRooms(name, input) {
2184
+ const member = declaredAction(name)?.room;
2185
+ if (member === undefined || input === null || typeof input !== 'object')
2186
+ return [];
2187
+ const named = input[member];
2188
+ return (Array.isArray(named) ? named : [named]).filter((room) => typeof room === 'string');
2189
+ }
2190
+ async function invokeAction(name, input, dispatching) {
1715
2191
  await ready;
1716
2192
  if (closed || refusal !== null)
1717
2193
  return UNCERTAIN;
@@ -1725,6 +2201,7 @@ export function composeRuntime(options) {
1725
2201
  }
1726
2202
  if (closed || authorization === undefined || refusal !== null)
1727
2203
  return UNCERTAIN;
2204
+ await dispatching?.();
1728
2205
  journal.record(`transfer action ${name}`);
1729
2206
  try {
1730
2207
  const result = await options.adapter.action(authorization, { name, input });
@@ -1745,6 +2222,60 @@ export function composeRuntime(options) {
1745
2222
  return UNCERTAIN;
1746
2223
  }
1747
2224
  }
2225
+ function unsettled(result) {
2226
+ return result.kind !== 'action' && result.retryable;
2227
+ }
2228
+ async function recoveredAction(name, input) {
2229
+ const operation = operationOf(input);
2230
+ if (operation === null)
2231
+ return invokeAction(name, input);
2232
+ const kept = async () => (await openLocal()).keepCall({ operation, name, input });
2233
+ calling.add(operation);
2234
+ try {
2235
+ let result = await invokeAction(name, input, kept);
2236
+ if (unsettled(result)) {
2237
+ await recovery.attempt(`action ${operation}`, async () => {
2238
+ if (closed || refusal !== null)
2239
+ return 'done';
2240
+ if (!socketOpen)
2241
+ return 'again';
2242
+ result = await invokeAction(name, input, kept);
2243
+ return unsettled(result) ? 'again' : 'done';
2244
+ }, { again: true });
2245
+ }
2246
+ if (!unsettled(result))
2247
+ await (await openLocal()).dropCall(operation);
2248
+ return result;
2249
+ }
2250
+ finally {
2251
+ calling.delete(operation);
2252
+ }
2253
+ }
2254
+ async function resendCalls(signal) {
2255
+ if (!socketOpen || closed || stopping)
2256
+ return 'done';
2257
+ const local = await openLocal();
2258
+ for (const held of await local.calls()) {
2259
+ if (calling.has(held.operation))
2260
+ continue;
2261
+ if (closed || signal.aborted)
2262
+ return 'done';
2263
+ if (pastHorizon(held.operation)) {
2264
+ await local.dropCall(held.operation);
2265
+ continue;
2266
+ }
2267
+ calling.add(held.operation);
2268
+ try {
2269
+ if (unsettled(await invokeAction(held.name, held.input)))
2270
+ return 'again';
2271
+ await local.dropCall(held.operation);
2272
+ }
2273
+ finally {
2274
+ calling.delete(held.operation);
2275
+ }
2276
+ }
2277
+ return 'done';
2278
+ }
1748
2279
  function continuing() {
1749
2280
  return !closed && !discoveryPaused;
1750
2281
  }
@@ -1762,8 +2293,9 @@ export function composeRuntime(options) {
1762
2293
  async function pullRefresh(authorized, confirmed, live) {
1763
2294
  if (!live())
1764
2295
  return unconfirmed;
2296
+ const turn = generation;
1765
2297
  try {
1766
- const result = await refreshRoom(options.adapter, authorized, confirmed, (models, held) => (live() ? remodel(confirmed.record.locator, models, held) : held), live);
2298
+ const result = await refreshRoom(reads, authorized, confirmed, (models, held) => (live() ? remodel(confirmed.record.locator, models, held) : held), live);
1767
2299
  const detail = result.kind === 'advanced' ? result.confirmed.record.roomVersion : result.kind;
1768
2300
  journal.record(`transfer refresh ${confirmed.record.locator} ${detail}`);
1769
2301
  return result;
@@ -1772,6 +2304,9 @@ export function composeRuntime(options) {
1772
2304
  journal.record(`transfer refresh ${confirmed.record.locator} transport-uncertainty`);
1773
2305
  throw error;
1774
2306
  }
2307
+ finally {
2308
+ reads.finished(confirmed.record.locator, turn);
2309
+ }
1775
2310
  }
1776
2311
  function staging(local, live) {
1777
2312
  return {
@@ -1814,12 +2349,13 @@ export function composeRuntime(options) {
1814
2349
  async function pullBootstrap(authorized, room, local, live) {
1815
2350
  if (!live())
1816
2351
  return unconfirmed;
2352
+ const turn = generation;
1817
2353
  if (replicas.has(room.locator)) {
1818
2354
  catching.add(room.locator);
1819
2355
  readSide.recover();
1820
2356
  }
1821
2357
  try {
1822
- const result = await bootstrapRoom(options.adapter, authorized, room, {
2358
+ const result = await bootstrapRoom(reads, authorized, room, {
1823
2359
  collection: modelOf(room.locator),
1824
2360
  selection: modelOf(room.locator, 'typed-selection'),
1825
2361
  }, (models, held) => (live() ? remodel(room.locator, models, held) : held), live, staging(local, live), reusable(room));
@@ -1834,12 +2370,28 @@ export function composeRuntime(options) {
1834
2370
  caughtUpTo(room.locator);
1835
2371
  throw error;
1836
2372
  }
2373
+ finally {
2374
+ reads.finished(room.locator, turn);
2375
+ }
1837
2376
  }
1838
2377
  function caughtUpTo(locator) {
1839
2378
  if (catching.delete(locator))
1840
2379
  readSide.recover();
1841
2380
  }
2381
+ function behind(room) {
2382
+ const held = replicas.get(room.locator)?.confirmed.record.roomVersion;
2383
+ return (held !== undefined &&
2384
+ [announced.get(room.locator), room.roomVersion].some((later) => later !== undefined && !options.adapter.reached(room.locator, held, later)));
2385
+ }
1842
2386
  async function advance(room, local, authorized, live) {
2387
+ const carried = reads.carried(room.locator);
2388
+ const withheld = await advanceOnce(room, local, authorized, live);
2389
+ if (withheld !== null || reads.carried(room.locator) === carried || !behind(room)) {
2390
+ return withheld;
2391
+ }
2392
+ return advanceOnce(room, local, authorized, live);
2393
+ }
2394
+ async function advanceOnce(room, local, authorized, live) {
1843
2395
  await referenced(room.locator);
1844
2396
  if (!live() || paused.has(room.locator))
1845
2397
  return unconfirmed;
@@ -1876,6 +2428,8 @@ export function composeRuntime(options) {
1876
2428
  readSide.recover();
1877
2429
  return unconfirmed;
1878
2430
  }
2431
+ if (reloadsDue.get(room.locator) === generation)
2432
+ return unconfirmed;
1879
2433
  }
1880
2434
  const bootstrapped = await pullBootstrap(authorized, room, local, live);
1881
2435
  if (!live())
@@ -1967,19 +2521,20 @@ export function composeRuntime(options) {
1967
2521
  logAccepted(room.locator, submitted, accepted);
1968
2522
  const applied = options.adapter.reached(room.locator, held, accepted.roomVersion)
1969
2523
  ? { kind: 'staged', confirmed: current.confirmed }
1970
- : applyReturned(current.confirmed, submitted, accepted, options.adapter.follows(room.locator, held, accepted.roomVersion)
2524
+ : await applyReturned(current.confirmed, submitted, accepted, options.adapter.follows(room.locator, held, accepted.roomVersion)
1971
2525
  ? accepted.roomVersion
1972
2526
  : held, accepted.roomVersion);
1973
2527
  if (applied.kind !== 'staged') {
1974
- const state = pendings.get(submitted.id);
2528
+ const key = pendingKey(room.locator, submitted.id);
2529
+ const state = pendings.get(key);
1975
2530
  await local.accept(room.locator, submitted.id, accepted.roomVersion);
1976
2531
  if (state !== undefined && !fences.has(room.locator))
1977
- pendings.set(submitted.id, { ...state, accepted: accepted.roomVersion });
2532
+ pendings.set(key, { ...state, accepted: accepted.roomVersion });
1978
2533
  emitQueue(room.locator);
1979
2534
  return applied;
1980
2535
  }
1981
2536
  const settled = await settle(local, room.locator, current, applied.confirmed, current.queue.filter((batch) => batch.id !== submitted.id), { room: true });
1982
- pendings.delete(submitted.id);
2537
+ pendings.delete(pendingKey(room.locator, submitted.id));
1983
2538
  unreadable.delete(room.locator);
1984
2539
  sourceRefusals.delete(room.locator);
1985
2540
  declarationRefusals.delete(room.locator);
@@ -1990,22 +2545,150 @@ export function composeRuntime(options) {
1990
2545
  return null;
1991
2546
  }
1992
2547
  async function adopted(room, local, submitted, accepted) {
1993
- const failed = await exclusive(() => adoptAccepted(room, local, submitted, accepted));
2548
+ const failed = await exclusive(async () => {
2549
+ const adopting = await adoptAccepted(room, local, submitted, accepted);
2550
+ await unpair(local);
2551
+ return adopting;
2552
+ });
1994
2553
  if (failed === null)
1995
2554
  return true;
1996
2555
  if (failed.kind === 'refused' && continuing())
1997
2556
  refusedSource(room, failed);
1998
2557
  return false;
1999
2558
  }
2559
+ async function adoptedMove(room, partner, local, submitted, accepted) {
2560
+ const other = discovered.get(partner);
2561
+ const failed = await exclusive(async () => {
2562
+ const left = await adoptAccepted(room, local, submitted, accepted);
2563
+ const arriving = replicas.get(partner)?.queue.find((batch) => batch.id === submitted.id);
2564
+ const arrived = other === undefined || arriving === undefined || accepted.destination === undefined
2565
+ ? null
2566
+ : await adoptAccepted(other, local, arriving, {
2567
+ kind: 'accepted',
2568
+ ...accepted.destination,
2569
+ });
2570
+ if (other !== undefined && arrived?.kind === 'refused' && continuing()) {
2571
+ refusedSource(other, arrived);
2572
+ }
2573
+ await unpair(local);
2574
+ return left;
2575
+ });
2576
+ submitLater(partner);
2577
+ if (failed === null)
2578
+ return true;
2579
+ if (failed.kind === 'refused' && continuing())
2580
+ refusedSource(room, failed);
2581
+ return false;
2582
+ }
2583
+ function queueIn(locator) {
2584
+ return replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? [];
2585
+ }
2586
+ function behindIn(locator, batch) {
2587
+ const held = replicas.get(locator)?.queue;
2588
+ if (held === undefined)
2589
+ return queuesWithoutReplica.get(locator) !== undefined;
2590
+ return held.findIndex((one) => one.id === batch.id) > 0;
2591
+ }
2592
+ function unpaired(skipped) {
2593
+ for (const locator of [...replicas.keys(), ...queuesWithoutReplica.keys()]) {
2594
+ for (const batch of queueIn(locator)) {
2595
+ const partner = partnerOf(batch, locator);
2596
+ if (partner === null || skipped.has(pendingKey(locator, batch.id)))
2597
+ continue;
2598
+ if (queueIn(partner).some((held) => held.id === batch.id))
2599
+ continue;
2600
+ if (pendings.get(pendingKey(locator, batch.id))?.accepted !== undefined)
2601
+ continue;
2602
+ if (leavingIn(batch, locator) && !withdrawable(locator)(batch))
2603
+ continue;
2604
+ return { locator, batch };
2605
+ }
2606
+ }
2607
+ return null;
2608
+ }
2609
+ async function unpair(local) {
2610
+ const handled = new Set();
2611
+ for (let held = unpaired(handled); held !== null && continuing(); held = unpaired(handled)) {
2612
+ const { locator, batch } = held;
2613
+ handled.add(pendingKey(locator, batch.id));
2614
+ journal.record(`outcome ${locator} ${batch.id} ${localSaves ? 'dropped' : 'unpaired'}`);
2615
+ const leaving = {
2616
+ batch,
2617
+ returned: !localSaves && leavingIn(batch, locator) ? returnedBy('withdrawn') : null,
2618
+ };
2619
+ const current = replicas.get(locator);
2620
+ if (current !== undefined) {
2621
+ const settled = await settle(local, locator, current, current.confirmed, current.queue.filter((one) => one.id !== batch.id), { leaving });
2622
+ publishChangeSet(settled());
2623
+ continue;
2624
+ }
2625
+ const queue = queueIn(locator).filter((one) => one.id !== batch.id);
2626
+ const written = new Map((leaving.returned === null
2627
+ ? []
2628
+ : (pendings.get(pendingKey(locator, batch.id))?.drafts ?? [])).map((saved) => [
2629
+ saved.path,
2630
+ {
2631
+ locator,
2632
+ path: saved.path,
2633
+ revision: roomDraftRevision(),
2634
+ parts: returnedInto(roomDrafts.get(locator)?.get(saved.path)?.parts, saved.parts),
2635
+ returned: leaving.returned,
2636
+ },
2637
+ ]));
2638
+ const carried = carriedBack(locator, leaving.returned === null ? [] : [batch], written);
2639
+ await local.keepAuthored({
2640
+ locator,
2641
+ queue,
2642
+ roomDrafts: [...written.values()],
2643
+ consumedRoomDrafts: carried.taken,
2644
+ }, ...carried.writes);
2645
+ pendings.delete(pendingKey(locator, batch.id));
2646
+ if (queue.length > 0)
2647
+ queuesWithoutReplica.set(locator, queue);
2648
+ else
2649
+ queuesWithoutReplica.delete(locator);
2650
+ for (const record of written.values())
2651
+ rememberRoomDraft(record);
2652
+ carried.remember();
2653
+ publishChangeSet(mergeChangeSets([
2654
+ changeSet(locator, null, null, {
2655
+ queue: true,
2656
+ drafts: [...written.keys(), ...carried.taken],
2657
+ }),
2658
+ ...carried.changes,
2659
+ ]));
2660
+ }
2661
+ if (handled.size === 0)
2662
+ return;
2663
+ moveTo({ ...status, ...attention() });
2664
+ for (const key of handled)
2665
+ submitLater(key.slice(0, key.indexOf('\u0000')));
2666
+ }
2667
+ async function discardHeld(head, room, local, signal) {
2668
+ const partner = partnerOf(head, room.locator);
2669
+ const other = partner === null ? undefined : discovered.get(partner);
2670
+ await discardPending(room, local, signal);
2671
+ if (other !== undefined && !signal.aborted)
2672
+ await discardPending(other, local, signal);
2673
+ }
2000
2674
  async function submitRoom(room, local, authorized, progress, signal) {
2001
2675
  while (continuing() && authorization !== undefined && !signal.aborted) {
2002
2676
  const replica = replicas.get(room.locator);
2003
2677
  const head = replica?.queue[0];
2004
2678
  if (replica === undefined || head === undefined)
2005
2679
  return 'done';
2006
- if (pendings.get(head.id)?.accepted !== undefined)
2680
+ const state = pendings.get(pendingKey(room.locator, head.id));
2681
+ if (state?.accepted !== undefined)
2682
+ return 'done';
2683
+ const partner = partnerOf(head, room.locator);
2684
+ if (partner !== null && !leavingIn(head, room.locator)) {
2685
+ submitLater(partner);
2686
+ return 'done';
2687
+ }
2688
+ if (partner !== null && behindIn(partner, head)) {
2689
+ progress.complete = false;
2007
2690
  return 'done';
2008
- const state = pendings.get(head.id);
2691
+ }
2009
2692
  const { submission, lost: earlier } = state ?? {
2010
2693
  submission: { state: 'waiting' },
2011
2694
  lost: false,
@@ -2021,16 +2704,16 @@ export function composeRuntime(options) {
2021
2704
  }
2022
2705
  const lost = earlier || submission.state === 'submitted';
2023
2706
  if (lost && pastHorizon(head.id)) {
2024
- await discardPending(room, local, signal);
2707
+ await discardHeld(head, room, local, signal);
2025
2708
  return 'done';
2026
2709
  }
2027
2710
  let result;
2028
2711
  journal.record(`submission ${room.locator} ${head.id}`);
2029
- await exclusive(() => mark(local, room.locator, head.id, { state: 'submitted' }, lost));
2712
+ await exclusive(() => mark(local, room.locator, head, { state: 'submitted' }, lost));
2030
2713
  if (discoveryPaused || fences.has(room.locator))
2031
2714
  return 'done';
2032
2715
  if (signal.aborted || writesHeld()) {
2033
- await exclusive(() => mark(local, room.locator, head.id, submission, earlier));
2716
+ await exclusive(() => mark(local, room.locator, head, submission, earlier));
2034
2717
  if (signal.aborted)
2035
2718
  return 'done';
2036
2719
  progress.complete = false;
@@ -2038,11 +2721,17 @@ export function composeRuntime(options) {
2038
2721
  return 'done';
2039
2722
  }
2040
2723
  const opensBefore = openSignals;
2041
- const answered = awaitingAnswer(room.locator);
2724
+ const answeredHere = awaitingAnswer(room.locator);
2725
+ const answeredThere = partner === null ? () => { } : awaitingAnswer(partner);
2726
+ const answered = () => {
2727
+ answeredHere();
2728
+ answeredThere();
2729
+ };
2042
2730
  try {
2043
2731
  result = await options.adapter.mutate(authorized, {
2044
2732
  locator: room.locator,
2045
2733
  changeBatch: head,
2734
+ file: batchFile(head),
2046
2735
  ...(state?.upload === undefined ? {} : { upload: state.upload }),
2047
2736
  }, (upload) => exclusive(() => keepUpload(local, room.locator, head.id, upload)));
2048
2737
  }
@@ -2067,9 +2756,10 @@ export function composeRuntime(options) {
2067
2756
  return 'again';
2068
2757
  }
2069
2758
  if (result.kind === 'room-not-readable') {
2759
+ const unread = discovered.get(result.locator) ?? room;
2070
2760
  progress.complete = false;
2071
- unreadable.add(room.locator);
2072
- list(room, false);
2761
+ unreadable.add(unread.locator);
2762
+ list(unread, false);
2073
2763
  emitRooms();
2074
2764
  return 'done';
2075
2765
  }
@@ -2084,24 +2774,30 @@ export function composeRuntime(options) {
2084
2774
  }
2085
2775
  if (result.kind === 'write-halted') {
2086
2776
  journal.record(`outcome ${room.locator} ${head.id} write-halted`);
2087
- await exclusive(() => mark(local, room.locator, head.id, { state: 'waiting' }, lost));
2777
+ await exclusive(() => mark(local, room.locator, head, { state: 'waiting' }, lost));
2088
2778
  if (serviceMode === 'open' && openSignals !== opensBefore)
2089
2779
  continue;
2090
2780
  haltedRefusal = true;
2091
2781
  progress.complete = false;
2092
2782
  return 'done';
2093
2783
  }
2784
+ const other = partner === null ? undefined : discovered.get(partner);
2094
2785
  if (result.kind === 'conflicted' ||
2095
2786
  result.kind === 'rejected' ||
2096
2787
  result.kind === 'expired' ||
2097
2788
  result.kind === 'retryable-refusal') {
2098
2789
  if (result.kind === 'expired' && lost && result.restored !== true) {
2099
2790
  journal.record(`outcome ${room.locator} ${head.id} expired`);
2100
- await discardPending(room, local, signal);
2791
+ await discardHeld(head, room, local, signal);
2101
2792
  return 'done';
2102
2793
  }
2103
2794
  if (result.kind === 'expired') {
2104
- await exclusive(() => mark(local, room.locator, head.id, { state: 'waiting' }, false));
2795
+ await exclusive(() => mark(local, room.locator, head, { state: 'waiting' }, partner !== null && lost));
2796
+ const there = other === undefined ? null : await advance(other, local, authorized, continuing);
2797
+ if (other !== undefined && there !== null) {
2798
+ await withhold(there, other, local, progress);
2799
+ return 'done';
2800
+ }
2105
2801
  const withheld = await advance(room, local, authorized, continuing);
2106
2802
  if (withheld !== null) {
2107
2803
  await withhold(withheld, room, local, progress);
@@ -2118,11 +2814,25 @@ export function composeRuntime(options) {
2118
2814
  if (result.kind === 'retryable-refusal') {
2119
2815
  const reset = result.reset;
2120
2816
  progress.complete = false;
2121
- await exclusive(() => mark(local, room.locator, head.id, reset === undefined ? { state: 'waiting' } : { state: 'reset', reset }, lost));
2817
+ await exclusive(() => mark(local, room.locator, head, reset === undefined ? { state: 'waiting' } : { state: 'reset', reset }, lost));
2122
2818
  return reset === undefined ? 'again' : { at: Date.parse(reset) };
2123
2819
  }
2124
2820
  if (result.kind === 'conflicted' || result.kind === 'rejected' || result.kind === 'expired') {
2125
2821
  const left = leaving(head, result);
2822
+ const refreshed = async () => ({
2823
+ there: other === undefined ? null : await advance(other, local, authorized, continuing),
2824
+ here: await advance(room, local, authorized, continuing),
2825
+ });
2826
+ const judged = result.kind === 'conflicted' && other !== undefined ? await refreshed() : null;
2827
+ if (judged !== null && (judged.there !== null || judged.here !== null)) {
2828
+ await exclusive(() => mark(local, room.locator, head, { state: 'waiting' }, lost));
2829
+ if (other !== undefined && judged.there !== null) {
2830
+ await withhold(judged.there, other, local, progress);
2831
+ }
2832
+ if (judged.here !== null)
2833
+ await withhold(judged.here, room, local, progress);
2834
+ return 'done';
2835
+ }
2126
2836
  await exclusive(async () => {
2127
2837
  if (!continuing())
2128
2838
  return;
@@ -2131,24 +2841,30 @@ export function composeRuntime(options) {
2131
2841
  return;
2132
2842
  }
2133
2843
  const settled = await settle(local, room.locator, current, current.confirmed, current.queue.filter((batch) => batch.id !== head.id), {
2134
- leaving: (result.kind === 'expired' && landed(head, current.confirmed)) ||
2135
- (result.kind === 'conflicted' && landed(head, current.confirmed, result.affected))
2844
+ leaving: (result.kind === 'expired' && landedWhole(room.locator, head, current.confirmed)) ||
2845
+ (result.kind === 'conflicted' &&
2846
+ landedWhole(room.locator, head, current.confirmed, result.affected))
2136
2847
  ? { ...left, returned: null }
2137
2848
  : left,
2138
2849
  });
2139
2850
  publishChangeSet(settled());
2851
+ await unpair(local);
2140
2852
  moveTo({ ...status, ...attention() });
2141
2853
  });
2142
2854
  if (result.kind === 'expired')
2143
2855
  continue;
2144
- const withheld = await advance(room, local, authorized, continuing);
2145
- if (withheld !== null) {
2146
- await withhold(withheld, room, local, progress);
2856
+ const { there, here } = judged ?? (await refreshed());
2857
+ if (other !== undefined && there !== null)
2858
+ await withhold(there, other, local, progress);
2859
+ if (here !== null) {
2860
+ await withhold(here, room, local, progress);
2147
2861
  return 'done';
2148
2862
  }
2149
2863
  continue;
2150
2864
  }
2151
- const kept = await adopted(room, local, head, result).finally(answered);
2865
+ const kept = await (partner === null
2866
+ ? adopted(room, local, head, result)
2867
+ : adoptedMove(room, partner, local, head, result)).finally(answered);
2152
2868
  if (!kept) {
2153
2869
  progress.complete = false;
2154
2870
  return 'done';
@@ -2175,9 +2891,9 @@ export function composeRuntime(options) {
2175
2891
  fences.delete(locator);
2176
2892
  }
2177
2893
  for (const batch of queue)
2178
- pendings.delete(batch.id);
2894
+ pendings.delete(pendingKey(locator, batch.id));
2179
2895
  queuesWithoutReplica.delete(locator);
2180
- const after = before === undefined ? null : replicaOf(before.confirmed, [], before);
2896
+ const after = before === undefined ? null : await stepped(replicating(before.confirmed, [], before));
2181
2897
  if (after !== null)
2182
2898
  replicas.set(locator, after);
2183
2899
  journal.record(`room discarded ${locator}`);
@@ -2229,6 +2945,7 @@ export function composeRuntime(options) {
2229
2945
  if (!continuing())
2230
2946
  return;
2231
2947
  const held = replicas.get(room.locator);
2948
+ let changed = null;
2232
2949
  if (held !== undefined) {
2233
2950
  const declared = {
2234
2951
  ...held.confirmed.record,
@@ -2238,8 +2955,8 @@ export function composeRuntime(options) {
2238
2955
  ...(attached === 'collection' ? { model: next } : { selectionModel: next }),
2239
2956
  };
2240
2957
  const reclassified = sameMembership(declared, held.confirmed.record)
2241
- ? { kind: 'staged', confirmed: confirmedOf(declared, held.confirmed) }
2242
- : readReclassified(declared, held.confirmed);
2958
+ ? { kind: 'staged', confirmed: await confirmedOf(declared, held.confirmed) }
2959
+ : await readReclassified(declared, held.confirmed);
2243
2960
  const record = reclassified.kind === 'staged'
2244
2961
  ? declared
2245
2962
  : {
@@ -2247,18 +2964,23 @@ export function composeRuntime(options) {
2247
2964
  typedSelection: held.confirmed.record.typedSelection,
2248
2965
  };
2249
2966
  const read = reclassified.kind === 'deferred'
2250
- ? { kind: 'staged', confirmed: confirmedOf(record, held.confirmed) }
2967
+ ? { kind: 'staged', confirmed: await confirmedOf(record, held.confirmed) }
2251
2968
  : reclassified;
2252
2969
  await local.write({ next: record, previous: held.confirmed.record });
2970
+ const replica = read.kind === 'staged'
2971
+ ? await stepped(replicating(read.confirmed, held.queue, held))
2972
+ : { ...held, confirmed: { ...held.confirmed, record } };
2973
+ await stepped(counting(replica));
2974
+ const set = await stepped(changing(room.locator, held, replica, { room: true }));
2975
+ replicas.set(room.locator, replica);
2976
+ changed = heldChange(room.locator, held, replica, set, { room: true });
2253
2977
  if (read.kind === 'staged') {
2254
- replicas.set(room.locator, replicaOf(read.confirmed, held.queue, held));
2255
2978
  if (declarationRefusals.delete(room.locator)) {
2256
2979
  sourceRefusals.delete(room.locator);
2257
2980
  unreadable.delete(room.locator);
2258
2981
  }
2259
2982
  }
2260
- else if (read.kind === 'refused') {
2261
- replicas.set(room.locator, { ...held, confirmed: { ...held.confirmed, record } });
2983
+ else {
2262
2984
  refusedSource(room, read);
2263
2985
  declarationRefusals.add(room.locator);
2264
2986
  }
@@ -2269,13 +2991,18 @@ export function composeRuntime(options) {
2269
2991
  invalidModels.delete(key);
2270
2992
  }
2271
2993
  list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));
2272
- if (held === undefined)
2994
+ if (changed === null)
2273
2995
  emitRooms();
2274
2996
  else
2275
- publishChangeSet(changeSet(room.locator, held, replicas.get(room.locator) ?? null, { room: true }));
2997
+ publishChangeSet(changed);
2276
2998
  });
2277
2999
  }
2278
3000
  async function scoped(result, room, local) {
3001
+ if (result.scope === 'content' && !result.retryable) {
3002
+ journal.record(`scoped refusal ${room.locator} ${result.scope} ${result.code}`);
3003
+ await loseRooms([room.locator]);
3004
+ return;
3005
+ }
2279
3006
  scopedRefusals.set(room.locator, {
2280
3007
  code: result.code,
2281
3008
  fields: result.fields,
@@ -2289,15 +3016,7 @@ export function composeRuntime(options) {
2289
3016
  });
2290
3017
  else if (result.scope !== 'operation') {
2291
3018
  unreadable.add(room.locator);
2292
- scopedAway = {
2293
- ...room,
2294
- replica: { ...room.replica, admission: 'unavailable' },
2295
- operations: {
2296
- ...room.operations,
2297
- ...(result.scope === 'content' ? { read: [] } : {}),
2298
- ...(result.scope === 'sync' ? { sync: [] } : {}),
2299
- },
2300
- };
3019
+ scopedAway = { ...room, replica: { ...room.replica, admission: 'unavailable' } };
2301
3020
  await retainModel(local, scopedAway, 'collection', modelOf(room.locator));
2302
3021
  }
2303
3022
  if (!continuing())
@@ -2322,16 +3041,15 @@ export function composeRuntime(options) {
2322
3041
  });
2323
3042
  }
2324
3043
  async function synchronize(listed, local, progress, attempt, live) {
2325
- const acquired = listed.filter(acquires);
2326
- const prepared = await Promise.allSettled(acquired.map((room) => prepareRoom(room, local, progress)));
3044
+ const prepared = await Promise.allSettled(listed.map((room) => prepareRoom(room, local, progress)));
2327
3045
  if (!live())
2328
3046
  return;
2329
- const ready = acquired.filter((_, index) => {
3047
+ const ready = listed.filter((_, index) => {
2330
3048
  const outcome = prepared[index];
2331
3049
  return outcome?.status === 'fulfilled' && outcome.value;
2332
3050
  });
2333
3051
  if (attempt === 'opened') {
2334
- options.adapter.roomStream?.hold(heldRooms(ready), heldDemand(acquired));
3052
+ options.adapter.roomStream?.hold(heldRooms(ready));
2335
3053
  handed = true;
2336
3054
  }
2337
3055
  discovering?.release();
@@ -2359,19 +3077,10 @@ export function composeRuntime(options) {
2359
3077
  await retainModel(local, room, 'collection', modelOf(room.locator));
2360
3078
  if (discoveryPaused || authorization === undefined)
2361
3079
  return false;
2362
- if (room.replica.admission !== 'admitted') {
2363
- if (replicas.has(room.locator))
2364
- progress.complete = false;
2365
- return false;
2366
- }
2367
- return true;
3080
+ return room.replica.admission === 'admitted';
2368
3081
  }
2369
3082
  async function caughtUp(room, local, progress, live) {
2370
- const held = replicas.get(room.locator)?.confirmed.record.roomVersion;
2371
- if (held === undefined || authorization === undefined || !live())
2372
- return;
2373
- const behind = [announced.get(room.locator), room.roomVersion].some((later) => later !== undefined && !options.adapter.reached(room.locator, held, later));
2374
- if (!behind)
3083
+ if (authorization === undefined || !live() || !behind(room))
2375
3084
  return;
2376
3085
  const withheld = await advance(room, local, authorization, live);
2377
3086
  if (withheld !== null)
@@ -2399,6 +3108,8 @@ export function composeRuntime(options) {
2399
3108
  }
2400
3109
  async function reload(room, local, progress, live) {
2401
3110
  try {
3111
+ if (live())
3112
+ reloadsDue.delete(room.locator);
2402
3113
  if (!live() || authorization === undefined)
2403
3114
  return;
2404
3115
  const bootstrapped = await pullBootstrap(authorization, room, local, live);
@@ -2415,7 +3126,7 @@ export function composeRuntime(options) {
2415
3126
  caughtUpTo(room.locator);
2416
3127
  }
2417
3128
  }
2418
- async function discoverRooms(local, progress, attempt, live) {
3129
+ async function discoverRooms(local, progress, attempt, live, scope) {
2419
3130
  if (closed || authorization === undefined) {
2420
3131
  notifyReady();
2421
3132
  return;
@@ -2425,7 +3136,7 @@ export function composeRuntime(options) {
2425
3136
  const started = discoveries;
2426
3137
  let result;
2427
3138
  try {
2428
- result = await options.adapter.discover(authorization);
3139
+ result = await options.adapter.discover(authorization, scope);
2429
3140
  }
2430
3141
  catch {
2431
3142
  result = { kind: 'transport-uncertainty' };
@@ -2465,12 +3176,13 @@ export function composeRuntime(options) {
2465
3176
  }
2466
3177
  for (const room of result.rooms) {
2467
3178
  if (room.operations === undefined ||
2468
- !['read', 'sync', 'write', 'delete'].every((operation) => Array.isArray(room.operations[operation]) &&
3179
+ !['write', 'delete'].every((operation) => Array.isArray(room.operations[operation]) &&
2469
3180
  room.operations[operation].every((scope) => typeof scope === 'string')) ||
2470
3181
  room.replica === undefined ||
2471
3182
  typeof room.replica.selection !== 'string' ||
2472
3183
  room.replica.selection.length === 0 ||
2473
- !['admitted', 'unavailable'].includes(room.replica.admission)) {
3184
+ !['admitted', 'unavailable'].includes(room.replica.admission) ||
3185
+ !['locked', 'open'].includes(room.replica.offline)) {
2474
3186
  journal.record(`invalid model or replica declaration ${room.locator}`);
2475
3187
  await refuse('missing-required-guarantee');
2476
3188
  notifyReady();
@@ -2502,7 +3214,7 @@ export function composeRuntime(options) {
2502
3214
  member = signedIn;
2503
3215
  emitMember();
2504
3216
  }
2505
- await synchronize(await applyDiscovery(result.rooms, started), local, progress, attempt, live);
3217
+ await synchronize(await applyDiscovery(result.rooms, started, result.covered), local, progress, attempt, live);
2506
3218
  }
2507
3219
  async function ensureAuthorization() {
2508
3220
  if (authorization !== undefined)
@@ -2599,9 +3311,44 @@ export function composeRuntime(options) {
2599
3311
  options.adapter.roomStream?.reopen();
2600
3312
  });
2601
3313
  }
2602
- function closedSocket(revoked) {
3314
+ function rediscover(scope) {
3315
+ return task(OPENING_LANE, async (live) => {
3316
+ if (!live() || !socketOpen)
3317
+ return;
3318
+ const progress = { complete: true, reachable: true };
3319
+ const gate = discover();
3320
+ moveTo(transferring(status));
3321
+ try {
3322
+ const local = await openLocal();
3323
+ if (!live())
3324
+ return;
3325
+ await ensureAuthorization();
3326
+ if (!live())
3327
+ return;
3328
+ await discoverRooms(local, progress, 'authorized', live, scope);
3329
+ }
3330
+ catch {
3331
+ progress.complete = false;
3332
+ }
3333
+ finally {
3334
+ gate.release();
3335
+ notifyReady();
3336
+ }
3337
+ if (!live())
3338
+ return;
3339
+ if (!progress.complete)
3340
+ complete = false;
3341
+ await rest(progress, live);
3342
+ });
3343
+ }
3344
+ function closedSocket(revoked, lost) {
2603
3345
  const opened = socketOpen;
2604
3346
  socketOpen = false;
3347
+ connectionLost();
3348
+ if (lost) {
3349
+ reads.lost();
3350
+ conversations.lost();
3351
+ }
2605
3352
  if (revoked) {
2606
3353
  void refuse('revoked-authorization');
2607
3354
  return;
@@ -2618,9 +3365,10 @@ export function composeRuntime(options) {
2618
3365
  function applyOpening(expired) {
2619
3366
  const progress = underway?.generation === generation ? underway.progress : null;
2620
3367
  const cycle = progress ?? { complete: true, reachable: true };
2621
- const replacing = reloadNow((room) => expired.includes(room.locator), cycle);
2622
3368
  if (opened === generation)
2623
3369
  opened = null;
3370
+ const reloading = progress === null ? [] : owedReloads(expired);
3371
+ const replacing = reloadNow((room) => expired.includes(room.locator) || reloading.includes(room.locator), cycle);
2624
3372
  return task(OPENING_LANE, async (live) => {
2625
3373
  underway = null;
2626
3374
  if (!live())
@@ -2630,24 +3378,17 @@ export function composeRuntime(options) {
2630
3378
  await rest(cycle, live);
2631
3379
  return;
2632
3380
  }
2633
- await roomsCarried(expired);
3381
+ await roomsCarried([...expired, ...reloading]);
2634
3382
  if (!live())
2635
3383
  return;
2636
- const replaced = new Set(owed);
2637
- owed.clear();
2638
3384
  try {
2639
3385
  const local = await openLocal();
2640
- const held = [...discovered.values()].filter((room) => replicas.has(room.locator));
2641
- const reloading = held.filter((room) => !expired.includes(room.locator) &&
2642
- (replaced.has(room.locator) || revoked(room.locator)));
2643
- for (const room of reloading)
2644
- catching.add(room.locator);
2645
- readSide.recover();
2646
- const reloads = Promise.allSettled(reloading.map((room) => roomTask(room.locator, (current) => reload(room, local, progress, current))));
2647
- const reloaded = [...(await reloads), ...(await replacing)];
3386
+ const reloaded = await replacing;
2648
3387
  if (progress.reachable) {
2649
- for (const room of held) {
2650
- if (!expired.includes(room.locator) && !reloading.includes(room)) {
3388
+ for (const room of discovered.values()) {
3389
+ if (replicas.has(room.locator) &&
3390
+ !expired.includes(room.locator) &&
3391
+ !reloading.includes(room.locator)) {
2651
3392
  await confirmModels(room, local);
2652
3393
  }
2653
3394
  }
@@ -2664,14 +3405,29 @@ export function composeRuntime(options) {
2664
3405
  await finishOpening(progress, live);
2665
3406
  });
2666
3407
  }
3408
+ function owedReloads(expired) {
3409
+ const reloading = [...discovered.values()]
3410
+ .filter((room) => replicas.has(room.locator) &&
3411
+ !expired.includes(room.locator) &&
3412
+ (owed.has(room.locator) || revoked(room.locator)))
3413
+ .map((room) => room.locator);
3414
+ owed.clear();
3415
+ for (const locator of reloading)
3416
+ catching.add(locator);
3417
+ readSide.recover();
3418
+ return reloading;
3419
+ }
2667
3420
  async function reloadNow(replaced, progress) {
3421
+ const reloaded = [...discovered.values()].filter((room) => replicas.has(room.locator) && replaced(room));
3422
+ for (const room of reloaded)
3423
+ reloadsDue.set(room.locator, generation);
2668
3424
  try {
2669
3425
  const local = await openLocal();
2670
- return await Promise.allSettled([...discovered.values()]
2671
- .filter((room) => replicas.has(room.locator) && replaced(room))
2672
- .map((room) => roomTask(room.locator, (live) => reload(room, local, progress, live))));
3426
+ return await Promise.allSettled(reloaded.map((room) => roomTask(room.locator, (live) => reload(room, local, progress, live))));
2673
3427
  }
2674
3428
  catch {
3429
+ for (const room of reloaded)
3430
+ reloadsDue.delete(room.locator);
2675
3431
  progress.reachable = false;
2676
3432
  return [];
2677
3433
  }
@@ -2788,6 +3544,7 @@ export function composeRuntime(options) {
2788
3544
  progress.complete = false;
2789
3545
  return;
2790
3546
  }
3547
+ reads.applied();
2791
3548
  submitAll();
2792
3549
  for (const locator of stale)
2793
3550
  if (repairable.has(locator))
@@ -2796,10 +3553,11 @@ export function composeRuntime(options) {
2796
3553
  if (status.providerUnreachable)
2797
3554
  conversations.reconnected();
2798
3555
  const reading = { complete: true, reachable: true };
2799
- if (demand.conversations)
2800
- await conversations.catchUp(reading);
3556
+ await conversations.catchUp(reading);
2801
3557
  if (progress.reachable && reading.reachable)
2802
3558
  await conversations.resend(reading);
3559
+ if (progress.reachable)
3560
+ void recovery.attempt('calls', resendCalls);
2803
3561
  if (!reading.reachable) {
2804
3562
  progress.reachable = false;
2805
3563
  resendLater();
@@ -2860,7 +3618,7 @@ export function composeRuntime(options) {
2860
3618
  return;
2861
3619
  const room = discovered.get(locator);
2862
3620
  const held = replicas.get(locator);
2863
- if (room === undefined || room.replica.admission !== 'admitted' || !acquires(room))
3621
+ if (room === undefined || room.replica.admission !== 'admitted')
2864
3622
  return;
2865
3623
  if (held !== undefined &&
2866
3624
  (held.confirmed.record.replica.selection !== room.replica.selection ||
@@ -2911,15 +3669,19 @@ export function composeRuntime(options) {
2911
3669
  return;
2912
3670
  if (event.kind === 'opened') {
2913
3671
  socketOpen = true;
3672
+ connectionLive();
2914
3673
  generation += 1;
3674
+ reads.opened();
2915
3675
  conversations.reopened();
2916
3676
  recovery.resume();
2917
3677
  void sync('opened');
2918
3678
  }
2919
3679
  else if (event.kind === 'closed')
2920
- closedSocket(event.revoked);
3680
+ closedSocket(event.revoked, event.lost);
2921
3681
  else if (event.kind === 'opening')
2922
3682
  void applyOpening(event.expired);
3683
+ else if (event.kind === 'authority-changed')
3684
+ void rediscover(event.scope);
2923
3685
  else
2924
3686
  void applyRoom(event.locator, event.roomVersion);
2925
3687
  }, receipts);
@@ -2974,7 +3736,7 @@ export function composeRuntime(options) {
2974
3736
  if (!live())
2975
3737
  return;
2976
3738
  await conversations.reconcile();
2977
- if (conversations.current() || !demand.conversations) {
3739
+ if (conversations.current()) {
2978
3740
  show();
2979
3741
  return;
2980
3742
  }
@@ -2992,10 +3754,10 @@ export function composeRuntime(options) {
2992
3754
  if (closed)
2993
3755
  return;
2994
3756
  closed = true;
2995
- if (narrowing !== null)
2996
- clearTimeout(narrowing);
2997
3757
  if (rechecking !== null)
2998
3758
  clearInterval(rechecking);
3759
+ connectionLive();
3760
+ lockListeners.clear();
2999
3761
  readinessWatches.clear();
3000
3762
  withdrawStream?.();
3001
3763
  withdrawStream = undefined;
@@ -3041,56 +3803,124 @@ export function composeRuntime(options) {
3041
3803
  if (options.adapter.roomStream === undefined)
3042
3804
  void sync('unstreamed');
3043
3805
  function planned(input, reach) {
3044
- return planOf(input, roomFacts(reach), planReach(reach));
3806
+ const plan = planOf(input, roomFacts(reach), planReach(reach));
3807
+ const named = plan.paths !== null &&
3808
+ plan.rooms !== null &&
3809
+ plan.paths.length * plan.rooms.length <= MAXIMUM_WINDOW;
3810
+ return plan.limit === null && named ? plan : { ...plan, limit: capped(plan.limit) };
3045
3811
  }
3046
3812
  function watchPlan(plan, deliver) {
3047
- return readSide.watch(plan, identityOf(plan), () => {
3813
+ let seeded = false;
3814
+ let pending = true;
3815
+ const shown = () => {
3816
+ const seed = seeds.get(plan.key);
3817
+ if (seed === undefined || seeded || !pending)
3818
+ return;
3819
+ seeded = true;
3820
+ deliver(seededResult(seed));
3821
+ };
3822
+ const watchers = seedWatchers.get(plan.key) ?? new Set();
3823
+ seedWatchers.set(plan.key, watchers);
3824
+ watchers.add(shown);
3825
+ const stop = readSide.watch(plan, identityOf(plan), () => {
3048
3826
  const cover = covered(plan);
3049
3827
  awaitPreparation(cover);
3050
- return cover;
3051
- }, deliver);
3828
+ return seedBehind(plan, cover);
3829
+ }, (message) => {
3830
+ const answered = message;
3831
+ pending = whole(answered) && 'pending' in answered.result;
3832
+ if (pending && seeds.has(plan.key)) {
3833
+ shown();
3834
+ return;
3835
+ }
3836
+ seeded = false;
3837
+ deliver(message);
3838
+ });
3839
+ return () => {
3840
+ watchers.delete(shown);
3841
+ if (watchers.size === 0)
3842
+ seedWatchers.delete(plan.key);
3843
+ stop();
3844
+ };
3052
3845
  }
3053
- async function searched(input, reach) {
3054
- const plan = searchPlanOf(input);
3055
- const filter = filterOf(plan.documents ?? {}, roomFacts(reach), planReach(reach));
3846
+ async function searched(input, reach, locked) {
3847
+ const asked = searchPlanOf(input);
3848
+ const plan = { ...asked, limit: capped(asked.limit) };
3849
+ const filter = {
3850
+ ...filterOf(plan.documents ?? {}, roomFacts(reach), planReach(reach)),
3851
+ locked,
3852
+ };
3853
+ const unlocking = (filter.rooms ?? [])
3854
+ .filter((room) => locked.includes(room))
3855
+ .map((room) => ({ room, awaits: 'unlock' }));
3056
3856
  for (;;) {
3057
3857
  const cover = covered(filter);
3058
3858
  awaitPreparation(cover);
3059
- const pending = 'pending' in cover ? [...cover.pending] : [];
3060
- const covering = 'pending' in cover ? [] : cover.coverage.rooms;
3859
+ const pending = [
3860
+ ...unlocking,
3861
+ ...('pending' in cover ? cover.pending : []),
3862
+ ];
3863
+ const awaited = new Set('pending' in cover ? cover.pending.map(({ room }) => room) : []);
3864
+ const held = covered({
3865
+ ...filter,
3866
+ rooms: reachedRooms(filter).filter((room) => !awaited.has(room)),
3867
+ });
3868
+ const covering = 'pending' in held ? [] : held.coverage.rooms;
3061
3869
  const unindexed = covering
3062
3870
  .filter(({ room }) => !searchIndex.rooms().has(room))
3063
3871
  .map(({ room }) => room);
3064
3872
  for (const room of unindexed)
3065
3873
  pending.push({ room, awaits: 'index' });
3066
- const held = conversations.searchable();
3874
+ const listed = conversations.searchable();
3067
3875
  const named = reach !== null && !reach.conversations
3068
3876
  ? []
3069
- : (plan.conversations ?? held).filter((one) => held.includes(one) && conversations.acquired(one));
3877
+ : (plan.conversations ?? listed).filter((one) => listed.includes(one) && conversations.acquired(one));
3070
3878
  const waiting = named.filter((one) => !searchIndex.conversations().has(one));
3071
3879
  for (const conversation of waiting)
3072
3880
  pending.push({ conversation, awaits: 'index' });
3073
3881
  if (unindexed.length > 0 || waiting.length > 0)
3074
3882
  index(unindexed, waiting);
3075
- if (pending.length > 0 || 'pending' in cover)
3076
- return { pending };
3883
+ const complete = pending.length === 0 && !('pending' in cover);
3884
+ const answering = complete
3885
+ ? filter
3886
+ : {
3887
+ ...filter,
3888
+ rooms: covering
3889
+ .filter(({ room }) => searchIndex.rooms().has(room))
3890
+ .map(({ room }) => room),
3891
+ };
3892
+ const answered = covered(answering);
3893
+ if ('pending' in answered)
3894
+ continue;
3895
+ const searchedConversations = named.filter((one) => searchIndex.conversations().has(one));
3896
+ await readSide.settled();
3077
3897
  const seen = searchIndex.changes();
3078
3898
  await searchIndex.caughtUp();
3079
- const selected = plan.documents === undefined && reach === null ? null : await rowsQuery(filter);
3899
+ const selected = roomsAlone(answering) ? null : await rowsQuery(answering);
3080
3900
  if (selected !== null && 'pending' in selected)
3081
- return selected;
3901
+ continue;
3082
3902
  if (searchIndex.changes() !== seen ||
3083
- JSON.stringify(covered(filter)) !== JSON.stringify(cover))
3903
+ JSON.stringify(covered(answering)) !== JSON.stringify(answered))
3084
3904
  continue;
3085
- return {
3086
- ...searchIndex.search(plan, selected === null ? null : selected.documents, named),
3087
- coverage: {
3088
- rooms: covering,
3089
- conversations: named,
3090
- index: searchIndex.generation(),
3091
- overlay: cover.coverage.overlay,
3092
- },
3905
+ const hits = searchIndex.search(plan, selected === null ? null : selected.documents, searchedConversations, answering.rooms !== null
3906
+ ? new Set(answering.rooms)
3907
+ : locked.length === 0
3908
+ ? null
3909
+ : new Set(reachedRooms(answering)), plan.collection
3910
+ ? new Map(answered.coverage.rooms.map(({ room }) => [
3911
+ room,
3912
+ replicas.get(room)?.confirmed.record.typedSelection?.roots ?? [],
3913
+ ]))
3914
+ : null);
3915
+ const coverage = {
3916
+ rooms: answered.coverage.rooms,
3917
+ conversations: searchedConversations,
3918
+ index: searchIndex.generation(),
3919
+ overlay: answered.coverage.overlay,
3093
3920
  };
3921
+ return complete
3922
+ ? { ...hits, coverage }
3923
+ : { pending, documents: hits.documents, messages: hits.messages, coverage };
3094
3924
  }
3095
3925
  }
3096
3926
  const watch = (topic, input, deliver) => {
@@ -3138,7 +3968,7 @@ export function composeRuntime(options) {
3138
3968
  };
3139
3969
  }
3140
3970
  if (topic === 'readiness') {
3141
- return watchReadiness({ target: '', code: 'stored', capacity: null }, null, deliver);
3971
+ return watchReadiness({ target: '', code: 'stored', capacity: null, search: 'unused' }, null, deliver);
3142
3972
  }
3143
3973
  if (topic === 'rooms') {
3144
3974
  roomListeners.add(deliver);
@@ -3200,7 +4030,7 @@ export function composeRuntime(options) {
3200
4030
  return listed();
3201
4031
  },
3202
4032
  query: ((input) => rowsQuery(planned(input, null))),
3203
- search: (input) => searched(input, null),
4033
+ search: (input) => searched(input, null, []),
3204
4034
  types(locator) {
3205
4035
  return {
3206
4036
  collection: modelTypes(modelOf(locator)),
@@ -3244,7 +4074,9 @@ export function composeRuntime(options) {
3244
4074
  parts: held(current?.parts, parts, file),
3245
4075
  returned: current?.returned ?? null,
3246
4076
  };
3247
- await local.keepRoomDraft(record);
4077
+ await local.keepRoomDraft(record, parts.file === undefined || file === undefined
4078
+ ? []
4079
+ : [{ key: file.localId, blob: parts.file.blob }]);
3248
4080
  rememberRoomDraft(record);
3249
4081
  publishChangeSet(changeSet(room, null, null, { drafts: [path] }));
3250
4082
  return { outcome: 'written', roomDraft: roomDraftOf(record) };
@@ -3275,27 +4107,36 @@ export function composeRuntime(options) {
3275
4107
  });
3276
4108
  },
3277
4109
  write(app, value) {
3278
- return exclusive(async () => {
3279
- const local = await openLocal();
3280
- const stored = structuredClone(value);
3281
- await local.present({ app, value: stored });
3282
- presentations.set(app, stored);
3283
- publishChangeSet(changeSet('', null, null, { presentation: app }));
3284
- });
4110
+ return keepPresentation(app, () => structuredClone(value));
4111
+ },
4112
+ edit(app, members) {
4113
+ return keepPresentation(app, (held) => Object.fromEntries([
4114
+ ...Object.entries(plain(held) ? held : {}).filter(([member]) => !Object.hasOwn(members, member)),
4115
+ ...Object.entries(structuredClone(members)).filter(([, value]) => value !== null),
4116
+ ]));
3285
4117
  },
3286
4118
  },
3287
4119
  save(room, named, writtenBy) {
3288
4120
  return exclusive(() => saveRoomDrafts(room, named, writtenBy));
3289
4121
  },
4122
+ saveParts(room, parts, writtenBy) {
4123
+ return exclusive(() => saveParts(room, parts, writtenBy));
4124
+ },
3290
4125
  history(locator, path, query) {
3291
4126
  return readHistory(locator, path, query);
3292
4127
  },
4128
+ resolve(room, path, destination) {
4129
+ return resolveReference(room, path, destination);
4130
+ },
3293
4131
  binaryFile: {
3294
4132
  read: readBinaryPath,
4133
+ link: linkBinaryPath,
3295
4134
  readReference: readBinaryReference,
3296
4135
  },
3297
- call(name, input) {
3298
- return invokeAction(name, input);
4136
+ async call(name, input) {
4137
+ await ready;
4138
+ const room = calledRooms(name, input).find((one) => locked(one));
4139
+ return room === undefined ? recoveredAction(name, input) : lockedRoom(room);
3299
4140
  },
3300
4141
  reached(locator, roomVersion, path) {
3301
4142
  return path === undefined
@@ -3339,15 +4180,18 @@ export function composeRuntime(options) {
3339
4180
  query: (plan) => rowsQuery(plan),
3340
4181
  watchPlan,
3341
4182
  search: searched,
3342
- searching,
3343
4183
  watchReadiness,
4184
+ locked,
4185
+ lockedRooms,
4186
+ watchLocks,
4187
+ located,
3344
4188
  };
3345
4189
  return {
3346
4190
  md,
4191
+ seed,
3347
4192
  stop,
3348
4193
  lose: loseRooms,
3349
4194
  watch,
3350
- acquire,
3351
4195
  persisted(answer) {
3352
4196
  if (answer === persistence)
3353
4197
  return;