@mmstack/mesh 22.1.0 → 22.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,59 +1,23 @@
1
- import { inject, Injector, signal, computed, isDevMode, runInInjectionContext, DestroyRef } from '@angular/core';
1
+ import { createWatch } from '@angular/core/primitives/signals';
2
+ import { createConvergingApply, createStoreContext, store, opSync, forkStore, OP_PROTO_VERSION, registerResource } from '@mmstack/primitives';
2
3
  import { MESH_PROTO_VERSION, checkEnvelope } from '@mmstack/mesh-protocol';
3
- import { opSync, registerResource } from '@mmstack/primitives';
4
+ import { inject, Injector, signal, computed, isDevMode, runInInjectionContext, DestroyRef } from '@angular/core';
4
5
 
5
- // a versioned reject means "your build is behind" → prompt an update, not a dead socket
6
- const OUTDATED_REASONS = new Set([
7
- 'proto',
8
- 'policy-version',
9
- 'schema',
10
- ]);
11
6
  const RECONNECT_BASE_MS = 500;
12
- const OUTBOX_DEBOUNCE_MS = 300;
13
- /**
14
- * Replicates a signal store across clients through a relay room: local writes emit stamped
15
- * envelopes, remote envelopes fold in convergently, reconnects resume via delta or snapshot
16
- * with unacknowledged local writes rebased on top, and presence rides an ephemeral channel.
17
- * A synced store reads exactly like a local one — connection state surfaces only through
18
- * `status` and the transition scope.
19
- */
20
- function meshSync(source, opt) {
21
- const injector = opt.injector ?? inject(Injector);
22
- const status = signal('connecting', /* @ts-ignore */
23
- ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
24
- const lastReason = signal(undefined, /* @ts-ignore */
25
- ...(ngDevMode ? [{ debugName: "lastReason" }] : /* istanbul ignore next */ []));
26
- const lastSyncedAt = signal(undefined, /* @ts-ignore */
27
- ...(ngDevMode ? [{ debugName: "lastSyncedAt" }] : /* istanbul ignore next */ []));
28
- const peerMap = signal(new Map(), /* @ts-ignore */
29
- ...(ngDevMode ? [{ debugName: "peerMap" }] : /* istanbul ignore next */ []));
30
- const peers = computed(() => [...peerMap().values()], /* @ts-ignore */
31
- ...(ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []));
32
- const policyVersion = opt.policyVersion ?? 0;
33
- const health = computed(() => {
34
- const at = lastSyncedAt();
35
- switch (status()) {
36
- case 'live':
37
- return { status: 'live', lastSyncedAt: at };
38
- case 'ejected': {
39
- const reason = lastReason();
40
- return reason && OUTDATED_REASONS.has(reason)
41
- ? { status: 'outdated', reason, lastSyncedAt: at }
42
- : { status: 'ejected', reason, lastSyncedAt: at };
43
- }
44
- default: // connecting / reconnecting / closed — not reachable
45
- return { status: 'offline', lastSyncedAt: at };
46
- }
47
- }, /* @ts-ignore */
48
- ...(ngDevMode ? [{ debugName: "health" }] : /* istanbul ignore next */ []));
49
- // Created lazily: with a persisted outbox we must adopt the stored origin BEFORE minting anything
50
- let sync;
51
- let started = false;
52
- let unsubLocal = () => undefined;
7
+ function meshSession(opt) {
8
+ const { sync, hooks } = opt;
9
+ const schedule = opt.schedule ?? {
10
+ set: (fn, ms) => setTimeout(fn, ms),
11
+ clear: (handle) => clearTimeout(handle),
12
+ };
13
+ let status = 'connecting';
14
+ const ownOrigins = new Set([sync.origin]);
53
15
  const unacked = new Map();
54
- let highestAcked = 0;
16
+ const acked = new Map();
17
+ const unackedKey = (env) => `${env.origin} ${env.version}`;
55
18
  let lastSeq = 0;
56
- let epoch;
19
+ let instance;
20
+ let peers = new Map();
57
21
  let presenceData;
58
22
  let hasPresence = false;
59
23
  let transport = null;
@@ -61,91 +25,102 @@ function meshSync(source, opt) {
61
25
  let reconnectTimer;
62
26
  let unsubs = [];
63
27
  let closed = false;
64
- let persistTimer;
65
- // single-writer Web Lock (crossTab:'queue'): `release` frees it for the next tab once acquired;
66
- // `cancel` aborts a still-queued request if we tear down before the lock is ever granted.
67
- let releaseLock;
68
- let cancelLock;
69
- const doPersist = () => {
70
- if (!opt.outbox || !started)
71
- return;
72
- const payload = {
73
- origin: sync.origin,
74
- version: sync.watermark()[sync.origin] ?? 0,
75
- envs: [...unacked.values()],
76
- };
77
- void Promise.resolve(opt.outbox.store.set(opt.outbox.key, payload));
78
- };
79
- // coalesce outbox writes; `immediate` forces a synchronous-path write (first boot, teardown)
80
- const persistOutbox = (immediate = false) => {
81
- if (!opt.outbox)
82
- return;
83
- if (immediate) {
84
- if (persistTimer !== undefined)
85
- clearTimeout(persistTimer);
86
- persistTimer = undefined;
87
- doPersist();
88
- return;
89
- }
90
- if (persistTimer !== undefined)
91
- return;
92
- persistTimer = setTimeout(() => {
93
- persistTimer = undefined;
94
- doPersist();
95
- }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);
28
+ const setStatus = (next, reason) => {
29
+ status = next;
30
+ hooks.onStatus(next, reason);
96
31
  };
97
32
  const terminal = (state, reason) => {
33
+ if (closed)
34
+ return;
98
35
  closed = true;
99
- cancelLock?.(); // drop a still-queued lock request so we never steal it after teardown
100
- releaseLock?.(); // free a held lock for the next waiting tab
101
- cancelLock = releaseLock = undefined;
102
- if (reconnectTimer !== undefined)
103
- clearTimeout(reconnectTimer);
36
+ if (reconnectTimer !== undefined) {
37
+ schedule.clear(reconnectTimer);
38
+ reconnectTimer = undefined;
39
+ }
104
40
  for (const unsub of unsubs.splice(0))
105
41
  unsub();
106
42
  unsubLocal();
107
- persistOutbox(true); // save the still-unacked tail for the next boot before dropping it
43
+ hooks.onTerminal?.(state, reason); // unacked is still intact here — the persist window
108
44
  unacked.clear();
109
45
  transport?.close();
110
46
  transport = null;
111
- peerMap.set(new Map());
112
- lastReason.set(reason);
113
- status.set(state);
114
- if (reason !== undefined)
115
- opt.onEject?.(reason);
47
+ peers = new Map();
48
+ hooks.onPeers?.(peers);
49
+ setStatus(state, reason);
116
50
  };
117
51
  const sendEnv = (env) => {
118
52
  transport?.send({ t: 'env', room: opt.room, env });
119
53
  };
54
+ // Flushed in insertion order — emission order. An envelope only cites dots that existed
55
+ // in its store when it was emitted, so any cited own-dot is either already acked or sits
56
+ // EARLIER in this map; that holds across boots because the outbox persists and restores
57
+ // the tail in this same order. Sorting across origins (a multi-boot tail spans several)
58
+ // can send a citing envelope before its cited one — an honest writer ejected by a
59
+ // citation-verifying relay.
120
60
  const flushUnacked = () => {
121
- for (const env of [...unacked.values()].sort((a, b) => a.version - b.version)) {
61
+ for (const env of unacked.values())
122
62
  sendEnv(env);
63
+ };
64
+ const applyRemote = (env) => {
65
+ lastSeq = Math.max(lastSeq, env.seq);
66
+ hooks.onSynced?.();
67
+ if (opt.schemaVersion !== undefined &&
68
+ env.schemaVersion !== undefined &&
69
+ env.schemaVersion > opt.schemaVersion) {
70
+ terminal('ejected', 'schema');
71
+ return;
72
+ }
73
+ if (ownOrigins.has(env.origin)) {
74
+ unacked.delete(unackedKey(env));
75
+ acked.set(env.origin, Math.max(acked.get(env.origin) ?? 0, env.version));
76
+ hooks.onOutboxChange?.();
77
+ return;
123
78
  }
79
+ sync.receive(env);
80
+ hooks.onRemote?.({ seq: env.seq, writer: env.writer, ops: env.ops });
124
81
  };
125
82
  const handle = (msg) => {
126
83
  if (msg.room !== opt.room)
127
84
  return;
128
85
  switch (msg.t) {
129
86
  case 'welcome': {
130
- if (epoch !== undefined && msg.epoch !== epoch)
87
+ const instanceChanged = instance !== undefined && msg.instance !== instance;
88
+ if (instanceChanged)
131
89
  lastSeq = 0;
132
- epoch = msg.epoch;
133
- peerMap.set(new Map(msg.peers.map((p) => [p.origin, p])));
90
+ instance = msg.instance;
91
+ peers = new Map(msg.peers.map((p) => [p.origin, p]));
92
+ hooks.onPeers?.(peers);
93
+ const resync = msg.mode === 'snapshot' || instanceChanged;
134
94
  if (msg.mode === 'delta') {
135
95
  for (const env of msg.envs)
136
96
  applyRemote(env);
137
97
  }
138
98
  else if (msg.mode === 'snapshot') {
139
- sync.hydrate(msg.root, { [sync.origin]: highestAcked });
99
+ const conv = createConvergingApply({ policies: opt.policies });
100
+ conv.load(msg.registers);
101
+ const ownWm = {};
102
+ for (const o of ownOrigins)
103
+ ownWm[o] = acked.get(o) ?? 0;
104
+ sync.hydrate({
105
+ root: conv.materialize(),
106
+ registers: msg.registers,
107
+ wm: { ...msg.wm, ...ownWm },
108
+ }, [...unacked.values()]);
140
109
  lastSeq = msg.seq;
141
110
  }
142
111
  else if (msg.seq === 0 && lastSeq === 0) {
143
112
  sync.seed();
144
113
  }
114
+ // every branch can end terminal (schema eject in a delta env, a seed or rebase
115
+ // emission tripping the emit-side policy) — never revive to live
116
+ if (closed)
117
+ return;
145
118
  lastSeq = Math.max(lastSeq, msg.seq);
146
119
  attempts = 0;
147
- lastSyncedAt.set(Date.now());
148
- status.set('live');
120
+ hooks.onSynced?.();
121
+ if (resync)
122
+ hooks.onResync?.(lastSeq);
123
+ setStatus('live');
149
124
  flushUnacked();
150
125
  if (hasPresence)
151
126
  transport?.send({
@@ -159,12 +134,13 @@ function meshSync(source, opt) {
159
134
  applyRemote(msg.env);
160
135
  return;
161
136
  case 'presence': {
162
- const next = new Map(peerMap());
137
+ const next = new Map(peers);
163
138
  if (msg.gone)
164
139
  next.delete(msg.peer.origin);
165
140
  else
166
141
  next.set(msg.peer.origin, msg.peer);
167
- peerMap.set(next);
142
+ peers = next;
143
+ hooks.onPeers?.(peers);
168
144
  return;
169
145
  }
170
146
  case 'eject':
@@ -174,26 +150,11 @@ function meshSync(source, opt) {
174
150
  case 'reject':
175
151
  terminal('ejected', msg.reason);
176
152
  return;
153
+ case 'frontier':
154
+ sync.prune(msg.frontier);
155
+ return;
177
156
  }
178
157
  };
179
- const applyRemote = (env) => {
180
- lastSeq = Math.max(lastSeq, env.seq);
181
- lastSyncedAt.set(Date.now());
182
- // a migration to a shape newer than ours: stop applying + surface 'outdated' (never downgrade-interpret newer data)
183
- if (opt.schemaVersion !== undefined &&
184
- env.schemaVersion !== undefined &&
185
- env.schemaVersion > opt.schemaVersion) {
186
- terminal('ejected', 'schema');
187
- return;
188
- }
189
- if (env.origin === sync.origin) {
190
- unacked.delete(env.version);
191
- highestAcked = Math.max(highestAcked, env.version);
192
- persistOutbox();
193
- return;
194
- }
195
- sync.receive(env);
196
- };
197
158
  const connect = () => {
198
159
  if (closed)
199
160
  return;
@@ -207,9 +168,9 @@ function meshSync(source, opt) {
207
168
  if (closed || transport !== t)
208
169
  return;
209
170
  transport = null;
210
- status.set('reconnecting');
171
+ setStatus('reconnecting');
211
172
  const delay = Math.min(opt.reconnect?.maxDelayMs ?? 15_000, RECONNECT_BASE_MS * 2 ** attempts++);
212
- reconnectTimer = setTimeout(() => {
173
+ reconnectTimer = schedule.set(() => {
213
174
  reconnectTimer = undefined;
214
175
  connect();
215
176
  }, delay + Math.random() * 100);
@@ -220,29 +181,361 @@ function meshSync(source, opt) {
220
181
  room: opt.room,
221
182
  origin: sync.origin,
222
183
  proto: MESH_PROTO_VERSION,
223
- policyVersion,
184
+ policyVersion: opt.policyVersion,
224
185
  seq: lastSeq > 0 ? lastSeq : undefined,
225
186
  schemaVersion: opt.schemaVersion,
226
187
  });
227
188
  };
228
- const wireLocal = () => {
229
- unsubLocal = sync.subscribe((env) => {
230
- const violation = checkEnvelope(opt.policy, env, {
231
- ...opt.ctx,
232
- writer: opt.writer,
233
- });
234
- if (violation) {
235
- if (isDevMode()) {
236
- console.warn('[@mmstack/mesh] local write violates the room policy — not sent', violation);
237
- }
238
- return;
189
+ const unsubLocal = sync.subscribe((env) => {
190
+ const violation = checkEnvelope(opt.policy, env, { ...opt.ctx, writer: opt.writer }, opt.room);
191
+ if (violation) {
192
+ // same outcome the relay's own check would produce one hop later — the emit-side
193
+ // check is an optimization, never the enforcement
194
+ hooks.onLocalReject?.(violation);
195
+ terminal('ejected', violation.reason);
196
+ return;
197
+ }
198
+ ownOrigins.add(env.origin); // the fresh mint, or a restored-tail origin resending verbatim
199
+ unacked.set(unackedKey(env), env);
200
+ hooks.onOutboxChange?.();
201
+ if (status === 'live')
202
+ sendEnv(env);
203
+ });
204
+ return {
205
+ connect,
206
+ status: () => status,
207
+ lastSeq: () => lastSeq,
208
+ hasUnacked: () => unacked.size > 0,
209
+ unackedEnvs: () => [...unacked.values()],
210
+ peers: () => peers,
211
+ setPresence: (data) => {
212
+ presenceData = data;
213
+ hasPresence = true;
214
+ if (status === 'live') {
215
+ transport?.send({ t: 'presence', room: opt.room, data });
239
216
  }
240
- unacked.set(env.version, env);
241
- persistOutbox();
242
- if (status() === 'live')
243
- sendEnv(env);
217
+ },
218
+ close: () => terminal('closed'),
219
+ };
220
+ }
221
+
222
+ const microtaskDriver = () => (run) => {
223
+ let scheduled = false;
224
+ const watch = createWatch(() => run(), (w) => {
225
+ if (scheduled)
226
+ return;
227
+ scheduled = true;
228
+ queueMicrotask(() => {
229
+ scheduled = false;
230
+ w.run();
244
231
  });
232
+ }, false);
233
+ watch.notify();
234
+ return { destroy: () => watch.destroy() };
235
+ };
236
+ /**
237
+ * A headless mesh peer: the same replica and wire contract `meshSync` implements in the
238
+ * browser, without Angular's injector or any browser API — for agents, server-side bridges,
239
+ * and device writers joining a room as first-class, attributed participants. Each call is
240
+ * one identity with its own replica; run several seats in one process for several
241
+ * collaborators. Governance is the room's: the relay's policy applies to a seat exactly as
242
+ * to any human peer.
243
+ */
244
+ function agentSeat(initial, opt) {
245
+ const context = opt.context ?? createStoreContext();
246
+ const root = store(initial, context);
247
+ const doc = root;
248
+ const read = root;
249
+ const policyVersion = opt.policyVersion ?? 0;
250
+ // onReject fires synchronously inside receive(); the flag keeps a malformed envelope's
251
+ // ops (which did NOT apply) out of the change stream.
252
+ let rejected = false;
253
+ const sync = opSync(root, {
254
+ writer: opt.writer,
255
+ policies: opt.policies,
256
+ policyVersion,
257
+ driver: microtaskDriver(),
258
+ onReject: (_env, reason) => {
259
+ rejected = true;
260
+ console.warn(`[@mmstack/mesh] agent seat dropped a malformed envelope (${reason})`);
261
+ },
262
+ });
263
+ const listeners = new Set();
264
+ const emit = (event) => {
265
+ for (const cb of [...listeners])
266
+ cb(event);
245
267
  };
268
+ let welcomed = false;
269
+ let diverged = false;
270
+ const session = meshSession({
271
+ room: opt.room,
272
+ writer: opt.writer,
273
+ transport: opt.transport,
274
+ sync,
275
+ policies: opt.policies,
276
+ policy: opt.policy,
277
+ ctx: opt.ctx,
278
+ policyVersion,
279
+ schemaVersion: opt.schemaVersion,
280
+ reconnect: opt.reconnect,
281
+ hooks: {
282
+ onStatus: (s, reason) => {
283
+ if (s === 'live')
284
+ welcomed = true;
285
+ if (s === 'ejected' && reason !== undefined)
286
+ opt.onEject?.(reason);
287
+ },
288
+ onRemote: (batch) => {
289
+ if (rejected) {
290
+ rejected = false;
291
+ return;
292
+ }
293
+ emit({ kind: 'change', ...batch });
294
+ },
295
+ onResync: (seq) => emit({ kind: 'resync', seq }),
296
+ onLocalReject: (violation) => {
297
+ diverged = true; // the write stays in the replica but will never reach the room
298
+ console.warn('[@mmstack/mesh] agent seat write violates the room policy — not sent', violation);
299
+ },
300
+ onTerminal: () => {
301
+ if (session.hasUnacked())
302
+ diverged = true;
303
+ },
304
+ },
305
+ });
306
+ session.connect();
307
+ return {
308
+ doc,
309
+ status: () => session.status(),
310
+ peers: () => [...session.peers().values()],
311
+ snapshot: () => read(),
312
+ stableSnapshot: () => {
313
+ sync.flush(); // a write made this tick must count as pending, not linger unstamped
314
+ if (!welcomed || diverged || session.hasUnacked())
315
+ return null;
316
+ return { seq: session.lastSeq(), doc: read() };
317
+ },
318
+ write: (fn) => {
319
+ fn();
320
+ sync.flush();
321
+ },
322
+ setAtPath: (path, value) => {
323
+ setAtPath(doc, path, value);
324
+ sync.flush();
325
+ },
326
+ changes: (cb) => {
327
+ listeners.add(cb);
328
+ return () => listeners.delete(cb);
329
+ },
330
+ fork: (forkOpt) => {
331
+ const f = forkStore(doc, forkOpt);
332
+ let frontier = sync.captureFrontier();
333
+ const recapture = () => {
334
+ frontier = sync.captureFrontier();
335
+ };
336
+ return {
337
+ store: f.store,
338
+ ops: f.ops,
339
+ commit: () => {
340
+ sync.commitScope(frontier, () => f.commit());
341
+ sync.flush();
342
+ },
343
+ discard: () => {
344
+ f.discard();
345
+ recapture();
346
+ },
347
+ rebase: recapture,
348
+ };
349
+ },
350
+ setPresence: (data) => session.setPresence(data),
351
+ close: () => {
352
+ session.close();
353
+ sync.destroy();
354
+ },
355
+ };
356
+ }
357
+ const parsePath = (path) => typeof path === 'string' ? path.split('.').filter((s) => s !== '') : path;
358
+ // resolve a string segment against an array ('0' → 0) so dot-paths address list items
359
+ const resolveKey = (current, seg) => Array.isArray(current) && typeof seg === 'string' && /^\d+$/.test(seg)
360
+ ? Number(seg)
361
+ : seg;
362
+ function withPathSet(current, path, value) {
363
+ if (path.length === 0)
364
+ return value;
365
+ const [head, ...rest] = path;
366
+ if (Array.isArray(current)) {
367
+ const idx = typeof head === 'number' ? head : Number(head);
368
+ const copy = [...current];
369
+ copy[idx] = withPathSet(current[idx], rest, value);
370
+ return copy;
371
+ }
372
+ const base = current !== null && typeof current === 'object'
373
+ ? current
374
+ : {};
375
+ return { ...base, [head]: withPathSet(base[head], rest, value) };
376
+ }
377
+ /**
378
+ * Applies `value` at a path on a signal-store node — the write shape a tool-calling model
379
+ * naturally produces (`'plan.endDate'`, `'tasks.t1.done'`). Walks child signals as far as
380
+ * the path exists in the current value and finishes with one immutable set on the deepest
381
+ * real node, which also covers paths that do not exist yet (a fresh record key creates it).
382
+ * Works on a seat's `doc` and on a fork's `store` alike; on a seat, prefer
383
+ * `seat.setAtPath`, which also emits immediately.
384
+ */
385
+ function setAtPath(node, path, value) {
386
+ const segs = parsePath(path);
387
+ let cursor = node;
388
+ let walked = 0;
389
+ for (const seg of segs) {
390
+ const current = cursor();
391
+ if (current === null || typeof current !== 'object')
392
+ break;
393
+ const key = resolveKey(current, seg);
394
+ if (!Object.hasOwn(current, key))
395
+ break;
396
+ const child = cursor[key];
397
+ if (typeof child !== 'function')
398
+ break;
399
+ cursor = child;
400
+ walked++;
401
+ }
402
+ const rest = segs.slice(walked);
403
+ if (rest.length === 0) {
404
+ cursor.set(value);
405
+ return;
406
+ }
407
+ cursor.set(withPathSet(cursor(), rest, value));
408
+ }
409
+ const MAX_VALUE_CHARS = 120;
410
+ const printable = (value) => {
411
+ const json = JSON.stringify(value);
412
+ if (json === undefined)
413
+ return String(value);
414
+ return json.length > MAX_VALUE_CHARS
415
+ ? `${json.slice(0, MAX_VALUE_CHARS - 1)}…`
416
+ : json;
417
+ };
418
+ /**
419
+ * One store op as a plain-English line ("mira set plan.endDate to \"2026-10-11\""), for
420
+ * activity feeds and model context. Values render as truncated JSON. Pair with a seat's
421
+ * `changes` stream: narrating each batch's ops yields an append-only account of the room.
422
+ */
423
+ function describeOp(op, writer) {
424
+ const at = op.path.length === 0 ? 'the document root' : op.path.join('.');
425
+ switch (op.kind) {
426
+ case 'set':
427
+ return `${writer} set ${at} to ${printable(op.next)}`;
428
+ case 'delete':
429
+ return `${writer} removed ${at}`;
430
+ case 'clear':
431
+ return `${writer} cleared ${at}`;
432
+ }
433
+ }
434
+
435
+ // a versioned reject means "your build is behind" → prompt an update, not a dead socket
436
+ const OUTDATED_REASONS = new Set([
437
+ 'proto',
438
+ 'policy-version',
439
+ 'schema',
440
+ ]);
441
+ const OUTBOX_DEBOUNCE_MS = 300;
442
+ /**
443
+ * Replicates a signal store across clients through a relay room: local writes emit stamped
444
+ * envelopes, remote envelopes fold in convergently, reconnects resume via delta or snapshot
445
+ * with unacknowledged local writes rebased on top, and presence rides an ephemeral channel.
446
+ * A synced store reads exactly like a local one — connection state surfaces only through
447
+ * `status` and the transition scope.
448
+ */
449
+ function meshSync(source, opt) {
450
+ const injector = opt.injector ?? inject(Injector);
451
+ const status = signal('connecting', /* @ts-ignore */
452
+ ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
453
+ const lastReason = signal(undefined, /* @ts-ignore */
454
+ ...(ngDevMode ? [{ debugName: "lastReason" }] : /* istanbul ignore next */ []));
455
+ const lastSyncedAt = signal(undefined, /* @ts-ignore */
456
+ ...(ngDevMode ? [{ debugName: "lastSyncedAt" }] : /* istanbul ignore next */ []));
457
+ const droppedOffline = signal(0, /* @ts-ignore */
458
+ ...(ngDevMode ? [{ debugName: "droppedOffline" }] : /* istanbul ignore next */ []));
459
+ const droppedInvalid = signal(0, /* @ts-ignore */
460
+ ...(ngDevMode ? [{ debugName: "droppedInvalid" }] : /* istanbul ignore next */ []));
461
+ const peerMap = signal(new Map(), /* @ts-ignore */
462
+ ...(ngDevMode ? [{ debugName: "peerMap" }] : /* istanbul ignore next */ []));
463
+ const peers = computed(() => [...peerMap().values()], /* @ts-ignore */
464
+ ...(ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []));
465
+ const policyVersion = opt.policyVersion ?? 0;
466
+ const health = computed(() => {
467
+ const at = lastSyncedAt();
468
+ const dropped = droppedOffline();
469
+ const invalid = droppedInvalid();
470
+ const extra = {
471
+ ...(dropped > 0 ? { droppedOfflineWrites: dropped } : undefined),
472
+ ...(invalid > 0 ? { droppedInvalidEnvelopes: invalid } : undefined),
473
+ };
474
+ switch (status()) {
475
+ case 'live':
476
+ return { status: 'live', lastSyncedAt: at, ...extra };
477
+ case 'ejected': {
478
+ const reason = lastReason();
479
+ return reason && OUTDATED_REASONS.has(reason)
480
+ ? { status: 'outdated', reason, lastSyncedAt: at, ...extra }
481
+ : { status: 'ejected', reason, lastSyncedAt: at, ...extra };
482
+ }
483
+ default: // connecting / reconnecting / closed — not reachable
484
+ return { status: 'offline', lastSyncedAt: at, ...extra };
485
+ }
486
+ }, /* @ts-ignore */
487
+ ...(ngDevMode ? [{ debugName: "health" }] : /* istanbul ignore next */ []));
488
+ // Created lazily: with a persisted outbox we must adopt the stored origin BEFORE minting anything
489
+ let sync;
490
+ let session;
491
+ let started = false;
492
+ let closed = false;
493
+ let pendingPresence;
494
+ let persistTimer;
495
+ let releaseLock;
496
+ let cancelLock;
497
+ const doPersist = () => {
498
+ if (closed || !opt.outbox || !started || !session)
499
+ return;
500
+ const payload = {
501
+ origin: sync.origin,
502
+ version: sync.watermark()[sync.origin] ?? 0,
503
+ envs: session.unackedEnvs(),
504
+ };
505
+ void Promise.resolve(opt.outbox.store.set(opt.outbox.key, payload));
506
+ };
507
+ // coalesce outbox writes; `immediate` forces a synchronous-path write (first boot, teardown)
508
+ const persistOutbox = (immediate = false) => {
509
+ if (!opt.outbox)
510
+ return;
511
+ if (immediate) {
512
+ if (persistTimer !== undefined)
513
+ clearTimeout(persistTimer);
514
+ persistTimer = undefined;
515
+ doPersist();
516
+ return;
517
+ }
518
+ if (persistTimer !== undefined)
519
+ return;
520
+ persistTimer = setTimeout(() => {
521
+ persistTimer = undefined;
522
+ doPersist();
523
+ }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);
524
+ };
525
+ const dropLocks = () => {
526
+ cancelLock?.(); // drop a still-queued lock request so we never steal it after teardown
527
+ releaseLock?.(); // free a held lock for the next waiting tab
528
+ cancelLock = releaseLock = undefined;
529
+ };
530
+ // Only a tail this boot could actually get admitted is worth resending: recorded under
531
+ // this writer, on the current proto and policyVersion pins (the relay rejects a stale pin
532
+ // per envelope, so restoring one would eject the boot, persist the tail intact, and brick
533
+ // every boot after). Anything else drops loudly instead.
534
+ const restorable = (env) => env.proto === OP_PROTO_VERSION &&
535
+ env.writer === opt.writer &&
536
+ env.policyVersion === policyVersion &&
537
+ env.ops.every((op) => Array.isArray(op.cites) &&
538
+ typeof op.epoch === 'number');
246
539
  const initCore = (restore) => {
247
540
  if (closed)
248
541
  return;
@@ -251,15 +544,67 @@ function meshSync(source, opt) {
251
544
  policies: opt.policies,
252
545
  policyVersion,
253
546
  injector,
254
- origin: restore?.origin,
547
+ onReject: (_env, reason) => {
548
+ droppedInvalid.update((n) => n + 1);
549
+ if (isDevMode()) {
550
+ console.warn(`[@mmstack/mesh] dropped malformed envelope from a peer (${reason})`);
551
+ }
552
+ },
255
553
  });
256
554
  started = true;
257
- wireLocal();
555
+ session = meshSession({
556
+ room: opt.room,
557
+ writer: opt.writer,
558
+ transport: opt.transport,
559
+ sync,
560
+ policies: opt.policies,
561
+ policy: opt.policy,
562
+ ctx: opt.ctx,
563
+ policyVersion,
564
+ schemaVersion: opt.schemaVersion,
565
+ reconnect: opt.reconnect,
566
+ hooks: {
567
+ onStatus: (s, reason) => {
568
+ if (s === 'ejected' || s === 'closed') {
569
+ closed = true;
570
+ lastReason.set(reason);
571
+ }
572
+ status.set(s);
573
+ if ((s === 'ejected' || s === 'closed') && reason !== undefined) {
574
+ opt.onEject?.(reason);
575
+ }
576
+ },
577
+ onSynced: () => lastSyncedAt.set(Date.now()),
578
+ onPeers: (map) => peerMap.set(map),
579
+ onOutboxChange: () => persistOutbox(),
580
+ onTerminal: () => {
581
+ dropLocks();
582
+ persistOutbox(true); // save the still-unacked tail for the next boot before dropping it
583
+ },
584
+ onLocalReject: (violation) => {
585
+ if (isDevMode()) {
586
+ console.warn('[@mmstack/mesh] local write violates the room policy — not sent', violation);
587
+ }
588
+ },
589
+ },
590
+ });
258
591
  if (restore && (restore.envs.length > 0 || restore.version > 0)) {
259
- sync.restore(restore.envs, restore.version); // → subscribe repopulates `unacked` for resend
592
+ const kept = restore.envs.filter(restorable);
593
+ const dropped = restore.envs.length - kept.length;
594
+ if (dropped > 0) {
595
+ droppedOffline.set(dropped);
596
+ if (isDevMode()) {
597
+ console.warn(`[@mmstack/mesh] dropped ${dropped} persisted offline write(s) that cannot be resent: recorded under a different writer, or from an older protocol version (citations are never fabricated)`);
598
+ }
599
+ }
600
+ sync.restore(kept, restore.version); // → the session's subscribe repopulates its unacked tail for resend
260
601
  }
261
- persistOutbox(true); // pin the (possibly freshly minted) origin so later boots reuse it
262
- connect();
602
+ persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe
603
+ if (pendingPresence) {
604
+ session.setPresence(pendingPresence.data);
605
+ pendingPresence = undefined;
606
+ }
607
+ session.connect();
263
608
  };
264
609
  if (opt.register) {
265
610
  const connection = {
@@ -278,13 +623,20 @@ function meshSync(source, opt) {
278
623
  };
279
624
  runInInjectionContext(injector, () => registerResource(connection, { suspends: opt.register === 'suspend' }));
280
625
  }
281
- injector.get(DestroyRef).onDestroy(() => {
282
- if (!closed)
283
- terminal('closed');
284
- unsubLocal();
626
+ const teardown = () => {
627
+ if (session) {
628
+ session.close(); // no-op if already terminal; onTerminal handled locks + persist
629
+ }
630
+ else if (!closed) {
631
+ // closed before the (async) boot ever created the session
632
+ closed = true;
633
+ dropLocks();
634
+ status.set('closed');
635
+ }
285
636
  if (started)
286
637
  sync.destroy();
287
- });
638
+ };
639
+ injector.get(DestroyRef).onDestroy(teardown);
288
640
  // Load the persisted outbox, then boot with the adopted origin. A fresh/unreadable slot boots clean.
289
641
  const bootFromDisk = async () => {
290
642
  if (closed || !opt.outbox)
@@ -312,9 +664,6 @@ function meshSync(source, opt) {
312
664
  void bootFromDisk(); // no single-writer lock — the app coordinates ownership
313
665
  }
314
666
  else {
315
- // crossTab:'queue' — hold an exclusive Web Lock on the key for this tab's lifetime, so a
316
- // second tab sharing the key WAITS (stays 'connecting') instead of restoring the same origin
317
- // and colliding on version mints. The lock auto-releases if the tab crashes.
318
667
  const locks = globalThis.navigator?.locks;
319
668
  if (!locks) {
320
669
  if (isDevMode()) {
@@ -345,9 +694,6 @@ function meshSync(source, opt) {
345
694
  }
346
695
  }
347
696
  };
348
- // Assemble the local base first (worker hydration, disk snapshot), THEN connect, so the room
349
- // welcome rebases pending onto a populated store instead of racing it. A rejection is treated as
350
- // ready so a failed base load never wedges the connection.
351
697
  if (opt.whenReady) {
352
698
  void Promise.resolve()
353
699
  .then(() => opt.whenReady?.())
@@ -361,19 +707,29 @@ function meshSync(source, opt) {
361
707
  health,
362
708
  peers,
363
709
  setPresence: (data) => {
364
- presenceData = data;
365
- hasPresence = true;
366
- if (status() === 'live') {
367
- transport?.send({ t: 'presence', room: opt.room, data });
368
- }
710
+ if (session)
711
+ session.setPresence(data);
712
+ else
713
+ pendingPresence = { data };
369
714
  },
370
- close: () => {
371
- if (!closed)
372
- terminal('closed');
373
- unsubLocal();
374
- if (started)
375
- sync.destroy();
715
+ fork: (forkOpt) => {
716
+ const f = forkStore(source, forkOpt);
717
+ let frontier = started ? sync.captureFrontier() : { seq: 0 };
718
+ const recapture = () => {
719
+ frontier = started ? sync.captureFrontier() : { seq: 0 };
720
+ };
721
+ return {
722
+ store: f.store,
723
+ ops: f.ops,
724
+ commit: () => started ? sync.commitScope(frontier, () => f.commit()) : f.commit(),
725
+ discard: () => {
726
+ f.discard();
727
+ recapture();
728
+ },
729
+ rebase: recapture,
730
+ };
376
731
  },
732
+ close: teardown,
377
733
  };
378
734
  }
379
735
 
@@ -573,9 +929,11 @@ function rtcPeerConnector(config) {
573
929
  * Peer-to-peer mesh sync: the relay only signals
574
930
  * and tracks membership; envelopes flow over WebRTC data channels and converge via the
575
931
  * per-path register map. Catch-up is pairwise: on channel open both sides exchange
576
- * watermarks; a side whose state is strictly covered hydrates from the other. Two peers that
577
- * diverged while BOTH held state keep their convergent go-forward guarantees but do not
578
- * retroactively merge history (same contract as the tab rung).
932
+ * watermarks; a side whose state is strictly covered hydrates from the other's FULL
933
+ * checkpoint (root + per-path register state + watermark), so supersession and precedence
934
+ * carry over intact: a late joiner is indistinguishable from a peer that saw every
935
+ * envelope. Two peers that each hold envelopes the other lacks keep their convergent
936
+ * go-forward guarantees but do not exchange the missed envelopes retroactively.
579
937
  */
580
938
  function webRtcMesh(source, opt) {
581
939
  const injector = opt.injector ?? inject(Injector);
@@ -653,12 +1011,12 @@ function webRtcMesh(source, opt) {
653
1011
  if (covered(snap.wm, msg.wm))
654
1012
  sendTo(peer, { t: 'uptodate' });
655
1013
  else
656
- sendTo(peer, { t: 'state', root: snap.root, wm: snap.wm });
1014
+ sendTo(peer, { t: 'state', state: snap });
657
1015
  return;
658
1016
  }
659
1017
  case 'state': {
660
- if (covered(sync.watermark(), msg.wm)) {
661
- sync.hydrate(msg.root, msg.wm);
1018
+ if (covered(sync.watermark(), msg.state.wm)) {
1019
+ sync.hydrate(msg.state);
662
1020
  }
663
1021
  return;
664
1022
  }
@@ -746,5 +1104,5 @@ function webRtcMesh(source, opt) {
746
1104
  * Generated bundle index. Do not edit.
747
1105
  */
748
1106
 
749
- export { directTransport, meshSync, rtcPeerConnector, webRtcMesh, webSocketTransport };
1107
+ export { agentSeat, describeOp, directTransport, meshSync, rtcPeerConnector, setAtPath, webRtcMesh, webSocketTransport };
750
1108
  //# sourceMappingURL=mmstack-mesh.mjs.map