From 25157609a18c94183a4c45c346709523f34a488b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 9 Sep 2026 13:21:25 -0500 Subject: [PATCH] docs: split end-user docs from maintainer/agent docs Move ARCHITECTURE.md, IDEAS.md, known-pitfalls.md, adr/, and agent-rules/ into docs/internal/ so docs/ holds only what an end user of the built tool needs. Strip ADR citations and internal-doc links out of the remaining end-user docs (ABOUT.md, CLI.md, CLIENT.md, CONFIGURATION.md, HTTP-API.md) and out of the CLI's own --help banner, which pointed at a repo-relative file path that doesn't exist for anyone who installed from a registry. Split EVENTS.md into an end-user catalog (docs/EVENTS.md) and a maintainer copy with the ADR/rationale context (docs/internal/EVENTS.md); while doing that, fix a pre-existing duplicated "Fleet (gateway mode)" section and correct worker.rejected's documented emitter to WorkerRegistry. Add docs/internal/agent-rules/documentation.md codifying the split so future changes land docs in the right place. --- AGENTS.md | 41 ++-- README.md | 8 +- docs/ABOUT.md | 12 +- docs/CLI.md | 53 +++-- docs/CLIENT.md | 37 ++-- docs/CONFIGURATION.md | 21 +- docs/EVENTS.md | 192 ++++++------------ docs/HTTP-API.md | 41 ++-- docs/{ => internal}/ARCHITECTURE.md | 10 +- docs/internal/EVENTS.md | 189 +++++++++++++++++ docs/{ => internal}/IDEAS.md | 4 +- .../KNOWN-PITFALLS.md} | 18 +- .../adr/0001-simlock-owned-device-roots.md | 0 .../adr/0002-opt-in-slim-ios-simulators.md | 2 +- ...d-daemon-contract-behind-every-frontend.md | 0 ...004-ttl-first-leases-on-every-transport.md | 4 +- .../adr/0005-gateway-and-worker-modes.md | 6 +- docs/{ => internal}/adr/README.md | 0 .../agent-rules/architecture.md | 0 docs/internal/agent-rules/documentation.md | 50 +++++ docs/{ => internal}/agent-rules/events.md | 0 docs/{ => internal}/agent-rules/safety.md | 0 docs/{ => internal}/agent-rules/testing.md | 0 docs/loop.md | 8 +- e2e/README.md | 2 +- e2e/contract-surface.test.ts | 2 +- e2e/gateway-fleet.test.ts | 2 +- e2e/mcp-session.test.ts | 2 +- e2e/slow-ios-slim.test.ts | 6 +- src/bus/index.ts | 2 +- src/cli/index.test.ts | 2 +- src/cli/index.ts | 6 +- src/client/index.ts | 2 +- src/contract/schemas.ts | 2 +- src/core/device-root.ts | 2 +- src/core/driver.ts | 8 +- src/core/warm-pool-coordinator.ts | 2 +- src/daemon/dispatcher.test.ts | 4 +- src/daemon/dispatcher.ts | 2 +- src/daemon/main.test.ts | 2 +- src/daemon/main.ts | 2 +- src/daemon/server.test.ts | 4 +- src/daemon/server.ts | 2 +- src/drivers/android/adb-server.ts | 2 +- src/drivers/android/index.ts | 2 +- src/gateway/fleet-coordinator.test.ts | 4 +- src/gateway/fleet-coordinator.ts | 4 +- src/gateway/service.test.ts | 2 +- src/gateway/service.ts | 2 +- src/gateway/worker-link.ts | 4 +- src/gateway/worker-registry.ts | 2 +- src/http/app.ts | 2 +- src/http/errors.ts | 4 +- src/ports/parent-watch.ts | 2 +- 54 files changed, 470 insertions(+), 312 deletions(-) rename docs/{ => internal}/ARCHITECTURE.md (99%) create mode 100644 docs/internal/EVENTS.md rename docs/{ => internal}/IDEAS.md (98%) rename docs/{known-pitfalls.md => internal/KNOWN-PITFALLS.md} (98%) rename docs/{ => internal}/adr/0001-simlock-owned-device-roots.md (100%) rename docs/{ => internal}/adr/0002-opt-in-slim-ios-simulators.md (99%) rename docs/{ => internal}/adr/0003-one-typed-daemon-contract-behind-every-frontend.md (100%) rename docs/{ => internal}/adr/0004-ttl-first-leases-on-every-transport.md (98%) rename docs/{ => internal}/adr/0005-gateway-and-worker-modes.md (99%) rename docs/{ => internal}/adr/README.md (100%) rename docs/{ => internal}/agent-rules/architecture.md (100%) create mode 100644 docs/internal/agent-rules/documentation.md rename docs/{ => internal}/agent-rules/events.md (100%) rename docs/{ => internal}/agent-rules/safety.md (100%) rename docs/{ => internal}/agent-rules/testing.md (100%) diff --git a/AGENTS.md b/AGENTS.md index 38a39c433..5a66de764 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,36 +5,51 @@ parallel coding agents lease devices without fighting over them. ## Rules — read before writing code -The rules in [docs/agent-rules/](docs/agent-rules/) are binding for all +The rules in [docs/internal/agent-rules/](docs/internal/agent-rules/) are binding for all changes in this repo: -- [architecture.md](docs/agent-rules/architecture.md) — loosely coupled +- [architecture.md](docs/internal/agent-rules/architecture.md) — loosely coupled modules; platform-agnostic core; iOS and Android encapsulated in their own driver modules; event bus for observers only; one place enforces a rule; bounded cross-process waits; every exit leaves one named state. -- [events.md](docs/agent-rules/events.md) — event naming +- [events.md](docs/internal/agent-rules/events.md) — event naming (`subject.past-tense-fact`), post-commit emission, payload contracts, keeping EVENTS.md in sync. -- [safety.md](docs/agent-rules/safety.md) — registry-only destruction, never +- [safety.md](docs/internal/agent-rules/safety.md) — registry-only destruction, never touch leased devices, no implicit downloads, ownership proven not inferred, root validation fails closed, wire input is a claim not a fact. -- [testing.md](docs/agent-rules/testing.md) — a test's title is a claim its +- [testing.md](docs/internal/agent-rules/testing.md) — a test's title is a claim its body must prove; every test must be able to fail for the right reason; untested code is code you can delete with a green suite. +- [documentation.md](docs/internal/agent-rules/documentation.md) — end-user + docs (`docs/`) vs. maintainer/agent docs (`docs/internal/`); no ADR links + or internal-doc links from end-user docs; nothing the tool prints names a + file path in this repo. -So are the accepted records in [docs/adr/](docs/adr/). An ADR marked +So are the accepted records in [docs/internal/adr/](docs/internal/adr/). An ADR marked _Accepted — not yet implemented_ means the documentation already describes the decided end state while the code has not caught up: treat the docs as the specification, and do not "fix" them back to match current behaviour. ## Documentation -Useful documentation lives in [docs/](docs/): +[docs/internal/agent-rules/documentation.md](docs/internal/agent-rules/documentation.md) +governs the split below — read it before adding or editing any doc. + +End-user docs live directly under [docs/](docs/) and must stay self-contained +(no ADR links, no links into `docs/internal/`): - [ABOUT.md](docs/ABOUT.md) — what the tool is and the problem it solves -- [ARCHITECTURE.md](docs/ARCHITECTURE.md) — high-level architecture overview -- [CLI.md](docs/CLI.md) — the expected CLI command surface (user manual) -- [EVENTS.md](docs/EVENTS.md) — catalog of business events -- [IDEAS.md](docs/IDEAS.md) — post-v1 ideas; don't implement these unless asked -- [known-pitfalls.md](docs/known-pitfalls.md) — accepted gaps and their planned fixes -- [adr/](docs/adr/) — architecture decision records and their status +- [CLI.md](docs/CLI.md) — the CLI command surface (user manual) +- [CLIENT.md](docs/CLIENT.md) — the programmatic client (`simlock/client`, `simlock/admin`) +- [CONFIGURATION.md](docs/CONFIGURATION.md) — every config key, its default, and how limits interact +- [HTTP-API.md](docs/HTTP-API.md) — the network-facing HTTP API +- [EVENTS.md](docs/EVENTS.md) — catalog of business events, end-user cut + +Maintainer/agent docs live under [docs/internal/](docs/internal/): + +- [ARCHITECTURE.md](docs/internal/ARCHITECTURE.md) — high-level architecture overview +- [EVENTS.md](docs/internal/EVENTS.md) — the same catalog with rationale and ADR references +- [IDEAS.md](docs/internal/IDEAS.md) — post-v1 ideas; don't implement these unless asked +- [KNOWN-PITFALLS.md](docs/internal/KNOWN-PITFALLS.md) — accepted gaps and their planned fixes +- [adr/](docs/internal/adr/) — architecture decision records and their status diff --git a/README.md b/README.md index 4454c7888..944b5639a 100644 --- a/README.md +++ b/README.md @@ -34,8 +34,7 @@ vanish. **One machine is a starting point, not a limit.** A simlock daemon runs either as a **worker** — what every daemon is today, owning the devices on its own machine — or as a **gateway**, which owns no devices and fronts the -workers that have joined it ([ADR -0005](docs/adr/0005-gateway-and-worker-modes.md)). Workers dial _out_ to the +workers that have joined it. Workers dial _out_ to the gateway over a single WebSocket uplink, so a Mac behind NAT joins a fleet with a URL and a join token and never needs an inbound port; the gateway keeps one fleet-wide queue and sends each request to the worker best placed @@ -204,12 +203,11 @@ lease-loss notifications are documented in ## Documentation - [docs/ABOUT.md](docs/ABOUT.md) — what the tool is and the problem it solves, in short form -- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — how the daemon, drivers, and frontends fit together - [docs/CLI.md](docs/CLI.md) — the full command reference +- [docs/CLIENT.md](docs/CLIENT.md) — the programmatic client (`simlock/client`, `simlock/admin`) - [docs/CONFIGURATION.md](docs/CONFIGURATION.md) — every config key, its default, and how limits interact +- [docs/HTTP-API.md](docs/HTTP-API.md) — the network-facing HTTP API - [docs/EVENTS.md](docs/EVENTS.md) — catalog of business events on `simlock events` -- [docs/known-pitfalls.md](docs/known-pitfalls.md) — accepted gaps and their planned fixes -- [docs/IDEAS.md](docs/IDEAS.md) — post-v1 ideas, not yet built ## Made with ❤️ at Callstack diff --git a/docs/ABOUT.md b/docs/ABOUT.md index 28240345e..56efaa382 100644 --- a/docs/ABOUT.md +++ b/docs/ABOUT.md @@ -37,8 +37,7 @@ programmatic client the CLI and MCP frontends are themselves built on (see One machine's worth of devices runs out eventually, and a team with several Macs should not have to hand each agent a specific one. So a simlock daemon -runs in one of two modes ([ADR -0005](adr/0005-gateway-and-worker-modes.md)). A **worker** is what every +runs in one of two modes. A **worker** is what every daemon is today — it owns the devices on its machine — and joining a fleet costs it two config keys pointing at a gateway; it keeps serving its own local agents exactly as before. A **gateway** owns no devices at all: workers @@ -73,9 +72,6 @@ registry, and every safety invariant stay on the worker. progress (e.g. provisioning ETAs) streams as JSON lines on stderr. The optional MCP server reserves stdout for MCP JSON-RPC. -See [ARCHITECTURE.md](ARCHITECTURE.md) for how it's built (and -[its gateway section](ARCHITECTURE.md#gateway-and-worker-modes-adr-0005) for -how a fleet fits together), [CLI.md](CLI.md) for the command surface, -[CLIENT.md](CLIENT.md) for the programmatic client, -[HTTP-API.md](HTTP-API.md) for the network API, and -[known-pitfalls.md](known-pitfalls.md) for accepted gaps. +See [CLI.md](CLI.md) for the command surface, +[CLIENT.md](CLIENT.md) for the programmatic client, and +[HTTP-API.md](HTTP-API.md) for the network API. diff --git a/docs/CLI.md b/docs/CLI.md index 67c2d7078..f091c4d54 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -62,9 +62,9 @@ surfaced by `lease renew`) falls back to exit 1; the structured stderr line still reports the specific code — a renew by a running `simlock lease` is the exception, and exits `14`. -The five ADR 0005 codes are placed on existing numbers rather than new ones, -and the numbers are fixed by the contract's error table in the PRs that -implement them ([ADR 0005](adr/0005-gateway-and-worker-modes.md)): +The five gateway-mode codes are placed on existing numbers rather than new +ones, and the numbers are fixed by the contract's error table in the PRs that +implement them: - `WORKER_UNREACHABLE` is `kind: "transport"`, the fleet's version of `DAEMON_CONNECTION_LOST`: the thing you were talking to went away. Both @@ -75,8 +75,7 @@ implement them ([ADR 0005](adr/0005-gateway-and-worker-modes.md)): fix is a different command, or the same command against a different daemon. `UNSUPPORTED_IN_GATEWAY_MODE` in particular is permanent, not provisional: `nuke`, `cleanup`, `doctor`, and `driver.passthrough` stay per-worker - operations rather than waiting on some later fleet-wide version (ADR 0005 - §34). + operations rather than waiting on some later fleet-wide version. - `UNKNOWN_WORKER` takes `12`, the number the table already gives to "the thing you named cannot be resolved" (`UNKNOWN_MODEL`, `NO_DRIVER`), because that is what it is: a worker id the gateway has no record of. @@ -127,8 +126,7 @@ simlock lease --platform --device [--os ] [--bind-pid ] ``` -There is only one kind of lease ([ADR -0004](adr/0004-ttl-first-leases-on-every-transport.md)): every lease has a +There is only one kind of lease: every lease has a TTL and lives until it expires, is renewed, or is released. `--detach` changes what *this process* does after the grant, not what the daemon granted. @@ -170,8 +168,7 @@ granted. `component.install-started` / `component.installed` / `component.install-failed` on the event bus (`simlock events --follow`); see [EVENTS.md](EVENTS.md#components). The requester's own progress stream - (below) does not yet reflect an in-flight download — see - [known-pitfalls.md](known-pitfalls.md). + (below) does not yet reflect an in-flight download. - `--full` — opt this lease out of iOS slim mode (see [CONFIGURATION.md](CONFIGURATION.md) for what slim mode disables). Only meaningful when `ios.slim.enabled` is on; ignored otherwise, and ignored @@ -200,7 +197,7 @@ error message names the existing lease id to release first. agent. As soon as the device is ready, one JSON line is printed on stdout — the contract's `lease.request` output (`LeaseGrant`: `device`, `lease`, `timing`) serialized as-is, plus the one field the CLI adds on top, the connection's -resolved `role` (ADR 0003 §5): +resolved `role`: The fields you usually care about, from that same line: @@ -245,11 +242,10 @@ run it: that lease is not released, and its device stays leased until `ttlDeadline` — at most the lease's own TTL after its last renew: `lease.defaultTtlMs` unless the request asked for more, never more than `lease.maxTtlMs`. If that matters, lower `lease.defaultTtlMs` or pass a -shorter `--ttl`; see -[known-pitfalls.md](known-pitfalls.md#a-sigkilled-lease-holder-keeps-its-device-until-the-ttl-expires). +shorter `--ttl`. **If the connection dies, the lease outlives it but this process does not.** -The CLI never reconnects (ADR 0003 §10), so a daemon that stops, crashes, or +The CLI never reconnects, so a daemon that stops, crashes, or has its socket killed leaves the holder unable to renew or release. It writes one error line naming the lease and its deadline, and exits `1`: @@ -294,7 +290,7 @@ reclaiming work is reported separately: ``` `push` is the one field the CLI adds to identify the line's kind; everything -else is the contract's `LeaseProgress` push, serialized as-is (ADR 0003 §11). +else is the contract's `LeaseProgress` push, serialized as-is. `reclaiming` follows `queued` when the device the request is waiting on is being purged for its previous holder: the position alone would not say that @@ -333,8 +329,8 @@ a signal, and it does not try to release a lease the daemon has already taken back. `lease-lost` is a push from a live daemon connection — a connection that simply died is exit `1` and a `DAEMON_CONNECTION_LOST` line instead, and leaves the lease standing. The `reason` is whatever ended it — `device-lost` -here, but equally `expired` or `killed`. See [known-pitfalls.md](known-pitfalls.md) -for what a reboot cannot bring back — anything the agent had running inside +here, but equally `expired` or `killed`. A reboot cannot bring back +anything the agent had running inside the device (a launched app, `log stream`, an Appium/XCUITest session, a port forward) is gone whether or not recovery succeeds. @@ -448,7 +444,7 @@ there instead — see [Against a gateway](#against-a-gateway). The refusals above are unchanged, and where they are enforced does not change either: **the daemon refuses, the CLI reports.** The CLI holds no copy of the refusal list in either direction — frontends render the contract, and the list lives -with the driver that owns the device (ADR 0003 §11). Locally that means +with the driver that owns the device. Locally that means `driver.passthrough` refuses and the CLI relabels the answer as `USAGE` (exit 2); through a gateway it sends `device.exec` and the worker refuses with `PASSTHROUGH_REFUSED`, or `UNKNOWN_PASSTHROUGH_TOOL` for a tool it does @@ -491,7 +487,7 @@ ones known to be dangerous: the attached forms `-t123`, and including one that follows another global's value, e.g. `-s emulator-5554 -t 1 shell …`) are let through — they select a device inside the containment Simlock already established - rather than escaping it (see [known-pitfalls.md](known-pitfalls.md)). + rather than escaping it. `--version` and `--help` are also let through, since adb answers those on its own before it ever looks for a subcommand. - Everything else positioned there is refused, whether or not it is a flag @@ -536,7 +532,7 @@ startup to recover. ## Against a gateway A **gateway** is a simlock daemon that owns no devices and fronts the workers -that joined it ([ADR 0005](adr/0005-gateway-and-worker-modes.md); see +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 @@ -574,7 +570,7 @@ with no gateway-side state to lose), but it is **opaque** — do not parse it. **`lease renew`, `release`, and lease reads are forwarded** to the worker that owns the lease, and the `ttlDeadline` you see is that worker's own. -Leases are TTL-first on every transport (ADR 0004), so a gateway emulates +Leases are TTL-first on every transport, so a gateway emulates nothing: a `simlock lease` left running renews on its timer as always, and a client that stops renewing loses the lease on the worker's clock whether or not a gateway is in the path. @@ -667,7 +663,7 @@ reaches the same operation as `POST /v1/leases/{id}/exec`; see Files do not travel with the command: `simctl install ` and `adb install ` resolve their path on the **worker's** filesystem, so the artifact has to be there already (a shared volume, a CI checkout on that -machine). See [known-pitfalls.md](known-pitfalls.md). +machine). **Three commands refuse outright**, with `UNSUPPORTED_IN_GATEWAY_MODE` (exit 2): `simlock nuke`, `simlock cleanup`, and `simlock doctor`. Each acts on one @@ -726,7 +722,7 @@ simlock worker remove `downloads.policy` is that worker's own effective policy, read once with `config.get` when its uplink connects — routing needs it to know whether a machine may install a missing runtime before sending it a request that needs -one. `protocol` is the range that worker negotiated; ADR 0005 moves the wire +one. `protocol` is the range that worker negotiated; the wire moves to `{min: 5, max: 5}` with no shim, so a worker older than it does not overlap and shows as `incompatible`. Worker ids are UUIDs — the examples here abbreviate them to their first segment. @@ -874,7 +870,7 @@ renewed), and queue depth. `--json` for the structured equivalent. `overLimit` is true when a lowered limit cannot yet be met, for example because active leases consume all running slots. -Against a **gateway** (`config.mode: "gateway"`, ADR 0005) the same command +Against a **gateway** (`config.mode: "gateway"`) 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, one line per worker precedes the devices, and every device and lease names the worker it @@ -958,7 +954,7 @@ after an upgrade. Before the first device of a purge is destroyed, each root the purge is about to reach into is re-validated — ownership is proven at startup and then trusted for the life of the daemon, which is fine for reporting and not fine for -destroying (see [known-pitfalls.md](known-pitfalls.md)). A root that no longer +destroying. A root that no longer proves ownership abandons the whole purge and leaves every finding standing. So does a device that could not be destroyed: it stays reported, and the rest of the run continues. @@ -1031,7 +1027,7 @@ connected are not backfilled. 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 (ADR 0005) — and +`config.mode` selects — a worker (the default) or a gateway — and `status` reports it, both in the human line (`Daemon: running (gateway)`) and as `daemon.mode` under `--json`. `stop` does not touch leases: they persist, and the next daemon restores each one's TTL timer from its deadline. What a @@ -1070,7 +1066,7 @@ shows the current file with the immediately preceding one prepended. ## `simlock worker ` -The operator's view of a fleet (ADR 0005). Every subcommand is an admin +The operator's view of a fleet. Every subcommand is an admin operation **on a gateway**; against a worker they answer `UNKNOWN_REQUEST` (exit 2), because a worker has no worker registry to answer from. @@ -1177,7 +1173,7 @@ Three roles: - `operator` — everything an agent can do, plus the admin-only routes; also accepted as the admin credential at `hello` (see [admin credential resolution](#admin-credential-resolution)). -- `worker` — a **join token** (ADR 0005): minted on a *gateway* and put in a +- `worker` — a **join token**: minted on a *gateway* and put in a worker's `gateway.token`. It authorizes exactly one thing, opening an uplink at `GET /v1/uplink`, and is `403` on every other `/v1` route; conversely an `agent` or `operator` token is `403` at `/v1/uplink`. Revoking one closes the @@ -1203,8 +1199,7 @@ the secret and its hash. `revoke ` prints `{"revoked":true}` or ### The `worker` role: join tokens `--role worker` mints a **join token**: the credential a worker presents when -it opens its uplink to a gateway ([ADR -0005](adr/0005-gateway-and-worker-modes.md)). Mint it **on the gateway**, +it opens its uplink to a gateway. Mint it **on the gateway**, then put the secret in that worker's `gateway.token` beside its `gateway.url`. It is the narrowest role there is — a `worker` token can open an uplink and nothing else, and presenting one on any `/v1` route other than diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 7d5af1c8d..adcf4f90a 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -19,7 +19,7 @@ agent-role method plus the admin-role ones (`list`, `runCleanup`, `runNuke`, `createToken`/`listTokens`/`revokeToken`). The split exists so `simlock/client` doesn't even show admin methods in a caller's editor; the daemon's own role check is what actually stops an agent-role session from -calling one (ADR 0003 §3) — this is a discoverability choice, not the +calling one — this is a discoverability choice, not the enforcement mechanism. Both are async factories that open one connection and complete the `hello` @@ -38,8 +38,7 @@ await client.releaseLease({ leaseId: grant.lease.id }); await client.close(); ``` -**Keeping the lease alive is yours to do.** Every lease is TTL-bound ([ADR -0004](adr/0004-ttl-first-leases-on-every-transport.md)): it expires at +**Keeping the lease alive is yours to do.** Every lease is TTL-bound: it expires at `grant.lease.ttlDeadline` unless a `renewLease` call lands first, and the daemon does nothing on its own to keep it. `requestLease` takes an optional `ttlMs` (`lease.defaultTtlMs` when omitted, `BAD_REQUEST` above @@ -54,8 +53,7 @@ before the deadline is the whole mechanism. `connectSimlockAdmin` additionally accepts `credential` — an operator token or the daemon's per-start `admin.token` secret (see -[ARCHITECTURE.md](ARCHITECTURE.md#security-model-cooperative-identity-not-a-hostile-process-boundary) -for what those are and how the CLI resolves one). A missing or wrong +[CLI.md](CLI.md#admin-credential-resolution) for how the CLI resolves one). A missing or wrong credential fails the handshake with `ADMIN_AUTHENTICATION_FAILED` before any other request is sent on that connection: @@ -158,8 +156,8 @@ touches a mutation, so this module simply does not have one at all, for anything. **A dead connection is not a dead lease.** The daemon keeps no -per-connection lease state and releases nothing when a connection closes -(ADR 0004 §3), so the leases this client held are still granted, still +per-connection lease state and releases nothing when a connection closes, +so the leases this client held are still granted, still yours, and still counting down their TTL. What you have lost is the ability to renew them and to receive their pushes — nothing more. Connect again and call `renewLease` with the lease id and you have picked the lease straight @@ -179,8 +177,8 @@ this client can make a universal decision about: comes — but that trigger only ever connects to a daemon that is already listening, never launches one, so an operator's `daemon stop` is not undone by an idle session. -- **The CLI** needs none, and deliberately still does not have one under - ADR 0004. A `simlock lease` holder's lease outlives its connection, but the +- **The CLI** needs none, and deliberately still does not have one. + A `simlock lease` holder's lease outlives its connection, but the holder itself does not: it writes a `DAEMON_CONNECTION_LOST` line naming the lease and its deadline, exits `1`, and leaves the lease standing for another invocation to renew or for the TTL to end. @@ -208,7 +206,7 @@ client.onConnectionLost((error) => { `requestLease` takes an `AbortSignal` as part of its options. Aborting does not simply drop the caller's interest client-side — it drives the daemon's -own `lease.cancel` operation (ADR 0003 §9) and waits for a real outcome, so +own `lease.cancel` operation and waits for a real outcome, so the caller is never left guessing whether a device is or isn't leased to it: ```ts @@ -242,14 +240,13 @@ Four cases, by when the signal fires: The "device work already in flight" case above releases the grant immediately once it lands rather than actually interrupting the in-flight provision/boot/reclaim — the daemon keeps doing the work, the caller just -doesn't end up holding the result. This is recorded as a known gap in -[known-pitfalls.md](known-pitfalls.md). +doesn't end up holding the result. This is a known gap. ## Running a command on the leased device: `exec` `exec` runs one `simctl` / `adb` command against a device you hold a lease on, wherever that device actually is, and streams its output back as it -arrives ([ADR 0005](adr/0005-gateway-and-worker-modes.md)): +arrives: ```ts const { exitCode } = await client.exec( @@ -271,7 +268,7 @@ Omit `onOutput` and the output is simply dropped. `exec` takes an optional `requesterId`, defaulting to the principal. An agent-role connection does not need it: it is gated the ordinary way, its -principal against the lease's `ownerId` (ADR 0003 §4), exactly as +principal against the lease's `ownerId`, exactly as `renewLease` and `releaseLease` are. The field exists for the one session that would otherwise bypass that check — the gateway's admin session on a worker — and on this operation, unlike renew and release, **admin does not @@ -299,7 +296,7 @@ Five things to know before building on it: - **The command runs on the machine that owns the device**, against that machine's filesystem. A path in `args` (`simctl install `, `adb install `) resolves *there*, so getting an artifact to a remote worker - is out of band in v1 — see [known-pitfalls.md](known-pitfalls.md). + is out of band in v1. - **`stdin` is one string, sent with the request** and then closed, and there is no pseudo-terminal. Line-oriented commands work; full-screen ones do not. @@ -320,8 +317,7 @@ Five things to know before building on it: `connectSimlock`/`connectSimlockAdmin` connect to a **gateway** — a daemon that owns no devices and fronts a fleet of workers — exactly as they connect to an ordinary worker daemon, over its unix socket, with the same methods, -the same types, and the same error codes ([ADR -0005](adr/0005-gateway-and-worker-modes.md)). That is the point of the +the same types, and the same error codes. That is the point of the gateway implementing the same contract: nothing in this module knows the difference, and neither does code written against it. @@ -355,11 +351,8 @@ neither of which changes a call's shape: on anything but "nothing is listening" (a version mismatch or a refused handshake means something answered, and launching there risks a second daemon instance or masking a real incompatibility). -- It does not restart the daemon on a protocol version mismatch — see - [ARCHITECTURE.md](ARCHITECTURE.md) and [ADR - 0003](adr/0003-one-typed-daemon-contract-behind-every-frontend.md) §6 for - the decision. ADR 0004 changed what a stop costs without changing the - answer: leases now survive a restart, but stopping a daemon out from under +- It does not restart the daemon on a protocol version mismatch. Leases + survive a restart, but stopping a daemon out from under its users still kills every queued lease request on the machine and leaves every lease it was serving burning TTL with nothing to renew against. `PROTOCOL_VERSION_UNSUPPORTED` names the running daemon's version; the fix diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 340f3fe82..ed34f7c17 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -21,9 +21,9 @@ a warning. Inspect the effective, merged configuration at any time with | `gateway.token` | **Worker side.** The join token (`simlock token create --role worker`, minted on the gateway) this worker presents when it opens its uplink. Required whenever `gateway.url` is set. | unset | | `gateway.label` | **Worker side.** Display name for this worker in `simlock worker list`, `status`, the console, and on the lease's `worker` block. Display-only: nothing routes on it and it need not be unique. | the worker's own id | | `exec.timeoutMs` | **Worker side.** How long one `device.exec` command (`simlock simctl` / `simlock adb` against a gateway or over HTTP) may run before the worker kills it and the operation fails with `EXEC_TIMEOUT`. Authoritative: it bounds the process that actually runs. | `10 minutes` | -| `gateway.routing` | **Gateway side.** Which routing policy places a queued request on a worker. `warm-then-free` is the only policy in v1: warm hit first, then the most free running capacity for the platform. See [Routing](ARCHITECTURE.md#routing). | `warm-then-free` | +| `gateway.routing` | **Gateway side.** Which routing policy places a queued request on a worker. `warm-then-free` is the only policy in v1: warm hit first, then the most free running capacity for the platform. | `warm-then-free` | | `gateway.disconnectedRetentionMs` | **Gateway side.** How long a disconnected worker is kept (greyed, never dispatched to) before the gateway forgets it. The clock is held while the gateway still knows of gateway-issued leases on that worker, and that hold ends when the last of those leases passes its deadline. | `24 hours` | -| `gateway.execTimeoutMs` | **Gateway side.** How long the gateway waits on a proxied `device.exec` before giving up. A backstop for a worker that never answers at all — deliberately longer than the worker's own `exec.timeoutMs`, which is authoritative because that side owns the process and can kill it, so an ordinary timeout surfaces as the worker's `EXEC_TIMEOUT` rather than racing this one. See [ADR 0005](adr/0005-gateway-and-worker-modes.md) §19e. | `11 minutes` | +| `gateway.execTimeoutMs` | **Gateway side.** How long the gateway waits on a proxied `device.exec` before giving up. A backstop for a worker that never answers at all — deliberately longer than the worker's own `exec.timeoutMs`, which is authoritative because that side owns the process and can kill it, so an ordinary timeout surfaces as the worker's `EXEC_TIMEOUT` rather than racing this one. | `11 minutes` | | `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)). 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` | @@ -80,7 +80,7 @@ misconfigured by leftovers from the config it was flipped out of. registered routing policies, and `exec.timeoutMs`, `gateway.execTimeoutMs`, `gateway.leaseRequestTimeoutMs`, and `gateway.disconnectedRetentionMs` positive numbers. -**`mode: "gateway"` with `http.enabled: false` is rejected at load** (ADR 0005 §2), naming the key: a +**`mode: "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.defaultTtlMs` and `lease.maxTtlMs` must be positive numbers, and @@ -102,11 +102,9 @@ See [CLI.md](CLI.md#simlock-config-get-keyset-key-value) for the ## Gateway and worker modes -`mode` selects what `simlock daemon start` starts ([ADR -0005](adr/0005-gateway-and-worker-modes.md)). The default, `worker`, is what +`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 — see -[ARCHITECTURE.md](ARCHITECTURE.md#gateway-and-worker-modes-adr-0005). +devices and fronts the workers connected to it. **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 @@ -145,8 +143,8 @@ restart; every other part of a worker view is rebuilt from the worker itself. ### Retired `lease.*` keys -[ADR 0004](adr/0004-ttl-first-leases-on-every-transport.md) collapsed the -held/detached lease split into one TTL-bound lease, which retired three keys. +A collapse of the +held/detached lease split into one TTL-bound lease retired three keys. **All three are simply unrecognized now** — `simlock config` warns about each one and ignores it, exactly as it does for any other unknown key. None of them is aliased onto a new key, so a config file that still sets one gets the @@ -165,8 +163,7 @@ 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 ([ADR -0005](adr/0005-gateway-and-worker-modes.md)). One daemon runs exactly one +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. @@ -256,7 +253,7 @@ Simlock keeps every device it creates inside a root it owns, one per platform, and scopes every platform command to that root. A simulator or emulator in a Simlock root does not appear in Xcode, in Android Studio, or in a plain `simctl list` / `adb devices`, and Simlock in turn cannot reach anything -outside it. See [ADR 0001](adr/0001-simlock-owned-device-roots.md) for why. +outside it. ``` ~/.simlock/devices/ diff --git a/docs/EVENTS.md b/docs/EVENTS.md index e32fa76a7..0fc989a35 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -1,42 +1,29 @@ # Events -Catalog of business events carried on the daemon's event bus. Naming and -authoring rules live in [agent-rules/events.md](agent-rules/events.md) — -in short: `subject.past-tense-fact`, emitted post-commit, facts not commands. - -> Status: **planned catalog** — update the Status column as events are -> implemented, and add new events here in the same change that introduces them. - -> **The payload removals in the lease rows are a deliberate exception to -> events rule 6** ("treat payload shape as a public contract: additive -> changes only"), granted by [ADR -> 0004](adr/0004-ttl-first-leases-on-every-transport.md) in its Consequences: -> `lease.granted` loses `mode` and `lease.released` loses the `closed` and -> `orphaned` reasons, since neither concept exists any more — there is no -> connection close to release on, and no startup sweep to orphan anything. -> The ADR takes that exception once, while the package is 0.x; this note -> records it here so the catalogue does not read as a silent rule violation. +Catalog of business events carried on the daemon's event bus, exposed +through `simlock events` and `simlock events --follow`. + +> Status: **planned catalog** — the Status column reflects what has shipped. ## Lease lifecycle | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `lease.requested` | request spec, requester, wait policy | a lease request is accepted by the daemon | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway, ADR 0005 §11 — its own fleet queue's admission, before any worker is chosen) | implemented | +| `lease.requested` | request spec, requester, wait policy | a lease request is accepted by the daemon | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway — its own fleet queue's admission, before any worker is chosen) | implemented | | `lease.queued` | request id, queue position | no capacity; request entered the wait queue | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway) | implemented | -| `lease.granted` | lease id, device id, requester | a device was assigned and handed out | LeaseLifecycle | implemented (payload per ADR 0004 pending) | -| `lease.renewed` | lease id, new deadline | a `lease.renew` succeeded — whether it came from `simlock lease renew`, `POST /v1/leases/{id}/renew`, or the renew timer a running `simlock lease` / MCP session keeps over its own lease. There is one renew path and this is it | LeaseLifecycle | implemented (payload per ADR 0004 pending) | -| `lease.released` | lease id, device id, reason (explicit/killed/device-lost), owner id | an explicit `lease.release` (which is what a `simlock lease` holder does on its way out), (killed) an operator `release --all` or `nuke`, or (device-lost) a leased device could not be recovered after it stopped running outside simlock. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented (payload per ADR 0004 pending) | -| `lease.expired` | lease id, device id, owner id | the lease's deadline passed with no `lease.renew` behind it — the grant-time TTL, or the TTL of the last renew, simply ran out. This is the one way a lease ends without somebody asking, and the only bound on a holder that was killed outright | LeaseLifecycle | implemented (payload per ADR 0004 pending) | -| `lease.rejected` | request spec, reason (timeout/no-wait/unresolvable-spec/already-leased/boot-timeout/killed/cancelled) | a request ended without a grant; `cancelled` is an explicit single-request cancel (`LeaseEngine#cancelPending`, backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter -- one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses | LeaseAcquisitionCoordinator / WaitQueue (worker) / FleetLeaseCoordinator (gateway) | implemented | +| `lease.granted` | lease id, device id, requester | a device was assigned and handed out | LeaseLifecycle | implemented | +| `lease.renewed` | lease id, new deadline | a `lease.renew` succeeded — whether it came from `simlock lease renew`, `POST /v1/leases/{id}/renew`, or the renew timer a running `simlock lease` / MCP session keeps over its own lease. There is one renew path and this is it | LeaseLifecycle | implemented | +| `lease.released` | lease id, device id, reason (explicit/killed/device-lost), owner id | an explicit `lease.release` (which is what a `simlock lease` holder does on its way out), (killed) an operator `release --all` or `nuke`, or (device-lost) a leased device could not be recovered after it stopped running outside simlock. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented | +| `lease.expired` | lease id, device id, owner id | the lease's deadline passed with no `lease.renew` behind it — the grant-time TTL, or the TTL of the last renew, simply ran out. This is the one way a lease ends without somebody asking, and the only bound on a holder that was killed outright | LeaseLifecycle | implemented | +| `lease.rejected` | request spec, reason (timeout/no-wait/unresolvable-spec/already-leased/boot-timeout/killed/cancelled) | a request ended without a grant; `cancelled` is an explicit single-request cancel (backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter — one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses | LeaseAcquisitionCoordinator / WaitQueue (worker) / FleetLeaseCoordinator (gateway) | implemented | -On a **gateway**, these three are its own fleet queue's facts (ADR 0005 §11/§14), +On a **gateway**, the first three of these are its own fleet queue's facts, emitted by `FleetLeaseCoordinator` and never by the worker whose device is eventually granted — `lease.granted`/`renewed`/`released`/`expired` for a fleet lease arrive already relayed from the owning worker (see "Fleet (gateway mode)" below), so a gateway never emits those four itself. `already-leased` -on a gateway is the fleet-wide one-lease-per-requester check (§14, keyed on -`requesterId`), answered from the gateway's own lease index before any -worker is ever contacted. +on a gateway is the fleet-wide one-lease-per-requester check, answered from +the gateway's own lease index before any worker is ever contacted. ## Device lifecycle @@ -54,23 +41,16 @@ worker is ever contacted. | `device.deleted` | device id, initiator | device removed from disk and registry | Registry | implemented | | `device.foreign-state-detected` | device id, platform, expected (running/stopped), observed (running/stopped) | doctor reconcile found a managed device's observed boot state disagreeing with the committed registry state | Doctor | implemented | | `device.foreign-provenance-detected` | device id, platform, detail (erased/mark-mismatch/durable-mark-missing) | doctor reconcile found a managed device's provenance marks no longer proving Simlock owns it | Doctor | implemented | -| `device.stalled-transition-detected` | device id, platform, state (provisioning/reclaiming), age, threshold | doctor reconcile found a `provisioning`/`reclaiming` device whose time in that state exceeds a driver-derived threshold (`stalledTransition.thresholdMultiplier` over `Driver.estimate`, floored at `stalledTransition.minimumThresholdMs`) — the driver call meant to resolve the transition never did | Doctor | implemented | -| `device.crash-detected` | device id, lease id, platform, observed | a leased device was observed `stopped` for `health.stableObservations` consecutive ticks | LeaseHealthMonitor | implemented | +| `device.stalled-transition-detected` | device id, platform, state (provisioning/reclaiming), age, threshold | doctor reconcile found a `provisioning`/`reclaiming` device whose time in that state exceeds a driver-derived threshold — the driver call meant to resolve the transition never did | Doctor | implemented | +| `device.crash-detected` | device id, lease id, platform, observed | a leased device was observed `stopped` for several consecutive health checks | LeaseHealthMonitor | implemented | | `device.recovered` | device id, lease id, attempts, duration | a crashed leased device was rebooted under its existing lease and passed readiness | LeaseHealthMonitor | implemented | | `device.recovery-failed` | device id, lease id, attempts, reason, error | recovery could not restore a leased device (absent from driver reality, provenance drift, or attempts exhausted) and its lease was released | LeaseHealthMonitor | implemented | -| `device.orphan-purged` | driver device id, platform, device root | `simlock doctor --purge-orphans` destroyed a device that sat inside a validly-marked Simlock device root with no registry record — see [ADR 0001](adr/0001-simlock-owned-device-roots.md) | Doctor | implemented | -| `device.slimmed` | device id, address, platform (ios), categories, label count, duration, signature, unknown labels | *after* the post-slim reboot's `bootstatus` succeeded -- i.e. once the `launchctl disable` overrides applied via `simctl spawn` are actually in force on the simulator | driver-diagnostics | implemented | - -`device.slimmed` reports a fact committed to the *simulator's own launchd database*, not to the -Simlock registry (ADR 0002, `docs/adr/0002-opt-in-slim-ios-simulators.md`) -- so events rule 3 ("emit post-commit -only") is satisfied by waiting for that commit to become observable, not by waiting on a registry -write: the driver applies the `launchctl disable` overrides, reboots the device, and only fires -`onSlimmed` once the second `bootstatus` has passed, proving the overrides survived the reboot and -are actually in force. The registry's own `device.ready` for that same boot is a separate, -later event, emitted through the normal readiness path once the driver call returns. A *skipped* -slim -- the runtime is older than iOS 18.5, its runtime id didn't parse, or the disable pass itself -failed -- is deliberately not an event: it isn't a fact worth putting in front of every event-bus -consumer, just operator diagnostics, so it's a `warn` log line (`daemon.driver-discovery`) instead. +| `device.orphan-purged` | driver device id, platform, device root | `simlock doctor --purge-orphans` destroyed a device that sat inside a validly-marked Simlock device root with no registry record | Doctor | implemented | +| `device.slimmed` | device id, address, platform (ios), categories, label count, duration, signature, unknown labels | after the post-slim reboot succeeded, i.e. once the overrides that disable a set of iOS launchd services are confirmed in force on the simulator | driver-diagnostics | implemented | + +A *skipped* slim (an older runtime, a runtime id that didn't parse, or a +failed disable pass) is deliberately not an event — it's operator +diagnostics, not a fact worth putting in front of every event-bus consumer. ## Components @@ -80,15 +60,9 @@ consumer, just operator diagnostics, so it's a `warn` log line (`daemon.driver-d | `component.installed` | platform, component id, duration, requester id | the install succeeded **and** a post-install re-scan confirmed the component the request actually needed is present (paired with the requested device type, for iOS) — never fired on a bare exit-0 | driver-diagnostics | implemented | | `component.install-failed` | platform, component id, duration, stable error summary, requester id | the install failed, including a license-retry failure (exactly one `install-failed` per attempted install, never one per retry), **or** the installer exited 0 but the post-install re-scan could not confirm the component | driver-diagnostics | implemented | -Drivers never touch the event bus directly (architecture rule 5): both drivers report these -facts through their own `onDiagnostic` callback (mirroring the Android driver's pre-existing -diagnostic pattern), and `src/daemon/main.ts` bridges that diagnostic to the bus at driver -construction time — hence the `driver-diagnostics` emitter rather than `IosSimctlDriver` / -`AndroidDriver`. A disk-preflight failure (`InsufficientDiskSpaceError`) happens before any -diagnostic fires: no install was attempted, so nothing is reported as started or failed. See -"Device requests" and "Fresh-state strategy" in [ARCHITECTURE.md](ARCHITECTURE.md) for how a -missing component gets to this point, and `docs/known-pitfalls.md` for the requester-visible -progress gap this leaves. +A disk-preflight failure happens before any diagnostic fires: no install was +attempted, so nothing is reported as started or failed. The requester's own +progress stream does not yet reflect an in-flight download. ## System @@ -105,62 +79,53 @@ progress gap this leaves. ## Fleet (gateway mode) These are the facts a daemon running as a **gateway** emits about the fleet -connected to it ([ADR 0005](adr/0005-gateway-and-worker-modes.md)). A worker -never emits them — it has no workers or fleet queue of its own — and a -gateway emits none of the device-lifecycle facts above on its own behalf, -because it owns no devices. +connected to it. A worker never emits them — it has no workers or fleet +queue of its own — and a gateway emits none of the device-lifecycle facts +above on its own behalf, because it owns no devices. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| | `worker.connected` | worker id, label, worker's daemon version | a worker's uplink opened and its `hello` completed, so the gateway can drive it. A worker whose `hello` found no overlapping protocol range emits nothing: it is in the registry as `incompatible`, which is where an operator finds it | WorkerRegistry | implemented | -| `worker.rejected` | `{ reason, workerId?, label?, protocol? }` — reason is `unauthenticated` (the join token was missing or unrecognized, `401`) or `forbidden` (a valid token of the wrong role, `403`) | an uplink was turned away at the door, before any session existed. Every field but `reason` is optional, because a dial that fails authentication proves no identity. Version skew is deliberately not one of these: that uplink authenticated, so the worker enters the registry as `incompatible` and emits nothing (see the note below the table) | WorkerRegistry | implemented | -| `worker.disconnected` | worker id, label, lease count | a worker's uplink closed. `leaseCount` is what its view still shows it holding — how much is stranded, and why the view is kept rather than dropped, not ended: the gateway never guesses a lease is gone before the worker says so | WorkerRegistry | implemented | -| `worker.removed` | worker id, label, reason (operator/retention) | a disconnected worker's view was forgotten: by `simlock worker remove`, or because every gateway-issued lease on it had expired and `gateway.disconnectedRetentionMs` elapsed. Never emitted for a connected worker (`WORKER_CONNECTED` refuses that) | WorkerRegistry | implemented | +| `worker.rejected` | reason (unauthenticated/forbidden), worker id, label, occasionally a count | an uplink was turned away at the door, before any session existed: `unauthenticated` (401) for a missing or unrecognized join token, `forbidden` (403) for a real token whose role is not `worker`. Version skew is deliberately not one of these: that uplink authenticated, so the worker enters the registry as `incompatible` and emits nothing. `count`, present only above one, is how many identical refusals a coalescing window absorbed | WorkerRegistry | implemented | +| `worker.disconnected` | worker id, label, lease count | a worker's uplink closed. `leaseCount` is what its view still shows it holding — how much is stranded, and why the view is kept rather than dropped: the gateway never guesses a lease is gone before the worker says so | WorkerRegistry | implemented | +| `worker.removed` | worker id, label, reason (operator/retention) | a disconnected worker's view was forgotten: by `simlock worker remove`, or because every lease on it had expired and `gateway.disconnectedRetentionMs` elapsed. Never emitted for a connected worker | WorkerRegistry | implemented | | `worker.drain-started` | worker id, label | `simlock worker drain` flagged a worker: it keeps its leases and receives no new dispatches | WorkerRegistry | implemented | -| `worker.drain-ended` | worker id, label | `simlock worker undrain` cleared that flag. Nothing else ends a drain: the flag lives in the gateway's persisted worker registry, so it survives both a worker reconnect and a gateway restart | WorkerRegistry | implemented | -| `request.dispatched` | `{ requestId, workerId, requesterId, platform, model, reason, queuedMs }` — `reason` is the routing policy's own `warm-hit`/`free-capacity` distinction (ADR 0005 §13), `queuedMs` how long the request sat queued before this dispatch | the gateway's fleet queue sent a queued request to a worker with `noWait: true`, and the worker took it — the grant itself, or its first `progress` push, whichever arrives first (ADR 0005 §11: device work having started means the request is that worker's now). An immediate `NO_CAPACITY` is a stale view, not a dispatch, and emits nothing — the request stays queued and is retried on the next pass | FleetLeaseCoordinator | implemented | +| `worker.drain-ended` | worker id, label | `simlock worker undrain` cleared that flag. The flag lives in the gateway's persisted worker registry, so it survives both a worker reconnect and a gateway restart | WorkerRegistry | implemented | +| `request.dispatched` | request id, worker id, requester id, platform, model, reason (warm-hit/free-capacity), queued duration | the gateway's fleet queue sent a queued request to a worker, and the worker took it — the grant itself, or its first `progress` push, whichever arrives first. An immediate `NO_CAPACITY` is a stale view, not a dispatch, and emits nothing — the request stays queued and is retried on the next pass | FleetLeaseCoordinator | implemented | Drain and undrain are idempotent, and an event is a fact about a *change*: draining an already-drained worker succeeds and emits nothing. -`worker.rejected` exists because the alternative is silence (ADR 0005 §22): a -worker whose credential is refused produces no `worker.connected`, and -without this fact an operator staring at `simlock worker list` sees a machine -that simply never appears, with nothing anywhere to say why. It is -deliberately *not* a `worker.disconnected` with another reason — nothing -connected, so nothing disconnected, and a fact whose subject never existed -should not borrow the vocabulary of one that did. +`worker.rejected` exists because the alternative is silence: a worker whose +credential is refused produces no `worker.connected`, and without this fact +an operator staring at `simlock worker list` sees a machine that simply +never appears, with nothing anywhere to say why. It is deliberately *not* a +`worker.disconnected` with another reason — nothing connected, so nothing +disconnected. **A protocol mismatch is neither of those.** That uplink presented a valid -join token and authenticated; what failed was `hello`'s range negotiation. So -the worker *does* enter the registry, with `state: "incompatible"` and both -ranges on its view, visible in `simlock worker list` — which is the whole -point, since that is the machine an operator has to go and upgrade. It is -simply never dispatched to, and no `worker.connected` follows, because -nothing usable connected. That is also why `incompatible` is not one of -`worker.disconnected`'s reasons: an incompatible worker was never a connected -worker to lose. - -**`device.exec` emits no event, and that is deliberate.** It is the one -operation here with no fact of its own. Running a command against a device is -not a state change simlock owns — the lease that authorizes it already -emitted `lease.granted`, the device's own state is untouched, and a fleet -where every `adb shell input tap` produced a bus event would push everything -else out of a 1000-entry ring buffer within minutes. An audit trail of what -agents ran on their devices is a different feature with different retention -needs, not a line in this catalogue. +join token and authenticated; what failed was `hello`'s range negotiation. +So the worker *does* enter the registry, with `state: "incompatible"` and +both ranges on its view, visible in `simlock worker list` — which is the +whole point, since that is the machine an operator has to go and upgrade. +It is simply never dispatched to, and no `worker.connected` follows. + +**`device.exec` emits no event, and that is deliberate.** Running a command +against a device is not a state change simlock owns — the lease that +authorizes it already emitted `lease.granted`, the device's own state is +untouched, and a fleet where every `adb shell` command produced a bus event +would push everything else out of the ring buffer within minutes. **Every worker's own business events are republished on the gateway's bus** -with `workerId` added to the payload, under their original names and with -their original emitting module — the fact happened in that worker's lease -engine or reaper, and rewriting either would make the audit trail lie about -where. That is what makes `simlock events` and `simlock events --follow` -against a gateway a fleet-wide view (`lease.granted`, `device.ready`, -`cleanup.executed`, and the rest, each naming the machine it happened on), -and it is the one place a payload documented above arrives with an extra -field: additive, and only ever on a gateway. The seven events in this -section's own table are the gateway's own, and carry no `workerId` beyond -the worker they are about. +with `workerId` added to the payload, under their original names — the fact +happened in that worker's lease engine or reaper, and rewriting either would +make the audit trail lie about where. That is what makes `simlock events` +and `simlock events --follow` against a gateway a fleet-wide view +(`lease.granted`, `device.ready`, `cleanup.executed`, and the rest, each +naming the machine it happened on), and it is the one place a payload +documented above arrives with an extra field: additive, and only ever on a +gateway. The events in this section's own table are the gateway's own, and +carry no `workerId` beyond the worker they are about. Two consequences of relaying rather than owning: the gateway's ring buffer only holds what arrived while its uplinks were up (a worker's events from @@ -168,46 +133,11 @@ before it connected are not backfilled), and a worker's own `simlock events` keeps showing exactly what it always did, un-prefixed and unaware that anything is watching. -## Fleet (gateway mode) - -Emitted only by a daemon in gateway mode ([ADR -0005](adr/0005-gateway-and-worker-modes.md) §22), about the workers connected -to it. - -| Event | Payload (key fields) | Emitted when | Emitter | Status | -|---|---|---|---|---| -| `worker.connected` | worker id, label, worker's daemon version | a worker's uplink opened and its `hello` completed, so the gateway can drive it. A worker whose `hello` found no overlapping protocol range emits nothing: it is in the registry as `incompatible`, which is where an operator finds it | WorkerRegistry | implemented | -| `worker.rejected` | reason (unauthenticated/forbidden), worker id, label, occasionally a count | an uplink was turned away at the door, before any session existed: `unauthenticated` (401) for a missing or unrecognized join token — a revoked or mistyped one lands here — and `forbidden` (403) for a real token whose role is not `worker`. Version skew is deliberately not one of these: that uplink authenticated, so the worker enters the registry as `incompatible` and emits nothing. A refused peer proves no identity, so `workerId` and `label` are only what the connection claimed and may be absent. `count`, present only above one, is how many identical (reason, claimed id) refusals the *previous* coalescing window absorbed — a flood of refused dials collapses to one event per window rather than one per attempt, since the ring buffer they land in is bounded by count, not bytes | GatewayService | implemented | -| `worker.disconnected` | worker id, label, lease count | a worker's uplink closed. `leaseCount` is what its view still shows it holding — how much is stranded, and why the view is kept rather than dropped | WorkerRegistry | implemented | -| `worker.removed` | worker id, label, reason (operator/retention) | a disconnected worker's view was forgotten: by `simlock worker remove`, or because every lease on it had expired and `gateway.disconnectedRetentionMs` elapsed | WorkerRegistry | implemented | -| `worker.drain-started` | worker id, label | `simlock worker drain` flagged a worker: it keeps its leases and receives no new dispatches | WorkerRegistry | implemented | -| `worker.drain-ended` | worker id, label | `simlock worker undrain` cleared that flag | WorkerRegistry | implemented | - -Drain and undrain are idempotent, and an event is a fact about a *change*: -draining an already-drained worker succeeds and emits nothing. - -**A worker's own events are republished on the gateway's bus** with `workerId` -added to the payload, under their original names and with their original -emitting module — the fact happened in that worker's lease engine or reaper, -and rewriting either would make the audit trail lie about where. That is what -makes `simlock events` and `simlock events --follow` against a gateway a -fleet-wide view, and it is the one place a payload documented above arrives -with an extra field: additive, and only ever on a gateway. The six events in -this section are the gateway's own, and carry no `workerId` beyond the worker -they are about. A relayed `lease.expired`/`lease.released`/`device.crash-detected`/ `device.recovered` names the *worker's own* lease id in its payload, not the -gateway's — `GatewayOwnerRoutedFacts` (the gateway's `OwnerRoutedFacts`) is -what resolves the gateway's own lease id, and the `ownerId` to route the -corresponding `lease-lost`/`device-unhealthy`/`device-recovered` push by, -from the fleet lease index rather than the relayed payload directly. The -payload's own `ownerId` is correct for a worker's own local lease (the -worker never had a reason to touch it), but for a gateway-issued one it is -whatever that worker echoed back of what the gateway forwarded when it -granted the lease (ADR §27a) — round-tripped through a machine this gateway -does not control, not a value it minted itself, so it is resolved from the -index (which recorded the real answer at grant time) rather than trusted -verbatim off the wire. +gateway's — the gateway resolves the `ownerId` to route the corresponding +`lease-lost`/`device-unhealthy`/`device-recovered` push from its own fleet +lease index, rather than trusting the relayed payload's `ownerId` verbatim. ## Conventions recap diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 9d9c87b07..5f621e977 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -9,21 +9,19 @@ reverse proxy) — Simlock does no TLS termination in v1, and `Authorization` is required on every route regardless of how it's reached, loopback included. This frontend calls the exact same in-process `Dispatcher` the unix socket -calls (ADR 0003 §2) — not a second copy of role/ownership logic, and not a +calls — not a second copy of role/ownership logic, and not a loopback hop through the socket either. Every route that maps onto a daemon operation gets the same input parsing, role check, `authorize`/ownership hook, and startup-readiness parking a socket request gets, from that one shared instance. This is also why a fix on the socket side (the download policy, startup-readiness parking, error mapping) lands on HTTP for free — -see [ARCHITECTURE.md](ARCHITECTURE.md#contract-dispatcher-and-roles-adr-0003) -for how it fits together, and the two bug fixes called out below for what +see the two bug fixes called out below for what this actually changed. ## Leases are TTL-bound, the same as everywhere else A lease granted through this API is the same kind of lease `simlock lease` -gets on the unix socket ([ADR -0004](adr/0004-ttl-first-leases-on-every-transport.md)): it carries a TTL, it +gets on the unix socket: it carries a TTL, it is kept alive by `POST /v1/leases/:id/renew` arriving before `expiresAt`, and nothing else keeps it alive. There is no connection-liveness mode to be the odd one out from — HTTP is stateless, and so is the lease model now, on every @@ -51,7 +49,7 @@ Every route requires `Authorization: Bearer slk_` except `GET Tokens are minted and managed with `simlock token` (see [CLI.md](CLI.md)). Since 0.3.0 `token.create|list|revoke` are daemon operations (admin role) and the daemon is the only process that reads or writes `tokens.json`, so unlike -`config set` these do go through the daemon (ADR 0003 §11). Each token record +`config set` these do go through the daemon. Each token record is `{ id, role, label?, createdAt }`, hashed at rest in `~/.simlock/tokens.json` (SHA-256; the plaintext secret is shown exactly once, at `create`, and never @@ -79,8 +77,7 @@ opens and the only route it opens: presented on any other `/v1` route it is `403`, and an `agent` or `operator` token presented at `/v1/uplink` is `403` just the same. Join tokens are minted with `simlock token create --role worker` on the **gateway**, and tokens never cross machines — a gateway's -tokens are valid on that gateway and nowhere else ([ADR -0005](adr/0005-gateway-and-worker-modes.md)). +tokens are valid on that gateway and nowhere else. **An `agent` token on a worker is a host-level credential, not a device-level one.** `POST /v1/leases/{id}/exec` runs the command's *arguments* @@ -90,7 +87,7 @@ on the worker's own filesystem with the daemon's own uid and environment enough to write or read files anywhere that uid can reach, not only the leased device: `adb pull ` is a host-side arbitrary file write, and there is no argument grammar this API parses that -would stop it (see [known-pitfalls.md](known-pitfalls.md)). Size a worker's +would stop it. Size a worker's trust boundary around the daemon's own uid, not around "one device," before handing an `agent` token to something you would not otherwise let run on that machine. @@ -98,9 +95,8 @@ that machine. ## Endpoints All routes are under `/v1`, JSON bodies both ways, additive evolution only — -new fields, never removed or repurposed ones. [ADR -0004](adr/0004-ttl-first-leases-on-every-transport.md) breaks that rule once, -under its "Breaking for 0.x" consequence, and each break is called out where +new fields, never removed or repurposed ones. That rule was broken once, +as a deliberate 0.x-only exception, and each break is called out where it applies below: - **`mode` is gone** from the lease record the operator routes serialize @@ -114,7 +110,7 @@ it applies below: Routes, status codes, and every other field are unchanged. -[ADR 0005](adr/0005-gateway-and-worker-modes.md) is purely additive on top of +Gateway/worker fleet mode is purely additive on top of that: the same routes answer identically whether the daemon behind them is a worker or a **gateway** fronting a fleet of workers, and what it adds are new routes (`/v1/uplink`, `/v1/workers*`, `POST /v1/leases/{id}/exec`), new @@ -320,7 +316,7 @@ same answer the socket transport gives, via the same operation's `ownsLease` authorize hook. (0.3.0 briefly had every lease route answering `404` here; that overcorrected the lease-*request* routes' old `403` and is why renew and release were moved off the `lease.list`-filtered lookup — see -`docs/known-pitfalls.md`. `exec` arrives on the dispatching side of that +`docs/internal/KNOWN-PITFALLS.md`. `exec` arrives on the dispatching side of that split, with renew and release.) This is different again from the lease-*request* routes below @@ -378,7 +374,7 @@ below. Runs one `simctl`/`adb` command **on the machine that owns the device** and streams its output back. This is what makes a leased device drivable from here at all — over HTTP against a lone worker, and through a gateway to whichever worker holds the lease, with the same request and the -same response either way ([ADR 0005](adr/0005-gateway-and-worker-modes.md)). +same response either way. Every other way of reaching a device assumes the caller shares that machine's filesystem. @@ -509,8 +505,8 @@ Role: `agent` (own lease); `operator` may release any lease. → `202 { "released": true, "device": { "id": "dev_1a2b", "state": "reclaiming" } }` The lease is gone the moment this responds; the driver-side purge continues -in the background (existing release semantics — see "Release hands the -purge off" in [ARCHITECTURE.md](ARCHITECTURE.md)), hence `202`, not `200`. +in the background (existing release semantics: release hands the +purge off), hence `202`, not `200`. ### `GET /v1/uplink` (WebSocket upgrade) @@ -528,7 +524,7 @@ token and needs no inbound port of its own, and no client ever learns a worker's address. What travels over the socket is not a new API: it is the same typed daemon -contract (ADR 0003), with **the gateway as the protocol client**. It sends +contract, with **the gateway as the protocol client**. It sends `hello`, negotiates the protocol range exactly as over the unix socket, and then issues ordinary operations (`status.get`, `list.get`, `catalog.get`, `events.subscribe`, `lease.request`, `device.exec`, …) to the worker's own @@ -569,7 +565,7 @@ worker may install a missing runtime at all before sending it a request that depends on one; it is never an override, since the worker clamps `allowDownload` through the same policy regardless. -`protocol` is the range that worker negotiated. ADR 0005 moves the wire to +`protocol` is the range that worker negotiated. The wire moves to `{min: 5, max: 5}` with no compatibility shim, so a worker from before it does not overlap and shows as `incompatible` — the ordinary upgrade path, not a fault. @@ -657,7 +653,7 @@ Every failure is the same shape the daemon protocol uses: | 503 | `NO_CAPACITY` (only with `noWait: true`; response carries `Retry-After`), `WORKER_UNREACHABLE` (a gateway could not reach the worker holding this lease or request) | | 504 | `EXEC_TIMEOUT` (a `device.exec` command outlived `exec.timeoutMs`) | -Three notes on the ADR 0005 codes. +Three notes on these codes. `WORKER_UNREACHABLE` sits on `503` with `NO_CAPACITY` rather than on `502`, because its `kind` is `transport` and every other `transport`-kind code in @@ -740,9 +736,8 @@ and `message` — details are contract, message text is not. against a lone worker and through a gateway alike. - **File transfer for `exec`.** A command that names a path resolves it on the machine that owns the device; there is no upload route in this version, - and the seam for a later `device.upload` is left open by design (ADR 0005). + and the seam for a later `device.upload` is left open by design. - MCP-over-HTTP and in-process TLS are out of scope for this version too. - Multi-host brokering is no longer on this list: [ADR - 0005](adr/0005-gateway-and-worker-modes.md) designs it as gateway and + Multi-host brokering is no longer on this list: it is designed as gateway and worker modes, and its routes (`/v1/uplink`, `/v1/workers*`) are documented above. diff --git a/docs/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md similarity index 99% rename from docs/ARCHITECTURE.md rename to docs/internal/ARCHITECTURE.md index dcfb72fd9..592a84de9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -37,7 +37,7 @@ modes](#gateway-and-worker-modes-adr-0005) below for that topology. typed contract (ADR 0003; see "Contract, dispatcher, and roles" below). The core never knows which frontend made a request. The CLI and MCP server sit over `simlock/client`/`simlock/admin` (the typed daemon client, see - [CLIENT.md](CLIENT.md)) and the unix socket; the CLI is the full operator + [CLIENT.md](../CLIENT.md)) and the unix socket; the CLI is the full operator interface, and the MCP server intentionally limits its tool surface to leasing and releasing for an agent session. The HTTP frontend is different in kind, not just transport: it is the one frontend meant to be reached over a @@ -54,7 +54,7 @@ modes](#gateway-and-worker-modes-adr-0005) below for that topology. already finished and so never needed to park anything. A request that arrives before convergence completes now waits on the shared dispatcher's readiness gate exactly like a socket request, instead of being refused. See - [HTTP-API.md](HTTP-API.md) for the full route reference. + [HTTP-API.md](../HTTP-API.md) for the full route reference. - **CLI**: by default it acquires a lease, prints one JSON result line on stdout, then stays alive — renewing the lease at one third of the lease's TTL and releasing it on exit, parent death, or `SIGINT`/`SIGTERM`. That is the @@ -343,10 +343,10 @@ driver reality — worth knowing before calling it from a tight loop or a context where that per-device process-spawn cost is unwelcome. `fix: true` requires the admin role because it can quarantine or destroy devices. -See [CLIENT.md](CLIENT.md) for how `simlock/client`/`simlock/admin` expose -`credential` and role at connect time, [CLI.md](CLI.md#admin-credential-resolution) +See [CLIENT.md](../CLIENT.md) for how `simlock/client`/`simlock/admin` expose +`credential` and role at connect time, [CLI.md](../CLI.md#admin-credential-resolution) for the CLI's own walkthrough of the same resolution order, and -[HTTP-API.md](HTTP-API.md#authentication) for how HTTP's bearer-token roles +[HTTP-API.md](../HTTP-API.md#authentication) for how HTTP's bearer-token roles map onto `agent`/`admin`. ## Gateway and worker modes (ADR 0005) diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md new file mode 100644 index 000000000..e522b5e96 --- /dev/null +++ b/docs/internal/EVENTS.md @@ -0,0 +1,189 @@ +# Events + +Catalog of business events carried on the daemon's event bus. Naming and +authoring rules live in [agent-rules/events.md](agent-rules/events.md) — +in short: `subject.past-tense-fact`, emitted post-commit, facts not commands. + +> Status: **planned catalog** — update the Status column as events are +> implemented, and add new events here in the same change that introduces them. + +> **The payload removals in the lease rows are a deliberate exception to +> events rule 6** ("treat payload shape as a public contract: additive +> changes only"), granted by [ADR +> 0004](adr/0004-ttl-first-leases-on-every-transport.md) in its Consequences: +> `lease.granted` loses `mode` and `lease.released` loses the `closed` and +> `orphaned` reasons, since neither concept exists any more — there is no +> connection close to release on, and no startup sweep to orphan anything. +> The ADR takes that exception once, while the package is 0.x; this note +> records it here so the catalogue does not read as a silent rule violation. + +## Lease lifecycle + +| Event | Payload (key fields) | Emitted when | Emitter | Status | +|---|---|---|---|---| +| `lease.requested` | request spec, requester, wait policy | a lease request is accepted by the daemon | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway, ADR 0005 §11 — its own fleet queue's admission, before any worker is chosen) | implemented | +| `lease.queued` | request id, queue position | no capacity; request entered the wait queue | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway) | implemented | +| `lease.granted` | lease id, device id, requester | a device was assigned and handed out | LeaseLifecycle | implemented (payload per ADR 0004 pending) | +| `lease.renewed` | lease id, new deadline | a `lease.renew` succeeded — whether it came from `simlock lease renew`, `POST /v1/leases/{id}/renew`, or the renew timer a running `simlock lease` / MCP session keeps over its own lease. There is one renew path and this is it | LeaseLifecycle | implemented (payload per ADR 0004 pending) | +| `lease.released` | lease id, device id, reason (explicit/killed/device-lost), owner id | an explicit `lease.release` (which is what a `simlock lease` holder does on its way out), (killed) an operator `release --all` or `nuke`, or (device-lost) a leased device could not be recovered after it stopped running outside simlock. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented (payload per ADR 0004 pending) | +| `lease.expired` | lease id, device id, owner id | the lease's deadline passed with no `lease.renew` behind it — the grant-time TTL, or the TTL of the last renew, simply ran out. This is the one way a lease ends without somebody asking, and the only bound on a holder that was killed outright | LeaseLifecycle | implemented (payload per ADR 0004 pending) | +| `lease.rejected` | request spec, reason (timeout/no-wait/unresolvable-spec/already-leased/boot-timeout/killed/cancelled) | a request ended without a grant; `cancelled` is an explicit single-request cancel (`LeaseEngine#cancelPending`, backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter -- one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses | LeaseAcquisitionCoordinator / WaitQueue (worker) / FleetLeaseCoordinator (gateway) | implemented | + +On a **gateway**, these three are its own fleet queue's facts (ADR 0005 §11/§14), +emitted by `FleetLeaseCoordinator` and never by the worker whose device is +eventually granted — `lease.granted`/`renewed`/`released`/`expired` for a fleet +lease arrive already relayed from the owning worker (see "Fleet (gateway +mode)" below), so a gateway never emits those four itself. `already-leased` +on a gateway is the fleet-wide one-lease-per-requester check (§14, keyed on +`requesterId`), answered from the gateway's own lease index before any +worker is ever contacted. + +## Device lifecycle + +| Event | Payload (key fields) | Emitted when | Emitter | Status | +|---|---|---|---|---| +| `device.provisioned` | device id, spec, driver, duration | driver `provision` committed to registry | Registry | implemented | +| `device.ready` | device id, boot duration | readiness probe passed | Registry | implemented | +| `device.reclaimed` | device id, strategy (erase/snapshot/wipe), duration | fresh-state reclaim finished | Registry | implemented | +| `device.purge-failed` | device id, lease id, attempted strategy, duration, stable error summary | release-time purge failed; the device enters `quarantined` (see below) rather than rejoining the pool | WarmPoolCoordinator | implemented | +| `device.quarantined` | device id, max retries, next retry deadline | a device committed to `quarantined` — present in the registry, still counted as running, not eligible for a grant. Fires immediately after `device.purge-failed` for a release-time purge failure, or on its own for a stalled-transition timeout (see `device.stalled-transition-detected`) | QuarantineCoordinator | implemented | +| `device.quarantine-recovered` | device id, attempts, reclaim strategy | a quarantined device's retried purge succeeded; it returned to `ready`/`shutdown` and rejoined the warm pool | QuarantineCoordinator | implemented | +| `device.quarantine-abandoned` | device id, attempts | a quarantined device exhausted its configured retry budget (`warmPool.quarantine.maxRetries`) and was destroyed | QuarantineCoordinator | implemented | +| `device.quarantine-stranded` | device id, attempts, stable error summary | a quarantined device exhausted its retry budget and the destroy that should have retired it also failed; it stays `quarantined` with no further retry until an operator intervenes | QuarantineCoordinator | implemented | +| `device.shutdown` | device id, initiator (rule/command) | device stopped, still on disk | Registry; WarmPoolCoordinator for interrupted reclaim recovery | implemented | +| `device.deleted` | device id, initiator | device removed from disk and registry | Registry | implemented | +| `device.foreign-state-detected` | device id, platform, expected (running/stopped), observed (running/stopped) | doctor reconcile found a managed device's observed boot state disagreeing with the committed registry state | Doctor | implemented | +| `device.foreign-provenance-detected` | device id, platform, detail (erased/mark-mismatch/durable-mark-missing) | doctor reconcile found a managed device's provenance marks no longer proving Simlock owns it | Doctor | implemented | +| `device.stalled-transition-detected` | device id, platform, state (provisioning/reclaiming), age, threshold | doctor reconcile found a `provisioning`/`reclaiming` device whose time in that state exceeds a driver-derived threshold (`stalledTransition.thresholdMultiplier` over `Driver.estimate`, floored at `stalledTransition.minimumThresholdMs`) — the driver call meant to resolve the transition never did | Doctor | implemented | +| `device.crash-detected` | device id, lease id, platform, observed | a leased device was observed `stopped` for `health.stableObservations` consecutive ticks | LeaseHealthMonitor | implemented | +| `device.recovered` | device id, lease id, attempts, duration | a crashed leased device was rebooted under its existing lease and passed readiness | LeaseHealthMonitor | implemented | +| `device.recovery-failed` | device id, lease id, attempts, reason, error | recovery could not restore a leased device (absent from driver reality, provenance drift, or attempts exhausted) and its lease was released | LeaseHealthMonitor | implemented | +| `device.orphan-purged` | driver device id, platform, device root | `simlock doctor --purge-orphans` destroyed a device that sat inside a validly-marked Simlock device root with no registry record — see [ADR 0001](adr/0001-simlock-owned-device-roots.md) | Doctor | implemented | +| `device.slimmed` | device id, address, platform (ios), categories, label count, duration, signature, unknown labels | *after* the post-slim reboot's `bootstatus` succeeded -- i.e. once the `launchctl disable` overrides applied via `simctl spawn` are actually in force on the simulator | driver-diagnostics | implemented | + +`device.slimmed` reports a fact committed to the *simulator's own launchd database*, not to the +Simlock registry (ADR 0002, `docs/internal/adr/0002-opt-in-slim-ios-simulators.md`) -- so events rule 3 ("emit post-commit +only") is satisfied by waiting for that commit to become observable, not by waiting on a registry +write: the driver applies the `launchctl disable` overrides, reboots the device, and only fires +`onSlimmed` once the second `bootstatus` has passed, proving the overrides survived the reboot and +are actually in force. The registry's own `device.ready` for that same boot is a separate, +later event, emitted through the normal readiness path once the driver call returns. A *skipped* +slim -- the runtime is older than iOS 18.5, its runtime id didn't parse, or the disable pass itself +failed -- is deliberately not an event: it isn't a fact worth putting in front of every event-bus +consumer, just operator diagnostics, so it's a `warn` log line (`daemon.driver-discovery`) instead. + +## Components + +| Event | Payload (key fields) | Emitted when | Emitter | Status | +|---|---|---|---|---| +| `component.install-started` | platform, component id (iOS runtime version or "latest"; Android `sdkmanager` package name), requester id (when the triggering resolution knew one) | a driver is about to run `xcodebuild -downloadPlatform` / `sdkmanager --install` for a missing component, disk preflight already passed | driver-diagnostics | implemented | +| `component.installed` | platform, component id, duration, requester id | the install succeeded **and** a post-install re-scan confirmed the component the request actually needed is present (paired with the requested device type, for iOS) — never fired on a bare exit-0 | driver-diagnostics | implemented | +| `component.install-failed` | platform, component id, duration, stable error summary, requester id | the install failed, including a license-retry failure (exactly one `install-failed` per attempted install, never one per retry), **or** the installer exited 0 but the post-install re-scan could not confirm the component | driver-diagnostics | implemented | + +Drivers never touch the event bus directly (architecture rule 5): both drivers report these +facts through their own `onDiagnostic` callback (mirroring the Android driver's pre-existing +diagnostic pattern), and `src/daemon/main.ts` bridges that diagnostic to the bus at driver +construction time — hence the `driver-diagnostics` emitter rather than `IosSimctlDriver` / +`AndroidDriver`. A disk-preflight failure (`InsufficientDiskSpaceError`) happens before any +diagnostic fires: no install was attempted, so nothing is reported as started or failed. See +"Device requests" and "Fresh-state strategy" in [ARCHITECTURE.md](ARCHITECTURE.md) for how a +missing component gets to this point, and `docs/internal/KNOWN-PITFALLS.md` for the requester-visible +progress gap this leaves. + +## System + +| Event | Payload (key fields) | Emitted when | Emitter | Status | +|---|---|---|---|---| +| `daemon.started` | version, config snapshot | daemon finished startup + reconcile | DaemonServer | implemented | +| `daemon.stopping` | reason | graceful shutdown began | DaemonServer | implemented | +| `disk.pressure-detected` | free bytes, threshold | free disk crossed under the configured threshold (edge-triggered: once per crossing, not once per tick while it persists) | CleanupReaper | implemented | +| `cleanup.executed` | rule name, action, target, reason | cleanup executor committed a proposed action | CleanupExecutor | implemented | +| `doctor.reconciled` | drift findings | daemon reconciliation completed | Doctor | implemented | +| `driver.root-rejected` | platform, root path, reason (not-absolute/missing-marker/invalid-marker/wrong-instance/symlink/wrong-owner/wrong-permissions/non-empty-unowned-root/unreadable) | a driver's device root failed ownership validation at startup, so that platform's driver did not start | DaemonServer | implemented | +| `driver.adb-server-rejected` | port, reason (occupied/start-failed/invalid-port) | Simlock's own adb server could not be established — the port was occupied by a server it does not own, the server it started never began listening, or the configured port is not usable — so the Android driver did not start | DaemonServer | implemented | + +## Fleet (gateway mode) + +These are the facts a daemon running as a **gateway** emits about the fleet +connected to it ([ADR 0005](adr/0005-gateway-and-worker-modes.md)). A worker +never emits them — it has no workers or fleet queue of its own — and a +gateway emits none of the device-lifecycle facts above on its own behalf, +because it owns no devices. + +| Event | Payload (key fields) | Emitted when | Emitter | Status | +|---|---|---|---|---| +| `worker.connected` | worker id, label, worker's daemon version | a worker's uplink opened and its `hello` completed, so the gateway can drive it. A worker whose `hello` found no overlapping protocol range emits nothing: it is in the registry as `incompatible`, which is where an operator finds it | WorkerRegistry | implemented | +| `worker.rejected` | reason (`unauthenticated`/`forbidden`), worker id, label, occasionally a count | an uplink was turned away at the door, before any session existed: `unauthenticated` (`401`) for a missing or unrecognized join token — a revoked or mistyped one lands here — and `forbidden` (`403`) for a real token whose role is not `worker`. Version skew is deliberately not one of these: that uplink authenticated, so the worker enters the registry as `incompatible` and emits nothing (see the note below the table). A refused peer proves no identity, so `workerId` and `label` are only what the connection claimed and may be absent. `count`, present only above one, is how many identical (reason, claimed id) refusals the *previous* coalescing window absorbed — `GatewayService` computes it before calling into the registry, so a flood of refused dials collapses to one event per window rather than one per attempt, since the ring buffer they land in is bounded by count, not bytes | WorkerRegistry | implemented | +| `worker.disconnected` | worker id, label, lease count | a worker's uplink closed. `leaseCount` is what its view still shows it holding — how much is stranded, and why the view is kept rather than dropped, not ended: the gateway never guesses a lease is gone before the worker says so | WorkerRegistry | implemented | +| `worker.removed` | worker id, label, reason (operator/retention) | a disconnected worker's view was forgotten: by `simlock worker remove`, or because every gateway-issued lease on it had expired and `gateway.disconnectedRetentionMs` elapsed. Never emitted for a connected worker (`WORKER_CONNECTED` refuses that) | WorkerRegistry | implemented | +| `worker.drain-started` | worker id, label | `simlock worker drain` flagged a worker: it keeps its leases and receives no new dispatches | WorkerRegistry | implemented | +| `worker.drain-ended` | worker id, label | `simlock worker undrain` cleared that flag. Nothing else ends a drain: the flag lives in the gateway's persisted worker registry, so it survives both a worker reconnect and a gateway restart | WorkerRegistry | implemented | +| `request.dispatched` | `{ requestId, workerId, requesterId, platform, model, reason, queuedMs }` — `reason` is the routing policy's own `warm-hit`/`free-capacity` distinction (ADR 0005 §13), `queuedMs` how long the request sat queued before this dispatch | the gateway's fleet queue sent a queued request to a worker with `noWait: true`, and the worker took it — the grant itself, or its first `progress` push, whichever arrives first (ADR 0005 §11: device work having started means the request is that worker's now). An immediate `NO_CAPACITY` is a stale view, not a dispatch, and emits nothing — the request stays queued and is retried on the next pass | FleetLeaseCoordinator | implemented | + +Drain and undrain are idempotent, and an event is a fact about a *change*: +draining an already-drained worker succeeds and emits nothing. + +`worker.rejected` exists because the alternative is silence (ADR 0005 §22): a +worker whose credential is refused produces no `worker.connected`, and +without this fact an operator staring at `simlock worker list` sees a machine +that simply never appears, with nothing anywhere to say why. It is +deliberately *not* a `worker.disconnected` with another reason — nothing +connected, so nothing disconnected, and a fact whose subject never existed +should not borrow the vocabulary of one that did. + +**A protocol mismatch is neither of those.** That uplink presented a valid +join token and authenticated; what failed was `hello`'s range negotiation. So +the worker *does* enter the registry, with `state: "incompatible"` and both +ranges on its view, visible in `simlock worker list` — which is the whole +point, since that is the machine an operator has to go and upgrade. It is +simply never dispatched to, and no `worker.connected` follows, because +nothing usable connected. That is also why `incompatible` is not one of +`worker.disconnected`'s reasons: an incompatible worker was never a connected +worker to lose. + +**`device.exec` emits no event, and that is deliberate.** It is the one +operation here with no fact of its own. Running a command against a device is +not a state change simlock owns — the lease that authorizes it already +emitted `lease.granted`, the device's own state is untouched, and a fleet +where every `adb shell input tap` produced a bus event would push everything +else out of a 1000-entry ring buffer within minutes. An audit trail of what +agents ran on their devices is a different feature with different retention +needs, not a line in this catalogue. + +**Every worker's own business events are republished on the gateway's bus** +with `workerId` added to the payload, under their original names and with +their original emitting module — the fact happened in that worker's lease +engine or reaper, and rewriting either would make the audit trail lie about +where. That is what makes `simlock events` and `simlock events --follow` +against a gateway a fleet-wide view (`lease.granted`, `device.ready`, +`cleanup.executed`, and the rest, each naming the machine it happened on), +and it is the one place a payload documented above arrives with an extra +field: additive, and only ever on a gateway. The seven events in this +section's own table are the gateway's own, and carry no `workerId` beyond +the worker they are about. + +Two consequences of relaying rather than owning: the gateway's ring buffer +only holds what arrived while its uplinks were up (a worker's events from +before it connected are not backfilled), and a worker's own +`simlock events` keeps showing exactly what it always did, un-prefixed and +unaware that anything is watching. + +A relayed `lease.expired`/`lease.released`/`device.crash-detected`/ +`device.recovered` names the *worker's own* lease id in its payload, not the +gateway's — `GatewayOwnerRoutedFacts` (the gateway's `OwnerRoutedFacts`) is +what resolves the gateway's own lease id, and the `ownerId` to route the +corresponding `lease-lost`/`device-unhealthy`/`device-recovered` push by, +from the fleet lease index rather than the relayed payload directly. The +payload's own `ownerId` is correct for a worker's own local lease (the +worker never had a reason to touch it), but for a gateway-issued one it is +whatever that worker echoed back of what the gateway forwarded when it +granted the lease (ADR §27a) — round-tripped through a machine this gateway +does not control, not a value it minted itself, so it is resolved from the +index (which recorded the real answer at grant time) rather than trusted +verbatim off the wire. + +## Conventions recap + +- Every event carries: `timestamp`, `event`, `payload`, emitting module. +- Events are appended to a ring buffer that powers `simlock events --follow` + and serves as the audit trail. diff --git a/docs/IDEAS.md b/docs/internal/IDEAS.md similarity index 98% rename from docs/IDEAS.md rename to docs/internal/IDEAS.md index 64b042b7a..6db9a32f9 100644 --- a/docs/IDEAS.md +++ b/docs/internal/IDEAS.md @@ -65,13 +65,13 @@ Store internally) would let the driver resolve the exact newest compatible patch release instead of gambling on the major matching a real build. Not pursued in v1: parsing an undocumented, Apple-controlled catalog format is a maintenance burden disproportionate to the edge case it closes (see -`docs/known-pitfalls.md`, "Component downloads"). +`docs/internal/KNOWN-PITFALLS.md`, "Component downloads"). ## Requester-visible download progress Neither driver's install (`xcodebuild -downloadPlatform`, `sdkmanager --install`) currently reaches the requesting connection's progress stream — -see `docs/known-pitfalls.md` ("no progress push"). Closing this needs a +see `docs/internal/KNOWN-PITFALLS.md` ("no progress push"). Closing this needs a `downloading` stage on `LeaseProgress` (`src/core/wait-queue.ts`) and a `Driver.resolveSpec` progress callback both drivers implement, threaded through `LeaseAcquisitionCoordinator#resolveAndDrive` the same way diff --git a/docs/known-pitfalls.md b/docs/internal/KNOWN-PITFALLS.md similarity index 98% rename from docs/known-pitfalls.md rename to docs/internal/KNOWN-PITFALLS.md index c38717e75..cf35fff40 100644 --- a/docs/known-pitfalls.md +++ b/docs/internal/KNOWN-PITFALLS.md @@ -30,7 +30,7 @@ or a socket hiccup no longer costs a live holder its device. `ttlMs` on a request) bounds it for one lease. Both are worth lowering in a CI-shaped fleet where holders are killed routinely; both cost more renew traffic and a tighter deadline for a holder that stalls. See -[CONFIGURATION.md](CONFIGURATION.md). +[CONFIGURATION.md](../CONFIGURATION.md). ## Orphaned lease holders (resolved) @@ -124,7 +124,7 @@ misbehaving. **Fix (#21):** a failed purge now commits the device to `quarantined` instead of readiness-checking it back into circulation. `quarantined` is a shared "present in the registry, counts against running capacity, not grantable" -disposition (see `docs/ARCHITECTURE.md`, "Quarantine: present but not +disposition (see `docs/internal/ARCHITECTURE.md`, "Quarantine: present but not grantable") — `AcquisitionPlanner` and the warm-pool eviction helpers select targets by exact state, so a quarantined device is simply invisible to every grant path with no special-casing required. `QuarantineCoordinator` retries @@ -135,7 +135,7 @@ destroys it (registry-only, as always). The device stays visible as `quarantined` in `simlock status` and `simlock list --devices` throughout. `device.purge-failed` still fires as before; `device.quarantined`, `device.quarantine-recovered`, and `device.quarantine-abandoned` are the new -follow-up facts (see `docs/EVENTS.md`). +follow-up facts (see `docs/internal/EVENTS.md`). ## Device roots are an accident boundary, not a security boundary @@ -177,7 +177,7 @@ is a device id, on a surface that changes with the platform tools rather than with simlock. A parser that is wrong in the permissive direction refuses nothing extra; one that is wrong in the strict direction refuses commands that were always fine. The verbs simlock *does* refuse -([CLI.md](CLI.md)) are the ones that move a device's lifecycle behind the +([CLI.md](../CLI.md)) are the ones that move a device's lifecycle behind the registry's back or escape containment altogether — `adb kill-server`, `simctl delete` — which is a judgement about what an action does, not about identity. adb's server-scope globals are handled differently, and more @@ -289,7 +289,7 @@ download: unbounded models (no `maxRuntimeVersion` cap) get a plain older device type whose newest compatible runtime is a specific release) gets `-buildVersion ` — just the major version number, since the exact patch release isn't known offline (Apple's -downloadables index isn't parsed in v1; see `docs/IDEAS.md`). If Xcode +downloadables index isn't parsed in v1; see `docs/internal/IDEAS.md`). If Xcode doesn't have a build matching that bare major version, the download fails and the caller is told to pass `--os ` explicitly rather than retrying blind. @@ -374,7 +374,7 @@ client is absent between calls by construction, so something has to hold the fact until it comes back, and today that something lives in the frontend. A daemon restart loses in-flight lease-request tracking state and buffered notices the same way it always did pre-ADR 0003 — see [Lifecycle -semantics](HTTP-API.md#lifecycle-semantics) for the documented recovery loop +semantics](../HTTP-API.md#lifecycle-semantics) for the documented recovery loop (`404` → re-request → maybe `409` → `GET`), which exists specifically because the tracker does not survive a restart. @@ -514,7 +514,7 @@ this away; sizing it around "the daemon's own uid" does not. **Why this is not being fixed by parsing arguments:** the same reasoning the adb/simctl scans themselves rely on (safety rule 9, "fail closed") argues -against it here too — `docs/adr/0005-gateway-and-worker-modes.md` §19a is +against it here too — `docs/internal/adr/0005-gateway-and-worker-modes.md` §19a is explicit that arguments are accident-boundary scoping, not a security boundary, the same distinction ADR 0001 draws for the local passthrough wrappers this operation reuses. A grammar that tried to refuse "device paths @@ -524,7 +524,7 @@ adds), and a guess that misses one is worse than no guess, since it reads as a promise this API does not keep. **Status:** accepted, and now said plainly rather than left to be discovered -— see the [Authentication](HTTP-API.md#authentication) section of +— see the [Authentication](../HTTP-API.md#authentication) section of `HTTP-API.md`, which an operator sizing a worker's trust boundary should read before handing an `agent` token to anything they would not otherwise let run on that machine. @@ -606,7 +606,7 @@ follow-up to `device.exec`. `ios.slim` (opt-in, default off) has the iOS driver disable ~170 launchd daemons across simulator daemon categories to cut RAM/CPU footprint (see -[CONFIGURATION.md](CONFIGURATION.md)). It carries four trade-offs worth +[CONFIGURATION.md](../CONFIGURATION.md)). It carries four trade-offs worth knowing before turning it on. **Every reclaim pays two boots, indefinitely.** `IosSimctlDriver.reclaim` diff --git a/docs/adr/0001-simlock-owned-device-roots.md b/docs/internal/adr/0001-simlock-owned-device-roots.md similarity index 100% rename from docs/adr/0001-simlock-owned-device-roots.md rename to docs/internal/adr/0001-simlock-owned-device-roots.md diff --git a/docs/adr/0002-opt-in-slim-ios-simulators.md b/docs/internal/adr/0002-opt-in-slim-ios-simulators.md similarity index 99% rename from docs/adr/0002-opt-in-slim-ios-simulators.md rename to docs/internal/adr/0002-opt-in-slim-ios-simulators.md index 396b79867..113a58e5a 100644 --- a/docs/adr/0002-opt-in-slim-ios-simulators.md +++ b/docs/internal/adr/0002-opt-in-slim-ios-simulators.md @@ -218,7 +218,7 @@ proceeds. Only a genuine inability to bring the device back up propagates. `--full` request match nothing until the idle cleanup rules reap them. **Safety review.** Compatible with every invariant in -`docs/agent-rules/safety.md`: registry-only targets, never a leased device, +`docs/internal/agent-rules/safety.md`: registry-only targets, never a leased device, no downloads, destruction only through the existing `erase` path, every pass attributable through `device.slimmed`. diff --git a/docs/adr/0003-one-typed-daemon-contract-behind-every-frontend.md b/docs/internal/adr/0003-one-typed-daemon-contract-behind-every-frontend.md similarity index 100% rename from docs/adr/0003-one-typed-daemon-contract-behind-every-frontend.md rename to docs/internal/adr/0003-one-typed-daemon-contract-behind-every-frontend.md diff --git a/docs/adr/0004-ttl-first-leases-on-every-transport.md b/docs/internal/adr/0004-ttl-first-leases-on-every-transport.md similarity index 98% rename from docs/adr/0004-ttl-first-leases-on-every-transport.md rename to docs/internal/adr/0004-ttl-first-leases-on-every-transport.md index 16017df5c..0991d876b 100644 --- a/docs/adr/0004-ttl-first-leases-on-every-transport.md +++ b/docs/internal/adr/0004-ttl-first-leases-on-every-transport.md @@ -96,7 +96,7 @@ for a `ttlMs` on the wrong mode are all costs of that one coupling. release-on-close, ADR 0003 §8) is deleted. - `lease.granted` loses `mode` and `lease.released` loses the `closed` and `orphaned` reasons, since neither concept exists any more. This is a - deliberate exception to `docs/agent-rules/events.md` rule 6 (additive + deliberate exception to `docs/internal/agent-rules/events.md` rule 6 (additive payloads only), taken once while the package is 0.x; `EVENTS.md` notes it. - The HTTP API's "additive evolution only" promise takes the same kind of @@ -119,7 +119,7 @@ for a `ttlMs` on the wrong mode are all costs of that one coupling. - Breaking for 0.x: `lease.heartbeat` and `mode` leave the contract; three config keys are renamed or removed (`simlock config` warns on the old names). `docs/CLI.md`, `docs/CLIENT.md`, `docs/HTTP-API.md`, - `docs/CONFIGURATION.md`, and `docs/ARCHITECTURE.md` ("Leases") are + `docs/CONFIGURATION.md`, and `docs/internal/ARCHITECTURE.md` ("Leases") are rewritten in the same change. - `StartupConverger`'s orphan sweep goes away: there are no held leases to release at start. Startup restores every lease's TTL timer from its diff --git a/docs/adr/0005-gateway-and-worker-modes.md b/docs/internal/adr/0005-gateway-and-worker-modes.md similarity index 99% rename from docs/adr/0005-gateway-and-worker-modes.md rename to docs/internal/adr/0005-gateway-and-worker-modes.md index d6da05618..dce6e93a0 100644 --- a/docs/adr/0005-gateway-and-worker-modes.md +++ b/docs/internal/adr/0005-gateway-and-worker-modes.md @@ -29,7 +29,7 @@ to. To a client, a gateway looks like a single, larger simlock. Simlock coordinates agents on **one** machine. A team that owns several Macs (each with its own simlock daemon) has to hand each agent a specific host, watch each host separately, and rebalance by hand when one fills up while -another sits idle. `docs/IDEAS.md` records "cross-machine coordination" as +another sits idle. `docs/internal/IDEAS.md` records "cross-machine coordination" as deliberately out of scope for v1; the HTTP API (`docs/HTTP-API.md`, "Not implemented") reserved room for "multi-host brokering" without designing it. The web console (#88) is explicitly one console per daemon for the same @@ -595,7 +595,7 @@ drive the device it leased. workers it knows and which are drained — because drain is an operator's intent and not an observation; nothing about a *lease* is written there. 6. **Capacity and safety stay on the worker.** The gateway never touches a - device, so every rule in `docs/agent-rules/safety.md` keeps holding by + device, so every rule in `docs/internal/agent-rules/safety.md` keeps holding by construction: registry-only destruction, never touching a leased device, no implicit downloads (the gateway forwards `allowDownload` and the worker clamps it through its own policy). @@ -659,7 +659,7 @@ drive the device it leased. to configure — so unlike two *workers* on one machine there is no `drivers.android.adbServerPort` to split. - `docs/HTTP-API.md` gains the `/v1/workers` routes and the uplink endpoint, - and drops "multi-host brokering" from "Not implemented"; `docs/IDEAS.md` + and drops "multi-host brokering" from "Not implemented"; `docs/internal/IDEAS.md` drops "Cross-machine coordination"; #88 drops its "one console per daemon" non-goal. - Sequencing, one PR each, each leaving the tree working, after ADR 0004 diff --git a/docs/adr/README.md b/docs/internal/adr/README.md similarity index 100% rename from docs/adr/README.md rename to docs/internal/adr/README.md diff --git a/docs/agent-rules/architecture.md b/docs/internal/agent-rules/architecture.md similarity index 100% rename from docs/agent-rules/architecture.md rename to docs/internal/agent-rules/architecture.md diff --git a/docs/internal/agent-rules/documentation.md b/docs/internal/agent-rules/documentation.md new file mode 100644 index 000000000..1f6fcae5a --- /dev/null +++ b/docs/internal/agent-rules/documentation.md @@ -0,0 +1,50 @@ +# Agent rules: documentation + +Rules for anyone (human or agent) writing or editing documentation, or any +user-visible string the CLI/HTTP API/MCP server prints. Violating these is +grounds for rejecting a change even if the prose reads well. + +1. **There are two audiences, and they get two directories.** `docs/` is for + end users of the built tool — someone who installed `simlock` and wants to + use, configure, or integrate with it. `docs/internal/` (plus `AGENTS.md` at + the repo root) is for maintainers and coding agents changing simlock + itself — architecture, ADRs, agent rules, known pitfalls, and future ideas. + Before adding a new doc file, decide which reader it is for and put it in + the matching directory; do not add a third category. +2. **An end-user doc never cites an ADR, and never links into + `docs/internal/`.** A reader installing and using the tool does not need + to know a decision record exists, why it was made, or what its number is. + If a sentence's only content is "see ADR NNNN" or "see ARCHITECTURE.md", + either state the fact directly and drop the citation, or delete the + sentence — never leave a dangling reference to an internal doc standing in + for an explanation. This applies to `docs/ABOUT.md`, `docs/CLI.md`, + `docs/CLIENT.md`, `docs/CONFIGURATION.md`, `docs/HTTP-API.md`, + `docs/EVENTS.md`, and `README.md`. +3. **Nothing the running tool prints or returns ever names a file path in + this repository.** `--help` text, usage banners, error messages, and HTTP + error bodies must not tell a user to go read a specific markdown file — + that file may not exist for someone who installed from a package registry + rather than cloned the repo, and even when it does, a bare relative path + means nothing outside a checkout. Point at the GitHub repository itself + (e.g. the `homepage`/`repository` URL in `package.json`) if a pointer is + useful at all, or say the thing directly instead of pointing anywhere. +4. **A doc that genuinely serves both audiences gets split, not shared.** + `docs/EVENTS.md` (end-user: event names, payloads, when they fire — the + catalog `simlock events` output is checked against) and + `docs/internal/EVENTS.md` (maintainer: the same catalog plus the ADR + citations, authoring-rule cross-references, and design rationale behind + each row) are the model. When a new event is added, update both in the + same change — the end-user table and the internal one — rather than + letting one drift into the authoritative copy and the other into a stale + mirror. +5. **Casing is a directory-level convention, and new files match their + neighbors.** The top-level files directly under `docs/` and directly under + `docs/internal/` are `UPPER-CASE.md`. `docs/internal/adr/` and + `docs/internal/agent-rules/` are their own established `lower-case.md` + namespaces (ADR numbers, agent-rule topics) — match whichever directory a + new file lands in, don't introduce a third casing style. +6. **A link that crosses `docs/` and `docs/internal/` needs the right + relative prefix**, and it only ever runs in one direction: from + `docs/internal/` out to `docs/` (e.g. `../CLIENT.md`) is fine — a + maintainer doc pointing at the user-facing reference for the same + feature. From `docs/` into `docs/internal/` is never fine (see rule 2). diff --git a/docs/agent-rules/events.md b/docs/internal/agent-rules/events.md similarity index 100% rename from docs/agent-rules/events.md rename to docs/internal/agent-rules/events.md diff --git a/docs/agent-rules/safety.md b/docs/internal/agent-rules/safety.md similarity index 100% rename from docs/agent-rules/safety.md rename to docs/internal/agent-rules/safety.md diff --git a/docs/agent-rules/testing.md b/docs/internal/agent-rules/testing.md similarity index 100% rename from docs/agent-rules/testing.md rename to docs/internal/agent-rules/testing.md diff --git a/docs/loop.md b/docs/loop.md index 569fef0fb..e58bc57c5 100644 --- a/docs/loop.md +++ b/docs/loop.md @@ -5,7 +5,7 @@ specifications have been removed from `docs/stages/`. ## Phase 0 — Orient -1. Read `AGENTS.md`, all of `docs/agent-rules/`, and `docs/ARCHITECTURE.md`. +1. Read `AGENTS.md`, all of `docs/internal/agent-rules/`, and `docs/internal/ARCHITECTURE.md`. The agent rules are binding; architecture violations are defects even if tests pass. 2. Read the relevant stage specification and confirm every stage it depends on @@ -31,7 +31,7 @@ specifications have been removed from `docs/stages/`. 7. Scope discipline: implement ONLY your stage. No future-stage work, no speculative abstractions. If you find a genuine gap that a later stage needs, leave a `TODO(stage-NN):` marker and mention it in your report. -8. New events → update `docs/EVENTS.md` in the same change (events rule 8). +8. New events → update `docs/internal/EVENTS.md` in the same change (events rule 8). New external dependency → its port first (architecture rule 9). New runtime npm dependency → forbidden unless your stage file explicitly allows it. @@ -41,10 +41,10 @@ specifications have been removed from `docs/stages/`. 9. Run `pnpm check` (typecheck + lint + all tests, not just yours). 10. Read your full diff (`git diff`) as a reviewer, checking: - every acceptance criterion in the stage file, one by one; - - every rule in `docs/agent-rules/architecture.md`, `events.md`, + - every rule in `docs/internal/agent-rules/architecture.md`, `events.md`, `safety.md` against the new code; - the stage's "Watch out" list; - - test quality, against `docs/agent-rules/testing.md` — which is the + - test quality, against `docs/internal/agent-rules/testing.md` — which is the binding statement of it; this file is historical and does not restate it. 11. Fix every issue found, then re-run `pnpm check`. Repeat until a review diff --git a/e2e/README.md b/e2e/README.md index 8e5ea5556..0a183484a 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -58,7 +58,7 @@ running test body silently never fires — see the comment in `helpers/env.ts`. every attempt so far: a daemon occasionally outlives `daemon stop` and trips teardown's stray-process assertion, and the no-implicit-download flow has hit its 300s timeout. Not yet root-caused, and not yet distinguished from the - reclaim stall recorded in [../docs/known-pitfalls.md](../docs/known-pitfalls.md). + reclaim stall recorded in [../docs/internal/KNOWN-PITFALLS.md](../docs/internal/KNOWN-PITFALLS.md). Treat the slow lane as a manual, one-flow-at-a-time tool until that is fixed. - `daemon status` ignores `--json` and always prints raw JSON; documented by an `it.fails` in `daemon-lifecycle.test.ts`. diff --git a/e2e/contract-surface.test.ts b/e2e/contract-surface.test.ts index db93eb3f5..de20cb5c7 100644 --- a/e2e/contract-surface.test.ts +++ b/e2e/contract-surface.test.ts @@ -11,7 +11,7 @@ import type { TestEnv } from "./helpers/env.js"; * * Every other flow in this suite drives one feature through the CLI. This one asks a * different question: is each operation the contract *declares* reachable at all? Nothing - * else answers it. `docs/adr/0003` §2 splits an operation across three places -- the + * else answers it. `docs/internal/adr/0003` §2 splits an operation across three places -- the * `OPERATIONS` registry, a `case` in `DaemonServer`'s hand-written socket switch, and a * handler in the `Dispatcher` -- and only the last of those is checked by the compiler. * A declaration whose switch case was never written falls through to `default:` and diff --git a/e2e/gateway-fleet.test.ts b/e2e/gateway-fleet.test.ts index 28889dfe5..413548bb3 100644 --- a/e2e/gateway-fleet.test.ts +++ b/e2e/gateway-fleet.test.ts @@ -183,7 +183,7 @@ describe("gateway fleet", () => { // fleet is #118's, not this PR's), well after its `events.subscribe` was established at // connect. `module` is asserted as `lease-lifecycle` -- the emitting engine's own name, // unchanged by republishing -- specifically because it is not one of the six subjects - // `docs/EVENTS.md` calls "the gateway's own" (`worker.*`), so this cannot be satisfied by + // `docs/internal/EVENTS.md` calls "the gateway's own" (`worker.*`), so this cannot be satisfied by // a gateway-authored fact that merely happens to name worker B. const events = await gateway.events(); const connectedFacts = events.filter((event) => event.event === "worker.connected"); diff --git a/e2e/mcp-session.test.ts b/e2e/mcp-session.test.ts index 2ab06d8e4..d4b21bfff 100644 --- a/e2e/mcp-session.test.ts +++ b/e2e/mcp-session.test.ts @@ -93,7 +93,7 @@ describe("MCP session semantics", () => { expect(warning.logger).toBe("simlock"); expect(warning.level).toBe("warning"); // `killed`: an operator took the lease away, which is not the same fact as its holder - // releasing it (docs/EVENTS.md, and `Dispatcher#leaseReleaseAll`). + // releasing it (docs/internal/EVENTS.md, and `Dispatcher#leaseReleaseAll`). expect(warning.data).toMatchObject({ deviceId: expect.any(String), leaseId: leased.lease.id, diff --git a/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index f822cf6d4..ce6e88b3a 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -279,7 +279,7 @@ describe.skipIf(process.platform !== "darwin")( "machine (26.4.1, 27.0) are >= 18.5", ).toEqual([]); - // --- scenario 3: release, then re-lease the same spec. Per docs/known-pitfalls.md + // --- scenario 3: release, then re-lease the same spec. Per docs/internal/KNOWN-PITFALLS.md // ("Every reclaim pays two boots, indefinitely"), IosSimctlDriver.reclaim always runs // `simctl erase`, wiping the launchctl overrides -- so the documented behaviour is // that the warm-pooled device comes back stock and pays a SECOND device.slimmed, not @@ -301,7 +301,7 @@ describe.skipIf(process.platform !== "darwin")( expect( slimmedAfterRelease.length, "expected a SECOND device.slimmed for this udid after release+re-lease, per the " + - "documented erase-on-reclaim cost (docs/known-pitfalls.md)", + "documented erase-on-reclaim cost (docs/internal/KNOWN-PITFALLS.md)", ).toBe(slimmedBefore + 2); await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); @@ -447,7 +447,7 @@ describe.skipIf(process.platform !== "darwin")( // The SDK's default request timeout is 60s; a cold slim lease takes ~160s on this // machine (two real boots). Simlock relays boot progress as MCP progress // notifications, so a client that resets its timeout on progress survives it -- - // which is what a real agent's client must do too (see docs/known-pitfalls.md). + // which is what a real agent's client must do too (see docs/internal/KNOWN-PITFALLS.md). const leaseCallOptions = { resetTimeoutOnProgress: true, timeout: 600_000 }; const fullResult = await mcp.client.callTool( { diff --git a/src/bus/index.ts b/src/bus/index.ts index d44d58284..5d006e7a4 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -238,7 +238,7 @@ export interface EventMap { * work having started means the request is that worker's now). A `NO_CAPACITY` refusal is a * stale view, not a dispatch, and emits nothing -- the request stays queued. * - * C2 (round 2 review): widened back to what `docs/EVENTS.md` always specified for this row -- + * C2 (round 2 review): widened back to what `docs/internal/EVENTS.md` always specified for this row -- * `requesterId`/`platform`/`model` so the fact is self-contained (events rule 6) rather than * naming only the gateway-internal `requestId`, `reason` (the routing policy's own warm-hit / * free-capacity distinction, already computed by `RoutingPolicy#select` and previously diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 63ae0557c..28536a9ec 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2881,7 +2881,7 @@ describe("CLI: pure helpers", () => { // Round 4, test-title finding 3: the "remote passthrough" suite's own stdin test injects // `readStdin` directly and never exercises this function at all -- documented in -// `docs/known-pitfalls.md` as an unbounded read, and until now entirely untested. +// `docs/internal/KNOWN-PITFALLS.md` as an unbounded read, and until now entirely untested. describe("readPipedStdin", () => { function fakeStdin(chunks: readonly string[], isTTY: boolean): typeof process.stdin { const stream = Readable.from(chunks); diff --git a/src/cli/index.ts b/src/cli/index.ts index 78421d34b..f2dff4e98 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -58,7 +58,7 @@ Commands: Run 'simlock --help' for command usage. Pass --token anywhere on the command line to connect as admin -explicitly; see docs/CLI.md#admin-credential-resolution for the default +explicitly; see https://github.com/callstackincubator/simlock for the default resolution order.`; /** @@ -471,7 +471,7 @@ export function buildCliEnvironment( * so there is nowhere to send a partial one, and a caller whose stdin is a pipe nothing ever * closes (an inherited, never-redirected pipe in CI) hangs here with no timeout -- see * "`simlock simctl` / `simlock adb` can hang forever reading a piped stdin" in - * `docs/known-pitfalls.md`. Accepted deliberately, not an oversight. + * `docs/internal/KNOWN-PITFALLS.md`. Accepted deliberately, not an oversight. */ export async function readPipedStdin(): Promise { if (process.stdin.isTTY === true) return undefined; @@ -936,7 +936,7 @@ async function runLease( // `BAD_REQUEST` rather than being clamped here to a value the caller did not write. const ttlMs = typeof values.ttl === "string" ? parseDuration(values.ttl) : undefined; // A holder watches its parent so a crashed agent's backgrounded `simlock lease` - // self-terminates instead of surviving reparenting (docs/known-pitfalls.md) -- the one + // self-terminates instead of surviving reparenting (docs/internal/KNOWN-PITFALLS.md) -- the one // failure a TTL cannot bound, because a reparented holder keeps renewing. `--bind-pid` // overrides which pid that is, for a holder spawned from a short-lived subshell whose // immediate parent dies before the agent does. diff --git a/src/client/index.ts b/src/client/index.ts index 8dcb7d370..9d153f039 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -65,7 +65,7 @@ export interface ConnectSimlockOptions { * session. Rejects with a `SimlockError` (`PROTOCOL_VERSION_UNSUPPORTED`, * `ADMIN_AUTHENTICATION_FAILED` never applies here since no credential is sent, * `DAEMON_CONNECTION_LOST` if the socket cannot be reached) without ever restarting the - * daemon -- see `docs/adr/0003-...md` §6. */ + * daemon -- see `docs/internal/adr/0003-...md` §6. */ export async function connectSimlock(options: ConnectSimlockOptions): Promise { const resolved: ConnectOptions = { ...(options.connection === undefined ? {} : { connection: options.connection }), diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index bf2296376..165f58c62 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -348,7 +348,7 @@ export const nukeReportSchema = z.object({ /** * Mirrors `EventEnvelope` (src/bus/index.ts) at the envelope level only. `event` stays a plain * string and `payload` stays `z.unknown()` rather than redeclaring all ~30 `EventMap` payload - * shapes here -- see docs/EVENTS.md for the authoritative catalog. This is a deliberate, + * shapes here -- see docs/internal/EVENTS.md for the authoritative catalog. This is a deliberate, * documented simplification: re-declaring every business event's payload shape a second time, * next to `events.md`'s existing documentation requirement, is a lot of near-duplicate surface * for a channel this PR does not change the routing of. Tightening this (e.g. a discriminated diff --git a/src/core/device-root.ts b/src/core/device-root.ts index 4d1b144bd..de5bff910 100644 --- a/src/core/device-root.ts +++ b/src/core/device-root.ts @@ -10,7 +10,7 @@ const ROOT_MODE = 0o700; /** * Why a root was refused. These strings are wire-visible: they travel in the - * `driver.root-rejected` event payload and are listed in `docs/EVENTS.md`, so the + * `driver.root-rejected` event payload and are listed in `docs/internal/EVENTS.md`, so the * vocabulary is fixed and a new one cannot be invented here alone. */ export type RootRejectionReason = diff --git a/src/core/driver.ts b/src/core/driver.ts index bdfa3c1e3..fd304630d 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -190,7 +190,7 @@ export interface Driver { * The requester on whose behalf this resolution runs, when known. Optional: a caller that * resolves outside of a lease request (e.g. a driver revalidating its own cached spec) has * no requester to attribute. Threaded through to a driver's component-install diagnostics - * so the resulting `component.install-*` events carry it -- see `docs/EVENTS.md`. + * so the resulting `component.install-*` events carry it -- see `docs/internal/EVENTS.md`. */ readonly requesterId?: string; }, @@ -236,7 +236,7 @@ export interface Driver { leaseEnvironment(): Readonly>; /** * Releases whatever this driver holds outside its own process -- Android supervises an - * adb server it must reap by pid, since nothing else can (`docs/known-pitfalls.md`). + * adb server it must reap by pid, since nothing else can (`docs/internal/KNOWN-PITFALLS.md`). * Optional because most drivers hold nothing; the daemon calls it on every shutdown * path and never lets a failure here abort the rest of one. */ @@ -337,7 +337,7 @@ type DriverRejectionEvent = "driver.root-rejected" | "driver.adb-server-rejected /** * Why Simlock's own adb server could not be established. Wire-visible, like the root * reasons: these travel in the `driver.adb-server-rejected` payload and are listed in - * `docs/EVENTS.md`, so the vocabulary is fixed and closed. + * `docs/internal/EVENTS.md`, so the vocabulary is fixed and closed. * * It sits beside the event names rather than in `drivers/android` because the two are one * contract: the core publishes neither without the other, and a driver module cannot be @@ -356,7 +356,7 @@ export type DriverRejectionReason = RootRejectionReason | AdbServerRejectionReas * One refusal, with the payload the event it names is published with. * * The pairing is the point. The core forwards `payload` to the bus without reading it, so - * this is the only place the wire contract in `docs/EVENTS.md` can still be checked -- a + * this is the only place the wire contract in `docs/internal/EVENTS.md` can still be checked -- a * wider `Record` would type-check an adb rejection carrying a * string port, or a root rejection with no root at all, and it would reach * `simlock events --json` unexamined. diff --git a/src/core/warm-pool-coordinator.ts b/src/core/warm-pool-coordinator.ts index a1a125d2c..01735e250 100644 --- a/src/core/warm-pool-coordinator.ts +++ b/src/core/warm-pool-coordinator.ts @@ -142,7 +142,7 @@ export class WarmPoolCoordinator { /** * Hands the release-time purge failure to the quarantine coordinator instead * of readiness-checking the device back into circulation: the first warm-pool - * version did that (see docs/known-pitfalls.md) so a dirty device could still + * version did that (see docs/internal/KNOWN-PITFALLS.md) so a dirty device could still * be leased, which is exactly the confusing failure mode quarantine replaces. */ async #recoverPurgeFailure( diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 05b24406f..888858690 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -583,7 +583,7 @@ describe("Dispatcher: ownership", () => { // Review finding S9: `Dispatcher#leaseReleaseAll` and `#nukeRun` were exercised by no test // anywhere (`nuke.run` appeared in `server.test.ts` only inside a comment) -- both are -// admin-only and destructive, which is exactly what `docs/agent-rules/safety.md` rules 1 +// admin-only and destructive, which is exactly what `docs/internal/agent-rules/safety.md` rules 1 // ("registry-only destruction") and 5 ("destructive CLI commands confirm or require --yes") are // about. `--yes`/confirmation is a CLI-layer concern (not this dispatcher's), but role // enforcement and "it actually destroys only what it should" are, and neither had coverage. @@ -626,7 +626,7 @@ describe("Dispatcher: lease.release-all", () => { expect(new Set(result.leaseIds)).toEqual(new Set([first.lease.id, second.lease.id])); expect(registry.snapshot.leases).toHaveLength(0); - // `killed`, not `explicit`: nobody's holder asked for this (docs/EVENTS.md), and that is + // `killed`, not `explicit`: nobody's holder asked for this (docs/internal/EVENTS.md), and that is // the distinction a `lease-lost` reader acts on. expect( eventBus diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 4c9067644..8ed9ece21 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -371,7 +371,7 @@ export class Dispatcher { }; /** - * `killed`, not `explicit`: `docs/EVENTS.md` splits the two by who ended the lease and + * `killed`, not `explicit`: `docs/internal/EVENTS.md` splits the two by who ended the lease and * whether its holder asked. An operator's `simlock release --all` (and `nuke`, which already * reports `killed` through `NukeService`) takes leases away from holders that never asked -- * which is exactly what a `lease-lost` reader needs to tell apart from the holder's own diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 568e7f658..701e092c0 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -572,7 +572,7 @@ describe("discoverDrivers", () => { expect(rejections.map((rejection) => rejection.platform)).toEqual(["ios"]); }); - it("publishes the refusal as the payload docs/EVENTS.md documents for driver.root-rejected", async () => { + it("publishes the refusal as the payload docs/internal/EVENTS.md documents for driver.root-rejected", async () => { const filesystem = await foreignOwnedRoot(); const refusal = await refusedRoot(filesystem); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 285760f06..23713a7e0 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -1040,7 +1040,7 @@ export function emitComponentInstallDiagnostic( * (architecture rule 5) -- this is the one place, at driver construction, that bridges the * driver's `onSlimmed` callback to a post-commit fact for observers (`simlock events`, and the * durable-log subscription in `startDaemon`). A *skipped* slim is deliberately not bridged here - * -- see `onSlimSkipped` in `discoverDrivers`, which logs it instead (see `docs/EVENTS.md`). + * -- see `onSlimSkipped` in `discoverDrivers`, which logs it instead (see `docs/internal/EVENTS.md`). */ export function emitSlimDiagnostic(eventBus: Pick): (fact: SlimmedFact) => void { return (fact) => { diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index cffeec39e..00e558909 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1168,7 +1168,7 @@ describe("DaemonServer startup readiness", () => { // completion before convergence resolves. `start()` must then bail rather than // subscribe to a disposed bus, schedule a heartbeat tick on a dead daemon, and emit // `daemon.started` after `daemon.stopping` (a fact untrue when emitted, which - // `docs/agent-rules/events.md` rule 3 forbids). + // `docs/internal/agent-rules/events.md` rule 3 forbids). const converge = deferred(); const harness = await createHarness({ converge: () => converge.promise, start: false }); const emitted: string[] = []; @@ -1392,7 +1392,7 @@ describe("DaemonServer driver rejections", () => { it("refuses at compile time to pair an event with another event's payload", () => { const rejection: DriverRejection = { event: "driver.adb-server-rejected", - // @ts-expect-error -- `port` is a number on the wire (docs/EVENTS.md). The check has + // @ts-expect-error -- `port` is a number on the wire (docs/internal/EVENTS.md). The check has // to happen where a refusal is written, because the daemon forwards `payload` to the // ring buffer -- and to `simlock events --json` -- without ever reading it. payload: { port: "5038", reason: "occupied" }, diff --git a/src/daemon/server.ts b/src/daemon/server.ts index f773697a1..15a0adb81 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -465,7 +465,7 @@ export class DaemonServer { // and starts the health monitor. Running any of that // against an already-disposed engine would leave timers armed on a dead daemon and would // emit `daemon.started` after `daemon.stopping` -- a fact that is not true when emitted, - // which `docs/agent-rules/events.md` rule 3 forbids. Bail out instead; the stop that + // which `docs/internal/agent-rules/events.md` rule 3 forbids. Bail out instead; the stop that // already ran owns the teardown, so there is nothing left for this call to undo. if (this.#stopping) { this.#logger.info("Daemon converged after a stop was requested; not arming", { diff --git a/src/drivers/android/adb-server.ts b/src/drivers/android/adb-server.ts index 5f0d527c0..063ef1e46 100644 --- a/src/drivers/android/adb-server.ts +++ b/src/drivers/android/adb-server.ts @@ -49,7 +49,7 @@ const SCOPED_ENVIRONMENT = { } as const; /** What `${SIMLOCK_HOME}/adb-server.json` holds: the only handle on a server that outlives us. */ -// fallow-ignore-next-line unused-type -- on-disk contract; documented in docs/known-pitfalls.md and read back by a later daemon. +// fallow-ignore-next-line unused-type -- on-disk contract; documented in docs/internal/KNOWN-PITFALLS.md and read back by a later daemon. export interface AdbServerRecord { readonly pid: number; readonly port: number; diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 2c90d665c..dd0d8fa71 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -263,7 +263,7 @@ const STOPS_A_RUNNING_DEVICE = * refusing them would break every multi-device invocation to prevent nothing, since every * device they can name is one Simlock already manages. What that does mean -- any lease * holder can name any Simlock device on this machine -- is the accident boundary ADR 0001 - * draws, not a hole in this list; see `docs/known-pitfalls.md`. Everything else -- the known + * draws, not a hole in this list; see `docs/internal/KNOWN-PITFALLS.md`. Everything else -- the known * scope flags, `-a`, `--exit-on-write-error`, `--one-device`, `--reply-fd`, and any global a * future adb adds -- is refused in this position, whether or not it turns out to be benign. * diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 315083805..74fb6f6e2 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -487,7 +487,7 @@ describe("FleetLeaseCoordinator dispatch", () => { // undetached: `#withLeaseRequestTimeout` settling `WORKER_UNREACHABLE` only stops the // returned promise from being awaited -- the worker's own still-pending `lease.request` RPC // is never cancelled, and its `onProgress` closure stays live for as long as the worker cares - // to keep pushing. `docs/EVENTS.md` defines `request.dispatched` as "the gateway's fleet queue + // to keep pushing. `docs/internal/EVENTS.md` defines `request.dispatched` as "the gateway's fleet queue // sent a queued request to a worker ... and the worker took it" -- a false past-tense fact for // a request the caller has already been told is `WORKER_UNREACHABLE`. const { clock, coordinator, directory, eventBus, workers } = harness({ @@ -719,7 +719,7 @@ describe("FleetLeaseCoordinator dispatch", () => { const grant = await coordinator.request(REQUEST, requestOptions()); - // C2 (round 2 review): the full self-contained payload `docs/EVENTS.md` specifies -- not + // C2 (round 2 review): the full self-contained payload `docs/internal/EVENTS.md` specifies -- not // just the gateway-internal `requestId`/`workerId` pair. expect(dispatched).toEqual([ { diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index 7e4e0680e..c96549e6e 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -709,7 +709,7 @@ export class FleetLeaseCoordinator { const announceDispatched = (): void => { if (announced) return; announced = true; - // C2 (round 2 review): the full payload `docs/EVENTS.md` always specified for this row -- + // C2 (round 2 review): the full payload `docs/internal/EVENTS.md` always specified for this row -- // see `bus/index.ts`'s own doc comment on why it was narrowed and then restored. const createdAt = this.#createdAt.get(waiter); this.#emit("request.dispatched", { @@ -730,7 +730,7 @@ export class FleetLeaseCoordinator { // a late `progress` push after the timeout had already rejected the waiter still called // `announceDispatched()` and emitted `request.dispatched` for a request this gateway had // already told its caller was `WORKER_UNREACHABLE` -- a false past-tense fact against - // `docs/EVENTS.md`'s own "and the worker took it". Same mechanism as `exec`'s `detached`, not + // `docs/internal/EVENTS.md`'s own "and the worker took it". Same mechanism as `exec`'s `detached`, not // a second bespoke one: flipped by `#withLeaseRequestTimeout`'s own `onTimeout` hook, checked // here before either `announceDispatched()` or `notifyProgress` run. let detached = false; diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index ae447e6b1..b48ba853c 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -209,7 +209,7 @@ describe("GatewayService", () => { // Hardening: a worker's event name is taken on faith from its own `events.subscribe` push -- // `workerId` is merged in last so it cannot be spoofed, but nothing about the protocol proves // the *name* is genuinely the worker's own. Without a guard, a worker (or anything speaking - // its admin protocol) could forge one of the six subjects `docs/EVENTS.md` calls "the + // its admin protocol) could forge one of the six subjects `docs/internal/EVENTS.md` calls "the // gateway's own" -- e.g. `worker.drain-ended` -- straight into the operator's audit trail. it("refuses to republish a worker's event under a name reserved for the gateway itself", async () => { const harness = fleet(); diff --git a/src/gateway/service.ts b/src/gateway/service.ts index a87c2a149..ed8a73097 100644 --- a/src/gateway/service.ts +++ b/src/gateway/service.ts @@ -39,7 +39,7 @@ const DEFAULT_WORKER_REFRESH_INTERVAL_MS = 30_000; * enough of them evicts every other fact an operator comes to `simlock events` for. One second * is short enough that a legitimate operator watching `simlock events --follow` still sees a * refusal essentially the moment it happens, and long enough to collapse a tight retry loop - * (a worker's backoff floor, per `docs/known-pitfalls.md`, is measured in seconds) to about one + * (a worker's backoff floor, per `docs/internal/KNOWN-PITFALLS.md`, is measured in seconds) to about one * event per second regardless of how fast the dials themselves arrive. */ export const REJECTION_COALESCE_WINDOW_MS = 1_000; diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index efc53e98e..a4a6c82ef 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -447,7 +447,7 @@ export class WorkerLink { * Hardening: `envelope.event` is whatever string a worker's own `events.subscribe` push sends * -- a client of this same admin protocol, on a machine this gateway does not otherwise * control -- and `workerId` is merged in last, so it cannot be spoofed, but the *name* is - * taken on faith. Refusing the six subjects `docs/EVENTS.md` calls "the gateway's own" + * taken on faith. Refusing the six subjects `docs/internal/EVENTS.md` calls "the gateway's own" * (`GATEWAY_OWN_EVENTS`) keeps a worker from forging `worker.drain-ended`, `worker.removed`, * etc. into the operator's audit trail -- facts this gateway itself is supposed to be the only * author of. Every other name still forwards unchanged, including ones this gateway's own @@ -478,7 +478,7 @@ export class WorkerLink { } /** - * ADR 0005 §22 / `docs/EVENTS.md`: the six facts only a gateway itself ever emits, about the + * ADR 0005 §22 / `docs/internal/EVENTS.md`: the six facts only a gateway itself ever emits, about the * workers connected to it. Never forwarded from a worker's own event stream (see * `#onWorkerEvent`) -- a worker is a client of the same admin protocol, and nothing about * `events.subscribe` proves the name it pushes is genuinely its own. diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index c2d801501..ba1a59587 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -266,7 +266,7 @@ export class WorkerRegistry { * already accepted. That mismatch becomes visible the moment this worker's `config.get` * answer lands in its view (`WorkerLink#rebuildView`), which is exactly where it is reported * here -- as a log line, not a bus event: an operator configuration warning is not a business - * fact about the fleet (`docs/agent-rules/events.md`), the same reasoning `core/config.ts` + * fact about the fleet (`docs/internal/agent-rules/events.md`), the same reasoning `core/config.ts` * already applies to a worker-only key left in a gateway's config. * * Warned on the transition into the mismatched state (or a change while inside it), never on diff --git a/src/http/app.ts b/src/http/app.ts index 85706ba37..76c7330f1 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -615,7 +615,7 @@ function requireOwnRequest(identity: TokenIdentity, requesterId: string): void { * the list, and `unknownLease` covers both "doesn't exist" and "not yours" the same way * `lease.list` itself does not distinguish them, at 404. This is a deliberate, narrower * divergence than the one S6 fixed for the mutating routes below -- see - * `docs/known-pitfalls.md` ("HTTP single-lease reads answer 404, not 403, for an unowned + * `docs/internal/KNOWN-PITFALLS.md` ("HTTP single-lease reads answer 404, not 403, for an unowned * lease"). */ async function findOwnedLease( deps: HttpGatewayDeps, diff --git a/src/http/errors.ts b/src/http/errors.ts index 8a44fd4d5..1c8b270d3 100644 --- a/src/http/errors.ts +++ b/src/http/errors.ts @@ -27,7 +27,7 @@ export type HttpStatus = 400 | 401 | 403 | 404 | 409 | 422 | 500 | 501 | 503 | 5 * `SimlockErrorCode` union (`src/contract/errors.ts`) -- ADR §7's "a code the client does not * know wraps as `UNKNOWN_DAEMON_ERROR`" applies here: a typed client built against the contract * cannot narrow on any of these four today, only on the raw string inside - * `UNKNOWN_DAEMON_ERROR`'s `details`. See `docs/known-pitfalls.md` ("HTTP error codes outside + * `UNKNOWN_DAEMON_ERROR`'s `details`. See `docs/internal/KNOWN-PITFALLS.md` ("HTTP error codes outside * the closed contract union") for the exact rows this needs. */ export class HttpApiError extends Error { @@ -62,7 +62,7 @@ export function badRequest(message: string): HttpApiError { * meant a client branching on `error.code` alone could not tell "no such request id" from "no * such operation" -- ADR §7 makes codes contract, not message text (S8). `UNKNOWN_LEASE_REQUEST` * is outside the contract's closed union like `UNAUTHENTICATED`/`REQUEST_NOT_CANCELLABLE`/ - * `REQUEST_CANCELLED` below; see `docs/known-pitfalls.md` for what a closed-union fix would + * `REQUEST_CANCELLED` below; see `docs/internal/KNOWN-PITFALLS.md` for what a closed-union fix would * need. */ export function unknownRequest(id: string): HttpApiError { return new HttpApiError(404, "UNKNOWN_LEASE_REQUEST", `Unknown lease request: ${id}`); diff --git a/src/ports/parent-watch.ts b/src/ports/parent-watch.ts index ef570ced9..f8def5bf9 100644 --- a/src/ports/parent-watch.ts +++ b/src/ports/parent-watch.ts @@ -1,7 +1,7 @@ /** * Watches a specific process and notifies once when it exits, so a * process-held CLI lease self-terminates instead of surviving reparenting - * after the agent that launched it dies. See docs/known-pitfalls.md. + * after the agent that launched it dies. See docs/internal/KNOWN-PITFALLS.md. */ export interface ParentWatch { /**