@mmstack/mesh 21.15.2 → 21.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,10 +2,13 @@
2
2
 
3
3
  > **Experimental.** The API may still change and this package is not yet battle-tested in production. Pin a version and expect some churn.
4
4
 
5
- Multiplayer for `@mmstack/primitives` signal stores. `meshSync(store, ...)` replicates a store
6
- across clients through a relay, and a synced store reads exactly like a local one: synchronous,
7
- no new nullability, no callbacks in your components. Connection state surfaces through a status
8
- signal and the transition scope, never as an exception from a read.
5
+ Local-first sync for `@mmstack/primitives` signal stores. `meshSync(store, ...)` replicates a store
6
+ across clients through a relay. Several writers can edit it at once and converge on the same state.
7
+ Writes made offline are kept and rebased onto the room when the client reconnects. A synced store
8
+ reads exactly like a local one: synchronous, no new nullability, no callbacks in your components.
9
+ You never emit a change by hand: once per tick the client diffs the committed store and derives
10
+ the ops from that diff, so app code only ever writes to the store. Connection state surfaces
11
+ through a status signal and the transition scope, never as an exception from a read.
9
12
 
10
13
  ```bash
11
14
  npm install @mmstack/mesh @mmstack/mesh-protocol
@@ -15,6 +18,12 @@ The relay is [`@mmstack/mesh-protocol`](https://www.npmjs.com/package/@mmstack/m
15
18
  which has no dependencies and runs on Node, Bun, or a Durable Object. You bring your own socket
16
19
  and your own auth.
17
20
 
21
+ For a meshed store, the `outbox` takes the place of `persist`. It saves each of your writes before
22
+ it is sent, in a journal where storage decides between tabs, while `persist` stays the tool for a store that is
23
+ only ever local. See [Offline and durable outbox](#offline-and-durable-outbox),
24
+ [Assemble a base before connecting](#assemble-a-base-before-connecting) and
25
+ [Multiple tabs](#multiple-tabs).
26
+
18
27
  ## meshSync
19
28
 
20
29
  ```ts
@@ -31,20 +40,22 @@ const mesh = meshSync(board, {
31
40
  ```
32
41
 
33
42
  Write to `board` like any store. Local changes emit to the relay, remote changes fold in, and
34
- both sides converge. `mesh.status()` is `'connecting' | 'live' | 'reconnecting' | 'ejected'`,
35
- and `mesh.peers()` is the current presence roster. When you provide `register: 'track'`, the
36
- store also participates in transition scopes, so a reconnect shows up as `pending` to a
43
+ both sides converge. `mesh.status()` is
44
+ `'connecting' | 'waiting' | 'live' | 'reconnecting' | 'ejected' | 'closed'`, and `mesh.peers()` is
45
+ the current presence roster. `'waiting'` means another tab owns this key's saved outbox and this
46
+ one is queued behind it; `'closed'` means the sync was closed or destroyed. When you provide
47
+ `register: 'track'`, the store also participates in transition scopes, so a reconnect shows up as `pending` to a
37
48
  `<mm-suspense>` boundary without any wiring.
38
49
 
39
50
  Reconnection is automatic, with exponential backoff. On reconnect the client resumes from a
40
51
  delta when possible, and re-applies any writes made while offline on top of whatever the room
41
- moved to in the meantime. A relay restart is detected through a room instance nonce, so a stale
42
- sequence number never corrupts state.
52
+ moved to in the meantime. Each hello names the room generation the client holds, and only a hello
53
+ that names the current one is answered with a delta, so a sequence number from another generation
54
+ never corrupts state.
43
55
 
44
- `mesh.origin()` is `null` until the session sends hello, then reflects the origin that hello
45
- used. It stays stable across socket reconnects and follows the current op engine when a session
46
- is rebuilt; an outbox restore publishes the new boot's origin, not the origins of replayed writes.
47
- The last announced origin remains available after close. `mesh.members()` lists other relay
56
+ `mesh.origin()` is `null` until the outbox has loaded, then reflects this client's origin. With an
57
+ `outbox` it is the saved outbox's origin, the same on every boot that reads it; without one, each
58
+ boot has an origin of its own. The origin remains available after close. `mesh.members()` lists other relay
48
59
  origins, including peers that have never published presence. It is empty before welcome and
49
60
  while disconnected, and updates on welcomes, joins, and departures.
50
61
 
@@ -91,7 +102,9 @@ meshSync(board, {
91
102
  ```
92
103
 
93
104
  `preserve` turns a clash into a `Conflicted` value holding every side that clashed, not just two,
94
- so nothing is silently lost and a resolution is just a later write. See `@mmstack/primitives` for
105
+ so nothing is silently lost and a resolution is just a later write. A side that deleted the value
106
+ shows as a `Deleted` marker (test it with `isDeleted`), never as `undefined`, so a `Conflicted`
107
+ value survives JSON and structured clone whenever its values do. See `@mmstack/primitives` for
95
108
  the full set of merge policies; they are the same ones the store uses for forks and tabs.
96
109
 
97
110
  The default is last-writer-wins on a leaf, which drops one side of a true clash on the same field.
@@ -156,35 +169,65 @@ by default, so a full reload loses any write the room never acknowledged. Pass `
156
169
  it:
157
170
 
158
171
  ```ts
159
- import * as idbKeyval from 'idb-keyval';
172
+ import { del, get, update } from 'idb-keyval';
173
+ import { journalStore } from '@mmstack/primitives';
160
174
 
161
175
  meshSync(board, {
162
176
  room: 'board-42',
163
177
  writer: currentUserId,
164
178
  transport,
165
- outbox: { key: 'board-42', store: idbKeyval },
179
+ outbox: { key: 'board-42', store: journalStore({ get, update, del }) },
166
180
  });
167
181
  ```
168
182
 
169
- `store` is any `AsyncStore` (`get`, `set`, `del`), the same interface `persist` takes. On boot the
170
- client restores the saved queue and resends the unacknowledged writes when it reconnects, each under
171
- the origin it was recorded with. New writes go out under a fresh origin: every boot mints its own. Those offline edits then rebase onto whatever the room
172
- moved to while the tab was gone. The queue is saved on a 300ms debounce; set `debounceMs` to change
173
- it, or `0` to write on every change.
174
-
175
- The saved queue is a single-writer slot, and a Web Lock on the key elects its writer. `crossTab` sets
176
- what a second tab on the same key does:
177
-
178
- - `'queue'` (default): the second tab waits, with `status()` reading `'waiting'`, until the first
179
- tab closes, then takes over.
180
- - `'ephemeral'`: the second tab is live at once on its own origin. It never reads or writes the saved
181
- queue, so its unacknowledged writes are lost if it closes before the room acknowledges them. When
182
- the lock is free, it takes the lock and behaves like `'queue'`.
183
- - `'off'` skips the lock. Use it when you coordinate ownership yourself, for example a distinct key
184
- per tab, or leader election over `tabSync`.
183
+ `store` is a `JournalStore` from `@mmstack/primitives`. Build one over idb-keyval's own functions
184
+ with `journalStore({ get, update, del })`, or see `JournalStore` there for a store of your own. The
185
+ outbox is a journal: every write is saved before it is sent, and every answer the room gives about it is saved
186
+ before it shows, at once, with no timer. A crash at any moment loses nothing that was sent. On boot
187
+ the client restores the writes that are still pending and resends them, unchanged, after the next
188
+ welcome. Those offline edits then rebase onto whatever the room moved to while the tab was gone.
189
+
190
+ If a tab ends while a save is still on its way, that save can land after the next tab has read
191
+ the outbox. The new tab's next save is then refused, and its handle ends `ejected` with the reason
192
+ `'moved'` (`health()` reads `storage` with the reason `'moved'`). IndexedDB runs a later read after
193
+ an earlier write that has already started, so over idb-keyval this is not expected.
194
+
195
+ The saved outbox also keeps this client's origin, so every boot that reads it continues as the same
196
+ client: one origin per saved outbox, stable across reloads. Two keys are written, `<key>:log` and
197
+ `<key>:snap`, and nothing is deleted from them. An outbox saved by an earlier version of this
198
+ library under `key` itself is not read: it is deleted unread at each boot, when the store can
199
+ delete, and the writes it held are not sent.
200
+
201
+ Storage decides between tabs. When another tab has written the outbox in a handle's place, that
202
+ handle ends `ejected` with the reason `'moved'`. A write it had not saved by then is not saved, and
203
+ no other tab can send it: `acked()` reads `false` and `whenAcked()` rejects, and what to do with it
204
+ is yours. A Web Lock on the key keeps live tabs from taking each other's place; it is not what keeps
205
+ the outbox whole. `crossTab` sets what a tab that did not get the lock does:
206
+
207
+ - `'queue'` (default): the tab waits, with `status()` reading `'waiting'`, until the tab that holds
208
+ the lock closes, then takes over. Store writes made while it waits are sent, as their net change,
209
+ when it takes over.
210
+ - `'ephemeral'`: the tab is live at once, as a client of its own. It never reads or writes the saved
211
+ outbox, so its writes live in memory only and are lost if it ends before the room acknowledges
212
+ them. It stays ephemeral for its life, also after the other tab leaves. When the lock is free, it
213
+ takes the lock and behaves like `'queue'`.
214
+ - `'off'` skips the lock. Every tab that opens the key continues the same saved client, and when two
215
+ tabs write it, one of them ends `ejected` with the reason `'moved'`. Keeping to one tab per key is
216
+ yours: for example a distinct key per tab, or leader election over `tabSync`. Without the lock, a
217
+ tab that has only read the outbox does not keep another tab's `clearOutbox()` from wiping what it
218
+ is about to send. In development mode it warns once.
185
219
 
186
220
  When the Web Locks API is unavailable, `'queue'` and `'ephemeral'` log a development warning and run
187
- without the lock, as the owner of the saved queue.
221
+ without the lock, as `'off'` does: when two tabs use the key, one of them ends `ejected` with the
222
+ reason `'moved'`.
223
+
224
+ Within one page, a handle made in the turn another handle of the page over the same key was closed takes over from it (unless another tab asked for the lock first).
225
+ A handle made while another handle of the page over the key is still open is treated as a second
226
+ tab would be: `'queue'` waits for it, and `'ephemeral'` runs over memory for its life, so close the
227
+ old handle first. A `'queue'` handle closed while it waits keeps its place in the browser's lock
228
+ queue until its turn; then the lock is taken and given back at once. Until then a new handle of the
229
+ page is treated as it would be while the other tab holds the lock. Two copies of this library in one
230
+ page behave as two tabs.
188
231
 
189
232
  The outbox persists your unacknowledged writes, not a full snapshot. For a meshed store, use it in
190
233
  place of wrapping the store in `persist`. The two race on boot, and the outbox is the one that
@@ -192,11 +235,51 @@ rebases offline edits onto the room. `persist` stays the tool for a store that i
192
235
  cold offline boot shows the store's initial value plus your restored writes until a welcome arrives.
193
236
  If you also need to read the last room state while fully offline, assemble it as a base first, below.
194
237
 
195
- The outbox also records the room **generation** the tail was written in (the relay's `instance`
196
- nonce), this device's emission epoch floors and its clock high-water. A relay cuts a generation on
197
- a migration: every write from before the cut is refused, and on the first welcome after a reboot
198
- the client drops such a tail loudly through `onRefused` instead of resending it. A tail written
199
- before any welcome ever named a generation adopts the first one it meets.
238
+ The outbox also records the room **generation** each write was made in (the room's lineage, the
239
+ relay's `instance` nonce and the generation's index), this device's emission epoch floors and its
240
+ clock high-water. A relay cuts a generation on a migration, a rollback or a compaction. A
241
+ compaction cut carries the pending writes of the same lineage into the new generation, each checked
242
+ against what the cut kept (a write that cites something the cut folded away is listed in
243
+ `conflicts`). A migration or a rollback discards them, and so does a room that was
244
+ created anew: such a write is not resent, and it is listed in `unstored` with the reason
245
+ `'generation'`. A tail written before any welcome ever named a generation adopts the first one it
246
+ meets.
247
+
248
+ When you upgrade: a relay that comes back with a room that is not empty under a new lineage (a
249
+ checkpoint from before this version, or a host that lost its generation record) holds no receipt
250
+ for a write it had admitted before. Such a write is listed in `unstored` with the reason
251
+ `'generation'`, and `whenAcked()` rejects with `refused: generation`, although its effect may be
252
+ in the room.
253
+
254
+ The saved outbox holds what you see in `conflicts` and `unstored` too, so both stay listed across
255
+ reboots until you answer them. To drop everything, call `clearOutbox()`: it discards every write not
256
+ yet in the room, every conflict and every `unstored` entry, and ends the session. From the call
257
+ nothing more is sent or saved, `acked()` reads `false` and `whenAcked()` rejects with `'cleared'`;
258
+ the handle keeps the outbox lock and its status until storage answers. Once storage holds the wipe,
259
+ the session ends `closed` with the reason `'cleared'`, `onEject` is called with `'cleared'`, and the
260
+ promise resolves. When the handle holds the saved outbox, the next boot then starts a new outbox as
261
+ a new client. It rejects with `'moved'`
262
+ when another tab wrote the outbox first, with `'storage'` when the outcome is not known, and with the
263
+ reason of any ending that comes first (`'closed'` for `close()`). A crash before it resolves leaves
264
+ the outbox as it was, and the next boot continues it and sends what is pending. Called before the
265
+ boot has finished, it clears once the boot is done, or rejects with the boot's reason.
266
+
267
+ A handle runs over memory when it was given no `outbox`, when it is an `'ephemeral'` tab beside
268
+ another tab that holds the outbox, or when the saved outbox could not be read. Called while such a
269
+ handle is live, `clearOutbox()` discards this handle's own writes, resolves, and ends the handle
270
+ `closed` with `'cleared'`, calling `onEject('cleared')`. A saved outbox the handle never held is
271
+ left exactly as it is, and the next boot that can read it sends what it holds. An outbox that
272
+ could not be read is not removed by `clearOutbox()`: remove it from your own store, under the key
273
+ you gave, when you want it gone.
274
+
275
+ Called once the session has ended by itself (ejected, outdated, a storage ending), `clearOutbox()`
276
+ takes the outbox lock if it is free (else it rejects with `'busy'`), reads the outbox again and
277
+ wipes it only when no other tab has written it since this handle ended (else it rejects with
278
+ `'moved'`). It rejects with `'unreadable'` when the outbox cannot be read again, and with
279
+ `'storage'` when the store does not say whether the wipe was stored. It holds the lock until
280
+ storage answers, and `close()` meanwhile rejects it with
281
+ `'closed'`. After `close()`, and on a handle that never held the saved outbox, it rejects with
282
+ `'closed'`. A second call while one runs joins it.
200
283
 
201
284
  ## Assemble a base before connecting
202
285
 
@@ -210,7 +293,7 @@ meshSync(graph, {
210
293
  room: 'graph-7',
211
294
  writer: currentUserId,
212
295
  transport,
213
- outbox: { key: 'graph-7', store: idbKeyval },
296
+ outbox: { key: 'graph-7', store: journalStore({ get, update, del }) },
214
297
  whenReady: () => baseReady, // a promise that resolves once the base is filled
215
298
  });
216
299
  ```
@@ -227,10 +310,12 @@ Run `tabSync` and `meshSync` on the same store to share it across a user's tabs
227
310
  carries it to the room. The outbox lock elects the leader, so only one tab holds the relay
228
311
  connection and the others share state over `tabSync`. A write in any tab reaches the room through the
229
312
  leader, and a room write reaches every tab through `tabSync`. When the leader tab closes, another
230
- tab acquires the lock and takes over on a fresh origin, restoring and resending the persisted tail.
313
+ tab acquires the lock and takes over as the same client, under the saved outbox's origin, restoring
314
+ and resending the pending writes.
231
315
 
232
316
  ```ts
233
- import { store, tabSync } from '@mmstack/primitives';
317
+ import { del, get, update } from 'idb-keyval';
318
+ import { journalStore, store, tabSync } from '@mmstack/primitives';
234
319
  import { meshSync, webSocketTransport } from '@mmstack/mesh';
235
320
 
236
321
  const board = store<Board>(initialBoard());
@@ -239,7 +324,8 @@ meshSync(board, {
239
324
  room: 'board-42',
240
325
  writer: currentUserId,
241
326
  transport: webSocketTransport('wss://sync.example.com'),
242
- outbox: { key: 'board-42', store: idbKeyval }, // crossTab:'queue' elects one leader
327
+ // crossTab:'queue' elects one leader
328
+ outbox: { key: 'board-42', store: journalStore({ get, update, del }) },
243
329
  });
244
330
  ```
245
331
 
@@ -330,13 +416,22 @@ reads work as usual. `setAtPath` takes the dot paths a tool-calling model natura
330
416
  Reconnection, delta resume, and offline rebase behave exactly as in `meshSync`; the two are shells
331
417
  over one session implementation.
332
418
 
419
+ The seat starts a moment after `agentSeat` returns. It keeps its writes in a journal held in
420
+ memory (a seat has no `outbox`) and opens that journal before it connects. Writes made before the
421
+ start are held and sent once it starts; until then `acked()` reads `false` and `whenAcked()` waits.
422
+ Like `meshSync`, a seat lists the writes that will never land in `unstored`, and has a
423
+ `clearOutbox()`. Its `onEject` is called once when the seat ends by itself, with the reason, and
424
+ when a `clearOutbox()` ends it, with `'cleared'`; never for `close()`. Inside it the seat reads as
425
+ ended: `status()` reads `'ejected'`, or `'closed'` after a clear.
426
+
333
427
  ### Review a branch
334
428
 
335
429
  An agent's write is a sample that can be wrong, so the safe default keeps it behind a person's
336
430
  approval. `seat.fork()` (and `mesh.fork()` in the browser) gives the agent an isolated branch of
337
431
  the synced store. Its writes stay on the fork, so nothing reaches the room until someone approves.
338
432
  `ops()` is the staged change as data, ready to render for review. `commit()` emits it to the room;
339
- `discard()` drops it.
433
+ `discard()` drops it and re-observes the room, so a later commit from the same fork cites the room
434
+ as it is at the discard.
340
435
 
341
436
  ```ts
342
437
  const proposal = seat.fork(); // the agent's isolated branch, off the room
@@ -357,8 +452,12 @@ directly. This is the fit when a write should be seen before it lands.
357
452
  ### Feed the model diffs, not the world
358
453
 
359
454
  Room state and the model loop meet at two calls. `stableSnapshot()` returns the document stamped
360
- with the relay sequence number it is provably the fold of, or `null` while one of the seat's own
361
- writes is still in flight. A non-null result is byte-stable for its seq: rebuilding the room at
455
+ with the relay sequence number it is provably the fold of, or `null` before the first welcome,
456
+ while one of the seat's own writes is still in flight, or after the room refuses one of its writes, until the fresh snapshot
457
+ that follows has landed. It returns a value again once that window closes. It stays `null` for
458
+ good only after the session ends with writes still unacknowledged, after the local policy check
459
+ rejects one of the seat's writes, or after `close()`. A non-null result is byte-stable for its
460
+ seq: rebuilding the room at
362
461
  that seq yields exactly this document, which is what makes it safe to put in a provider prompt
363
462
  cache. `changes` then delivers everything after that seq in order, so a prompt becomes a cached
364
463
  prefix plus an append-only suffix, and each turn sends only what happened since.
@@ -426,7 +525,9 @@ agentSeat(initialBoard(), {
426
525
  transport,
427
526
  ctx: { kind: 'agent', claims: { scope: 'pricing' } },
428
527
  policy: pricingScopeOnly,
429
- onEject: (reason) => log.warn('agent ejected', reason),
528
+ onEject: (reason) => {
529
+ if (reason !== 'cleared') log.warn('agent ejected', reason);
530
+ },
430
531
  });
431
532
  ```
432
533
 
@@ -441,41 +542,122 @@ reject reason into one value you can render:
441
542
 
442
543
  ```ts
443
544
  const mesh = meshSync(store, { room, writer, transport });
444
- // mesh.health() -> { status, reason?, lastSyncedAt? }
545
+ // mesh.health() -> { status, reason?, lastSyncedAt?, storing }
445
546
  ```
446
547
 
447
- `status` is one of `live`, `offline`, `outdated`, `ejected`, or `degraded`. The useful distinction
548
+ `status` is one of `live`, `waiting`, `offline`, `outdated`, `ejected`, `degraded`, or `storage`. `waiting` is
549
+ a tab queued behind the one that owns the saved outbox, as in `status()`. The useful distinction
448
550
  is `outdated` versus `ejected`. A versioned reject (the client's `proto`, `policyVersion`, or
449
551
  `schemaVersion` is behind the room) reports `outdated` with the reason, so you can show an update or
450
552
  reload prompt instead of a dead connection. A policy tripwire reports `ejected`. `degraded` is the
451
553
  slot for local problems such as a full storage quota or a dead worker; those are your own signals to
452
554
  fold in, since `meshSync` only owns the connection side.
453
555
 
556
+ `storage` is the one local problem `meshSync` reports itself: the outbox can no longer save this
557
+ handle's writes. The session has ended and nothing more is sent; `status()` reads `'ejected'` and
558
+ `onEject` is called with the reason. The reason says why: `'moved'` (another tab wrote the outbox
559
+ in this handle's place), `'exhausted'` (the outbox ran out of sequence numbers) or `'storage'`
560
+ (a save failed, or the outcome of a write is not known: it is reported neither as saved nor as
561
+ lost). A first read of the outbox that fails does not end the handle: see `outboxUnreadable`.
562
+ Three optional fields report what was set aside:
563
+
564
+ - `droppedOfflineWrites`: saved writes this build cannot send (another writer, protocol or policy
565
+ version, malformed, or refused by the room policy). They are never sent; each is listed in
566
+ `unstored` with the reason `'incompatible'`.
567
+ - `outboxUnreadable`: the saved outbox could not be read, because it is in a format this build
568
+ cannot read or because the store failed the read. It is left as it is, and this boot's writes
569
+ are kept in memory only, under an origin of their own, until the handle closes. The handle runs
570
+ live over memory, and `health` does not turn `storage` for this.
571
+ - `droppedInvalidEnvelopes`: received envelopes dropped as malformed.
572
+
573
+ `storing` counts the groups of this handle's writes that are in storage's hands and not yet saved.
574
+ Nothing times out: a store call that never answers keeps the handle live and holding the outbox
575
+ lock, with `storing` above zero, until the handle closes. If you want a limit, set a timer of your
576
+ own and close the handle when it fires.
577
+
454
578
  ## Knowing a write landed
455
579
 
456
580
  `health` and `status` describe the connection. They do not answer "is what I wrote in the room",
457
581
  and a live socket with an unacknowledged tail answers no. Two members do:
458
582
 
459
583
  ```ts
460
- mesh.acked(); // signal: every local write is acknowledged
461
- await mesh.whenAcked(); // resolves when the tail empties
584
+ mesh.acked(); // signal: nothing the engine has taken up is pending, unsaved, or held as a conflict
585
+ await mesh.whenAcked(); // resolves once nothing written is outstanding, a write made this turn included
462
586
  ```
463
587
 
588
+ `acked` follows the sync engine, which takes a store write up a moment later, at its next tick.
589
+ Read in the same turn as a write, it still gives the earlier answer. `whenAcked()` counts a write
590
+ made in this turn, and from that call `acked()` counts it too. To ask whether everything is saved,
591
+ including what you just wrote, call `whenAcked()`.
592
+
464
593
  `whenAcked()` resolves immediately when nothing is outstanding and rejects with the terminal reason
465
594
  if the session is ejected or closed while writes remain — those never reached the room, so every
466
595
  later call rejects the same way and `acked()` stays `false`. Await it before publishing anything
467
596
  that has to contain every edit; against a relay whose adapter confirms durability before echoing,
468
- acknowledged also means stored. `agentSeat` exposes the same pair as plain functions.
597
+ acknowledged also means stored. `agentSeat` exposes the same pair as plain functions, and its
598
+ `acked()` counts a write made in the same turn as the call.
599
+
600
+ Before the outbox has loaded, `acked()` reads `false` and `whenAcked()` waits for the load, since
601
+ what is pending is not known yet. `whenAcked()` also rejects with `'storage'`, `'moved'` or
602
+ `'exhausted'` once the outbox can no longer save, with `'cleared'` after `clearOutbox()`, and with `'schema'` when this client's data shape
603
+ is older than the room's. After a storage failure or `clearOutbox()`, `acked()` reads `false`.
604
+
605
+ The same holds for writes made at the edges of a session. A write made after an eject is never
606
+ sent, so it turns `acked()` to `false` and `whenAcked()` rejects with the terminal reason. A write
607
+ the local policy check rejects never reaches the room either, and reads the same way. A write
608
+ made before the first welcome is not acknowledged until the relay sequences it or it is reported
609
+ lost. A write made while the boot waits for the outbox lock or reads the saved outbox is held and
610
+ sent when the tab boots, as its net change (an edit undone during the wait is not sent and leaves
611
+ `acked()` true), with each `sync.override` made in the wait sent in order as its own authority
612
+ write; closing before the boot drops it, and `whenAcked()` rejects with `closed`. Writes made
613
+ inside `whenReady` are the local base and do not count. After `close()` the handle is frozen: the
614
+ sync engine is destroyed, and a later write to the store is not synced. `acked()` and
615
+ `whenAcked()` keep the answer they had at the close, and a later write does not change it. The
616
+ same holds for a seat.
617
+
618
+ `close()` lets the outbox lock go at once. A write made in the turn of the close is handed to
619
+ storage first, but only when nothing of the handle is in storage's hands: no earlier write still
620
+ being saved, and not the record the handle saves as it goes live. A write queued behind anything
621
+ still out is not saved. Either way nobody is told it is stored: `acked()` reads `false` and
622
+ `whenAcked()` rejects with `'closed'`. To know that every write is saved, wait for `whenAcked()`,
623
+ or for `acked()` to read `true`, before you close. A save in storage's hands at the close may still
624
+ land later, and the outbox stays whole either way: when it lands after the next tab has read the
625
+ outbox, that tab's next save is refused and it ends `ejected` with the reason `'moved'`.
469
626
 
470
627
  The relay answers every write it neither echoes nor ejects, so the tail is always classified one
471
628
  round trip after a welcome. A resend of a write the room already holds comes back as `duplicate`,
472
- which is the acknowledgement. A refusal — `generation` (written before a cut), `schema` (an older
473
- data shape), `order` (a version this origin never had admitted, which only a second tab on one
474
- origin can produce) — means the write is not in the room and never will be: the client hands the
475
- envelope to `onRefused` (its values are inside, so you can offer to write them again), rehydrates
476
- from a fresh snapshot so the store shows the room, and rejects any pending `whenAcked()` with
477
- `refused: <reason>`. `health().refusedWrites` counts them. "Every write was classified" and
478
- "every write was stored" are different questions; `whenAcked()` answers the second.
629
+ which is the acknowledgement. A `generation` drop is not a refusal: the write was stamped with a
630
+ generation the relay has closed, it stays pending, and it is judged again in the generation the
631
+ client lands in. A refusal (`schema`, an older data shape; `order`, a version this origin never had
632
+ admitted, which only a second tab on one origin can produce; `compacting`, refused by a host while
633
+ this client was declared ready for a cut) means the write as sent is not in the room and never will
634
+ be. Once that answer is saved, the client lists the write in `unstored`, rehydrates from a fresh
635
+ snapshot so the store shows the room, and rejects the `whenAcked()` calls pending then with
636
+ `refused: <reason>`. Its effect stays in the store until that snapshot lands, so if the room turns
637
+ out empty first, the seed that creates it can carry that effect into the room after all (a write
638
+ refused `compacting` then leaves `unstored` once the seed is admitted). "Every write was classified"
639
+ and "every write was stored" are different questions; `whenAcked()` answers the second for the
640
+ writes still in the tail. A refused write leaves the tail, so a later call no longer waits for it:
641
+ watch `unstored` for those.
642
+
643
+ ```ts
644
+ for (const w of mesh.unstored()) {
645
+ offerToWriteAgain(w.env, w.reason); // the envelope holds the values that were written
646
+ w.dismiss(); // removes the entry; it stays listed across reboots until this is saved
647
+ }
648
+ ```
649
+
650
+ Each entry of `unstored` holds the envelope as it was written, its `reason` (`'generation'`,
651
+ `'schema'`, `'order'`, `'compacting'`, or `'incompatible'` for a saved write this build cannot send)
652
+ and `dismiss()`. The list is in the order the writes were made, and it is empty before the outbox
653
+ has loaded.
654
+
655
+ A write the relay turns into a conflict (`citation` or `epoch-bump`, listed in `conflicts`) is
656
+ outstanding until you discard it or write it again. While one is held, `acked()` is `false` and
657
+ `whenAcked()` rejects at once with `conflict: <cause>`; `reauthor()` hands that over to the new
658
+ write, which is acknowledged like any other. `discard()` answers the conflict; it does not edit the
659
+ store. If the room then turns out empty, the seed that creates it is the store as it stands, and it
660
+ may hold that write's effect.
479
661
 
480
662
  ## Schema versions
481
663
 
@@ -510,6 +692,30 @@ one is a few lines. `onClose` reports the close `code` and `reason` (a 1009 mean
510
692
  closed because a frame was too big), and `meshSync`'s `onDisconnect` option surfaces them
511
693
  when a reconnect is scheduled.
512
694
 
695
+ The client also closes a connection itself, with code 1000 and one of three reasons: `'timeout'` (a
696
+ hello went unanswered), `'displaced'` (a later connection of this client took its place) or
697
+ `'counter'` (the connection used up its request ids). The `handshake` option sets how long a hello
698
+ may wait: `timeoutMs` (default 15 000), doubled for every hello in a row that went unanswered, up
699
+ to `maxTimeoutMs` (default 120 000). An answered hello starts the count again, and an unanswered
700
+ one counts as a failed attempt for the reconnect backoff. A relay that never answers a hello within
701
+ `maxTimeoutMs` leaves the client resetting the connection at that pace for as long as it lasts:
702
+ nothing is lost, and nothing gets through. `agentSeat` takes the same option.
703
+
704
+ A transport factory or a `send` that throws is reported and loses the connection, with code 1006
705
+ and the reason `'transport'` or `'send'` (through `onDisconnect`). A callback of yours that throws
706
+ (`onEject`, `onDisconnect`, a `direct` or signaling listener) is reported through `reportError`,
707
+ else `console.error`, and changes nothing else.
708
+
709
+ ```ts
710
+ meshSync(store, {
711
+ room,
712
+ writer,
713
+ transport,
714
+ handshake: { timeoutMs: 10_000, maxTimeoutMs: 60_000 },
715
+ onDisconnect: (code, reason) => log.info('mesh disconnected', code, reason),
716
+ });
717
+ ```
718
+
513
719
  ## Peer to peer
514
720
 
515
721
  `webRtcMesh` runs the same convergence over WebRTC data channels, using the relay only for