From 35517d1aaafef8a307f16df1d2f3c6838bb396b6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 16:21:47 +0200 Subject: [PATCH 1/3] feat(daemon,gateway,cli): status and the worker list report host facts (#181) status.get gains a required host block: operating system, version, CPU architecture from a new host port, and each driver's tool versions (Xcode from xcodebuild -version; Android emulator, platform-tools and cmdline-tools from source.properties). Served from memory and re-read in the background once older than 60 s. A gateway reports its own host with no tools and copies each worker's host into its view; an incompatible worker's view has none. The Android driver takes the host ABI from the composition root. Worker list samples in the docs are replaced with real output. --- docs/CLI.md | 120 ++++++++++++++++++++++------ docs/CLIENT.md | 21 +++++ docs/HTTP-API.md | 119 ++++++++++++++++++++++----- docs/internal/ARCHITECTURE.md | 56 ++++++++----- e2e/fake-driver/fake-driver.ts | 7 ++ e2e/fake-driver/types.ts | 6 ++ e2e/gateway-fleet.test.ts | 45 +++++++++++ src/cli/index.test.ts | 61 ++++++++++++++ src/cli/index.ts | 15 +++- src/contract/doc-samples.test.ts | 41 ++++++++++ src/contract/operations.test.ts | 14 ++++ src/contract/operations.ts | 6 ++ src/contract/schemas.ts | 29 +++++++ src/core/driver.ts | 18 +++++ src/core/host-facts.test.ts | 82 +++++++++++++++++++ src/core/host-facts.ts | 96 ++++++++++++++++++++++ src/core/index.ts | 2 + src/daemon/dispatcher.test.ts | 64 +++++++++++++++ src/daemon/dispatcher.ts | 4 + src/daemon/main.test.ts | 79 +++++++++++++++++- src/daemon/main.ts | 29 +++++++ src/daemon/server.test.ts | 1 + src/daemon/server.ts | 4 + src/drivers/android/index.test.ts | 43 ++++++++++ src/drivers/android/index.ts | 60 +++++++++++--- src/drivers/ios/index.test.ts | 33 ++++++++ src/drivers/ios/index.ts | 23 ++++++ src/gateway/aggregate.test.ts | 31 ++++--- src/gateway/aggregate.ts | 3 + src/gateway/dispatcher.test.ts | 16 ++++ src/gateway/dispatcher.ts | 5 +- src/gateway/service.test.ts | 41 ++++++++++ src/gateway/test-support.ts | 14 ++++ src/gateway/worker-link.ts | 1 + src/gateway/worker-registry.test.ts | 21 ++++- src/gateway/worker-registry.ts | 8 +- src/ports/host-info.test.ts | 45 +++++++++++ src/ports/host-info.ts | 70 ++++++++++++++++ src/ports/index.ts | 1 + src/simlock-client/client.test.ts | 51 ++++++++++++ 40 files changed, 1290 insertions(+), 95 deletions(-) create mode 100644 src/contract/doc-samples.test.ts create mode 100644 src/core/host-facts.test.ts create mode 100644 src/core/host-facts.ts create mode 100644 src/ports/host-info.test.ts create mode 100644 src/ports/host-info.ts diff --git a/docs/CLI.md b/docs/CLI.md index 76babe5b0..97cf44da5 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -716,9 +716,10 @@ the `admin` role (see [Admin credential resolution](#admin-credential-resolution)). A worker has no workers of its own, so it does not implement these operations at all and answers `UNKNOWN_REQUEST` — they are not a gateway-mode refusal of something a worker -could otherwise do, they are simply not part of a worker's surface. Output is -JSON on stdout, unconditionally — `--json` is a usage error (exit 2), as -everywhere except `status`/`catalog`/`daemon`. +could otherwise do, they are simply not part of a worker's surface. `list` +prints one line per worker, or the views as JSON with `--json`; `drain`, +`undrain` and `remove` print JSON on stdout, unconditionally — `--json` is a +usage error (exit 2) for those three. ``` simlock worker list @@ -727,26 +728,86 @@ simlock worker undrain simlock worker remove ``` -`list` prints one worker view per connected-or-remembered worker: +`list --json` prints one worker view per connected-or-remembered worker. A +real answer, trimmed to one worker: ```json -{"workers":[{"id":"3f81a2c4","label":"mac-studio-2","state":"connected","drained":false, - "daemonVersion":"0.4.0","protocol":{"min":7,"max":7}, - "connectedAt":1735689600000,"lastSeenAt":1735689930000, - "capacity":{"ios":{"running":2,"limit":4},"android":{"running":0,"limit":2}}, - "downloads":{"policy":"on-request"}, - "queueDepth":0,"leases":3,"devices":5}]} +{ + "workers": [ + { + "id": "2b026432-7743-4a08-98fc-ce494d11866f", + "label": "worker-a", + "connection": "connected", + "drained": false, + "lastSeenAt": 1790864080506, + "health": "running", + "version": "1.0.0", + "capacity": { + "ios": { + "running": 0, + "maxRunning": 8, + "reserved": 0, + "overLimit": false, + "limit": 8, + "warm": 0, + "used": 0 + }, + "android": { + "running": 0, + "maxRunning": 8, + "reserved": 0, + "overLimit": false, + "limit": 8, + "warm": 0, + "used": 0 + }, + "global": {"running": 0, "maxRunning": 8, "reserved": 0, "overLimit": false, "warm": 0} + }, + "downloads": {"policy": "on-request"}, + "lease": {"maxTtlMs": 14400000}, + "queueDepth": 0, + "leases": [], + "devices": [], + "catalog": [ + { + "platform": "ios", + "models": ["iPhone 16"], + "runtimes": ["18.4", "26.0"], + "defaultRuntime": "26.0", + "modelRuntimes": {"iPhone 16": ["18.4"]} + }, + { + "platform": "android", + "models": [], + "runtimes": ["18.0"], + "defaultRuntime": "18.0", + "modelRuntimes": {} + } + ], + "host": { + "os": "macOS", + "osVersion": "26.6.1", + "arch": "arm64", + "tools": [{"platform": "ios", "name": "xcode", "version": "16.4", "build": "16F6"}] + } + } + ] +} ``` -`downloads.policy` is that worker's own effective policy, read once with -`config.get` when its uplink connects — routing needs it to know whether a -machine may install a missing runtime before sending it a request that needs -one. `protocol` is the range that worker negotiated; the wire moves -to `{min: 7, max: 7}` with no shim, so a worker older than it does not -overlap and shows as `incompatible`. Worker ids are UUIDs — the examples here -abbreviate them to their first segment. - -`state` is `connected`, `disconnected`, or `incompatible`. A **disconnected** +`downloads.policy` and `lease.maxTtlMs` are that worker's own effective +config, read when its uplink connects and again on every periodic refresh — +routing needs the policy to know whether a machine may install a missing +runtime before sending it a request that needs one. `catalog` is what that +worker can lease, each model with the runtimes it pairs with. `host` is the +machine: operating system, its version, CPU architecture, and the version of +each platform tool its drivers use (`xcode` with its build; the Android +`emulator`, `platform-tools` and `cmdline-tools`). A tool the worker cannot +read is left out. `protocol` appears only on an `incompatible` worker and +names both ranges, the worker's and the gateway's, so you can see which side +to upgrade. Worker ids are UUIDs; the human listing below abbreviates them. + +`connection` is `connected`, `disconnected`, or `incompatible`. A **disconnected** worker keeps its last-known view (nothing is dispatched to it) until an operator removes it or `gateway.disconnectedRetentionMs` (24 hours) elapses. The retention clock is held while the gateway still knows of gateway-issued @@ -889,7 +950,8 @@ A device currently `provisioning` or `reclaiming` carries a derived and `list --devices` well before it crosses the threshold that would make `doctor` flag it as stalled. -Human-oriented overview: daemon health *and mode*, managed capacity +Human-oriented overview: daemon health *and mode*, the host it runs on +(`Host: macOS 15.5 arm64; xcode 16.4 (16F6), emulator 35.4.9`), managed capacity (used/limit per platform), running and reserved capacity (globally and per platform), every managed device with its state and device mode (`Device dev_7: ready, mode slim`), current leases (who — the agent @@ -907,7 +969,14 @@ lives on (`Device dev_7 on wrk_a: leased, mode full`). `--json` gains a `workers device and lease; `daemon.mode` says which kind of daemon answered. The daemon block carries `mode` (`"worker"` or `"gateway"`) — the one field -that tells a client which kind of daemon answered. Do not confuse it with each +that tells a client which kind of daemon answered. Beside it, `host` says +what machine the daemon runs on: `os`, `osVersion`, `arch`, and `tools`, one +entry per platform tool its drivers use with the `platform`, `name`, +`version` and, for Xcode, `build`. Tool versions are read when the daemon +starts and again in the background once a minute has passed, so `status` +never waits for them; right after a start, or for a tool that cannot be read, +`tools` has no entry. A gateway runs no drivers, so its own `host` has no +tools; each worker's is on its worker view. Do not confuse it with each device's own `mode`, the device mode (`"slim"` or `"full"`). Against a **gateway** the same view is the fleet's: capacity summed over the connected workers, every lease and device tagged with the `workerId` it lives on, the gateway queue's @@ -1166,8 +1235,9 @@ operation **on a gateway**; against a worker they answer `UNKNOWN_REQUEST` - `list [--json]` — one line per worker: its id (the worker's own instance identity — stable across restarts, and not its label or host name), its - label if it set one, connection state, capacity, and how many leases it - holds. A worker the gateway cannot speak to shows `incompatible` with both + label if it set one, connection state, capacity, how many leases it + holds, and its host: operating system, version, architecture, and tool + versions. A worker the gateway cannot speak to shows `incompatible` with both protocol ranges, which is what version skew looks like from here. `--json` prints the raw worker views, which is what the console renders. - `drain ` / `undrain ` — a drained worker keeps its @@ -1187,8 +1257,8 @@ operation **on a gateway**; against a worker they answer `UNKNOWN_REQUEST` ```console $ simlock worker list -wrk_9f2c (mac-mini-1): connected -- ios 1/2, android 0/1, 1 lease(s) -wrk_4a10 (ci-runner-3): disconnected, drained -- ios 0/4, android 0/2, 0 lease(s) +wrk_9f2c (mac-mini-1): connected -- ios 1/2, android 0/1, 1 lease(s) -- macOS 15.5 arm64; xcode 16.4 (16F6), emulator 35.4.9 +wrk_4a10 (ci-runner-3): disconnected, drained -- ios 0/4, android 0/2, 0 lease(s) -- macOS 14.7 x64; xcode 16.2 (16C5032a) ``` ## `simlock config [get |set ]` diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 12255686d..dd2210a5a 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -205,6 +205,27 @@ runtime. The gateway does not yet use the pairings to pick a worker, so a pair it lists can still go to a worker that has the model and the runtime but cannot pair them, and that request fails there. +## What machine answered: `getStatus().host` + +`getStatus()` carries a `host` block beside `daemon`: the machine the daemon +runs on, worked out from the machine itself. + +```ts +const { host } = await client.getStatus(); +// { os: "macOS", osVersion: "15.5", arch: "arm64", +// tools: [{ platform: "ios", name: "xcode", version: "16.4", build: "16F6" }, +// { platform: "android", name: "emulator", version: "35.4.9" }] } +``` + +- `tools` has one entry per platform tool the daemon's drivers use. A tool + that cannot be read is left out, and right after a daemon starts the list + can be empty for a moment: versions are read in the background, so + `getStatus` never waits for them. They are read again once a minute has + passed. +- A gateway reports its own machine with no tools, since it runs no + drivers. Each worker's `host` is on its entry in `workers`, and on + `listWorkers()` from the admin client. + ## One connection, no reconnect, no retry This is the one thing to internalize before building anything on top of this diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 2b4b5bdc5..5d7d24ea7 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -139,6 +139,23 @@ daemon answered: { "daemon": { "health": "running", "mode": "worker" } } ``` +Beside it, **`host`** says what machine the daemon runs on: the operating +system, its version, the CPU architecture, and the version of each platform +tool its drivers use: + +```json +"host": { "os": "macOS", "osVersion": "15.5", "arch": "arm64", + "tools": [ { "platform": "ios", "name": "xcode", "version": "16.4", "build": "16F6" }, + { "platform": "android", "name": "emulator", "version": "35.4.9" }, + { "platform": "android", "name": "platform-tools", "version": "36.0.0" }, + { "platform": "android", "name": "cmdline-tools", "version": "19.0" } ] } +``` + +The daemon works these out from the machine; no config key changes them. Tool +versions are read at start and again in the background once a minute has +passed, so this endpoint never waits for them. Right after a start, or for a +tool that cannot be read, `tools` has no entry for it. + On a **gateway** the numbers are the fleet's — capacity summed across connected workers, every gateway-issued and local lease, every device, the gateway queue's depth — every lease and device carries the **`workerId`** it lives @@ -147,10 +164,13 @@ on, and an additive **`workers`** array carries one ```json { "daemon": { "health": "running", "mode": "gateway" }, - "workers": [ { "id": "3f81a2c4", "label": "mac-studio-2", "state": "connected", "drained": false } ] } + "host": { "os": "Linux", "osVersion": "6.8.0", "arch": "x64", "tools": [] }, + "workers": [ { "id": "3f81a2c4", "label": "mac-studio-2", "connection": "connected", "drained": false } ] } ``` -On a worker, `workers` is absent and `workerId` never appears. A client that +A gateway's own `host` is the gateway's machine and has no tools, since it +runs no drivers; each worker's is on its worker view. On a worker, `workers` +is absent and `workerId` never appears. A client that reads neither cannot tell the difference, which is the point. ### `GET /v1/catalog?platform=ios|android` @@ -585,30 +605,89 @@ workers of its own and does not implement the underlying operations at all. - `DELETE /v1/workers/{id}/drain` — undrain it, putting it back in rotation. - `DELETE /v1/workers/{id}` — forget a worker's view. +`GET /v1/workers`, a real answer trimmed to one worker: + ```json -{ "workers": [ { - "id": "3f81a2c4", "label": "mac-studio-2", - "state": "connected", "drained": false, - "daemonVersion": "0.4.0", "protocol": { "min": 7, "max": 7 }, - "connectedAt": "2026-09-01T09:00:00Z", "lastSeenAt": "2026-09-01T09:14:30Z", - "capacity": { "ios": { "running": 2, "limit": 4 }, "android": { "running": 0, "limit": 2 } }, - "downloads": { "policy": "on-request" }, - "queueDepth": 0, "leases": 3, "devices": 5 -} ] } +{ + "workers": [ + { + "id": "2b026432-7743-4a08-98fc-ce494d11866f", + "label": "worker-a", + "connection": "connected", + "drained": false, + "lastSeenAt": 1790864080506, + "health": "running", + "version": "1.0.0", + "capacity": { + "ios": { + "running": 0, + "maxRunning": 8, + "reserved": 0, + "overLimit": false, + "limit": 8, + "warm": 0, + "used": 0 + }, + "android": { + "running": 0, + "maxRunning": 8, + "reserved": 0, + "overLimit": false, + "limit": 8, + "warm": 0, + "used": 0 + }, + "global": {"running": 0, "maxRunning": 8, "reserved": 0, "overLimit": false, "warm": 0} + }, + "downloads": {"policy": "on-request"}, + "lease": {"maxTtlMs": 14400000}, + "queueDepth": 0, + "leases": [], + "devices": [], + "catalog": [ + { + "platform": "ios", + "models": ["iPhone 16"], + "runtimes": ["18.4", "26.0"], + "defaultRuntime": "26.0", + "modelRuntimes": {"iPhone 16": ["18.4"]} + }, + { + "platform": "android", + "models": [], + "runtimes": ["18.0"], + "defaultRuntime": "18.0", + "modelRuntimes": {} + } + ], + "host": { + "os": "macOS", + "osVersion": "26.6.1", + "arch": "arm64", + "tools": [{"platform": "ios", "name": "xcode", "version": "16.4", "build": "16F6"}] + } + } + ] +} ``` -`downloads.policy` is that worker's own effective policy, read once with -`config.get` when its uplink connects. Routing needs it to know whether a -worker may install a missing runtime at all before sending it a request that -depends on one; it is never an override, since the worker clamps +`downloads.policy` is that worker's own effective policy, read when its +uplink connects and again on every periodic refresh. Routing needs it to know +whether a worker may install a missing runtime at all before sending it a +request that depends on one; it is never an override, since the worker clamps `allowDownload` through the same policy regardless. -`protocol` is the range that worker negotiated. The wire moves to -`{min: 7, max: 7}` with no compatibility shim, so a worker from before it -does not overlap and shows as `incompatible` — the ordinary upgrade path, not -a fault. +`catalog` is what that worker can lease, each model with the runtimes it +pairs with. `host` is the worker's machine, the same block its own +`GET /v1/status` reports, as of the gateway's last refresh: a tool installed +or upgraded on the worker shows here without a restart of either side. + +`protocol` appears only on an `incompatible` worker: it names both ranges, +the worker's and the gateway's, so you can see which side to upgrade. A worker +too old to overlap is the ordinary upgrade path, not a fault, and its view +carries no `host`, since the gateway asks it nothing. -`state` is `connected`, `disconnected`, or `incompatible`. A worker view is +`connection` is `connected`, `disconnected`, or `incompatible`. A worker view is rebuilt over the uplink and never persisted, so these are current facts, not a registry: a worker appears by connecting, and there is deliberately no route that *adds* one. diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 85d8e0390..d63811f68 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -147,10 +147,11 @@ agent / console ──token auth──> │ HTTP frontend + unix socket worker's own `instance.json` identity), label, connection state (`connected` / `disconnected` / `incompatible`), daemon health and version, capacity per platform, download policy, queue depth, leases, devices, - catalog, drain state, and a last-seen timestamp. It is rebuilt over the - uplink — `status.get`, `list.get`, `catalog.get`, `config.get` and - `events.subscribe` on connect, a refresh on every worker event about a lease - or a device, and a slow periodic tick as a backstop — and never persisted. + catalog, host facts, drain state, and a last-seen timestamp. It is rebuilt + over the uplink — `status.get`, `list.get`, `catalog.get`, `config.get` and + `events.subscribe` on connect, a refresh of status and devices on every + worker event about a lease or a device, and a slow periodic tick that also + re-reads the catalog and config — and never persisted. A gateway restart re-derives every view from the workers that reconnect. - **The uplink is the reachability signal**: no polling. A closed uplink flips the view to `disconnected` immediately and keeps its last-known state, so a @@ -452,23 +453,35 @@ manually-advanced `Clock`, exactly as the core's tests script drivers. ### The worker view A **worker view** is what the gateway currently knows about one worker: its -id, `label`, daemon health and version, negotiated protocol range, capacity -per platform, queue depth, leases, devices, catalog, effective download -policy, and drain state. On connect the gateway calls `status.get`, -`list.get`, `catalog.get`, `config.get`, and `events.subscribe` on the worker -and builds the view from the answers; it refreshes status and list on every -worker event that changes capacity or leases, and on a slow periodic tick as -a backstop. - -`config.get` is the one of those read **once per connect** rather than on the -refresh path: config is daemon input, read at start, so a worker whose -`downloads.policy` changed has already restarted and reconnected. It is an -admin operation, which the uplink session is. The gateway keeps exactly one -field out of it — the effective `downloads.policy` — because routing has to -know whether a worker is even *allowed* to install a missing runtime before -it sends that worker a request which depends on one. It is a routing input -and never an override: the worker still clamps `allowDownload` through its -own policy, whatever the view said. +id, `label`, daemon health and version, negotiated protocol range (only when +`incompatible`), capacity per platform, queue depth, leases, devices, +catalog, host facts, effective download policy and `lease.maxTtlMs`, and +drain state. On connect the gateway calls `status.get`, `list.get`, +`catalog.get`, `config.get`, and `events.subscribe` on the worker and builds +the view from the answers. It refreshes status and list on every worker event +that changes capacity or leases. A slow periodic tick refreshes all four +reads, catalog and config included, so a runtime installed on a worker +reaches its view without a restart of either side. + +The **host facts** are the `host` block of the worker's `status.get` +(ADR 0008 §5-§8): operating system, version, architecture from the host +port, read once at the worker's start, and tool versions from each driver's +`toolVersions()`, joined in `core/host-facts.ts`. The worker serves them from +memory, so `status.get` stays a liveness probe that never starts a process; +a stale value starts a background re-read after 60 s. They come over on every +status refresh. An `incompatible` worker is asked nothing, so its view +carries none. A gateway's own `status.get` reports the gateway's machine with +no tools. + +From `config.get` the gateway keeps two fields. The effective +`downloads.policy`, because routing has to know whether a worker is even +*allowed* to install a missing runtime before it sends that worker a request +which depends on one. It is a routing input and never an override: the +worker still clamps `allowDownload` through its own policy, whatever the view +said. And `lease.maxTtlMs`, compared against the gateway's own to warn when a +worker's cap is lower. Config is daemon input, read at start, so these change +only across a worker restart; re-reading them on the tick costs one call. +`config.get` is an admin operation, which the uplink session is. The view is **rebuilt, never persisted**. A gateway restart loses nothing it cannot ask for again, and a worker stays the authority on its own state. Two @@ -1338,6 +1351,7 @@ Filesystem — read/write/delete/stat/disk-free ProcessRunner — spawn/exec/kill, capture stdout/stderr Clock — now(), timers (no direct Date/setTimeout in logic) SystemStats — cpu count, total/free RAM, disk free +HostInfo — operating system, its version, CPU architecture (`sw_vers` on macOS) IpcConnector / IpcListenerFactory — connect to and host daemon IPC endpoints DaemonLauncher — detached daemon startup with append-only combined logs Logger — debug/info/warn/error(message, fields) plus child(module) scoping diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index cda5daf86..035665690 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -12,6 +12,7 @@ import { type DriverDevice, type DriverEstimate, type DriverReality, + type DriverToolVersion, type ObservedMark, type ObservedRunState, type PassthroughCommand, @@ -329,6 +330,12 @@ export class OutOfProcessFakeDriver implements Driver { }; } + /** Read straight from the script, not through `#beforeCall`: the daemon asks for these on + * its own schedule, and a test's call log should hold only what the test caused. */ + async toolVersions(): Promise { + return (await this.#readScript()).toolVersions ?? []; + } + async listCatalog(): Promise { const script = await this.#beforeCall("listCatalog", []); const runtimes = [ diff --git a/e2e/fake-driver/types.ts b/e2e/fake-driver/types.ts index beee90c51..5337d7ba1 100644 --- a/e2e/fake-driver/types.ts +++ b/e2e/fake-driver/types.ts @@ -61,6 +61,12 @@ export interface FakeDriverPlatformScript { * version, which is also the default for every model. */ readonly modelRuntimes?: Readonly>; + /** What `toolVersions` reports for `status.get`'s host facts. None by default. */ + readonly toolVersions?: readonly { + readonly name: string; + readonly version: string; + readonly build?: string; + }[]; readonly latencyMs?: Partial>; readonly estimateMs?: Partial>; readonly reclaimResult?: "ready" | "shutdown"; diff --git a/e2e/gateway-fleet.test.ts b/e2e/gateway-fleet.test.ts index 1f487b737..d2b9f4352 100644 --- a/e2e/gateway-fleet.test.ts +++ b/e2e/gateway-fleet.test.ts @@ -24,6 +24,17 @@ interface WorkerView { readonly models: readonly string[]; readonly modelRuntimes: Readonly>; }[]; + readonly host?: { + readonly os: string; + readonly osVersion: string; + readonly arch: string; + readonly tools: readonly { + readonly platform: string; + readonly name: string; + readonly version: string; + readonly build?: string; + }[]; + }; } interface StatusView { @@ -243,6 +254,7 @@ describe("gateway fleet", () => { availableOsVersions: installed, knownModels: ["iPhone 16"], modelRuntimes: { "iPhone 16": ["18.4"] }, + toolVersions: [{ build: "16F6", name: "xcode", version: "16.4" }], }, }, }); @@ -253,6 +265,7 @@ describe("gateway fleet", () => { availableOsVersions: installed, knownModels: ["iPhone 16"], modelRuntimes: { "iPhone 16": ["26.0"] }, + toolVersions: [{ build: "17A324", name: "xcode", version: "26.0" }], }, }, }); @@ -271,6 +284,38 @@ describe("gateway fleet", () => { expect(pairingOf("worker-a")).toEqual({ "iPhone 16": ["18.4"] }); expect(pairingOf("worker-b")).toEqual({ "iPhone 16": ["26.0"] }); + // Each worker's host facts sit beside its catalog, tools included once the worker has read + // them; `GET /v1/workers` serves the same views. + const xcodeOf = (views: readonly WorkerView[], label: string) => + views.find((view) => view.label === label)?.host?.tools.find((tool) => tool.name === "xcode"); + const withTools = await waitForWorkers( + gateway, + (views) => + xcodeOf(views, "worker-a") !== undefined && xcodeOf(views, "worker-b") !== undefined, + "both workers report their tool versions", + ); + expect(xcodeOf(withTools, "worker-a")).toEqual({ + build: "16F6", + name: "xcode", + platform: "ios", + version: "16.4", + }); + expect(xcodeOf(withTools, "worker-b")).toMatchObject({ version: "26.0" }); + for (const view of withTools) { + expect(view.host).toMatchObject({ arch: expect.any(String), os: expect.any(String) }); + } + const operator = await gateway.cli(["token", "create", "--role", "operator"]); + const response = await fetch(`http://127.0.0.1:${port}/v1/workers`, { + headers: { authorization: `Bearer ${(operator.json as { secret: string }).secret}` }, + }); + expect(response.status).toBe(200); + const overHttp = ((await response.json()) as { workers: WorkerView[] }).workers; + expect(xcodeOf(overHttp, "worker-a")?.version).toBe("16.4"); + expect( + overHttp.find((view) => view.label === "worker-b")?.catalog.find((e) => e.platform === "ios") + ?.modelRuntimes, + ).toEqual({ "iPhone 16": ["26.0"] }); + const catalog = await gateway.cli(["catalog", "--json"]); expect(catalog.code).toBe(0); const ios = ( diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 99f4235e1..68a84b8c2 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1749,6 +1749,38 @@ describe("CLI: worker commands (ADR 0005 §8/§23)", () => { expect(output.stdout).toContain("1 lease(s)"); }); + it("prints each worker's operating system, architecture, and tool versions", async () => { + const output = outputCapture(); + const environment = output.environmentWith({ + connectAdmin: async () => + fakeClient({ + listWorkers: () => + Promise.resolve({ + workers: [ + { + ...connectedWorker, + host: { + arch: "arm64", + os: "macOS", + osVersion: "15.5", + tools: [ + { build: "16F6", name: "xcode", platform: "ios" as const, version: "16.4" }, + { name: "emulator", platform: "android" as const, version: "35.4.9" }, + ], + }, + }, + ], + }), + }), + }); + + await runCli(["worker", "list"], environment); + + expect(output.stdout).toContain( + "1 lease(s) -- macOS 15.5 arm64; xcode 16.4 (16F6), emulator 35.4.9", + ); + }); + it("says so plainly when no worker has ever connected", async () => { const output = outputCapture(); const environment = output.environmentWith({ connectAdmin: async () => fakeClient() }); @@ -1900,6 +1932,7 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = }, }, daemon: { health: "running" as const, mode: "gateway" as const }, + host: { arch: "x64", os: "Linux", osVersion: "6.8.0", tools: [] }, devices: [ { id: "dev_1", @@ -1948,6 +1981,31 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = expect(output.stdout).toContain("Lease lease_1: agent-1 on wrk_1"); }); + it("prints the host line", async () => { + const output = outputCapture(); + const environment = output.environmentWith({ + connectAdmin: async () => + fakeClient({ + getStatus: () => + Promise.resolve({ + ...EMPTY_STATUS, + host: { + arch: "arm64", + os: "macOS", + osVersion: "15.5", + tools: [ + { build: "16F6", name: "xcode", platform: "ios" as const, version: "16.4" }, + ], + }, + }), + }), + }); + + await runCli(["status"], environment); + + expect(output.stdout).toContain("Host: macOS 15.5 arm64; xcode 16.4 (16F6)\n"); + }); + it("says worker on a worker, and leaves its devices and leases unqualified", async () => { const output = outputCapture(); const environment = output.environmentWith({ connectAdmin: async () => fakeClient() }); @@ -3432,6 +3490,7 @@ function simlockError(code: AnySimlockError["code"]): AnySimlockError { * `mode` -- which is what the passthrough path branches on (ADR 0005 §19c). */ const EMPTY_STATUS: StatusGetOutput = { devices: [], + host: { arch: "arm64", os: "macOS", osVersion: "15.5", tools: [] }, leases: [], capacity: { ios: { limit: 1, running: 0, maxRunning: 1, reserved: 0, overLimit: false, warm: 0, used: 0 }, @@ -3658,6 +3717,7 @@ async function startTestDaemon(): Promise<{ socketPath: string; daemon: DaemonSe filesystem: new NodeFilesystem(), listenerFactory: new NodeIpcTransport(), }), + hostFacts: () => ({ arch: "arm64", os: "macOS", osVersion: "15.5", tools: [] }), leases: engine, queue: engine, reaper, @@ -3773,6 +3833,7 @@ async function startInMemoryDaemon(options: { filesystem, listenerFactory: ipcTransport, }), + hostFacts: () => ({ arch: "arm64", os: "macOS", osVersion: "15.5", tools: [] }), leases: engine, queue: engine, reaper, diff --git a/src/cli/index.ts b/src/cli/index.ts index c16495418..6161ad0ea 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -1850,11 +1850,21 @@ function formatWorkers(workers: WorkerView[]): string { ? "" : ` protocol ${worker.protocol.worker.min}-${worker.protocol.worker.max}` + ` vs gateway ${worker.protocol.gateway.min}-${worker.protocol.gateway.max}`; - return `${label}: ${state} -- ${capacity}, ${String(worker.leases.length)} lease(s)${skew}`; + const host = worker.host === undefined ? "" : ` -- ${formatHost(worker.host)}`; + return `${label}: ${state} -- ${capacity}, ${String(worker.leases.length)} lease(s)${skew}${host}`; }) .join("\n"); } +/** `macOS 15.5 arm64; xcode 16.4 (16F6), emulator 35.4.9` -- the machine, then each tool. */ +function formatHost(host: StatusGetOutput["host"]): string { + const system = `${host.os} ${host.osVersion} ${host.arch}`; + const tools = host.tools.map( + (tool) => `${tool.name} ${tool.version}${tool.build === undefined ? "" : ` (${tool.build})`}`, + ); + return tools.length === 0 ? system : `${system}; ${tools.join(", ")}`; +} + function commandArgs( argv: readonly string[], options: NonNullable[0]>["options"], @@ -1973,7 +1983,7 @@ function writeResult(environment: CliEnvironment, value: unknown): void { // fallow-ignore-next-line complexity -- stable human status rendering is intentionally a single formatter. function formatStatus(status: StatusGetOutput): string { - const { capacity, daemon, devices, leases, queueDepth, workers } = status; + const { capacity, daemon, devices, host, leases, queueDepth, workers } = status; const globalLine = `Running global: ${capacity.global.running} + ${capacity.global.reserved} reserved/${capacity.global.maxRunning}, warm ${capacity.global.warm}${capacity.global.overLimit ? " (over limit)" : ""}`; const capacityLines = (["ios", "android"] as const).map((platform) => { const usage = capacity[platform]; @@ -2005,6 +2015,7 @@ function formatStatus(status: StatusGetOutput): string { ); return [ `Daemon: ${daemon.health} (${daemon.mode})`, + `Host: ${formatHost(host)}`, globalLine, ...capacityLines, ...workerLines, diff --git a/src/contract/doc-samples.test.ts b/src/contract/doc-samples.test.ts new file mode 100644 index 000000000..174e7544f --- /dev/null +++ b/src/contract/doc-samples.test.ts @@ -0,0 +1,41 @@ +import { readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { describe, expect, it } from "vitest"; + +import { OPERATIONS } from "./operations.js"; + +const docsDir = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "docs"); + +/** Every fenced JSON block in `markdown` whose top level is exactly `{ "workers": [...] }`. */ +function workerListSamples(markdown: string): unknown[] { + return [...markdown.matchAll(/```json\n([\s\S]*?)```/g)] + .map((match) => { + try { + return JSON.parse(match[1] ?? "") as unknown; + } catch { + return undefined; + } + }) + .filter( + (value): value is { workers: unknown } => + typeof value === "object" && + value !== null && + Object.keys(value).length === 1 && + "workers" in value, + ); +} + +describe("worker list samples in the docs", () => { + it.each(["HTTP-API.md", "CLI.md"])("%s's samples parse as worker.list's output", (file) => { + const samples = workerListSamples(readFileSync(join(docsDir, file), "utf8")); + + expect(samples.length).toBeGreaterThan(0); + for (const sample of samples) { + // Parsing drops fields the contract does not have, so comparing to the input also + // catches a sample that carries one. + expect(OPERATIONS["worker.list"].output.parse(sample)).toEqual(sample); + } + }); +}); diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 05c1d3400..dade3c577 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -278,6 +278,12 @@ describe("operation input/output round trips", () => { global: { running: 0, maxRunning: 2, reserved: 0, overLimit: false, warm: 0 }, }, daemon: { health: "running", mode: "worker" }, + host: { + os: "macOS", + osVersion: "15.5", + arch: "arm64", + tools: [{ platform: "ios", name: "xcode", version: "16.4", build: "16F6" }], + }, queueDepth: 0, }; expect(OPERATIONS["status.get"].output.parse(status)).toBeDefined(); @@ -322,6 +328,7 @@ describe("operation input/output round trips", () => { leases: [lease], capacity, daemon: { health: "running", mode: "gateway" }, + host: { os: "Linux", osVersion: "6.8.0", arch: "x64", tools: [] }, queueDepth: 0, workers: [ { @@ -333,6 +340,12 @@ describe("operation input/output round trips", () => { health: "running", version: "0.3.0", capacity, + host: { + os: "macOS", + osVersion: "15.5", + arch: "arm64", + tools: [{ platform: "android", name: "emulator", version: "35.4.9" }], + }, queueDepth: 0, leases: [lease], devices: [], @@ -358,6 +371,7 @@ describe("operation input/output round trips", () => { ], }); expect(parsed.workers?.[1]?.protocol?.worker).toEqual({ min: 3, max: 3 }); + expect(parsed.workers?.[0]?.host?.tools[0]?.name).toBe("emulator"); expect(parsed.devices[0]?.workerId).toBe("wrk_1"); expect(parsed.leases[0]?.workerId).toBe("wrk_1"); }); diff --git a/src/contract/operations.ts b/src/contract/operations.ts index fe04def62..0b553fa9c 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -18,6 +18,7 @@ import { deviceRecordSchema, doctorReportSchema, eventEnvelopeSchema, + hostFactsSchema, leaseGrantSchema, leaseRecordSchema, nukeReportSchema, @@ -101,6 +102,11 @@ export const statusGet = defineOperation({ * same protocol bump that added `mode`. */ daemon: z.object({ health: daemonHealthSchema, mode: daemonModeSchema }), + /** + * ADR 0008 §5: the machine, beside `daemon`, the process. Served from memory, so reading it + * never makes `status.get` wait. + */ + host: hostFactsSchema, queueDepth: z.number(), /** * ADR 0005 §20: one entry per worker view, additive and gateway-only. Absent (not empty) diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 3c78cf3f8..307099193 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -280,6 +280,32 @@ export const statusCapacitySchema = z.object({ export const daemonHealthSchema = z.enum(["starting", "running", "failed"]); +/** + * ADR 0008 §5: what machine a daemon runs on. Every string and the `tools` list are bounded, + * because a gateway stores what each worker reports in that worker's view (safety rule 10). + */ +const hostStringSchema = z.string().min(1).max(128); + +export const hostFactsSchema = z.object({ + /** Operating system product name (`macOS`), or the kernel name where there is none. */ + os: hostStringSchema, + osVersion: hostStringSchema, + /** CPU architecture as Node names it (`arm64`, `x64`). */ + arch: hostStringSchema, + /** The platform tools each driver uses, with the version installed. Empty on a gateway, which + * runs no drivers. */ + tools: z + .array( + z.object({ + platform: platformSchema, + name: hostStringSchema, + version: hostStringSchema, + build: hostStringSchema.optional(), + }), + ) + .max(32), +}); + export const platformCatalogSchema = z.object({ platform: platformSchema, models: z.array(z.string()), @@ -648,6 +674,9 @@ export const workerViewSchema = z.object({ leases: z.array(leaseRecordSchema), devices: z.array(statusDeviceSchema), catalog: z.array(platformCatalogSchema), + /** ADR 0008 §8: the `host` block of the worker's last `status.get`. Absent for a worker the + * gateway has not read status from, and for an `incompatible` one. */ + host: hostFactsSchema.optional(), }); /** diff --git a/src/core/driver.ts b/src/core/driver.ts index 7e8121557..15c205fce 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -146,6 +146,17 @@ export interface DriverAdvisory { readonly message: string; } +/** + * One platform tool a driver uses and the version installed (ADR 0008 §6). `name` and the + * version format are the driver's own; the core reports them and reads neither. + */ +export interface DriverToolVersion { + readonly name: string; + readonly version: string; + /** A build identifier the tool reports beside its version, when it has one. */ + readonly build?: string; +} + export interface Driver { readonly platform: Platform; /** @@ -275,6 +286,13 @@ export interface Driver { * advise omits it. */ advisories?(): Promise; + /** + * The versions of the platform tools this driver uses, for `status.get`'s host facts. Same + * contract as `advisories`: read-only, never downloads, and never throws -- a tool that + * cannot be read is left out. Every process it starts is bounded. Optional: a driver with no + * tools to report omits it. + */ + toolVersions?(): Promise; } /** diff --git a/src/core/host-facts.test.ts b/src/core/host-facts.test.ts new file mode 100644 index 000000000..397ea5c33 --- /dev/null +++ b/src/core/host-facts.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "vitest"; + +import { FakeClock } from "../ports/index.js"; +import type { DriverToolVersion } from "./driver.js"; +import { HOST_FACTS_MAX_AGE_MS, HostFactsReader } from "./host-facts.js"; + +const SYSTEM = { arch: "arm64", os: "macOS", osVersion: "15.5" }; + +/** A driver whose answers a test hands out one read at a time. */ +function scriptedDriver(platform: "ios" | "android") { + const pending: ((answer: readonly DriverToolVersion[] | Error) => void)[] = []; + let reads = 0; + return { + platform, + get reads() { + return reads; + }, + answer(next: readonly DriverToolVersion[] | Error): void { + pending.shift()?.(next); + }, + toolVersions(): Promise { + reads += 1; + return new Promise((resolve, reject) => { + pending.push((answer) => (answer instanceof Error ? reject(answer) : resolve(answer))); + }); + }, + }; +} + +describe("HostFactsReader", () => { + it("serves host facts without waiting and re-reads them once older than the maximum age", async () => { + const clock = new FakeClock(1_000); + const driver = scriptedDriver("ios"); + const reader = new HostFactsReader({ clock, drivers: [driver], system: SYSTEM }); + + // The first call answers at once, before any driver read has finished. + expect(reader.current()).toEqual({ ...SYSTEM, tools: [] }); + expect(driver.reads).toBe(1); + driver.answer([{ build: "16F6", name: "xcode", version: "16.4" }]); + await reader.refresh(); + expect(reader.current().tools).toEqual([ + { build: "16F6", name: "xcode", platform: "ios", version: "16.4" }, + ]); + + // Still fresh: no second read. + clock.advance(HOST_FACTS_MAX_AGE_MS - 1); + reader.current(); + expect(driver.reads).toBe(1); + + // Stale: the next call still answers from memory and starts one background read. + clock.advance(1); + expect(reader.current().tools[0]?.version).toBe("16.4"); + reader.current(); + expect(driver.reads).toBe(2); + driver.answer([{ build: "17A1", name: "xcode", version: "26.0" }]); + await reader.refresh(); + expect(reader.current().tools[0]?.version).toBe("26.0"); + }); + + it("keeps the last tool versions when a re-read fails", async () => { + const clock = new FakeClock(0); + const ios = scriptedDriver("ios"); + const android = scriptedDriver("android"); + const reader = new HostFactsReader({ clock, drivers: [ios, android], system: SYSTEM }); + + const first = reader.refresh(); + ios.answer([{ name: "xcode", version: "16.4" }]); + android.answer([{ name: "emulator", version: "35.4.9" }]); + await first; + + clock.advance(HOST_FACTS_MAX_AGE_MS); + const second = reader.refresh(); + ios.answer(new Error("xcodebuild hung")); + android.answer([{ name: "emulator", version: "36.1.0" }]); + await second; + + expect(reader.current().tools).toEqual([ + { name: "xcode", platform: "ios", version: "16.4" }, + { name: "emulator", platform: "android", version: "36.1.0" }, + ]); + }); +}); diff --git a/src/core/host-facts.ts b/src/core/host-facts.ts new file mode 100644 index 000000000..9b3618b6a --- /dev/null +++ b/src/core/host-facts.ts @@ -0,0 +1,96 @@ +/** + * ADR 0008 §5-§7: what `status.get` reports about the machine. The operating system comes from + * the host port, read once by the composition root; tool versions come from each driver. This + * module joins the two and names no tool (architecture rule 1). + * + * `status.get` is the gateway's liveness probe, so it never waits here: facts are served from + * memory, and a re-read starts in the background once they are older than `HOST_FACTS_MAX_AGE_MS`. + */ +import type { Clock, HostSystem, Logger } from "../ports/index.js"; +import { NoopLogger } from "../ports/index.js"; +import type { Driver, DriverToolVersion } from "./driver.js"; +import type { Platform } from "./domain.js"; + +/** Fixed, not configured (ADR 0008 §9): tool versions change only when someone installs one. */ +export const HOST_FACTS_MAX_AGE_MS = 60_000; + +export interface HostToolVersion extends DriverToolVersion { + readonly platform: Platform; +} + +export interface HostFacts extends HostSystem { + readonly tools: readonly HostToolVersion[]; +} + +export interface HostFactsReaderOptions { + readonly clock: Clock; + readonly drivers: readonly Pick[]; + readonly logger?: Logger; + readonly system: HostSystem; +} + +export class HostFactsReader { + readonly #clock: Clock; + readonly #drivers: HostFactsReaderOptions["drivers"]; + readonly #logger: Logger; + readonly #system: HostSystem; + /** Each driver's last successful answer, so one driver's failed read keeps its own tools. */ + readonly #toolsByDriver = new Map(); + /** When the last read finished; undefined until the first one does. */ + #readAt: number | undefined; + #inFlight: Promise | undefined; + + constructor(options: HostFactsReaderOptions) { + this.#clock = options.clock; + this.#drivers = options.drivers; + this.#logger = options.logger ?? new NoopLogger(); + this.#system = options.system; + } + + /** + * The facts as last read. Starts a background re-read when there is none yet or they are + * older than the maximum age; this call itself never waits for it. + */ + current(): HostFacts { + if (this.#readAt === undefined || this.#clock.now() - this.#readAt >= HOST_FACTS_MAX_AGE_MS) { + void this.refresh(); + } + return { + ...this.#system, + tools: [...this.#toolsByDriver.keys()] + .sort((left, right) => left - right) + .flatMap((index) => this.#toolsByDriver.get(index) ?? []), + }; + } + + /** Reads every driver's tool versions. Single-flight: a call during a read joins it. */ + refresh(): Promise { + this.#inFlight ??= this.#read().finally(() => { + this.#inFlight = undefined; + }); + return this.#inFlight; + } + + async #read(): Promise { + await Promise.all( + this.#drivers.map(async (driver, index) => { + if (driver.toolVersions === undefined) return; + try { + const tools = await driver.toolVersions(); + this.#toolsByDriver.set( + index, + tools.map((tool) => ({ ...tool, platform: driver.platform })), + ); + } catch (error: unknown) { + // The contract says a driver does not throw here. One that does keeps the tools it + // reported last, so a passing failure does not blank the host's status. + this.#logger.warn("Tool version read failed", { + platform: driver.platform, + reason: error instanceof Error ? error.message : "unknown", + }); + } + }), + ); + this.#readAt = this.#clock.now(); + } +} diff --git a/src/core/index.ts b/src/core/index.ts index 3b34ca3f9..1e20bbe0a 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -33,6 +33,7 @@ export { type DriverEstimate, type DriverReality, type DriverRejection, + type DriverToolVersion, InsufficientDiskSpaceError, type LegacyDevice, LicenseNotAcceptedError, @@ -47,6 +48,7 @@ export { UnknownPassthroughToolError } from "./driver-catalog.js"; // fallow-ignore-next-line unused-type -- wire-visible rejection vocabulary for Simlock's own adb server. export type { AdbServerRejectionReason, DriverRejectionReason } from "./driver.js"; export { Doctor } from "./doctor.js"; +export { type HostFacts, HostFactsReader } from "./host-facts.js"; export { ensureOwnedRoot, OWNED_ROOT_MARKER_FILE, OwnedRootError } from "./device-root.js"; export type { EnsureOwnedRootOptions } from "./device-root.js"; // fallow-ignore-next-line unused-type -- wire-visible rejection vocabulary, carried in the driver.root-rejected payload. diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 015159c5e..afea03098 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -5,6 +5,8 @@ import { CleanupReaper, Doctor, FakeDriver, + type HostFacts, + HostFactsReader, LeaseEngine, Nuke, PassthroughRefusedError, @@ -30,6 +32,7 @@ import type { DispatchSession } from "./dispatcher.js"; import { Dispatcher, DispatchError } from "./dispatcher.js"; const gibibyte = 1024 ** 3; +const HOST_SYSTEM = { arch: "arm64", os: "macOS", osVersion: "15.5" }; /** * ADR 0003 §12: "full contract coverage at the dispatcher: one suite ... against a fake driver @@ -104,6 +107,8 @@ async function buildDispatcher( readonly passthroughOverride?: PassthroughResolver; /** Stands in for the event history, so `events.replay` can be checked against it. */ readonly eventHistory?: Pick; + /** `status.get`'s host block; a fixed machine with no tools by default. */ + readonly hostFacts?: () => HostFacts; } = {}, ) { const clock = overrides.clock ?? new FakeClock(1_000); @@ -192,6 +197,7 @@ async function buildDispatcher( doctor, eventHistory: resolveEventHistoryOverride(eventBus, filesystem, overrides.eventHistory), health: () => "running", + hostFacts: overrides.hostFacts ?? (() => ({ ...HOST_SYSTEM, tools: [] })), leases: engine, ...(overrides.includeNuke === true ? { nuke: new Nuke({ executor: engine, registry }) } : {}), passthrough: resolvePassthroughOverride(engine, overrides.passthroughOverride), @@ -923,7 +929,65 @@ describe("Dispatcher: the download policy clamp applies regardless of caller", ( }); }); +describe("Dispatcher: status.get host facts", () => { + it("reports operating system, version, architecture, and every driver's tool versions", async () => { + const hostFacts = new HostFactsReader({ + clock: new FakeClock(0), + drivers: [ + { + platform: "ios", + toolVersions: () => Promise.resolve([{ build: "16F6", name: "xcode", version: "16.4" }]), + }, + { + platform: "android", + toolVersions: () => Promise.resolve([{ name: "emulator", version: "35.4.9" }]), + }, + ], + system: HOST_SYSTEM, + }); + await hostFacts.refresh(); + const { dispatcher } = await buildDispatcher({ hostFacts: () => hostFacts.current() }); + + const status = (await dispatcher.dispatch("status.get", {}, session())) as { + readonly host: unknown; + }; + + expect(status.host).toEqual({ + arch: "arm64", + os: "macOS", + osVersion: "15.5", + tools: [ + { build: "16F6", name: "xcode", platform: "ios", version: "16.4" }, + { name: "emulator", platform: "android", version: "35.4.9" }, + ], + }); + }); +}); + describe("Dispatcher: startup-readiness parking", () => { + it("answers status.get with host facts while other operations are parked on startup", async () => { + const { dispatcher } = await buildDispatcher({ + awaitReady: () => new Promise(() => undefined), + hostFacts: () => ({ + ...HOST_SYSTEM, + tools: [{ name: "xcode", platform: "ios", version: "16.4" }], + }), + }); + + let parked = true; + void dispatcher.dispatch("catalog.get", {}, session()).then(() => { + parked = false; + }); + const status = (await dispatcher.dispatch("status.get", {}, session())) as { + readonly host: { readonly os: string; readonly tools: readonly unknown[] }; + }; + await flush(); + + expect(parked).toBe(true); + expect(status.host.os).toBe("macOS"); + expect(status.host.tools).toHaveLength(1); + }); + it("parks every operation but status.get on awaitReady", async () => { let releaseReady: () => void = () => {}; const readyPromise = new Promise((resolve) => { diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 0a6fc7fc7..128974b97 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -7,6 +7,7 @@ import { type DeviceRecord, type DeviceRequest, type Doctor, + type HostFacts, type Nuke, type Registry, effectiveAllowDownload, @@ -122,6 +123,8 @@ export interface DispatcherOptions { readonly tokens?: TokenStore; /** Reports current daemon health for `status.get`. */ readonly health: () => "starting" | "running" | "failed"; + /** `status.get`'s host block, from memory: answering never waits for a read (ADR 0008 §7). */ + readonly hostFacts: () => HostFacts; /** * ADR §2 step 4: every operation but `status.get` parks here before its handler runs. * `hello` never reaches `dispatch()` at all -- it is answered before a `Session` exists, @@ -280,6 +283,7 @@ export class Dispatcher { // it leased is on this machine (§19c) -- today every daemon configures `worker`, and // #117 is what makes `gateway` mean something beyond this field. daemon: { health: this.options.health(), mode: this.options.config.mode }, + host: this.options.hostFacts(), leases: [...snapshot.leases], queueDepth: this.options.queue.queueDepth, }; diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index b788972bd..fdafda7ee 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -4,7 +4,12 @@ import { join } from "node:path"; import { connect, createServer, Server } from "node:net"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { FakeDriver, OWNED_ROOT_MARKER_FILE, type OwnedRootError } from "../core/index.js"; +import { + type DriverToolVersion, + FakeDriver, + OWNED_ROOT_MARKER_FILE, + type OwnedRootError, +} from "../core/index.js"; import { IosSimctlDriver } from "../drivers/ios/index.js"; import { EventBus } from "../bus/index.js"; import { DAEMON_PROTOCOL_VERSION } from "../daemon-protocol/index.js"; @@ -12,6 +17,7 @@ import { CryptoIdGenerator, CryptoTokenSecrets, FakeClock, + FakeHostInfo, FakeProcessSupervisor, FakeTcpProbe, JsonLinesLogger, @@ -94,6 +100,20 @@ class DisposableFakeDriver extends FakeDriver { } } +/** A fake driver that reports tool versions, which `FakeDriver` does not. */ +class ToolsFakeDriver extends FakeDriver { + constructor( + options: ConstructorParameters[0], + private readonly tools: () => Promise, + ) { + super(options); + } + + toolVersions(): Promise { + return this.tools(); + } +} + describe("startDaemon", () => { it("writes a structured start record with version, protocol version, socket path, and effective config", async () => { const { daemon, sink } = await start(); @@ -198,6 +218,59 @@ describe("startDaemon", () => { ); }); + it("starts, and reports the host and every tool read, while one driver's tool read never answers", async () => { + const clock = new FakeClock(1_000); + const { daemon } = await start({ + drivers: [ + new ToolsFakeDriver( + { availableOsVersions: ["26.5"], clock, platform: "ios" }, + // What an iOS driver whose `xcodebuild` never answers looks like from here. + () => new Promise(() => undefined), + ), + new ToolsFakeDriver({ availableOsVersions: ["35"], clock, platform: "android" }, () => + Promise.resolve([{ name: "emulator", version: "35.4.9" }]), + ), + ], + hostInfo: new FakeHostInfo({ arch: "arm64", os: "macOS", osVersion: "15.5" }), + }); + + await expect + .poll(async () => { + const status = (await daemon.dispatch( + "status.get", + {}, + { + manageEventSubscription: () => undefined, + principal: "agent", + role: "agent", + }, + )) as { readonly host: unknown }; + return status.host; + }) + .toEqual({ + arch: "arm64", + os: "macOS", + osVersion: "15.5", + tools: [{ name: "emulator", platform: "android", version: "35.4.9" }], + }); + }); + + it("reads tool versions at start, before anything asks for status", async () => { + const clock = new FakeClock(1_000); + let reads = 0; + await start({ + drivers: [ + new ToolsFakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }, () => { + reads += 1; + return Promise.resolve([]); + }), + ], + hostInfo: new FakeHostInfo({ arch: "arm64", os: "macOS", osVersion: "15.5" }), + }); + + expect(reads).toBe(1); + }); + it("scopes child loggers under daemon. so records are attributable", async () => { const { sink } = await start(); @@ -570,6 +643,7 @@ describe("discoverDrivers", () => { driversConfig: {}, eventBus: new EventBus(new FakeClock()), filesystem, + hostArch: "arm64", hostPlatform: "linux", idGenerator: new CryptoIdGenerator(), instanceId: "instance-1", @@ -781,6 +855,7 @@ describe("discoverDrivers on a host with an Android SDK", () => { driversConfig: {}, eventBus: new EventBus(new FakeClock()), filesystem, + hostArch: "arm64", hostPlatform: "linux", idGenerator: new CryptoIdGenerator(), instanceId: INSTANCE_ID, @@ -849,6 +924,7 @@ function discoverIos( driversConfig: {}, eventBus: new EventBus(new FakeClock()), filesystem: overrides.filesystem ?? new MemoryFilesystem(), + hostArch: "arm64", hostPlatform: overrides.hostPlatform ?? "darwin", idGenerator: overrides.idGenerator ?? new CryptoIdGenerator(), instanceId: INSTANCE_ID, @@ -1098,6 +1174,7 @@ describe("discoverDrivers with SIMLOCK_DRIVERS_MODULE", () => { driversConfig: {}, eventBus: new EventBus(new FakeClock()), filesystem: new MemoryFilesystem(), + hostArch: "arm64", hostPlatform: "linux", idGenerator: new CryptoIdGenerator(), instanceId: "instance-1", diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 5b2b37768..8ecf0d619 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -11,6 +11,7 @@ import { CleanupReaper, DiskSpaceGuard, Doctor, + HostFactsReader, LeaseEngine, loadConfig, loadInstanceId, @@ -22,6 +23,7 @@ import { AdbServerUnavailableError, AndroidDriver, ANDROID_PASSTHROUGH_TOOL, + hostAbiFor, SdkMissingError, type AndroidDriverDiagnostic, type AndroidEmulatorLaunchOptions, @@ -39,12 +41,15 @@ import { NodeFileLogSink, type Clock, type Filesystem, + type HostInfo, + type HostSystem, type IdGenerator, type IpcConnector, type IpcListenerFactory, type Logger, type LogLevel, NodeFilesystem, + NodeHostInfo, NodeIpcTransport, NodeProcessRunner, NodeProcessSupervisor, @@ -89,6 +94,7 @@ export interface StartDaemonOptions { readonly defaultRequesterId?: string; readonly drivers?: readonly Driver[]; readonly filesystem?: Filesystem; + readonly hostInfo?: HostInfo; readonly idGenerator?: IdGenerator; readonly ipc?: IpcConnector & IpcListenerFactory; readonly logger?: Logger; @@ -133,6 +139,11 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise hostFacts.current(), host: new DaemonEndpointHost({ connector: ipc, endpoint: socketPath, @@ -490,6 +513,8 @@ interface GatewayDaemonOptions { readonly eventBus: EventBus; readonly eventHistory: EventHistory; readonly filesystem: Filesystem; + /** The gateway's own machine. It runs no drivers, so its host facts carry no tools. */ + readonly hostSystem: HostSystem; readonly idGenerator: IdGenerator; readonly ipc: IpcConnector & IpcListenerFactory; readonly logger: Logger; @@ -636,6 +661,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise daemon.health, + host: { ...options.hostSystem, tools: [] }, leaseIndex, logger: logger.child("gateway"), tokens, @@ -769,6 +795,8 @@ export interface DriverDiscoveryContext { * Mac, and so is untestable everywhere Simlock's own CI runs. */ readonly hostPlatform: NodeJS.Platform; + /** The host port's architecture; the Android driver prefers images of the ABI it runs. */ + readonly hostArch: string; readonly idGenerator: IdGenerator; readonly instanceId: string; readonly logger: Logger; @@ -903,6 +931,7 @@ async function discoverAndroidDriver( env: process.env, filesystem: options.filesystem, homeDirectory: homedir(), + hostAbi: hostAbiFor(options.hostArch), idGenerator: options.idGenerator, instanceId: options.instanceId, onDiagnostic: bridgeAndroidDriverDiagnostic(options.eventBus), diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index b00e7708d..bfafdc54a 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -2872,6 +2872,7 @@ async function createHarness( filesystem: new NodeFilesystem(), listenerFactory: new NodeIpcTransport(), }), + hostFacts: () => ({ arch: "arm64", os: "macOS", osVersion: "15.5", tools: [] }), leases: engine, ...(options.logger === undefined ? {} : { logger: options.logger }), passthrough: engine, diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 048d6d07a..73dceacf2 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -8,6 +8,7 @@ import { type CleanupReaper, type Doctor, type DriverRejection, + type HostFacts, type LeaseHealthMonitor, NoDriverError, type Nuke, @@ -139,6 +140,8 @@ export interface DaemonServerEngineOptions { /** What `events.replay` answers from; see `EventHistory`. */ readonly eventHistory: Pick; readonly leases: LeaseCommands; + /** `status.get`'s host block (ADR 0008 §5); see `DispatcherOptions.hostFacts`. */ + readonly hostFacts: () => HostFacts; readonly queue: QueueControl; readonly reaper: CleanupReaper; readonly healthMonitor?: LeaseHealthMonitor; @@ -285,6 +288,7 @@ function buildDispatcher( errorCode: classifyError, eventHistory: options.eventHistory, health: hooks.health, + hostFacts: options.hostFacts, leases: options.leases, ...(options.logger === undefined ? {} : { logger: options.logger }), ...(options.nuke === undefined ? {} : { nuke: options.nuke }), diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 3f6abd290..59e75c092 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -79,6 +79,7 @@ describe("AndroidDriver", () => { }, filesystem, homeDirectory: home, + hostAbi: "arm64-v8a", instanceId, processRunner: runner, processSupervisor: new FakeProcessSupervisor([adbServerPid]), @@ -95,6 +96,7 @@ describe("AndroidDriver", () => { env: {}, filesystem: new MemoryFilesystem(), homeDirectory: home, + hostAbi: "arm64-v8a", instanceId, processRunner: runner, processSupervisor: new FakeProcessSupervisor(), @@ -2120,6 +2122,7 @@ describe("AndroidDriver.create", () => { env: { ANDROID_HOME: sdk }, filesystem, homeDirectory: home, + hostAbi: "arm64-v8a", instanceId, processRunner: new ScriptedProcessRunner([]), processSupervisor: new FakeProcessSupervisor(), @@ -2388,6 +2391,7 @@ describe("AndroidDriver.create", () => { env: { ANDROID_HOME: sdk }, filesystem, homeDirectory: home, + hostAbi: "arm64-v8a", instanceId, processRunner: new ScriptedProcessRunner([ { @@ -2585,6 +2589,7 @@ live( env: process.env, filesystem: new NodeFilesystem(), homeDirectory: process.env.HOME ?? home, + hostAbi: "arm64-v8a", instanceId: `live-${process.pid}`, processRunner: new NodeProcessRunner(), processSupervisor: new NodeProcessSupervisor(), @@ -2732,6 +2737,44 @@ async function provisionedHarness( * paths are covered against the supervisor itself in `adb-server.test.ts`, and end to end * in this file's own `AndroidDriver.create` block. */ +describe("AndroidDriver toolVersions()", () => { + it("reports emulator, platform-tools, and command-line tools revisions from each package's source.properties", async () => { + const filesystem = await androidFilesystem(); + await filesystem.writeFileAtomic( + `${sdk}/emulator/source.properties`, + "Pkg.Desc=Android Emulator\nPkg.Revision=35.4.9\n", + ); + await filesystem.writeFileAtomic( + `${sdk}/platform-tools/source.properties`, + "Pkg.Revision=36.0.0\nPkg.Path=platform-tools\n", + ); + await filesystem.writeFileAtomic( + `${sdk}/cmdline-tools/latest/source.properties`, + "Pkg.Revision=19.0\n", + ); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + await expect(driver.toolVersions()).resolves.toEqual([ + { name: "emulator", version: "35.4.9" }, + { name: "platform-tools", version: "36.0.0" }, + { name: "cmdline-tools", version: "19.0" }, + ]); + }); + + it("omits a tool whose source.properties cannot be read", async () => { + const filesystem = await androidFilesystem(); + await filesystem.writeFileAtomic(`${sdk}/emulator/source.properties`, "Pkg.Revision=35.4.9\n"); + // platform-tools has no source.properties; cmdline-tools has one without a revision. + await filesystem.writeFileAtomic( + `${sdk}/cmdline-tools/latest/source.properties`, + "Pkg.Desc=Android SDK Command-line Tools\n", + ); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + await expect(driver.toolVersions()).resolves.toEqual([{ name: "emulator", version: "35.4.9" }]); + }); +}); + async function createDriver( filesystem: Filesystem, processRunner: ScriptedProcessRunner, diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 7c076aaaa..a89e7a3b6 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -1,4 +1,4 @@ -import { join } from "node:path"; +import { dirname, join } from "node:path"; import type { DeviceSpec } from "../../core/domain.js"; import { @@ -11,6 +11,7 @@ import { DriverCrashError, type DriverEstimate, type DriverReality, + type DriverToolVersion, LicenseNotAcceptedError, type ObservedDevice, type ObservedMark, @@ -172,7 +173,12 @@ export interface AndroidDriverOptions { readonly env: Readonly>; readonly filesystem: Filesystem; readonly homeDirectory: string; - readonly hostAbi?: string; + /** + * The ABI this host runs natively (`hostAbiFor` of the host port's architecture), passed in + * by the composition root so the image this driver prefers and the architecture `status.get` + * reports come from the same reading. + */ + readonly hostAbi: string; readonly idGenerator?: IdGenerator; /** Identity this driver's device root ownership marker is checked against. */ readonly instanceId: string; @@ -471,7 +477,7 @@ export class AndroidDriver implements Driver { this.#emulatorFlags = emulatorLaunchFlags(options.emulator); this.#baselineLaunchInputs = baselineLaunchInputs(options.emulator); this.#filesystem = options.filesystem; - this.#hostAbi = options.hostAbi ?? hostAbiFor(process.arch); + this.#hostAbi = options.hostAbi; this.#idGenerator = options.idGenerator ?? new SequentialIdGenerator(); this.#onDiagnostic = options.onDiagnostic; this.#processRunner = options.processRunner; @@ -1092,6 +1098,26 @@ export class AndroidDriver implements Driver { } } + /** + * Revisions of the SDK packages this driver runs: the emulator, platform-tools (adb), and the + * command-line tools whose `sdkmanager` it uses. Read from each package's `source.properties`, + * so no tool is started; a package whose file cannot be read is left out. + */ + async toolVersions(): Promise { + const packages = [ + { name: "emulator", path: dirname(this.#sdk.emulator) }, + { name: "platform-tools", path: dirname(this.#sdk.adb) }, + { name: "cmdline-tools", path: dirname(dirname(this.#sdk.sdkmanager)) }, + ]; + const versions = await Promise.all( + packages.map(async ({ name, path }) => { + const version = await packageRevision(this.#filesystem, path); + return version === undefined ? undefined : { name, version }; + }), + ); + return versions.filter((version) => version !== undefined); + } + async listCatalog(): Promise { const [models, images] = await Promise.all([ this.#deviceProfiles.listModels(), @@ -1961,17 +1987,24 @@ function systemImagePackage(apiLevel: string, tag: string, abi: string): string } async function systemImageVersion(filesystem: Filesystem, imagePath: string): Promise { + return (await packageRevision(filesystem, imagePath)) ?? "unknown"; +} + +/** `Pkg.Revision` from an SDK package's `source.properties`; undefined when it cannot be read. */ +async function packageRevision( + filesystem: Filesystem, + packagePath: string, +): Promise { try { - const properties = await filesystem.readFile(`${imagePath}/source.properties`); - return ( - properties - .split(/\r?\n/) - .find((line) => line.startsWith("Pkg.Revision=")) - ?.slice("Pkg.Revision=".length) - .trim() ?? "unknown" - ); + const properties = await filesystem.readFile(`${packagePath}/source.properties`); + const revision = properties + .split(/\r?\n/) + .find((line) => line.startsWith("Pkg.Revision=")) + ?.slice("Pkg.Revision=".length) + .trim(); + return revision === "" ? undefined : revision; } catch { - return "unknown"; + return undefined; } } @@ -2099,7 +2132,8 @@ function stableHash(parts: readonly string[]): string { return (hash >>> 0).toString(16).padStart(8, "0"); } -function hostAbiFor(architecture: string): string { +/** The Android ABI that runs natively on a CPU of this architecture, as Node names it. */ +export function hostAbiFor(architecture: string): string { return architecture === "arm64" ? "arm64-v8a" : "x86_64"; } diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 9df6a174a..aef872cff 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -2973,6 +2973,39 @@ describe("IosSimctlDriver", () => { }); }); +describe("IosSimctlDriver toolVersions()", () => { + it("reports the Xcode version and build that xcodebuild -version prints", async () => { + const runner = new ScriptedProcessRunner([ + { + match: { args: ["-version"], command: "xcodebuild" }, + result: { code: 0, stderr: "", stdout: "Xcode 16.4\nBuild version 16F6\n" }, + }, + ]); + const driver = await createDriver(runner); + + await expect(driver.toolVersions()).resolves.toEqual([ + { build: "16F6", name: "xcode", version: "16.4" }, + ]); + expect(runner.calls[0]?.options.timeoutMs).toBeGreaterThan(0); + }); + + it("reports no Xcode entry when xcodebuild fails", async () => { + const runner = new ScriptedProcessRunner([ + { + match: { args: ["-version"], command: "xcodebuild" }, + result: { + code: 1, + stderr: "xcode-select: error: tool 'xcodebuild' requires Xcode", + stdout: "", + }, + }, + ]); + const driver = await createDriver(runner); + + await expect(driver.toolVersions()).resolves.toEqual([]); + }); +}); + function createDriver( runner: ScriptedProcessRunner, clock = new FakeClock(), diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index a3b8d510b..788c094e4 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -6,6 +6,7 @@ import { DiskSpaceGuard, type Driver, type DriverAdvisory, + type DriverToolVersion, type DriverCatalogEntry, type DriverDevice, DriverCrashError, @@ -37,6 +38,9 @@ import type { ComponentInstallDiagnostic } from "../diagnostics.js"; import { labelsFor, resolveSlimCategories, slimSignature } from "./slim-labels.js"; const COMMAND_TIMEOUT_MS = 30_000; +// `xcodebuild -version` answers in about a second; a first run after an Xcode update can take +// longer while it checks its components, and a hang must not hold host facts forever. +const XCODE_VERSION_TIMEOUT_MS = 15_000; const BOOTSTATUS_TIMEOUT_MS = 120_000; const PROVISION_ESTIMATE_MS = 500; // Mirrors `downloads.timeoutMs`'s config default (`src/core/config.ts`) -- used only when a @@ -1217,6 +1221,25 @@ export class IosSimctlDriver implements Driver { return [...(await this.#unreclaimableCacheAdvisories()), ...(await this.#slimAdvisories())]; } + /** + * The Xcode version and build `xcodebuild -version` prints. Anything else -- no Xcode, a + * failed or timed-out run, output in a shape this does not know -- reports no entry. + */ + async toolVersions(): Promise { + try { + const result = await this.#processRunner.run("xcodebuild", ["-version"], { + timeoutMs: XCODE_VERSION_TIMEOUT_MS, + }); + if (result.code !== 0) return []; + const version = /^Xcode (\S+)$/m.exec(result.stdout)?.[1]; + const build = /^Build version (\S+)$/m.exec(result.stdout)?.[1]; + if (version === undefined) return []; + return [{ name: "xcode", version, ...(build === undefined ? {} : { build }) }]; + } catch { + return []; + } + } + /** * Issue #79: a runtime download outlives the runtime. `simctl runtime delete` unregisters * the runtime and leaves its ~7.5 GiB bundle in the OS asset store, from which CoreSimulator diff --git a/src/gateway/aggregate.test.ts b/src/gateway/aggregate.test.ts index e6612b89e..14c577ac0 100644 --- a/src/gateway/aggregate.test.ts +++ b/src/gateway/aggregate.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; import { OPERATIONS } from "../contract/index.js"; import { aggregateCatalog, aggregateStatus } from "./aggregate.js"; import { FleetLeaseIndex } from "./lease-index.js"; -import { deviceFixture, leaseFixture } from "./test-support.js"; +import { deviceFixture, hostFixture, leaseFixture } from "./test-support.js"; import type { WorkerView } from "./worker-registry.js"; function capacity(running: number, limit: number) { @@ -30,6 +30,8 @@ function capacity(running: number, limit: number) { }; } +const GATEWAY_HOST = { arch: "x64", os: "Linux", osVersion: "6.8.0", tools: [] }; + function view(overrides: Partial & { readonly id: string }): WorkerView { return { catalog: [], @@ -44,7 +46,7 @@ function view(overrides: Partial & { readonly id: string }): WorkerV describe("aggregateStatus", () => { it("returns the same shape a worker returns, with the gateway named in the daemon block", () => { - const status = aggregateStatus([], { health: "running", queueDepth: 0 }); + const status = aggregateStatus([], { health: "running", host: GATEWAY_HOST, queueDepth: 0 }); // The contract is the arbiter: a gateway's answer parses as `status.get`'s output or it is // not the same shape. @@ -53,6 +55,16 @@ describe("aggregateStatus", () => { expect(status.workers).toEqual([]); }); + it("reports the gateway's own host with no tools, not any worker's", () => { + const status = aggregateStatus( + [view({ host: hostFixture({ os: "macOS", osVersion: "15.5" }), id: "wrk_a" })], + { health: "running", host: GATEWAY_HOST, queueDepth: 0 }, + ); + + expect(status.host).toEqual({ arch: "x64", os: "Linux", osVersion: "6.8.0", tools: [] }); + expect(status.workers?.[0]?.host?.os).toBe("macOS"); + }); + // Round 6 review: `aggregateStatus`'s whole `leaseIndex` branch was deletable with a green // suite -- replacing it with the pre-#118 `{...lease, workerId}` passthrough broke nothing, // because every case here omitted the optional `leaseIndex` and so exercised only the @@ -73,7 +85,7 @@ describe("aggregateStatus", () => { const status = aggregateStatus( [view({ id: "wrk_a", label: "mac-mini-1", leases: [leaseFixture("lease_1", "dev_1")] })], - { health: "running", leaseIndex, queueDepth: 0 }, + { health: "running", host: GATEWAY_HOST, leaseIndex, queueDepth: 0 }, ); expect(status.leases).toEqual([ @@ -95,7 +107,7 @@ describe("aggregateStatus", () => { const status = aggregateStatus( [view({ id: "wrk_a", label: "mac-mini-1", leases: [leaseFixture("lease_1", "dev_1")] })], - { health: "running", leaseIndex, queueDepth: 0 }, + { health: "running", host: GATEWAY_HOST, leaseIndex, queueDepth: 0 }, ); expect(status.leases).toEqual([ @@ -110,7 +122,7 @@ describe("aggregateStatus", () => { view({ capacity: capacity(1, 2), id: "wrk_a" }), view({ capacity: capacity(2, 4), id: "wrk_b" }), ], - { health: "running", queueDepth: 0 }, + { health: "running", host: GATEWAY_HOST, queueDepth: 0 }, ); expect(status.capacity.ios).toMatchObject({ limit: 6, running: 3, used: 3, warm: 2 }); @@ -125,7 +137,7 @@ describe("aggregateStatus", () => { view({ capacity: capacity(1, 2), id: "wrk_a" }), view({ capacity: capacity(9, 9), connection: "disconnected", id: "wrk_b" }), ], - { health: "running", queueDepth: 0 }, + { health: "running", host: GATEWAY_HOST, queueDepth: 0 }, ); expect(status.capacity.ios).toMatchObject({ limit: 2, running: 1 }); @@ -141,7 +153,7 @@ describe("aggregateStatus", () => { id: "wrk_b", }), ], - { health: "running", queueDepth: 0 }, + { health: "running", host: GATEWAY_HOST, queueDepth: 0 }, ); expect(status.capacity.ios.overLimit).toBe(true); @@ -157,7 +169,7 @@ describe("aggregateStatus", () => { }), view({ devices: [deviceFixture("dev_2")], id: "wrk_b" }), ], - { health: "running", queueDepth: 0 }, + { health: "running", host: GATEWAY_HOST, queueDepth: 0 }, ); expect(status.devices).toEqual([ @@ -178,7 +190,7 @@ describe("aggregateStatus", () => { leases: [leaseFixture("lease_1", "dev_1")], }), ], - { health: "running", queueDepth: 0 }, + { health: "running", host: GATEWAY_HOST, queueDepth: 0 }, ); expect(status.leases).toEqual([expect.objectContaining({ id: "lease_1", workerId: "wrk_a" })]); @@ -187,6 +199,7 @@ describe("aggregateStatus", () => { it("reports the gateway's own queue depth and health, not any worker's", () => { const status = aggregateStatus([view({ health: "failed", id: "wrk_a", queueDepth: 7 })], { health: "starting", + host: GATEWAY_HOST, queueDepth: 0, }); diff --git a/src/gateway/aggregate.ts b/src/gateway/aggregate.ts index 425ca46b5..cde2dc83c 100644 --- a/src/gateway/aggregate.ts +++ b/src/gateway/aggregate.ts @@ -37,6 +37,8 @@ const EMPTY_GLOBAL_CAPACITY = { export interface AggregateStatusOptions { /** The *gateway's* own health, not any worker's. */ readonly health: StatusOutput["daemon"]["health"]; + /** The *gateway's* own machine. Each worker's is on its view. */ + readonly host: StatusOutput["host"]; /** The gateway's fleet queue depth -- 0 until #118 gives it a queue. */ readonly queueDepth: number; /** @@ -71,6 +73,7 @@ export function aggregateStatus( return { capacity: sumCapacity(views.filter((view) => view.connection === "connected")), daemon: { health: options.health, mode: "gateway" }, + host: options.host, devices: views.flatMap((view) => view.devices.map((device) => ({ ...device, workerId: view.id })), ), diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 91d2b5146..4969e7e98 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -20,6 +20,7 @@ import { catalogFixture, deviceFixture, grantFixture, + hostFixture, leaseFixture, ScriptedWorkerClient, statusFixture, @@ -98,6 +99,9 @@ class FakeTokens implements GatewayTokenStore { * prefix is that principal plus a trailing `:`, the same shape `worker-registry.test.ts` uses. */ const GATEWAY_REQUESTER_PREFIX = "gw:instance-1:"; +/** The gateway's own machine, as the composition root hands it over: read once, no tools. */ +const GATEWAY_HOST = { arch: "x64", os: "Linux", osVersion: "6.8.0", tools: [] }; + /** A `WorkerDirectory` a test populates by hand -- see `fleet-coordinator.test.ts`'s own copy * for the fuller doc comment; this file only ever needs one worker at a time. */ class FakeDirectory implements WorkerDirectory { @@ -168,6 +172,7 @@ function harness(options: { readonly eventHistory?: Pick path: "/events.jsonl", }), health: () => "running", + host: GATEWAY_HOST, leaseIndex, // `classifyError`'s answer for the errors this dispatcher throws itself. errorCode: (error) => (error instanceof DispatchError ? error.code : undefined), @@ -257,6 +262,17 @@ describe("GatewayDispatcher", () => { expect(status.leases).toEqual([expect.objectContaining({ workerId: "wrk_1" })]); }); + it("reports its own host with no tools on status.get, and each worker's on its view", async () => { + const { dispatcher, workers } = harness(); + workers.connected("wrk_1", "mac-mini-1", "0.3.0"); + workers.refresh("wrk_1", { host: hostFixture() }); + + const status = await dispatcher.dispatch("status.get", {}, session()); + + expect(status.host).toEqual({ arch: "x64", os: "Linux", osVersion: "6.8.0", tools: [] }); + expect(status.workers?.[0]?.host).toEqual(hostFixture()); + }); + it("reports each worker device's mode on status.get and worker.list", async () => { const { dispatcher, workers } = harness(); workers.connected("wrk_1", undefined, "0.3.0"); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index dda7404bb..00ebbace5 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -39,7 +39,7 @@ import { } from "../daemon/dispatch.js"; import type { Clock, Logger } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; -import { aggregateCatalog, aggregateStatus } from "./aggregate.js"; +import { aggregateCatalog, aggregateStatus, type AggregateStatusOptions } from "./aggregate.js"; import type { FleetLeaseCoordinator } from "./fleet-coordinator.js"; import type { FleetLeaseIndex } from "./lease-index.js"; import type { WorkerRegistry } from "./worker-registry.js"; @@ -105,6 +105,8 @@ export interface GatewayDispatcherOptions { readonly errorCode?: (error: unknown) => string | undefined; /** The gateway's own health, for `status.get`. */ readonly health: () => "starting" | "running" | "failed"; + /** The gateway's own machine, for `status.get` (ADR 0008 §8): read once at start, no tools. */ + readonly host: AggregateStatusOptions["host"]; readonly awaitReady: () => Promise; /** * #118: admission, dispatch, and lease/exec forwarding. Every lease-lifecycle handler and @@ -208,6 +210,7 @@ export class GatewayDispatcher { #statusGet: Handler<"status.get"> = () => aggregateStatus(this.options.workers.views(), { health: this.options.health(), + host: this.options.host, // ADR 0005 §20: the gateway's own fleet queue depth. queueDepth: this.options.coordinator.queueDepth, leaseIndex: this.options.leaseIndex, diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index b7ea6423a..3860b4c59 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -14,6 +14,7 @@ import { GatewayService, REJECTION_COALESCE_WINDOW_MS } from "./service.js"; import { catalogFixture, deviceFixture, + hostFixture, leaseFixture, protocolMismatchError, ScriptedWorkerClient, @@ -370,6 +371,46 @@ describe("GatewayService", () => { await harness.service.stop(); }); + it("carries the host facts its worker last reported on the view", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + worker.status = statusFixture({ host: hostFixture({ arch: "x64", osVersion: "14.7" }) }); + + await harness.join("wrk_1", worker); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.host).toEqual( + hostFixture({ arch: "x64", osVersion: "14.7" }), + ), + ); + + await harness.service.stop(); + }); + + it("shows a changed tool version on the view after the next refresh", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.host?.tools[0]?.version).toBe("16.4"), + ); + worker.status = statusFixture({ + host: hostFixture({ + tools: [{ build: "17A324", name: "xcode", platform: "ios", version: "26.0" }], + }), + }); + + harness.clock.advance(REFRESH_MS); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.host?.tools[0]?.version).toBe("26.0"), + ); + + await harness.service.stop(); + }); + describe("warning on a worker's lower lease.maxTtlMs (ADR 0005 §15)", () => { it("warns once the joining worker's own config.get reports a lower cap", async () => { const logger = new RecordingLogger(); diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index 848bb9f53..ee18ae171 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -42,6 +42,19 @@ const emptyPlatformCapacity = { warm: 0, }; +/** A worker's `host` block (ADR 0008 §5): one Mac with Xcode installed. */ +export function hostFixture( + overrides: Partial = {}, +): StatusGetOutput["host"] { + return { + arch: "arm64", + os: "macOS", + osVersion: "15.5", + tools: [{ build: "16F6", name: "xcode", platform: "ios", version: "16.4" }], + ...overrides, + }; +} + export function statusFixture(overrides: Partial = {}): StatusGetOutput { return { capacity: { @@ -51,6 +64,7 @@ export function statusFixture(overrides: Partial = {}): StatusG }, daemon: { health: "running", mode: "worker" }, devices: [], + host: hostFixture(), leases: [], queueDepth: 0, ...overrides, diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index a4a6c82ef..6278556f9 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -359,6 +359,7 @@ export class WorkerLink { capacity: status.capacity, devices: viewDevicesSchema.parse(devices), health: status.daemon.health, + host: status.host, leases: status.leases, queueDepth: status.queueDepth, version: client.daemonVersion, diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index 79e79b0eb..33cd28289 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -4,7 +4,7 @@ import { EventBus, type EventEnvelope } from "../bus/index.js"; import { PROTOCOL_VERSION_RANGE } from "../contract/index.js"; import { FakeClock, type Logger } from "../ports/index.js"; import { MemoryDrainStore } from "./drain-store.js"; -import { leaseFixture } from "./test-support.js"; +import { hostFixture, leaseFixture } from "./test-support.js"; import { WorkerRegistry } from "./worker-registry.js"; const RETENTION_MS = 24 * 60 * 60_000; @@ -244,6 +244,25 @@ describe("WorkerRegistry", () => { expect(events).toEqual([]); }); + it("carries no host facts on an incompatible worker's view, even after a compatible session", () => { + const { workers } = registry(); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { host: hostFixture() }); + expect(workers.view("wrk_1")?.host).toEqual(hostFixture()); + + // The same machine comes back downgraded: it is never asked for status, so the host facts + // its earlier session reported are no longer known. + const view = workers.incompatible( + "wrk_1", + undefined, + { gateway: PROTOCOL_VERSION_RANGE, worker: { min: 4, max: 4 } }, + "0.2.0", + ); + + expect(view.host).toBeUndefined(); + expect(workers.view("wrk_1")?.host).toBeUndefined(); + }); + it("clears the protocol ranges when an upgraded worker reconnects", () => { const { workers } = registry(); workers.incompatible( diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index ba1a59587..8021e19ca 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -29,6 +29,7 @@ export type WorkerViewSnapshot = Pick< | "devices" | "downloads" | "health" + | "host" | "lease" | "leases" | "queueDepth" @@ -198,9 +199,12 @@ export class WorkerRegistry { ...(label === undefined ? {} : { label }), ...(version === undefined ? {} : { version }), }; - this.#workers.set(workerId, view); + // ADR 0008 §8: host facts come from `status.get`, which an incompatible worker is never + // asked. A view left over from an earlier, compatible session must not keep showing them. + const { host: _stale, ...withoutHost } = view; + this.#workers.set(workerId, withoutHost); this.#notifyViewsChanged(); - return view; + return withoutHost; } /** diff --git a/src/ports/host-info.test.ts b/src/ports/host-info.test.ts new file mode 100644 index 000000000..6a73cd422 --- /dev/null +++ b/src/ports/host-info.test.ts @@ -0,0 +1,45 @@ +import { release, type } from "node:os"; + +import { describe, expect, it } from "vitest"; + +import { NodeHostInfo, ScriptedProcessRunner } from "./index.js"; + +const SW_VERS_OUTPUT = "ProductName:\t\tmacOS\nProductVersion:\t\t15.5\nBuildVersion:\t\t24F74\n"; + +describe("NodeHostInfo", () => { + it("reports the macOS product name and version from sw_vers", async () => { + const processRunner = new ScriptedProcessRunner([ + { + match: { args: [], command: "sw_vers" }, + result: { code: 0, stderr: "", stdout: SW_VERS_OUTPUT }, + }, + ]); + + const system = await new NodeHostInfo({ platform: "darwin", processRunner }).read(); + + expect(system).toMatchObject({ os: "macOS", osVersion: "15.5" }); + expect(processRunner.calls[0]?.options.timeoutMs).toBeGreaterThan(0); + }); + + it("falls back to the kernel name and release when sw_vers fails", async () => { + const processRunner = new ScriptedProcessRunner([ + { + match: { args: [], command: "sw_vers" }, + result: { code: 1, stderr: "boom", stdout: "" }, + }, + ]); + + const system = await new NodeHostInfo({ platform: "darwin", processRunner }).read(); + + expect(system).toMatchObject({ os: type(), osVersion: release() }); + }); + + it("does not run sw_vers on another operating system", async () => { + const processRunner = new ScriptedProcessRunner([]); + + const system = await new NodeHostInfo({ platform: "linux", processRunner }).read(); + + expect(system).toMatchObject({ os: type(), osVersion: release() }); + expect(processRunner.calls).toEqual([]); + }); +}); diff --git a/src/ports/host-info.ts b/src/ports/host-info.ts new file mode 100644 index 000000000..40570ed32 --- /dev/null +++ b/src/ports/host-info.ts @@ -0,0 +1,70 @@ +import { arch, release, type } from "node:os"; + +import type { ProcessRunner } from "./process-runner.js"; + +/** What the machine is, as opposed to what tools it has: ADR 0008 §6's host port. */ +export interface HostSystem { + /** Product name of the operating system (`macOS`), or the kernel name where there is none. */ + readonly os: string; + readonly osVersion: string; + /** CPU architecture as Node names it (`arm64`, `x64`). */ + readonly arch: string; +} + +export interface HostInfo { + /** Never throws: a fact that cannot be read falls back to what `node:os` reports. */ + read(): Promise; +} + +/** Bounds the one `sw_vers` call (architecture rule 11). It answers in milliseconds. */ +const SW_VERS_TIMEOUT_MS = 5_000; + +export interface NodeHostInfoOptions { + readonly processRunner: ProcessRunner; + /** `process.platform`; injected so the macOS path can be tested anywhere. */ + readonly platform: NodeJS.Platform; +} + +/** + * On macOS the kernel version `node:os` reports (`24.5.0`) is not the version anyone looks for, + * so the product name and version come from `sw_vers`. Everywhere else `node:os` is the answer. + */ +export class NodeHostInfo implements HostInfo { + constructor(private readonly options: NodeHostInfoOptions) {} + + async read(): Promise { + const fallback: HostSystem = { arch: arch(), os: type(), osVersion: release() }; + if (this.options.platform !== "darwin") return fallback; + try { + const result = await this.options.processRunner.run("sw_vers", [], { + timeoutMs: SW_VERS_TIMEOUT_MS, + }); + if (result.code !== 0) return fallback; + const os = swVersField(result.stdout, "ProductName"); + const osVersion = swVersField(result.stdout, "ProductVersion"); + return os === undefined || osVersion === undefined + ? fallback + : { arch: fallback.arch, os, osVersion }; + } catch { + return fallback; + } + } +} + +function swVersField(output: string, key: string): string | undefined { + const value = output + .split(/\r?\n/) + .find((line) => line.startsWith(`${key}:`)) + ?.slice(key.length + 1) + .trim(); + return value === undefined || value === "" ? undefined : value; +} + +export class FakeHostInfo implements HostInfo { + constructor(private readonly system: HostSystem) {} + + // fallow-ignore-next-line unused-class-member -- reached through the HostInfo port by startDaemon. + read(): Promise { + return Promise.resolve(this.system); + } +} diff --git a/src/ports/index.ts b/src/ports/index.ts index c65534914..122cb7adc 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -56,6 +56,7 @@ export type { LogRecord } from "./logger.js"; export { CryptoIdGenerator, type IdGenerator } from "./id-generator.js"; export { CryptoTokenSecrets, type TokenSecrets } from "./token-secrets.js"; export { FakeSystemStats, NodeSystemStats, type SystemStats } from "./system-stats.js"; +export { FakeHostInfo, type HostInfo, type HostSystem, NodeHostInfo } from "./host-info.js"; export { FakeParentWatch, NodeParentWatch, type ParentWatch } from "./parent-watch.js"; export type { ParentWatchHandle } from "./parent-watch.js"; export { FakeProcessSupervisor, NodeProcessSupervisor } from "./process-supervisor.js"; diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index 99c747871..a1f3e9b8a 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -181,6 +181,57 @@ describe("connectSimlock: handshake", () => { await expect(callPromise).rejects.toMatchObject({ code: "BAD_FRAME" }); }); + it("rejects status.get from a worker with an over-long host string by the gateway's schema", async () => { + // A gateway reads each worker through this client (`WorkerLink`), so this parse is where + // a worker's host facts are bounded before they reach its view. + const connection = new ScriptedConnection(); + const connectPromise = connectSimlockAdmin({ connection, principal: "gw:instance-1" }); + await flushMicrotasks(); + completeHello(connection, { role: "admin" }); + const client = await connectPromise; + const status = { + capacity: { + android: { + limit: 1, + maxRunning: 1, + overLimit: false, + reserved: 0, + running: 0, + used: 0, + warm: 0, + }, + global: { maxRunning: 2, overLimit: false, reserved: 0, running: 0, warm: 0 }, + ios: { + limit: 1, + maxRunning: 1, + overLimit: false, + reserved: 0, + running: 0, + used: 0, + warm: 0, + }, + }, + daemon: { health: "running", mode: "worker" }, + devices: [], + host: { arch: "arm64", os: "macOS", osVersion: "15.5", tools: [] }, + leases: [], + queueDepth: 0, + }; + + const accepted = client.getStatus(); + await flushMicrotasks(); + connection.reply(connection.lastSentOf("status.get")!.id, status); + await expect(accepted).resolves.toMatchObject({ host: { os: "macOS" } }); + + const rejected = client.getStatus(); + await flushMicrotasks(); + connection.reply(connection.lastSentOf("status.get")!.id, { + ...status, + host: { ...status.host, osVersion: "1".repeat(129) }, + }); + await expect(rejected).rejects.toMatchObject({ code: "BAD_FRAME" }); + }); + it("wraps an error code it does not recognize as UNKNOWN_DAEMON_ERROR", async () => { const connection = new ScriptedConnection(); const connectPromise = connectSimlock({ connection }); From 274bb2b597d3b8049aa65407bfda3940eff3cbce Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 16:38:31 +0200 Subject: [PATCH 2/3] fix(core,drivers,e2e): bound host facts, name legacy SDK tools, close test gaps (#181) Host facts past the status.get schema's bounds are left out (a tool) or cut to length (a host string) in the core, so an odd value cannot fail the worker's own status.get. The Android driver names the legacy tools package tools rather than cmdline-tools. Tests now fail when the exit-code checks, the no-build Xcode case, the empty revision, the hostAbi wiring, the gateway's empty tool list, or either CLI host branch are broken. The fleet e2e checks both workers' host and catalog over HTTP. --- docs/CLI.md | 2 +- e2e/gateway-fleet.test.ts | 12 ++++--- src/cli/index.test.ts | 5 ++- src/core/host-facts.test.ts | 49 ++++++++++++++++++++++++++++ src/core/host-facts.ts | 26 +++++++++++++-- src/daemon/gateway-fleet.e2e.test.ts | 8 ++++- src/daemon/main.test.ts | 42 ++++++++++++++++++++++-- src/drivers/android/index.test.ts | 17 ++++++++-- src/drivers/android/index.ts | 9 +++-- src/drivers/ios/index.test.ts | 17 ++++++++-- src/ports/host-info.test.ts | 7 ++-- 11 files changed, 173 insertions(+), 21 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 97cf44da5..fd01fcffe 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -805,7 +805,7 @@ each platform tool its drivers use (`xcode` with its build; the Android `emulator`, `platform-tools` and `cmdline-tools`). A tool the worker cannot read is left out. `protocol` appears only on an `incompatible` worker and names both ranges, the worker's and the gateway's, so you can see which side -to upgrade. Worker ids are UUIDs; the human listing below abbreviates them. +to upgrade. Worker ids are UUIDs; the console example below shortens them to fit. `connection` is `connected`, `disconnected`, or `incompatible`. A **disconnected** worker keeps its last-known view (nothing is dispatched to it) until an diff --git a/e2e/gateway-fleet.test.ts b/e2e/gateway-fleet.test.ts index d2b9f4352..8c3b758d8 100644 --- a/e2e/gateway-fleet.test.ts +++ b/e2e/gateway-fleet.test.ts @@ -310,11 +310,15 @@ describe("gateway fleet", () => { }); expect(response.status).toBe(200); const overHttp = ((await response.json()) as { workers: WorkerView[] }).workers; + for (const label of ["worker-a", "worker-b"]) { + const view = overHttp.find((candidate) => candidate.label === label); + const fromCli = withTools.find((candidate) => candidate.label === label); + expect(view?.host).toBeDefined(); + expect(view?.host).toEqual(fromCli?.host); + expect(view?.catalog).toEqual(fromCli?.catalog); + } expect(xcodeOf(overHttp, "worker-a")?.version).toBe("16.4"); - expect( - overHttp.find((view) => view.label === "worker-b")?.catalog.find((e) => e.platform === "ios") - ?.modelRuntimes, - ).toEqual({ "iPhone 16": ["26.0"] }); + expect(xcodeOf(overHttp, "worker-b")?.version).toBe("26.0"); const catalog = await gateway.cli(["catalog", "--json"]); expect(catalog.code).toBe(0); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 68a84b8c2..0f4736eac 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1746,7 +1746,8 @@ describe("CLI: worker commands (ADR 0005 §8/§23)", () => { expect(output.stdout).toContain("wrk_1 (mac-mini-1): connected"); expect(output.stdout).toContain("ios 1/2"); - expect(output.stdout).toContain("1 lease(s)"); + // No host facts on this view yet, so the line ends at the lease count. + expect(output.stdout).toContain("1 lease(s)\n"); }); it("prints each worker's operating system, architecture, and tool versions", async () => { @@ -1976,6 +1977,8 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = await runCli(["status"], environment); expect(output.stdout).toContain("Daemon: running (gateway)"); + // A gateway runs no drivers: its host line names the machine and nothing after it. + expect(output.stdout).toContain("Host: Linux 6.8.0 x64\n"); expect(output.stdout).toContain("wrk_1: connected, drained"); expect(output.stdout).toContain("Device dev_1 on wrk_1: leased, mode full"); expect(output.stdout).toContain("Lease lease_1: agent-1 on wrk_1"); diff --git a/src/core/host-facts.test.ts b/src/core/host-facts.test.ts index 397ea5c33..18517ab05 100644 --- a/src/core/host-facts.test.ts +++ b/src/core/host-facts.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; +import { OPERATIONS } from "../contract/index.js"; import { FakeClock } from "../ports/index.js"; import type { DriverToolVersion } from "./driver.js"; import { HOST_FACTS_MAX_AGE_MS, HostFactsReader } from "./host-facts.js"; @@ -79,4 +80,52 @@ describe("HostFactsReader", () => { { name: "emulator", platform: "android", version: "36.1.0" }, ]); }); + + it("leaves out a tool whose strings do not fit status.get's bounds, and cuts an over-long host string", async () => { + const reader = new HostFactsReader({ + clock: new FakeClock(0), + drivers: [ + { + platform: "android", + toolVersions: () => + Promise.resolve([ + { name: "emulator", version: "9".repeat(129) }, + { name: "platform-tools", version: "36.0.0" }, + { name: "cmdline-tools", version: "" }, + ]), + }, + ], + system: { ...SYSTEM, osVersion: "1".repeat(200) }, + }); + + await reader.refresh(); + const facts = reader.current(); + + expect(facts.tools).toEqual([ + { name: "platform-tools", platform: "android", version: "36.0.0" }, + ]); + expect(facts.osVersion).toHaveLength(128); + expect(() => OPERATIONS["status.get"].output.shape.host.parse(facts)).not.toThrow(); + }); + + it("reports at most as many tools as status.get's bounds allow", async () => { + const reader = new HostFactsReader({ + clock: new FakeClock(0), + drivers: [ + { + platform: "android", + toolVersions: () => + Promise.resolve( + Array.from({ length: 40 }, (_, index) => ({ name: `tool-${index}`, version: "1" })), + ), + }, + ], + system: SYSTEM, + }); + + await reader.refresh(); + + expect(() => OPERATIONS["status.get"].output.shape.host.parse(reader.current())).not.toThrow(); + expect(reader.current().tools).toHaveLength(32); + }); }); diff --git a/src/core/host-facts.ts b/src/core/host-facts.ts index 9b3618b6a..d51ad169a 100644 --- a/src/core/host-facts.ts +++ b/src/core/host-facts.ts @@ -14,6 +14,15 @@ import type { Platform } from "./domain.js"; /** Fixed, not configured (ADR 0008 §9): tool versions change only when someone installs one. */ export const HOST_FACTS_MAX_AGE_MS = 60_000; +/** + * The bounds `status.get`'s `host` schema enforces (`hostFactsSchema` in the contract, which this + * module cannot import). A value past them would fail the daemon's own output check and take + * `status.get` down with it, so it is kept out here instead: a tool that does not fit is left + * out like one that cannot be read, and a host string that does not fit is cut to length. + */ +const MAX_HOST_STRING_LENGTH = 128; +const MAX_HOST_TOOLS = 32; + export interface HostToolVersion extends DriverToolVersion { readonly platform: Platform; } @@ -44,7 +53,11 @@ export class HostFactsReader { this.#clock = options.clock; this.#drivers = options.drivers; this.#logger = options.logger ?? new NoopLogger(); - this.#system = options.system; + this.#system = { + arch: options.system.arch.slice(0, MAX_HOST_STRING_LENGTH), + os: options.system.os.slice(0, MAX_HOST_STRING_LENGTH), + osVersion: options.system.osVersion.slice(0, MAX_HOST_STRING_LENGTH), + }; } /** @@ -59,7 +72,8 @@ export class HostFactsReader { ...this.#system, tools: [...this.#toolsByDriver.keys()] .sort((left, right) => left - right) - .flatMap((index) => this.#toolsByDriver.get(index) ?? []), + .flatMap((index) => this.#toolsByDriver.get(index) ?? []) + .slice(0, MAX_HOST_TOOLS), }; } @@ -79,7 +93,7 @@ export class HostFactsReader { const tools = await driver.toolVersions(); this.#toolsByDriver.set( index, - tools.map((tool) => ({ ...tool, platform: driver.platform })), + tools.filter(fitsBounds).map((tool) => ({ ...tool, platform: driver.platform })), ); } catch (error: unknown) { // The contract says a driver does not throw here. One that does keeps the tools it @@ -94,3 +108,9 @@ export class HostFactsReader { this.#readAt = this.#clock.now(); } } + +function fitsBounds(tool: DriverToolVersion): boolean { + return [tool.name, tool.version, ...(tool.build === undefined ? [] : [tool.build])].every( + (value) => value.length > 0 && value.length <= MAX_HOST_STRING_LENGTH, + ); +} diff --git a/src/daemon/gateway-fleet.e2e.test.ts b/src/daemon/gateway-fleet.e2e.test.ts index e1058e1dc..81472ce60 100644 --- a/src/daemon/gateway-fleet.e2e.test.ts +++ b/src/daemon/gateway-fleet.e2e.test.ts @@ -29,12 +29,13 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { FakeDriver } from "../core/index.js"; import type { Filesystem } from "../ports/index.js"; -import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; +import { FakeHostInfo, MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon } from "./main.js"; import type { DaemonServer } from "./server.js"; const GATEWAY_PORT = 48173; +const GATEWAY_HOST = { arch: "x64", os: "Linux", osVersion: "6.8.0" }; const GATEWAY_URL = `ws://127.0.0.1:${GATEWAY_PORT}`; /** Distinct from `GATEWAY_PORT` above so this file's second `it` never races the first one's * own listener through TIME_WAIT on the same port (H3, round 1 review: both are `it`s in this @@ -103,6 +104,7 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { }, dataDirectory: directory, filesystem: new MemoryFilesystem(), + hostInfo: new FakeHostInfo(GATEWAY_HOST), logger: new NoopLogger(), statePath: join(directory, "state.json"), version: "1.0.0-e2e", @@ -235,6 +237,10 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { expect(workerServes(workers, "Pixel-B")).toBe(true); }); + // The gateway's own host: the machine it runs on, and no tools, since it runs no drivers. + const status = await gateway.dispatch("status.get", {}, agentSession()); + expect(status.host).toEqual({ ...GATEWAY_HOST, tools: [] }); + const grant = await gateway.dispatch( "lease.request", { model: "Pixel-B", platform: "android", noWait: true }, diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index fdafda7ee..b00d9943c 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -827,6 +827,42 @@ describe("discoverDrivers on a host with an Android SDK", () => { ]); }); + it("hands the Android driver the ABI of the host architecture it was given", async () => { + const filesystem = await androidSdk(); + await filesystem.mkdirp(SIMLOCK_HOME); + await filesystem.writeFileAtomic( + join(SIMLOCK_HOME, "adb-server.json"), + JSON.stringify({ pid: 4242, port: 5038, startedAt: 1 }), + ); + // The profile list answers; the install that follows is refused once its argv is recorded. + const processRunner = new ScriptedProcessRunner([ + { + match: { args: ["list", "device"], command: /avdmanager$/ }, + result: { + code: 0, + stderr: "", + stdout: 'Available devices:\nid: 0 or "pixel_8"\n Name: Pixel 8\n', + }, + }, + ]); + + const { drivers } = await discoverAndroid(filesystem, new FakeTcpProbe([5038]), [4242], { + hostArch: "x64", + processRunner, + }); + await drivers + .find((driver) => driver.platform === "android") + ?.resolveSpec( + { model: "Pixel 8", osVersion: "35", platform: "android" }, + { allowDownload: true }, + ) + .catch(() => undefined); + + expect(processRunner.calls.flatMap((call) => call.args)).toContain( + "system-images;android-35;google_apis;x86_64", + ); + }); + /** The minimum layout `discoverSdk` accepts, in memory. */ async function androidSdk(): Promise { const filesystem = new MemoryFilesystem(); @@ -847,15 +883,17 @@ describe("discoverDrivers on a host with an Android SDK", () => { filesystem: MemoryFilesystem, tcpProbe: FakeTcpProbe, livePids: readonly number[] = [], - overrides: Partial> = {}, + overrides: Partial< + Pick + > = {}, ) { return discoverDrivers({ - ...overrides, clock: new FakeClock(), driversConfig: {}, eventBus: new EventBus(new FakeClock()), filesystem, hostArch: "arm64", + ...overrides, hostPlatform: "linux", idGenerator: new CryptoIdGenerator(), instanceId: INSTANCE_ID, diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 59e75c092..cf2645e06 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -2761,13 +2761,26 @@ describe("AndroidDriver toolVersions()", () => { ]); }); + it("names the legacy SDK tools package as tools when its sdkmanager is the one in use", async () => { + const filesystem = await androidFilesystem(); + await filesystem.rm(`${sdk}/cmdline-tools`); + const legacyTools = `${sdk}/tools/bin`; + await filesystem.mkdirp(legacyTools); + await filesystem.writeFileAtomic(`${legacyTools}/avdmanager`, "binary"); + await filesystem.writeFileAtomic(`${legacyTools}/sdkmanager`, "binary"); + await filesystem.writeFileAtomic(`${sdk}/tools/source.properties`, "Pkg.Revision=26.1.1\n"); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + await expect(driver.toolVersions()).resolves.toEqual([{ name: "tools", version: "26.1.1" }]); + }); + it("omits a tool whose source.properties cannot be read", async () => { const filesystem = await androidFilesystem(); await filesystem.writeFileAtomic(`${sdk}/emulator/source.properties`, "Pkg.Revision=35.4.9\n"); - // platform-tools has no source.properties; cmdline-tools has one without a revision. + // platform-tools has no source.properties; cmdline-tools has one with an empty revision. await filesystem.writeFileAtomic( `${sdk}/cmdline-tools/latest/source.properties`, - "Pkg.Desc=Android SDK Command-line Tools\n", + "Pkg.Desc=Android SDK Command-line Tools\nPkg.Revision=\n", ); const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index a89e7a3b6..b983668a8 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -1100,14 +1100,19 @@ export class AndroidDriver implements Driver { /** * Revisions of the SDK packages this driver runs: the emulator, platform-tools (adb), and the - * command-line tools whose `sdkmanager` it uses. Read from each package's `source.properties`, + * command-line tools (or legacy SDK tools) whose `sdkmanager` it uses. Read from each package's `source.properties`, * so no tool is started; a package whose file cannot be read is left out. */ async toolVersions(): Promise { const packages = [ { name: "emulator", path: dirname(this.#sdk.emulator) }, { name: "platform-tools", path: dirname(this.#sdk.adb) }, - { name: "cmdline-tools", path: dirname(dirname(this.#sdk.sdkmanager)) }, + // `/cmdline-tools//bin/sdkmanager`, or the obsolete `/tools/bin/` one + // this driver falls back to, which is a different package and is named as such. + { + name: this.#sdk.sdkmanager.includes("/cmdline-tools/") ? "cmdline-tools" : "tools", + path: dirname(dirname(this.#sdk.sdkmanager)), + }, ]; const versions = await Promise.all( packages.map(async ({ name, path }) => { diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index aef872cff..4e21785e9 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -2989,14 +2989,27 @@ describe("IosSimctlDriver toolVersions()", () => { expect(runner.calls[0]?.options.timeoutMs).toBeGreaterThan(0); }); + it("reports the Xcode version without a build when xcodebuild prints none", async () => { + const runner = new ScriptedProcessRunner([ + { + match: { args: ["-version"], command: "xcodebuild" }, + result: { code: 0, stderr: "", stdout: "Xcode 16.4\n" }, + }, + ]); + const driver = await createDriver(runner); + + await expect(driver.toolVersions()).resolves.toEqual([{ name: "xcode", version: "16.4" }]); + }); + it("reports no Xcode entry when xcodebuild fails", async () => { const runner = new ScriptedProcessRunner([ { match: { args: ["-version"], command: "xcodebuild" }, + // Output that would parse, so only the exit code can be what turns it away. result: { code: 1, - stderr: "xcode-select: error: tool 'xcodebuild' requires Xcode", - stdout: "", + stderr: "xcodebuild: error: timed out", + stdout: "Xcode 16.4\nBuild version 16F6\n", }, }, ]); diff --git a/src/ports/host-info.test.ts b/src/ports/host-info.test.ts index 6a73cd422..a907e890d 100644 --- a/src/ports/host-info.test.ts +++ b/src/ports/host-info.test.ts @@ -1,4 +1,4 @@ -import { release, type } from "node:os"; +import { arch, release, type } from "node:os"; import { describe, expect, it } from "vitest"; @@ -17,7 +17,7 @@ describe("NodeHostInfo", () => { const system = await new NodeHostInfo({ platform: "darwin", processRunner }).read(); - expect(system).toMatchObject({ os: "macOS", osVersion: "15.5" }); + expect(system).toEqual({ arch: arch(), os: "macOS", osVersion: "15.5" }); expect(processRunner.calls[0]?.options.timeoutMs).toBeGreaterThan(0); }); @@ -25,7 +25,8 @@ describe("NodeHostInfo", () => { const processRunner = new ScriptedProcessRunner([ { match: { args: [], command: "sw_vers" }, - result: { code: 1, stderr: "boom", stdout: "" }, + // Output that would parse, so only the exit code can be what turns it away. + result: { code: 1, stderr: "boom", stdout: SW_VERS_OUTPUT }, }, ]); From acfadb65c779fc38c455f8f064061879f34b1270 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 17:04:32 +0200 Subject: [PATCH 3/3] fix(core,drivers,contract): a failed tool read rejects and keeps the last value (#181) A driver now leaves out a tool that is not installed and rejects a read that fails, so the core can keep that driver's last answer. iOS treats xcodebuild's 'requires Xcode' as not installed and any other failure as a failed read. The core gives up on a driver read after 30 s so one stuck read cannot stop the rest. Size bounds live once, beside the contract's schema, as fitHostFacts, which the daemon applies to what it serves. --- docs/CLI.md | 14 ++++--- docs/CLIENT.md | 8 ++-- docs/HTTP-API.md | 6 ++- docs/internal/ARCHITECTURE.md | 7 +++- src/contract/schemas.test.ts | 39 ++++++++++++++++++++ src/contract/schemas.ts | 33 ++++++++++++++++- src/core/driver.ts | 10 +++-- src/core/host-facts.test.ts | 69 +++++++++++++---------------------- src/core/host-facts.ts | 53 ++++++++++++++++----------- src/daemon/main.test.ts | 46 +++++++++++++++-------- src/daemon/main.ts | 5 ++- src/drivers/ios/index.test.ts | 29 +++++++++++++-- src/drivers/ios/index.ts | 27 +++++++------- src/ports/host-info.test.ts | 10 +++++ 14 files changed, 236 insertions(+), 120 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index fd01fcffe..215882cd2 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -728,8 +728,9 @@ simlock worker undrain simlock worker remove ``` -`list --json` prints one worker view per connected-or-remembered worker. A -real answer, trimmed to one worker: +`list --json` prints one worker view per connected-or-remembered worker. This +one is a real answer from a test fleet whose drivers are simulated, which is +why its Android catalog looks thin, trimmed to one worker: ```json { @@ -802,8 +803,8 @@ runtime before sending it a request that needs one. `catalog` is what that worker can lease, each model with the runtimes it pairs with. `host` is the machine: operating system, its version, CPU architecture, and the version of each platform tool its drivers use (`xcode` with its build; the Android -`emulator`, `platform-tools` and `cmdline-tools`). A tool the worker cannot -read is left out. `protocol` appears only on an `incompatible` worker and +`emulator`, `platform-tools` and `cmdline-tools`). A tool the worker does not +have is left out. `protocol` appears only on an `incompatible` worker and names both ranges, the worker's and the gateway's, so you can see which side to upgrade. Worker ids are UUIDs; the console example below shortens them to fit. @@ -974,8 +975,9 @@ what machine the daemon runs on: `os`, `osVersion`, `arch`, and `tools`, one entry per platform tool its drivers use with the `platform`, `name`, `version` and, for Xcode, `build`. Tool versions are read when the daemon starts and again in the background once a minute has passed, so `status` -never waits for them; right after a start, or for a tool that cannot be read, -`tools` has no entry. A gateway runs no drivers, so its own `host` has no +never waits for them. Right after a start, or for a tool that is not +installed, `tools` has no entry; if a later read fails, the last version read +stays. A gateway runs no drivers, so its own `host` has no tools; each worker's is on its worker view. Do not confuse it with each device's own `mode`, the device mode (`"slim"` or `"full"`). Against a **gateway** the same view is the fleet's: capacity summed over the connected workers, every diff --git a/docs/CLIENT.md b/docs/CLIENT.md index dd2210a5a..a3e6b7f1e 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -218,10 +218,10 @@ const { host } = await client.getStatus(); ``` - `tools` has one entry per platform tool the daemon's drivers use. A tool - that cannot be read is left out, and right after a daemon starts the list - can be empty for a moment: versions are read in the background, so - `getStatus` never waits for them. They are read again once a minute has - passed. + that is not installed is left out. Versions are read in the background, so + `getStatus` never waits for them, and right after a daemon starts the list + can be empty for a moment. They are read again once a minute has passed; + if a read fails, the version from the last good read stays. - A gateway reports its own machine with no tools, since it runs no drivers. Each worker's `host` is on its entry in `workers`, and on `listWorkers()` from the admin client. diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 5d7d24ea7..db6d8b3a9 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -154,7 +154,8 @@ tool its drivers use: The daemon works these out from the machine; no config key changes them. Tool versions are read at start and again in the background once a minute has passed, so this endpoint never waits for them. Right after a start, or for a -tool that cannot be read, `tools` has no entry for it. +tool that is not installed, `tools` has no entry for it; if a later read +fails, the last version read stays. On a **gateway** the numbers are the fleet's — capacity summed across connected workers, every gateway-issued and local lease, every device, the gateway @@ -605,7 +606,8 @@ workers of its own and does not implement the underlying operations at all. - `DELETE /v1/workers/{id}/drain` — undrain it, putting it back in rotation. - `DELETE /v1/workers/{id}` — forget a worker's view. -`GET /v1/workers`, a real answer trimmed to one worker: +`GET /v1/workers`, a real answer from a test fleet whose drivers are +simulated (hence the thin Android catalog), trimmed to one worker: ```json { diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index d63811f68..efe3ea9bf 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -468,8 +468,11 @@ The **host facts** are the `host` block of the worker's `status.get` port, read once at the worker's start, and tool versions from each driver's `toolVersions()`, joined in `core/host-facts.ts`. The worker serves them from memory, so `status.get` stays a liveness probe that never starts a process; -a stale value starts a background re-read after 60 s. They come over on every -status refresh. An `incompatible` worker is asked nothing, so its view +a stale value starts a background re-read after 60 s. A driver leaves out a +tool that is not installed and rejects a read that fails; the core then keeps +that driver's last answer, and gives up on a read after 30 s. The contract's +`fitHostFacts` cuts what the daemon serves to the schema's bounds. They come +over on every status refresh. An `incompatible` worker is asked nothing, so its view carries none. A gateway's own `status.get` reports the gateway's machine with no tools. diff --git a/src/contract/schemas.test.ts b/src/contract/schemas.test.ts index 920a08baa..1c8454eaf 100644 --- a/src/contract/schemas.test.ts +++ b/src/contract/schemas.test.ts @@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest"; import { deviceRecordSchema, + fitHostFacts, grantedDeviceSchema, + hostFactsSchema, leaseGrantSchema, statusDeviceSchema, } from "./schemas.js"; @@ -218,3 +220,40 @@ describe("statusDeviceSchema's device projection", () => { expect(() => deviceRecordSchema.parse({ ...record, mode: "reduced" })).toThrow(); }); }); + +describe("fitHostFacts", () => { + it("cuts over-long host strings, leaves out tools that do not fit, and stops at the list's maximum", () => { + const fitted = fitHostFacts({ + arch: "a".repeat(200), + os: "o".repeat(200), + osVersion: "1".repeat(200), + tools: [ + { name: "emulator", platform: "android" as const, version: "9".repeat(129) }, + { name: "cmdline-tools", platform: "android" as const, version: "" }, + ...Array.from({ length: 40 }, (_, index) => ({ + name: `tool-${index}`, + platform: "android" as const, + version: "1", + })), + ], + }); + + expect(fitted.arch).toHaveLength(128); + expect(fitted.os).toHaveLength(128); + expect(fitted.osVersion).toHaveLength(128); + expect(fitted.tools).toHaveLength(32); + expect(fitted.tools[0]?.name).toBe("tool-0"); + expect(() => hostFactsSchema.parse(fitted)).not.toThrow(); + }); + + it("leaves facts that already fit as they are", () => { + const host = { + arch: "arm64", + os: "macOS", + osVersion: "15.5", + tools: [{ build: "16F6", name: "xcode", platform: "ios" as const, version: "16.4" }], + }; + + expect(fitHostFacts(host)).toEqual(host); + }); +}); diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 307099193..cca1446bf 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -284,7 +284,9 @@ export const daemonHealthSchema = z.enum(["starting", "running", "failed"]); * ADR 0008 §5: what machine a daemon runs on. Every string and the `tools` list are bounded, * because a gateway stores what each worker reports in that worker's view (safety rule 10). */ -const hostStringSchema = z.string().min(1).max(128); +const MAX_HOST_STRING_LENGTH = 128; +const MAX_HOST_TOOLS = 32; +const hostStringSchema = z.string().min(1).max(MAX_HOST_STRING_LENGTH); export const hostFactsSchema = z.object({ /** Operating system product name (`macOS`), or the kernel name where there is none. */ @@ -303,9 +305,36 @@ export const hostFactsSchema = z.object({ build: hostStringSchema.optional(), }), ) - .max(32), + .max(MAX_HOST_TOOLS), }); +/** The shape `fitHostFacts` reads: the core's own host facts type and this schema's both fit. */ +interface HostFactsShape { + readonly arch: string; + readonly os: string; + readonly osVersion: string; + readonly tools: readonly unknown[]; +} + +/** + * Brings host facts a daemon read from its own machine within `hostFactsSchema`'s bounds, so an + * odd value cannot fail the daemon's own `status.get` output check and take its liveness probe + * down (ADR 0008 §7). A tool that does not fit is left out, like one that cannot be read; a host + * string that does not fit is cut to length; the list stops at its maximum. Lives beside the + * schema so the bounds are written once. + */ +export function fitHostFacts(host: Host): Host { + const fit = (value: string) => value.slice(0, MAX_HOST_STRING_LENGTH); + const tool = hostFactsSchema.shape.tools.element; + return { + ...host, + arch: fit(host.arch), + os: fit(host.os), + osVersion: fit(host.osVersion), + tools: host.tools.filter((entry) => tool.safeParse(entry).success).slice(0, MAX_HOST_TOOLS), + }; +} + export const platformCatalogSchema = z.object({ platform: platformSchema, models: z.array(z.string()), diff --git a/src/core/driver.ts b/src/core/driver.ts index 15c205fce..24df9f5fd 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -287,10 +287,12 @@ export interface Driver { */ advisories?(): Promise; /** - * The versions of the platform tools this driver uses, for `status.get`'s host facts. Same - * contract as `advisories`: read-only, never downloads, and never throws -- a tool that - * cannot be read is left out. Every process it starts is bounded. Optional: a driver with no - * tools to report omits it. + * The versions of the platform tools this driver uses, for `status.get`'s host facts. + * Read-only and never downloads, like `advisories`. A tool that is not installed is left out. + * A read that fails -- a tool that is there but errors, times out, or answers in a shape the + * driver does not know -- rejects, and the core keeps what this driver reported last + * (`HostFactsReader`). Every process it starts is bounded. Optional: a driver with no tools to + * report omits it. */ toolVersions?(): Promise; } diff --git a/src/core/host-facts.test.ts b/src/core/host-facts.test.ts index 18517ab05..07d8111d8 100644 --- a/src/core/host-facts.test.ts +++ b/src/core/host-facts.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from "vitest"; -import { OPERATIONS } from "../contract/index.js"; import { FakeClock } from "../ports/index.js"; import type { DriverToolVersion } from "./driver.js"; import { HOST_FACTS_MAX_AGE_MS, HostFactsReader } from "./host-facts.js"; @@ -81,51 +80,33 @@ describe("HostFactsReader", () => { ]); }); - it("leaves out a tool whose strings do not fit status.get's bounds, and cuts an over-long host string", async () => { - const reader = new HostFactsReader({ - clock: new FakeClock(0), - drivers: [ - { - platform: "android", - toolVersions: () => - Promise.resolve([ - { name: "emulator", version: "9".repeat(129) }, - { name: "platform-tools", version: "36.0.0" }, - { name: "cmdline-tools", version: "" }, - ]), - }, - ], - system: { ...SYSTEM, osVersion: "1".repeat(200) }, - }); + it("gives up on a driver read that never settles, keeps that driver's last tools, and re-reads the others", async () => { + const clock = new FakeClock(0); + const ios = scriptedDriver("ios"); + const android = scriptedDriver("android"); + const reader = new HostFactsReader({ clock, drivers: [ios, android], system: SYSTEM }); + const first = reader.refresh(); + ios.answer([{ name: "xcode", version: "16.4" }]); + android.answer([{ name: "emulator", version: "35.4.9" }]); + await first; - await reader.refresh(); - const facts = reader.current(); + // The second read: iOS never answers. + clock.advance(HOST_FACTS_MAX_AGE_MS); + const second = reader.refresh(); + android.answer([{ name: "emulator", version: "36.1.0" }]); + // Let Android's answer land before the clock runs out on iOS. + for (let turn = 0; turn < 10; turn += 1) await Promise.resolve(); + clock.advance(30_000); + await second; - expect(facts.tools).toEqual([ - { name: "platform-tools", platform: "android", version: "36.0.0" }, + expect(reader.current().tools).toEqual([ + { name: "xcode", platform: "ios", version: "16.4" }, + { name: "emulator", platform: "android", version: "36.1.0" }, ]); - expect(facts.osVersion).toHaveLength(128); - expect(() => OPERATIONS["status.get"].output.shape.host.parse(facts)).not.toThrow(); - }); - - it("reports at most as many tools as status.get's bounds allow", async () => { - const reader = new HostFactsReader({ - clock: new FakeClock(0), - drivers: [ - { - platform: "android", - toolVersions: () => - Promise.resolve( - Array.from({ length: 40 }, (_, index) => ({ name: `tool-${index}`, version: "1" })), - ), - }, - ], - system: SYSTEM, - }); - - await reader.refresh(); - - expect(() => OPERATIONS["status.get"].output.shape.host.parse(reader.current())).not.toThrow(); - expect(reader.current().tools).toHaveLength(32); + // The stuck read let go of the single flight: the next one asks both drivers again. + clock.advance(HOST_FACTS_MAX_AGE_MS); + reader.current(); + expect(ios.reads).toBe(3); + expect(android.reads).toBe(3); }); }); diff --git a/src/core/host-facts.ts b/src/core/host-facts.ts index d51ad169a..ddab151c6 100644 --- a/src/core/host-facts.ts +++ b/src/core/host-facts.ts @@ -5,6 +5,8 @@ * * `status.get` is the gateway's liveness probe, so it never waits here: facts are served from * memory, and a re-read starts in the background once they are older than `HOST_FACTS_MAX_AGE_MS`. + * Nothing here enforces `status.get`'s size bounds; the contract's `fitHostFacts` does, where the + * daemon serves these. */ import type { Clock, HostSystem, Logger } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; @@ -15,13 +17,12 @@ import type { Platform } from "./domain.js"; export const HOST_FACTS_MAX_AGE_MS = 60_000; /** - * The bounds `status.get`'s `host` schema enforces (`hostFactsSchema` in the contract, which this - * module cannot import). A value past them would fail the daemon's own output check and take - * `status.get` down with it, so it is kept out here instead: a tool that does not fit is left - * out like one that cannot be read, and a host string that does not fit is cut to length. + * The core's own bound on one driver's read (architecture rule 11). A driver bounds the + * processes it starts; this covers one that never settles anyway, which would otherwise hold + * the single in-flight read open and stop every other driver from being re-read. A read that + * runs out is a failed read: that driver keeps what it reported last. */ -const MAX_HOST_STRING_LENGTH = 128; -const MAX_HOST_TOOLS = 32; +const TOOL_READ_TIMEOUT_MS = 30_000; export interface HostToolVersion extends DriverToolVersion { readonly platform: Platform; @@ -53,11 +54,7 @@ export class HostFactsReader { this.#clock = options.clock; this.#drivers = options.drivers; this.#logger = options.logger ?? new NoopLogger(); - this.#system = { - arch: options.system.arch.slice(0, MAX_HOST_STRING_LENGTH), - os: options.system.os.slice(0, MAX_HOST_STRING_LENGTH), - osVersion: options.system.osVersion.slice(0, MAX_HOST_STRING_LENGTH), - }; + this.#system = options.system; } /** @@ -72,8 +69,7 @@ export class HostFactsReader { ...this.#system, tools: [...this.#toolsByDriver.keys()] .sort((left, right) => left - right) - .flatMap((index) => this.#toolsByDriver.get(index) ?? []) - .slice(0, MAX_HOST_TOOLS), + .flatMap((index) => this.#toolsByDriver.get(index) ?? []), }; } @@ -90,14 +86,14 @@ export class HostFactsReader { this.#drivers.map(async (driver, index) => { if (driver.toolVersions === undefined) return; try { - const tools = await driver.toolVersions(); + const tools = await this.#bounded(driver.toolVersions()); this.#toolsByDriver.set( index, - tools.filter(fitsBounds).map((tool) => ({ ...tool, platform: driver.platform })), + tools.map((tool) => ({ ...tool, platform: driver.platform })), ); } catch (error: unknown) { - // The contract says a driver does not throw here. One that does keeps the tools it - // reported last, so a passing failure does not blank the host's status. + // A failed read, which a driver reports by rejecting: keep the tools it reported last, + // so a passing failure does not blank the host's status (architecture rule 12). this.#logger.warn("Tool version read failed", { platform: driver.platform, reason: error instanceof Error ? error.message : "unknown", @@ -107,10 +103,23 @@ export class HostFactsReader { ); this.#readAt = this.#clock.now(); } -} -function fitsBounds(tool: DriverToolVersion): boolean { - return [tool.name, tool.version, ...(tool.build === undefined ? [] : [tool.build])].every( - (value) => value.length > 0 && value.length <= MAX_HOST_STRING_LENGTH, - ); + /** Rejects once `TOOL_READ_TIMEOUT_MS` passes; the timer is cancelled when `read` settles. */ + #bounded(read: Promise): Promise { + return new Promise((resolve, reject) => { + const timer = this.#clock.setTimer(TOOL_READ_TIMEOUT_MS, () => { + reject(new Error(`Tool version read did not finish within ${TOOL_READ_TIMEOUT_MS} ms`)); + }); + read.then( + (value) => { + this.#clock.cancel(timer); + resolve(value); + }, + (error: unknown) => { + this.#clock.cancel(timer); + reject(error instanceof Error ? error : new Error(String(error))); + }, + ); + }); + } } diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index b00d9943c..acbfcf0f3 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -100,6 +100,14 @@ class DisposableFakeDriver extends FakeDriver { } } +async function agentStatus(daemon: DaemonServer) { + return (await daemon.dispatch( + "status.get", + {}, + { manageEventSubscription: () => undefined, principal: "agent", role: "agent" }, + )) as { readonly host: { readonly tools: readonly unknown[] } }; +} + /** A fake driver that reports tool versions, which `FakeDriver` does not. */ class ToolsFakeDriver extends FakeDriver { constructor( @@ -218,14 +226,14 @@ describe("startDaemon", () => { ); }); - it("starts, and reports the host and every tool read, while one driver's tool read never answers", async () => { + it("starts and reports no entry for a driver whose tool read fails, and every other tool", async () => { const clock = new FakeClock(1_000); const { daemon } = await start({ drivers: [ new ToolsFakeDriver( { availableOsVersions: ["26.5"], clock, platform: "ios" }, - // What an iOS driver whose `xcodebuild` never answers looks like from here. - () => new Promise(() => undefined), + // What an iOS driver whose `xcodebuild` fails looks like from here. + () => Promise.reject(new Error("xcodebuild -version exited with 1")), ), new ToolsFakeDriver({ availableOsVersions: ["35"], clock, platform: "android" }, () => Promise.resolve([{ name: "emulator", version: "35.4.9" }]), @@ -235,18 +243,7 @@ describe("startDaemon", () => { }); await expect - .poll(async () => { - const status = (await daemon.dispatch( - "status.get", - {}, - { - manageEventSubscription: () => undefined, - principal: "agent", - role: "agent", - }, - )) as { readonly host: unknown }; - return status.host; - }) + .poll(async () => (await agentStatus(daemon)).host) .toEqual({ arch: "arm64", os: "macOS", @@ -255,6 +252,25 @@ describe("startDaemon", () => { }); }); + it("answers status.get when a driver reports a tool version past the contract's bounds", async () => { + const clock = new FakeClock(1_000); + const { daemon } = await start({ + drivers: [ + new ToolsFakeDriver({ availableOsVersions: ["35"], clock, platform: "android" }, () => + Promise.resolve([ + { name: "emulator", version: "9".repeat(500) }, + { name: "platform-tools", version: "36.0.0" }, + ]), + ), + ], + hostInfo: new FakeHostInfo({ arch: "arm64", os: "macOS", osVersion: "15.5" }), + }); + + await expect + .poll(async () => (await agentStatus(daemon)).host.tools) + .toEqual([{ name: "platform-tools", platform: "android", version: "36.0.0" }]); + }); + it("reads tool versions at start, before anything asks for status", async () => { const clock = new FakeClock(1_000); let reads = 0; diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 8ecf0d619..011a57d15 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -3,6 +3,7 @@ import { join, resolve } from "node:path"; import { pathToFileURL } from "node:url"; import { EVENT_FILE_NAME, EventBus, EventHistory, type EventBusLogger } from "../bus/index.js"; +import { fitHostFacts } from "../contract/index.js"; import { type Config, type ConfigOverrides, @@ -339,7 +340,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise hostFacts.current(), + hostFacts: () => fitHostFacts(hostFacts.current()), host: new DaemonEndpointHost({ connector: ipc, endpoint: socketPath, @@ -661,7 +662,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise daemon.health, - host: { ...options.hostSystem, tools: [] }, + host: fitHostFacts({ ...options.hostSystem, tools: [] }), leaseIndex, logger: logger.child("gateway"), tokens, diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 4e21785e9..bfb8a329b 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -3001,15 +3001,15 @@ describe("IosSimctlDriver toolVersions()", () => { await expect(driver.toolVersions()).resolves.toEqual([{ name: "xcode", version: "16.4" }]); }); - it("reports no Xcode entry when xcodebuild fails", async () => { + it("reports no Xcode entry when only the command line tools are installed", async () => { const runner = new ScriptedProcessRunner([ { match: { args: ["-version"], command: "xcodebuild" }, - // Output that would parse, so only the exit code can be what turns it away. result: { code: 1, - stderr: "xcodebuild: error: timed out", - stdout: "Xcode 16.4\nBuild version 16F6\n", + stderr: + "xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance", + stdout: "", }, }, ]); @@ -3017,6 +3017,27 @@ describe("IosSimctlDriver toolVersions()", () => { await expect(driver.toolVersions()).resolves.toEqual([]); }); + + it.each([ + // Output that would parse, so only the exit code can be what turns it away. + ["exits non-zero", { code: 1, stderr: "error", stdout: "Xcode 16.4\nBuild version 16F6\n" }], + ["is killed by its timeout", { code: null, stderr: "", stdout: "" }], + ["prints no Xcode version", { code: 0, stderr: "", stdout: "something else\n" }], + ])("rejects when xcodebuild %s", async (_case, result) => { + const runner = new ScriptedProcessRunner([ + { match: { args: ["-version"], command: "xcodebuild" }, result }, + ]); + const driver = await createDriver(runner); + + await expect(driver.toolVersions()).rejects.toThrow(/xcodebuild/); + }); + + it("rejects when xcodebuild cannot be started", async () => { + // No scripted invocation: the runner refuses to start it, as a spawn failure would. + const driver = await createDriver(new ScriptedProcessRunner([])); + + await expect(driver.toolVersions()).rejects.toThrow(); + }); }); function createDriver( diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 788c094e4..9a528c680 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -1222,22 +1222,23 @@ export class IosSimctlDriver implements Driver { } /** - * The Xcode version and build `xcodebuild -version` prints. Anything else -- no Xcode, a - * failed or timed-out run, output in a shape this does not know -- reports no entry. + * The Xcode version and build `xcodebuild -version` prints. A Mac with only the command line + * tools has an `xcodebuild` that refuses to run without Xcode: that is no Xcode, and reports + * no entry. Any other failure -- a run that errors, times out, or prints a shape this does not + * know -- rejects, so the core keeps the version it last read. */ async toolVersions(): Promise { - try { - const result = await this.#processRunner.run("xcodebuild", ["-version"], { - timeoutMs: XCODE_VERSION_TIMEOUT_MS, - }); - if (result.code !== 0) return []; - const version = /^Xcode (\S+)$/m.exec(result.stdout)?.[1]; - const build = /^Build version (\S+)$/m.exec(result.stdout)?.[1]; - if (version === undefined) return []; - return [{ name: "xcode", version, ...(build === undefined ? {} : { build }) }]; - } catch { - return []; + const result = await this.#processRunner.run("xcodebuild", ["-version"], { + timeoutMs: XCODE_VERSION_TIMEOUT_MS, + }); + if (result.code !== 0) { + if (/requires Xcode/.test(result.stderr)) return []; + throw new Error(`xcodebuild -version exited with ${String(result.code)}`); } + const version = /^Xcode (\S+)$/m.exec(result.stdout)?.[1]; + const build = /^Build version (\S+)$/m.exec(result.stdout)?.[1]; + if (version === undefined) throw new Error("xcodebuild -version printed no Xcode version"); + return [{ name: "xcode", version, ...(build === undefined ? {} : { build }) }]; } /** diff --git a/src/ports/host-info.test.ts b/src/ports/host-info.test.ts index a907e890d..ae9ff0667 100644 --- a/src/ports/host-info.test.ts +++ b/src/ports/host-info.test.ts @@ -35,6 +35,16 @@ describe("NodeHostInfo", () => { expect(system).toMatchObject({ os: type(), osVersion: release() }); }); + it("falls back to the kernel name and release when sw_vers cannot be started", async () => { + // No scripted invocation: the runner refuses to start it, as a spawn failure would. + const system = await new NodeHostInfo({ + platform: "darwin", + processRunner: new ScriptedProcessRunner([]), + }).read(); + + expect(system).toMatchObject({ os: type(), osVersion: release() }); + }); + it("does not run sw_vers on another operating system", async () => { const processRunner = new ScriptedProcessRunner([]);