@nanobpm/nano-workforce 0.51.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ # [0.53.0](https://github.com/nanobpm/nano-workforce/compare/v0.52.0...v0.53.0) (2026-08-13)
2
+
3
+
4
+ ### Features
5
+
6
+ * relay ring + transcript store agentic family (H3) ([#162](https://github.com/nanobpm/nano-workforce/issues/162)) ([f629526](https://github.com/nanobpm/nano-workforce/commit/f62952698fa3cfb3321e60fdce61fdb1f13ca9d6)), closes [#142](https://github.com/nanobpm/nano-workforce/issues/142) [#143](https://github.com/nanobpm/nano-workforce/issues/143) [#146](https://github.com/nanobpm/nano-workforce/issues/146) [#streams](https://github.com/nanobpm/nano-workforce/issues/streams)
7
+
8
+ # [0.52.0](https://github.com/nanobpm/nano-workforce/compare/v0.51.0...v0.52.0) (2026-08-13)
9
+
10
+
11
+ ### Features
12
+
13
+ * presence + registry family over app.data (H1) ([#161](https://github.com/nanobpm/nano-workforce/issues/161)) ([6666ff1](https://github.com/nanobpm/nano-workforce/commit/6666ff148d02bc0f7ae9740511fdc62bbe9c2e70)), closes [#142](https://github.com/nanobpm/nano-workforce/issues/142) [#152](https://github.com/nanobpm/nano-workforce/issues/152) [#152](https://github.com/nanobpm/nano-workforce/issues/152) [#144](https://github.com/nanobpm/nano-workforce/issues/144)
14
+
1
15
  # [0.51.0](https://github.com/nanobpm/nano-workforce/compare/v0.50.0...v0.51.0) (2026-08-13)
2
16
 
3
17
 
@@ -0,0 +1,341 @@
1
+ // Unit tests for the agentic presence & registry family (ADR 0056, H1 / #144).
2
+ //
3
+ // Two layers:
4
+ // 1. PresenceRegistry over an in-memory SQLite DataLayer — snapshot grouping, liveness, the
5
+ // jobKeys seam, the canonical supply rows, reconcile, and the register/heartbeat/deregister/
6
+ // TTL lifecycle.
7
+ // 2. The `family` module end-to-end against a REAL AgenticHub driven by an in-memory transport:
8
+ // a REGISTER frame creates a durable row; HEARTBEAT keeps it; DEREGISTER and disconnect remove
9
+ // it; teardown stops cleanly; a mount with no DataLayer is a safe no-op.
10
+ import { readFileSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { DatabaseSync } from "node:sqlite";
13
+ import { test } from "node:test";
14
+ import { fileURLToPath } from "node:url";
15
+ import { AgenticHub } from "@nanobpm/agentic/channel";
16
+ import type {
17
+ Authenticator,
18
+ ChannelConnection,
19
+ ChannelTransport,
20
+ } from "@nanobpm/agentic/channel";
21
+ import { encodeFrame, type Frame, type MessageFamily } from "@nanobpm/agentic/protocol";
22
+ import type { SqliteDb } from "@nanobpm/agentic/presence";
23
+ import type { DataLayer } from "@nanobpm/urban";
24
+ import { assert, assertEquals } from "#test-assert";
25
+ import { noopLog } from "../../../test/log.ts";
26
+ import type { AgenticContext } from "../registry.ts";
27
+ import {
28
+ createPresenceStore,
29
+ currentPresenceRegistry,
30
+ family,
31
+ openPresenceDb,
32
+ PresenceRegistry,
33
+ } from "./presence.family.ts";
34
+
35
+ // ── in-memory SQLite (the app's synchronous SqliteDb shape) ────────────────────────────────────
36
+
37
+ function memSqlite(): SqliteDb {
38
+ const db = new DatabaseSync(":memory:");
39
+ return {
40
+ exec: (sql) => db.exec(sql),
41
+ run: (sql, params = []) => {
42
+ const r = db.prepare(sql).run(...(params as never[]));
43
+ return { changes: Number(r.changes), lastInsertRowid: Number(r.lastInsertRowid) };
44
+ },
45
+ all: <T = Record<string, unknown>>(sql: string, params: unknown[] = []) =>
46
+ db.prepare(sql).all(...(params as never[])) as T[],
47
+ };
48
+ }
49
+
50
+ /** A DataLayer whose default source exposes the given synchronous SqliteDb (nothing else is used). */
51
+ function memData(db: SqliteDb): DataLayer {
52
+ return { source: () => ({ db }) } as unknown as DataLayer;
53
+ }
54
+
55
+ /** A mutable fake clock so TTL sweeps are deterministic. */
56
+ function fakeClock(start = 1_000): { now(): number; advance(ms: number): void } {
57
+ let t = start;
58
+ return { now: () => t, advance: (ms) => { t += ms; } };
59
+ }
60
+
61
+ // ── PresenceRegistry over an in-memory DataLayer ───────────────────────────────────────────────
62
+
63
+ test("snapshot: groups registered workers by leaf token with family/host", () => {
64
+ const store = createPresenceStore(memSqlite());
65
+ store.ensureSchema();
66
+ // Two workers under leaf token "leafA", one under "leafB".
67
+ store.register({ instance: "w2", connectionId: "c2", identity: "leafA", capability: { family: "kimi", host: "boxA2" } });
68
+ store.register({ instance: "w1", connectionId: "c1", identity: "leafA", capability: { family: "opus", host: "boxA1" } });
69
+ store.register({ instance: "w3", connectionId: "c3", identity: "leafB", capability: { family: "qwen", host: "boxB" } });
70
+
71
+ const registry = new PresenceRegistry(store, () => new Set(["c1", "c2", "c3"]));
72
+ const snap = registry.snapshot({ now: 2_000 });
73
+
74
+ assertEquals(snap.count, 3);
75
+ assertEquals(snap.leaves.map((l) => l.token), ["leafA", "leafB"], "leaves sorted by token");
76
+ const leafA = snap.leaves[0];
77
+ assertEquals(leafA.workers.map((w) => w.instance), ["w1", "w2"], "workers sorted by instance");
78
+ assertEquals(leafA.workers[0].family, "opus");
79
+ assertEquals(leafA.workers[0].host, "boxA1");
80
+ assertEquals(snap.leaves[1].workers[0].family, "qwen");
81
+ assertEquals(snap.workers.map((w) => w.instance), ["w1", "w2", "w3"], "flat list sorted");
82
+ });
83
+
84
+ test("snapshot: liveness reflects the open-connection set", () => {
85
+ const store = createPresenceStore(memSqlite());
86
+ store.ensureSchema();
87
+ store.register({ instance: "live", connectionId: "cLive", identity: "leaf", capability: {} });
88
+ store.register({ instance: "gone", connectionId: "cGone", identity: "leaf", capability: {} });
89
+
90
+ const registry = new PresenceRegistry(store, () => new Set(["cLive"]));
91
+ const byInstance = new Map(registry.snapshot().workers.map((w) => [w.instance, w]));
92
+ assertEquals(byInstance.get("live")?.live, true);
93
+ assertEquals(byInstance.get("gone")?.live, false);
94
+ });
95
+
96
+ test("snapshot: staleMs is measured from lastSeen and jobKeysFor seeds current jobKeys", () => {
97
+ const clock = fakeClock(5_000);
98
+ const store = createPresenceStore(memSqlite(), { clock });
99
+ store.ensureSchema();
100
+ store.register({ instance: "w1", connectionId: "c1", identity: "leaf", capability: {} });
101
+
102
+ const registry = new PresenceRegistry(store, () => new Set(["c1"]));
103
+ const snap = registry.snapshot({
104
+ now: 5_250,
105
+ jobKeysFor: (instance) => (instance === "w1" ? ["job-42", "job-43"] : []),
106
+ });
107
+ assertEquals(snap.workers[0].staleMs, 250);
108
+ assertEquals(snap.workers[0].jobKeys, ["job-42", "job-43"]);
109
+ });
110
+
111
+ test("snapshot: jobKeys default to none (presence carries no job attribution)", () => {
112
+ const store = createPresenceStore(memSqlite());
113
+ store.ensureSchema();
114
+ store.register({ instance: "w1", connectionId: "c1", identity: "leaf", capability: {} });
115
+ const registry = new PresenceRegistry(store, () => new Set(["c1"]));
116
+ assertEquals(registry.snapshot().workers[0].jobKeys, []);
117
+ });
118
+
119
+ test("registeredWorkers: returns the canonical {instance, capability} supply rows", () => {
120
+ const store = createPresenceStore(memSqlite());
121
+ store.ensureSchema();
122
+ store.register({ instance: "w1", connectionId: "c1", identity: "leaf", capability: { family: "opus", weight: 4.8, cognition: "deep" } });
123
+ const registry = new PresenceRegistry(store, () => new Set(["c1"]));
124
+ assertEquals(registry.registeredWorkers(), [
125
+ { instance: "w1", capability: { cognition: "deep", weight: 4.8, family: "opus" } },
126
+ ]);
127
+ });
128
+
129
+ test("reconcile: removes rows whose connection the hub has closed, keeps live ones", () => {
130
+ const store = createPresenceStore(memSqlite());
131
+ store.ensureSchema();
132
+ store.register({ instance: "keep", connectionId: "cLive", identity: "leaf", capability: {} });
133
+ store.register({ instance: "drop", connectionId: "cGone", identity: "leaf", capability: {} });
134
+
135
+ const registry = new PresenceRegistry(store, () => new Set(["cLive"]));
136
+ const removed = registry.reconcile();
137
+ assertEquals(removed, ["drop"]);
138
+ assertEquals(registry.count(), 1);
139
+ assertEquals(registry.snapshot().workers.map((w) => w.instance), ["keep"]);
140
+ });
141
+
142
+ test("lifecycle: register creates, heartbeat keeps live, deregister removes, TTL sweep ages out", () => {
143
+ const clock = fakeClock(0);
144
+ const store = createPresenceStore(memSqlite(), { ttlMs: 1_000, clock });
145
+ store.ensureSchema();
146
+ const registry = new PresenceRegistry(store, () => new Set(["c1", "c2"]));
147
+
148
+ store.register({ instance: "w1", connectionId: "c1", identity: "leaf", capability: {} });
149
+ assertEquals(registry.count(), 1);
150
+
151
+ // A heartbeat just before the TTL keeps the worker alive across the sweep.
152
+ clock.advance(900);
153
+ assert(store.heartbeat("w1", "leaf"), "heartbeat refreshes a registered instance");
154
+ clock.advance(900);
155
+ assertEquals(store.sweep().length, 0, "not stale — heartbeat kept it live");
156
+ assertEquals(registry.count(), 1);
157
+
158
+ // Without a further heartbeat it ages out past the TTL.
159
+ clock.advance(1_500);
160
+ assertEquals(store.sweep().map((r) => r.instance), ["w1"]);
161
+ assertEquals(registry.count(), 0);
162
+
163
+ // A graceful deregister removes a re-registered instance immediately.
164
+ store.register({ instance: "w2", connectionId: "c2", identity: "leaf", capability: {} });
165
+ assert(store.deregister("w2", "leaf"));
166
+ assertEquals(registry.count(), 0);
167
+ });
168
+
169
+ test("migration 023 provisions the exact table the store reads/writes", () => {
170
+ const db = memSqlite();
171
+ const sql = readFileSync(
172
+ join(fileURLToPath(new URL("../../../db/migrations/023_agentic_presence.sql", import.meta.url))),
173
+ "utf8",
174
+ );
175
+ db.exec(sql);
176
+ // A store that does NOT call ensureSchema still works against the migrated table.
177
+ const store = createPresenceStore(db);
178
+ store.register({ instance: "w1", connectionId: "c1", identity: "leaf", capability: { family: "opus", host: "box" } });
179
+ assertEquals(store.get("w1")?.capability.host, "box");
180
+ });
181
+
182
+ test("openPresenceDb: returns undefined when no DataLayer is mounted", () => {
183
+ assertEquals(openPresenceDb(undefined), undefined);
184
+ });
185
+
186
+ // ── family module against a real hub + in-memory transport ─────────────────────────────────────
187
+
188
+ interface FakeConn {
189
+ readonly conn: ChannelConnection;
190
+ feed(frame: Frame): void;
191
+ disconnect(): void;
192
+ }
193
+
194
+ function fakeConn(id: string, identity: string): FakeConn {
195
+ let onMessage: ((bytes: Uint8Array) => void) | undefined;
196
+ let onClose: ((code?: number, reason?: string) => void) | undefined;
197
+ const conn: ChannelConnection = {
198
+ id,
199
+ handshake: { query: { identity }, token: "t", credential: "c" },
200
+ send: () => {},
201
+ close: (code, reason) => onClose?.(code, reason),
202
+ onMessage: (l) => { onMessage = l; },
203
+ onClose: (l) => { onClose = l; },
204
+ };
205
+ return {
206
+ conn,
207
+ feed: (frame) => onMessage?.(encodeFrame(frame)),
208
+ disconnect: () => onClose?.(),
209
+ };
210
+ }
211
+
212
+ function memTransport(): { transport: ChannelTransport; connect(conn: ChannelConnection): void } {
213
+ let onConnection: ((conn: ChannelConnection) => void) | undefined;
214
+ const transport: ChannelTransport = {
215
+ onConnection: (l) => { onConnection = l; },
216
+ address: { port: 0 },
217
+ close: async () => {},
218
+ };
219
+ return { transport, connect: (conn) => onConnection?.(conn) };
220
+ }
221
+
222
+ /** Authenticate every peer, deriving its identity (the leaf token) from the handshake query. */
223
+ const authenticator: Authenticator = (req) => ({
224
+ ok: true,
225
+ grant: { identity: req.query?.identity ?? "anon" },
226
+ });
227
+
228
+ /** Flush the hub's microtasks (async auth + async frame routing) so assertions see the result. */
229
+ const flush = () => new Promise((resolve) => setImmediate(resolve));
230
+
231
+ function registerFrame(instance: string, capability: Record<string, unknown>): Frame {
232
+ return { lane: "control", family: "register", seq: 1, payload: { instance, capability } };
233
+ }
234
+ function familyFrame(fam: MessageFamily, instance: string): Frame {
235
+ return { lane: "control", family: fam, seq: 1, payload: { instance } };
236
+ }
237
+
238
+ async function mountFamily(db: SqliteDb | undefined): Promise<{ hub: AgenticHub; transport: ReturnType<typeof memTransport> }> {
239
+ const transport = memTransport();
240
+ const hub = new AgenticHub({ transport: transport.transport, authenticator, sweepIntervalMs: 0 });
241
+ const ctx: AgenticContext = {
242
+ hub,
243
+ registry: hub.registry,
244
+ // The transport handle is not exercised by the presence family; the in-memory one stands in.
245
+ transport: transport.transport as never,
246
+ data: db ? memData(db) : undefined,
247
+ log: noopLog(),
248
+ };
249
+ await family.mount(ctx);
250
+ return { hub, transport };
251
+ }
252
+
253
+ test("family: mount attaches the three handlers and a REGISTER creates a durable presence row", async () => {
254
+ const { hub, transport } = await mountFamily(memSqlite());
255
+ try {
256
+ assertEquals(hub.router.families().sort(), ["deregister", "heartbeat", "register"]);
257
+
258
+ const peer = fakeConn("c1", "leafA");
259
+ transport.connect(peer.conn);
260
+ await flush();
261
+ peer.feed(registerFrame("w1", { family: "opus", host: "boxA" }));
262
+ await flush();
263
+
264
+ const snap = currentPresenceRegistry()?.snapshot();
265
+ assert(snap, "registry is mounted");
266
+ assertEquals(snap.count, 1);
267
+ assertEquals(snap.leaves[0].token, "leafA");
268
+ assertEquals(snap.leaves[0].workers[0].family, "opus");
269
+ assertEquals(snap.leaves[0].workers[0].host, "boxA");
270
+ assertEquals(snap.leaves[0].workers[0].live, true, "connection is open");
271
+ } finally {
272
+ family.teardown?.();
273
+ await hub.close();
274
+ }
275
+ });
276
+
277
+ test("family: HEARTBEAT keeps a worker and DEREGISTER removes it", async () => {
278
+ const { hub, transport } = await mountFamily(memSqlite());
279
+ try {
280
+ const peer = fakeConn("c1", "leaf");
281
+ transport.connect(peer.conn);
282
+ await flush();
283
+ peer.feed(registerFrame("w1", {}));
284
+ await flush();
285
+ assertEquals(currentPresenceRegistry()?.count(), 1);
286
+
287
+ peer.feed(familyFrame("heartbeat", "w1"));
288
+ await flush();
289
+ assertEquals(currentPresenceRegistry()?.count(), 1, "heartbeat keeps the row");
290
+
291
+ peer.feed(familyFrame("deregister", "w1"));
292
+ await flush();
293
+ assertEquals(currentPresenceRegistry()?.count(), 0, "deregister removes the row");
294
+ } finally {
295
+ family.teardown?.();
296
+ await hub.close();
297
+ }
298
+ });
299
+
300
+ test("family: a disconnect removes the worker via reconcile", async () => {
301
+ const { hub, transport } = await mountFamily(memSqlite());
302
+ try {
303
+ const peer = fakeConn("c1", "leaf");
304
+ transport.connect(peer.conn);
305
+ await flush();
306
+ peer.feed(registerFrame("w1", {}));
307
+ await flush();
308
+ assertEquals(currentPresenceRegistry()?.count(), 1);
309
+
310
+ // Simulate the peer vanishing: the hub's own close listener drops it from the live registry.
311
+ peer.disconnect();
312
+ assertEquals(hub.connectionCount, 0, "hub no longer tracks the connection");
313
+
314
+ const removed = currentPresenceRegistry()?.reconcile();
315
+ assertEquals(removed, ["w1"]);
316
+ assertEquals(currentPresenceRegistry()?.count(), 0);
317
+ } finally {
318
+ family.teardown?.();
319
+ await hub.close();
320
+ }
321
+ });
322
+
323
+ test("family: teardown stops the family and clears the current registry", async () => {
324
+ const { hub } = await mountFamily(memSqlite());
325
+ assert(currentPresenceRegistry(), "mounted");
326
+ family.teardown?.();
327
+ assertEquals(currentPresenceRegistry(), undefined, "cleared on teardown");
328
+ await hub.close();
329
+ });
330
+
331
+ test("family: mounting without a DataLayer is a safe no-op", async () => {
332
+ const { hub } = await mountFamily(undefined);
333
+ try {
334
+ assertEquals(currentPresenceRegistry(), undefined, "no registry without data");
335
+ // The three presence handlers are not attached when there is nothing to persist to.
336
+ assertEquals(hub.router.families(), []);
337
+ } finally {
338
+ family.teardown?.();
339
+ await hub.close();
340
+ }
341
+ });
@@ -0,0 +1,279 @@
1
+ // nano-workforce — the agentic presence & registry family (ADR 0056, H1 / #144).
2
+ //
3
+ // A pluggable {@link AgenticFamily} that plugs into the H0 seam (`app/agentic/registry.ts`) with NO
4
+ // edit to `main.ts`, `drainAndExit`, or any shared boot line — the loader discovers this file by its
5
+ // `*.family.ts` suffix and the seam mounts it. It owns the channel's `register` / `heartbeat` /
6
+ // `deregister` message families (attached through the hub's `registerFamilyHandler` seam, never a
7
+ // shared dispatch switch) and layers a DURABLE supply registry over the app's SQLite DataLayer — the
8
+ // same store the advisory blackboard uses; no separate database.
9
+ //
10
+ // What it gives the fleet:
11
+ // - REGISTER → a durable presence row (instance + declared capability + connection + liveness).
12
+ // - HEARTBEAT → refreshes the row's `last_seen` so a live worker stays visible.
13
+ // - DEREGISTER / disconnect / TTL timeout → removes the row (see the maintenance tick below).
14
+ // - {@link PresenceRegistry.snapshot} → the read-only SUPPLY mirror: connected workers grouped by
15
+ // leaf token, each with identity, family, host, liveness (and a seam for current jobKeys). This
16
+ // is the supply feed the enrolment epic (#152) reads and the cockpit (H5) renders.
17
+ //
18
+ // Invariants (ADR 0056): app-tier only, never the engine; the Camunda-8 job protocol (worker⇄engine)
19
+ // is untouched — presence rides the agentic channel only; ADVISORY — the registry is a read-only
20
+ // mirror and NEVER hard-locks or gates a BPMN sequence flow. Capability (cognition/weight/family/host)
21
+ // is an ENROLMENT attribute, never a routing token.
22
+ import {
23
+ attachPresenceFamily,
24
+ type PresenceFamilyHandle,
25
+ PresenceStore,
26
+ type PresenceStoreOptions,
27
+ type SqliteDb,
28
+ } from "@nanobpm/agentic/presence";
29
+ import type { DataLayer } from "@nanobpm/urban";
30
+ import type { AgenticContext, AgenticFamily } from "../registry.ts";
31
+
32
+ /** The message-family name this module owns (its three handlers are register/heartbeat/deregister). */
33
+ export const PRESENCE_FAMILY = "presence";
34
+
35
+ /** The maintenance tick runs at a third of the presence TTL — matching the hub/store sweep cadence. */
36
+ const SWEEP_DIVISOR = 3;
37
+
38
+ /** One worker in the supply mirror: a durable presence row projected for the cockpit/enrolment feed. */
39
+ export interface SupplyWorker {
40
+ /** The worker instance id (`register.instance`). */
41
+ readonly instance: string;
42
+ /** The authenticated ADR 0028 principal — the leaf token this worker registered under. */
43
+ readonly identity: string;
44
+ /** Declared cognition (enrolment attribute), if any. */
45
+ readonly cognition?: string;
46
+ /** Declared cognition weight (enrolment attribute), if any. */
47
+ readonly weight?: number;
48
+ /** Declared family (enrolment attribute) — the diversity-SLO seat filler, if any. */
49
+ readonly family?: string;
50
+ /** Declared host (enrolment attribute) — where the worker runs, if any. */
51
+ readonly host?: string;
52
+ /** The channel connection the worker last registered on. */
53
+ readonly connectionId: string;
54
+ /** When the worker first registered, ISO-8601. */
55
+ readonly registeredAt: string;
56
+ /** Last liveness refresh (register/heartbeat), epoch ms. */
57
+ readonly lastSeen: number;
58
+ /** Whether the worker's connection is still open in the hub's live connection registry. */
59
+ readonly live: boolean;
60
+ /** How long since the last liveness refresh, in ms (0 when fresh). */
61
+ readonly staleMs: number;
62
+ /**
63
+ * The jobKeys this worker is currently processing. Presence carries no job attribution of its own,
64
+ * so this is populated from the injected {@link SnapshotOptions.jobKeysFor} resolver — the seam the
65
+ * relay/correlation slice (H6) wires; it is `[]` until then.
66
+ */
67
+ readonly jobKeys: readonly string[];
68
+ }
69
+
70
+ /** The supply for one leaf token: the workers registered under it. */
71
+ export interface SupplyLeaf {
72
+ /** The leaf token — the ADR 0028 identity principal. (Refined to SERVE tokens when vocab #152 lands.) */
73
+ readonly token: string;
74
+ /** The workers registered under this leaf token, sorted by instance. */
75
+ readonly workers: readonly SupplyWorker[];
76
+ }
77
+
78
+ /** The read-only supply snapshot: the live registry grouped by leaf token, plus a flat worker list. */
79
+ export interface PresenceSnapshot {
80
+ /** Supply grouped by leaf token, sorted by token. */
81
+ readonly leaves: readonly SupplyLeaf[];
82
+ /** Every registered worker, flat, sorted by instance. */
83
+ readonly workers: readonly SupplyWorker[];
84
+ /** The number of registered workers. */
85
+ readonly count: number;
86
+ }
87
+
88
+ /** The canonical supply-row shape the enrolment epic (#152) resolves against the vocab. */
89
+ export interface RegisteredWorker {
90
+ readonly instance: string;
91
+ readonly capability: {
92
+ readonly cognition?: string;
93
+ readonly weight?: number;
94
+ readonly family?: string;
95
+ readonly host?: string;
96
+ };
97
+ }
98
+
99
+ /** Options for {@link PresenceRegistry.snapshot}. */
100
+ export interface SnapshotOptions {
101
+ /** "Now" in epoch ms for the `staleMs` computation. Defaults to `Date.now()`. */
102
+ readonly now?: number;
103
+ /** Resolve the current jobKeys for a worker instance. Defaults to none (presence has no jobs). */
104
+ readonly jobKeysFor?: (instance: string) => readonly string[];
105
+ }
106
+
107
+ /**
108
+ * The durable presence registry: a read-only projection over the {@link PresenceStore}, cross-checked
109
+ * against the set of currently-open hub connections for liveness. It NEVER gates control flow — it is
110
+ * the supply mirror the enrolment epic and the cockpit read.
111
+ */
112
+ export class PresenceRegistry {
113
+ readonly #store: PresenceStore;
114
+ readonly #liveConnectionIds: () => Set<string>;
115
+
116
+ constructor(store: PresenceStore, liveConnectionIds: () => Set<string>) {
117
+ this.#store = store;
118
+ this.#liveConnectionIds = liveConnectionIds;
119
+ }
120
+
121
+ /** The presence liveness TTL in ms. */
122
+ get ttlMs(): number {
123
+ return this.#store.ttlMs;
124
+ }
125
+
126
+ /** The number of registered workers. */
127
+ count(): number {
128
+ return this.#store.count();
129
+ }
130
+
131
+ /** The canonical supply rows (`{ instance, capability }`) the enrolment epic (#152) consumes. */
132
+ registeredWorkers(): RegisteredWorker[] {
133
+ return this.#store.list().map((row) => ({ instance: row.instance, capability: { ...row.capability } }));
134
+ }
135
+
136
+ /**
137
+ * Eagerly drop presence rows whose connection the hub has already closed (a disconnect the hub's
138
+ * single close listener removed from its in-memory registry). Rows also age out on the presence
139
+ * TTL via {@link PresenceStore.sweep}; this is the eager disconnect path. Returns the removed
140
+ * instance ids.
141
+ */
142
+ reconcile(): string[] {
143
+ const live = this.#liveConnectionIds();
144
+ const deadConnections = new Set<string>();
145
+ for (const row of this.#store.list()) {
146
+ if (!live.has(row.connectionId)) deadConnections.add(row.connectionId);
147
+ }
148
+ const removed: string[] = [];
149
+ for (const connectionId of deadConnections) {
150
+ removed.push(...this.#store.removeByConnection(connectionId));
151
+ }
152
+ return removed;
153
+ }
154
+
155
+ /** The read-only supply snapshot: connected workers grouped by leaf token, with family/host/liveness. */
156
+ snapshot(options: SnapshotOptions = {}): PresenceSnapshot {
157
+ const now = options.now ?? Date.now();
158
+ const jobKeysFor = options.jobKeysFor ?? (() => []);
159
+ const live = this.#liveConnectionIds();
160
+ const workers: SupplyWorker[] = this.#store.list().map((row) => ({
161
+ instance: row.instance,
162
+ identity: row.identity,
163
+ cognition: row.capability.cognition,
164
+ weight: row.capability.weight,
165
+ family: row.capability.family,
166
+ host: row.capability.host,
167
+ connectionId: row.connectionId,
168
+ registeredAt: row.registeredAt,
169
+ lastSeen: row.lastSeen,
170
+ live: live.has(row.connectionId),
171
+ staleMs: Math.max(0, now - row.lastSeen),
172
+ jobKeys: [...jobKeysFor(row.instance)],
173
+ }));
174
+
175
+ const byToken = new Map<string, SupplyWorker[]>();
176
+ for (const worker of workers) {
177
+ const bucket = byToken.get(worker.identity);
178
+ if (bucket) bucket.push(worker);
179
+ else byToken.set(worker.identity, [worker]);
180
+ }
181
+ const byInstance = (a: SupplyWorker, b: SupplyWorker) => a.instance.localeCompare(b.instance);
182
+ const leaves: SupplyLeaf[] = [...byToken.entries()]
183
+ .sort(([a], [b]) => a.localeCompare(b))
184
+ .map(([token, ws]) => ({ token, workers: ws.slice().sort(byInstance) }));
185
+
186
+ return { leaves, workers: workers.slice().sort(byInstance), count: workers.length };
187
+ }
188
+ }
189
+
190
+ /** Open the app's synchronous SQLite handle from the DataLayer, or undefined when data isn't mounted. */
191
+ export function openPresenceDb(data: DataLayer | undefined): SqliteDb | undefined {
192
+ if (!data) return undefined;
193
+ return data.source().db;
194
+ }
195
+
196
+ /** The live registry from the most recent mount, so the cockpit/report (H5) can read the supply feed. */
197
+ let currentRegistry: PresenceRegistry | undefined;
198
+
199
+ /** The mounted presence registry (the supply feed), or undefined before mount / after teardown. */
200
+ export function currentPresenceRegistry(): PresenceRegistry | undefined {
201
+ return currentRegistry;
202
+ }
203
+
204
+ interface MountState {
205
+ readonly registry: PresenceRegistry;
206
+ readonly handle: PresenceFamilyHandle;
207
+ readonly timer: ReturnType<typeof setInterval> | undefined;
208
+ }
209
+
210
+ let state: MountState | undefined;
211
+
212
+ /** Build the presence store; exported so tests can inject a fake clock / TTL over an in-memory db. */
213
+ export function createPresenceStore(db: SqliteDb, options?: PresenceStoreOptions): PresenceStore {
214
+ return new PresenceStore(db, options);
215
+ }
216
+
217
+ /**
218
+ * The presence family module. `mount` attaches register/heartbeat/deregister to the hub, applies the
219
+ * schema, and starts ONE canonical maintenance tick that both ages out on the presence TTL and drops
220
+ * rows for disconnected connections. `teardown` stops the tick and the presence sweep.
221
+ */
222
+ export const family: AgenticFamily = {
223
+ name: PRESENCE_FAMILY,
224
+
225
+ mount(ctx: AgenticContext): void {
226
+ const db = openPresenceDb(ctx.data);
227
+ if (!db) {
228
+ ctx.log.warn("agentic presence: no data layer mounted — presence registry disabled");
229
+ return;
230
+ }
231
+ const store = createPresenceStore(db);
232
+ store.ensureSchema();
233
+
234
+ const liveConnectionIds = () => new Set(ctx.hub.registry.list().map((conn) => conn.id));
235
+ const registry = new PresenceRegistry(store, liveConnectionIds);
236
+
237
+ // Attach the three presence handlers via the S1 seam. Disable the package's own TTL timer
238
+ // (`sweepIntervalMs: 0`) so this module runs a SINGLE maintenance loop rather than two — the
239
+ // canonical presence-maintenance pass, not a second poller (derivation over duplication).
240
+ const handle = attachPresenceFamily(ctx.hub, store, {
241
+ sweepIntervalMs: 0,
242
+ onError: (err, connectionId) =>
243
+ ctx.log.warn("agentic presence fault", { connectionId, err: String(err) }),
244
+ });
245
+
246
+ const interval = Math.max(1, Math.floor(store.ttlMs / SWEEP_DIVISOR));
247
+ const tick = () => {
248
+ // TTL age-out (silent-worker liveness timeout) + eager disconnect cleanup, on one cadence.
249
+ handle.sweepNow();
250
+ try {
251
+ registry.reconcile();
252
+ } catch (err) {
253
+ ctx.log.warn("agentic presence reconcile failed", { err: String(err) });
254
+ }
255
+ };
256
+ // Run one maintenance pass eagerly at mount so the registry is correct immediately: the
257
+ // presence table is durable across restarts, so without this first sweep/reconcile
258
+ // `registeredWorkers()` / `snapshot()` could briefly surface stale rows from a previous run
259
+ // (all connections start closed) until the first interval tick fires.
260
+ tick();
261
+ const timer = interval > 0 ? setInterval(tick, interval) : undefined;
262
+ // Never keep the process alive for the presence sweep alone.
263
+ timer?.unref?.();
264
+
265
+ state = { registry, handle, timer };
266
+ currentRegistry = registry;
267
+ ctx.log.info("agentic presence mounted", { family: PRESENCE_FAMILY, ttlMs: store.ttlMs });
268
+ },
269
+
270
+ teardown(): void {
271
+ if (!state) return;
272
+ if (state.timer !== undefined) clearInterval(state.timer);
273
+ state.handle.stop();
274
+ state = undefined;
275
+ currentRegistry = undefined;
276
+ },
277
+ };
278
+
279
+ export default family;