@johnhenry/browsermesh-apps 0.2.0 → 0.4.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.
Files changed (50) hide show
  1. package/README.md +232 -1
  2. package/package.json +7 -3
  3. package/src/agent-runtime.mjs +342 -0
  4. package/src/chunk-replication.mjs +751 -0
  5. package/src/cloud-storage-backend.mjs +932 -0
  6. package/src/cloud-storage.mjs +859 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/grant-log.mjs +840 -0
  9. package/src/index.mjs +34 -2
  10. package/src/key-distribution.mjs +525 -0
  11. package/src/manifest-sync.mjs +363 -0
  12. package/src/mesh-agent-swarm.mjs +376 -0
  13. package/src/mesh-bootstrap.mjs +1131 -12
  14. package/src/mesh-compute.mjs +397 -0
  15. package/src/mesh-dht.mjs +182 -0
  16. package/src/mesh-fetch.mjs +246 -0
  17. package/src/mesh-hardening.mjs +226 -0
  18. package/src/mesh-health.mjs +282 -0
  19. package/src/mesh-keepalive.mjs +353 -0
  20. package/src/mesh-kv.mjs +673 -0
  21. package/src/mesh-orchestrator-tools.mjs +251 -0
  22. package/src/mesh-orchestrator.mjs +343 -0
  23. package/src/mesh-rpc.mjs +300 -0
  24. package/src/mesh-service.mjs +403 -0
  25. package/src/mesh-swarm.mjs +677 -0
  26. package/src/mesh-timestamp.mjs +265 -0
  27. package/src/mesh-torrent.mjs +683 -0
  28. package/src/mesh-verification.mjs +367 -0
  29. package/src/mesh-websocket.mjs +722 -0
  30. package/src/observability-bridge.mjs +453 -0
  31. package/src/orchestrator.mjs +18 -5
  32. package/src/peer-agent-swarm.mjs +12 -1
  33. package/src/peer-chat.mjs +230 -61
  34. package/src/peer-compute.mjs +66 -3
  35. package/src/peer-escrow.mjs +350 -1
  36. package/src/peer-files.mjs +362 -168
  37. package/src/peer-ipfs.mjs +205 -10
  38. package/src/peer-node.mjs +33 -2
  39. package/src/peer-routing.mjs +369 -5
  40. package/src/peer-terminal.mjs +400 -130
  41. package/src/serverless-executor-andbox.mjs +136 -0
  42. package/src/serverless-fetch.mjs +70 -0
  43. package/src/serverless-functions.mjs +67 -0
  44. package/src/serverless-peer-select.mjs +69 -0
  45. package/src/serverless-proxy.mjs +127 -0
  46. package/src/serverless-router.mjs +115 -0
  47. package/src/serverless-sites.mjs +116 -0
  48. package/src/serverless-static.mjs +202 -0
  49. package/src/serverless-wire.mjs +87 -0
  50. package/src/peer-session.mjs +0 -937
@@ -0,0 +1,453 @@
1
+ /**
2
+ * observability-bridge.mjs -- Phase 2 of the mesh-KV-and-observability plan
3
+ * (`mesh-kv-and-observability.md`): the adapter that finally gives
4
+ * `visualizations.mjs` (903 lines, real, tested, previously dormant -- see
5
+ * that file's own module doc comment) a genuine data source, by subscribing
6
+ * to Phase 1's `ctx.emit()` observability convention (`mesh-service.mjs`)
7
+ * and a real `PeerNode`'s own connect/disconnect events (`peer-node.mjs`).
8
+ *
9
+ * This file is intentionally NOT a rewrite of `visualizations.mjs` (per the
10
+ * plan's own "Design decisions" section: "the observability bridge is new
11
+ * code, not a `visualizations.mjs` rewrite") -- `TopologySnapshot`,
12
+ * `TrustHeatmap`, and `VisualizationExporter` are used exactly as they
13
+ * already exist. It is also NOT a `MeshService` itself: it consumes events
14
+ * from already-attached services and from a `PeerNode`, it doesn't attach
15
+ * anything of its own to the mesh for messaging purposes.
16
+ *
17
+ * ---------------------------------------------------------------------------
18
+ * TWO INPUT STREAMS, kept deliberately separate (mirroring the plan's own
19
+ * framing: "peer connect/disconnect -> TopologySnapshot, a couple of the
20
+ * most illustrative service events -> TrustHeatmap/edge weight"):
21
+ *
22
+ * 1. `PeerNode`'s own `'peer:connect'`/`'peer:disconnect'` events
23
+ * (`peer-node.mjs`'s `on()`/`off()`, backed by `PeerRegistry`'s
24
+ * `onPeerConnect()`/`onPeerDisconnect()`) -- these are TRANSPORT-LEVEL
25
+ * session events, entirely independent of which `MeshService`s (if
26
+ * any) happen to be attached. `createObservabilityBridge()` always
27
+ * wires these the moment it's constructed (no opt-in needed): every
28
+ * `PeerNode` has them, so there is nothing to scope here.
29
+ *
30
+ * 2. Per-service `attachService()` handle events (`handle.on()`), opted
31
+ * into explicitly per handle via `bridge.observe(handle)` -- the
32
+ * caller decides which attached services' events this bridge should
33
+ * see, this file never reaches into a node's internals to discover
34
+ * services on its own (matching the plan's "the caller of your
35
+ * adapter needs to pass in the handles it wants observed, don't
36
+ * hardcode which services" instruction... with one caveat: WHICH of a
37
+ * given service's OWN events get wired, once its handle is passed to
38
+ * `observe()`, is fixed by this file -- see "Curated events" below).
39
+ *
40
+ * ---------------------------------------------------------------------------
41
+ * TopologySnapshot HAS NO `addNode()`/`addEdge()`/`removeNode()` METHODS
42
+ * (only `TrustGraphLayout` does) -- checked directly against
43
+ * `visualizations.mjs` before writing this file. `TopologySnapshot.nodes`/
44
+ * `.links` are plain, non-frozen, publicly-assigned arrays (not private
45
+ * fields), so this bridge mutates them directly via small
46
+ * upsert/remove helpers (`upsertNode()`/`upsertLink()`/`removeLink()`
47
+ * below) that reproduce the "add if missing, patch if present" semantics
48
+ * the task description asked for, using the surface `TopologySnapshot`
49
+ * actually exposes rather than inventing methods on that class (which
50
+ * would violate the plan's "not a `visualizations.mjs` rewrite" decision).
51
+ *
52
+ * DISCONNECT REMOVES THE EDGE, NOT THE NODE (a deliberate reading of
53
+ * "removal", stated explicitly): when a peer disconnects, the LINK between
54
+ * the local node and that peer is removed (it genuinely no longer exists),
55
+ * but the peer's NODE is kept, with `status` updated to `'disconnected'`.
56
+ * Deleting the node entirely on every disconnect would (a) orphan any
57
+ * `TrustHeatmap` entry already recorded for that peer via a grant-log event
58
+ * (trust from a grant survives a transport blip -- that's the whole point
59
+ * of Phase D's replicated GrantLog outliving any one session), and (b)
60
+ * make `TopologyDiff.compute()` across a disconnect/reconnect blip report a
61
+ * node removal+re-add instead of a status change, which is a strictly
62
+ * less useful signal for a dashboard. A caller that genuinely wants
63
+ * fully-gone peers pruned from the topology can do so itself against
64
+ * `bridge.snapshot.nodes` -- this file does not make that call for them.
65
+ *
66
+ * ---------------------------------------------------------------------------
67
+ * CURATED SERVICE EVENTS -- per the plan's explicit instruction ("don't try
68
+ * to wire every single event from every service; pick a few that tell a
69
+ * real story... Document exactly which events you chose to wire and why,
70
+ * and which you deliberately left out"):
71
+ *
72
+ * `grant-log:*` (any handle whose `.name` starts with `'grant-log:'`):
73
+ * - WIRED: `grant-log:grant-applied` -- bumps `TrustHeatmap`'s
74
+ * `(localPodId, pubKey)` trust value up by `TRUST_STEP` per newly
75
+ * effective scope (capped at 1). This is the plan's own named example
76
+ * ("grant-log:grant-applied feeding TrustHeatmap's trust value for
77
+ * that peer").
78
+ * - WIRED: `grant-log:revoke-applied` -- the natural complement, moves
79
+ * trust back down by the same step per scope that stopped being
80
+ * effective (capped at 0). Left out would make the heatmap only ever
81
+ * climb, never reflecting an actual revoke -- a materially misleading
82
+ * "trust" signal for a dashboard to show.
83
+ * - LEFT OUT: `grant-log:admin-changed`. It fires ALONGSIDE
84
+ * `grant-applied`/`revoke-applied` specifically when the changed scope
85
+ * is the admin scope (see `grant-log.mjs`'s own doc comment) -- wiring
86
+ * it too would double-count the exact same transition into the trust
87
+ * heatmap a second time. A future revision that wants to visually
88
+ * distinguish "admin" trust from "ordinary capability" trust should add
89
+ * a SEPARATE heatmap/series for it, not fold it into this one.
90
+ *
91
+ * `chunk-replication:*` (any handle whose `.name` starts with
92
+ * `'chunk-replication:'`):
93
+ * - WIRED: `chunk-replication:chunk-replicated` -- for each peer in
94
+ * `replicatedTo`, upserts an edge from the local node to that peer and
95
+ * increments an `activity` counter on it (a simple, monotonic "how much
96
+ * replication traffic has flowed on this edge" indicator -- the plan's
97
+ * own named example, "chunk-replication:chunk-replicated updating an
98
+ * edge weight/activity indicator").
99
+ * - LEFT OUT: `chunk-replication:read-repair` (a lazy-pull success --
100
+ * topologically it's the same "bytes moved between these two peers"
101
+ * story as `chunk-replicated`, and folding both into the same
102
+ * `activity` counter would conflate eager-push health with read-repair
103
+ * frequency, two different operational signals; a future revision
104
+ * wanting BOTH should track them as separate edge fields, not overload
105
+ * one), `chunk-replication:push-rejected` and
106
+ * `chunk-replication:fetch-exhausted` (both failure/security-relevant
107
+ * events, not topology state -- nothing about the mesh's shape changed
108
+ * because a push was rejected or a fetch was exhausted; these belong on
109
+ * a security/error dashboard, not a topology map).
110
+ *
111
+ * `mesh-websocket` (a handle whose `.name === 'mesh-websocket'`, i.e. only
112
+ * the ACCEPTING side's `createMeshWebSocketService()` handle -- see that
113
+ * file's own doc comment: only that side has a `ctx` to emit through at
114
+ * all):
115
+ * - WIRED: `mesh-websocket:connection-opened` -- upserts a node + edge for
116
+ * the connecting peer. `mesh-websocket:connection-closed` -- removes
117
+ * that edge (mirrors the disconnect handling above: the connection
118
+ * genuinely stopped existing). Together these are the plan's own named
119
+ * example ("mesh-websocket:connection-opened/connection-closed
120
+ * updating TopologySnapshot edges").
121
+ * - LEFT OUT: `mesh-websocket:connection-rejected` -- no session was ever
122
+ * established, so there is no edge to represent; this is a security/
123
+ * policy event (an `onConnection` hook said no), same reasoning as the
124
+ * chunk-replication failure events above.
125
+ *
126
+ * `mesh-kv:` (any handle whose `.name` starts with `'mesh-kv:'`, i.e.
127
+ * `createMeshKvService()`'s own low-level handle -- see `mesh-kv.mjs`'s
128
+ * module doc comment for the full event vocabulary. Phase 3 shipped after
129
+ * this file, so this bucket is a Phase 4 addition to the same curation
130
+ * exercise, not part of the original Phase 2 pass):
131
+ * - WIRED: `mesh-kv:watching`/`mesh-kv:unwatching` -- the store-level
132
+ * analogue of `mesh-websocket`'s open/close pair above: `watching`
133
+ * upserts a node + edge FROM the local node TO the watched peer
134
+ * (`status: 'watching'`, this store's `storeId` recorded on the edge);
135
+ * `unwatching` removes that edge. A `MeshKv.grant()` call always
136
+ * triggers a `watch()` immediately after applying the grant (see
137
+ * `mesh-kv.mjs`), so in practice this is the topology-level trace of
138
+ * "who currently has live access to this store."
139
+ * - WIRED: `mesh-kv:entry-set`/`mesh-kv:entry-deleted` -- only when
140
+ * `data.from !== ` this bridge's own `localId()` (i.e. only for an
141
+ * ACCEPTED REMOTE merge, not a local write): upserts an edge FROM the
142
+ * writing peer (`from`) TO the local node and increments its `activity`
143
+ * counter by 1, the same "how much traffic flowed on this edge"
144
+ * semantic `chunk-replication:chunk-replicated` uses above. A LOCAL
145
+ * `set()`/`delete()` (`from === localId()`) is deliberately NOT wired to
146
+ * an edge: the event payload carries no counterpart peer id for a local
147
+ * write (it could be broadcast to zero, one, or many watchers), so there
148
+ * is no single edge a local write could unambiguously update -- a
149
+ * caller that wants to see the LOCAL side of that same activity can read
150
+ * it directly off `mesh-kv:entry-set`/`entry-deleted` itself (this
151
+ * bridge does not need to be the only consumer of a service's events).
152
+ * - LEFT OUT: `mesh-kv:write-rejected` -- a security-relevant rejection,
153
+ * not a topology-state change (nothing about the mesh's shape or an
154
+ * edge's activity actually changed because a write was refused), same
155
+ * reasoning as `chunk-replication:push-rejected`/
156
+ * `mesh-websocket:connection-rejected` above.
157
+ *
158
+ * A handle whose `.name` doesn't match any of the four patterns above is
159
+ * accepted by `observe()` without throwing (a caller passing in every
160
+ * attached service's handle indiscriminately shouldn't have to filter
161
+ * first) but nothing is wired for it -- `onLog` (if supplied) is told via
162
+ * `observability-bridge:unrecognized-service`, matching this family's
163
+ * established convention of a non-fatal, discoverable no-op rather than a
164
+ * silent one or a thrown error.
165
+ *
166
+ * ---------------------------------------------------------------------------
167
+ * OUTPUT: reuses `VisualizationExporter` AS-IS (no reimplementation) --
168
+ * `bridge.exportTopology(layoutEngine?, layoutType?)` /
169
+ * `bridge.exportHeatmap()` call straight through to
170
+ * `VisualizationExporter#exportTopology()`/`#exportHeatmap()` against the
171
+ * `TopologySnapshot`/`TrustHeatmap` instances this bridge maintains
172
+ * (either caller-supplied via `opts.snapshot`/`opts.heatmap`, or created
173
+ * internally if omitted -- letting a caller share one `TopologySnapshot`
174
+ * across multiple bridges/nodes if it wants a single node-wide view, per
175
+ * `mesh-service.mjs`'s own "a later composition layer... does that fan-in"
176
+ * note).
177
+ *
178
+ * No browser-only imports at module level.
179
+ */
180
+
181
+ import { TopologySnapshot, TrustHeatmap, VisualizationExporter } from './visualizations.mjs'
182
+
183
+ /** How much one grant-applied/revoke-applied scope changes a heatmap trust value by. Not a tuned constant -- a simple, demonstrable default; a caller wanting different trust semantics should post-process `bridge.heatmap` itself. */
184
+ const TRUST_STEP = 0.2
185
+
186
+ /** @param {number} n @returns {number} */
187
+ function clamp01(n) {
188
+ return Math.max(0, Math.min(1, n))
189
+ }
190
+
191
+ // ---------------------------------------------------------------------------
192
+ // TopologySnapshot mutation helpers -- see module doc comment for why these
193
+ // exist (TopologySnapshot itself has no addNode()/addEdge()/removeNode()).
194
+ // ---------------------------------------------------------------------------
195
+
196
+ /** @param {TopologySnapshot} snapshot @param {string} id @param {object} patch */
197
+ function upsertNode(snapshot, id, patch) {
198
+ if (!id) return
199
+ const idx = snapshot.nodes.findIndex((n) => n.id === id)
200
+ if (idx === -1) {
201
+ snapshot.nodes.push({ id, ...patch })
202
+ } else {
203
+ snapshot.nodes[idx] = { ...snapshot.nodes[idx], ...patch }
204
+ }
205
+ }
206
+
207
+ /** @param {TopologySnapshot} snapshot @param {string} from @param {string} to @returns {number} */
208
+ function findLinkIndex(snapshot, from, to) {
209
+ return snapshot.links.findIndex((l) => l.from === from && l.to === to)
210
+ }
211
+
212
+ /** @param {TopologySnapshot} snapshot @param {string} from @param {string} to @param {object} patch */
213
+ function upsertLink(snapshot, from, to, patch) {
214
+ if (!from || !to) return
215
+ const idx = findLinkIndex(snapshot, from, to)
216
+ if (idx === -1) {
217
+ snapshot.links.push({ from, to, ...patch })
218
+ } else {
219
+ snapshot.links[idx] = { ...snapshot.links[idx], ...patch }
220
+ }
221
+ }
222
+
223
+ /** @param {TopologySnapshot} snapshot @param {string} from @param {string} to */
224
+ function removeLink(snapshot, from, to) {
225
+ const idx = findLinkIndex(snapshot, from, to)
226
+ if (idx !== -1) snapshot.links.splice(idx, 1)
227
+ }
228
+
229
+ // ---------------------------------------------------------------------------
230
+ // createObservabilityBridge
231
+ // ---------------------------------------------------------------------------
232
+
233
+ /**
234
+ * @param {object} opts
235
+ * @param {import('./peer-node.mjs').PeerNode} opts.peerNode - A real
236
+ * `PeerNode` (must provide `.podId`, `.on()`, `.off()` -- the
237
+ * `'peer:connect'`/`'peer:disconnect'` events this bridge always wires).
238
+ * @param {TopologySnapshot} [opts.snapshot] - Reused as-is if supplied
239
+ * (lets multiple bridges/nodes share one node-wide snapshot); a fresh one
240
+ * is created otherwise.
241
+ * @param {TrustHeatmap} [opts.heatmap] - Same sharing story as `snapshot`.
242
+ * @param {VisualizationExporter} [opts.exporter] - Same sharing story;
243
+ * `VisualizationExporter` is stateless, so a fresh one is cheap either way.
244
+ * @param {Function} [opts.onLog] - Free-form debug logging, matching every
245
+ * other file in this family's `onLog` convention (NOT the `ctx.emit()`
246
+ * convention this bridge is itself consuming -- this bridge has no `ctx`
247
+ * of its own, it is not a `MeshService`).
248
+ * @returns {{
249
+ * observe: (handle: {name: string, on: Function}) => (() => void),
250
+ * snapshot: TopologySnapshot,
251
+ * heatmap: TrustHeatmap,
252
+ * exportTopology: (layoutEngine?: import('./visualizations.mjs').TopologyLayout, layoutType?: string) => object,
253
+ * exportHeatmap: () => object,
254
+ * teardown: () => void,
255
+ * }}
256
+ */
257
+ export function createObservabilityBridge({ peerNode, snapshot, heatmap, exporter, onLog } = {}) {
258
+ if (!peerNode || typeof peerNode.on !== 'function' || typeof peerNode.off !== 'function') {
259
+ throw new Error('createObservabilityBridge: peerNode is required and must provide on()/off() (a real PeerNode)')
260
+ }
261
+
262
+ const topology = snapshot instanceof TopologySnapshot ? snapshot : new TopologySnapshot({ id: `observability:${peerNode.podId || 'local'}` })
263
+ const trust = heatmap instanceof TrustHeatmap ? heatmap : new TrustHeatmap()
264
+ const exp = exporter instanceof VisualizationExporter ? exporter : new VisualizationExporter()
265
+ const log = typeof onLog === 'function' ? onLog : () => {}
266
+
267
+ /** @returns {string} */
268
+ function localId() {
269
+ return peerNode.podId || 'local'
270
+ }
271
+
272
+ upsertNode(topology, localId(), { label: localId(), type: 'self', status: 'running' })
273
+
274
+ // -------------------------------------------------------------------
275
+ // 1. PeerNode's own connect/disconnect -> TopologySnapshot
276
+ // -------------------------------------------------------------------
277
+
278
+ /** @param {{fingerprint?: string, label?: string, status?: string, transport?: string}} peer */
279
+ function handlePeerConnect(peer) {
280
+ const id = peer?.fingerprint
281
+ if (!id) return
282
+ upsertNode(topology, localId(), { label: localId(), type: 'self', status: 'running' })
283
+ upsertNode(topology, id, { label: peer.label || id, type: 'peer', status: peer.status || 'connected' })
284
+ upsertLink(topology, localId(), id, { transport: peer.transport || undefined, status: 'connected' })
285
+ log('observability-bridge:peer-connected', { id })
286
+ }
287
+
288
+ /** @param {{fingerprint?: string}} peer */
289
+ function handlePeerDisconnect(peer) {
290
+ const id = peer?.fingerprint
291
+ if (!id) return
292
+ upsertNode(topology, id, { status: 'disconnected' })
293
+ removeLink(topology, localId(), id)
294
+ log('observability-bridge:peer-disconnected', { id })
295
+ }
296
+
297
+ peerNode.on('peer:connect', handlePeerConnect)
298
+ peerNode.on('peer:disconnect', handlePeerDisconnect)
299
+
300
+ // -------------------------------------------------------------------
301
+ // 2. Per-service handle.on() -> TrustHeatmap / TopologySnapshot
302
+ // See module doc comment's "Curated service events" section for the
303
+ // exact vocabulary wired per service and why.
304
+ // -------------------------------------------------------------------
305
+
306
+ const serviceUnsubscribes = []
307
+
308
+ /** @param {{on: Function}} handle */
309
+ function observeGrantLog(handle) {
310
+ serviceUnsubscribes.push(handle.on('grant-log:grant-applied', (data) => {
311
+ const { pubKey, added } = data || {}
312
+ if (!pubKey || !Array.isArray(added) || added.length === 0) return
313
+ const current = trust.getTrust(localId(), pubKey)
314
+ trust.setTrust(localId(), pubKey, clamp01(current + TRUST_STEP * added.length))
315
+ upsertNode(topology, pubKey, { label: pubKey, type: 'peer' })
316
+ log('observability-bridge:trust-increased', { pubKey, added })
317
+ }))
318
+ serviceUnsubscribes.push(handle.on('grant-log:revoke-applied', (data) => {
319
+ const { pubKey, removed } = data || {}
320
+ if (!pubKey || !Array.isArray(removed) || removed.length === 0) return
321
+ const current = trust.getTrust(localId(), pubKey)
322
+ trust.setTrust(localId(), pubKey, clamp01(current - TRUST_STEP * removed.length))
323
+ log('observability-bridge:trust-decreased', { pubKey, removed })
324
+ }))
325
+ }
326
+
327
+ /** @param {{on: Function}} handle */
328
+ function observeChunkReplication(handle) {
329
+ serviceUnsubscribes.push(handle.on('chunk-replication:chunk-replicated', (data) => {
330
+ const { cids, replicatedTo } = data || {}
331
+ if (!Array.isArray(replicatedTo)) return
332
+ for (const peerId of replicatedTo) {
333
+ upsertNode(topology, peerId, { label: peerId, type: 'peer' })
334
+ const idx = findLinkIndex(topology, localId(), peerId)
335
+ const activity = (idx !== -1 ? topology.links[idx].activity || 0 : 0) + 1
336
+ upsertLink(topology, localId(), peerId, { status: 'connected', activity, lastReplicatedCids: cids })
337
+ }
338
+ log('observability-bridge:chunk-replicated', { replicatedTo, cids })
339
+ }))
340
+ }
341
+
342
+ /** @param {{on: Function}} handle */
343
+ function observeMeshWebsocket(handle) {
344
+ serviceUnsubscribes.push(handle.on('mesh-websocket:connection-opened', (data) => {
345
+ const { from, path } = data || {}
346
+ if (!from) return
347
+ upsertNode(topology, from, { label: from, type: 'peer' })
348
+ upsertLink(topology, localId(), from, { status: 'open', transport: 'mesh-websocket', path })
349
+ log('observability-bridge:ws-opened', { from, path })
350
+ }))
351
+ serviceUnsubscribes.push(handle.on('mesh-websocket:connection-closed', (data) => {
352
+ const { from } = data || {}
353
+ if (!from) return
354
+ removeLink(topology, localId(), from)
355
+ log('observability-bridge:ws-closed', { from })
356
+ }))
357
+ }
358
+
359
+ /** @param {{on: Function}} handle */
360
+ function observeMeshKv(handle) {
361
+ serviceUnsubscribes.push(handle.on('mesh-kv:watching', (data) => {
362
+ const { pubKey, storeId } = data || {}
363
+ if (!pubKey) return
364
+ upsertNode(topology, pubKey, { label: pubKey, type: 'peer' })
365
+ upsertLink(topology, localId(), pubKey, { status: 'watching', storeId })
366
+ log('observability-bridge:mesh-kv-watching', { pubKey, storeId })
367
+ }))
368
+ serviceUnsubscribes.push(handle.on('mesh-kv:unwatching', (data) => {
369
+ const { pubKey } = data || {}
370
+ if (!pubKey) return
371
+ removeLink(topology, localId(), pubKey)
372
+ log('observability-bridge:mesh-kv-unwatching', { pubKey })
373
+ }))
374
+
375
+ /** @param {boolean} tombstone @param {object} data */
376
+ function handleEntryChange(tombstone, data) {
377
+ const { from, key, storeId } = data || {}
378
+ // Only an accepted REMOTE merge has a meaningful counterpart edge --
379
+ // see module doc comment's "mesh-kv:" section for why a local write
380
+ // is deliberately not wired to any single edge.
381
+ if (!from || from === localId()) return
382
+ upsertNode(topology, from, { label: from, type: 'peer' })
383
+ const idx = findLinkIndex(topology, from, localId())
384
+ const activity = (idx !== -1 ? topology.links[idx].activity || 0 : 0) + 1
385
+ upsertLink(topology, from, localId(), { status: 'connected', activity, storeId, lastKey: key })
386
+ log('observability-bridge:mesh-kv-activity', { from, key, storeId, tombstone })
387
+ }
388
+ serviceUnsubscribes.push(handle.on('mesh-kv:entry-set', (data) => handleEntryChange(false, data)))
389
+ serviceUnsubscribes.push(handle.on('mesh-kv:entry-deleted', (data) => handleEntryChange(true, data)))
390
+ }
391
+
392
+ const WIRERS = [
393
+ { test: (name) => name.startsWith('grant-log:'), wire: observeGrantLog },
394
+ { test: (name) => name.startsWith('chunk-replication:'), wire: observeChunkReplication },
395
+ { test: (name) => name === 'mesh-websocket', wire: observeMeshWebsocket },
396
+ { test: (name) => name.startsWith('mesh-kv:'), wire: observeMeshKv },
397
+ ]
398
+
399
+ /**
400
+ * Opt this bridge into one attached service's curated events. The caller
401
+ * decides WHICH handles to pass (this file never enumerates a node's
402
+ * services on its own) -- see module doc comment's "Curated service
403
+ * events" section for exactly what gets wired per recognized `.name`.
404
+ * @param {{name: string, on: (event: string, cb: Function) => (() => void)}} handle
405
+ * An `attachService()`-returned handle (`mesh-service.mjs`).
406
+ * @returns {() => void} No-op (subscriptions are torn down as a group via
407
+ * this bridge's own `teardown()`, not individually -- matches
408
+ * `attachService()`'s own handle, whose `teardown()` similarly stops
409
+ * ALL of that service's event delivery at once, not per-subscriber).
410
+ */
411
+ function observe(handle) {
412
+ if (!handle || typeof handle.on !== 'function' || typeof handle.name !== 'string') {
413
+ throw new Error('createObservabilityBridge: observe(handle) requires an attachService() handle ({name, on, ...})')
414
+ }
415
+ const wirer = WIRERS.find((w) => w.test(handle.name))
416
+ if (!wirer) {
417
+ log('observability-bridge:unrecognized-service', { name: handle.name })
418
+ return () => {}
419
+ }
420
+ wirer.wire(handle)
421
+ return () => {}
422
+ }
423
+
424
+ return {
425
+ observe,
426
+ get snapshot() { return topology },
427
+ get heatmap() { return trust },
428
+
429
+ /**
430
+ * @param {import('./visualizations.mjs').TopologyLayout} [layoutEngine]
431
+ * @param {string} [layoutType='circular']
432
+ * @returns {object} `VisualizationExporter#exportTopology()`'s output, unmodified.
433
+ */
434
+ exportTopology(layoutEngine, layoutType) {
435
+ return exp.exportTopology(topology, layoutEngine, layoutType)
436
+ },
437
+
438
+ /** @returns {object} `VisualizationExporter#exportHeatmap()`'s output, unmodified. */
439
+ exportHeatmap() {
440
+ return exp.exportHeatmap(trust)
441
+ },
442
+
443
+ /** Stops all further updates from both the `PeerNode` and every `observe()`d service handle. Does not clear already-recorded `snapshot`/`heatmap` state. */
444
+ teardown() {
445
+ peerNode.off('peer:connect', handlePeerConnect)
446
+ peerNode.off('peer:disconnect', handlePeerDisconnect)
447
+ for (const unsubscribe of serviceUnsubscribes) {
448
+ if (typeof unsubscribe === 'function') unsubscribe()
449
+ }
450
+ serviceUnsubscribes.length = 0
451
+ },
452
+ }
453
+ }
@@ -11,13 +11,26 @@
11
11
  * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-orchestrator.test.mjs
12
12
  */
13
13
 
14
- // Stub BrowserTool base class for Node.js testing
15
- const BrowserTool = globalThis.BrowserTool || class {
16
- constructor() {}
17
- }
18
-
19
14
  import { MESH_TYPE } from '@johnhenry/browsermesh-primitives'
20
15
  import { ComputeRequest, ResourceDescriptor, ResourceScorer } from './resources.mjs'
16
+ import { BrowserTool as CompatBrowserTool } from './compat.mjs'
17
+
18
+ // A real browser environment (clawser's web/clawser-tools.js) may already
19
+ // have defined a real, richer `globalThis.BrowserTool` -- honored first, as
20
+ // before. Otherwise (plain Node, e.g. this package's own tests, or any
21
+ // standalone use of this file), fall back to compat.mjs's real `BrowserTool`
22
+ // (Phase 1 of the agent-runtime plan, issue #90) rather than the do-nothing
23
+ // stub this used to fall back to (`class { constructor() {} }`, with no
24
+ // `.spec` getter at all). That stub silently broke `BrowserToolRegistry
25
+ // .register()` (Phase 4, `mesh-orchestrator-tools.mjs`) for every Meshctl*Tool
26
+ // below in Node -- `.spec` composes `{name, description, parameters,
27
+ // required_permission}` from each subclass's own overridden getters, which
28
+ // only exists on compat.mjs's real `BrowserTool`, not the old stub. Using the
29
+ // real class changes nothing about the 8 Meshctl*Tool subclasses' own bodies
30
+ // below (their name/description/parameters/permission getters and execute()
31
+ // methods are all still their own overrides) -- only what `.spec` (and the
32
+ // default `execute()`/`permission` a subclass doesn't override) resolves to.
33
+ const BrowserTool = globalThis.BrowserTool || CompatBrowserTool
21
34
 
22
35
  // ---------------------------------------------------------------------------
23
36
  // Wire constants (re-exported from canonical registry)
@@ -1,10 +1,21 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
2
  * clawser-peer-agent-swarm.js — Multi-agent coordination protocol.
4
3
  *
5
4
  * Agents share goals, decompose tasks, divide work, merge results,
6
5
  * and achieve collective objectives across the mesh.
7
6
  *
7
+ * `AgentSwarmCoordinator` itself is plain and dependency-injected
8
+ * (`{agentProxy, onLog}`), with no `PeerNode`/mesh-transport awareness of its
9
+ * own -- see `mesh-agent-swarm.mjs`'s `createAgentSwarmService()` (issue
10
+ * #124, `mesh-service.mjs`'s `MeshService` convention) for the wrapper that
11
+ * wires it onto a real `PeerNode`'s `ctx.sendTo()`/`ctx.onIncomingData()`/
12
+ * `ctx.registry.checkAccess()`, giving `executeSubTask()` a real path to
13
+ * reach a REMOTE assignee (this class's own `executeSubTask()` always calls
14
+ * `agentProxy.chat(assignee, ...)` directly and locally, with no notion of
15
+ * "assignee lives on another peer" -- see that file's header for the full
16
+ * design and why a `meshAgentProxy` wrapper, not a rewrite of this class, is
17
+ * what makes remote dispatch real).
18
+ *
8
19
  * Run tests:
9
20
  * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-agent-swarm.test.mjs
10
21
  */