@nanobpm/nano-workforce 0.54.0 → 0.55.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.
@@ -0,0 +1,144 @@
1
+ // The SUPPLY-only cockpit DOM renderer (ADR 0056, H5 / #148).
2
+ //
3
+ // Renders a {@link SupplyView} into a host element: the live worker list grouped by leaf token, each
4
+ // worker showing family, host, current jobs, and a liveness dot. Clicking a worker calls
5
+ // {@link RenderOptions.onDrill} with that worker's relay stream id, which the boot layer turns into a
6
+ // live terminal. This renders only the *volatile* part of the page (re-rendered each poll pass); the
7
+ // drill-in terminal is owned by {@link ../supply-boot.ts} in a persistent region so it survives a
8
+ // refresh.
9
+ //
10
+ // It draws a supply-only projection ON PURPOSE — NOT the packaged `renderCockpit`, which draws the
11
+ // demand×supply matrix, the missing-agent-type reds, and the diversity-SLO light. Those are deferred
12
+ // to enrolment epic #152 (see `./supply-view.ts`). The genuinely reusable, correctness-critical parts
13
+ // of the cockpit — the relay client and the resume-from-offset terminal session — ARE reused from
14
+ // `@nanobpm/agentic/cockpit` by the boot layer; only this supply projection, which the package does
15
+ // not provide, is authored here.
16
+ //
17
+ // Like the packaged renderer it builds against the structural {@link ElementLike} / {@link DocumentLike}
18
+ // subset (reused from `@nanobpm/agentic/cockpit`) rather than the global `document`, so the real DOM
19
+ // satisfies it at runtime AND a plain in-memory fake satisfies it for DOM-free Node tests (no `as`).
20
+ import type { DocumentLike, ElementLike } from "@nanobpm/agentic/cockpit";
21
+ import type { Liveness, SupplyLeafView, SupplyView, SupplyWorkerView } from "./supply-view.ts";
22
+
23
+ export interface RenderSupplyOptions {
24
+ /** Called with a worker's relay stream id when the operator drills into it. */
25
+ readonly onDrill?: (stream: string) => void;
26
+ }
27
+
28
+ /** Handles into the rendered tree the caller may need. */
29
+ export interface SupplyDom {
30
+ /** The freshly built root the view was rendered into. */
31
+ readonly root: ElementLike;
32
+ }
33
+
34
+ function el(doc: DocumentLike, tag: string, className?: string, text?: string): ElementLike {
35
+ const node = doc.createElement(tag);
36
+ if (className !== undefined) node.className = className;
37
+ if (text !== undefined) node.textContent = text;
38
+ return node;
39
+ }
40
+
41
+ function dot(doc: DocumentLike, liveness: Liveness): ElementLike {
42
+ const node = el(doc, "span", "cockpit-dot");
43
+ node.setAttribute("data-liveness", liveness);
44
+ return node;
45
+ }
46
+
47
+ function workerRow(doc: DocumentLike, worker: SupplyWorkerView, options: RenderSupplyOptions): ElementLike {
48
+ const row = el(doc, "tr", "cockpit-supply-worker");
49
+ row.setAttribute("data-worker", worker.instance);
50
+ row.setAttribute("data-liveness", worker.liveness);
51
+ row.setAttribute("data-stream", worker.stream);
52
+
53
+ const nameCell = el(doc, "td", "cockpit-td cockpit-supply-name");
54
+ nameCell.appendChild(dot(doc, worker.liveness));
55
+ const button = el(doc, "button", "cockpit-worker", worker.instance);
56
+ button.setAttribute("type", "button");
57
+ button.setAttribute("data-stream", worker.stream);
58
+ const onDrill = options.onDrill;
59
+ if (onDrill !== undefined) {
60
+ button.addEventListener("click", () => onDrill(worker.stream));
61
+ }
62
+ nameCell.appendChild(button);
63
+ row.appendChild(nameCell);
64
+
65
+ row.appendChild(el(doc, "td", "cockpit-td cockpit-supply-family", worker.family));
66
+ row.appendChild(el(doc, "td", "cockpit-td cockpit-supply-host", worker.host));
67
+
68
+ const jobsCell = el(doc, "td", "cockpit-td cockpit-supply-jobs", worker.jobs === 0 ? "—" : worker.jobKeys.join(", "));
69
+ jobsCell.setAttribute("data-jobs", String(worker.jobs));
70
+ row.appendChild(jobsCell);
71
+
72
+ const livenessCell = el(doc, "td", "cockpit-td cockpit-supply-liveness", worker.liveness);
73
+ livenessCell.setAttribute("data-liveness", worker.liveness);
74
+ row.appendChild(livenessCell);
75
+
76
+ return row;
77
+ }
78
+
79
+ function leafSection(doc: DocumentLike, leaf: SupplyLeafView, options: RenderSupplyOptions): ElementLike {
80
+ const section = el(doc, "section", "cockpit-leaf");
81
+ section.setAttribute("data-leaf", leaf.token);
82
+
83
+ const header = el(doc, "div", "cockpit-leaf-head");
84
+ header.appendChild(el(doc, "span", "cockpit-leaf-name", leaf.token));
85
+ header.appendChild(el(doc, "span", "cockpit-leaf-count", `${leaf.liveCount}/${leaf.total} live`));
86
+ section.appendChild(header);
87
+
88
+ const table = el(doc, "table", "cockpit-supply-table");
89
+ const thead = el(doc, "thead", "cockpit-supply-thead");
90
+ const head = el(doc, "tr", "cockpit-supply-head");
91
+ for (const label of ["worker", "family", "host", "jobs", "liveness"]) {
92
+ head.appendChild(el(doc, "th", "cockpit-th", label));
93
+ }
94
+ thead.appendChild(head);
95
+ table.appendChild(thead);
96
+
97
+ const tbody = el(doc, "tbody", "cockpit-supply-tbody");
98
+ for (const worker of leaf.workers) {
99
+ tbody.appendChild(workerRow(doc, worker, options));
100
+ }
101
+ table.appendChild(tbody);
102
+ section.appendChild(table);
103
+ return section;
104
+ }
105
+
106
+ /**
107
+ * Render `view` into `host`, replacing whatever was there. Idempotent: call it again on every refresh
108
+ * to reflect the latest supply snapshot.
109
+ */
110
+ export function renderSupply(
111
+ host: ElementLike,
112
+ doc: DocumentLike,
113
+ view: SupplyView,
114
+ options: RenderSupplyOptions = {},
115
+ ): SupplyDom {
116
+ host.replaceChildren();
117
+ const root = el(doc, "div", "cockpit-supply");
118
+ root.setAttribute("data-worker-count", String(view.count));
119
+ root.setAttribute("data-live-count", String(view.live));
120
+
121
+ const header = el(doc, "header", "cockpit-header");
122
+ header.appendChild(el(doc, "h1", "cockpit-title", "Workers — supply"));
123
+ const summary = el(doc, "span", "cockpit-supply-summary", `${view.live}/${view.count} live`);
124
+ summary.setAttribute("data-summary", "supply");
125
+ header.appendChild(summary);
126
+ root.appendChild(header);
127
+
128
+ if (view.count === 0) {
129
+ const empty = el(doc, "div", "cockpit-supply-empty", "No workers connected.");
130
+ empty.setAttribute("data-empty", "true");
131
+ root.appendChild(empty);
132
+ host.appendChild(root);
133
+ return { root };
134
+ }
135
+
136
+ const list = el(doc, "div", "cockpit-supply-list");
137
+ for (const leaf of view.leaves) {
138
+ list.appendChild(leafSection(doc, leaf, options));
139
+ }
140
+ root.appendChild(list);
141
+
142
+ host.appendChild(root);
143
+ return { root };
144
+ }
@@ -0,0 +1,76 @@
1
+ // Unit tests for the SUPPLY cockpit view-model projection (H5 / #148).
2
+ import assert from "node:assert/strict";
3
+ import { test } from "node:test";
4
+
5
+ import { type SupplyReport, supplyView } from "./supply-view.ts";
6
+
7
+ function report(over: Partial<SupplyReport> = {}): SupplyReport {
8
+ const workers = over.workers ?? [];
9
+ return {
10
+ workers,
11
+ leaves: over.leaves ?? [],
12
+ count: over.count ?? workers.length,
13
+ generatedAt: over.generatedAt,
14
+ };
15
+ }
16
+
17
+ test("grades liveness: down when disconnected, stale past the threshold, else live", () => {
18
+ const view = supplyView(
19
+ report({
20
+ workers: [
21
+ { instance: "a", identity: "t", stream: "a", jobKeys: [], live: false, staleMs: 0 },
22
+ { instance: "b", identity: "t", stream: "b", jobKeys: [], live: true, staleMs: 20_000 },
23
+ { instance: "c", identity: "t", stream: "c", jobKeys: [], live: true, staleMs: 100 },
24
+ ],
25
+ }),
26
+ { staleAfterMs: 15_000 },
27
+ );
28
+ assert.equal(view.workers.find((w) => w.instance === "a")?.liveness, "down");
29
+ assert.equal(view.workers.find((w) => w.instance === "b")?.liveness, "stale");
30
+ assert.equal(view.workers.find((w) => w.instance === "c")?.liveness, "live");
31
+ assert.equal(view.count, 3);
32
+ assert.equal(view.live, 1);
33
+ });
34
+
35
+ test("defaults absent family/host to a stable dash and counts + sorts jobKeys", () => {
36
+ const view = supplyView(
37
+ report({
38
+ workers: [{ instance: "a", identity: "t", stream: "a", jobKeys: ["z", "a"], live: true, staleMs: 0 }],
39
+ }),
40
+ );
41
+ const w = view.workers[0];
42
+ assert.equal(w?.family, "—");
43
+ assert.equal(w?.host, "—");
44
+ assert.deepEqual(w?.jobKeys, ["a", "z"]);
45
+ assert.equal(w?.jobs, 2);
46
+ });
47
+
48
+ test("sorts leaves by token and workers by instance, with per-leaf live counts", () => {
49
+ const view = supplyView(
50
+ report({
51
+ leaves: [
52
+ {
53
+ token: "leaf-b",
54
+ workers: [
55
+ { instance: "b2", identity: "leaf-b", stream: "b2", jobKeys: [], live: true, staleMs: 0 },
56
+ { instance: "b1", identity: "leaf-b", stream: "b1", jobKeys: [], live: false, staleMs: 0 },
57
+ ],
58
+ },
59
+ {
60
+ token: "leaf-a",
61
+ workers: [{ instance: "a1", identity: "leaf-a", stream: "a1", jobKeys: [], live: true, staleMs: 0 }],
62
+ },
63
+ ],
64
+ }),
65
+ );
66
+ assert.deepEqual(
67
+ view.leaves.map((l) => l.token),
68
+ ["leaf-a", "leaf-b"],
69
+ );
70
+ assert.deepEqual(
71
+ view.leaves[1]?.workers.map((w) => w.instance),
72
+ ["b1", "b2"],
73
+ );
74
+ assert.equal(view.leaves[1]?.liveCount, 1);
75
+ assert.equal(view.leaves[1]?.total, 2);
76
+ });
@@ -0,0 +1,165 @@
1
+ // The SUPPLY-only cockpit view-model (ADR 0056, H5 / #148).
2
+ //
3
+ // A pure, deterministic projection of the app's SUPPLY report — the live worker registry (H1 #144)
4
+ // carried over the agentic channel — onto the shape the supply cockpit renders: a per-leaf-token
5
+ // list of connected workers with family, host, current jobs, and liveness.
6
+ //
7
+ // This is DELIBERATELY the supply half only. The DEMAND×supply matrix, the missing-agent-type reds,
8
+ // and the diversity-SLO lights (the packaged `@nanobpm/agentic/cockpit` view/render draws those from
9
+ // a `DemandSupplyReport`) are OUT OF SCOPE for this epic (#142) — they depend on the vocab /
10
+ // capability→SERVE / diversity-SLO machinery deferred to the paired enrolment epic #152. So this
11
+ // module models a supply-only report and never fabricates demand data.
12
+ //
13
+ // Like the packaged `cockpit/view.ts` it is framework-free and side-effect-free: the same report
14
+ // always yields the same {@link SupplyView}, so it is safe to snapshot in a test and to render
15
+ // identically whether the page is embedded in the console (App View, ADR 0057) or served standalone.
16
+
17
+ /** A worker's coarse liveness grade, rendered as a coloured dot. */
18
+ export type Liveness = "live" | "stale" | "down";
19
+
20
+ /** One connected worker as the app's supply feed reports it (mirrors the H1 registry snapshot row). */
21
+ export interface SupplyWorkerReport {
22
+ /** The worker instance id. */
23
+ readonly instance: string;
24
+ /** The authenticated ADR 0028 principal — the leaf token this worker registered under. */
25
+ readonly identity: string;
26
+ /**
27
+ * The relay stream to drill into for this worker's live terminal. The supply endpoint defaults it
28
+ * to the worker instance; the correlation slice (H6 #149) may repoint it at a jobKey-keyed stream.
29
+ */
30
+ readonly stream: string;
31
+ /** Declared family (enrolment attribute), if any. */
32
+ readonly family?: string;
33
+ /** Declared host (where the worker runs), if any. */
34
+ readonly host?: string;
35
+ /** The jobKeys the worker is currently processing (empty until H6 wires the resolver). */
36
+ readonly jobKeys: readonly string[];
37
+ /** Whether the worker's channel connection is still open. */
38
+ readonly live: boolean;
39
+ /** How long since the worker's last liveness refresh, in ms. */
40
+ readonly staleMs: number;
41
+ }
42
+
43
+ /** The supply registered under one leaf token. */
44
+ export interface SupplyLeafReport {
45
+ readonly token: string;
46
+ readonly workers: readonly SupplyWorkerReport[];
47
+ }
48
+
49
+ /** The supply-only report the cockpit polls (no demand fields — those are enrolment epic #152). */
50
+ export interface SupplyReport {
51
+ /** Supply grouped by leaf token. */
52
+ readonly leaves: readonly SupplyLeafReport[];
53
+ /** Every connected worker, flat. */
54
+ readonly workers: readonly SupplyWorkerReport[];
55
+ /** The number of connected workers. */
56
+ readonly count: number;
57
+ /** When the snapshot was taken, ISO-8601 (optional). */
58
+ readonly generatedAt?: string;
59
+ }
60
+
61
+ /** One worker row in the renderable supply view. */
62
+ export interface SupplyWorkerView {
63
+ readonly instance: string;
64
+ readonly identity: string;
65
+ /** The relay stream to open when the operator drills into this worker. */
66
+ readonly stream: string;
67
+ /** Declared family, or `"—"` when absent (so the cell always renders something stable). */
68
+ readonly family: string;
69
+ /** Declared host, or `"—"` when absent. */
70
+ readonly host: string;
71
+ /** The worker's current jobKeys, sorted. */
72
+ readonly jobKeys: readonly string[];
73
+ /** The number of current jobs. */
74
+ readonly jobs: number;
75
+ /** The coarse liveness grade for the status dot. */
76
+ readonly liveness: Liveness;
77
+ /** How long since the last liveness refresh, in ms. */
78
+ readonly staleMs: number;
79
+ }
80
+
81
+ /** One leaf-token section in the renderable supply view. */
82
+ export interface SupplyLeafView {
83
+ readonly token: string;
84
+ readonly workers: readonly SupplyWorkerView[];
85
+ /** Workers under this leaf currently graded `live`. */
86
+ readonly liveCount: number;
87
+ /** Total workers under this leaf. */
88
+ readonly total: number;
89
+ }
90
+
91
+ /** The full renderable supply view. */
92
+ export interface SupplyView {
93
+ /** Supply grouped by leaf token, sorted by token. */
94
+ readonly leaves: readonly SupplyLeafView[];
95
+ /** Every worker, flat, sorted by instance. */
96
+ readonly workers: readonly SupplyWorkerView[];
97
+ /** The number of workers. */
98
+ readonly count: number;
99
+ /** The number of workers graded `live`. */
100
+ readonly live: number;
101
+ }
102
+
103
+ /** Options for {@link supplyView}. */
104
+ export interface SupplyViewOptions {
105
+ /**
106
+ * A live worker whose last refresh is older than this (ms) is graded `stale` rather than `live`.
107
+ * A disconnected worker is always `down`. Default 15000.
108
+ */
109
+ readonly staleAfterMs?: number;
110
+ }
111
+
112
+ const DEFAULT_STALE_AFTER_MS = 15_000;
113
+
114
+ function liveness(worker: SupplyWorkerReport, staleAfterMs: number): Liveness {
115
+ if (!worker.live) return "down";
116
+ return worker.staleMs >= staleAfterMs ? "stale" : "live";
117
+ }
118
+
119
+ function workerView(worker: SupplyWorkerReport, staleAfterMs: number): SupplyWorkerView {
120
+ const jobKeys = [...worker.jobKeys].sort((a, b) => a.localeCompare(b));
121
+ return {
122
+ instance: worker.instance,
123
+ identity: worker.identity,
124
+ stream: worker.stream,
125
+ family: worker.family ?? "—",
126
+ host: worker.host ?? "—",
127
+ jobKeys,
128
+ jobs: jobKeys.length,
129
+ liveness: liveness(worker, staleAfterMs),
130
+ staleMs: worker.staleMs,
131
+ };
132
+ }
133
+
134
+ const byInstance = (a: SupplyWorkerView, b: SupplyWorkerView) => a.instance.localeCompare(b.instance);
135
+
136
+ /**
137
+ * Derive the renderable supply view from the app's supply-only report.
138
+ *
139
+ * Pure and total: it re-sorts leaves by token and workers by instance so the derived view is stable
140
+ * and diff-friendly regardless of the report's incoming order; no input mutates and no I/O happens.
141
+ */
142
+ export function supplyView(report: SupplyReport, options: SupplyViewOptions = {}): SupplyView {
143
+ const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;
144
+
145
+ const leaves: SupplyLeafView[] = report.leaves
146
+ .map((leaf) => {
147
+ const workers = leaf.workers.map((w) => workerView(w, staleAfterMs)).sort(byInstance);
148
+ return {
149
+ token: leaf.token,
150
+ workers,
151
+ liveCount: workers.filter((w) => w.liveness === "live").length,
152
+ total: workers.length,
153
+ };
154
+ })
155
+ .sort((a, b) => a.token.localeCompare(b.token));
156
+
157
+ const workers = report.workers.map((w) => workerView(w, staleAfterMs)).sort(byInstance);
158
+
159
+ return {
160
+ leaves,
161
+ workers,
162
+ count: workers.length,
163
+ live: workers.filter((w) => w.liveness === "live").length,
164
+ };
165
+ }
package/openapi.yaml CHANGED
@@ -99,6 +99,79 @@ components:
99
99
  type: array
100
100
  items:
101
101
  $ref: "#/components/schemas/ActivePr"
102
+ AgenticSupplyWorker:
103
+ type: object
104
+ description: One connected worker in the supply mirror (H5 cockpit; sourced from the H1 presence registry).
105
+ required:
106
+ - instance
107
+ - identity
108
+ - stream
109
+ - jobKeys
110
+ - live
111
+ - staleMs
112
+ properties:
113
+ instance:
114
+ type: string
115
+ description: The worker instance id.
116
+ identity:
117
+ type: string
118
+ description: The ADR 0028 leaf token the worker registered under.
119
+ stream:
120
+ type: string
121
+ description: The relay stream id to subscribe when drilling into this worker's terminal.
122
+ family:
123
+ type: string
124
+ description: Declared family (enrolment attribute), if any.
125
+ host:
126
+ type: string
127
+ description: Declared host (where the worker runs), if any.
128
+ jobKeys:
129
+ type: array
130
+ description: The jobKeys this worker is currently processing (empty until the H6 correlation seam lands).
131
+ items:
132
+ type: string
133
+ live:
134
+ type: boolean
135
+ description: Whether the worker's channel connection is still open.
136
+ staleMs:
137
+ type: integer
138
+ description: Milliseconds since the last liveness refresh (0 when fresh).
139
+ AgenticSupplyLeaf:
140
+ type: object
141
+ description: The supply for one leaf token — the workers registered under it.
142
+ required:
143
+ - token
144
+ - workers
145
+ properties:
146
+ token:
147
+ type: string
148
+ workers:
149
+ type: array
150
+ items:
151
+ $ref: "#/components/schemas/AgenticSupplyWorker"
152
+ AgenticSupplyReport:
153
+ type: object
154
+ description: The SUPPLY-ONLY visibility report — the live worker list grouped by leaf. No demand-side
155
+ fields (the demand×supply matrix / diversity SLO are deferred to enrolment epic #152).
156
+ required:
157
+ - count
158
+ - workers
159
+ - leaves
160
+ properties:
161
+ count:
162
+ type: integer
163
+ description: The number of connected workers.
164
+ generatedAt:
165
+ type: string
166
+ description: When this snapshot was taken, ISO-8601.
167
+ workers:
168
+ type: array
169
+ items:
170
+ $ref: "#/components/schemas/AgenticSupplyWorker"
171
+ leaves:
172
+ type: array
173
+ items:
174
+ $ref: "#/components/schemas/AgenticSupplyLeaf"
102
175
  VersionInfo:
103
176
  type: object
104
177
  description: The running app's identity (which code is actually live).
@@ -509,6 +582,27 @@ paths:
509
582
  application/json:
510
583
  schema:
511
584
  $ref: "#/components/schemas/ErrorBody"
585
+ /agentic/supply:
586
+ get:
587
+ operationId: getAgenticSupply
588
+ summary: The SUPPLY-ONLY agentic visibility report — the live worker list (family, host, current jobs,
589
+ liveness) grouped by leaf, sourced from the H1 presence registry. Feeds the H5 cockpit page.
590
+ security:
591
+ - hookSecret: []
592
+ - {}
593
+ responses:
594
+ "200":
595
+ description: The supply report.
596
+ content:
597
+ application/json:
598
+ schema:
599
+ $ref: "#/components/schemas/AgenticSupplyReport"
600
+ "401":
601
+ description: Missing/invalid shared secret (only when NANO_PR_WEBHOOK_SECRET is set).
602
+ content:
603
+ application/json:
604
+ schema:
605
+ $ref: "#/components/schemas/ErrorBody"
512
606
  /version:
513
607
  get:
514
608
  operationId: getVersion
@@ -0,0 +1,153 @@
1
+ // Tests for GET /app/api/agentic/supply → operation `getAgenticSupply` (H5 / #148).
2
+ //
3
+ // Covers: the empty report when no presence family is mounted; the shared-secret guard; and the
4
+ // end-to-end mapping of a mounted presence registry's snapshot into the supply report (stream keyed
5
+ // by instance, family/host/jobKeys/liveness) — driven through a REAL AgenticHub + in-memory transport
6
+ // exactly as the presence family is exercised, so the singleton the operation reads is the live one.
7
+ import { DatabaseSync } from "node:sqlite";
8
+ import { test } from "node:test";
9
+ import { AgenticHub } from "@nanobpm/agentic/channel";
10
+ import type { Authenticator, ChannelConnection, ChannelTransport } from "@nanobpm/agentic/channel";
11
+ import { encodeFrame, type Frame } from "@nanobpm/agentic/protocol";
12
+ import type { SqliteDb } from "@nanobpm/agentic/presence";
13
+ import type { AppApi, DataLayer } from "@nanobpm/urban";
14
+ import { assert, assertEquals } from "#test-assert";
15
+ import { family } from "../app/agentic/families/presence.family.ts";
16
+ import type { AgenticContext } from "../app/agentic/registry.ts";
17
+ import { noopLog } from "../test/log.ts";
18
+ import handler from "./getAgenticSupply.ts";
19
+
20
+ function memSqlite(): SqliteDb {
21
+ const db = new DatabaseSync(":memory:");
22
+ return {
23
+ exec: (sql) => db.exec(sql),
24
+ run: (sql, params = []) => {
25
+ const r = db.prepare(sql).run(...(params as never[]));
26
+ return { changes: Number(r.changes), lastInsertRowid: Number(r.lastInsertRowid) };
27
+ },
28
+ all: <T = Record<string, unknown>>(sql: string, params: unknown[] = []) =>
29
+ db.prepare(sql).all(...(params as never[])) as T[],
30
+ };
31
+ }
32
+
33
+ function memData(db: SqliteDb): DataLayer {
34
+ return { source: () => ({ db }) } as unknown as DataLayer;
35
+ }
36
+
37
+ function memTransport(): { transport: ChannelTransport; connect(conn: ChannelConnection): void } {
38
+ let onConnection: ((conn: ChannelConnection) => void) | undefined;
39
+ const transport: ChannelTransport = {
40
+ onConnection: (l) => {
41
+ onConnection = l;
42
+ },
43
+ address: { port: 0 },
44
+ close: async () => {},
45
+ };
46
+ return { transport, connect: (conn) => onConnection?.(conn) };
47
+ }
48
+
49
+ function fakeConn(id: string, identity: string): { conn: ChannelConnection; feed(frame: Frame): void } {
50
+ let onMessage: ((bytes: Uint8Array) => void) | undefined;
51
+ const conn: ChannelConnection = {
52
+ id,
53
+ handshake: { query: { identity }, token: "t", credential: "c" },
54
+ send: () => {},
55
+ close: () => {},
56
+ onMessage: (l) => {
57
+ onMessage = l;
58
+ },
59
+ onClose: () => {},
60
+ };
61
+ return { conn, feed: (frame) => onMessage?.(encodeFrame(frame)) };
62
+ }
63
+
64
+ const authenticator: Authenticator = (req) => ({ ok: true, grant: { identity: req.query?.identity ?? "anon" } });
65
+ const flush = () => new Promise((resolve) => setImmediate(resolve));
66
+
67
+ async function mountPresence(db: SqliteDb): Promise<AgenticHub> {
68
+ const transport = memTransport();
69
+ const hub = new AgenticHub({ transport: transport.transport, authenticator, sweepIntervalMs: 0 });
70
+ const ctx: AgenticContext = {
71
+ hub,
72
+ registry: hub.registry,
73
+ transport: transport.transport as never,
74
+ data: memData(db),
75
+ log: noopLog(),
76
+ };
77
+ await family.mount(ctx);
78
+ // Register one live worker under leaf "leafA" with declared family + host.
79
+ const peer = fakeConn("c1", "leafA");
80
+ transport.connect(peer.conn);
81
+ await flush();
82
+ peer.feed({ lane: "control", family: "register", seq: 1, payload: { instance: "wk-a", capability: { family: "opus", host: "boxA" } } });
83
+ await flush();
84
+ return hub;
85
+ }
86
+
87
+ function input(headers: Record<string, string> = {}) {
88
+ return {
89
+ req: {
90
+ method: "GET",
91
+ path: "/app/api/agentic/supply",
92
+ query: new URLSearchParams(),
93
+ headers: new Headers(headers),
94
+ text: async () => "",
95
+ } as never,
96
+ params: {},
97
+ query: {},
98
+ body: undefined,
99
+ };
100
+ }
101
+
102
+ const app = { log: noopLog() } as unknown as AppApi;
103
+
104
+ test("returns an empty supply report when no presence family is mounted", async () => {
105
+ family.teardown?.();
106
+ const res = (await handler(input(), app)) as { status: number; body: { count: number; workers: unknown[]; leaves: unknown[] } };
107
+ assertEquals(res.status, 200);
108
+ assertEquals(res.body.count, 0);
109
+ assertEquals(res.body.workers.length, 0);
110
+ assertEquals(res.body.leaves.length, 0);
111
+ });
112
+
113
+ test("maps the presence snapshot into the supply report (stream, family, host, liveness)", async () => {
114
+ const hub = await mountPresence(memSqlite());
115
+ try {
116
+ const res = (await handler(input(), app)) as {
117
+ status: number;
118
+ body: { count: number; workers: Array<Record<string, unknown>>; leaves: Array<{ token: string; workers: unknown[] }> };
119
+ };
120
+ assertEquals(res.status, 200);
121
+ assertEquals(res.body.count, 1);
122
+ const w = res.body.workers[0];
123
+ assertEquals(w.instance, "wk-a");
124
+ assertEquals(w.identity, "leafA");
125
+ assertEquals(w.stream, "wk-a", "the drill stream is keyed by the worker instance");
126
+ assertEquals(w.family, "opus");
127
+ assertEquals(w.host, "boxA");
128
+ assertEquals(w.live, true);
129
+ assertEquals(w.jobKeys, []);
130
+ assertEquals(res.body.leaves[0]?.token, "leafA");
131
+ assertEquals(res.body.leaves[0]?.workers.length, 1);
132
+ } finally {
133
+ family.teardown?.();
134
+ await hub.close();
135
+ }
136
+ });
137
+
138
+ test("shared-secret guard rejects a missing secret when configured", async () => {
139
+ const prev = process.env["NANO_PR_WEBHOOK_SECRET"];
140
+ process.env["NANO_PR_WEBHOOK_SECRET"] = "s3cr3t";
141
+ try {
142
+ const mod = await import(`./getAgenticSupply.ts?guard=${Date.now()}`);
143
+ const guarded = mod.default as typeof handler;
144
+ const bad = (await guarded(input(), app)) as { status: number };
145
+ assertEquals(bad.status, 401);
146
+ const ok = (await guarded(input({ "x-hook-secret": "s3cr3t" }), app)) as { status: number; body: Record<string, unknown> };
147
+ assertEquals(ok.status, 200);
148
+ assert("count" in ok.body);
149
+ } finally {
150
+ if (prev === undefined) delete process.env["NANO_PR_WEBHOOK_SECRET"];
151
+ else process.env["NANO_PR_WEBHOOK_SECRET"] = prev;
152
+ }
153
+ });