diff --git a/docs/CLI.md b/docs/CLI.md index 4cfb767e4..85f63305c 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -26,6 +26,42 @@ pointer to `simlock --help`, so a human hitting one from a terminal isn't stranded with only a JSON blob — the full command banner itself is no longer dumped to stderr on every failure, only on request via `--help`. +## Global flags + +Two flags are accepted anywhere on the command line, before or after the +command: + +- `--token ` (or `--token=`) connects as admin with that + credential; see [Admin credential resolution](#admin-credential-resolution). +- `--gateway` sends the command, the daemon auto-start it may trigger, and + `simlock mcp` to this machine's gateway (the daemon in `~/.simlock/gateway`) + in place of its worker (the daemon in `~/.simlock`). It takes no value: + `--gateway=yes` is a usage error. Without the flag, every command goes to + the worker. + +A machine has a gateway only after `simlock --gateway daemon start` (the first +start creates it) or `simlock --gateway config set ` (which writes +its `config.json`). With none, every other `--gateway` command (`status`, +`daemon status`, `daemon stop`, `daemon logs`, `events`, `config get`, +`lease`, and the rest) exits 2 with `GATEWAY_NOT_PRESENT` and starts nothing, +reads nothing and writes nothing; a `--gateway mcp` tool call fails with the +same code. `--help` still prints usage, except after `adb` or `simctl`. + +To run a gateway beside the worker on one machine: + +```sh +simlock --gateway daemon start +simlock status --json | jq -r .daemon.mode +# worker +simlock --gateway status --json | jq -r .daemon.mode +# gateway +``` + +The worker and the gateway each keep their own config, state, socket and log. +A worker listens for HTTP on 4701 and a gateway on 4700 unless +`http.port` says otherwise, so both can have HTTP on at once. A second worker +for the same user cannot start: the running worker's socket refuses it. + ## Prerequisites Simlock drives the platform tools already on the machine. It does not install @@ -89,6 +125,7 @@ command starts it again) to bring the platform up. | 2 | `BAD_REQUEST` | request payload failed validation | | 2 | `UNSUPPORTED_IN_GATEWAY_MODE` | this command acts on one machine (its devices, or its installed components) and the daemon answering is a gateway; run it on the worker, or for `component install` name the workers with `--worker` or `--all-workers` | | 2 | `UNSUPPORTED_IN_WORKER_MODE` | this command acts on a gateway's workers or alert destinations (`worker drain`, `undrain`, `remove`, `alerts test`, or `component install --worker`/`--all-workers`) and the daemon answering is a single host; run it against the gateway, or for `component install` drop the worker flag to install on this host | +| 2 | `GATEWAY_NOT_PRESENT` | `--gateway` on a machine with no gateway (also the code a `--gateway mcp` tool call fails with); start one with `simlock --gateway daemon start` | | 2 | `WORKER_CONNECTED` | `worker remove` on a worker whose uplink is still open; `drain` it and let it disconnect first | | 2 | `UNKNOWN_REQUEST` | the daemon has no such operation — usually a client newer than the daemon | | 2 | `PASSTHROUGH_REFUSED` | a `simctl`/`adb`/`devicectl` verb simlock refuses, a caller-supplied `--set`/`-P`, or a bare `adb shell` where there is no terminal to give it | @@ -862,10 +899,10 @@ startup to recover. A **gateway** is a simlock daemon that owns no devices and fronts the workers that joined it (see -[CONFIGURATION.md](CONFIGURATION.md#modes-gateway-and-worker) for `mode` and -the keys each side reads). Point the CLI at one the way you point it at any -daemon: `SIMLOCK_HOME` selects the data directory, and the daemon socket in -it is what the CLI connects to. **The commands do not change.** A gateway +[CONFIGURATION.md](CONFIGURATION.md#modes-gateway-and-worker) for the keys each +side reads). Point the CLI at one with the global `--gateway` flag (see +[Global flags](#global-flags)): the gateway's daemon socket, in +`~/.simlock/gateway`, is what the CLI connects to. **The commands do not change.** A gateway implements the same contract a worker does, so this whole document still applies; what follows is only the handful of places where you can tell. @@ -1272,8 +1309,8 @@ the maintenance. `undrain` puts it back in rotation. Draining sticks until you undrain it. It is your intent about that machine, not something read off it, so it lives in the gateway's **worker registry** — -the one piece of gateway state that is persisted (a small file under the -gateway's `SIMLOCK_HOME`, owner-only) as opposed to the worker *view*, which +the one piece of gateway state that is persisted (a small file in the +gateway's folder, owner-only) as opposed to the worker *view*, which is rebuilt on every connect. A drained worker that restarts comes back drained, and so does one whose *gateway* restarted. Nothing but `undrain` puts a machine back in rotation, which is the point: an operator who drained @@ -1535,7 +1572,7 @@ shows `starting` after its connection state and `leases unknown` in place of a lease count, in the same way. Human-oriented overview: daemon health *and mode*, the web console's address -when HTTP is enabled (`Console: http://127.0.0.1:4700/`, see +when HTTP is enabled (`Console: http://127.0.0.1:4701/`, see [CONSOLE.md](CONSOLE.md); `daemon.consoleUrl` in `--json`), the host it runs on (`Host: macOS 15.5 arm64; xcode 16.4 (16F6), emulator 35.4.9`), its load (`Load: CPU 34% busy (10 cores) · memory 9.8 GiB of 32.0 GiB available · ...`; `load` in `--json`), managed capacity @@ -1598,7 +1635,7 @@ for example after a restart with larger per-device sizes; until a device is deleted, none is created, and no shut-down slim device boots if its slim size is smaller than the full size. -Against a **gateway** (`config.mode: "gateway"`) the same command +Against a **gateway** (`simlock --gateway status`) the same command answers for the whole fleet, in the same shape: the daemon line reads `running (gateway)`, capacity is summed across the connected workers (the RAM budget over those that report one, over its limit when any worker is; a @@ -2465,9 +2502,10 @@ unanswered probe times out with `DAEMON_STARTUP_FAILED`. A connection to an already listening daemon keeps the usual `DAEMON_CONNECTION_LOST` behavior. Manage the daemon explicitly. Other commands auto-start it on demand; `daemon` -exists for operators and debugging. `start` starts whichever mode -`config.mode` selects — a worker (the default) or a gateway — and -`status` reports it, both in the human line (`Daemon: running (gateway)`) and +exists for operators and debugging. `start` starts the worker, and +`simlock --gateway daemon start` starts the gateway; a second worker for the +same user cannot start, because the running one's socket refuses it. `status` +reports the role, both in the human line (`Daemon: running (gateway)`) and as `daemon.mode` under `--json`. With HTTP enabled, `start` and `status` also print the web console's address on a `Console:` line (see [CONSOLE.md](CONSOLE.md)). `stop` does not touch leases: they persist, @@ -2499,8 +2537,8 @@ version mismatch) — the two used to be reported identically as "stopped". A daemon that refuses to boot because of its configuration — a `lease.defaultTtlMs` above `lease.maxTtlMs` or a non-positive value for -either, `mode: "gateway"` with `http.enabled: false`, or, in worker mode, -`gateway.url` without `gateway.token` or the reverse; see +either, a gateway with `http.enabled: false`, a `config.json` that still sets +`mode`, or, on a worker, `gateway.url` without `gateway.token` or the reverse; see [CONFIGURATION.md](CONFIGURATION.md) for the full set — fails the start rather than picking a value the operator did not write. A command that would auto-start the daemon (`simlock daemon start`, `simlock lease`) loads @@ -2601,30 +2639,29 @@ when it holds one: that key no longer exists (the event history is one SQLite file, not rotated generations). The command then prints `Removed eventLog.rotateBytes from : it is no longer used.` on stderr, once. -`simlock config set mode gateway` turns this daemon into a **gateway** — one -that owns no devices and fronts the workers that join it — and `simlock -config set mode worker` turns it back. Like every `config set`, it is a -validated file write, and config is daemon *input*, read at start: the -running daemon keeps running in the mode it started in until -`simlock daemon stop` and the next start. The same command sets a worker's -`gateway.url` and `gateway.token` to join a fleet. See +`simlock config set` writes the worker's `config.json`, and `simlock --gateway +config set` writes the gateway's (and makes the gateway present). Like every +`config set`, it is a validated file write, and config is daemon *input*, read +at start: a running daemon keeps its settings until `daemon stop` and the next +start. The same command sets a worker's `gateway.url` and `gateway.token` to +join a fleet. `mode` is no longer a config key; setting it exits 2 with a +message that says to use `--gateway` instead, and a `config.json` that still +has it is refused at load. See [CONFIGURATION.md](CONFIGURATION.md#modes-gateway-and-worker) for which keys -each mode reads. +each role reads. An object value takes JSON: `simlock config set http.proxyAuth '{"header":"cf-access-jwt-assertion","jwksUrl":"https://…","issuer":"https://…","audience":"…"}'`. Each `config set` checks the whole file, so the four required `http.proxyAuth` keys go in together as one object; one alone is refused (see [CONFIGURATION.md](CONFIGURATION.md#signing-in-through-a-proxy)). -Switching to `gateway` is **two keys, not one**: `mode` and `http.enabled`. A gateway is the fleet's contact point, so it must listen on HTTP — workers -open their uplinks there and remote agents lease through it — and -`mode: "gateway"` with `http.enabled: false` is therefore rejected at load -and the daemon does not start, naming the key. It is the one gateway config -pair that fails rather than warns, for the same reason a `lease.defaultTtlMs` -above `lease.maxTtlMs` fails: there is no safe way to read it. So: +open their uplinks there and remote agents lease through it — and a gateway +with `http.enabled: false` is rejected at load and the daemon does not start, +naming the key. It is the one gateway config pair that fails rather than +warns, for the same reason a `lease.defaultTtlMs` above `lease.maxTtlMs` +fails: there is no safe way to read it. A gateway has HTTP on by default, so: ```sh -simlock config set mode gateway -simlock config set http.enabled true -simlock daemon stop && simlock daemon start +simlock --gateway config set http.port 4800 +simlock --gateway daemon stop && simlock --gateway daemon start ``` ## Admin credential resolution @@ -2637,7 +2674,7 @@ to send at handshake, in order: 1. `--token ` — accepted anywhere on the command line. 2. `SIMLOCK_ADMIN_TOKEN` — the environment variable. -3. the local `admin.token` file the daemon writes under `SIMLOCK_HOME` at +3. the local `admin.token` file the daemon writes in its data folder at startup (read is retried briefly, to ride out the daemon still writing it after a fresh `daemon start`). @@ -2708,26 +2745,6 @@ fleet; `simlock worker remove` then forgets its view. ## Environment variables -### `SIMLOCK_HOME` - -Overrides the data directory the CLI, MCP server, and daemon all use for -`config.json`, `state.json`, `daemon.sock`, `daemon.log`, `history.db`, and — unless -overridden — the device roots themselves under `devices/`. Defaults to -`~/.simlock`. Because devices live under it, it needs a local volume with tens -of gigabytes free. All three frontends resolve it through the same function -(`resolveSimlockHome` in `src/ports/paths.ts`), so setting it once in an -agent's environment repoints every command at an isolated data directory — -useful for running multiple independent simlock instances on one machine, or -for tests. Two instances on one machine also need distinct -`drivers.android.adbServerPort` values, since a TCP port is machine-global and -`SIMLOCK_HOME` cannot isolate it. When the CLI or MCP server auto-starts the daemon, the daemon -process inherits the variable like the rest of the environment. - -Keep it short: `daemon.sock` lives directly under it, and the kernel caps a Unix -socket path at 104 bytes on macOS (108 on Linux). A deeper `SIMLOCK_HOME` is -refused up front by every frontend with a `USAGE` error naming the limit, rather -than failing on connect with a bare `EINVAL`. - ### `SIMLOCK_ADMIN_TOKEN` The second source in [admin credential resolution](#admin-credential-resolution) diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 5af8f10cb..de234ca55 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -890,6 +890,10 @@ neither of which changes a call's shape: uplink. Treat it as you would `DAEMON_CONNECTION_LOST` for that one lease: the lease is not necessarily gone, you simply cannot reach it right now, and it runs on the worker's TTL either way. +- The error code `GATEWAY_NOT_PRESENT` (`kind: "domain"`) never comes back + from a daemon. The CLI and `simlock --gateway mcp` raise it themselves when + this machine has no gateway to connect to, so a client that connects to a + socket never sees it. The fleet methods on the admin client work against a single host too, which answers as a fleet of one: diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 159cb0795..97641bb0a 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -1,7 +1,8 @@ # Configuration Simlock reads `~/.simlock/config.json` and merges it over built-in -defaults. Only the keys below are recognized; unknown keys are ignored with +defaults. A gateway reads `~/.simlock/gateway/config.json` instead (see +[Gateway and worker modes](#gateway-and-worker-modes)). Only the keys below are recognized; unknown keys are ignored with a warning. Inspect the effective, merged configuration at any time with `simlock config`. @@ -12,7 +13,6 @@ edit yourself keeps the mode you give it until the next `config set`; run | Property | Description | Default | | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | -| `mode` | Which shape this daemon runs as: `worker` (owns devices on this machine) or `gateway` (owns none, fronts the workers that join it). See [Modes: gateway and worker](#modes-gateway-and-worker). | `worker` | | `capacity.strategy` | Which policy decides how many devices may exist and run at once: `resource` or `fixed`. The options under `capacity.config` are that strategy's own -- see [Capacity strategies](#capacity-strategies). | `resource` | | `idle.shutdownAfterMs` | How long an unused device sits idle before Simlock shuts it down (tier 1, reclaims RAM). Devices that a `warmPool.targets` entry keeps ready ignore it; a device that never served a lease and that no target keeps is shut down once it has been ready this long. | `10 minutes` | | `idle.deleteAfterMs` | How long a shut-down device sits idle before Simlock deletes it (tier 2, reclaims disk). Idle counts from the end of the device's last lease, or, for a device that never served one (one the pool created for a `warmPool.targets` entry that was later lowered or removed, say), from when it was shut down. | `1 hour` | @@ -51,7 +51,7 @@ edit yourself keeps the mode you give it until the next `config set`; run | `gateway.leaseRequestTimeoutMs` | **Gateway side.** How long the gateway waits on a forwarded `lease.request` before giving up on that worker for this request, answering `WORKER_UNREACHABLE`. Bounds the one uplink call that otherwise had no timeout of its own, so a wedged worker cannot park a request where neither a deadline nor `lease.cancel` could ever reach it again. Generous against a cold device provision-plus-boot; well below `gateway.execTimeoutMs`, since granting a lease should never take as long as a command run against the device afterward. | `5 minutes` | | `http.enabled` | Master switch for the network-facing HTTP API (see [HTTP-API.md](HTTP-API.md)) and the web console served beside it (see [CONSOLE.md](CONSOLE.md)). Off by default; the daemon binds nothing until this is `true`. A gateway is the fleet's contact point, so it must be `true` there — see [Modes](#modes-gateway-and-worker). | `false` | | `http.host` | Address the HTTP listener binds. `127.0.0.1` keeps it loopback-only; reaching it remotely is the operator's own tunnel (Tailscale, cloudflared, reverse proxy) — Simlock does no TLS termination in v1. | `127.0.0.1` | -| `http.port` | Port the HTTP listener binds. Must be an integer `1`-`65535`. | `4700` | +| `http.port` | Port the HTTP listener binds. Must be an integer `1`-`65535`. 4700 for a gateway, 4701 for a worker, so both can listen on one machine. | `4700` gateway, `4701` worker | | `http.proxyAuth` | Sign-in through a proxy in front of Simlock (Cloudflare Access, for one). Not set: proxy sign-in is off. Set the four required keys together, as one JSON object, because each `config set` checks the whole file; one key alone is refused, naming the first missing key (`expected set with the other http.proxyAuth keys`). `signOutUrl` alone counts as an incomplete set. Read in both modes; takes effect on daemon restart. | not set | | `http.proxyAuth.header` | Required. The request header carrying the proxy's signed JWT, e.g. `cf-access-jwt-assertion`. 1-64 letters, digits or `-`; matched without regard to case. With `authorization`, only a `Bearer` value that does not start `slk_` is taken as the JWT. | — | | `http.proxyAuth.jwksUrl` | Required. Where the proxy publishes its public keys. An `https://` URL, or `http://` on `127.0.0.1`, `::1` or `localhost`. The daemon fetches it (5 s limit, no redirects, at most 64 KiB) and keeps the keys 10 minutes. | — | @@ -83,10 +83,10 @@ edit yourself keeps the mode you give it until the next `config set`; run | `health.maxConcurrentRecoveries` | Cap on simultaneous recovery reboots, so a machine wake (every device reads `stopped` at once) cannot start a boot storm. | `1` | | `stalledTransition.thresholdMultiplier` | Factor applied to a driver's own `provision + boot` (for `provisioning`) or `reclaim` (for `reclaiming`) estimate to get the stall threshold: past it, `simlock doctor` reports a `stalled-transition` finding and `simlock status` marks the device `stalled`. | `3` | | `stalledTransition.minimumThresholdMs` | Floor under the multiplied estimate, for a driver whose estimate is near zero. | `1 minute` | -| `drivers.ios.deviceRoot` | The CoreSimulator device set Simlock owns and scopes every `simctl` call to. See [Device roots](#device-roots). | `${SIMLOCK_HOME}/devices/ios` | +| `drivers.ios.deviceRoot` | The CoreSimulator device set Simlock owns and scopes every `simctl` call to. See [Device roots](#device-roots). | `~/.simlock/devices/ios` | | `drivers.ios.screenCaptureCommand` | The program that captures a simulator's screen for `capabilities.stream.enabled`. Unset, the one `pnpm build` put beside the daemon. | unset | | `drivers.ios.deviceCaptureCommand` | The program that captures a physical iPhone's screen for `capabilities.stream.enabled`. Unset, the one `pnpm build` put beside the daemon. | unset | -| `drivers.android.deviceRoot` | The AVD home Simlock owns; exported as `ANDROID_AVD_HOME` to every `avdmanager`/`emulator` call. See [Device roots](#device-roots). | `${SIMLOCK_HOME}/devices/android` | +| `drivers.android.deviceRoot` | The AVD home Simlock owns; exported as `ANDROID_AVD_HOME` to every `avdmanager`/`emulator` call. See [Device roots](#device-roots). | `~/.simlock/devices/android` | | `drivers.android.adbServerPort` | TCP port for Simlock's own adb server. Must not be the shared server's `5037`. Startup fails closed if it is occupied. | `5038` | | `ios.defaultMode` | The device mode an iOS lease request gets when it names none: `slim` or `full`. Every worker makes both kinds whatever this says. See [Device mode: slim and full](#device-mode-slim-and-full). | `full` | | `ios.slim.categories` | Which daemon categories a slim iOS device has disabled. Omitted means every category the driver knows. | every known category | @@ -108,7 +108,7 @@ must be non-negative numbers (milliseconds and bytes, respectively). `stalledTransition.minimumThresholdMs` must be a non-negative number. `http.enabled` is a boolean, `http.host` a string, and `http.port` an integer in `1`-`65535`. -`mode` is `worker` or `gateway`; `gateway.url`, `gateway.token` and +`gateway.url`, `gateway.token` and `gateway.label` are strings, and `gateway.disconnectedRetentionMs`, `gateway.execTimeoutMs`, and `gateway.leaseRequestTimeoutMs` positive numbers. @@ -120,19 +120,18 @@ non-empty string. Any other value is rejected at load, and the error names the key. Simlock does not check that a `gpu` string names a mode the emulator knows: a mode the emulator rejects fails that device's next boot, not the config load. -`mode` must be exactly `"worker"` or `"gateway"`. `gateway.url` must be an +`gateway.url` must be an absolute `ws`/`wss` URL — `http`/`https` are rejected — and `gateway.token` -a non-empty string; **in `mode: "worker"`**, setting either without the other +a non-empty string; **on a worker**, setting either without the other is rejected at load and the daemon does not start, because a half-configured uplink would otherwise come up looking like an ordinary standalone worker. That rule does -not apply in `mode: "gateway"`, where both keys are worker-side and are -warned about and ignored like every other worker key — a gateway is not -misconfigured by leftovers from the config it was flipped out of. +not apply to a gateway, where both keys are worker-side and are +warned about and ignored like every other worker key. `gateway.label` is a non-empty string, `gateway.routing` one of the registered routing policies, `gateway.alerts.destinations` the list described under [Alerts](#alerts), and `exec.timeoutMs`, `gateway.execTimeoutMs`, `gateway.leaseRequestTimeoutMs`, and `gateway.disconnectedRetentionMs` positive numbers. -**`mode: "gateway"` with `http.enabled: false` is rejected at load**, naming the key: a +**A gateway with `http.enabled: false` is rejected at load**, naming the key: a gateway is the fleet's contact point over HTTP, so one nothing can reach has no safe reading. `lease.identity.ios` and `lease.identity.android` must each be `reusable` or @@ -158,9 +157,14 @@ See [CLI.md](CLI.md#simlock-config-get-keyset-key-value) for the ## Gateway and worker modes -`mode` selects what `simlock daemon start` starts. The default, `worker`, is what -every simlock daemon has always been. `gateway` is a daemon that owns no -devices and fronts the workers connected to it. +The folder a daemon lives in decides what it is: `~/.simlock` is a worker and +`~/.simlock/gateway` is a gateway. No config key names the role. A worker is +what every simlock daemon has always been; a gateway is a daemon that owns no +devices and fronts the workers connected to it. `simlock --gateway daemon start` +starts the gateway (creating it on the first start), and plain `simlock daemon +start` starts the worker; both run on one machine, each with its own config, +state, socket and log. A `config.json` that still sets `mode` is refused at +load, with a message that says to remove the key. **Joining a fleet takes two keys on the worker**, and they are required together: `gateway.url` (the gateway's base URL) and `gateway.token` (a join @@ -173,7 +177,7 @@ reconnect loop. Nothing else about the worker changes: it keeps serving its local agents whether or not its gateway is reachable, and `http.enabled` stays off by default. -**A gateway reads a deliberately small slice of this file**: `mode`, `http.*`, +**A gateway reads a deliberately small slice of this file**: `http.*`, `log.*`, `lease.*`, `eventBuffer.*`, `eventLog.*`, `metrics.*`, `gateway.*` and `capabilities.*` (`enabled`, and `leaseTtlCapMs` for agent-device). Every other key — capacity, drivers, downloads, idle, warmPool, health, ios, android, stalledTransition — @@ -182,16 +186,15 @@ gateway's config is reported with a warning and ignored, the same treatment an unknown key gets. The worker-side `gateway.url`/`token`/`label`, `capabilities.agent-device.command` and `capabilities.stream.fps`/`maxDimension`/`bitrateKbps` are warned about there too. Nothing is stripped: the same file can be copied between a -worker and a gateway with only `mode` differing, and the warning is what makes +worker and a gateway, and the warning is what makes the difference visible rather than silent. -**`http.enabled` is not optional for a gateway.** It defaults to `true` in -gateway mode (it stays `false` for a worker), and an explicit `false` fails the +**`http.enabled` is not optional for a gateway.** It defaults to `true` for a +gateway (it stays `false` for a worker), and an explicit `false` fails the start naming the key. HTTP is how agents reach a fleet *and* what the worker uplink upgrades from, so a gateway without it is a process nothing can reach and no worker can join — quietly overriding the operator's value would be -worse than refusing it. Switching a daemon between modes is therefore a -two-key edit, `mode` and (if it was set) `http.enabled`. +worse than refusing it. The gateway keeps one small file of its own beside `tokens.json`: `workers.json`, owner-only, holding the ids of workers an operator has @@ -220,12 +223,14 @@ this setting, and it is the one in the table above. ## Modes: gateway and worker -`mode` decides what the daemon this config belongs to *is*, so it also -decides which of the keys above mean anything. One daemon runs exactly one -mode; `simlock daemon start` starts whichever is configured, and switching is -`simlock config set mode gateway` followed by a restart. +The folder a daemon lives in decides what the daemon *is*, so it also decides +which of the keys above mean anything. One daemon runs exactly one role. The +daemon in `~/.simlock` is a worker; the daemon in `~/.simlock/gateway` is a +gateway, started and reached with the global `--gateway` flag. A worker and a +gateway on one machine are two daemons, each reading the `config.json` in its +own folder. -**A worker (`mode: "worker"`, the default) reads every key in this +**A worker (the daemon in `~/.simlock`) reads every key in this document.** It is today's simlock, unchanged. Joining a fleet adds exactly two keys — `gateway.url` and `gateway.token` — plus the optional `gateway.label`, and changes nothing else about it: same drivers, same @@ -233,12 +238,11 @@ registry, same capacity limits, same local unix socket, and its own local agents keep leasing from it as before. `http.enabled` is *not* required for a worker, because the uplink is outbound. -**A gateway (`mode: "gateway"`) owns no devices**, so most of this document +**A gateway (the daemon in `~/.simlock/gateway`) owns no devices**, so most of this document does not apply to it. It reads: | Key group | Why | |---|---| -| `mode` | to be a gateway at all | | `gateway.routing`, `gateway.disconnectedRetentionMs`, `gateway.execTimeoutMs`, `gateway.leaseRequestTimeoutMs` | how to run the fleet | | `gateway.alerts.destinations` | where to send fleet events | | `http.*` | it is the fleet's contact point | @@ -280,11 +284,11 @@ Everything else — `capacity.*`, `idle.*`, `warmPool.*`, `health.*`, `downloads.*`, and the worker-side `gateway.url`/`gateway.token`/ `gateway.label`/`exec.timeoutMs` — is **ignored with a warning**, exactly as an unknown key is. That is deliberately the softer treatment: a gateway's -config file is usually a worker's config file with `mode` flipped, and a +config file is usually a copy of a worker's config file, and a warning names each key that stopped mattering rather than refusing to start over a leftover. -There is one hard failure: **`mode: "gateway"` with `http.enabled: false` is +There is one hard failure: **a gateway with `http.enabled: false` is rejected at load and the daemon does not start**, naming the key. A gateway with no HTTP listener is unreachable by definition — no worker could open an uplink to it and no agent could lease through it — so there is no safe way to @@ -293,26 +297,31 @@ above `lease.maxTtlMs`. The `gateway.*` block reads in both directions on purpose: on a worker it says *which gateway to join*, on a gateway it says *how to be one*. The table -above marks which is which, and each key is only ever read in one mode. +above marks which is which, and each key is only ever read by one role. A machine that should both front a fleet and own devices runs **two daemons**: one gateway, one worker, the worker joining the gateway over localhost. There -is no hybrid mode. What the two need to keep apart is smaller than it looks, -because only one of them owns anything: - -- **Distinct `SIMLOCK_HOME`s.** That is what gives them separate config, - state, sockets, logs, instance ids, and token stores — and the separate - instance ids are what make the worker a distinct member of the fleet. +is no hybrid mode. Start the gateway with `simlock --gateway daemon start`; +the worker starts as it always did. What the two need to keep apart is smaller +than it looks, because only one of them owns anything: + +- **Separate folders.** That is what gives them separate config, state, + sockets, logs, instance ids, and token stores — and the separate instance + ids are what make the worker a distinct member of the fleet. Set the + gateway's keys with `simlock --gateway config set`. - **Only the gateway needs `http.enabled`** (and must have it). The worker dials out, so it needs no listener of its own; leave its `http.enabled` off unless you also want to reach that one worker directly. -- **Distinct `http.port`s, if you do enable HTTP on both.** A port is - machine-global and `SIMLOCK_HOME` cannot isolate it. +- **Distinct `http.port`s, if you do enable HTTP on both.** A gateway + listens on 4700 and a worker on 4701 unless told otherwise, so the + defaults never collide; a port is machine-global, so two daemons that are + given the same one cannot both start. - **The worker keeps its `drivers.*` block** — device roots, adb server port, the lot. It owns the devices; the gateway has no drivers to - configure. Two *workers* on one machine would additionally need distinct - `drivers.android.adbServerPort` values (see below), but a gateway plus a - worker is one driver set, so there is nothing to split. + configure. + +A second worker for the same user cannot start: the running worker's socket +refuses it. ## Alerts @@ -466,8 +475,7 @@ outside it. └── simlock_.avd/ ``` -Both roots default under `SIMLOCK_HOME`, so pointing `SIMLOCK_HOME` somewhere -else moves the devices with it. Override a single platform when its data +Both roots default under `~/.simlock`. Override a single platform when its data belongs on another volume — device data runs to tens of gigabytes: ```json @@ -494,7 +502,7 @@ that owns it. Simlock creates the marker **only** for a root it creates empty itself, and refuses any existing root that is unmarked, marked for another instance, symlinked, or wrongly owned or permissioned. It never adopts a directory it did not create. The instance identity lives in -`${SIMLOCK_HOME}/instance.json`, written once on first start. +`~/.simlock/instance.json`, written once on first start. A root that fails validation stops that platform's driver at startup — Simlock fails closed rather than falling back to the default device location. `simlock @@ -535,10 +543,6 @@ Consequence worth knowing: your own `adb` will not see Simlock's emulators. A lease hands you the port to use — see [CLI.md](CLI.md#reaching-a-leased-device). -Running two Simlock instances on one machine now needs distinct -`drivers.android.adbServerPort` values as well as distinct `SIMLOCK_HOME` -values. - ## Device mode: slim and full A lease request can ask for a `slim` or a `full` device (`simlock lease @@ -878,11 +882,11 @@ those settings would have no effect. ## Signing in through a proxy -`http.proxyAuth` makes Simlock treat a person the sign-in proxy has signed in as an operator, with no Simlock token. Set it as one object: +`http.proxyAuth` makes Simlock treat a person the sign-in proxy has signed in as an operator, with no Simlock token. It is an `http` key, so a gateway reads it from `~/.simlock/gateway/config.json`; the commands below set it there with `--gateway`. Drop `--gateway` to set it on the worker. Set it as one object: ``` -simlock config set http.proxyAuth '{"header":"cf-access-jwt-assertion","jwksUrl":"https://team.cloudflareaccess.com/cdn-cgi/access/certs","issuer":"https://team.cloudflareaccess.com","audience":"4f1c…"}' -simlock daemon stop && simlock daemon start +simlock --gateway config set http.proxyAuth '{"header":"cf-access-jwt-assertion","jwksUrl":"https://team.cloudflareaccess.com/cdn-cgi/access/certs","issuer":"https://team.cloudflareaccess.com","audience":"4f1c…"}' +simlock --gateway daemon stop && simlock --gateway daemon start ``` Setting one key alone fails the whole-file check: `Invalid config after setting http.proxyAuth.header: Invalid config value for "http.proxyAuth.jwksUrl": expected set with the other http.proxyAuth keys`. See [HTTP-API.md](HTTP-API.md#signing-in-through-a-proxy) for how a request is checked. diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index a79c8c4ac..df74add36 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -66,8 +66,9 @@ simlock config set http.enabled true simlock daemon stop && simlock daemon start ``` -`http.host` and `http.port` decide where it listens, `127.0.0.1:4700` by -default (see [CONFIGURATION.md](CONFIGURATION.md)). +`http.host` and `http.port` decide where it listens, `127.0.0.1:4701` by +default for a worker and `127.0.0.1:4700` for a gateway (see +[CONFIGURATION.md](CONFIGURATION.md)). ## Open it @@ -75,14 +76,14 @@ default (see [CONFIGURATION.md](CONFIGURATION.md)). ``` Daemon running -Console: http://127.0.0.1:4700/ +Console: http://127.0.0.1:4701/ ``` `simlock status` prints it after the daemon's health and mode: ``` Daemon: running (worker) -Console: http://127.0.0.1:4700/ +Console: http://127.0.0.1:4701/ ... ``` @@ -93,7 +94,7 @@ Open that address in a browser. `simlock status --json` has it as When `http.host` is `0.0.0.0` or `::`, the daemon listens on every interface and the address says `localhost`. From another machine, use this host's name or address instead. An IPv6 host is shown in brackets, as a browser expects: -`http://[::1]:4700/`. +`http://[::1]:4701/`. The console uses the HTTP listener and nothing else. To reach it from another machine, use the same tunnel you use for the HTTP API (Tailscale, cloudflared, diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index a8eb691dc..711478afc 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -236,7 +236,7 @@ The daemon block carries `health` (`starting`/`running`) and **`mode`** daemon answered: ```json -{ "daemon": { "health": "running", "mode": "worker", "consoleUrl": "http://127.0.0.1:4700/" } } +{ "daemon": { "health": "running", "mode": "worker", "consoleUrl": "http://127.0.0.1:4701/" } } ``` **`consoleUrl`** is the web console's address (see [CONSOLE.md](CONSOLE.md)): diff --git a/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index 7186bdbe9..80800f3f9 100644 --- a/docs/internal/flows/startup.md +++ b/docs/internal/flows/startup.md @@ -10,7 +10,7 @@ Entry: `src/daemon/main.ts` `startDaemon` → `DaemonServer.start` (`src/daemon/ 3. Host info read once (`sw_vers` on macOS); bounded, never throws. 4. `EventBus` → the event history is created (`createEventHistory`). It touches no file yet. `createAuth` then builds the token store and the admin secret (hash in memory), once, for both modes. -5. `config.mode: gateway` → the gateway section. Otherwise go on. +5. Started with `--gateway` (role `gateway`, data directory `/gateway`) → the gateway section. Otherwise go on. ## Worker: build (before the claim) diff --git a/e2e/console-serving.test.ts b/e2e/console-serving.test.ts index a2acf509e..55067e6db 100644 --- a/e2e/console-serving.test.ts +++ b/e2e/console-serving.test.ts @@ -58,7 +58,8 @@ describe("the web console", () => { it("a gateway serves the console page at the address simlock status prints", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index 38e7f20bb..5b2d5980f 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -6,7 +6,7 @@ import { type Server, type ServerResponse, } from "node:http"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -55,7 +55,6 @@ export interface RunningDaemon extends ConsoleDaemon { } export interface StartOptions { - /** Merged over the config the lane writes: HTTP on a free port, and the mode. */ readonly config?: Readonly>; /** The fake driver's script, written before the daemon starts. */ readonly driverScript?: FakeDriverScript; @@ -84,13 +83,16 @@ export async function startDaemon( const home = await mkdtemp(join(tmpdir(), "simlock-console-")); const port = await freeLoopbackPort(); const scriptPath = join(home, "fake-driver-script.json"); + // why: a gateway lives in `/gateway` and every CLI call that reaches it says `--gateway` (ADR 0034). + const dataDirectory = mode === "gateway" ? join(home, "gateway") : home; + const gatewayFlag = mode === "gateway" ? ["--gateway"] : []; const { http: extraHttp, ...extraConfig } = options.config ?? {}; + await mkdir(dataDirectory, { recursive: true }); await writeFile( - join(home, "config.json"), + join(dataDirectory, "config.json"), JSON.stringify({ ...(mode === "worker" ? FAKE_CAPACITY : {}), http: { enabled: true, host: "127.0.0.1", port, ...(extraHttp as object | undefined) }, - mode, ...extraConfig, }), ); @@ -108,19 +110,19 @@ export async function startDaemon( } : {}), }; - const socketPath = join(home, "daemon.sock"); + const socketPath = join(dataDirectory, "daemon.sock"); const background = new Set(); const stop = async () => { - await cli(["daemon", "stop"], env).catch(() => undefined); + await cli([...gatewayFlag, "daemon", "stop"], env).catch(() => undefined); await waitFor(() => !existsSync(socketPath), { timeout: 10_000 }).catch(() => undefined); }; const start = async () => { - const started = await cli(["daemon", "start"], env, { timeout: 30_000 }); + const started = await cli([...gatewayFlag, "daemon", "start"], env, { timeout: 30_000 }); if (started.code === 0) return; // why: a failed start reports only what the CLI saw while polling the socket, and `dispose` // deletes this home with `daemon.log` — the only record of the cause the daemon itself wrote. // Read the tail here, before any caller's catch reaches `dispose`, and fail with both. - const log = await readFile(join(home, "daemon.log"), "utf8").catch(() => ""); + const log = await readFile(join(dataDirectory, "daemon.log"), "utf8").catch(() => ""); const tail = log.split("\n").slice(-20).join("\n"); expect(started.code, `daemon start failed: ${started.stderr}\n${tail}`).toBe(0); }; @@ -131,11 +133,11 @@ export async function startDaemon( }; try { await start(); - const status = await cli(["status", "--json"], env); + const status = await cli([...gatewayFlag, "status", "--json"], env); const url = (status.json as { daemon: { consoleUrl?: string } }).daemon.consoleUrl; expect(url).toBe(`http://127.0.0.1:${port}/`); const mint = async (role: string) => { - const minted = await cli(["token", "create", "--role", role], env); + const minted = await cli([...gatewayFlag, "token", "create", "--role", role], env); expect(minted.code, minted.stderr).toBe(0); return (minted.json as { secret: string }).secret; }; @@ -155,9 +157,9 @@ export async function startDaemon( { label: "HTTP listener accepting connections" }, ); return { - cli: (args) => cli(args, env), + cli: (args) => cli([...gatewayFlag, ...args], env), cliBackground(args) { - const handle = cliBackground(args, env); + const handle = cliBackground([...gatewayFlag, ...args], env); background.add(handle); return handle; }, diff --git a/e2e/contract-surface.test.ts b/e2e/contract-surface.test.ts index 607082472..49f7c48e9 100644 --- a/e2e/contract-surface.test.ts +++ b/e2e/contract-surface.test.ts @@ -107,7 +107,8 @@ describe("contract surface", () => { // `UNSUPPORTED_IN_GATEWAY_MODE` reject an unparseable payload with `BAD_REQUEST` first. // Anything that came back `UNKNOWN_REQUEST` here would be an operation a gateway forgot. const { env } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); expect((await env.startDaemon()).code).toBe(0); diff --git a/e2e/daemon-folders.test.ts b/e2e/daemon-folders.test.ts new file mode 100644 index 000000000..5ed777094 --- /dev/null +++ b/e2e/daemon-folders.test.ts @@ -0,0 +1,271 @@ +import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; +import { readFile, writeFile } from "node:fs/promises"; +import { createServer } from "node:net"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { freeLoopbackPort, REPO_ROOT, type TestEnv, waitFor, withDaemon } from "./helpers/index.js"; + +// why: an env's teardown stops only the worker's socket, so a test stops a gateway it started in its own `finally`. + +const NO_GATEWAY = "No gateway on this machine. Start one with: simlock --gateway daemon start"; +const MODE_REMOVED = + '"mode" is no longer a config key. A daemon started with --gateway is a gateway; any other is a worker. Remove "mode" from config.json.'; + +function gatewayFolder(env: TestEnv): string { + return join(env.home, "gateway"); +} + +async function makeGatewayPresent(env: TestEnv): Promise { + const port = await freeLoopbackPort(); + const set = await env.cli(["--gateway", "config", "set", "http.port", String(port)]); + expect(set.code, set.stderr).toBe(0); +} + +async function startGateway(env: TestEnv): Promise { + await makeGatewayPresent(env); + const started = await env.cli(["--gateway", "daemon", "start"]); + expect(started.code, started.stderr).toBe(0); + await waitFor(() => existsSync(join(gatewayFolder(env), "admin.token")), { + label: "the gateway's admin.token written", + }); +} + +async function stopGateway(env: TestEnv): Promise { + await env.cli(["--gateway", "daemon", "stop"]); +} + +function daemonMode(result: { readonly json: unknown }): unknown { + return (result.json as { daemon: { mode: string } }).daemon.mode; +} + +describe("daemon folders (ADR 0034)", () => { + it.each([ + ["status", ["status"]], + ["daemon status", ["daemon", "status"]], + ["daemon stop", ["daemon", "stop"]], + ["daemon logs", ["daemon", "logs"]], + ["events --since 1h", ["events", "--since", "1h"]], + ["config get", ["config", "get"]], + ["adb shell ls -h", ["adb", "shell", "ls", "-h"]], + ["adb -h", ["adb", "-h"]], + ["simctl --help", ["simctl", "--help"]], + ])( + "with no gateway present, every --gateway command but daemon start and config set exits 2 with GATEWAY_NOT_PRESENT and starts nothing (%s)", + async (_name, argv) => { + const env = await withDaemon({ mode: "auto" }); + + const result = await env.cli(["--gateway", ...argv]); + + expect(result.code).toBe(2); + expect(result.error).toEqual({ code: "GATEWAY_NOT_PRESENT", message: NO_GATEWAY }); + expect(existsSync(gatewayFolder(env))).toBe(false); + expect(existsSync(env.socketPath)).toBe(false); + }, + ); + + it.each([ + ["--gateway status --help", ["--gateway", "status", "--help"]], + ["--gateway --help", ["--gateway", "--help"]], + ])("`%s` prints usage, not the error", async (_name, argv) => { + const env = await withDaemon({ mode: "auto" }); + + const result = await env.cli(argv); + + expect(result.code).toBe(0); + expect(result.error).toBeUndefined(); + expect(result.stdout).toContain("Usage: simlock"); + }); + + it("--gateway config set makes a gateway present, after which --gateway status starts it", async () => { + const env = await withDaemon({ mode: "auto" }); + + try { + await makeGatewayPresent(env); + expect(existsSync(join(gatewayFolder(env), "config.json"))).toBe(true); + + const status = await env.cli(["--gateway", "status", "--json"]); + + expect(status.code, status.stderr).toBe(0); + expect(daemonMode(status)).toBe("gateway"); + } finally { + await stopGateway(env); + } + }); + + it("a gateway started with --gateway runs beside the worker of the same root, each in its own folder", async () => { + const env = await withDaemon(); + + try { + await startGateway(env); + + const worker = await env.cli(["status", "--json"]); + const gateway = await env.cli(["--gateway", "status", "--json"]); + + expect(daemonMode(worker)).toBe("worker"); + expect(daemonMode(gateway)).toBe("gateway"); + const workerInstance = await readFile(join(env.home, "instance.json"), "utf8"); + const gatewayInstance = await readFile(join(gatewayFolder(env), "instance.json"), "utf8"); + expect(gatewayInstance).not.toBe(workerInstance); + expect(existsSync(join(gatewayFolder(env), "state.json"))).toBe(false); + } finally { + await stopGateway(env); + } + }); + + it("simlock config set mode gateway exits 2 with the mode message and leaves config.json as it was", async () => { + const env = await withDaemon({ mode: "auto" }); + await writeFile(env.configPath, '{"http":{"port":4999}}\n', "utf8"); + + const result = await env.cli(["config", "set", "mode", "gateway"]); + + expect(result.code).toBe(2); + expect(result.error?.code).toBe("USAGE"); + expect(result.error?.message).toBe(`Invalid config after setting mode: ${MODE_REMOVED}`); + expect(await readFile(env.configPath, "utf8")).toBe('{"http":{"port":4999}}\n'); + }); + + it("a daemon started from a config that still sets mode does not start, and the CLI prints the mode message with exit 1", async () => { + const env = await withDaemon({ mode: "auto" }); + await writeFile(env.configPath, '{"mode":"worker"}\n', "utf8"); + + const result = await env.cli(["daemon", "start"]); + + expect(result.code).toBe(1); + expect(result.error).toEqual({ code: "INTERNAL", message: MODE_REMOVED }); + expect(existsSync(env.socketPath)).toBe(false); + }); + + it("a gateway that fails to start logs the reason to /gateway/daemon.log, not /daemon.log", async () => { + const env = await withDaemon({ mode: "auto" }); + const holder = createServer(); + const port = await new Promise((resolve) => { + holder.listen(0, "127.0.0.1", () => { + const address = holder.address(); + resolve(typeof address === "object" && address !== null ? address.port : 0); + }); + }); + + try { + const set = await env.cli(["--gateway", "config", "set", "http.port", String(port)]); + expect(set.code, set.stderr).toBe(0); + + await env.cli(["--gateway", "daemon", "start"]); + + const gatewayLog = join(gatewayFolder(env), "daemon.log"); + await waitFor( + async () => + existsSync(gatewayLog) && + (await readFile(gatewayLog, "utf8")).includes("Daemon failed to start"), + { label: "the gateway's start failure in /gateway/daemon.log" }, + ); + expect(existsSync(join(env.home, "daemon.log"))).toBe(false); + } finally { + await stopGateway(env); + await new Promise((resolve) => holder.close(() => resolve())); + } + }); + + it("the daemon entry run with an unknown argument exits 1 and logs Daemon failed to start to /daemon.log", async () => { + const env = await withDaemon({ mode: "auto" }); + + const code = await new Promise((resolve, reject) => { + const child = spawn(process.execPath, [join(REPO_ROOT, "dist/daemon/main.js"), "--bogus"], { + env: env.env, + stdio: "ignore", + }); + child.once("error", reject); + child.once("close", resolve); + }); + + expect(code).toBe(1); + expect(await readFile(join(env.home, "daemon.log"), "utf8")).toContain( + "Daemon failed to start", + ); + }); + + describe("MCP", () => { + it("simlock --gateway mcp lists the gateway's catalog, plain simlock mcp lists the worker's", async () => { + const env = await withDaemon(); + await env.driverScript.set({ + ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, + }); + + try { + await startGateway(env); + const workerMcp = await env.mcpClient(); + const gatewayMcp = await env.mcpClient({ gateway: true }); + + const workerCatalog = await workerMcp.client.callTool({ + name: "list_devices", + arguments: {}, + }); + const gatewayCatalog = await gatewayMcp.client.callTool({ + name: "list_devices", + arguments: {}, + }); + + expect(workerCatalog.structuredContent).toMatchObject({ + platforms: expect.arrayContaining([ + expect.objectContaining({ platform: "ios", models: ["iPhone 16"] }), + ]), + }); + expect(gatewayCatalog.structuredContent).toEqual({ platforms: [] }); + } finally { + await stopGateway(env); + } + }); + + it("with no gateway present, a --gateway mcp tool call fails with GATEWAY_NOT_PRESENT", async () => { + const env = await withDaemon({ mode: "auto" }); + const mcp = await env.mcpClient({ gateway: true }); + + const result = await mcp.client.callTool({ name: "list_devices", arguments: {} }); + + expect(result.isError).toBe(true); + expect(JSON.parse((result.content as { text: string }[])[0]?.text ?? "{}")).toEqual({ + code: "GATEWAY_NOT_PRESENT", + message: NO_GATEWAY, + }); + expect(existsSync(gatewayFolder(env))).toBe(false); + }); + + it("a --gateway mcp session that started before any gateway existed reaches it once simlock --gateway daemon start has run", async () => { + const env = await withDaemon({ mode: "auto" }); + const mcp = await env.mcpClient({ gateway: true }); + + try { + const before = await mcp.client.callTool({ name: "list_devices", arguments: {} }); + expect(before.isError).toBe(true); + + await startGateway(env); + const after = await mcp.client.callTool({ name: "list_devices", arguments: {} }); + + expect(after.isError).toBeFalsy(); + expect(after.structuredContent).toEqual({ platforms: [] }); + } finally { + await stopGateway(env); + } + }); + + it("with a gateway present but stopped, a --gateway mcp tool call starts the gateway in /gateway", async () => { + const env = await withDaemon({ mode: "auto" }); + const mcp = await env.mcpClient({ gateway: true }); + + try { + await makeGatewayPresent(env); + + const result = await mcp.client.callTool({ name: "list_devices", arguments: {} }); + + expect(result.isError).toBeFalsy(); + const status = await env.cli(["--gateway", "status", "--json"]); + expect(daemonMode(status)).toBe("gateway"); + expect(existsSync(join(env.home, "instance.json"))).toBe(false); + expect(existsSync(join(gatewayFolder(env), "gateway"))).toBe(false); + } finally { + await stopGateway(env); + } + }); + }); +}); diff --git a/e2e/gateway-component-install.test.ts b/e2e/gateway-component-install.test.ts index 27be953e0..aad32f20e 100644 --- a/e2e/gateway-component-install.test.ts +++ b/e2e/gateway-component-install.test.ts @@ -45,7 +45,8 @@ async function androidRuntimeWorkers(gateway: TestEnv, runtime: string): Promise describe("simlock component install through a gateway", () => { it("asks every worker, shows the install in worker list while it runs, reports each by id, refuses on the worker set to never, the gateway's catalog lists the component for the one that installed it, and an agent token gets 403 over HTTP", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); @@ -150,7 +151,8 @@ describe("simlock component install through a gateway", () => { it("refuses component install with no worker flag on a gateway with exit 2, telling the operator to name workers", async () => { const { env: gateway } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); diff --git a/e2e/gateway-event-relay.test.ts b/e2e/gateway-event-relay.test.ts index 7cb9f2393..124e23afc 100644 --- a/e2e/gateway-event-relay.test.ts +++ b/e2e/gateway-event-relay.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { createConnection, createServer, type Socket } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -16,7 +16,8 @@ import type { RecordedEvent } from "./helpers/events.js"; async function gatewayWithWorker() { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); @@ -198,7 +199,9 @@ describe("gateway event relay", () => { const { gateway, worker } = await gatewayWithWorker(); const gate = await gateReplay(gateway.socketPath); try { - const adminToken = (await readFile(join(gateway.home, "admin.token"), "utf8")).trim(); + const adminToken = ( + await readFile(join(gateway.dataDirectory, "admin.token"), "utf8") + ).trim(); const follower = gateway.cliBackground(["events", "--follow", "--since", "1h"], { env: { SIMLOCK_ADMIN_TOKEN: adminToken, SIMLOCK_HOME: gate.home }, }); @@ -248,6 +251,10 @@ describe("gateway event relay", () => { */ async function gateReplay(upstreamSocket: string) { const home = await mkdtemp(join(tmpdir(), "sl-gate-")); + // why: the follower runs with `--gateway`, which looks for a gateway folder under this root. + const gatewayFolder = join(home, "gateway"); + await mkdir(gatewayFolder); + await writeFile(join(gatewayFolder, "config.json"), "{}"); let held: (() => void) | undefined; let released = false; const pushed: RecordedEvent[] = []; @@ -286,7 +293,7 @@ async function gateReplay(upstreamSocket: string) { client.on("error", () => upstream.destroy()); upstream.on("error", () => client.destroy()); }); - await new Promise((resolve) => server.listen(join(home, "daemon.sock"), resolve)); + await new Promise((resolve) => server.listen(join(gatewayFolder, "daemon.sock"), resolve)); return { home, replayHeld: () => held !== undefined, diff --git a/e2e/gateway-fast-fail.test.ts b/e2e/gateway-fast-fail.test.ts index 04c063608..814fa5df3 100644 --- a/e2e/gateway-fast-fail.test.ts +++ b/e2e/gateway-fast-fail.test.ts @@ -28,7 +28,8 @@ interface WorkerView { async function startGateway() { // `driver: "none"`: a gateway starts no drivers (ADR 0005 §2). const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); diff --git a/e2e/gateway-fleet.test.ts b/e2e/gateway-fleet.test.ts index 65897f66f..76509ba93 100644 --- a/e2e/gateway-fleet.test.ts +++ b/e2e/gateway-fleet.test.ts @@ -135,7 +135,8 @@ describe("gateway fleet", () => { // `driver: "none"`: a gateway starts no drivers and warns about every worker-only key in // its config (ADR 0005 §2), so it gets no fake-driver wiring and no capacity seeding. const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); @@ -280,7 +281,8 @@ describe("gateway fleet", () => { it("shows each worker's own pairings, other names, and images in the worker list and their union in the catalog", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); @@ -396,7 +398,8 @@ describe("gateway fleet", () => { it("shows each worker's own custom models in the worker list, and marks a model custom in the catalog when any worker does", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); @@ -450,7 +453,8 @@ describe("gateway fleet", () => { it("gives a request with a mode that mode on either worker, and a request with none the default of the worker it landed on", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); @@ -526,7 +530,8 @@ describe("gateway fleet", () => { it("grants --device 'iphone 16 pro' and --device pixel_7 through a gateway by the worker's own names", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); @@ -573,7 +578,8 @@ describe("gateway fleet", () => { it("grants an Android --class phone request on the worker holding a warm Pixel, not on one with free capacity", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); @@ -649,7 +655,8 @@ describe("gateway fleet", () => { it("grants --class phone with --os '>=18' through a gateway on a worker whose runtime is in the range, and nothing else", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); @@ -696,7 +703,8 @@ describe("gateway fleet", () => { it("refuses an uplink whose token is not a worker join token", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); // An operator token is a real credential that opens no uplink (ADR 0005 §25). The worker @@ -729,7 +737,8 @@ describe("gateway fleet", () => { it("through a gateway, a caller-chosen lease ID comes back with no worker prefix, renews and releases by that ID, and a second request for it is LEASE_ID_TAKEN", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const { secret } = (await gateway.cli(["token", "create", "--role", "worker"])).json as { diff --git a/e2e/gateway-lease-limit.test.ts b/e2e/gateway-lease-limit.test.ts index 31f69b2da..08bb69936 100644 --- a/e2e/gateway-lease-limit.test.ts +++ b/e2e/gateway-lease-limit.test.ts @@ -15,9 +15,9 @@ async function startGateway(maxPerRequester: number) { configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, lease: { maxPerRequester }, - mode: "gateway", }, driver: "none", + role: "gateway", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); expect(minted.code, minted.stderr).toBe(0); diff --git a/e2e/gateway-physical-routing.test.ts b/e2e/gateway-physical-routing.test.ts index 7a71b82ee..de3aa288d 100644 --- a/e2e/gateway-physical-routing.test.ts +++ b/e2e/gateway-physical-routing.test.ts @@ -72,7 +72,8 @@ interface Fleet { async function startFleet(specs: readonly WorkerSpec[]): Promise { const { env: gateway, port } = await withHttpDaemon((port) => ({ agentId: "fleet-agent", - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); diff --git a/e2e/gateway-smoke.test.ts b/e2e/gateway-smoke.test.ts index 0f2ff5ab2..ea258816a 100644 --- a/e2e/gateway-smoke.test.ts +++ b/e2e/gateway-smoke.test.ts @@ -63,7 +63,8 @@ async function startFleet(specs: readonly WorkerSpec[], agentId: string): Promis // config (ADR 0005 §2), so it gets no fake-driver wiring and no capacity seeding. const { env: gateway, port } = await withHttpDaemon((port) => ({ agentId, - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index 6c03bc2d1..ab85432ac 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -1,6 +1,6 @@ import { execFile } from "node:child_process"; import { existsSync } from "node:fs"; -import { mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { promisify } from "node:util"; @@ -108,15 +108,21 @@ export interface WithDaemonOptions { readonly configOverrides?: Record; readonly agentId?: string; /** - * "fake" (default) wires `SIMLOCK_DRIVERS_MODULE` at the scriptable out-of-process + * why: "fake" (default) wires `SIMLOCK_DRIVERS_MODULE` at the scriptable out-of-process * fake driver. "real" leaves driver discovery alone -- the daemon finds the real * iOS/Android drivers exactly as it would in production -- for the slow, real-SDK * lane; `driverScript`/`driverLog` are inert in that mode (nothing reads them). * "none" wires no driver and seeds no driver-shaped config at all: what a - * `mode: "gateway"` daemon needs, since it starts no drivers and warns about every + * gateway needs, since it starts no drivers and warns about every * worker-only key it is given (ADR 0005 §2). */ readonly driver?: "fake" | "real" | "none"; + /** + * why: "gateway" makes this env's daemon the gateway of its home: it lives in `/gateway`, + * and every CLI call the env makes puts `--gateway` first (ADR 0034). Omitted, the daemon is + * the home's worker. + */ + readonly role?: "gateway"; /** * Written to the fake driver's script file before the daemon starts, so the daemon's very * first driver calls already see it. Setting `driverScript` after `withDaemon()` returns is @@ -132,6 +138,7 @@ export interface WithDaemonOptions { export interface TestEnv { readonly home: string; + readonly dataDirectory: string; /** * The port this env's Simlock runs its own adb server on, in the real-SDK lane. A TCP * port is machine-global, so `SIMLOCK_HOME` alone no longer isolates two Simlocks and a @@ -224,9 +231,11 @@ async function buildEnv( options: WithDaemonOptions, ): Promise<{ testEnv: TestEnv; state: TeardownState }> { const home = await mkdtemp(join(tmpdir(), "simlock-e2e-")); - const socketPath = join(home, "daemon.sock"); - const logPath = join(home, "daemon.log"); - const configPath = join(home, "config.json"); + const gatewayFlag: readonly string[] = options.role === "gateway" ? ["--gateway"] : []; + const dataDirectory = options.role === "gateway" ? join(home, "gateway") : home; + const socketPath = join(dataDirectory, "daemon.sock"); + const logPath = join(dataDirectory, "daemon.log"); + const configPath = join(dataDirectory, "config.json"); const scriptPath = join(home, "fake-driver-script.json"); const logCallPath = join(home, "fake-driver-calls.jsonl"); @@ -235,6 +244,7 @@ async function buildEnv( const adbServerPort = options.driver === "real" ? await freeLoopbackPort() : undefined; const seededConfig = seedConfig(options, adbServerPort); if (seededConfig !== undefined) { + await mkdir(dataDirectory, { recursive: true }); await writeFile(configPath, `${JSON.stringify(seededConfig, null, 2)}\n`, "utf8"); } @@ -244,27 +254,31 @@ async function buildEnv( const testEnv: TestEnv = { adbServerPort, home, + dataDirectory, socketPath, logPath, configPath, env, driverScript: driverScriptControl(scriptPath), driverLog: driverLogControl(logCallPath), - cli: (args, cliOptions) => cli(args, env, cliOptions), + cli: (args, cliOptions) => cli([...gatewayFlag, ...args], env, cliOptions), cliBackground: (args, cliOptions) => { - const handle = cliBackground(args, env, cliOptions); + const handle = cliBackground([...gatewayFlag, ...args], env, cliOptions); backgroundProcesses.add(handle); return handle; }, mcpClient: async (mcpOptions) => { - const handle = await mcpClient(env, mcpOptions); + const handle = await mcpClient(env, { + ...mcpOptions, + ...(options.role === "gateway" ? { gateway: true } : {}), + }); mcpClients.add(handle); return handle; }, - events: (since, timeout) => events(env, since, timeout), - expectEvents: (names, expectOptions) => expectEvents(env, names, expectOptions), + events: (since, timeout) => events(env, since, timeout, gatewayFlag), + expectEvents: (names, expectOptions) => expectEvents(env, names, expectOptions, gatewayFlag), async startDaemon() { - const started = await cli(["daemon", "start"], env); + const started = await cli([...gatewayFlag, "daemon", "start"], env); // `daemon start` exits once the daemon answers `status.get`, which it does from its socket // claim on, but the daemon writes `admin.token` only after that claim (ADR 0003 §5). A CLI // that reads the file before it lands connects as agent, so an admin command run next @@ -272,7 +286,7 @@ async function buildEnv( // waiting for the file orders later CLI calls after the write; after a restart the previous // run's file may still be there and passes the wait at once. if (started.code === 0) { - await waitFor(() => existsSync(join(home, "admin.token")), { + await waitFor(() => existsSync(join(dataDirectory, "admin.token")), { label: "admin.token written", }); } @@ -284,7 +298,7 @@ async function buildEnv( // can land slightly before the process fully drains its event loop. Starting // a new daemon while the old one is still mid-exit leaks daemon processes. const pidsBeforeStop = await pidsHoldingSocket(socketPath); - await cli(["daemon", "stop"], env); + await cli([...gatewayFlag, "daemon", "stop"], env); await waitFor(() => !existsSync(socketPath), { timeout: 10_000, label: "daemon socket removed", @@ -345,7 +359,9 @@ async function buildEnv( testEnv, state: { backgroundProcesses, + dataDirectory, env, + gatewayFlag, home, mcpClients, realDrivers: options.driver === "real", @@ -368,7 +384,7 @@ export async function withSharedDaemon(options: WithDaemonOptions = {}): Promise const { testEnv, state } = await buildEnv(options); const restartSteps = async (): Promise => { const pids = await pidsHoldingSocket(state.socketPath); - await cli(["daemon", "stop"], state.env, { timeout: 30_000 }); + await cli([...state.gatewayFlag, "daemon", "stop"], state.env, { timeout: 30_000 }); await waitFor( async () => !(await Promise.all(pids.map((pid) => isProcessAlive(pid)))).some(Boolean), { timeout: 30_000, label: "previous daemon process exited" }, @@ -408,8 +424,8 @@ export async function withSharedDaemon(options: WithDaemonOptions = {}): Promise }, async teardown() { // why: read before teardown deletes the home. - const pid = await readAgentDevicePid(state.home); - const resolved = await realpath(state.home).catch(() => state.home); + const pid = await readAgentDevicePid(state.dataDirectory); + const resolved = await realpath(state.dataDirectory).catch(() => state.dataDirectory); try { await teardown(state); } finally { @@ -421,7 +437,9 @@ export async function withSharedDaemon(options: WithDaemonOptions = {}): Promise interface TeardownState { readonly backgroundProcesses: ReadonlySet; + readonly dataDirectory: string; readonly env: NodeJS.ProcessEnv; + readonly gatewayFlag: readonly string[]; readonly home: string; readonly mcpClients: ReadonlySet; /** @@ -433,7 +451,8 @@ interface TeardownState { } async function teardown(state: TeardownState): Promise { - const { backgroundProcesses, env, home, mcpClients, realDrivers, socketPath } = state; + const { backgroundProcesses, env, gatewayFlag, home, mcpClients, realDrivers, socketPath } = + state; for (const client of mcpClients) { await client.close().catch(() => undefined); } @@ -449,7 +468,7 @@ async function teardown(state: TeardownState): Promise { // socket file still there" after `daemon stop` would miss a process that // unlinked its socket on the way out but never actually terminated. const pidsBeforeStop = await pidsHoldingSocket(socketPath); - await cli(["daemon", "stop"], env).catch(() => undefined); + await cli([...gatewayFlag, "daemon", "stop"], env).catch(() => undefined); // why: a daemon a test SIGKILLed leaves its socket file behind, and nobody will remove it. if (pidsBeforeStop.length > 0) { await waitFor(() => !existsSync(socketPath), { timeout: 5_000 }).catch(() => undefined); diff --git a/e2e/helpers/events.ts b/e2e/helpers/events.ts index 176ae367a..530623141 100644 --- a/e2e/helpers/events.ts +++ b/e2e/helpers/events.ts @@ -14,9 +14,10 @@ export async function events( env: NodeJS.ProcessEnv, since = "1h", timeout?: number, + cliPrefix: readonly string[] = [], ): Promise { const result = await cli( - ["events", "--since", since], + [...cliPrefix, "events", "--since", since], env, timeout === undefined ? {} : { timeout }, ); @@ -39,11 +40,12 @@ export async function expectEvents( env: NodeJS.ProcessEnv, expectedNames: readonly string[], options: { readonly since?: string; readonly timeout?: number } = {}, + cliPrefix: readonly string[] = [], ): Promise { let recorded: RecordedEvent[] = []; await waitFor( async () => { - recorded = await events(env, options.since); + recorded = await events(env, options.since, undefined, cliPrefix); return containsOrderedSubsequence( recorded.map((entry) => entry.event), expectedNames, diff --git a/e2e/helpers/mcp.ts b/e2e/helpers/mcp.ts index de9172a58..74e96b6ce 100644 --- a/e2e/helpers/mcp.ts +++ b/e2e/helpers/mcp.ts @@ -14,6 +14,7 @@ const CLI_ENTRY = join(REPO_ROOT, "dist/cli/main.js"); export interface McpClientOptions { readonly env?: NodeJS.ProcessEnv; + readonly gateway?: boolean; } export interface McpClientHandle { @@ -52,7 +53,7 @@ export async function mcpClient( let stderrOutput = ""; const transport = new StdioClientTransport({ command: process.execPath, - args: [CLI_ENTRY, "mcp"], + args: [CLI_ENTRY, ...(options.gateway === true ? ["--gateway"] : []), "mcp"], // StdioClientTransport only inherits a safe-listed subset of process.env by // default (DEFAULT_INHERITED_ENV_VARS) -- explicit here so SIMLOCK_HOME / // SIMLOCK_DRIVERS_MODULE / SIMLOCK_AGENT_ID actually reach the spawned process. diff --git a/e2e/http-api.test.ts b/e2e/http-api.test.ts index 279454118..a2fd29654 100644 --- a/e2e/http-api.test.ts +++ b/e2e/http-api.test.ts @@ -612,7 +612,8 @@ describe("HTTP API", () => { it("with an operator token returns the same body as simlock stats --json for a fixed from/to, without requests, and &ledger=1 adds them, on a gateway with one worker; an agent token gets 403", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); diff --git a/e2e/identity.test.ts b/e2e/identity.test.ts index 3aea7f4ff..4390a1d99 100644 --- a/e2e/identity.test.ts +++ b/e2e/identity.test.ts @@ -11,7 +11,7 @@ async function httpDaemon(mode: "worker" | "gateway"): Promise { const { env, port } = await withHttpDaemon((port) => { const http = { enabled: true, host: "127.0.0.1", port }; return mode === "gateway" - ? { agentId: "claude-1", configOverrides: { http, mode: "gateway" }, driver: "none" } + ? { agentId: "claude-1", configOverrides: { http }, driver: "none", role: "gateway" as const } : { agentId: "claude-1", configOverrides: { http } }; }); const baseUrl = `http://127.0.0.1:${port}`; diff --git a/e2e/installs-in-progress.test.ts b/e2e/installs-in-progress.test.ts index 867bbcd1e..d17d8eb51 100644 --- a/e2e/installs-in-progress.test.ts +++ b/e2e/installs-in-progress.test.ts @@ -30,7 +30,8 @@ async function viewInstalls(gateway: TestEnv): Promise { it("shows an install on the worker's status and on its gateway's worker list while it runs, and on neither after it ends", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); diff --git a/e2e/physical-devices-core.test.ts b/e2e/physical-devices-core.test.ts index 53fa94089..81cc628fa 100644 --- a/e2e/physical-devices-core.test.ts +++ b/e2e/physical-devices-core.test.ts @@ -494,7 +494,8 @@ interface Fleet { async function fleetWithPhysicalWorker(physical: readonly PhysicalSeed[]): Promise { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); diff --git a/e2e/physical-enrollment.test.ts b/e2e/physical-enrollment.test.ts index a641a5913..957e0e8e1 100644 --- a/e2e/physical-enrollment.test.ts +++ b/e2e/physical-enrollment.test.ts @@ -598,7 +598,8 @@ describe("device add over HTTP", () => { describe("device add through a gateway", () => { async function fleet(): Promise<{ gateway: TestEnv; worker: TestEnv; workerId: string }> { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); diff --git a/e2e/physical-gateway.test.ts b/e2e/physical-gateway.test.ts index ae53bf98d..2ebc89446 100644 --- a/e2e/physical-gateway.test.ts +++ b/e2e/physical-gateway.test.ts @@ -40,7 +40,8 @@ interface Row { async function fleetWithIphone(): Promise<{ gateway: TestEnv; worker: TestEnv }> { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); diff --git a/e2e/proxy-auth.test.ts b/e2e/proxy-auth.test.ts index 207638e5b..6984bc4cf 100644 --- a/e2e/proxy-auth.test.ts +++ b/e2e/proxy-auth.test.ts @@ -48,7 +48,6 @@ async function startKeyServer(key: TestKey): Promise { async function gatewayTrusting(jwksUrl: string): Promise { const { env, port } = await withHttpDaemon((port) => ({ configOverrides: { - mode: "gateway", http: { enabled: true, host: "127.0.0.1", @@ -57,6 +56,7 @@ async function gatewayTrusting(jwksUrl: string): Promise { }, }, driver: "none", + role: "gateway", })); const baseUrl = `http://127.0.0.1:${String(port)}`; await waitFor( diff --git a/e2e/real-proxy/lane.ts b/e2e/real-proxy/lane.ts index b3215ca34..ec284ffab 100644 --- a/e2e/real-proxy/lane.ts +++ b/e2e/real-proxy/lane.ts @@ -1,5 +1,5 @@ import { existsSync } from "node:fs"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -36,7 +36,10 @@ async function startDaemon( config: Readonly>, ): Promise { const home = await mkdtemp(join(tmpdir(), "simlock-real-proxy-")); - await writeFile(join(home, "config.json"), JSON.stringify({ mode, ...config })); + const dataDirectory = mode === "gateway" ? join(home, "gateway") : home; + const gatewayFlag = mode === "gateway" ? ["--gateway"] : []; + await mkdir(dataDirectory, { recursive: true }); + await writeFile(join(dataDirectory, "config.json"), JSON.stringify(config)); const env: NodeJS.ProcessEnv = { ...process.env, SIMLOCK_HOME: home, @@ -48,20 +51,20 @@ async function startDaemon( } : {}), }; - const socketPath = join(home, "daemon.sock"); + const socketPath = join(dataDirectory, "daemon.sock"); const dispose = async () => { - await cli(["daemon", "stop"], env).catch(() => undefined); + await cli([...gatewayFlag, "daemon", "stop"], env).catch(() => undefined); await waitFor(() => !existsSync(socketPath), { timeout: 10_000 }).catch(() => undefined); await rm(home, { force: true, recursive: true }); }; try { - const started = await cli(["daemon", "start"], env, { timeout: 30_000 }); + const started = await cli([...gatewayFlag, "daemon", "start"], env, { timeout: 30_000 }); if (started.code !== 0) throw new Error(`daemon start failed: ${started.stderr}`); } catch (error: unknown) { await dispose(); throw error; } - return { cli: (args) => cli(args, env), dispose }; + return { cli: (args) => cli([...gatewayFlag, ...args], env), dispose }; } export async function startGateway(): Promise { diff --git a/e2e/slow-agent-device-gateway.test.ts b/e2e/slow-agent-device-gateway.test.ts index f3bbf6b2a..fe8502ed6 100644 --- a/e2e/slow-agent-device-gateway.test.ts +++ b/e2e/slow-agent-device-gateway.test.ts @@ -155,10 +155,10 @@ function defineSuite(target: Target): void { gateway = await withSharedDaemon({ driver: "none", configOverrides: { - mode: "gateway", http: { enabled: true, host: "127.0.0.1", port: gatewayPort }, capabilities: { "agent-device": { enabled: true } }, }, + role: "gateway", }); sharedEnvs.add(gateway); const minted = await gateway.cli(["token", "create", "--role", "worker"], { timeout: 60_000 }); diff --git a/e2e/token-route.test.ts b/e2e/token-route.test.ts index e080fe28b..e1db89f48 100644 --- a/e2e/token-route.test.ts +++ b/e2e/token-route.test.ts @@ -33,7 +33,7 @@ async function httpDaemon(mode: "worker" | "gateway"): Promise { const { env, port } = await withHttpDaemon((port) => { const http = { enabled: true, host: "127.0.0.1", port }; return mode === "gateway" - ? { configOverrides: { http, mode: "gateway" }, driver: "none" } + ? { configOverrides: { http }, driver: "none", role: "gateway" as const } : { configOverrides: { http } }; }); const baseUrl = `http://127.0.0.1:${port}`; @@ -96,7 +96,9 @@ describe("GET /v1/tokens", () => { const daemon = await httpDaemon("worker"); const operator = await mint(daemon.env, "operator"); const agent = await mint(daemon.env, "agent", "ci-runner-3"); - const stored = JSON.parse(await readFile(join(daemon.env.home, "tokens.json"), "utf8")) as { + const stored = JSON.parse( + await readFile(join(daemon.env.dataDirectory, "tokens.json"), "utf8"), + ) as { hash: string; }[]; expect(stored).toHaveLength(2); diff --git a/e2e/usage-stats.test.ts b/e2e/usage-stats.test.ts index 72e2ec2a7..c5f781f71 100644 --- a/e2e/usage-stats.test.ts +++ b/e2e/usage-stats.test.ts @@ -124,7 +124,8 @@ describe("simlock stats", () => { it("on a gateway with two workers, simlock stats --json has fleet totals and one entry per worker, and each worker's own covers itself only", async () => { const port = await freeLoopbackPort(); const gateway = await withDaemon({ - configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { host: "127.0.0.1", port } }, + role: "gateway", driver: "none", }); const minted = await gateway.cli(["token", "create", "--role", "worker"]); diff --git a/e2e/waiting-requests.test.ts b/e2e/waiting-requests.test.ts index 417467af8..934830746 100644 --- a/e2e/waiting-requests.test.ts +++ b/e2e/waiting-requests.test.ts @@ -63,7 +63,8 @@ describe("simlock list --requests", () => { it("on a gateway, lists the fleet queue and a request in a worker's own queue with that worker", async () => { const { env: gateway, port } = await withHttpDaemon((port) => ({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + role: "gateway", driver: "none", })); const minted = await gateway.cli(["token", "create", "--role", "worker"]); diff --git a/src/agent-device/definition.test.ts b/src/agent-device/definition.test.ts index ae4d5cb8c..d2d9d5015 100644 --- a/src/agent-device/definition.test.ts +++ b/src/agent-device/definition.test.ts @@ -7,7 +7,11 @@ import { agentDeviceModule } from "./definition.js"; const configPath = "/home/agent/.simlock/config.json"; -async function loadWith(contents: unknown, warn?: (message: string) => void): Promise { +async function loadWith( + contents: unknown, + warn?: (message: string) => void, + role?: "gateway", +): Promise { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); await filesystem.writeFileAtomic(configPath, JSON.stringify(contents)); @@ -15,6 +19,7 @@ async function loadWith(contents: unknown, warn?: (message: string) => void): Pr configPath, filesystem, modules: [{ ...agentDeviceModule.config, name: agentDeviceModule.name }], + ...(role === undefined ? {} : { role }), systemStats: new FakeSystemStats({ cpuCount: 4, totalRamBytes: 16 * 1024 ** 3 }), ...(warn === undefined ? {} : { warn }), }); @@ -115,17 +120,14 @@ describe("agent-device's definition: capabilities.agent-device config", () => { const config = await loadWith( { capabilities: { "agent-device": { enabled: true, leaseTtlCapMs: 10_000 } }, - mode: "gateway", }, warn, + "gateway", ); expect(section(config)).toMatchObject({ enabled: true, leaseTtlCapMs: 10_000 }); expect(warn).not.toHaveBeenCalled(); - await loadWith( - { capabilities: { "agent-device": { command: "elsewhere" } }, mode: "gateway" }, - warn, - ); + await loadWith({ capabilities: { "agent-device": { command: "elsewhere" } } }, warn, "gateway"); expect(warn).toHaveBeenCalledWith( 'Ignoring "capabilities.agent-device.command": it configures a worker, and this daemon runs in gateway mode.', ); diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 0d6fcc897..663b7ef0c 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -189,8 +189,8 @@ async function setUp(options: SetUpOptions = {}): Promise { maxTtlMs, ...(options.endWaitMs === undefined ? {} : { endWaitMs: options.endWaitMs }), }, - ...(options.gatewayMode === true ? { mode: "gateway" as const } : {}), }, + ...(options.gatewayMode === true ? { role: "gateway" as const } : {}), dataDirectory: directory, drivers, filesystem, diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index 0e6c533d9..d838edd4f 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -230,8 +230,8 @@ async function setUp(options: SetUpOptions = {}): Promise { defaultTtlMs: options.defaultTtlMs ?? defaultTtlMs, maxTtlMs: options.maxTtlMs ?? gatewayMaxTtlMs, }, - mode: "gateway", }, + role: "gateway", dataDirectory: directory, filesystem, gatewayRelay: (created) => { diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index 31d000448..4e1746a0e 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -18,38 +18,41 @@ Surface: [CLI.md](../../docs/CLI.md) — every command, flag and exit code. ## Files -| File | Role | -| ---------------- | --------------------------------------------------------------------------------- | -| `index.ts` | `runCli`: the global `--token`, the command lookup, the error boundary | -| `tree.ts` | The command tree — each node names the module that implements it | -| `environment.ts` | `buildCliEnvironment`: the ports a command may reach, from the ports it is handed | -| `types.ts` | `CliEnvironment` and its ports — types only, so routing loads no code | -| `errors.ts` | The error → code/exit mapping | -| `usage-error.ts` | `UsageError` and `withHelpHint`, the help pointer's one wording | -| `connect.ts` | `connectDaemonClient`: credential order, the admin session, the notice | -| `args.ts` | `commandArgs` / `requiredPositional` / `subcommandOrUsage` / `writeResult` | -| `commands/*.ts` | One module per command, `run(argv, context)`; loaded by the tree on a hit | -| `format.ts` | The human renderers for `status`, `worker list`, `daemon start`, etc. | -| `duration.ts` | `parseDuration` for `--ttl`-style flags | -| `termination.ts` | The signals and parent-exit wait a held lease blocks on | -| `log-file.ts` | `readLogFile`: `daemon.log` plus a rotated generation | -| `stdio.ts` | `readPipedStdin`: a piped stdin for `simctl`/`adb`, read to EOF | -| `passthrough.ts` | `spawnPassthrough`: runs a resolved simctl/adb command, stdio inherited | -| `follow-log.ts` | `followLog`: `daemon logs --follow` across rotations | -| `main.ts` | The bin; sets `process.exitCode` | +| File | Role | +| ---------------- | -------------------------------------------------------------------------------------- | +| `index.ts` | `runCli`: the global `--token` and `--gateway`, the command lookup, the error boundary | +| `tree.ts` | The command tree — each node names the module that implements it | +| `environment.ts` | `buildCliEnvironment`: the ports a command may reach, from the ports it is handed | +| `types.ts` | `CliEnvironment` and its ports — types only, so routing loads no code | +| `errors.ts` | The error → code/exit mapping | +| `usage-error.ts` | `UsageError` and `withHelpHint`, the help pointer's one wording | +| `connect.ts` | `connectDaemonClient`: credential order, the admin session, the notice | +| `args.ts` | `commandArgs` / `requiredPositional` / `subcommandOrUsage` / `writeResult` | +| `commands/*.ts` | One module per command, `run(argv, context)`; loaded by the tree on a hit | +| `format.ts` | The human renderers for `status`, `worker list`, `daemon start`, etc. | +| `duration.ts` | `parseDuration` for `--ttl`-style flags | +| `termination.ts` | The signals and parent-exit wait a held lease blocks on | +| `log-file.ts` | `readLogFile`: `daemon.log` plus a rotated generation | +| `stdio.ts` | `readPipedStdin`: a piped stdin for `simctl`/`adb`, read to EOF | +| `passthrough.ts` | `spawnPassthrough`: runs a resolved simctl/adb command, stdio inherited | +| `follow-log.ts` | `followLog`: `daemon logs --follow` across rotations | +| `main.ts` | The bin; sets `process.exitCode` | `format.ts`, `duration.ts` and `termination.ts` are reached only from a command module, and `follow-log.ts` and `passthrough.ts` only from a dynamic import inside `environment.ts`. ## How it works -1. **Route** — `runCli` takes out a global `--token`, then walks `COMMANDS` to the deepest +1. **Route** — `runCli` takes out the global `--token` and `--gateway` (bare, anywhere; `--gateway=` is a usage error), then walks `COMMANDS` to the deepest node the words name and loads that one module (a parent and its children can share it). Nothing runs without a node: an unmatched word is a usage error before any command module is read. `--help`/`-h` as the first word, or no words, prints the root usage without building an environment at all. Any error is one JSON line on stderr, `{ error: { code, message } }`. Exit code: `ERROR_TABLE` `cliExitCode`, - 2 for a usage error, else 1. + 2 for a usage error, else 1. `--gateway` makes `resolveDaemonHome` pick `/gateway` + (the launcher gets `--gateway`, with `SIMLOCK_HOME` still the root); with no gateway + present every command but `daemon start`, `config set` and `mcp` (and any `--help`, except after `adb`/`simctl`) + stops with `GATEWAY_NOT_PRESENT`, exit 2, before it connects. 2. **Connect** (`connectDaemonClient`) — always `connectSimlockAdmin`; principal = `resolveRequesterId(env, )`. Credential, first found: `--token` → `SIMLOCK_ADMIN_TOKEN` → `admin.token` in the data directory (3 reads, 50 ms apart). @@ -85,7 +88,7 @@ Surface: [CLI.md](../../docs/CLI.md) — every command, flag and exit code. A new identity on `daemon.log.1` is a rotation: print its rest, restart at offset 0. 8. **`simlock config set`** — validates the merged file with `loadConfig`, writes `config.json` atomically, mode `0600`. -9. **`simlock mcp`** — imports `src/mcp/main.ts` and runs it. +9. **`simlock mcp`** — imports `src/mcp/main.ts` and runs it, passing `--gateway` as `{ gateway }`. ## Rules diff --git a/src/cli/commands/mcp.ts b/src/cli/commands/mcp.ts index 1511e003c..0d010e403 100644 --- a/src/cli/commands/mcp.ts +++ b/src/cli/commands/mcp.ts @@ -9,7 +9,10 @@ async function loadDefaultMcpStdio(): Promise { return (await import("../../mcp/main.js")).runMcpStdio; } -async function run(argv: readonly string[], { environment }: CommandContext): Promise { +async function run( + argv: readonly string[], + { environment, gateway }: CommandContext, +): Promise { if (argv.length === 1 && isHelp(argv[0])) { environment.stdout.write("Usage: simlock mcp\n"); return 0; @@ -17,7 +20,7 @@ async function run(argv: readonly string[], { environment }: CommandContext): Pr if (argv.length > 0) throw new UsageError("mcp accepts no arguments"); const runMcpStdio = environment.runMcpStdio ?? (await (environment.loadMcpStdio ?? loadDefaultMcpStdio)()); - await runMcpStdio(); + await runMcpStdio({ gateway }); return 0; } diff --git a/src/cli/environment.ts b/src/cli/environment.ts index 78dcf5ad7..468ff5482 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -173,7 +173,8 @@ export function buildCliEnvironment( ports: CliEnvironmentPorts, env: NodeJS.ProcessEnv = process.env, ): CliEnvironment { - const { clock, dataDirectory, filesystem, ipc, launcher, systemStats } = ports; + const { clock, daemonHome, filesystem, ipc, launcher, systemStats } = ports; + const { dataDirectory } = daemonHome; const configPath = join(dataDirectory, "config.json"); const logPath = join(dataDirectory, "daemon.log"); const adminTokenPath = join(dataDirectory, "admin.token"); @@ -186,6 +187,7 @@ export function buildCliEnvironment( configPath, filesystem, modules: await moduleConfigEntries(), + role: daemonHome.role, systemStats, }); }; @@ -222,6 +224,7 @@ export function buildCliEnvironment( return { clock, configPath, + daemonHome, requesterId, connectAdmin: (resolveCredential) => autoLaunch.connect(resolveCredential), connectExistingAdmin: (resolveCredential) => connect(ipc, resolveCredential), @@ -260,6 +263,7 @@ export function buildCliEnvironment( filesystem: new MemoryFilesystem(), modules: await moduleConfigEntries(), overrides: merged as ConfigOverrides, + role: daemonHome.role, systemStats, warn: (message) => { if (message.startsWith("Unknown config key:")) unknownKeyWarnings.push(message); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 17befbe07..f9009fa8f 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -179,6 +179,42 @@ describe("CLI: exit codes", () => { expect(output.stderr).not.toContain("already"); }); + const NO_GATEWAY_MESSAGE = + "No gateway on this machine. Start one with: simlock --gateway daemon start"; + + it("a CLI error with code GATEWAY_NOT_PRESENT prints that code and exits 2", async () => { + const output = outputCapture(); + let connected = false; + + await expect( + runCli( + ["--gateway", "status"], + output.environmentWith({ + connectAdmin: async () => { + connected = true; + return fakeClient(); + }, + }), + ), + ).resolves.toBe(2); + expect(JSON.parse(output.stderr)).toEqual({ + error: { code: "GATEWAY_NOT_PRESENT", message: NO_GATEWAY_MESSAGE }, + }); + expect(connected).toBe(false); + }); + + it("simlock --help lists --gateway", async () => { + const output = outputCapture(); + + await expect(runCli(["--help"], output.environmentWith())).resolves.toBe(0); + expect(output.stdout).toContain( + "Pass --gateway anywhere on the command line to reach this machine's gateway in place of its worker.", + ); + const gatewayOutput = outputCapture(); + await runCli(["--gateway", "--help"], gatewayOutput.environmentWith()); + expect(gatewayOutput.stdout).toBe(output.stdout); + }); + it("prints shell export lines instead of the JSON grant under --export-env", async () => { const output = outputCapture(); const grant: LeaseGrant = { @@ -1200,7 +1236,7 @@ describe("CLI: admin credential resolution (ADR 0003 §5)", () => { }), ipc: ipcTransport, launcher, - dataDirectory: "/simlock", + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, }); const exitCode = await runCli( ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--detach"], @@ -1232,7 +1268,7 @@ describe("CLI: admin credential resolution (ADR 0003 §5)", () => { }), ipc: new MemoryIpcTransport(), launcher, - dataDirectory: "/simlock", + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, }); const exitCode = await runCli(["daemon", "start"], output.environmentWith()); expect(exitCode).toBe(1); @@ -1262,7 +1298,7 @@ describe("CLI: admin credential resolution (ADR 0003 §5)", () => { }), ipc: ipcTransport, launcher, - dataDirectory: "/simlock", + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, }); const exitCode = await runCli( ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--detach"], @@ -1304,7 +1340,7 @@ describe("CLI: auto-launch's startup deadline (#663)", () => { }); }); }), - dataDirectory: "/simlock", + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, }; return { clock, ports }; } @@ -1420,7 +1456,7 @@ describe("CLI: auto-launch's failed start (#672)", () => { systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), ipc: new MemoryIpcTransport(), launcher, - dataDirectory: "/simlock", + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, }); let settled = false; const exitCode = runCli(["daemon", "start", "--json"], output.environmentWith()).then( @@ -1472,7 +1508,7 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), ipc: dyingDaemon, launcher, - dataDirectory: "/simlock", + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, }); let settled = false; const exitCode = runCli( @@ -2493,6 +2529,50 @@ describe("CLI: config set validates with the real config loader (ADR 0003 §11, expect(JSON.parse(output.stderr).error.code).toBe("USAGE"); }); + it("--gateway config set validates against the gateway's rules, not the worker's", async () => { + const gatewayHome = { + role: "gateway", + dataDirectory: "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/simlock/gateway", + gatewayPresent: true, + } as const; + const output = outputCapture({ ...realCliEnvironmentPorts(), daemonHome: gatewayHome }); + let wrote = false; + const exitCode = await runCli( + ["--gateway", "config", "set", "http.enabled", "false"], + output.environmentWith({ + readConfigFile: async () => ({}), + writeConfigFile: async () => { + wrote = true; + }, + }), + ); + expect(exitCode).toBe(2); + expect(wrote).toBe(false); + expect(output.stderr).toContain("http.enabled"); + }); + + it("starting a gateway checks its config.json as a gateway before launching", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("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/simlock/gateway"); + await filesystem.writeFileAtomic( + "/simlock/gateway/config.json", + JSON.stringify({ http: { enabled: false } }), + ); + const launcher = new FakeDaemonLauncher(); + const output = outputCapture({ + ...realCliEnvironmentPorts(filesystem), + daemonHome: { role: "gateway", dataDirectory: "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/simlock/gateway", gatewayPresent: true }, + launcher, + }); + const exitCode = await runCli( + ["--gateway", "daemon", "start", "--token", "probe"], + output.environmentWith(), + ); + expect(exitCode).not.toBe(0); + expect(launcher.launches).toBe(0); + expect(output.stderr).toContain("http.enabled"); + }); + it("rejects a mistyped key (missing the Ms suffix) instead of validating clean", async () => { const output = outputCapture(realCliEnvironmentPorts()); let wrote = false; @@ -5941,6 +6021,38 @@ describe("CLI: holder renew and release (ADR 0004 §2)", () => { }); describe("CLI: mcp command (ADR 0003 §11 -- lazy module load)", () => { + it.each([ + [["--gateway", "mcp"], 0, true], + [["mcp", "--gateway"], 0, true], + [["mcp"], 0, false], + [["--gateway=yes", "mcp"], 2, undefined], + ] as const)( + "--gateway is taken from anywhere in the argv and reaches the command as context.gateway; --gateway= is a usage error (%j)", + async (argv, exitCode, gateway) => { + const output = outputCapture(); + const seen: boolean[] = []; + + const code = await runCli( + argv, + output.environmentWith({ + runMcpStdio: async (options) => { + seen.push(options.gateway); + }, + }), + ); + + expect(code).toBe(exitCode); + if (gateway === undefined) { + expect(JSON.parse(output.stderr)).toMatchObject({ + error: { code: "USAGE", message: expect.stringContaining("--gateway takes no value") }, + }); + expect(seen).toEqual([]); + } else { + expect(seen).toEqual([gateway]); + } + }, + ); + it("does not load the MCP stdio module unless the mcp command runs", async () => { const output = outputCapture(); let loaded = false; @@ -6013,7 +6125,7 @@ describe("CLI: events history", () => { return { ...realCliEnvironmentPorts(new NodeFilesystem()), clock: new FakeClock(2 * hour), - dataDirectory: directory, + daemonHome: { role: "worker", dataDirectory: directory, gatewayPresent: false }, }; } @@ -6481,7 +6593,7 @@ describe("CLI: a SIMLOCK_HOME the kernel could not bind", () => { const tooDeep = `/tmp/${"d".repeat(120)}`; const ports = (): CliEnvironmentPorts => ({ ...realCliEnvironmentPorts(), - dataDirectory: tooDeep, + daemonHome: { role: "worker", dataDirectory: tooDeep, gatewayPresent: false }, }); it("still prints help, which needs no socket at all", async () => { @@ -6809,6 +6921,7 @@ function outputCapture(ports?: CliEnvironmentPorts): OutputCapture { return { clock: new FakeClock(0), configPath: "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/simlock/config.json", + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, requesterId: "test-requester", connectAdmin: async () => fakeClient(), connectExistingAdmin: async () => fakeClient(), @@ -7083,7 +7196,7 @@ function realCliEnvironmentPorts( }), ipc: new MemoryIpcTransport(), launcher: new FakeDaemonLauncher(), - dataDirectory: "/simlock", + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, }; } diff --git a/src/cli/index.ts b/src/cli/index.ts index 99938c1ca..9810a1b47 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -37,14 +37,18 @@ Run 'simlock --help' for command usage. Pass --token anywhere on the command line to connect as admin explicitly; see https://github.com/callstackincubator/simlock for the default -resolution order.`; +resolution order. -function extractGlobalToken(argv: readonly string[]): { +Pass --gateway anywhere on the command line to reach this machine's gateway in place of its worker.`; + +function extractGlobalFlags(argv: readonly string[]): { readonly token: string | undefined; + readonly gateway: boolean; readonly rest: string[]; } { const rest: string[] = []; let token: string | undefined; + let gateway = false; for (let index = 0; index < argv.length; index++) { const arg = argv[index] as string; if (arg === "--token") { @@ -58,9 +62,14 @@ function extractGlobalToken(argv: readonly string[]): { token = arg.slice("--token=".length); continue; } + if (arg === "--gateway") { + gateway = true; + continue; + } + if (arg.startsWith("--gateway=")) throw new UsageError("--gateway takes no value"); rest.push(arg); } - return { token, rest }; + return { token, gateway, rest }; } /** why: the ports barrel is loaded here, not statically, so `simlock --help` answers without @@ -68,7 +77,7 @@ function extractGlobalToken(argv: readonly string[]): { * exceeds the platform limit throws `SocketPathTooLongError`, and this runs inside `runCli`'s * try, where that throw becomes the single structured error line `docs/CLI.md` promises instead * of a raw stack trace. */ -async function buildDefaultEnvironment(): Promise { +async function buildDefaultEnvironment(gateway: boolean): Promise { const [{ join, dirname }, { fileURLToPath }, ports, { buildCliEnvironment }] = await Promise.all([ import("node:path"), import("node:url"), @@ -81,23 +90,29 @@ async function buildDefaultEnvironment(): Promise { NodeIpcTransport, NodeSystemStats, SystemClock, + resolveDaemonHome, resolveSimlockHome, } = ports; - const dataDirectory = resolveSimlockHome(process.env); - const logPath = join(dataDirectory, "daemon.log"); + const root = resolveSimlockHome(process.env); + const filesystem = new NodeFilesystem(); + const daemonHome = await resolveDaemonHome({ root, gateway, filesystem }); + const logPath = join(daemonHome.dataDirectory, "daemon.log"); return buildCliEnvironment( { - filesystem: new NodeFilesystem(), + filesystem, clock: new SystemClock(), systemStats: new NodeSystemStats(), ipc: new NodeIpcTransport(), launcher: new NodeDaemonLauncher({ - args: [join(dirname(fileURLToPath(import.meta.url)), "../daemon/main.js")], + args: [ + join(dirname(fileURLToPath(import.meta.url)), "../daemon/main.js"), + ...(gateway ? ["--gateway"] : []), + ], command: process.execPath, logPath, - simlockHome: dataDirectory, + simlockHome: root, }), - dataDirectory, + daemonHome, }, process.env, ); @@ -107,23 +122,46 @@ function isHelp(value: string | undefined): boolean { return value === "--help" || value === "-h"; } +const GATEWAY_EXEMPT_PATHS: readonly (readonly string[])[] = [ + ["daemon", "start"], + ["config", "set"], + ["mcp"], +]; + +async function refuseWhenNoGateway( + environment: CliEnvironment, + path: readonly string[], + rest: readonly string[], +): Promise { + if (environment.daemonHome.gatewayPresent) return; + if (GATEWAY_EXEMPT_PATHS.some((exempt) => exempt.join(" ") === path.join(" "))) return; + // why: `adb` and `simctl` have no help of their own and hand every argument to the tool, so a `-h` after them is never a help request. + const passthrough = path[0] === "adb" || path[0] === "simctl"; + if (!passthrough && rest.some(isHelp)) return; + const { gatewayNotPresentError } = await import("../contract/index.js"); + throw gatewayNotPresentError(); +} + export async function runCli( argv: readonly string[], environment?: CliEnvironment, ): Promise { try { - if (argv.length === 0 || isHelp(argv[0])) { + const { token, gateway, rest } = extractGlobalFlags(argv); + if (rest.length === 0 || isHelp(rest[0])) { (environment?.stdout ?? process.stdout).write(`${USAGE}\n`); return 0; } - const { token, rest } = extractGlobalToken(argv); const command = await resolveCommand(COMMANDS, rest); if (command === undefined) throw new UsageError(withHelpHint(`Unknown command: ${String(rest[0])}`)); + const resolved = environment ?? (await buildDefaultEnvironment(gateway)); + if (gateway) await refuseWhenNoGateway(resolved, command.path, command.rest); return await command.module.run(command.rest, { path: command.path, - environment: environment ?? (await buildDefaultEnvironment()), + environment: resolved, token, + gateway, }); } catch (error: unknown) { await writeError((value) => (environment?.stderr ?? process.stderr).write(value), error); diff --git a/src/cli/lazy-loading.test.ts b/src/cli/lazy-loading.test.ts index ab48887fe..1cde21ad1 100644 --- a/src/cli/lazy-loading.test.ts +++ b/src/cli/lazy-loading.test.ts @@ -58,7 +58,7 @@ const home = mkdtempSync(join(tmpdir(), "simlock-cli-lazy-")); async function environment(): Promise { const ports: CliEnvironmentPorts = { clock: new FakeClock(0), - dataDirectory: home, + daemonHome: { role: "worker", dataDirectory: home, gatewayPresent: false }, filesystem: new MemoryFilesystem(), ipc: new MemoryIpcTransport(), launcher: new FakeDaemonLauncher(), diff --git a/src/cli/lazy-parent-watch.test.ts b/src/cli/lazy-parent-watch.test.ts index 26a4a0bb4..9302ca596 100644 --- a/src/cli/lazy-parent-watch.test.ts +++ b/src/cli/lazy-parent-watch.test.ts @@ -42,7 +42,11 @@ describe("the default parent watch", () => { const environment = buildCliEnvironment( { clock: new FakeClock(0), - dataDirectory: mkdtempSync(join(tmpdir(), "simlock-cli-lazy-watch-")), + daemonHome: { + role: "worker", + dataDirectory: mkdtempSync(join(tmpdir(), "simlock-cli-lazy-watch-")), + gatewayPresent: false, + }, filesystem: new MemoryFilesystem(), ipc: new MemoryIpcTransport(), launcher: new FakeDaemonLauncher(), diff --git a/src/cli/tree.ts b/src/cli/tree.ts index 170eb5781..e64380855 100644 --- a/src/cli/tree.ts +++ b/src/cli/tree.ts @@ -8,6 +8,7 @@ export interface CommandContext { readonly path: readonly string[]; readonly environment: CliEnvironment; readonly token: string | undefined; + readonly gateway: boolean; } export interface CommandModule { diff --git a/src/cli/types.ts b/src/cli/types.ts index 6d769dfd8..83267a5cd 100644 --- a/src/cli/types.ts +++ b/src/cli/types.ts @@ -5,6 +5,7 @@ import type { EventEnvelope } from "../bus/index.js"; import type { PassthroughCommand } from "../client/index.js"; import type { Clock, + DaemonHome, DaemonLauncher, Filesystem, IpcConnector, @@ -24,11 +25,12 @@ export interface Output { /** why: the CLI's own shape for "start the stdio MCP server and run until it closes"; * `src/mcp/main.ts` has a runner of the same job under the same name and a different shape, so * this one is named for what the CLI holds rather than shared, which would couple the two. */ -export type McpStdioLauncher = () => Promise; +export type McpStdioLauncher = (options: { readonly gateway: boolean }) => Promise; export interface CliEnvironment { readonly clock: Clock; readonly configPath: string; + readonly daemonHome: DaemonHome; readonly requesterId: string; readonly connectAdmin: ( resolveCredential: () => Promise, @@ -46,7 +48,7 @@ export interface CliEnvironment { readonly followLogFile?: () => Promise; readonly readEventHistory: (sinceTs: number) => Promise; readonly loadMcpStdio?: () => Promise; - readonly runMcpStdio?: () => Promise; + readonly runMcpStdio?: McpStdioLauncher; readonly signals: Signals; readonly parentPid?: number; readonly parentWatch?: ParentWatch; @@ -63,7 +65,7 @@ export interface CliEnvironmentPorts { readonly systemStats: SystemStats; readonly ipc: IpcConnector; readonly launcher: DaemonLauncher; - readonly dataDirectory: string; + readonly daemonHome: DaemonHome; readonly parentWatch?: ParentWatch; readonly signals?: Signals; readonly stderr?: Output; diff --git a/src/contract/errors.ts b/src/contract/errors.ts index e5a512ec6..a53a5437e 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -105,6 +105,7 @@ export interface ErrorDetailsMap { HISTORY_UNAVAILABLE: Record; NUKE_UNAVAILABLE: Record; INTERNAL: Record; + GATEWAY_NOT_PRESENT: Record; UNSUPPORTED_IN_GATEWAY_MODE: { readonly operation: string }; /** @@ -378,6 +379,13 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry httpStatus: 503, }, INTERNAL: { code: "INTERNAL", kind: "domain", cliExitCode: 1, httpStatus: 500 }, + // why: never sent over HTTP (the CLI and MCP raise it before they connect); the table needs a value. + GATEWAY_NOT_PRESENT: { + code: "GATEWAY_NOT_PRESENT", + kind: "domain", + cliExitCode: 2, + httpStatus: 404, + }, // 501, not 400/503: the request was well-formed and the daemon is healthy -- this endpoint // simply does not implement that operation, which is exactly what "Not Implemented" says. // `cliExitCode: 2` puts it with the other "you asked the wrong thing" outcomes. @@ -488,6 +496,16 @@ export function isSimlockError(error: unknown): error is AnySimlockError { return error instanceof SimlockError; } +/** why: the CLI and MCP raise this one error from two places, so the wording lives once. */ +export function gatewayNotPresentError(): SimlockError<"GATEWAY_NOT_PRESENT"> { + return new SimlockError( + "GATEWAY_NOT_PRESENT", + "domain", + "No gateway on this machine. Start one with: simlock --gateway daemon start", + {}, + ); +} + /** * Builds a typed `SimlockError` from a raw wire `{code, message}` (and optional already-parsed * `details`), the client-side half of ADR §7's forward-compatibility rule: a `code` this diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index 5bb6073bc..883a9e26b 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -9,34 +9,34 @@ See also: [leasing](../leasing/AGENTS.md) (lease flow, when reclaim runs), [warm ## Files -| File | Role | -| ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Wiring and state** | | -| `create-core.ts`, `core-ports.ts` | `createCore`, `Core`, `CorePorts`; read ports (`CapacityReader`, `WarmPoolReader`, …) | -| `registry.ts` | `Registry`: the one writer of `state.json` | -| `domain.ts` | Records, specs, `transition`, `fits`, `mayBeGranted`, `sameSpec` | -| `serialized-decision.ts`, `device-operation-claims.ts` | The lock; one in-memory claim per device | -| `config.ts`, `validation.ts` | `loadConfig` (with the optional modules' `ModuleConfigEntry` list: `capabilities.` sections, `enabled` owned here), defaults, validators, `redactConfig`, `effectiveAllowDownload` | -| `lease-request-store.ts` | Pure lease-request record helpers, shared with leasing | -| **Device verbs** | | -| `managed-device-lifecycle.ts` | `ManagedDeviceLifecycle`: every driver verb on a registered device | -| `device-provisioner.ts` | `DeviceProvisioner`: the one place a device record is created | -| `reclaim-coordinator.ts` | `ReclaimCoordinator`: wipe after a lease, spent delete, interrupted reclaim | -| `quarantine-coordinator.ts` | `QuarantineCoordinator`: entry, retry on backoff, give up | -| `nuke-service.ts`, `nuke.ts` | `NukeService` (operator reset); `Nuke` (command facade) | -| `idle-order.ts` | LRU order and eviction victim choice | -| **Background** | | -| `warm-pool/`, `capacity/` | What stays warm; limits, RAM budget, reservations (own manuals) | -| `reaper.ts`, `cleanup/`, `cleanup-executor.ts` | `CleanupReaper`, pure rules, `CleanupExecutor` | -| **Startup, health, drivers** | | -| `startup-read.ts`, `startup-converger.ts` | `readStartup`; `StartupConverger`, the device half of startup | -| `doctor.ts`, `host-facts.ts` | `Doctor` findings and fixes; `HostFactsReader` for status | -| `driver.ts`, `driver-catalog.ts`, `screen.ts` | `Driver`, errors, `DiskSpaceGuard`; `DriverCatalog`; `ScreenCapture`, frame tags | -| `catalog-match.ts` | Model name, class and paired runtimes against a catalog entry | -| `component-installer.ts` | `ComponentInstaller`: install, list, remove | -| `physical-enrollment.ts`, `physical-presence.ts` | `device add`/`remove`; every presence read, `latestPresence` | -| `device-root.ts`, `instance-identity.ts` | `ensureOwnedRoot`; `loadInstanceId` | -| `stable-error.ts`, `testing.ts`, `fake-driver.ts` | `stableError`; test-only wiring and `FakeDriver` | +| File | Role | +| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Wiring and state** | | +| `create-core.ts`, `core-ports.ts` | `createCore`, `Core`, `CorePorts`; read ports (`CapacityReader`, `WarmPoolReader`, …) | +| `registry.ts` | `Registry`: the one writer of `state.json` | +| `domain.ts` | Records, specs, `transition`, `fits`, `mayBeGranted`, `sameSpec` | +| `serialized-decision.ts`, `device-operation-claims.ts` | The lock; one in-memory claim per device | +| `config.ts`, `validation.ts` | `loadConfig({ role })` (the role comes from the daemon, never a config key; a `mode` key is refused; with the optional modules' `ModuleConfigEntry` list: `capabilities.` sections, `enabled` owned here), defaults, validators, `redactConfig`, `effectiveAllowDownload` | +| `lease-request-store.ts` | Pure lease-request record helpers, shared with leasing | +| **Device verbs** | | +| `managed-device-lifecycle.ts` | `ManagedDeviceLifecycle`: every driver verb on a registered device | +| `device-provisioner.ts` | `DeviceProvisioner`: the one place a device record is created | +| `reclaim-coordinator.ts` | `ReclaimCoordinator`: wipe after a lease, spent delete, interrupted reclaim | +| `quarantine-coordinator.ts` | `QuarantineCoordinator`: entry, retry on backoff, give up | +| `nuke-service.ts`, `nuke.ts` | `NukeService` (operator reset); `Nuke` (command facade) | +| `idle-order.ts` | LRU order and eviction victim choice | +| **Background** | | +| `warm-pool/`, `capacity/` | What stays warm; limits, RAM budget, reservations (own manuals) | +| `reaper.ts`, `cleanup/`, `cleanup-executor.ts` | `CleanupReaper`, pure rules, `CleanupExecutor` | +| **Startup, health, drivers** | | +| `startup-read.ts`, `startup-converger.ts` | `readStartup`; `StartupConverger`, the device half of startup | +| `doctor.ts`, `host-facts.ts` | `Doctor` findings and fixes; `HostFactsReader` for status | +| `driver.ts`, `driver-catalog.ts`, `screen.ts` | `Driver`, errors, `DiskSpaceGuard`; `DriverCatalog`; `ScreenCapture`, frame tags | +| `catalog-match.ts` | Model name, class and paired runtimes against a catalog entry | +| `component-installer.ts` | `ComponentInstaller`: install, list, remove | +| `physical-enrollment.ts`, `physical-presence.ts` | `device add`/`remove`; every presence read, `latestPresence` | +| `device-root.ts`, `instance-identity.ts` | `ensureOwnedRoot`; `loadInstanceId` | +| `stable-error.ts`, `testing.ts`, `fake-driver.ts` | `stableError`; test-only wiring and `FakeDriver` | ## Wiring @@ -144,7 +144,7 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic - **A rollback keeps a stale quarantine cause.** An older daemon keeps `quarantineCause` unknown; re-entry under it shows the old one. - **One download at a time per platform.** A second missing runtime waits, spending its own `downloads.timeoutMs`. A bounded model with no `--os` asks Xcode for a bare major; pass `--os`. -- **`component remove` sees only this instance.** Another instance's devices, never-used default-set +- **`component remove` sees only this instance.** One worker per user, so this matters for test roots and a second OS user. Another instance's devices, never-used default-set simulators and foreign devices made after the driver's count are not counted. - **An older Simlock cannot end a physical lease.** It skips `physicalDevices`; `beginRelease` throws `UnknownDeviceError`. Release physical leases before a rollback. -- **Two instances can enrol one device.** Each release uninstalls apps not on its own list. Enrol a device in one instance only. +- **Two instances can enrol one device.** Only test roots and a second OS user can run a second instance. Each release uninstalls apps not on its own list. Enrol a device in one instance only. diff --git a/src/core/config-capabilities.test.ts b/src/core/config-capabilities.test.ts index 080c825b8..e2bf9db6e 100644 --- a/src/core/config-capabilities.test.ts +++ b/src/core/config-capabilities.test.ts @@ -21,6 +21,7 @@ async function load( contents: unknown, modules: readonly ModuleConfigEntry[] = [entry()], warnings: string[] = [], + role: "worker" | "gateway" = "worker", ) { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); @@ -29,6 +30,7 @@ async function load( configPath, filesystem, modules, + role, systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * 1024 ** 3 }), warn: (message) => warnings.push(message), }); @@ -100,13 +102,12 @@ describe("loadConfig with optional modules", () => { it("on a gateway, reads enabled without a warning, and warns about a key outside gatewayKeys, naming capabilities..", async () => { const contents = { capabilities: { alpha: { enabled: true, greeting: "hi" } }, - mode: "gateway", }; const closed: string[] = []; const open: string[] = []; - const config = await load(contents, [entry()], closed); - await load(contents, [entry({ gatewayKeys: ["greeting"] })], open); + const config = await load(contents, [entry()], closed, "gateway"); + await load(contents, [entry({ gatewayKeys: ["greeting"] })], open, "gateway"); expect(config.capabilities["alpha"]?.["enabled"]).toBe(true); expect(closed).toEqual([ diff --git a/src/core/config.test.ts b/src/core/config.test.ts index c8f1f0d1a..145c6899d 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -119,7 +119,7 @@ describe("loadConfig", () => { maxBytes: 256 * 1024 * 1024, }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, - http: { enabled: false, host: "127.0.0.1", port: 4700 }, + http: { enabled: false, host: "127.0.0.1", port: 4701 }, warmPool: { enabled: true, maxConcurrentBoots: 1, @@ -1698,6 +1698,7 @@ describe("loadConfig modes (ADR 0005)", () => { contents: unknown, options: { readonly overrides?: Parameters[0]["overrides"]; + readonly role?: "worker" | "gateway"; readonly warn?: (message: string) => void; } = {}, ) { @@ -1708,6 +1709,7 @@ describe("loadConfig modes (ADR 0005)", () => { configPath, filesystem, systemStats: createStats(), + ...(options.role === undefined ? {} : { role: options.role }), ...(options.overrides === undefined ? {} : { overrides: options.overrides }), ...(options.warn === undefined ? {} : { warn: options.warn }), }); @@ -1727,30 +1729,39 @@ describe("loadConfig modes (ADR 0005)", () => { }); }); - it("rejects a mode outside the two the ADR names", async () => { - await expect(load({ mode: "hybrid" })).rejects.toThrow("mode"); - }); + it.each([ + ["file worker", { contents: { mode: "worker" } }], + ["file gateway", { contents: { mode: "gateway" } }], + ["override gateway", { contents: {}, overrides: { mode: "gateway" } }], + ] as const)( + "refuses a config that sets mode, either value, from the file or the overrides, with the message that names --gateway (%s)", + async (_name, { contents, ...options }) => { + await expect(load(contents, options)).rejects.toThrow( + '"mode" is no longer a config key. A daemon started with --gateway is a gateway; any other is a worker. Remove "mode" from config.json.', + ); + }, + ); it("turns HTTP on by default in gateway mode -- a gateway is the fleet's contact point", async () => { - const config = await load({ mode: "gateway" }); + const config = await load({}, { role: "gateway" }); expect(config.http.enabled).toBe(true); expect(config.http.port).toBe(4700); }); it("refuses a gateway that switches HTTP off, naming the key, and loads a worker that does", async () => { - await expect(load({ mode: "gateway", http: { enabled: false } })).rejects.toThrow( + await expect(load({ http: { enabled: false } }, { role: "gateway" })).rejects.toThrow( "http.enabled", ); // HTTP is genuinely optional for a worker. - await expect(load({ mode: "worker", http: { enabled: false } })).resolves.toMatchObject({ + await expect(load({ http: { enabled: false } })).resolves.toMatchObject({ http: { enabled: false }, mode: "worker", }); }); it("keeps an explicit gateway http host/port", async () => { - const config = await load({ mode: "gateway", http: { host: "0.0.0.0", port: 4800 } }); + const config = await load({ http: { host: "0.0.0.0", port: 4800 } }, { role: "gateway" }); expect(config.http).toEqual({ enabled: true, host: "0.0.0.0", port: 4800 }); }); @@ -1759,12 +1770,11 @@ describe("loadConfig modes (ADR 0005)", () => { const warn = vi.fn(); const config = await load( { - mode: "gateway", capacity: { strategy: "fixed", config: { maxRunning: 3 } }, ios: { defaultMode: "slim" }, lease: { defaultTtlMs: 60_000 }, }, - { warn }, + { role: "gateway", warn }, ); expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring "capacity"')); @@ -1780,7 +1790,7 @@ describe("loadConfig modes (ADR 0005)", () => { it("reads lease.maxPerRequester in gateway mode without an ignored-key warning", async () => { const warn = vi.fn(); - const config = await load({ mode: "gateway", lease: { maxPerRequester: 2 } }, { warn }); + const config = await load({ lease: { maxPerRequester: 2 } }, { role: "gateway", warn }); expect(config.lease).toMatchObject({ maxPerRequester: 2 }); expect(warn).not.toHaveBeenCalled(); @@ -1790,8 +1800,8 @@ describe("loadConfig modes (ADR 0005)", () => { const warn = vi.fn(); const config = await load( - { mode: "gateway", metrics: { retention: 120 * 24 * 3_600_000 } }, - { warn }, + { metrics: { retention: 120 * 24 * 3_600_000 } }, + { role: "gateway", warn }, ); expect(config.metrics).toEqual({ retention: 120 * 24 * 3_600_000 }); @@ -1800,7 +1810,7 @@ describe("loadConfig modes (ADR 0005)", () => { it("raises the unknown-key warning for eventLog.rotateBytes in a gateway config", async () => { const warn = vi.fn(); - await load({ mode: "gateway", eventLog: { rotateBytes: 1024 } }, { warn }); + await load({ eventLog: { rotateBytes: 1024 } }, { role: "gateway", warn }); expect(warn).toHaveBeenCalledWith('Unknown config key: "eventLog.rotateBytes"'); }); @@ -1808,8 +1818,8 @@ describe("loadConfig modes (ADR 0005)", () => { it("warns about android.emulator on a gateway without refusing the config", async () => { const warn = vi.fn(); const config = await load( - { mode: "gateway", android: { defaultModels: {}, emulator: { headless: true } } }, - { warn }, + { android: { defaultModels: {}, emulator: { headless: true } } }, + { role: "gateway", warn }, ); expect(warn).toHaveBeenCalledWith( @@ -1821,21 +1831,23 @@ describe("loadConfig modes (ADR 0005)", () => { it("warns about the worker-side gateway.* keys on a gateway, but not the gateway's own", async () => { const warn = vi.fn(); - const config = await load({ - mode: "gateway", - gateway: { - url: "ws://127.0.0.1:4700/v1/uplink", - token: "secret", - label: "ignored", - disconnectedRetentionMs: 60_000, + const config = await load( + { + gateway: { + url: "ws://127.0.0.1:4700/v1/uplink", + token: "secret", + label: "ignored", + disconnectedRetentionMs: 60_000, + }, }, - }); + { role: "gateway" }, + ); expect(config.gateway.disconnectedRetentionMs).toBe(60_000); const warned = await load( - { mode: "gateway", gateway: { url: "ws://127.0.0.1:4700/v1/uplink" } }, - { warn }, + { gateway: { url: "ws://127.0.0.1:4700/v1/uplink" } }, + { role: "gateway", warn }, ); expect(warned.mode).toBe("gateway"); expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring "gateway.url"')); @@ -1871,7 +1883,7 @@ describe("loadConfig modes (ADR 0005)", () => { it("does not pair those keys on a gateway, which reads neither", async () => { const warn = vi.fn(); await expect( - load({ mode: "gateway", gateway: { url: "ws://fleet.example" } }, { warn }), + load({ gateway: { url: "ws://fleet.example" } }, { role: "gateway", warn }), ).resolves.toBeDefined(); expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring "gateway.url"')); }); @@ -1898,15 +1910,18 @@ describe("loadConfig modes (ADR 0005)", () => { }); it("defaults the gateway lease-request timeout well under the exec backstop", async () => { - const config = await load({ mode: "gateway" }); + const config = await load({}, { role: "gateway" }); expect(config.gateway.leaseRequestTimeoutMs).toBeLessThan(config.gateway.execTimeoutMs); }); - it("lets an override name the mode, like every other key", async () => { - const config = await load({}, { overrides: { mode: "gateway" } }); + it("reports the role it was loaded for as config.mode", async () => { + expect((await load({}, { role: "gateway" })).mode).toBe("gateway"); + expect((await load({}, { role: "worker" })).mode).toBe("worker"); + }); - expect(config.mode).toBe("gateway"); - expect(config.http.enabled).toBe(true); + it("HTTP defaults to port 4700 for a gateway and 4701 for a worker", async () => { + expect((await load({}, { role: "gateway" })).http.port).toBe(4700); + expect((await load({})).http.port).toBe(4701); }); }); @@ -1944,17 +1959,17 @@ describe("gateway.alerts.destinations", () => { async function load( gateway: Record, - mode: "gateway" | "worker" = "gateway", + role: "gateway" | "worker" = "gateway", warn: (message: string) => void = () => {}, ): Promise { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic(configPath, JSON.stringify({ mode, gateway })); - return loadConfig({ configPath, filesystem, systemStats: createStats(), warn }); + await filesystem.writeFileAtomic(configPath, JSON.stringify({ gateway })); + return loadConfig({ configPath, filesystem, role, systemStats: createStats(), warn }); } - function loadDestinations(destinations: unknown, mode: "gateway" | "worker" = "gateway") { - return load({ alerts: { destinations } }, mode); + function loadDestinations(destinations: unknown, role: "gateway" | "worker" = "gateway") { + return load({ alerts: { destinations } }, role); } it("loadConfig accepts a valid generic destination and defaults gateway.alerts.destinations to an empty list", async () => { @@ -2091,11 +2106,16 @@ describe("gateway.alerts.destinations", () => { }); describe("redactConfig", () => { - async function load(contents: unknown): Promise { + async function load(contents: unknown, role?: "gateway" | "worker"): Promise { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); await filesystem.writeFileAtomic(configPath, JSON.stringify(contents)); - return loadConfig({ configPath, filesystem, systemStats: createStats() }); + return loadConfig({ + configPath, + filesystem, + ...(role ? { role } : {}), + systemStats: createStats(), + }); } it("replaces a set gateway.token with the marker, keeps every other key, and leaves the input untouched", async () => { @@ -2136,10 +2156,7 @@ describe("redactConfig", () => { }, ]; for (const token of ["join-token", undefined]) { - const config = await load({ - mode: "gateway", - gateway: { token, alerts: { destinations } }, - }); + const config = await load({ gateway: { token, alerts: { destinations } } }, "gateway"); const before = structuredClone(config); const redacted = redactConfig(config); diff --git a/src/core/config.ts b/src/core/config.ts index 1efdb87e2..cd248f0bf 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -245,10 +245,10 @@ const DEFAULT_EXEC_TIMEOUT_MS = 10 * 60_000; export type DownloadPolicy = "never" | "on-request" | "always"; /** - * Which shape a daemon runs as (ADR 0005 §1): a `worker` owns the devices on its machine -- - * every daemon today -- and a `gateway` owns none and fronts the workers that joined it. One - * daemon runs exactly one mode, and it is a config value rather than a flag because it decides - * what the process *is*, not what one invocation does. + * why: which shape a daemon runs as (ADR 0005 §1): a `worker` owns the devices on its machine and a + * `gateway` owns none and fronts the workers that joined it. One daemon runs exactly one mode, + * and the folder it lives in decides it (ADR 0034): the daemon is told its role at start, and + * `loadConfig` takes it as an argument -- no config key names it. */ export type DaemonMode = "worker" | "gateway"; @@ -516,6 +516,9 @@ export interface ModuleConfigEntry { readonly check?: (section: never, config: Config) => void; } +const MODE_KEY_REMOVED = + '"mode" is no longer a config key. A daemon started with --gateway is a gateway; any other is a worker. Remove "mode" from config.json.'; + export interface LoadConfigOptions { readonly authStrategies?: readonly AuthStrategyDefinition[]; readonly modules?: readonly ModuleConfigEntry[]; @@ -523,6 +526,7 @@ export interface LoadConfigOptions { readonly systemStats: SystemStats; readonly configPath?: string; readonly overrides?: ConfigOverrides; + readonly role?: DaemonMode; readonly warn?: Warn; } @@ -534,6 +538,7 @@ export async function loadConfig({ filesystem, modules = [], overrides, + role = "worker", systemStats, warn = () => {}, }: LoadConfigOptions): Promise { @@ -544,10 +549,12 @@ export async function loadConfig({ // defaulted: it decides which options block `capacity.config` is, and which // defaults the merge starts from. const strategy = resolveStrategyName([fromFile, fromOverrides]); - // Same reason as the strategy above: `mode` decides which keys are read at all, and what - // `http.enabled` defaults to, so it has to be known before anything is defaulted or warned - // about. - const mode = resolveMode([fromFile, fromOverrides]); + // why: refused before any other validation, so a config that still sets `mode` fails on that alone. + for (const layer of [fromFile, fromOverrides]) { + if (Object.hasOwn(requireObject(layer, "config"), "mode")) { + throw new ConfigError(MODE_KEY_REMOVED); + } + } const validators = configValidators(strategy, modules, authStrategies); const fileConfig = normalizeLayer( @@ -562,7 +569,7 @@ export async function loadConfig({ ); const mergedWithoutMetrics = mergeConfig( - mergeConfig(defaultConfig(systemStats, strategy, mode, modules, authStrategies), fileConfig), + mergeConfig(defaultConfig(systemStats, strategy, role, modules, authStrategies), fileConfig), overrideConfig, ) as unknown as Omit & { readonly metrics?: Config["metrics"] }; const merged: Config = { @@ -578,7 +585,7 @@ export async function loadConfig({ validateMetricsRetention(merged); // why: a gateway reads a module's gateway keys, so a bad value stops it too. runModuleChecks(merged, modules); - if (mode === "gateway") { + if (role === "gateway") { warnWorkerOnlyKeys([fromFile, fromOverrides], warn, modules); requireGatewayHttp(merged); } else { @@ -640,7 +647,6 @@ function validateMetricsRetention(config: Config): void { * decision -- adding a key to `Config` should not silently make it gateway-relevant. */ const GATEWAY_CONFIG_KEYS: readonly string[] = [ - "mode", "http", "log", "lease", @@ -784,20 +790,6 @@ function validateGatewayMembership(config: Config): void { } } -/** Last layer that names a mode wins; absent everywhere means `worker` (ADR 0005 §1). */ -function resolveMode(layers: readonly unknown[]): DaemonMode { - let resolved: DaemonMode = "worker"; - for (const layer of layers) { - const candidate = requireObject(layer, "config")["mode"]; - if (candidate === undefined) continue; - if (candidate !== "worker" && candidate !== "gateway") { - throw invalidValue("mode", 'one of "worker", "gateway"'); - } - resolved = candidate; - } - return resolved; -} - /** Last layer that names a strategy wins; absent everywhere means the default. */ function resolveStrategyName(layers: readonly unknown[]): CapacityStrategyName { let resolved: CapacityStrategyName = DEFAULT_CAPACITY_STRATEGY; @@ -873,12 +865,12 @@ function asObject(value: unknown): Layer { function defaultConfig( systemStats: SystemStats, strategy: CapacityStrategyName, - mode: DaemonMode, + role: DaemonMode, modules: readonly ModuleConfigEntry[], authStrategies: readonly AuthStrategyDefinition[], ): Omit { return { - mode, + mode: role, capabilities: Object.fromEntries( modules.map((entry) => [ entry.name, @@ -929,9 +921,9 @@ function defaultConfig( // something every operator has to remember to switch on; a worker's HTTP gateway stays // opt-in exactly as before. http: { - enabled: mode === "gateway", + enabled: role === "gateway", host: "127.0.0.1", - port: 4700, + port: role === "gateway" ? 4700 : 4701, ...Object.fromEntries( authStrategies.flatMap((definition) => definition.config === undefined @@ -1019,7 +1011,6 @@ function validateConfigLayer( } const LOG_LEVELS: readonly LogLevel[] = ["debug", "info", "warn", "error"]; -const DAEMON_MODES: readonly DaemonMode[] = ["worker", "gateway"]; const DOWNLOAD_POLICIES: readonly DownloadPolicy[] = ["never", "on-request", "always"]; const LEASE_IDENTITIES: readonly LeaseIdentity[] = ["reusable", "fresh"]; @@ -1034,7 +1025,6 @@ function configValidators( ): Record { return { capabilities: capabilitiesValidator(modules), - mode: stringUnion(DAEMON_MODES), gateway: objectValidator({ url: stringValue, token: stringValue, diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 8bc3584bc..19daa951d 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -27,7 +27,7 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs ## Composition (`main.ts`) Both modes: config (`config.json`) → `Logger` → host info → `EventBus` → event history (`createEventHistory`, not yet started). -`config.mode` then picks one branch; a gateway builds none of the worker's parts. +The role (`StartDaemonOptions.role`; the entry reads it from `--gateway` through `parseDaemonArgv`) then picks one branch; a gateway builds none of the worker's parts. The data directory is `daemonDataDirectory(resolveSimlockHome(), role)`: `` for a worker, `/gateway` for a gateway. The daemon never reads the other role's folder. - **Worker** — `Registry` (`state.json`) → instance id (`instance.json`) → `discoverDrivers` (validates each root; a refused root costs that platform only) → @@ -132,9 +132,9 @@ Security model: cooperative identity, not a hostile-process boundary. - At `log.level: debug`, `LoggingProcessRunner` logs one `process` line per command. - Events: ring of `eventBuffer.capacity` (1000) in memory; `history.db` via the [history](../history/AGENTS.md), kept `eventLog.retention` (7 days), event rows capped at `eventLog.maxBytes` (256 MiB); usage rows are kept `metrics.retention` (90 days). `onSocketClaimed` - starts it in both modes with `config.mode` and `metrics.retention`; `dispose` stops it last. A file that fails costs only history. A start the history refuses (a newer stored projection version, a + starts it in both modes with the role and `metrics.retention`; `dispose` stops it last. A file that fails costs only history. A start the history refuses (a newer stored projection version, a failed migration) stops the daemon with reason `history-refused` and exit 1. `status.get` carries its `history`, also while starting. `usage.get` (both dispatchers, `usageAnswer` in `dispatch.ts`) reads the same file's usage rows through `core/usage` on a read thread; `main.ts` passes `historyPath` in both modes, and `dispose` stops the thread. `history.status().opened` false → `HISTORY_UNAVAILABLE`; a window ending before the oldest row → `HISTORY_NOT_KEPT`. -- A start that throws is logged by a fallback logger to the default `daemon.log`; exit 1. +- A start that throws is logged by a fallback logger to the role's `daemon.log`; exit 1. An entry argument other than none or `--gateway` is logged to `/daemon.log` as "Daemon failed to start"; exit 1. ## Rules diff --git a/src/daemon/gateway-fleet.e2e.test.ts b/src/daemon/gateway-fleet.e2e.test.ts index c86d67caa..13f9f9974 100644 --- a/src/daemon/gateway-fleet.e2e.test.ts +++ b/src/daemon/gateway-fleet.e2e.test.ts @@ -140,12 +140,12 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { gatewayPort = await freeLoopbackPort(); const daemon = await startDaemon({ configOverrides: { - mode: "gateway", http: { enabled: true, host: "127.0.0.1", port: gatewayPort }, ...(alerts.destinations === undefined ? {} : { gateway: { alerts: { destinations: alerts.destinations } } }), }, + role: "gateway", dataDirectory: directory, filesystem: new MemoryFilesystem(), hostInfo: new FakeHostInfo(GATEWAY_HOST), @@ -177,9 +177,9 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { restartGatewayPort = await freeLoopbackPort(); const daemon = await startDaemon({ configOverrides: { - mode: "gateway", http: { enabled: true, host: "127.0.0.1", port: restartGatewayPort }, }, + role: "gateway", dataDirectory: directory, filesystem, logger: new NoopLogger(), @@ -501,9 +501,9 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { daemons.splice(daemons.indexOf(firstGateway), 1); const restartedGateway = await startDaemon({ configOverrides: { - mode: "gateway", http: { enabled: true, host: "127.0.0.1", port: restartGatewayPort }, }, + role: "gateway", dataDirectory: directory, filesystem, logger: new NoopLogger(), diff --git a/src/daemon/gateway-modules.test.ts b/src/daemon/gateway-modules.test.ts index cf4013049..9ff86b767 100644 --- a/src/daemon/gateway-modules.test.ts +++ b/src/daemon/gateway-modules.test.ts @@ -66,8 +66,8 @@ function gatewayOptions( configOverrides: { capabilities: Object.fromEntries(on.map((name) => [name, { enabled: true }])), http: { enabled: true, host: "127.0.0.1", port }, - mode: "gateway", }, + role: "gateway", dataDirectory: directory, filesystem: new MemoryFilesystem(), hostLoadProbe: null, diff --git a/src/daemon/lease-requires.e2e.test.ts b/src/daemon/lease-requires.e2e.test.ts index 52589400f..dfc9cc7a7 100644 --- a/src/daemon/lease-requires.e2e.test.ts +++ b/src/daemon/lease-requires.e2e.test.ts @@ -59,7 +59,8 @@ describe("lease.request requires, through a gateway", () => { directories.push(directory); const port = await freeLoopbackPort(); const gateway = await startDaemon({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + role: "gateway", dataDirectory: directory, filesystem: new MemoryFilesystem(), logger: new NoopLogger(), diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 4e49ba559..e1069e199 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -43,6 +43,7 @@ import { modelPreferenceWiring, discoverDrivers, emitSlimDiagnostic, + parseDaemonArgv, processRunnerFor, startDaemon, type DriverDiscoveryContext, @@ -2519,8 +2520,8 @@ describe("startDaemon logger wiring", () => { const { daemon, sink } = await start({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, - mode: "gateway", }, + role: "gateway", }); await expect( @@ -2634,6 +2635,7 @@ describe("startDaemon with the agent-device edge", () => { readonly modules?: readonly FakeModule[]; readonly processRunner: ScriptedProcessRunner; readonly processSupervisor: FakeProcessSupervisor; + readonly role?: "gateway"; }, ) { const clock = new FakeClock(1_000); @@ -2641,6 +2643,7 @@ describe("startDaemon with the agent-device edge", () => { const daemon = await startDaemon({ clock, dataDirectory: setup.directory, + ...(ports.role === undefined ? {} : { role: ports.role }), drivers: ports.drivers ?? [ new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }), ], @@ -2814,14 +2817,18 @@ describe("startDaemon with the agent-device edge", () => { { capabilities: { "agent-device": { command, enabled: true } }, http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, - mode: "gateway", }, { record: { pid: 900 } }, ); const runner = new ScriptedProcessRunner([]); const processSupervisor = new FakeProcessSupervisor([900]); - await startEdge(setup, { drivers: [], processRunner: runner, processSupervisor }); + await startEdge(setup, { + drivers: [], + processRunner: runner, + processSupervisor, + role: "gateway", + }); await pollUntil(() => false, 100); expect(runner.calls).toEqual([]); @@ -3334,8 +3341,8 @@ describe("startDaemon in gateway mode host load", () => { clock, configOverrides: { http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, - mode: "gateway", }, + role: "gateway", dataDirectory: directory, drivers: [], filesystem: new MemoryFilesystem(), @@ -3400,8 +3407,8 @@ describe("startDaemon in gateway mode host load", () => { clock, configOverrides: { http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, - mode: "gateway", }, + role: "gateway", dataDirectory: first.directory, drivers: [], filesystem: new MemoryFilesystem(), @@ -3422,3 +3429,38 @@ describe("startDaemon in gateway mode host load", () => { expect(withLoser).toBe(withoutLoser); }); }); + +describe("daemon role (ADR 0034)", () => { + it("startDaemon with role gateway and no data directory uses /gateway", async () => { + const root = await mkdtemp(join(tmpdir(), "simlock-main-root-")); + temporaryDirectories.push(root); + vi.stubEnv("SIMLOCK_HOME", root); + try { + const daemon = await startDaemon({ + configOverrides: { + http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, + }, + drivers: [], + role: "gateway", + }); + runningDaemons.push(daemon); + + expect(existsSync(join(root, "gateway", "instance.json"))).toBe(true); + expect(existsSync(join(root, "instance.json"))).toBe(false); + } finally { + vi.unstubAllEnvs(); + } + }); + + it.each([ + [[], "worker"], + [["--gateway"], "gateway"], + [["--gateway", "x"], undefined], + [["--worker"], undefined], + ] as const)( + "parseDaemonArgv reads no arguments as a worker, --gateway as a gateway, and anything else as nothing (%j)", + (argv, expected) => { + expect(parseDaemonArgv(argv)).toBe(expected); + }, + ); +}); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index fb834fcc8..34b4e93bd 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -15,6 +15,7 @@ import { import { type Config, type ConfigOverrides, + type DaemonMode, type DeviceClass, type DeviceMode, type Driver, @@ -84,6 +85,7 @@ import { NodeBytePipeLauncher, NodeTcpProbe, NodeTcpStreamConnector, + daemonDataDirectory, resolveDaemonSocketPath, readPackageVersion, resolveSimlockHome, @@ -134,6 +136,7 @@ export interface StartDaemonOptions { /** why: test-only, replaces the registry of optional modules. */ readonly optionalModules?: readonly OptionalModuleDefinition[]; readonly relayTargets?: RelayTargets; + readonly role?: DaemonMode; readonly prerequisiteChecks?: readonly PrerequisiteCheck[]; readonly filesystem?: Filesystem; readonly hostInfo?: HostInfo; @@ -156,7 +159,8 @@ export interface StartDaemonOptions { // fallow-ignore-next-line complexity -- explicit production composition necessarily wires all external ports. export async function startDaemon(options: StartDaemonOptions = {}): Promise { const version = options.version ?? readPackageVersion(); - const dataDirectory = options.dataDirectory ?? resolveSimlockHome(); + const role = options.role ?? "worker"; + const dataDirectory = options.dataDirectory ?? daemonDataDirectory(resolveSimlockHome(), role); const filesystem = options.filesystem ?? new NodeFilesystem(); const clock = options.clock ?? new SystemClock(); const systemStats = options.systemStats ?? new NodeSystemStats(); @@ -178,6 +182,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise configWarnings.push(message), }); @@ -227,7 +232,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise { - const message = error instanceof Error ? error.message : String(error); - const stack = error instanceof Error ? error.stack : undefined; - try { - createFatalLogger().error("Daemon failed to start", { message, stack }); - } catch { - // Logging itself failed (e.g. an unwritable data directory) -- fall back to - // the original behavior so the failure is not silently swallowed. - console.error(error); - } - process.exitCode = 1; - }); + const argv = process.argv.slice(2); + const role = parseDaemonArgv(argv); + if (role === undefined) { + logFatalStart(undefined, "Unknown daemon arguments", { argv }); + } else { + void startDaemon({ role }).catch((error: unknown) => { + logFatalStart(role, error instanceof Error ? error.message : String(error), { + stack: error instanceof Error ? error.stack : undefined, + }); + }); + } } diff --git a/src/daemon/stream-gateway.e2e.test.ts b/src/daemon/stream-gateway.e2e.test.ts index 17f3814c5..0c703e891 100644 --- a/src/daemon/stream-gateway.e2e.test.ts +++ b/src/daemon/stream-gateway.e2e.test.ts @@ -89,9 +89,9 @@ describe("a screen stream through a gateway", () => { const gateway = await startDaemon({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, - mode: "gateway", capabilities: { stream: { enabled: true } }, }, + role: "gateway", dataDirectory: gatewayDirectory, filesystem: new MemoryFilesystem(), logger: new NoopLogger(), diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index 61909d4b6..75d29fe50 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -331,7 +331,8 @@ export async function startFleet(context: FleetContext, options: FleetOptions = let relay: GatewayRelay | undefined; const taps: TappedTransport[] = []; const gateway = await startDaemon({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + role: "gateway", dataDirectory: gatewayDirectory, filesystem: new MemoryFilesystem(), gatewayRelay: (given) => { diff --git a/src/daemon/worker-capabilities.e2e.test.ts b/src/daemon/worker-capabilities.e2e.test.ts index c15482c23..5e58f711b 100644 --- a/src/daemon/worker-capabilities.e2e.test.ts +++ b/src/daemon/worker-capabilities.e2e.test.ts @@ -47,7 +47,8 @@ describe("a worker's capabilities through a gateway", () => { directories.push(gatewayDirectory); const port = await freeLoopbackPort(); const gateway = await startDaemon({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + role: "gateway", dataDirectory: gatewayDirectory, filesystem: new MemoryFilesystem(), hostInfo: new FakeHostInfo({ arch: "x64", os: "Linux", osVersion: "6.8.0" }), diff --git a/src/gateway/AGENTS.md b/src/gateway/AGENTS.md index 0a05dbf56..12000323c 100644 --- a/src/gateway/AGENTS.md +++ b/src/gateway/AGENTS.md @@ -1,6 +1,6 @@ # Gateway -Does: a daemon in `mode: "gateway"`: owns no devices, fronts the workers that dial in. +Does: a daemon started with `--gateway` (it lives in `/gateway`): owns no devices, fronts the workers that dial in. Entry: `index.ts`; `startGatewayDaemon` (`../daemon/main.ts`) wires `GatewayService`, `FleetLeaseCoordinator`, `GatewayDispatcher`, `GatewayRelay`, `GatewayOwnerRoutedFacts`. Uses: auth (`TokenOperations`), bus, history (type), contract, ports, link, admin, simlock-client, `../daemon/dispatch.ts`, and from diff --git a/src/http/AGENTS.md b/src/http/AGENTS.md index c6b43139d..ff96f0a93 100644 --- a/src/http/AGENTS.md +++ b/src/http/AGENTS.md @@ -81,13 +81,13 @@ until `POST /v1/leases/{id}/renew` drains them into `notices`. `lease_lost` clea ## State and timers -| What | Default | Key | -| --------------------------- | -------------------------------- | ------------------------ | -| Listener on/off | off on a worker, on on a gateway | `http.enabled` | -| Address | `127.0.0.1:4700` | `http.host`, `http.port` | -| SSE keepalive | 15 s | fixed, `sse.ts` | -| Long-poll cap | 60 s | fixed, `app.ts` | -| `NO_CAPACITY` `Retry-After` | 5 s | fixed, `errors.ts` | +| What | Default | Key | +| --------------------------- | ----------------------------------------------------- | ------------------------ | +| Listener on/off | off on a worker, on on a gateway | `http.enabled` | +| Address | `127.0.0.1`, port 4701 on a worker, 4700 on a gateway | `http.host`, `http.port` | +| SSE keepalive | 15 s | fixed, `sse.ts` | +| Long-poll cap | 60 s | fixed, `app.ts` | +| `NO_CAPACITY` `Retry-After` | 5 s | fixed, `errors.ts` | - The listener starts right after the socket claim (`onSocketClaimed`), before startup convergence. Early requests park in the dispatcher. On a gateway the worker uplink diff --git a/src/mcp/AGENTS.md b/src/mcp/AGENTS.md index 86cbf0bb2..9dd2a0b2a 100644 --- a/src/mcp/AGENTS.md +++ b/src/mcp/AGENTS.md @@ -1,7 +1,7 @@ # stdio MCP server Does: one agent session over stdin/stdout — its tools, a renew timer, lazy reconnect. -Entry: `main.ts` → `runMcpStdio()`; `simlock mcp` loads it on demand (`src/cli/commands/mcp.ts`). +Entry: `main.ts` → `runMcpStdio({ gateway })`; `simlock mcp` loads it on demand (`src/cli/commands/mcp.ts`). Uses: client, lease-policy, agent-identity, contract, ports. Never imports: core, daemon, drivers, http. Surface: [CLI.md](../../docs/CLI.md#simlock-mcp). @@ -20,7 +20,11 @@ Surface: [CLI.md](../../docs/CLI.md#simlock-mcp). ## How it works 1. **Start** — requester id from `resolveRequesterId(env, "mcp:")`. It is the - principal; no credential, so the session is `agent`. + principal; no credential, so the session is `agent`. `simlock --gateway mcp` runs the + session on the gateway: every connect (a tool call's and a renew's) asks + `resolveDaemonHome` again, so a gateway started mid-session is found, and with none + present the connect throws `GATEWAY_NOT_PRESENT` before it connects, which the tool + reports as `{ code, message }`. 2. **Tools** (`server.ts`), each one call on the typed client: - `lease_simulator` → `lease.request`. Input: the contract's lease fields minus `requesterId`, `fleetRequestId`, `requires`. Progress goes out as diff --git a/src/mcp/main.test.ts b/src/mcp/main.test.ts index 6b27f2cef..f2fd06583 100644 --- a/src/mcp/main.test.ts +++ b/src/mcp/main.test.ts @@ -2,6 +2,9 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { describe, expect, it, vi } from "vitest"; import { buildCliEnvironment } from "../cli/index.js"; @@ -145,6 +148,8 @@ describe("MCP stdio lifecycle", () => { // The connection dies with no tool call in sight, and the renew timer comes due. toolCallClient.emitConnectionLost(); clock.advance(4_115); + // why: the renew connect looks the daemon's folder up on disk first, which takes more than microtasks. + await vi.waitFor(() => expect(connectToRunningDaemon).toHaveBeenCalledTimes(1)); for (let index = 0; index < 10; index += 1) await Promise.resolve(); expect(embedderConnects, "the timer did not reach for the connect it was not given").toBe(1); @@ -155,6 +160,54 @@ describe("MCP stdio lifecycle", () => { await runner.shutdown(); }); + it("renews a --gateway session's lease on the gateway's socket, not the worker's", async () => { + const root = await mkdtemp(join(tmpdir(), "mcp-gw-")); + vi.stubEnv("SIMLOCK_HOME", root); + try { + await mkdir(join(root, "gateway")); + await writeFile(join(root, "gateway", "instance.json"), "{}"); + const clock = new FakeClock(0); + const toolCallClient = new FakeSimlockClient(); + toolCallClient.requestLeaseImpl = () => Promise.resolve(sampleGrant()); + const renewClient = new FakeSimlockClient(); + renewClient.renewLeaseImpl = (input) => + Promise.resolve({ ...sampleGrant().lease, id: input.leaseId }); + renewClient.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); + connectWithAutoLaunch.mockReset().mockResolvedValue(toolCallClient); + connectToRunningDaemon.mockReset().mockResolvedValue(renewClient); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const runner = await startMcpStdio({ + clock, + createTransport: () => serverTransport, + gateway: true, + requesterId: "mcp-test", + signals: new FakeSignals(), + }); + const mcpClient = new Client({ name: "test", version: "1.0.0" }); + await mcpClient.connect(clientTransport); + await mcpClient.request( + { + method: "tools/call", + params: { arguments: { model: "iPhone", platform: "ios" }, name: "lease_simulator" }, + }, + CallToolResultSchema, + ); + + toolCallClient.emitConnectionLost(); + clock.advance(4_115); + await vi.waitFor(() => expect(connectToRunningDaemon).toHaveBeenCalledTimes(1)); + + expect(connectToRunningDaemon.mock.calls[0]?.[0]).toMatchObject({ + socketPath: join(root, "gateway", "daemon.sock"), + }); + await mcpClient.close(); + await runner.shutdown(); + } finally { + vi.unstubAllEnvs(); + await rm(root, { force: true, recursive: true }); + } + }); + it("sources the connection principal from SIMLOCK_AGENT_ID when no requesterId is given explicitly", async () => { connectWithAutoLaunch.mockReset().mockResolvedValue(new FakeSimlockClient()); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -226,7 +279,7 @@ describe("MCP stdio lifecycle", () => { const cli = buildCliEnvironment( { clock: new FakeClock(0), - dataDirectory: "/simlock", + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, filesystem: new MemoryFilesystem(), ipc: new MemoryIpcTransport(), launcher: new FakeDaemonLauncher(), diff --git a/src/mcp/main.ts b/src/mcp/main.ts index 4a3c23fdf..7a38fec90 100644 --- a/src/mcp/main.ts +++ b/src/mcp/main.ts @@ -5,9 +5,12 @@ import { fileURLToPath } from "node:url"; import { resolveRequesterId } from "../agent-identity/index.js"; import type { SimlockClient } from "../client/index.js"; +import { gatewayNotPresentError } from "../contract/index.js"; import { NodeDaemonLauncher, + NodeFilesystem, NodeIpcTransport, + resolveDaemonHome, resolveDaemonSocketPath, resolveSimlockHome, SystemClock, @@ -47,6 +50,7 @@ export interface McpStdioEnvironment { /** Source for `SIMLOCK_AGENT_ID` and the agent tool's session id (`resolveRequesterId`) when * `requesterId` is not given explicitly. */ readonly env?: NodeJS.ProcessEnv; + readonly gateway?: boolean; readonly requesterId?: string; readonly signals?: Signals; /** The stdio transport currently does not surface stdin EOF as onclose. */ @@ -77,7 +81,7 @@ export async function startMcpStdio( // One `Clock` for the whole frontend: the session's renew timer and the auto-launch retry // loop must not be able to disagree about what time it is (architecture rule 9). const clock = environment.clock ?? new SystemClock(); - const defaults = defaultEnvironment(requesterId, clock); + const defaults = defaultEnvironment(requesterId, clock, environment.gateway === true); const session = new McpSession({ clock, connect: environment.connect ?? defaults.connect, @@ -158,45 +162,50 @@ export async function startMcpStdio( function defaultEnvironment( requesterId: string, clock: Clock, + gateway: boolean, ): Required> { - const dataDirectory = resolveSimlockHome(); + const root = resolveSimlockHome(); + const filesystem = new NodeFilesystem(); const ipc = new NodeIpcTransport(); - const logPath = join(dataDirectory, "daemon.log"); + // why: resolved on every connect, so a gateway started after this session began is found, and + // a throw (an over-long `SIMLOCK_HOME`, a missing gateway) is a tool error rather than a dead + // server and a raw stack trace on the stdio channel an MCP client is speaking protocol over. + const daemonHome = async () => { + const home = await resolveDaemonHome({ root, gateway, filesystem }); + if (gateway && !home.gatewayPresent) throw gatewayNotPresentError(); + return home.dataDirectory; + }; return { // The tool-call trigger: auto-launches a daemon that is not running, exactly as the CLI // does. ADR 0004 §2/§4: the session keeps its lease alive with its own `lease.renew` timer // and releases explicitly when the agent goes away (stdin EOF -> session.close()), so it // declares no daemon-initiated heartbeat -- there is none left to declare. - connect: () => - connectWithAutoLaunch({ + connect: async () => { + const dataDirectory = await daemonHome(); + return connectWithAutoLaunch({ clock, ipc, launcher: new NodeDaemonLauncher({ - args: [join(dirname(fileURLToPath(import.meta.url)), "../daemon/main.js")], + args: [ + join(dirname(fileURLToPath(import.meta.url)), "../daemon/main.js"), + ...(gateway ? ["--gateway"] : []), + ], command: process.execPath, - logPath, - simlockHome: dataDirectory, + logPath: join(dataDirectory, "daemon.log"), + simlockHome: root, }), principal: requesterId, - // Resolved inside `connect` rather than during construction for the same reason as - // the CLI's: it throws for an over-long `SIMLOCK_HOME`, and out here that throw - // escaped before the server could report it, leaving a dead server and a raw stack - // trace on the stdio channel an MCP client is trying to speak protocol over. socketPath: resolveDaemonSocketPath(dataDirectory), - }), + }); + }, // The renew timer's trigger: connects to a daemon that is already listening and never // launches one, so an operator's `simlock daemon stop` is not undone by an idle session // (ADR 0004 §2). - connectForRenew: () => + connectForRenew: async () => connectToRunningDaemon({ ipc, principal: requesterId, - // Resolved here rather than hoisted into a shared `const`, for the same reason - // `connect` resolves it inline above: `resolveDaemonSocketPath` throws for an over-long - // `SIMLOCK_HOME`, and a throw during construction escapes before the server can report - // it -- leaving a dead server and a raw stack trace on the stdio channel an MCP client - // is trying to speak protocol over. - socketPath: resolveDaemonSocketPath(dataDirectory), + socketPath: resolveDaemonSocketPath(await daemonHome()), }), createTransport: () => new StdioServerTransport(), }; diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index ce3208725..1ff356fc4 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -7,30 +7,30 @@ Uses: nothing from other components. Imported by: every component that touches t ## Ports -| Port | File | Node adapter | Fake | What it covers | -| ------------------------------------------ | --------------------------- | ------------------------------------------------------------ | ------------------------------------------ | ------------------------------------------------------------- | -| `Clock` | `clock.ts` | `SystemClock` | `FakeClock` | `now`, `setTimer`, `cancel` | -| `Filesystem` | `filesystem.ts` | `NodeFilesystem` | `MemoryFilesystem` | Read, atomic write, stat, delete, disk free | -| `ProcessRunner` | `process-runner.ts` | `NodeProcessRunner` | `ScriptedProcessRunner` | Run or stream a command, capture output | -| (wrapper) | `logging-process-runner.ts` | `LoggingProcessRunner` | — | One `process` log line per command, at `debug` only | -| `ProcessSupervisor` | `process-supervisor.ts` | `NodeProcessSupervisor` | `FakeProcessSupervisor` | Is a pid alive; signal it | -| `ParentWatch` | `parent-watch.ts` | `NodeParentWatch` | `FakeParentWatch` | Call once when a pid exits (polls) | -| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log, `DAEMON_STARTUP_TIMEOUT_MS` | -| `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket | -| `UplinkConnector`, `UplinkListenerFactory` | `uplink.ts` | `WebSocketUplinkConnector`, `WebSocketUplinkListenerFactory` | `MemoryUplinkTransport` | A worker's uplink to its gateway | -| `Logger`, `LogSink` | `logger.ts` | `JsonLinesLogger`, `NodeFileLogSink` | `NoopLogger`, `MemoryLogSink` | JSON-line logs, `child(module)`, rotation | -| `SystemStats` | `system-stats.ts` | `NodeSystemStats` | `FakeSystemStats` | CPU count, total RAM | -| `HostInfo` | `host-info.ts` | `NodeHostInfo` | `FakeHostInfo` | OS, version (`sw_vers` on macOS), arch | -| `HostLoadProbe` | `host-load.ts` | `DarwinHostLoadProbe`, `LinuxHostLoadProbe` | `FakeHostLoadProbe` | CPU, memory, disk counters | -| `TcpProbe` | `tcp-probe.ts` | `NodeTcpProbe` | `FakeTcpProbe` | Is a loopback port listening; send bytes | -| `TcpStreamConnector` | `tcp-stream.ts` | `NodeTcpStreamConnector` | `FakeTcpStreamConnector` | A long-lived loopback connection, bytes both ways | -| `BytePipeLauncher` | `byte-pipe.ts` | `NodeBytePipeLauncher` | `FakeBytePipeLauncher` | A child with binary stdout and stdin as its liveness | -| `KeySetFetcher` | `key-set-fetcher.ts` | `NodeKeySetFetcher` | `FakeKeySetFetcher` | One GET of a key-set URL: no redirects, body capped at 64 KiB | -| `SqliteOpener` | `sqlite.ts` | `NodeSqliteOpener` | none; tests use the adapter on a temp file | Open a SQLite file; `exec`, `prepare`, `close` | +| Port | File | Node adapter | Fake | What it covers | +| ------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------ | --------------------------------------------------------------------------------------------------- | +| `Clock` | `clock.ts` | `SystemClock` | `FakeClock` | `now`, `setTimer`, `cancel` | +| `Filesystem` | `filesystem.ts` | `NodeFilesystem` | `MemoryFilesystem` | Read, atomic write, stat, delete, disk free | +| `ProcessRunner` | `process-runner.ts` | `NodeProcessRunner` | `ScriptedProcessRunner` | Run or stream a command, capture output | +| (wrapper) | `logging-process-runner.ts` | `LoggingProcessRunner` | — | One `process` log line per command, at `debug` only | +| `ProcessSupervisor` | `process-supervisor.ts` | `NodeProcessSupervisor` | `FakeProcessSupervisor` | Is a pid alive; signal it | +| `ParentWatch` | `parent-watch.ts` | `NodeParentWatch` | `FakeParentWatch` | Call once when a pid exits (polls) | +| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log, `DAEMON_STARTUP_TIMEOUT_MS` | +| `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket | +| `UplinkConnector`, `UplinkListenerFactory` | `uplink.ts` | `WebSocketUplinkConnector`, `WebSocketUplinkListenerFactory` | `MemoryUplinkTransport` | A worker's uplink to its gateway | +| `Logger`, `LogSink` | `logger.ts` | `JsonLinesLogger`, `NodeFileLogSink` | `NoopLogger`, `MemoryLogSink` | JSON-line logs, `child(module)`, rotation | +| `SystemStats` | `system-stats.ts` | `NodeSystemStats` | `FakeSystemStats` | CPU count, total RAM | +| `HostInfo` | `host-info.ts` | `NodeHostInfo` | `FakeHostInfo` | OS, version (`sw_vers` on macOS), arch | +| `HostLoadProbe` | `host-load.ts` | `DarwinHostLoadProbe`, `LinuxHostLoadProbe` | `FakeHostLoadProbe` | CPU, memory, disk counters | +| `TcpProbe` | `tcp-probe.ts` | `NodeTcpProbe` | `FakeTcpProbe` | Is a loopback port listening; send bytes | +| `TcpStreamConnector` | `tcp-stream.ts` | `NodeTcpStreamConnector` | `FakeTcpStreamConnector` | A long-lived loopback connection, bytes both ways | +| `BytePipeLauncher` | `byte-pipe.ts` | `NodeBytePipeLauncher` | `FakeBytePipeLauncher` | A child with binary stdout and stdin as its liveness | +| `KeySetFetcher` | `key-set-fetcher.ts` | `NodeKeySetFetcher` | `FakeKeySetFetcher` | One GET of a key-set URL: no redirects, body capped at 64 KiB | +| `SqliteOpener` | `sqlite.ts` | `NodeSqliteOpener` | none; tests use the adapter on a temp file | Open a SQLite file; `exec`, `prepare`, `close` | | `WebhookPoster` | `webhook-poster.ts` | `FetchWebhookPoster` | `FakeWebhookPoster` (`testing.ts`) | POST to an operator-named URL; a redirect is not followed | -| `IdGenerator` | `id-generator.ts` | `CryptoIdGenerator` | none; tests inline one | Random ids | -| `TokenSecrets` | `token-secrets.ts` | `CryptoTokenSecrets` | none; tests inline one | New secret, its hash | -| Paths | `paths.ts` | `resolveSimlockHome`, `resolveDaemonSocketPath` | — | `SIMLOCK_HOME` (default `~/.simlock`), socket path length | +| `IdGenerator` | `id-generator.ts` | `CryptoIdGenerator` | none; tests inline one | Random ids | +| `TokenSecrets` | `token-secrets.ts` | `CryptoTokenSecrets` | none; tests inline one | New secret, its hash | +| Paths | `paths.ts` | `resolveSimlockHome`, `daemonDataDirectory`, `resolveDaemonHome`, `resolveDaemonSocketPath` | — | `SIMLOCK_HOME` (test root; default `~/.simlock`), a gateway in `/gateway`, socket path length | `productionHostLoadProbe` picks the Darwin or Linux probe. `NodeFileLogSink` rotates to `.1` and keeps that one generation; the files it opens, and the log `NodeDaemonLauncher` diff --git a/src/ports/index.ts b/src/ports/index.ts index 27e3c0fcf..a1901dda6 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -6,7 +6,14 @@ export { } from "./filesystem.js"; export type { PathDetails } from "./filesystem.js"; export { readPackageVersion } from "./package-version.js"; -export { resolveDaemonSocketPath, resolveSimlockHome, SocketPathTooLongError } from "./paths.js"; +export { + daemonDataDirectory, + type DaemonHome, + resolveDaemonHome, + resolveDaemonSocketPath, + resolveSimlockHome, + SocketPathTooLongError, +} from "./paths.js"; export { DAEMON_STARTUP_TIMEOUT_MS, type DaemonLauncher, diff --git a/src/ports/ipc.test.ts b/src/ports/ipc.test.ts index 935a96195..85079399d 100644 --- a/src/ports/ipc.test.ts +++ b/src/ports/ipc.test.ts @@ -45,6 +45,27 @@ describe.each(implementations)("IpcTransport contract: $name", ({ create }) => { } }); + it("closes a connection whose data was never read, even after the client wrote to it", async () => { + const ipc = create(); + let server: Awaited> | undefined; + const listener = await ipc.listen(endpoint, (connection) => { + server = connection; + }); + const client = await ipc.connect(endpoint); + client.onData(() => undefined); + await client.write("unread\n"); + await expect.poll(() => server).toBeDefined(); + + await Promise.race([ + server?.close(), + new Promise((_, reject) => setTimeout(() => reject(new Error("close hung")), 2000)), + ]); + await Promise.race([ + listener.close(), + new Promise((_, reject) => setTimeout(() => reject(new Error("listener close hung")), 2000)), + ]); + }); + it("reports an endpoint nothing listens on as endpoint-not-found", async () => { await expect(create().connect(endpoint)).rejects.toMatchObject({ code: "endpoint-not-found", diff --git a/src/ports/ipc.ts b/src/ports/ipc.ts index cfc73074f..79de034ca 100644 --- a/src/ports/ipc.ts +++ b/src/ports/ipc.ts @@ -128,6 +128,8 @@ class NodeIpcConnection implements IpcConnection { if (this.closed) return Promise.resolve(); return new Promise((resolve) => { this.socket.once("close", resolve); + // why: a connection nobody read from is paused, so it never sees the peer's end and never closes -- which would hang its listener's close. + this.socket.resume(); this.socket.end(); }); } diff --git a/src/ports/paths.test.ts b/src/ports/paths.test.ts index e03039e68..314d08d6c 100644 --- a/src/ports/paths.test.ts +++ b/src/ports/paths.test.ts @@ -2,7 +2,14 @@ import { homedir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { resolveDaemonSocketPath, resolveSimlockHome, SocketPathTooLongError } from "./paths.js"; +import { MemoryFilesystem } from "./filesystem.js"; +import { + daemonDataDirectory, + resolveDaemonHome, + resolveDaemonSocketPath, + resolveSimlockHome, + SocketPathTooLongError, +} from "./paths.js"; describe("resolveDaemonSocketPath", () => { it("places the socket under the data directory", () => { @@ -77,3 +84,65 @@ describe("resolveSimlockHome", () => { ); }); }); + +describe("daemonDataDirectory", () => { + it("puts the gateway in /gateway and the worker in ", () => { + expect(daemonDataDirectory("/home/me/.simlock", "gateway")).toBe("/home/me/.simlock/gateway"); + expect(daemonDataDirectory("/home/me/.simlock", "worker")).toBe("/home/me/.simlock"); + }); +}); + +describe("resolveDaemonHome", () => { + const root = "/home/me/.simlock"; + + it.each([ + [true, "gateway", `${root}/gateway`], + [false, "worker", root], + ] as const)( + "sends the gateway flag to /gateway and everything else to (flag %s)", + async (gateway, role, dataDirectory) => { + const home = await resolveDaemonHome({ root, gateway, filesystem: new MemoryFilesystem() }); + + expect(home).toMatchObject({ role, dataDirectory }); + }, + ); + + async function present(files: readonly string[], extraDirectories: readonly string[] = []) { + const filesystem = new MemoryFilesystem(); + for (const directory of extraDirectories) await filesystem.mkdirp(directory); + for (const file of files) { + await filesystem.mkdirp(join(file, "..")); + await filesystem.writeFileAtomic(file, "{}"); + } + return (await resolveDaemonHome({ root, gateway: true, filesystem })).gatewayPresent; + } + + it.each([ + ["neither file", [], false], + ["instance.json only", [`${root}/gateway/instance.json`], true], + ["config.json only", [`${root}/gateway/config.json`], true], + ["both files", [`${root}/gateway/instance.json`, `${root}/gateway/config.json`], true], + ] as const)( + "reports a gateway present when gateway/instance.json or gateway/config.json exists (%s)", + async (_name, files, expected) => { + expect(await present(files)).toBe(expected); + }, + ); + + it("does not report a gateway present for an empty gateway folder", async () => { + expect(await present([], [`${root}/gateway`])).toBe(false); + }); + + it("counts a path under a file (ENOTDIR) as absent and rethrows any other exists error", async () => { + const failing = (code: string) => ({ + exists: () => Promise.reject(Object.assign(new Error(code), { code })), + }); + + await expect( + resolveDaemonHome({ root, gateway: true, filesystem: failing("ENOTDIR") }), + ).resolves.toMatchObject({ gatewayPresent: false }); + await expect( + resolveDaemonHome({ root, gateway: true, filesystem: failing("EACCES") }), + ).rejects.toThrow("EACCES"); + }); +}); diff --git a/src/ports/paths.ts b/src/ports/paths.ts index 97b08f51b..5bd1fb27f 100644 --- a/src/ports/paths.ts +++ b/src/ports/paths.ts @@ -1,6 +1,8 @@ import { homedir } from "node:os"; import { join, resolve } from "node:path"; +import type { Filesystem } from "./filesystem.js"; + /** * Resolves simlock's data directory (config.json, state.json, daemon.sock, daemon.log, * and the device roots under `devices/`). `SIMLOCK_HOME` overrides the default @@ -59,3 +61,53 @@ export function resolveDaemonSocketPath( } return socketPath; } + +export type DaemonRole = "worker" | "gateway"; + +export interface DaemonHome { + readonly role: DaemonRole; + readonly dataDirectory: string; + readonly gatewayPresent: boolean; +} + +export function daemonDataDirectory(root: string, role: DaemonRole): string { + return role === "gateway" ? join(root, "gateway") : root; +} + +/** why: `exists` treats only a missing path as absent; a root whose `gateway` is a file is just as absent. */ +async function existsOrAbsent( + filesystem: Pick, + path: string, +): Promise { + try { + return await filesystem.exists(path); + } catch (error: unknown) { + if ( + typeof error === "object" && + error !== null && + "code" in error && + error.code === "ENOTDIR" + ) { + return false; + } + throw error; + } +} + +// why: the one place the folder choice lives (ADR 0034); the daemon never calls it, it derives its folder from its role. +export async function resolveDaemonHome({ + filesystem, + gateway, + root, +}: { + readonly root: string; + readonly gateway: boolean; + readonly filesystem: Pick; +}): Promise { + const role: DaemonRole = gateway ? "gateway" : "worker"; + const gatewayFolder = daemonDataDirectory(root, "gateway"); + const gatewayPresent = + (await existsOrAbsent(filesystem, join(gatewayFolder, "instance.json"))) || + (await existsOrAbsent(filesystem, join(gatewayFolder, "config.json"))); + return { role, dataDirectory: daemonDataDirectory(root, role), gatewayPresent }; +} diff --git a/ui/vite.config.ts b/ui/vite.config.ts index 1dc718978..7c0dc0017 100644 --- a/ui/vite.config.ts +++ b/ui/vite.config.ts @@ -17,7 +17,7 @@ export default defineConfig({ modulePreload: { polyfill: false }, }, server: { - // Development only: a local daemon with `http.enabled` answers `/v1` on its default port. - proxy: { "/v1": "http://127.0.0.1:4700" }, + // why: development only; a local worker with `http.enabled` answers `/v1` on its default port, 4701. + proxy: { "/v1": "http://127.0.0.1:4701" }, }, });