@mmstack/mesh 22.15.1 → 22.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.
@@ -1,6 +1,11 @@
1
1
  import { Injector, Signal, WritableSignal } from "@angular/core";
2
- import { ClientMsg, ClientSignalMsg, CoverContext, Dot, GenerationReason, Hlc, IceServer, Key, OpEnvelope, OpPolicy, PolicyViolation, PresenceState, PrincipalCtx, Ranges, Receipts, RegisterStore, Relay, ServerDirectMsg, ServerMsg, StoreOp, TailPolicy, VersionRange } from "@mmstack/mesh-protocol";
3
- import { AsyncStore, DiffOpsOptions, ForkStoreOptions, MergePolicyEntry, OpEnvelope as OpEnvelope$1, OpSync, StoreOp as StoreOp$1, SyncedFork, WritableSignalStore, toStoreOptions } from "@mmstack/primitives/core";
2
+ import { ClientMsg, ClientSignalMsg, GenerationReason, Hlc, IceServer, OpPolicy, PresenceState, PrincipalCtx, Relay, ServerMsg, TailPolicy } from "@mmstack/mesh-protocol";
3
+ import { DiffOpsOptions, ForkStoreOptions, JournalStore, MergePolicyEntry, OpEnvelope, OpSync, StoreOp, SyncedFork, WritableSignalStore, toStoreOptions } from "@mmstack/primitives/core";
4
+ /** The authored intent of an own envelope: its raw ops and one bump flag, what a re-author rebuilds from. */
5
+ type Intent = {
6
+ readonly raws: readonly StoreOp[];
7
+ readonly bump: boolean;
8
+ };
4
9
  /**
5
10
  * The client half of a room generation: the record fields a snapshot welcome carries, the admission
6
11
  * evidence the client keeps for its pre-check, and the pure decisions the session takes on them
@@ -19,112 +24,6 @@ type InstalledGeneration = {
19
24
  /** The seq of the snapshot welcome that installed it (or a later one of the same generation). */
20
25
  readonly seq: number;
21
26
  };
22
- /**
23
- * The admission evidence of the installed generation as this client knows it: the welcome's ranges,
24
- * settled vector and first stamps, then every envelope the client ingests (its own included).
25
- * A lead or lag against the relay's view only ever yields a refusal the client lands as a conflict.
26
- */
27
- type ClientAdmission = {
28
- readonly ranges: Map<string, Ranges>;
29
- readonly settled: Map<string, Hlc>;
30
- readonly firstStamps: Map<string, Hlc>;
31
- };
32
- /** The serializable form of {@link ClientAdmission}. */
33
- type ClientAdmissionRecord = {
34
- readonly ranges: Readonly<Record<string, readonly VersionRange[]>>;
35
- readonly settled: Readonly<Record<string, Hlc>>;
36
- readonly firstStamps: Readonly<Record<string, Hlc>>;
37
- };
38
- declare const emptyAdmission: () => ClientAdmission;
39
- /** The admission evidence a snapshot welcome carries, as of its seq. */
40
- declare const admissionOf: (src: ClientAdmissionRecord) => ClientAdmission;
41
- declare const admissionRecord: (a: ClientAdmission) => ClientAdmissionRecord;
42
- /**
43
- * One envelope reaches this client's view (its own emission, a relay delivery, a replayed or
44
- * re-applied own write). A version it already holds is a duplicate, and one below its origin's
45
- * maximum was skipped by the relay: both are refused (`false`), nothing is recorded. Otherwise the
46
- * version joins the evidence exactly as the relay records it.
47
- */
48
- declare function admitLocal(a: ClientAdmission, env: {
49
- readonly origin: string;
50
- readonly version: number;
51
- readonly hlc: Hlc;
52
- }): boolean;
53
- /** The context `admits` reads: the installed record's extent and preCutMax, the client's evidence. */
54
- declare const coverContext: (gen: Pick<InstalledGeneration, "extent" | "preCutMax">, a: ClientAdmission) => CoverContext;
55
- /**
56
- * The replay pre-check: every cite of `env` (its own dot excepted) the installed state does not
57
- * cover, by the same `admits` the relay runs, over the client's register store. An envelope with
58
- * an uncovered cite is never sent; it is a conflict.
59
- */
60
- declare function uncoveredCites(store: RegisterStore, ctx: CoverContext, env: OpEnvelope): {
61
- readonly path: readonly Key[];
62
- readonly dot: Dot;
63
- }[];
64
- /** What the client knows of its installed generation when a snapshot welcome arrives. */
65
- type WelcomeFence = {
66
- readonly index: number;
67
- readonly instance: string | undefined;
68
- /** The seq of the installed snapshot. */
69
- readonly seq: number;
70
- /** The highest seq of a relay-delivered envelope of this generation, deduplicated or not. */
71
- readonly maxSeq: number;
72
- };
73
- /**
74
- * Which snapshot welcome installs. A newer generation (higher index) always does. One of the
75
- * installed generation does when it is not older than the installed snapshot (`stale` otherwise)
76
- * and not older than relay traffic already delivered (`older-than-traffic`): installing it would
77
- * replace that traffic with an earlier state. Anything else is stale.
78
- */
79
- declare function welcomeVerdict(installed: WelcomeFence, msg: {
80
- readonly index: number;
81
- readonly instance: string;
82
- readonly seq: number;
83
- }): 'newer' | 'same' | 'stale' | 'older-than-traffic';
84
- /** A pending envelope of an earlier generation, as the tail policy reads it. */
85
- type Pending = {
86
- readonly env: Pick<OpEnvelope, 'origin' | 'instance' | 'version'>;
87
- };
88
- /**
89
- * A new generation's first step with the pending tail: in version order, an envelope whose version
90
- * the receipts of its origin hold — in ANY generation — was admitted and is never resent; the rest
91
- * is kept for the tail policy. Membership is instance-agnostic: a replayed envelope carries the
92
- * current instance, so the relay receipts it there while the tail entry still names the generation
93
- * it was authored in, and a crash between the wire and the record would otherwise replay it again
94
- * after the next cut. An origin's versions never repeat (the counter runs through replay; a restart
95
- * that loses it mints a new origin), so the version alone identifies the write.
96
- */
97
- declare function trimByReceipts<T extends Pending>(pending: readonly T[], receipts: Receipts): {
98
- readonly trimmed: T[];
99
- readonly keep: T[];
100
- };
101
- /** A refusal was classified: a snapshot at or past its seq is owed. */
102
- declare const owedAfterRefusal: (owed: number | undefined, seq: number) => number;
103
- /** A snapshot installed at `seq`: the owed rehydration completes when it reaches the refusal. */
104
- declare const owedAfterInstall: (owed: number | undefined, seq: number) => number | undefined;
105
- /**
106
- * A member's readiness for a consensus cut: it pressed Compact, it is connected, and nothing it
107
- * wrote is outstanding (its outbox empty, no replay running). A conflict is never outstanding: it
108
- * is out of the outbox the moment it is classified.
109
- */
110
- declare const readyValue: (s: {
111
- readonly pressed: boolean;
112
- readonly connected: boolean;
113
- readonly replaying: boolean;
114
- readonly outstanding: number;
115
- }) => boolean;
116
- /**
117
- * The authored intent of an envelope: its raw op list and one bump flag, what a re-author rebuilds
118
- * from. The raws are the stamped ops without their expansion clears (a diffed write never emits a
119
- * `clear` of its own, so every `clear` is one) and without cites and epoch. The envelope bumped when
120
- * an op's epoch rises above the register baseline at its path as the client held it before the
121
- * envelope (the relay's own test for a bump).
122
- */
123
- type Intent = {
124
- readonly raws: readonly StoreOp[];
125
- readonly bump: boolean;
126
- };
127
- declare function intentOf(env: OpEnvelope, baseline: (path: readonly Key[]) => number): Intent;
128
27
  /**
129
28
  * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport
130
29
  * represents a single connection and never reconnects itself.
@@ -142,15 +41,30 @@ type MeshTransportFactory = () => MeshTransport;
142
41
  * flushed on open; malformed inbound frames are dropped.
143
42
  */
144
43
  export declare function webSocketTransport(url: string, protocols?: string | string[]): MeshTransportFactory;
44
+ type DirectTransportOptions = {
45
+ /**
46
+ * Hand the relay's messages to this peer BY REFERENCE instead of through a JSON hop. A snapshot
47
+ * welcome then costs the peer no copy of the room's registers: its stores hold the relay's own
48
+ * sibling objects, the same ones every other such peer holds. The peer must therefore treat
49
+ * everything it receives as the relay's memory and never mutate it — a write in place would
50
+ * corrupt the room for everyone. The peer's own messages still cross as JSON, so what it writes
51
+ * reaches the relay exactly as a socket peer's would. Off by default; opt in only for a process
52
+ * whose readers are known not to mutate what a seat materializes.
53
+ */
54
+ readonly byReference?: boolean;
55
+ };
145
56
  /**
146
57
  * Connects directly to an in-process `createRelay` — no network. The backbone of full-loop
147
58
  * tests, and handy for single-process demos or an SSR-side room.
148
59
  *
149
60
  * Messages cross as JSON in both directions, as they would over a socket, so a direct peer holds
150
61
  * exactly what a socket peer would. Handed over by reference, an `undefined` an emitter wrote
151
- * would reach relay memory where a socket peer's would have been dropped.
62
+ * would reach relay memory where a socket peer's would have been dropped. The relay's own
63
+ * messages may skip the hop ({@link DirectTransportOptions.byReference}): they never hold an
64
+ * `undefined` (every value in a room arrived as JSON), so the two peers read the same state and
65
+ * differ only in who owns the objects.
152
66
  */
153
- export declare function directTransport(relay: Relay, ctx: PrincipalCtx): MeshTransportFactory;
67
+ export declare function directTransport(relay: Relay, ctx: PrincipalCtx, options?: DirectTransportOptions): MeshTransportFactory;
154
68
  /**
155
69
  * Why a write is a conflict: its replay into a new generation cites something the generation does
156
70
  * not hold (`'uncovered'`, never sent), or the relay refused it — a cite it does not cover
@@ -161,17 +75,50 @@ type ConflictCause = 'uncovered' | 'citation' | 'epoch-bump';
161
75
  * A write that will never be admitted as it stands. Its local effect is retracted (a replay that
162
76
  * failed its pre-check is never applied; a refused write is dropped by the snapshot that follows).
163
77
  * The two verbs are the whole surface: `discard()` lets it go, `reauthor()` writes its raw ops again
164
- * as a new write citing the current state. Neither can submit the original envelope.
78
+ * as a new write citing the current state. Neither can submit the original envelope. A conflict is
79
+ * listed once its verdict is stored, and stays listed across reboots until it is answered.
165
80
  */
166
81
  type MeshConflict = {
167
82
  /** The envelope as it was authored (its values, cites and epoch). */
168
- readonly env: OpEnvelope$1;
83
+ readonly env: OpEnvelope;
169
84
  readonly intent: Intent;
170
85
  readonly cause: ConflictCause;
86
+ /** Let the write go. Nothing happens once the session has ended. */
171
87
  discard(): void;
172
- /** Write the raw ops again as a new write; false when the shell cannot write (no `reauthor`). */
88
+ /**
89
+ * Write the raw ops again as a new write; false when the shell cannot write (no `reauthor`).
90
+ * Also false when the conflict's ops cannot be written again as one write (a path twice, or an
91
+ * op under another op's path that is not an earlier set of a plain record); the conflict then
92
+ * stays, so it can still be discarded. Also false once the session has ended (closed or
93
+ * ejected): nothing is written and the conflict stays held. Also false inside
94
+ * {@link MeshSession.recordTogether}, with the same outcome.
95
+ * `true` means the write was emitted, not that it shows: one whose parent is gone by now, or
96
+ * that loses its fold, leaves the store as it was. The answer and the new write are stored
97
+ * together: after a crash either both are there or neither is. A write made before the call is
98
+ * not part of them: it is recorded on its own, first. False when the re-author emitted nothing.
99
+ */
173
100
  reauthor(): boolean;
174
101
  };
102
+ /**
103
+ * Why an own write was not stored: `'generation'` (written in a room generation a cut or a lost
104
+ * room creation closed), `'schema'` (a data shape older than the room's), `'order'` (a version below
105
+ * this origin's admitted maximum that was never admitted: a second writer on one origin),
106
+ * `'compacting'` (a host refused it while this client was declared ready for a cut) or
107
+ * `'incompatible'` (a restored write this client can no longer send).
108
+ */
109
+ type UnstoredReason = 'generation' | 'schema' | 'order' | 'compacting' | 'incompatible';
110
+ /**
111
+ * An own write that is not in the room and never will be, listed until the application dismisses it.
112
+ * It is listed once its verdict is stored, and again after a reboot until its dismissal is stored.
113
+ */
114
+ type UnstoredWrite = {
115
+ /** The envelope as it was authored: its values, so the application can offer to write them again. */
116
+ readonly env: OpEnvelope;
117
+ readonly intent: Intent;
118
+ readonly reason: UnstoredReason;
119
+ /** Remove the entry; it leaves the list at once. Nothing happens once the session has ended. */
120
+ dismiss(): void;
121
+ };
175
122
  /** The room's compaction state, as the relay last announced it. */
176
123
  type CompactionState = {
177
124
  /** Droppable tombstones counted against the budget. */
@@ -183,29 +130,6 @@ type CompactionState = {
183
130
  };
184
131
  /** The room generation the client installed, as its snapshot welcome named it. */
185
132
  type GenerationState = Pick<InstalledGeneration, 'instance' | 'index' | 'reason' | 'policy'>;
186
- /**
187
- * The session's durable half, persisted as one unit with the outbox: the fields of the generation
188
- * the tail was written in and its admission evidence, the intents of the pending writes, unresolved
189
- * conflicts and an owed snapshot. It holds NO registers and no sequence knowledge: a restart never
190
- * trusts stale registers — it installs nothing from disk, asks for a snapshot (hello without seq)
191
- * and resends its outbox first.
192
- */
193
- type SessionRecord = {
194
- readonly generation?: Omit<InstalledGeneration, 'seq'>;
195
- readonly admission?: ClientAdmissionRecord;
196
- readonly intents?: readonly {
197
- readonly origin: string;
198
- readonly version: number;
199
- readonly intent: Intent;
200
- }[];
201
- readonly conflicts?: readonly {
202
- readonly env: OpEnvelope$1;
203
- readonly intent: Intent;
204
- readonly cause: ConflictCause;
205
- }[];
206
- /** A refusal's seq: a snapshot at or past it must install before the client trusts its view. */
207
- readonly rehydrateOwed?: number;
208
- };
209
133
  type MeshStatus = 'connecting' |
210
134
  /** Queued behind another tab that owns this key's durable outbox (`crossTab: 'queue'`). */
211
135
  'waiting' | 'live' | 'reconnecting' | 'ejected' | 'closed';
@@ -216,172 +140,10 @@ type MeshDirect = {
216
140
  readonly data: unknown;
217
141
  };
218
142
  /**
219
- * Hands `msg` to every listener; a throwing listener never interrupts the session or the others.
220
- * @internal
221
- */
222
- declare const deliverDirect: (listeners: ReadonlySet<(msg: MeshDirect) => void>, msg: ServerDirectMsg) => void;
223
- /** One sequenced remote envelope's ops, attributed to the writer that made them. */
224
- type RemoteBatch = {
225
- /** The relay's total-order stamp for this batch. */
226
- readonly seq: number;
227
- readonly writer: string;
228
- readonly ops: readonly StoreOp$1[];
229
- };
230
- /**
231
- * Environment callbacks a session shell provides. All are optional except `onStatus`; the
232
- * session never touches signals, timers beyond `schedule`, storage, or the DOM itself.
143
+ * A data channel as the P2P engine needs it; it opens later. Peer links send only on an open
144
+ * channel, so the contract asks for no buffering, but the channels of {@link rtcPeerConnector}
145
+ * buffer sends made before open and flush them when the channel opens.
233
146
  */
234
- type MeshSessionHooks = {
235
- onStatus(status: MeshStatus, reason?: string): void;
236
- /** The current op engine's origin, published immediately before each hello. */
237
- onOrigin?(origin: string): void;
238
- /** Relay membership, independent of presence; undefined while disconnected or before welcome. */
239
- onMembers?(members: readonly string[] | undefined): void;
240
- /**
241
- * A room message after the session has processed it, for consumers sharing its connection.
242
- * `direct` frames never pass here; they go to {@link MeshSessionHooks.onDirect} only.
243
- */
244
- onMessage?(msg: ServerMsg): void;
245
- /**
246
- * A `direct` frame addressed to this session, in the frame version this side speaks; any other
247
- * version is refused unread. One that arrives before the current connection's welcome is held
248
- * (up to 256) and handed over right after it, unless its sender leaves first.
249
- */
250
- onDirect?(msg: ServerDirectMsg): void;
251
- /** A welcome or envelope arrived — the shell's "last synced" moment. */
252
- onSynced?(): void;
253
- /** The presence roster changed (welcome replace, join/leave, teardown clear). */
254
- onPeers?(peers: ReadonlyMap<string, PresenceState>): void;
255
- /** A remote (non-own) envelope was ingested, in seq order. */
256
- onRemote?(batch: RemoteBatch): void;
257
- /**
258
- * Seq continuity broke: a snapshot welcome (or a relay instance change) established state
259
- * without delivering the individual envelopes in between. Any consumer deriving from the
260
- * `onRemote` stream must rebuild from current state at this seq; appending across a resync
261
- * would silently skip history.
262
- */
263
- onResync?(seq: number): void;
264
- /** The unacknowledged local tail changed (emit or ack) — the durable-outbox trigger. */
265
- onOutboxChange?(): void;
266
- /**
267
- * A local write violated the room policy. The session ejects itself immediately after —
268
- * the outcome the relay's own independent check would have produced one hop later. The
269
- * emit-side check spares the room the round trip; it is never the enforcement.
270
- */
271
- onLocalReject?(violation: PolicyViolation): void;
272
- /** The transport closed and a reconnect is scheduled; `code` is the close code (1009 = message too big). */
273
- onDisconnect?(code: number, reason: string): void;
274
- /**
275
- * Teardown is starting; fired before the unacked tail is dropped, so a shell can persist
276
- * it (and release any single-writer locks) while it is still intact.
277
- */
278
- onTerminal?(state: 'ejected' | 'closed', reason?: string): void;
279
- /**
280
- * The relay refused one of this session's writes: it is not in the room and never will be.
281
- * `'generation'` — written in a room generation that a cut with the `discard` policy closed (a
282
- * migration or a rollback: the reset is the intent), or in a room recreated without its
283
- * generation record; `'schema'` — a data shape older than the room's; `'order'` — a version
284
- * below this origin's admitted maximum that was never admitted (a second tab on one origin);
285
- * `'compacting'` — a host refused a write from a connection declared ready for the current
286
- * generation (the relay itself never sends it). The session drops the write locally and hydrates from a fresh snapshot; the envelope carries the
287
- * values, so the application can offer to write them again. Any `whenAcked` waiter rejects.
288
- * A write a compaction cut replays is never refused here: it is resent, or it is a conflict.
289
- */
290
- onRefused?(env: OpEnvelope$1, reason: 'generation' | 'schema' | 'order' | 'compacting'): void;
291
- /** The unresolved conflicts changed (a write classified, discarded or re-authored). */
292
- onConflicts?(conflicts: readonly MeshConflict[]): void;
293
- /** The relay announced the room's compaction state (count, budget, ready members). */
294
- onCompaction?(state: CompactionState): void;
295
- /**
296
- * A snapshot welcome of a NEW generation installed (a cut's welcome, or the first snapshot of
297
- * the session); `undefined` when the room was recreated without its record. A welcome of the
298
- * installed generation never fires it.
299
- */
300
- onGeneration?(generation: GenerationState | undefined): void;
301
- };
302
- type MeshSessionOptions<T extends object> = {
303
- readonly room: string;
304
- readonly writer: string;
305
- readonly transport: MeshTransportFactory;
306
- /** The op engine this session feeds. The shell creates (and destroys) it. */
307
- readonly sync: OpSync<T>;
308
- readonly policies?: readonly MergePolicyEntry[];
309
- readonly policy?: OpPolicy;
310
- readonly ctx?: Omit<PrincipalCtx, 'writer'>;
311
- readonly policyVersion: number;
312
- readonly schemaVersion?: number;
313
- /** The room generation a restored outbox was written in; the first welcome decides whether it still holds. */
314
- readonly instance?: string;
315
- /**
316
- * The restored durable record (see {@link SessionRecord}), applied at `connect()` on top of the
317
- * restored outbox: the registers are hydrated with the pending writes re-applied over them.
318
- */
319
- readonly record?: SessionRecord;
320
- /**
321
- * Write a conflict's raw ops again (a new write citing the current state), on the shell's store;
322
- * with `bump`, as an authority override. Without it a conflict can only be discarded.
323
- */
324
- readonly reauthor?: (intent: Intent) => void;
325
- readonly reconnect?: {
326
- readonly maxDelayMs?: number;
327
- };
328
- /** Timer seam (tests, deterministic harnesses). Defaults to global timers. */
329
- readonly schedule?: {
330
- set(fn: () => void, ms: number): unknown;
331
- clear(handle: unknown): void;
332
- };
333
- readonly hooks: MeshSessionHooks;
334
- };
335
- /**
336
- * The relay-room session protocol, shell-agnostic: hello/welcome handshakes (snapshot
337
- * hydrate, delta replay, fresh-room seed), own-echo acknowledgement, unacked resend,
338
- * the relay's per-envelope answers (`drop`), reconnect backoff, presence, eject/reject, the
339
- * generation fence and settled-vector garbage collection. `meshSync` wraps it for
340
- * Angular; `agentSeat` wraps it for injector-free environments. One implementation of the
341
- * wire contract — shells differ only in environment concerns.
342
- */
343
- type MeshSession = {
344
- /** Open the first connection. Call once, after any outbox restore has replayed. */
345
- connect(): void;
346
- status(): MeshStatus;
347
- /** Highest relay seq observed. With no unacked writes, local state is the pure fold of the room at this seq. */
348
- lastSeq(): number;
349
- hasUnacked(): boolean;
350
- /**
351
- * Resolves once the unacknowledged local tail is empty — the acknowledgement barrier a
352
- * caller awaits before treating its writes as the room's. Resolves immediately when
353
- * nothing is outstanding. Rejects with the terminal reason if the session ends (eject or
354
- * close) while entries remain: those writes never reached the room, and every later call
355
- * rejects the same way.
356
- *
357
- * With a relay whose adapter confirms durability before echoing, acknowledged means
358
- * stored; against a relay that echoes eagerly it means only "the relay has it".
359
- */
360
- whenAcked(): Promise<void>;
361
- /** The unacknowledged local tail (the durable-outbox payload). */
362
- unackedEnvs(): readonly OpEnvelope$1[];
363
- /** The room generation this session is in, once a welcome (or a restored outbox) named one. */
364
- instance(): string | undefined;
365
- peers(): ReadonlyMap<string, PresenceState>;
366
- setPresence(data: unknown): void;
367
- /** Send peer signaling over the current connection without a second hello. */
368
- sendSignal(msg: ClientSignalMsg): void;
369
- /** Send a `direct` frame to one member over the current connection; lost when there is none. */
370
- sendDirect(to: string, data: unknown): void;
371
- /** Writes that will never be admitted as they stand, each with its two verbs. */
372
- conflicts(): readonly MeshConflict[];
373
- /**
374
- * The member pressed (or released) Compact. While pressed, the session declares itself ready for
375
- * a consensus cut whenever nothing it wrote is outstanding, and re-declares on every change; a
376
- * reconnect and a new generation release the press. Safety never depends on it.
377
- */
378
- declareReady(pressed: boolean): void;
379
- /** The durable record to persist with the outbox (see {@link SessionRecord}). */
380
- record(): SessionRecord;
381
- close(): void;
382
- };
383
- declare function meshSession<T extends object>(opt: MeshSessionOptions<T>): MeshSession;
384
- /** A data channel as the P2P engine needs it; opens later, buffers nothing itself. */
385
147
  type DataChannelLike = {
386
148
  send(frame: string): void;
387
149
  onMessage(cb: (frame: string) => void): () => void;
@@ -558,25 +320,37 @@ type MeshPeer = PresenceState;
558
320
  /**
559
321
  * A composed, user-facing health status for a synced store the surface that
560
322
  * turns a versioned reject from a dead socket into a speakable 'outdated' banner.
323
+ * `'storage'`: the outbox can no longer save this handle's writes, and the session has ended and
324
+ * sends nothing more. The reason says why: `'moved'` (another tab wrote the outbox in its place),
325
+ * `'exhausted'` (the outbox ran out of sequence numbers) or `'storage'` (a save failed, or the
326
+ * outcome of a write is not known: it is reported neither as saved nor as lost). A first read of
327
+ * the outbox that fails does not end the handle; see `outboxUnreadable`.
561
328
  */
562
- type SyncHealthStatus = 'live' | 'waiting' | 'offline' | 'outdated' | 'ejected' | 'degraded';
329
+ type SyncHealthStatus = 'live' | 'waiting' | 'offline' | 'outdated' | 'ejected' | 'degraded' | 'storage';
563
330
  type SyncHealth = {
564
331
  readonly status: SyncHealthStatus;
565
- /** Why, when the status is `outdated`/`ejected`/`degraded`. */
566
- readonly reason?: 'proto' | 'policy-version' | 'schema' | 'quota' | 'worker' | (string & {});
332
+ /** Why, when the status is `outdated`/`ejected`/`degraded`/`storage`. */
333
+ readonly reason?: 'proto' | 'policy-version' | 'schema' | 'quota' | 'worker' | 'storage' | 'moved' | 'exhausted' | (string & {});
567
334
  /** `Date.now()` of the last successful sync (welcome or applied env). */
568
335
  readonly lastSyncedAt?: number;
569
336
  /**
570
- * Offline writes persisted by an older build that could not be restored on boot. Envelopes
571
- * from a previous wire-protocol version lack the citation metadata current merging needs,
572
- * so they are dropped (loudly) instead of being upgraded with fabricated citations.
337
+ * How many groups of this handle's writes are in storage's hands and not yet saved. Nothing times
338
+ * out: a store that never answers keeps it above zero until the handle closes.
339
+ */
340
+ readonly storing: number;
341
+ /**
342
+ * Saved offline writes this boot cannot send: written under another writer, protocol version or
343
+ * policy version, malformed, or rejected by the room policy. They are never sent; each is listed
344
+ * in `unstored` with the reason `'incompatible'`.
573
345
  */
574
346
  readonly droppedOfflineWrites?: number;
575
347
  /**
576
- * Writes the relay refused on this session: they are not in the room. Each was handed to
577
- * `onRefused` with its values, and the store was rehydrated from a fresh snapshot after it.
348
+ * The saved outbox could not be read: it is in a format this build cannot read, or the store
349
+ * failed the read. It is left as it is, and this boot's writes are kept in memory only, under an
350
+ * origin of their own, until the handle closes. The handle runs live over memory, and its
351
+ * health does not turn `'storage'` for this.
578
352
  */
579
- readonly refusedWrites?: number;
353
+ readonly outboxUnreadable?: true;
580
354
  /**
581
355
  * Received envelopes rejected as malformed by the deterministic well-formedness check (a bad id
582
356
  * or path segment, a non-integer version, an unknown op kind, a negative epoch, forged cites, a
@@ -617,14 +391,36 @@ type MeshSyncOptions = {
617
391
  readonly reconnect?: {
618
392
  readonly maxDelayMs?: number;
619
393
  };
394
+ /**
395
+ * How long a hello may go unanswered before the connection is closed and opened again:
396
+ * `timeoutMs` (default 15 000), doubled for every hello in a row that went unanswered, up to
397
+ * `maxTimeoutMs` (default 120 000). An answered hello starts the count again. A hello that goes
398
+ * unanswered also counts as a failed attempt for the reconnect backoff. A relay that never
399
+ * answers a hello within `maxTimeoutMs` leaves the client resetting the connection at that pace
400
+ * for as long as it lasts: nothing is lost, and nothing gets through.
401
+ */
402
+ readonly handshake?: {
403
+ readonly timeoutMs?: number;
404
+ readonly maxTimeoutMs?: number;
405
+ };
620
406
  readonly injector?: Injector;
621
407
  /** Register with the nearest transition scope so (re)connection surfaces as `pending`. */
622
408
  readonly register?: 'track' | 'suspend';
409
+ /**
410
+ * Called once when the handle ends by itself (`ejected`, with the reason) and when a
411
+ * `clearOutbox()` ends it (`'cleared'`); never for `close()`. A callback that throws is reported
412
+ * and changes nothing.
413
+ */
623
414
  readonly onEject?: (reason: string) => void;
624
- /** The connection dropped and a reconnect is scheduled; `code` is the close code (1009 = message too big, 1006 = dropped). */
415
+ /**
416
+ * The connection dropped and a reconnect is scheduled; `code` is the close code (1009 = message
417
+ * too big, 1006 = dropped). The client also closes a connection itself, with code 1000 and the
418
+ * reason `'timeout'` (a hello went unanswered), `'displaced'` (a later connection of this client
419
+ * took its place) or `'counter'` (the connection used up its request ids). A transport factory or
420
+ * a `send` that throws is reported and loses the connection, with code 1006 and the reason
421
+ * `'transport'` or `'send'`.
422
+ */
625
423
  readonly onDisconnect?: (code: number, reason: string) => void;
626
- /** A write the relay refused (see `MeshSessionHooks.onRefused`); the envelope carries its values. */
627
- readonly onRefused?: (env: OpEnvelope$1, reason: 'generation' | 'schema' | 'order' | 'compacting') => void;
628
424
  /**
629
425
  * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects
630
426
  * (and before it restores an `outbox`), so a store hydrated from another source first (a worker
@@ -634,35 +430,50 @@ type MeshSyncOptions = {
634
430
  */
635
431
  readonly whenReady?: () => PromiseLike<void> | void;
636
432
  /**
637
- * Persist the unacknowledged local outbox (and the writing boot's origin) so offline writes
638
- * survive a REBOOT, not just a live reconnect: on boot they are restored and rebased onto the room
639
- * on the next welcome, instead of being lost with in-memory state. The payload is written to
640
- * `store` under `key`, debounced.
433
+ * Keep this client's own writes in `store` under `key`, so offline writes survive a reboot, not
434
+ * just a live reconnect. Every write is saved before it is sent, and every answer about it is
435
+ * saved before it shows, so a crash at any moment loses nothing that was sent. On boot the saved
436
+ * writes that are still pending are restored and sent again, unchanged, after the next welcome.
437
+ * The saved outbox also keeps this client's origin, so every boot that reads it continues as the
438
+ * same client. Without an outbox, writes are kept in memory only and each boot has an origin of
439
+ * its own.
641
440
  *
642
- * The persisted outbox under `key` is a single-writer slot: every persist overwrites it whole, so
643
- * two tabs writing one key would each drop the other's tail from disk. A Web Lock on `key` elects
644
- * the one tab that restores from the slot and writes to it; origins are fresh on every boot either
645
- * way, so the lock guards the slot, not the origin. `crossTab` sets what a tab that did not get the
646
- * lock does: `'queue'` (default) waits (`status` reads `'waiting'`) and takes over when the owner
647
- * closes; `'ephemeral'` runs live at once and never touches the slot. `'off'` skips the lock and
648
- * leaves ownership to you (e.g. a per-tab key, or leader election over `tabSync`). A debounced
649
- * write means a hard crash within the debounce window can drop the very last mint — a small,
650
- * best-effort gap; tune it with `debounceMs`.
441
+ * The store is a `JournalStore` (build one over idb-keyval's shape with `journalStore`). Two
442
+ * keys are written, `<key>:log` and `<key>:snap`. A value saved under `key` itself by an earlier
443
+ * version of this library is deleted unread at each boot, when the store can delete.
444
+ *
445
+ * Storage decides between tabs: when another tab has written the outbox in this handle's place,
446
+ * this handle ends `ejected` with the reason `'moved'`. A write it had not saved by then is not
447
+ * saved, and no other tab can send it: `acked` reads `false` and `whenAcked()` rejects, and the
448
+ * application decides what to do with it. A Web Lock on `key` keeps live tabs from taking each
449
+ * other's place; `crossTab` sets what a tab that did not get the lock does. Within one page, a handle
450
+ * made in the turn another handle over the same key was closed takes over from it (unless another
451
+ * tab asked for the lock first). A handle made while another handle of this page over the
452
+ * same key is still open is treated as a second tab would be: `'queue'` waits for it, `'ephemeral'`
453
+ * runs over memory for its life. So close the old handle first. Two copies of this library in one
454
+ * page behave as two tabs. Store writes made while the boot
455
+ * waits (for the lock or the read) are held in memory and sent, as their net change, when the tab
456
+ * boots. Nothing times out: a store call that never answers keeps the handle live and holding the
457
+ * lock, and `health().storing` above zero, until it closes.
651
458
  */
652
459
  readonly outbox?: {
653
460
  readonly key: string;
654
- readonly store: AsyncStore;
655
- /** Coalesce outbox writes by this many ms (default 300; `0` = write on every change). */
656
- readonly debounceMs?: number;
461
+ readonly store: JournalStore;
657
462
  /**
658
- * Cross-tab contention for the shared `key`. The persisted outbox is a single-writer slot: the
659
- * Web Lock elects the one tab that restores from it and writes to it.
660
- * `'queue'` (default): a tab that did not get the lock WAITS (`status` reads `'waiting'`) and
661
- * takes over when the owner closes. `'ephemeral'`: it runs live at once on its own fresh origin
662
- * and never touches the slot — its unacknowledged writes live in memory only and are lost if that
663
- * tab terminates before the room acknowledges them — online or offline, and it stays ephemeral
664
- * for life, also after the owner leaves. When the lock is free both behave the same (take it,
665
- * restore, persist). `'off'` skips the lock (you coordinate ownership).
463
+ * What a tab does when another tab holds the lock for `key`.
464
+ * `'queue'` (default): it WAITS (`status` reads `'waiting'`) and takes over when the owner
465
+ * closes; store writes made while it waits are sent, as their net change, when it takes over.
466
+ * `'ephemeral'`: it runs live at once, as a client of its own, and never touches the saved
467
+ * outbox: its writes live in memory only and are lost if that tab ends before the room
468
+ * acknowledges them. It stays ephemeral for life, also after the owner leaves. When the lock is
469
+ * free both behave the same (take it, restore, save).
470
+ * A `'queue'` handle closed while it waits for another tab keeps its place in the browser's lock
471
+ * queue until its turn; then the lock is taken and given back at once. Until then a new handle
472
+ * of this page is treated as it would be while that other tab holds the lock.
473
+ * `'off'` skips the lock: every tab that opens the key continues the same saved client, and
474
+ * when two tabs write it, one of them ends `ejected` with the reason `'moved'`. Without the
475
+ * lock a tab that has only read the outbox does not keep another tab's `clearOutbox()` from
476
+ * wiping what it is about to send. In development mode it warns once.
666
477
  */
667
478
  readonly crossTab?: 'queue' | 'off' | 'ephemeral';
668
479
  };
@@ -679,7 +490,10 @@ type MeshSyncOptions = {
679
490
  type SeatSync<T = unknown> = Pick<OpSync<T>, 'override' | 'captureFrontier' | 'commitScope' | 'liveUnder' | 'liveAt' | 'appliedFrontier'>;
680
491
  type MeshSyncRef<T extends object = Record<string, unknown>> = {
681
492
  readonly status: Signal<MeshStatus>;
682
- /** Origin used by the current session's hello; null until hello, including while waiting on an outbox. */
493
+ /**
494
+ * This client's origin: the saved outbox's, the same on every boot that reads it, or one of its
495
+ * own for a boot without a saved outbox. Null until the outbox has loaded.
496
+ */
683
497
  readonly origin: Signal<string | null>;
684
498
  /** Other relay members, including peers with no presence; empty before welcome and while disconnected. */
685
499
  readonly members: Signal<readonly string[]>;
@@ -688,16 +502,36 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
688
502
  /** Composed sync-health for a user-facing surface. */
689
503
  readonly health: Signal<SyncHealth>;
690
504
  /**
691
- * Every local write is acknowledged by the room. `false` while a write is still in the
692
- * unacknowledged tail, and it stays `false` once a session ends with writes outstanding —
693
- * those never landed, and no later echo can arrive to change that.
505
+ * Everything written through this handle is saved as the room's: nothing is pending or still
506
+ * being saved and no conflict is held. The signal follows the sync engine, which takes a store
507
+ * write up a moment later, at its next tick: read in the same turn as a write, it still gives
508
+ * the earlier answer. `whenAcked()` counts a write made in this turn, and from that call this
509
+ * signal counts it too. To ask whether everything is saved, including what was just written,
510
+ * call `whenAcked()`. `false` until the outbox has
511
+ * loaded (what is pending is not known before), while a write waits for the room or for storage,
512
+ * while a conflict is held (until it is discarded or written again), and for good once a write
513
+ * can no longer land: a write after an eject, or a write the emit-side policy
514
+ * rejected. After an eject it is `true` exactly when nothing was outstanding at the ejection
515
+ * and nothing was written since. A close freezes it: it keeps the value it had at the close,
516
+ * and a write after the close does not change it. After a storage failure or `clearOutbox()` it
517
+ * is `false`. Writes inside `whenReady` are the local base, not writes of their own. Writes made
518
+ * while the boot is held (waiting for the outbox lock or its read) are saved and sent, as their
519
+ * net change, when the boot ends; each `sync.override` made in the hold is its own authority
520
+ * write, in order. A write the relay refused is listed in `unstored`, not here.
694
521
  */
695
522
  readonly acked: Signal<boolean>;
696
523
  /**
697
- * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects
698
- * with the terminal reason if the session ends while writes are outstanding. The barrier
699
- * to await before publishing something that must contain every edit; `synced()` is a
700
- * connection indicator, not a save barrier.
524
+ * Resolves once nothing written through this handle is outstanding and that is saved
525
+ * (immediately if it already is). Before the outbox has loaded it waits for the load. Rejects
526
+ * with the terminal reason if the session ends while writes are outstanding or a write can no
527
+ * longer land (`'closed'` for writes held in a boot that is closed before it connects), with
528
+ * `'storage'`, `'moved'` or `'exhausted'` once the outbox can no longer save, with `'cleared'`
529
+ * after `clearOutbox()`, and with `'schema'` when this client's data shape is older than the
530
+ * room's. While a conflict is held it rejects at once with `conflict: <cause>`; a terminal reason
531
+ * wins. A write the relay refused rejects the calls pending when its answer is saved with
532
+ * `refused: <reason>`; a later call does not wait for it. The barrier to await before publishing
533
+ * something that must contain every edit; `synced()` is a connection indicator, not a save
534
+ * barrier.
701
535
  */
702
536
  whenAcked(): Promise<void>;
703
537
  readonly peers: Signal<readonly MeshPeer[]>;
@@ -711,6 +545,7 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
711
545
  /**
712
546
  * Listen for `direct` frames addressed to this client; returns the unsubscribe. A frame that
713
547
  * arrives with no listener is lost. Peer links on {@link MeshSyncRef.signaling} never see them.
548
+ * A listener that throws is reported, and the others still hear the frame.
714
549
  */
715
550
  direct(cb: (msg: MeshDirect) => void): () => void;
716
551
  /**
@@ -718,23 +553,40 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
718
553
  * fork observes the room as it is now; committing emits its diff citing only those observed
719
554
  * writes, so an edit that lands on the room while the fork is open stays a concurrent value the
720
555
  * merge policy decides rather than being overwritten by the commit. Call `rebase()` to re-observe
721
- * the room and commit on top of the latest instead. `discard()` drops the staged edits.
556
+ * the room and commit on top of the latest instead. `discard()` drops the staged edits and also
557
+ * re-observes the room, so a later commit on the same fork cites the room as it is at the discard.
558
+ * Before the boot nothing has been observed, so a fork commit made then is a plain held write.
722
559
  */
723
560
  fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
724
- /** Authority surface over the CURRENT op-sync (it is rebuilt on restore); see {@link SeatSync}. */
561
+ /**
562
+ * Authority surface over this handle's op-sync; see {@link SeatSync}. It is one object for the
563
+ * handle's life: taken before the boot, it works over the engine once the outbox has loaded.
564
+ * When the callback of `override` throws, the error reaches the caller and the writes it made are
565
+ * still sent with the override's authority, also while the boot is held. Before the boot nothing
566
+ * has been observed, so a `commitScope` run then is a plain held write.
567
+ */
725
568
  readonly sync: SeatSync<T>;
726
569
  /**
727
570
  * Writes that will never be admitted as they stand: a write a compaction cut could not replay
728
571
  * (it cites something the cut folded away) or one the relay refused. Each offers `discard()` or
729
- * `reauthor()` (write its values again, citing the current state). Persisted with the outbox.
572
+ * `reauthor()` (write its values again, citing the current state). Saved with the outbox: a
573
+ * conflict stays listed across reboots until it is answered.
730
574
  */
731
575
  readonly conflicts: Signal<readonly MeshConflict[]>;
576
+ /**
577
+ * Own writes that are not in the room and never will be, in the order they were made: refused by
578
+ * the relay, discarded with a room generation, or saved offline and no longer sendable by this
579
+ * boot (`'incompatible'`). Each entry holds the write, so it can be offered again, its reason, and
580
+ * `dismiss()`, which removes it. An entry is listed once its answer is saved and stays listed
581
+ * across reboots until its dismissal is saved. Empty before the outbox has loaded.
582
+ */
583
+ readonly unstored: Signal<readonly UnstoredWrite[]>;
732
584
  /** The room's compaction state as the relay last announced it; undefined before any notice. */
733
585
  readonly compaction: Signal<CompactionState | undefined>;
734
586
  /**
735
587
  * The room generation this client installed: set by every snapshot welcome of a new generation
736
588
  * (a cut's welcome flips it), untouched by one of the installed generation. Undefined until the
737
- * first snapshot welcome and after a room was recreated without its record.
589
+ * first snapshot welcome of this boot.
738
590
  */
739
591
  readonly generation: Signal<GenerationState | undefined>;
740
592
  /**
@@ -743,6 +595,55 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
743
595
  * reconnect or a new generation releases it.
744
596
  */
745
597
  declareReady(pressed: boolean): void;
598
+ /**
599
+ * Discard every write not yet in the room, every conflict and every `unstored` entry, and end the
600
+ * session. From the call nothing more is sent or saved, `acked` reads `false` and `whenAcked()`
601
+ * rejects with `'cleared'`; the handle keeps the outbox lock and its status until storage answers.
602
+ * The session ends `closed` with the reason `'cleared'` once storage holds the wipe, and the
603
+ * promise resolves then. It rejects with `'moved'` when another tab wrote the outbox first, with
604
+ * `'storage'` when the outcome is not known, and with the reason of any ending that comes first
605
+ * (`'closed'` for `close()`). A crash before it resolves leaves the outbox as it was, and the next
606
+ * boot continues it and sends what is pending. Called before the boot has finished, it clears
607
+ * once the boot is done, or rejects with the boot's reason.
608
+ *
609
+ * A handle runs over memory when it was given no `outbox`, when it is an `'ephemeral'` tab beside
610
+ * another tab that holds the outbox, or when the saved outbox could not be read. Called while
611
+ * such a handle is live, the clear discards this handle's own writes, resolves, and ends the
612
+ * handle `closed` with `'cleared'`, calling `onEject('cleared')`. A saved outbox the handle never
613
+ * held is left exactly as it is, and the next boot that can read it sends what it holds. An
614
+ * outbox that could not be read is not removed by `clearOutbox()`: the application removes it
615
+ * from its own store, under the key it gave, when it wants it gone.
616
+ *
617
+ * Called once the session has ended by itself (ejected, outdated, a storage ending), it takes the
618
+ * outbox lock if it is free (else it rejects with `'busy'`), reads the outbox again and wipes it
619
+ * only when no other tab has written it since this handle ended (else it rejects with `'moved'`);
620
+ * it rejects with `'unreadable'` when the outbox cannot be read again, and with `'storage'` when
621
+ * the store does not say whether the wipe was stored. It
622
+ * holds the lock until storage answers, and `close()` meanwhile rejects it with `'closed'`.
623
+ * After `close()`, and for a handle that never held the saved outbox, it rejects with
624
+ * `'closed'`. A second call while one runs joins it.
625
+ */
626
+ clearOutbox(): Promise<void>;
627
+ /**
628
+ * Leave the room, release the outbox lock and destroy the op engine. A write made in the same
629
+ * tick is handed to storage, before the lock is released, only when nothing of this handle is in
630
+ * storage's hands: no earlier write still being saved, and not the record the handle saves as it
631
+ * goes live, which storage holds for a moment as the status turns `'live'`. A write queued behind
632
+ * anything still out is not saved. Either way nobody is told it is stored: `acked` reads `false`
633
+ * and `whenAcked()` rejects with `'closed'`. To know that every write is saved, wait for
634
+ * `whenAcked()`, or for `acked` to read `true`, before closing.
635
+ * A save in storage's hands may still land after the lock is released, and storage decides
636
+ * between it and the next tab's writes.
637
+ * Closed while the boot is still held, the writes made in the hold are dropped: they were never
638
+ * saved, and with a net change `acked` reads `false` and `whenAcked()` rejects with `'closed'`.
639
+ * Without one, an outbox read in flight is let finish, writing nothing, and both answer from it:
640
+ * nothing pending and no conflict held reads `true` and resolves; anything else, or an outbox
641
+ * that cannot be read, reads `false` and rejects with `'closed'`. Until then `acked` is `false`
642
+ * and `whenAcked()` waits.
643
+ * The handle is frozen from then on: the store keeps working locally, but nothing is sent or
644
+ * saved, and `acked`, `conflicts`, `unstored` and `generation` keep the value they had at close.
645
+ * Destroying the injector closes it the same way.
646
+ */
746
647
  close(): void;
747
648
  };
748
649
  /**
@@ -759,7 +660,7 @@ type SeatChange = {
759
660
  /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */
760
661
  readonly seq: number;
761
662
  readonly writer: string;
762
- readonly ops: readonly StoreOp$1[];
663
+ readonly ops: readonly StoreOp[];
763
664
  };
764
665
  /**
765
666
  * Seq continuity broke: the seat re-established state from a room snapshot (a reconnect past
@@ -807,14 +708,30 @@ type AgentSeatOptions = {
807
708
  readonly reconnect?: {
808
709
  readonly maxDelayMs?: number;
809
710
  };
711
+ /**
712
+ * How long a hello may go unanswered before the connection is closed and opened again:
713
+ * `timeoutMs` (default 15 000), doubled for every hello in a row that went unanswered, up to
714
+ * `maxTimeoutMs` (default 120 000). An answered hello starts the count again. A relay that never
715
+ * answers a hello within `maxTimeoutMs` leaves the seat resetting the connection at that pace for
716
+ * as long as it lasts: nothing is lost, and nothing gets through.
717
+ */
718
+ readonly handshake?: {
719
+ readonly timeoutMs?: number;
720
+ readonly maxTimeoutMs?: number;
721
+ };
810
722
  /**
811
723
  * Store context for the replica (from `createStoreContext()`). Defaults to a fresh one;
812
724
  * pass your own to share proxy caches across several seats in one process.
813
725
  */
814
726
  readonly context?: toStoreOptions;
727
+ /**
728
+ * Called once when the seat ends by itself (`ejected`, with the reason, an outdated data shape
729
+ * included) and when a `clearOutbox()` ends it (`'cleared'`); never for `close()`. It is called
730
+ * last: the seat has ended and every clear it owed has settled, so inside it `status()`,
731
+ * `peers()`, `acked()` and `whenAcked()` answer as they do after it (`'ejected'`, or `'closed'`
732
+ * after a clear). A callback that throws is reported and changes nothing.
733
+ */
815
734
  readonly onEject?: (reason: string) => void;
816
- /** A write the relay refused; it is not in the room, and the doc was rehydrated. The envelope carries its values. */
817
- readonly onRefused?: (env: OpEnvelope$1, reason: 'generation' | 'schema' | 'order' | 'compacting') => void;
818
735
  };
819
736
  type AgentSeat<T extends object> = {
820
737
  /** The live converging replica. Reads exactly like a local signal store. */
@@ -824,8 +741,11 @@ type AgentSeat<T extends object> = {
824
741
  /** The current document value — plain JSON-serializable data, for context assembly. */
825
742
  snapshot(): T;
826
743
  /**
827
- * The current document, stamped with the relay seq it is provably the pure fold of
828
- * or null when stability cannot be guaranteed
744
+ * The current document, stamped with the relay seq it is provably the pure fold of, or null
745
+ * when that cannot be guaranteed: before the first welcome, while one of the seat's own writes
746
+ * is still unacknowledged, and from a refused write until the snapshot that replaces it lands.
747
+ * It stays null for good once the seat ended with writes outstanding, after an emit-side policy
748
+ * reject, and after `close()`.
829
749
  */
830
750
  stableSnapshot(): StableSnapshot<T> | null;
831
751
  /** Run local writes and emit them to the room as one envelope, like any peer's edit. */
@@ -835,6 +755,12 @@ type AgentSeat<T extends object> = {
835
755
  * carry, or a relay refusal), each with `discard()` and `reauthor()`.
836
756
  */
837
757
  conflicts(): readonly MeshConflict[];
758
+ /**
759
+ * The seat's writes that are not in the room and never will be, in the order they were made:
760
+ * refused by the relay or discarded with a room generation. Each entry holds the write, its
761
+ * reason and `dismiss()`, which removes it.
762
+ */
763
+ readonly unstored: Signal<readonly UnstoredWrite[]>;
838
764
  /** The room's compaction state as the relay last announced it; undefined before any notice. */
839
765
  readonly compaction: Signal<CompactionState | undefined>;
840
766
  /**
@@ -858,20 +784,43 @@ type AgentSeat<T extends object> = {
858
784
  * `commit()` emits its diff citing only those observed writes, so a room edit that lands
859
785
  * while the fork is open survives as a concurrent value for the merge policy to resolve
860
786
  * instead of being overwritten. `rebase()` re-observes the room; `discard()` drops the
861
- * staged edits.
787
+ * staged edits and also re-observes the room, so a later commit on the same fork cites the
788
+ * room as it is at the discard.
862
789
  */
863
790
  fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
864
791
  /**
865
- * Every local write is acknowledged by the room. `false` while a write is still in the
866
- * unacknowledged tail, and it stays `false` once the seat ends with writes outstanding.
792
+ * Everything written through this seat is the room's: nothing is pending and no conflict is
793
+ * held. It counts a write made in the same turn as the call. `false` until the seat has started
794
+ * (a moment after it is created),
795
+ * while a write waits for the room, while a conflict is held (until it is discarded or written
796
+ * again), and for good once a write can no longer land: a write after an eject,
797
+ * or a write the emit-side policy rejected. After an eject it is `true` exactly when nothing was
798
+ * outstanding at the ejection and nothing was written since. A close freezes it: it keeps the
799
+ * answer it had at the close, and a write after the close does not change it. After a storage
800
+ * failure or `clearOutbox()` it is `false`. A write the relay refused is listed in `unstored`,
801
+ * not here.
867
802
  */
868
803
  acked(): boolean;
869
804
  /**
870
- * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects
871
- * with the terminal reason if the seat ends while writes are outstanding. The barrier to
872
- * await before handing a result to something that must contain every edit.
805
+ * Resolves once nothing written through this seat is outstanding (immediately if it already is;
806
+ * before the seat has started it waits for the start). Rejects with the terminal reason if the
807
+ * seat ends while writes are outstanding or a write can no longer land, and with `'cleared'`
808
+ * after `clearOutbox()`. While a conflict is held it rejects at once with `conflict: <cause>`; a
809
+ * terminal reason wins. A write the relay refused rejects the calls pending when it is answered
810
+ * with `refused: <reason>`. The barrier to await before handing a result to something that must
811
+ * contain every edit.
873
812
  */
874
813
  whenAcked(): Promise<void>;
814
+ /**
815
+ * Discard every write not yet in the room, every conflict and every `unstored` entry, and end the
816
+ * seat: nothing more is sent, the status reads `'closed'`, and `whenAcked()` rejects with
817
+ * `'cleared'`. Called before the seat has started, it clears once it has; when the start fails it
818
+ * rejects with that reason, then and on every later call. After `close()` it rejects with
819
+ * `'closed'`. After an eject or an outdated ending the seat's journal is already closed, as at
820
+ * every ending, and a seat keeps nothing on storage: the call marks the seat cleared (`acked()`
821
+ * reads `false`, `whenAcked()` rejects with `'cleared'`) and resolves at once.
822
+ */
823
+ clearOutbox(): Promise<void>;
875
824
  /** Publish this seat's ephemeral presence payload (e.g. `{ name, kind: 'agent' }`). */
876
825
  setPresence(data: unknown): void;
877
826
  /**
@@ -886,6 +835,13 @@ type AgentSeat<T extends object> = {
886
835
  direct(cb: (msg: MeshDirect) => void): () => void;
887
836
  /** Authority surface over this seat's op-sync; see {@link SeatSync}. */
888
837
  readonly sync: SeatSync<T>;
838
+ /**
839
+ * Leave the room and destroy the seat's op engine. The handle is frozen from then on: `doc`
840
+ * still reads and writes locally, but nothing is sent, `acked()` and `whenAcked()` keep the
841
+ * answer they had at close, and `stableSnapshot()` is null. Closed before the seat has started,
842
+ * they answer once its journal has been read: with nothing written, `acked()` reads `true` and
843
+ * `whenAcked()` resolves; until then `acked()` is `false` and `whenAcked()` waits.
844
+ */
889
845
  close(): void;
890
846
  };
891
847
  /**
@@ -912,7 +868,7 @@ export declare function setAtPath(node: unknown, path: string | readonly PathSeg
912
868
  * activity feeds and model context. Values render as truncated JSON. Pair with a seat's
913
869
  * `changes` stream: narrating each batch's ops yields an append-only account of the room.
914
870
  */
915
- export declare function describeOp(op: StoreOp$1, writer: string): string;
871
+ export declare function describeOp(op: StoreOp, writer: string): string;
916
872
  type WebRtcMeshOptions = {
917
873
  readonly room: string;
918
874
  readonly writer: string;
@@ -950,8 +906,8 @@ type WebRtcMeshRef = {
950
906
  * Peer-to-peer mesh sync: the relay only signals
951
907
  * and tracks membership; envelopes flow over WebRTC data channels and converge via the
952
908
  * per-path register map. Catch-up is pairwise: on channel open both sides exchange
953
- * watermarks; a side whose state is strictly covered hydrates from the other's FULL
954
- * checkpoint (root + per-path register state + watermark), so supersession and precedence
909
+ * watermarks; a side whose state is covered (the other holds every envelope it holds)
910
+ * hydrates from the other's FULL checkpoint (root + per-path register state + watermark), so supersession and precedence
955
911
  * carry over intact: a late joiner is indistinguishable from a peer that saw every
956
912
  * envelope. Two peers that each hold envelopes the other lacks keep their convergent
957
913
  * go-forward guarantees but do not exchange the missed envelopes retroactively.
@@ -1024,4 +980,4 @@ type RtcPresenceRef<T> = {
1024
980
  * Values travel as JSON.
1025
981
  */
1026
982
  export declare function rtcPresence<T>(links: PeerLinks, opt: RtcPresenceOptions): RtcPresenceRef<T>;
1027
- export type { AgentSeat, AgentSeatOptions, DataChannelLike, MeshDirect, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerChannelSpec, PeerConnector, PeerLinks, PeerLinksOptions, PresenceFrame, RtcPresenceOptions, RtcPresenceRef, SeatChange, SeatEvent, SeatResync, SeatSync, SignalingPort, StableSnapshot, SyncHealth, SyncHealthStatus, WebRtcMeshOptions, WebRtcMeshRef };
983
+ export type { AgentSeat, AgentSeatOptions, DataChannelLike, DirectTransportOptions, MeshDirect, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerChannelSpec, PeerConnector, PeerLinks, PeerLinksOptions, PresenceFrame, RtcPresenceOptions, RtcPresenceRef, SeatChange, SeatEvent, SeatResync, SeatSync, SignalingPort, StableSnapshot, SyncHealth, SyncHealthStatus, UnstoredReason, UnstoredWrite, WebRtcMeshOptions, WebRtcMeshRef };