diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e863c81f..064f1ba4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,152 @@ # Changelog +## Unreleased + +ADR 0004 (`docs/adr/0004-ttl-first-leases-on-every-transport.md`): there is +now one kind of lease, on every transport. A lease carries a TTL, and the +only thing that keeps it alive is a client-initiated `lease.renew` arriving +before the deadline — on the unix socket, over HTTP, over MCP, and through a +gateway alike. Held mode is gone as a daemon concept; staying alive to renew +and releasing on exit is now the CLI's and the MCP session's own policy over +an ordinary lease. This is a breaking release for the contract, three config +keys, and one user-visible behaviour; see below. + +ADR 0004 is **Accepted — not yet implemented**: the entries in this section +describe the decided end state, and they land with the PRs that implement it +(the client's renew timers, and the daemon's heartbeat removal, config +rename, and protocol bump). + +### ⚠ BREAKING CHANGES + +- **Contract:** `lease.heartbeat` is removed as an operation, and `heartbeat` + is removed as a `hello` capability. The daemon never pushes to a client to + prove liveness any more; nothing replaces it, because `lease.renew` already + did the job on every transport that has one. +- **`mode` leaves the contract.** `lease.request` no longer accepts it, and the + lease record no longer carries it. `ttlMs` is now accepted on **every** + `lease.request` — supplying it used to be `BAD_REQUEST` for a held lease — + and is capped at `lease.maxTtlMs`, above which a request or a renew is + `BAD_REQUEST` rather than silently clamped. A caller reading `lease.mode` off + a grant now reads `undefined`, which is falsy, not an error; there is nothing + to branch on any more. +- **A body-less renew re-applies the lease's own TTL, not + `lease.defaultTtlMs`.** The lease record stores the `ttlMs` it was granted + with (or last renewed with, when a renew carried one), and `lease.renew` + without a `ttlMs` resets the deadline to now + that width. + `lease.defaultTtlMs` now applies in exactly one place: a `lease.request` that + names no `ttlMs`. A caller that relied on renew snapping every lease back to + the 15-minute default will find a four-hour lease staying four hours wide. +- **`lastRenewedAt` replaces `lastHeartbeatAt` — as a new stored field, not a + rename.** `lastHeartbeatAt` was never persisted: the dispatcher derived it as + `ttlDeadline - heldTtlBackstopMs`, which only worked because every held lease + shared one backstop width. With per-lease TTLs that arithmetic has no answer, + so the daemon now writes `lastRenewedAt` onto the lease record at grant and + on every renew, and `simlock status` renders it as "last renewed". A consumer + reading `lastHeartbeatAt` gets `undefined`. +- **Socket protocol:** moves to protocol 4 with no compatibility shim; the + range a daemon and client advertise is `{min: 4, max: 4}`. A + version-mismatched client fails `hello` with `PROTOCOL_VERSION_UNSUPPORTED` + and never restarts the daemon — run `simlock daemon stop` once it's idle. + `daemon.stop` remains a frozen exception, accepted at any protocol version + the daemon has ever spoken. +- **Config:** three `lease.*` keys are retired — `lease.detachedTtlMs`, + `lease.heldTtlBackstopMs`, and `lease.heartbeatIntervalMs`. All three are now + simply unrecognized: `simlock config` warns about each and ignores it, + exactly as it does for any other unknown key. **None of them is aliased onto + a new key**, so a config still setting `lease.detachedTtlMs` gets + `lease.defaultTtlMs`'s default rather than the value it wrote — copy the + value across. New: `lease.defaultTtlMs` (15 minutes, applied to a request + that names no `ttlMs`) and `lease.maxTtlMs` (4 hours). Both must be positive + numbers with `lease.defaultTtlMs <= lease.maxTtlMs`; a config that breaks + either rule is **rejected at load and the daemon does not start**, naming the + offending key, rather than being clamped. Note the two treatments are + different on purpose: a retired key is warned about and ignored, because it + is a leftover; a TTL pair that contradicts itself has no safe fallback to be + ignored in favour of. See `docs/CONFIGURATION.md#retired-lease-keys`. +- **Upgrading over a live held lease:** a lease a pre-ADR-0004 daemon + persisted in held mode survives the upgrade with its persisted deadline + intact — up to the old one-hour `lease.heldTtlBackstopMs`. Nothing can + renew it: its holder speaks protocol 3 and the new daemon speaks + `{min: 4, max: 4}`, so its `hello` fails. The lease simply expires on that + deadline and its device is reclaimed, or `simlock release ` ends + it sooner. Stopping the old daemon while it is idle, as the protocol- + mismatch error already advises, avoids the situation entirely. +- **A holder killed with `SIGKILL` keeps its device until the TTL expires.** + The daemon keeps no per-connection lease state and releases nothing when a + connection closes, on any transport — so a holder that dies without running + its own release path (`SIGKILL`, a crash, a lost machine) holds its device + until `expiresAt`, at most the lease's own TTL after its last renew — + `lease.defaultTtlMs` unless the request asked for more, never more than + `lease.maxTtlMs` — against today's immediate release on socket close. A + holder that exits normally, is `SIGTERM`ed, or whose parent dies still + releases at once, because that is its own policy. This is the one behaviour + change a local user notices, and it is the accepted price of a single + mechanism; the reverse case improves, as a machine sleep or a socket hiccup + no longer costs a live holder its device. `lease.defaultTtlMs` and `--ttl` + bound it — see `docs/known-pitfalls.md`. +- **`simlock daemon stop` no longer releases leases**, and there is no + orphaned-lease sweep at daemon startup. Leases persist across a restart and + the next daemon restores each one's TTL timer from its deadline; one whose + deadline passed in between expires as soon as a daemon is there to expire it. +- **Events:** `lease.granted`'s payload drops `mode`. `lease.released` loses + the `closed` and `orphaned` reasons — a closing connection is not a release + and never was a fact worth emitting, and there is no startup sweep to produce + an orphan. `explicit`, `killed`, and `device-lost` remain. +- **`simlock/client`:** `onLeaseLost` no longer fires with reason + `daemon-connection-lost` when a connection dies. The lease is still granted + and still yours — reconnect and renew it, or let its TTL run out. + `onConnectionLost` is what reports the dead connection; `onLeaseLost` now + only ever reports a lease the daemon actually ended. +- **The MCP server's renew timer reconnects, but never launches a daemon.** ADR + 0003 §10/§11 gave MCP one lazy reconnect trigger, the next tool call; ADR + 0004 adds a second. When the renew timer fires against a dead client the + session reconnects and renews, so an idle session no longer loses its lease + waiting for a call that may not come. That trigger only ever connects to a + daemon that is already listening — auto-launch stays a tool-call concern, so + an operator's `simlock daemon stop` is not undone by an idle session, and a + lease held across a stopped daemon expires unless the daemon is back before + its deadline. +- **A running `simlock lease` exits `1` when its daemon connection dies**, + writing one `DAEMON_CONNECTION_LOST` line that names the lease id and its + `ttlDeadline`. The CLI still does not reconnect (ADR 0003 §10), so it can + neither renew nor release — but it no longer implies the lease went with it. + The lease stands until its deadline and any later invocation can + `simlock lease renew ` it. Exit `14` keeps its narrower meaning: + the daemon ended the lease while the connection was alive. + +### Features + +These ship with the PRs that implement ADR 0004; this section describes what +those changes add, alongside the breaking changes above. + +- **cli:** `simlock lease` (without `--detach`) renews its own lease at one + third of the lease's TTL for as long as it runs — sending no TTL of its + own, so the deadline keeps the width the lease was granted with — and + releases on exit, parent death, or `SIGINT`/`SIGTERM`. `--detach` prints + the grant and exits; the lease it leaves behind is the same kind of lease, + and renewing it is the caller's job. +- **cli:** `simlock lease --ttl ` sets a lease's initial TTL in + place of `lease.defaultTtlMs`, capped by `lease.maxTtlMs`. +- **daemon:** one expiry path for every frontend — startup restores every + lease's TTL timer from its persisted deadline, and the held-lease + bookkeeping kept for release-on-close is deleted along with the + `StartupConverger` orphan sweep that existed to clean up after it. +- **config:** `lease.maxTtlMs` bounds what any caller may ask for, so one + client cannot pin a device for a day by naming a large `ttlMs`. + +### Documentation + +- record ADR 0004 as **Accepted — not yet implemented** + (`docs/adr/0004-ttl-first-leases-on-every-transport.md` and + `docs/adr/README.md`): the documentation describes the decided end state; + the code catches up in the changes that implement ADR 0004. +- rewrite the lease model across `docs/CLI.md`, `docs/CLIENT.md`, + `docs/HTTP-API.md`, `docs/CONFIGURATION.md`, `docs/ARCHITECTURE.md` + ("Leases", the frontend topology, and startup convergence), + `docs/EVENTS.md`, `docs/ABOUT.md`, and `README.md`; record the SIGKILLed + holder and re-frame the reparented-holder fix around renew timers in + `docs/known-pitfalls.md`. + ## [0.3.0](https://github.com/callstackincubator/simlock/compare/v0.2.0...v0.3.0) (2026-09-03) ADR 0003 (`docs/adr/0003-one-typed-daemon-contract-behind-every-frontend.md`): diff --git a/README.md b/README.md index bfa821e8b..567f11931 100644 --- a/README.md +++ b/README.md @@ -61,8 +61,9 @@ simlock lease --platform ios --device "iPhone 16" --detach "deviceId": "dev_1a2b", "requesterId": "agent-1", "ownerId": "agent-1", - "mode": "detached", "grantedAt": 1735689600000, + "ttlMs": 900000, + "lastRenewedAt": 1735689600000, "ttlDeadline": 1735690500000 }, "timing": { @@ -76,10 +77,12 @@ simlock lease --platform ios --device "iPhone 16" --detach ``` That's the whole interaction: ask for a platform and a device model, get -back an identified, ready-to-use device. Release it explicitly, or let its -TTL expire. This is the contract's own `LeaseGrant` shape, serialized -as-is — the CLI's `--json` output is a contract value, not a bespoke -rendering (see [docs/CLI.md](docs/CLI.md)). +back an identified, ready-to-use device. Release it explicitly, renew it +before `ttlDeadline` to keep it, or let its TTL expire. Drop `--detach` and +`simlock lease` stays running instead, doing the first two for you — renewing +on a timer and releasing when it exits. This is the contract's own +`LeaseGrant` shape, serialized as-is — the CLI's `--json` output is a +contract value, not a bespoke rendering (see [docs/CLI.md](docs/CLI.md)). Now say a second agent asks for the same `iPhone 16` a moment later. It's already leased to the first agent — no problem, Simlock just provisions @@ -104,8 +107,9 @@ the lease result lands on stdout the moment the new device is ready: "deviceId": "dev_3c4d", "requesterId": "agent-2", "ownerId": "agent-2", - "mode": "detached", "grantedAt": 1735689630000, + "ttlMs": 900000, + "lastRenewedAt": 1735689630000, "ttlDeadline": 1735690530000 }, "timing": { @@ -155,16 +159,17 @@ The daemon starts on demand — there's no separate setup step. Use Simlock-managed devices. See [docs/CLI.md](docs/CLI.md) for the full command reference and -[docs/CLI.md#mcp-integration-optional](docs/CLI.md) or the [README section +[docs/CLI.md#simlock-mcp](docs/CLI.md#simlock-mcp) or the [README section below](#mcp-integration-optional) for wiring up an MCP client. ## MCP integration (optional) -The CLI remains Simlock's primary, full operator interface. MCP is a -narrower, agent-focused integration: it intentionally exposes neither -status, configuration, events, lease renewal, nor destructive or other -operator commands. Start it with `simlock mcp` — it reserves stdout for MCP -JSON-RPC, so lease results never mix with protocol framing. +The CLI remains Simlock's primary, full operator interface. MCP is a narrower, +agent-focused integration: it intentionally exposes neither status, +configuration, events, manual lease renewal, nor destructive or other operator +commands — the server renews its own session's lease on a timer, so an agent +never has to ask it to. Start it with `simlock mcp` — it reserves stdout for +MCP JSON-RPC, so lease results never mix with protocol framing. `SIMLOCK_AGENT_ID` sets the server's stable requester identity. Simlock allows at most one active lease per identity, so give each agent session a @@ -172,10 +177,10 @@ distinct, stable id — run one MCP server process per agent session, each with its own id. The server exposes exactly four tools: `list_devices` (read-only catalog of -what can be leased), `lease_simulator`, `release_simulator`, and -`lease_status` (cheap, safe to poll after a context compaction to check -whether a device is still held). Full tool contracts, progress reporting, -and lease-loss notifications are documented in +what can be leased), `lease_simulator`, `release_simulator`, and `lease_status` +(cheap, safe to poll after a context compaction to check whether a device is +still leased to this session). Full tool contracts, progress reporting, and +lease-loss notifications are documented in [docs/CLI.md](docs/CLI.md#simlock-mcp). ## Documentation diff --git a/docs/ABOUT.md b/docs/ABOUT.md index 2d58e3a40..ce1e5d260 100644 --- a/docs/ABOUT.md +++ b/docs/ABOUT.md @@ -37,9 +37,13 @@ programmatic client the CLI and MCP frontends are themselves built on (see - **Advisory coordination.** Simlock does not sandbox anything. It works because agents are instructed to never call `simctl` / `avdmanager` directly and to only use devices handed to them by a lease. -- **Process-held leases.** The `lease` command stays running in the - background; the open connection to the daemon is the heartbeat. Killing the - process releases the lease. A daemon-side TTL is the backstop for zombies. +- **TTL leases, one kind everywhere.** Every lease carries a TTL and lives + until it expires, is renewed, or is released — on the socket, over HTTP, + and over MCP alike. `simlock lease` stays running in the background, + renewing on a timer and releasing when it exits, so killing it normally + frees the device at once; `--detach` skips the staying alive and leaves the + renewing to you. A holder that dies without releasing costs its device only + until the TTL runs out. - **One lease per agent** (v1). - **Managed-device registry.** Simlock only ever shuts down, erases, or deletes devices it created itself. Everything else on the machine is @@ -50,4 +54,5 @@ programmatic client the CLI and MCP frontends are themselves built on (see See [ARCHITECTURE.md](ARCHITECTURE.md) for how it's built, [CLI.md](CLI.md) for the command surface, [CLIENT.md](CLIENT.md) for the programmatic client, -and [known-pitfalls.md](known-pitfalls.md) for accepted gaps. +[HTTP-API.md](HTTP-API.md) for the network API, and +[known-pitfalls.md](known-pitfalls.md) for accepted gaps. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a508fc272..7a8176199 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -37,47 +37,60 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ leasing and releasing for an agent session. The HTTP gateway is different in kind, not just transport: it is the one frontend meant to be reached over a real network, so it calls the daemon's dispatcher **in-process** — the exact - same one the socket path calls — rather than going through the unix socket - at all, requires a bearer token on every route but `GET /v1/healthz`, and - only ever grants detached-style, TTL-renewed leases — "held lease = live - connection" does not survive a real network the way it does a local - process. Its listener now starts right after the socket claim, the same - moment the unix socket itself starts accepting connections and before - startup convergence runs (`DaemonServer`'s `onSocketClaimed` hook, see - "Startup: claim first, converge after" below) — a bug fix from the pre-ADR - gateway, which started only once convergence had 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. -- **CLI**: in the default *held* mode it acquires a lease, prints one JSON - result line on stdout, then stays alive holding the daemon connection; the - connection is the lease heartbeat. Progress streams as JSON lines on stderr. + same one the socket path calls — rather than going through the unix socket at + all, and requires a bearer token on every route but `GET /v1/healthz`. It + grants exactly the same TTL-renewed lease every other frontend does (ADR + 0004) — being reachable over a real network is no longer a reason for a + different lease model, because there is only one. Its listener now starts + right after the socket claim, the same moment the unix socket itself starts + accepting connections and before startup convergence runs (`DaemonServer`'s + `onSocketClaimed` hook, see "Startup: claim first, converge after" below) — a + bug fix from the pre-ADR gateway, which started only once convergence had + 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. +- **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 + CLI's own policy over an ordinary TTL lease, not a daemon mode: the + connection itself holds nothing (ADR 0004). `--detach` skips the staying + alive; the lease it prints is the same lease. Progress streams as JSON lines + on stderr. - **stdio MCP server**: its process owns one agent session and exposes MCP over stdin/stdout. `McpSession` (`src/mcp/session.ts`) holds one `simlock/client` connection at a time and does nothing today's typed client does not already - do (ADR §11: MCP keeps only "connection lifecycle ... and its MCP-only + do (ADR 0003 §11: MCP keeps only "connection lifecycle ... and its MCP-only relays"): tool calls are serialized onto it, `lease_status` is one `lease.list` call rather than a session-local cache, and a release the session does not own surfaces the daemon's own `FORBIDDEN` rather than a - client-side guard pre-empting it. A lease is held by that connection until - the session explicitly releases it or the connection dies. Like the CLI, it - relays the daemon's progress pushes for the in-flight `lease_simulator` - request — as MCP `notifications/progress` instead of stderr JSON lines, and - only when the client supplied a progress token. Unlike the CLI, this - process outlives any single daemon connection: the typed client itself - never reconnects (ADR §10), so `McpSession` builds a brand new one lazily, - on the next tool call, once its current client's `onConnectionLost` fires - — auto-starting the daemon exactly as the CLI does - (`connectWithAutoLaunch`, `src/mcp/connect.ts`), and never on a version - mismatch or a refused handshake, only on "nothing is listening". A held - lease never survives its connection dying (the daemon releases it on - graceful close, and `StartupConverger` sweeps any orphaned lease from an - ungraceful death at its own startup — see "Lease subsystem boundaries and - wiring" above): the client already synthesizes `onLeaseLost` (reason - `daemon-connection-lost`) for every lease it held the moment its connection - dies, so the session relays that straight through rather than asking the - daemon whether its old lease survived. + client-side guard pre-empting it. Like the CLI, the session runs a renew + timer over its lease and releases it when the process ends — its own policy, + not something the connection does. Like the CLI, it relays the daemon's + progress pushes for the in-flight `lease_simulator` request — as MCP + `notifications/progress` instead of stderr JSON lines, and only when the + client supplied a progress token. Unlike the CLI, this process outlives any + single daemon connection: the typed client itself never reconnects (ADR 0003 + §10), so `McpSession` builds a brand new one lazily, once its current client's + `onConnectionLost` fires. ADR 0004 narrows ADR 0003 §10/§11's lazy-only + reconnect to two triggers with deliberately different powers: + + - **On a tool call**, as before — auto-starting the daemon exactly as the + CLI does (`connectWithAutoLaunch`, `src/mcp/connect.ts`), and never on a + version mismatch or a refused handshake, only on "nothing is listening". + - **On the renew timer**, which is new: when the timer fires against a + dead client, the session reconnects to a daemon that is **already + listening** and renews, instead of waiting for a tool call that may not + come and letting its own lease expire while the session sits idle. This + trigger never launches a daemon. Auto-launch stays a tool-call concern + so an operator's `simlock daemon stop` cannot be undone by an idle + session, which means a lease held across a stopped daemon expires unless + the daemon is back before its deadline. + + Either way the lease survives the reconnect untouched — the daemon + released nothing when the old connection died — so the new client picks + the same lease back up (`lease.list` tells it which) rather than treating a + dead connection as a lost device and requesting a second one. - **Daemon**: owns all state, serializes all decisions. Started on demand, reachable over a unix socket. @@ -116,6 +129,16 @@ of a shared wire format — and every socket-side fix (the download policy in `config.downloads.policy`, startup-readiness parking, error mapping) applies to HTTP automatically because there is only one code path to fix. +**Protocol versions are negotiated as `{min, max}` ranges** and honestly: +a range widens only when a compatibility path is actually kept (ADR 0003 §6). +ADR 0004 removes `lease.heartbeat` and `mode` from the contract with no shim +behind them, so the range both sides advertise is `{min: 4, max: 4}` — a +protocol-3 client and a protocol-4 daemon simply do not overlap, and `hello` +fails with `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges. `daemon.stop` +stays the frozen exception, accepted at any version the daemon has ever +spoken, so the upgrade path (`simlock daemon stop`, then start the new +daemon) exists at all. + **Two roles**, `agent` and `admin`, declared in `src/contract/roles.ts`. Read-only and lease-lifecycle operations are `agent`; anything that reads or mutates state outside the caller's own leases (`list.get`, `cleanup.run`, @@ -182,11 +205,14 @@ client-declared role. How a caller supplies it, in resolution order: the `admin.token` file (CLI, briefly retried to ride out a daemon still writing it). **The CLI connects as admin whenever the local `admin.token` file is readable** — that's what keeps `simlock lease --detach` followed later by -`simlock release ` working across two separate CLI invocations with -different pid-derived identities, since both connect as admin and admin -bypasses the per-connection ownership check that would otherwise apply. -When none of the four sources resolves (a different OS user, or the file -genuinely missing), the CLI falls back to an agent-role session with a +`simlock lease renew ` or `simlock release ` working across separate +CLI invocations with different pid-derived identities, since all of them +connect as admin and admin bypasses the per-connection ownership check that +would otherwise apply. Renewing someone else's lease is an ownership +question, not a read: a plain agent-role invocation can only renew a lease +its own principal was granted. +When none of the CLI's three sources resolves (a different OS user, or the +file genuinely missing), the CLI falls back to an agent-role session with a one-line stderr notice, and `simlock lease`'s output JSON includes the connection's resolved `role` so a caller can tell which one it got. @@ -275,29 +301,27 @@ until the registry commits the resulting running or non-running state. Global and platform limits are checked atomically; no driver-specific runtime details participate in this decision. -At startup, `StartupConverger` first releases every persisted `held` lease -(reason `orphaned`) through the normal release path — a held lease's liveness -is its daemon connection, so it cannot have a live holder across a restart, -and this runs before timers are restored so an orphaned lease's timer is -never re-armed. Like every release (see "Release hands the purge off" below), -this step is registry-only: the device commits straight to `reclaiming` and -the lease record is gone, while the driver-side reclaim is kicked off in the -background, one per device rather than queued, so N orphaned leases no longer -cost N serial erases on this path. It -then restores persisted TTL timers for the remaining (`detached`) leases, -whose liveness is the TTL rather than a connection, and re-arms retry timers -for devices still `quarantined` (see below) from their persisted next-retry -deadline. It then recovers unleased interrupted reclaims through the +At startup, `StartupConverger` restores the persisted TTL timer of **every** +lease it finds, and re-arms retry timers for devices still `quarantined` (see +below) from their persisted next-retry deadline. A lease survives a daemon +restart because a lease's liveness was never the daemon connection to begin +with (ADR 0004). The *holder* does not survive it in the same way: the typed +client never reconnects (ADR 0003 §10), so a running `simlock lease` exits `1` +when the old daemon goes away and something has to renew the lease from a new +invocation before its deadline. What the restart no longer does is decide the +question for you by releasing the lease outright. There is no orphan sweep at +startup — nothing about a restart proves a holder is dead, so nothing is +released on the strength of it. A lease whose deadline already passed while no +daemon was running expires as soon as one is, through the ordinary expiry path. +`StartupConverger` then recovers unleased interrupted reclaims through the warm-pool recovery port — a backgrounded reclaim marks its device with a `reclaim` operation claim for exactly this reason, so this step can tell it apart from one truly orphaned by a *previous* crash (unclaimed, since claims never survive a restart) rather than cutting it short — and finally deterministically shuts down excess unleased, unclaimed `ready` registry -devices through `CleanupActionExecutor`. Running this release step before -timer restoration and capacity convergence means the devices it frees are -visible to both. Leased devices that survive the orphan sweep are never -touched, so a lowered limit may remain visibly over-limit until leases -naturally release. +devices through `CleanupActionExecutor`. Leased devices are never touched by +any of this, so a lowered limit may remain visibly over-limit until leases +expire or are released. The capacity sweep's view of what's `ready` is only ever a snapshot, and a background reclaim in flight makes it more so: `reclaiming` already counts @@ -391,38 +415,61 @@ Conclusions baked into the drivers: ## Leases -- **Held mode (default)**: lease lives as long as its holding frontend's daemon - connection. For the CLI, that is the CLI process; for MCP, it is the MCP - server process for that agent session. Connection close = release. The CLI - holder additionally watches its parent through the `ParentWatch` port and - self-terminates if it dies, so a crashed agent's backgrounded `simlock - lease` cannot outlive it by getting reparented — see - [known-pitfalls.md](known-pitfalls.md). -- **Detached mode (`--detach`)**: returns a token, daemon enforces a TTL, the - agent must `simlock renew` periodically. -- **TTL backstop**: even held leases have a long daemon-side TTL for zombie - sockets, machine sleep, etc. -- **Heartbeat-driven sliding TTL, capability-gated**: a held lease's backstop - deadline is set once at grant and never moves unless its holder proves it is - still alive. The daemon pushes `lease.heartbeat` every - `lease.heartbeatIntervalMs` to a connection only if it (a) holds at least one - lease and (b) declared `capabilities: { heartbeat: true }` at `hello` - (`src/daemon/server.ts`). `IpcDaemonConnection` answers automatically with a - `lease.heartbeat` request (`src/simlock-client/wire.ts`), so any - frontend inherits ponging for free just by declaring the capability — no - frontend-specific pong code. The daemon slides every lease the connection - holds through `LeaseLifecycle.heartbeat()`, which goes through - `registry.renewLease()` (not a direct `expiryScheduler.replace()`) so the - persisted deadline never goes stale and a daemon restart mid-lease restores - the slid deadline, not the grant-time one. It is a pure sliding window: a - holder that stops ponging simply reaches its existing backstop deadline and - expires exactly as before — no missed-pong counter, no extra expiry reason. - Both frontends' held mode declare the capability: MCP because its holder - process dies with its agent (stdin EOF), and CLI held mode because its - holder now self-terminates on parent death instead of surviving reparenting - (see [known-pitfalls.md](known-pitfalls.md)) — without that, a reparented - CLI holder would pong forever, turning a bounded leak into an unbounded - one. +There is **one kind of lease**, on every transport ([ADR +0004](adr/0004-ttl-first-leases-on-every-transport.md)). + +- **A lease is a TTL and nothing else.** Every lease carries `ttlMs` and a + `ttlDeadline` (`expiresAt` in HTTP bodies), set at grant from the request's + `ttlMs` or from `lease.defaultTtlMs`, and capped at `lease.maxTtlMs` — asking + for more is `BAD_REQUEST`, not a silent clamp. `LeaseLifecycle` arms one + expiry timer per lease and re-arms it on renew through + `registry.renewLease()` (not a direct `expiryScheduler.replace()`), so the + persisted deadline never goes stale and a restart mid-lease restores the + renewed deadline rather than the grant-time one. The record stores its + `ttlMs` too — the width it was granted with, or last renewed with when a + renew named one — because a body-less renew re-applies that width rather than + falling back to `lease.defaultTtlMs`. It also carries `lastRenewedAt`, a + **stored** field written at grant and on every renew, which is what `simlock + status` renders as "last renewed". That is a new field rather than a rename + of `lastHeartbeatAt`: the old one was never stored at all, it was derived at + the dispatcher as `ttlDeadline - heldTtlBackstopMs`, and that arithmetic + cannot survive per-lease TTLs. +- **The only thing that keeps a lease alive is `lease.renew`.** It is an + ordinary client-initiated operation, so it works identically on the unix + socket, over HTTP, over MCP, and through a gateway that forwards it to the + owning worker. There is no daemon-initiated heartbeat, no capability to + declare, and no second deadline behind the first. +- **Connection close means nothing to a lease.** The daemon keeps no + per-connection lease state and releases nothing when a connection closes, on + any transport. Nothing is swept at daemon startup either — a restart does not + prove a holder is dead. So a gateway hop, a suspended laptop, or a daemon + upgrade costs a client its stream and not its device. It can still cost the + client: the typed client does not reconnect (ADR 0003 §10), so a `simlock + lease` holder exits `1` on a dead connection and something has to renew that + still-standing lease from a new connection before its deadline. The lease + outliving the connection is the daemon's guarantee; picking it back up is the + frontend's job. +- **"Holding" is a frontend policy over that one lease.** `simlock lease` and + the MCP session both renew at one third of the lease's TTL — sending no TTL + of their own, so every renew re-applies the lease's stored `ttlMs` and the + deadline keeps its original width — and release on exit. A renew that fails + transiently on a live connection is simply retried on the next tick; one + answered `UNKNOWN_LEASE` means the daemon has already ended the lease, and + the holder stops exactly as a `lease-lost` push would stop it. The CLI holder + additionally watches its parent through the `ParentWatch` port and + self-terminates if it dies, so a crashed agent's backgrounded `simlock lease` + cannot outlive it by getting reparented — see + [known-pitfalls.md](known-pitfalls.md). `--detach` is the absence of that + policy, not a different lease. The daemon neither knows nor cares which + policy a client follows. +- **The cost of that simplicity, stated once:** a holder killed with `SIGKILL`, + or lost with its machine, runs no release, so its device stays leased until + the deadline — at most the lease's own TTL after its last renew: + `lease.defaultTtlMs` unless the request asked for more, never more than + `lease.maxTtlMs`. A short default TTL is the bound, deliberately chosen over + reintroducing per-connection lease state that HTTP and a gateway could never + honour anyway (ADR 0004, "Alternatives considered"). See + [known-pitfalls.md](known-pitfalls.md#a-sigkilled-lease-holder-keeps-its-device-until-the-ttl-expires). - One lease per agent in v1; no atomic multi-device acquisition (documented deadlock risk if two devices are taken sequentially). @@ -436,8 +483,8 @@ snapshot restore comparably — and it carries no information the releasing caller can act on. So `LeaseReleaseCoordinator` commits the first half, hands the second to `WarmPoolCoordinator` without awaiting it, and returns. An agent releasing over MCP or the CLI gets its turn back immediately instead of -blocking on a device it has already given up; startup's orphan sweep gets the -same treatment (see "Running capacity"), which is where the pattern started. +blocking on a device it has already given up, and an expiry frees its device +the same way. The device is not lost track of while that runs. It is `reclaiming`, so it still counts as running capacity and is invisible to every grant path @@ -491,10 +538,10 @@ capacity coordinator into these direct transactional call chains: `CleanupActionExecutor`; the executor revalidates registry ownership, lease/state safety, and delegates the driver operation to `ManagedDeviceLifecycle`. -- `StartupConverger` runs orphaned held-lease release, timer restoration, - interrupted-reclaim recovery, and running-capacity convergence in that - order. `NukeService` coordinates lease release, pending-request - cancellation, and registry-scoped reset operations. +- `StartupConverger` runs TTL-timer restoration, interrupted-reclaim + recovery, and running-capacity convergence in that order. `NukeService` + coordinates lease release, pending-request cancellation, and + registry-scoped reset operations. The serialized decision gate protects only short read-decide-commit sections. Driver work remains outside it. Component boundaries use direct calls for @@ -576,12 +623,18 @@ whatever the agent had running *inside* the device when it died — a launched app, a `log stream`, an Appium/XCUITest session, a port forward — simlock has no way to know that state existed, let alone restore it. So the monitor emits `device.crash-detected` the moment a crash is confirmed and `device.recovered` -once the reboot passes readiness; the daemon pushes both to whichever -connection currently holds the lease (`device-unhealthy` / `device-recovered` -on the wire) so the holder learns its device blinked instead of quietly -finding its session gone. A give-up is not a separate push: it ends the lease -through the normal `lease.released` path, so the holder learns about it the -same way it learns about any other lease loss. +once the reboot passes readiness; the daemon pushes both to every live +connection whose principal owns the lease (`device-unhealthy` / +`device-recovered` on the wire, ADR 0003 §8 and ADR 0004 §5) — so the holder +learns its device blinked instead of quietly finding its session gone. A +polling-only HTTP client, which has no connection to push to, reads the same +facts from the `notices` array on `POST /v1/leases/{id}/renew`; that buffer +(`LeaseNoticeBuffer`, `src/http/notices.ts`) is HTTP-side frontend state, not +part of the socket `lease.renew` response. + +A give-up is not a separate push: it ends the lease through the normal +`lease.released` path, so the holder learns about it the same way it learns +about any other lease loss. The monitor starts only after startup convergence completes (`DaemonServer#start`, after `#converge()` returns) — the same claim-first @@ -700,7 +753,7 @@ SystemStats — cpu count, total/free RAM, disk free IpcConnector / IpcListenerFactory — connect to and host daemon IPC endpoints DaemonLauncher — detached daemon startup with append-only combined logs Logger — debug/info/warn/error(message, fields) plus child(module) scoping -ParentWatch — watch a pid, notify once on exit (CLI held-mode self-termination) +ParentWatch — watch a pid, notify once on exit (lease holder self-termination) ``` Real implementations are thin adapters wired up once at daemon startup; @@ -735,10 +788,10 @@ interleaved with live lease/reclaim activity whenever a client issues `doctor.run` mid-session (it shells out per driver/device, then at most flags drift for a later `--fix`), so overlapping it with startup's own registry work introduces nothing this codebase doesn't already do elsewhere. Neither -call awaits a device reclaim inline any more (#43) — an orphaned held lease's -reclaim runs in the background once its release commits — so what's left on -this path is comparatively fast: per-driver/device reconnaissance plus -whatever unleased interrupted-reclaim recovery and capacity-sweep shutdowns +call awaits a device reclaim inline any more (#43) — a release's reclaim runs +in the background once the release commits — so what's left on this path is +comparatively fast: per-driver/device reconnaissance plus whatever unleased +interrupted-reclaim recovery and capacity-sweep shutdowns convergence itself still performs inline. Two consequences follow from claiming first: diff --git a/docs/CLI.md b/docs/CLI.md index 8479c7a4c..4de8aca4f 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -29,7 +29,7 @@ longer dumped to stderr on every failure, only on request via `--help`. | Exit | Error code | Meaning | |---|---|---| -| 0 | — | success (for `lease` held mode: lease ended normally) | +| 0 | — | success (for a `lease` that stayed alive: the lease ended normally) | | 1 | `INTERNAL` | internal / unexpected error | | 2 | `USAGE` | usage error (bad flags, missing required args, unknown command) | | 2 | `BAD_FRAME` | malformed request frame sent to the daemon | @@ -42,22 +42,24 @@ longer dumped to stderr on every failure, only on request via `--help`. | 12 | `INSUFFICIENT_DISK_SPACE` | not enough free disk space to install a component | | 12 | `LICENSE_NOT_ACCEPTED` | a required license (e.g. an Android SDK license) is not accepted | | 13 | `REQUESTER_ALREADY_LEASED` | requester already holds a lease or has a pending request — one lease per agent in v1; release the named lease first | -| 14 | — | `lease` held mode only: the daemon ended the lease without the holder asking (TTL backstop, operator `release`, or an unrecoverable device) | +| 14 | — | `lease` without `--detach` only: the daemon ended the lease without the holder asking (TTL expiry, operator `release`, or an unrecoverable device) | Every row but 14 matches the `cliExitCode` column of the contract's error table (`src/contract/errors.ts`'s `ERROR_TABLE`) exactly — the CLI does not -maintain a second mapping; 14 is not a daemon error code but an outcome of -held mode, so it lives beside the table's other `lease` outcome, 0. +maintain a second mapping; 14 is not a daemon error code but an outcome of a +`lease` that stays alive, so it lives beside the table's other `lease` +outcome, 0. A daemon error code with no entry here (for example `UNKNOWN_LEASE`, surfaced by `lease renew`) falls back to exit 1; the structured stderr line -still reports the specific code. +still reports the specific code — a renew by a running `simlock lease` is the +exception, and exits `14`. --- ## Agent identity -Leases are keyed by requester: at most one active lease (held or detached) -per agent id, enforced by the daemon. Give each agent session a **stable** +Leases are keyed by requester: at most one active lease per agent id, +enforced by the daemon. Give each agent session a **stable** id so this actually constrains anything — a fresh id on every CLI invocation (the default) makes the constraint a no-op, since every invocation looks like a different requester. @@ -77,16 +79,22 @@ agent holds what. ## `simlock lease` Acquire a device. Blocks while waiting for capacity, then while provisioning -and booting, then — in held mode — keeps running to hold the lease. +and booting, then — unless `--detach` — keeps running, renewing the lease on +a timer and releasing it when it exits. ``` simlock lease --platform --device [--os ] [--agent-id ] [--timeout ] [--no-wait] [--detach] - [--allow-download] [--export-env] [--bind-pid ] - - [--allow-download] [--full] [--bind-pid ] + [--ttl ] [--allow-download] [--full] [--export-env] + [--bind-pid ] ``` +There is only one kind of lease ([ADR +0004](adr/0004-ttl-first-leases-on-every-transport.md)): 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. + - `--platform`, `--device` — required. `--os` defaults to the newest runtime already installed for that platform. - `--agent-id` — this invocation's requester identity; see @@ -98,8 +106,10 @@ simlock lease --platform --device [--os ] (multi-GB; never implicit). Without it, a missing runtime is exit 12. iOS runtimes remain Xcode-managed in v1: `--allow-download` cannot install them; install the runtime through Xcode first. -- `--detach` — detached mode: print the lease result and exit; the lease is - TTL-bound and must be renewed with `simlock lease renew`. +- `--ttl ` — the lease's initial TTL, replacing + `lease.defaultTtlMs` (15m) for this lease. Asking for more than + `lease.maxTtlMs` (4h) is a `BAD_REQUEST` (exit 2), not a silent clamp. See + [CONFIGURATION.md](CONFIGURATION.md). - `--export-env` — print the grant's `environment` as shell `export` lines on stdout instead of the JSON line, for `eval "$(...)"`. See [Reaching a leased device](#reaching-a-leased-device). If the grant carries no @@ -131,25 +141,31 @@ simlock lease --platform --device [--os ] with, a slim device, so it can wait for a fresh device to provision or force a re-provision of one already running, even while slim devices sit idle in the warm pool. -- `--detach` — detached mode: print the lease result (the same JSON shape as - held mode's grant line, below, including `device.featureProfile`) and - exit; the lease is TTL-bound and must be renewed with `simlock lease - renew`. -- `--bind-pid ` — held mode only: watch this pid for death instead of - the CLI's actual parent. For a holder spawned from a short-lived subshell, - the immediate parent can die (and get reaped) while the owning agent is - still very much alive; point this at the agent's own pid instead. +- `--detach` — print the lease result (the same JSON shape as the grant line + below, including `device.featureProfile`) and exit instead of staying + alive. Nothing then renews the lease on your behalf: keep it with + `simlock lease renew` before `ttlDeadline`, and end it with + `simlock release`. From an invocation other than the one granted the + lease, both of those need an admin credential — see [Admin credential + resolution](#admin-credential-resolution). +- `--bind-pid ` — only meaningful without `--detach`: watch this pid for + death instead of the CLI's actual parent. For a holder spawned from a + short-lived subshell, the immediate parent can die (and get reaped) while + the owning agent is still very much alive; point this at the agent's own + pid instead. One lease per requester in v1: leasing while you already hold a lease or have a request queued fails with `REQUESTER_ALREADY_LEASED` (exit 13); the error message names the existing lease id to release first. -**Held mode (default):** intended to be run in the background by the agent. -As soon as the device is ready, one JSON line is printed on stdout — the +**Staying alive (the default):** intended to be run in the background by the +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): +The fields you usually care about, from that same line: + ```json {"lease":"lse_9f2c","platform":"ios","device":"iPhone 17 Pro","os":"26.5","udid":"ABCD-...","state":"leased", "environment":{"SIMLOCK_IOS_DEVICE_SET":"/Users/you/.simlock/devices/ios"}} @@ -160,9 +176,58 @@ Simlock keeps its devices in roots the platform tools do not look in by default, so a bare `simctl` or `adb` will not find them. See [Reaching a leased device](#reaching-a-leased-device). -{"device":{"id":"dev_1a2b","driverDeviceId":"ABCD-...","spec":{"platform":"ios","model":"iPhone 17 Pro","osVersion":"26.5"},"address":"...","featureProfile":"reduced"},"lease":{"id":"lse_9f2c","deviceId":"dev_1a2b","requesterId":"agent-1","ownerId":"agent-1","mode":"held","grantedAt":1735689600000,"ttlDeadline":1735689660000},"timing":{"estimatedProvisionMs":0,"estimatedBootMs":0,"estimatedReclaimMs":0,"estimatedReadyMs":0},"role":"agent"} +The full line, with every field the contract defines: + +```json +{"device":{"id":"dev_1a2b","driverDeviceId":"ABCD-...","spec":{"platform":"ios","model":"iPhone 17 Pro","osVersion":"26.5"},"address":"...","featureProfile":"reduced"},"lease":{"id":"lse_9f2c","deviceId":"dev_1a2b","requesterId":"agent-1","ownerId":"agent-1","grantedAt":1735689600000,"ttlMs":900000,"lastRenewedAt":1735689600000,"ttlDeadline":1735690500000},"timing":{"estimatedProvisionMs":0,"estimatedBootMs":0,"estimatedReclaimMs":0,"estimatedReadyMs":0},"role":"agent"} +``` + +`lease.ttlDeadline` is the moment the daemon will expire this lease if +nothing renews it. It is the only thing keeping the lease alive — there is +no second mechanism behind it. The lease also stores the `ttlMs` it was +granted with, which is what a renew re-applies unless one names a new TTL. + +Then the process stays alive, and while it is alive it does two things for you. +It **renews** the lease every third of the lease's TTL, sending no TTL of its +own, so each renew re-applies the lease's own `ttlMs` and the deadline keeps +moving out at its original width for as long as the process is there. A renew +that fails with a transient error while the connection is still alive is not +fatal — the next tick retries it, and there is a whole TTL of slack to retry +inside. A renew answered `UNKNOWN_LEASE` is different: the daemon has already +ended the lease, so the holder exits `14` exactly as a `lease-lost` push would +have ended it. And it **releases** on the way out: on a normal exit, on +`SIGINT`/`SIGTERM`, and on parent death — it watches its parent (the pid +captured at startup, or `--bind-pid`) and releases and exits on its own the +moment that parent is gone, so a crashed or killed agent's backgrounded `lease` +does not outlive it. + +Release-on-exit is this process's own policy, not something the daemon +enforces. A holder that is `SIGKILL`ed, or whose machine disappears, cannot +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). + +**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 +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`: + +```json +{"error":{"code":"DAEMON_CONNECTION_LOST","message":"lost the daemon connection; lease lse_9f2c is still yours until its ttlDeadline 1735690500000 -- renew it with `simlock lease renew lse_9f2c` or let it expire"}} ``` +Nothing was released. The lease is still granted to you on the daemon, still +counting down, and a later `simlock lease renew ` picks it straight +back up — from a different invocation only when that invocation resolves an +admin credential (see [Admin credential +resolution](#admin-credential-resolution)), since the lease's owner is the +session that was granted it. This is not exit `14`: `14` means the +daemon ended the lease while the connection was alive, which is a different +thing to have to handle. + `device` is a **projection** of the registry's device record — `id`, `driverDeviceId`, `spec`, `address?`, `featureProfile?` — not the full record `status.get`/`list.get` return to an admin caller. Internal @@ -179,13 +244,9 @@ of misreading it as a bug. See `src/contract/schemas.ts` field list — this is the one vocabulary every frontend (CLI, MCP, HTTP, the `simlock/client` package) now shares. -then the process stays alive holding the lease. **Kill the process to -release** — or let it die on its own: held mode watches its parent (the pid -captured at startup, or `--bind-pid`) and releases and exits on its own the -moment that parent is gone, so a crashed or killed agent's backgrounded -`lease` does not outlive it. Progress streams on stderr and reflects only the -action selected for that request. A queued request reports its position -without speculative work stages; reclaiming work is reported separately: +Progress streams on stderr and reflects only the action selected for that +request. A queued request reports its position without speculative work stages; +reclaiming work is reported separately: ```json {"push":"progress","stage":"queued","queuePosition":1} @@ -204,9 +265,9 @@ the driver's own estimate for the work it selected, which for a reclaim means the strategy that clean level uses -- an erase runs tens of seconds, a snapshot restore a few. -Once granted, held mode also relays the health monitor's findings about the -leased device for as long as the connection holds it, on the same stderr -stream: +Once granted, a `lease` that stays alive also relays the health monitor's +findings about the leased device for as long as it is connected, on the same +stderr stream: ```json {"push":"device-unhealthy","leaseId":"lse_9f2c","deviceId":"dev_1a2b"} @@ -215,11 +276,11 @@ stream: `device-unhealthy` means the device stopped running outside simlock and a reboot is in progress under the same lease; `device-recovered` means that -reboot passed readiness. The lease itself is untouched by either — it is -still held and must still be released the normal way. Recovery can instead -give up (the device vanished, its provenance no longer checks out, or reboot -attempts ran out); giving up is not itself one of these lines — it ends the -lease, which surfaces as the same line any other lease loss does: +reboot passed readiness. The lease itself is untouched by either — it is still +yours, still on its TTL, and must still be released the normal way. Recovery +can instead give up (the device vanished, its provenance no longer checks out, +or reboot attempts ran out); giving up is not itself one of these lines — it +ends the lease, which surfaces as the same line any other lease loss does: ```json {"push":"lease-lost","leaseId":"lse_9f2c","deviceId":"dev_1a2b","reason":"device-lost"} @@ -228,32 +289,41 @@ lease, which surfaces as the same line any other lease loss does: In all three lines `deviceId` is the registry device id — the `id` column of `simlock list --devices`, and the same identifier the event bus uses — not the driver-level `udid` the grant returns on stdout. A `lease-lost` line is -terminal for held mode: there is no longer a lease to -hold, so the process writes that line and exits `14` rather than waiting for a -signal, and it does not try to release a lease the daemon has already taken -back. The `reason` is whatever ended it — `device-lost` here, but equally -`expired` or `killed`. See [known-pitfalls.md](known-pitfalls.md) +terminal for a `lease` that stayed alive: there is no longer a lease to +renew, so the process writes that line and exits `14` rather than waiting for +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 the device (a launched app, `log stream`, an Appium/XCUITest session, a port forward) is gone whether or not recovery succeeds. ### `simlock lease renew [--ttl ]` -Extend a lease's TTL — works for both detached and held-mode leases. Renewal -always resets the deadline to now plus the TTL, regardless of how much time -was left. - -Without `--ttl`, the new deadline uses the lease's own mode-aware default: -`lease.detachedTtlMs` (15m) for a detached lease, `lease.heldTtlBackstopMs` -(1h) for a held one — never the other mode's default. Exit 1 if the lease is -unknown or already expired (error code `UNKNOWN_LEASE`). - -A holder that declares the `heartbeat` capability — both frontends' held -mode — slides its own deadline to now + `lease.heldTtlBackstopMs` -automatically on every heartbeat, so renewing such a lease to a deadline -further out than that does not stick — the next heartbeat pulls it back in. -Hand-renewal remains the only keep-alive for detached mode, which by design -never holds a connection to heartbeat over. +Extend a lease's TTL. Renewal always resets the deadline to now plus the TTL, +regardless of how much time was left. + +Without `--ttl`, a renew keeps the lease's own width: the new deadline is now ++ the lease's stored `ttlMs`, the TTL it was granted with or last renewed +with. `lease.defaultTtlMs` is what a *request* falls back to when it names no +`ttlMs`, not what a renew falls back to — a lease granted for four hours does +not quietly shrink to fifteen minutes the first time something renews it. +Passing `--ttl` changes the lease's width from that renew on, capped by +`lease.maxTtlMs` (4h); asking for more is a `BAD_REQUEST` (exit 2). Exit 1 if +the lease is unknown or already expired (error code `UNKNOWN_LEASE`). + +Renewing is the only thing that keeps any lease alive, on every transport. +A `simlock lease` left running does it for you on a timer; anything holding a +`--detach` lease has to do it itself, before `ttlDeadline`. + +From an invocation other than the one granted the lease, this needs an admin +credential — see [Admin credential +resolution](#admin-credential-resolution). A lease belongs to the session it +was granted to, so a fresh agent-role process renewing someone else's lease +id gets `FORBIDDEN`; the CLI connects as admin whenever the local +`admin.token` file is readable, which is why this normally just works. ## Reaching a leased device @@ -346,7 +416,7 @@ instead. ## `simlock release | --all` -Explicitly release a lease (primarily for detached mode or operator +Explicitly release a lease (primarily for a `--detach` lease or for operator intervention). `--all` force-releases every lease — confirmation required unless `--yes`. @@ -354,7 +424,7 @@ Release returns as soon as the lease is gone, not when the device is clean. Giving up the lease is a registry commit; wiping the device behind it is a driver operation that can run tens of seconds (an iOS `simctl erase`), and it proceeds in the background once the command has already exited. The same holds -for a held lease released by its holder exiting, and for `release_simulator` +for a lease released by its holder exiting, and for `release_simulator` over MCP — an agent gets its turn back immediately instead of waiting on a device it has already given up. @@ -369,16 +439,20 @@ startup to recover. ## `simlock mcp` -Start Simlock's local stdio MCP server. It accepts no flags. Standard output -is reserved for MCP JSON-RPC; fatal diagnostics are written to stderr. The -server auto-starts the daemon when needed and exposes the focused -`list_devices`, `lease_simulator`, `release_simulator`, and `lease_status` -tool surface for one agent session. If that session's held lease ends -elsewhere (expiry or a force-release), the server relays it as an MCP logging -notification. A `lease_simulator` call that carries a `_meta.progressToken` -gets queue/provisioning/boot progress relayed as MCP `notifications/progress` -for that request. See [../README.md](../README.md#mcp-integration-optional) -for details. +Start Simlock's local stdio MCP server. It accepts no flags. Standard output is +reserved for MCP JSON-RPC; fatal diagnostics are written to stderr. The server +exposes the focused `list_devices`, `lease_simulator`, `release_simulator`, and +`lease_status` tool surface for one agent session. The server auto-starts the +daemon when needed, on a tool call; its renew timer reconnects only to a +daemon that is already listening, and never launches one. `lease_simulator` +accepts the contract's optional `ttlMs` — defaulting to `lease.defaultTtlMs` +and `BAD_REQUEST` above `lease.maxTtlMs`, the same rule every other frontend +gets — and the session renews that lease on a timer and releases it when the +process ends, the same policy `simlock lease` follows. If that session's lease ends elsewhere (expiry or a force-release), +the server relays it as an MCP logging notification. A `lease_simulator` call +that carries a `_meta.progressToken` gets queue/provisioning/boot progress +relayed as MCP `notifications/progress` for that request. See +[../README.md](../README.md#mcp-integration-optional) for details. The requester identity for leases made through this server is `SIMLOCK_AGENT_ID`, falling back to a pid-derived value — see @@ -440,17 +514,19 @@ and `list --devices` well before it crosses the threshold that would make Human-oriented overview: daemon health, managed capacity (used/limit per platform), running and reserved capacity (globally and per platform), every -managed device with its state, current leases (who — the agent id, see -[Agent identity](#agent-identity) — since when), 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. +managed device with its state, current leases (who — the agent id, see [Agent +identity](#agent-identity) — since when, and when each was last 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. ## `simlock list [--devices|--leases|--rules]` Scriptable listings of managed devices, active leases, or registered cleanup rules. Defaults to `--devices`. Each lease record's `requesterId` is the -agent id (see [Agent identity](#agent-identity)) that holds it. +agent id (see [Agent identity](#agent-identity)) that holds it, and its +`lastRenewedAt` is when the lease was last renewed (set at grant, then on +every renew) — the same field `status` renders as "last renewed". ## `simlock catalog [--platform ] [--json]` @@ -480,10 +556,10 @@ each rule *would* take (rule name, target, reason) without executing. ## `simlock doctor [--fix] [--purge-orphans] [--yes]` Reconcile the daemon's state with reality (`simctl list`, `adb devices`, -running emulator processes): report orphaned processes, registry entries -whose device vanished, devices booted outside simlock, expired-but-held -leases, devices stuck mid-transition, and orphans. `--fix` applies the safe -corrections. +running emulator processes): report orphaned processes, registry entries whose +device vanished, devices booted outside simlock, expired leases whose device is +still marked `leased`, devices stuck mid-transition, and orphans. `--fix` +applies the safe corrections. An **orphan** is a device sitting inside a Simlock device root with no registry record — almost always a daemon that died between creating a device and writing @@ -554,15 +630,31 @@ lines. `--follow` keeps streaming; `--since 1h` replays recent history. ## `simlock daemon ` -Manage the daemon explicitly. Other commands auto-start it on demand; -`daemon` exists for operators and debugging. `logs` tails daemon logs and -works even when the daemon is dead — it reads the log file directly, no -connection attempted. `status` never auto-starts the daemon and distinguishes -two failure shapes: `{"status":"stopped"}` when nothing is listening on the -socket at all, versus `{"status":"handshake-refused","error":{"code":...}}` -(exit 1) when a daemon answered but refused the connection (a bad admin -credential, or a protocol version mismatch) — the two used to be reported -identically as "stopped". +Manage the daemon explicitly. Other commands auto-start it on demand; `daemon` +exists for operators and debugging. `stop` does not touch leases: they persist, +and the next daemon restores each one's TTL timer from its deadline. What a +stop does end is the connections to it — a running `simlock lease` cannot +reconnect, so it exits `1` with a `DAEMON_CONNECTION_LOST` line naming a lease +that is still granted; renew it from a later invocation once the daemon is +back. A lease whose deadline passed while no daemon was running expires as soon +as one is. `logs` tails daemon logs and works even when the daemon is dead — it +reads the log file directly, no connection attempted. `status` never +auto-starts the daemon and distinguishes two failure shapes: +`{"status":"stopped"}` when nothing is listening on the socket at all, versus +`{"status":"handshake-refused","error":{"code":...}}` (exit 1) when a daemon +answered but refused the connection (a bad admin credential, or a protocol +version mismatch) — the two used to be reported identically as "stopped". + +A daemon that refuses to boot because of its configuration — a +`lease.defaultTtlMs` above `lease.maxTtlMs`, or a non-positive value for +either, see [CONFIGURATION.md](CONFIGURATION.md) — fails the start rather +than picking a value the operator did not write. That validation runs before +the socket is claimed, so a command that auto-starts the daemon (`simlock +lease`, the MCP server) never gets a daemon to talk to: the launch times out +and the command fails with exit 1 (`INTERNAL`). The error line says nothing +about the config, because nothing ever answered — the reason is in `simlock +daemon logs`, which reads the log file directly and so works even though the +daemon never came up. The daemon writes one structured JSON line per record to `~/.simlock/daemon.log` (timestamp, level, module, message, and any fields) covering startup (version, @@ -587,9 +679,9 @@ before Simlock provisions or boots a shutdown device. ## Admin credential resolution Several commands (`list`, `cleanup`, `nuke`, `events`, `config get`, -`daemon stop`, `token create|list|revoke`, and cross-process `release`) need -the daemon's `admin` role. The CLI resolves a credential to send at -handshake, in order: +`daemon stop`, `token create|list|revoke`, and cross-process `lease renew` +and `release`) need the daemon's `admin` role. The CLI resolves a credential +to send at handshake, in order: 1. `--token ` — accepted anywhere on the command line. 2. `SIMLOCK_ADMIN_TOKEN` — the environment variable. @@ -604,10 +696,11 @@ same as any other role violation. `simlock lease`'s output JSON includes the connection's resolved `role` so a caller can tell which one it got. This is also why `simlock lease --detach` followed later by -`simlock release ` from a different invocation works even though -each CLI process has a different pid-derived identity: both commands connect -as admin (when the local file is readable), and admin bypasses the -per-connection ownership check that would otherwise apply. +`simlock lease renew ` or `simlock release ` from a +different invocation works even though each CLI process has a different +pid-derived identity: all of them connect as admin (when the local file is +readable), and admin bypasses the per-connection ownership check that would +otherwise apply. ## `simlock token create --role [--label ]` / `list` / `revoke ` diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 4f3179111..498cbfe50 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -38,6 +38,20 @@ 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 +`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 +`lease.maxTtlMs`), and the lease stores that width: a `renewLease` carrying +no `ttlMs` re-applies the lease's own, rather than falling back to +`lease.defaultTtlMs`. A frontend that means to hold a device for a while runs +its own renew timer over that — the CLI and the MCP server both renew at one +third of the lease's TTL and release on exit, and that is ordinary frontend +code, not something this client does for you. There is no heartbeat +to declare and no connection-liveness mode to opt into: a renew arriving +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) @@ -70,20 +84,39 @@ This is the one thing to internalize before building anything on top of this client: **it owns exactly one connection and never reconnects or retries, not even for reads.** When the connection dies — the daemon stops, crashes, or the socket is killed out from under it — every in-flight call rejects -with `DAEMON_CONNECTION_LOST`, `onLeaseLost` fires for each lease this -client held (reason `daemon-connection-lost`), and the client is done. There -is no automatic retry loop hiding behind any method, including `getStatus` -or `getCatalog` — a shared retry policy is a trap the moment it touches a -mutation, so this module simply does not have one at all, for anything. +with `DAEMON_CONNECTION_LOST`, `onConnectionLost` fires, and the client is +done. There is no automatic retry loop hiding behind any method, including +`getStatus` or `getCatalog` — a shared retry policy is a trap the moment it +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 +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 +back up; do nothing and it expires at its deadline like any other. That is +why `onLeaseLost` no longer fires on connection loss: it reports a lease the +daemon actually ended (expiry, an operator release, an unrecoverable +device), and a dropped socket is not one. Reconnect policy is deliberately a frontend's own concern, not something this client can make a universal decision about: -- **MCP** keeps a lazy reconnect, because its process outlives any single - connection — the next tool call after a dead connection builds a brand new - client (see `src/mcp/session.ts`, `src/mcp/connect.ts`). -- **The CLI** needs none — a CLI invocation's whole purpose ends with its - connection. +- **MCP** reconnects, because its process outlives any single connection, + on either of two triggers (see `src/mcp/session.ts`, `src/mcp/connect.ts`). + A tool call after a dead connection builds a brand new client and may + auto-launch a daemon that is not running. Its renew timer builds one too, + so an idle session does not lose its lease waiting for a call that never + 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 + 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. - **A host process** (agent-device) has its own supervisor and its own opinion about what "still needed" means across a daemon restart; this client does not guess on its behalf. @@ -92,13 +125,15 @@ The payoff of never reconnecting automatically: "reconnecting never implicitly acquires a device" is trivially true for a client that cannot reconnect at all. If you need resilience across a dropped connection, build it explicitly — call `connectSimlock`/`connectSimlockAdmin` again and decide -for yourself whether the lease you held is worth re-requesting. +for yourself whether the lease you were holding is worth renewing — or +whether letting it expire is the better answer. ```ts client.onConnectionLost((error) => { // Fires exactly once. Every in-flight call has already rejected - // DAEMON_CONNECTION_LOST and every onLeaseLost for a held lease has - // already fired by the time this runs. + // DAEMON_CONNECTION_LOST by the time this runs. Any lease this client + // was holding is still alive on the daemon — decide whether to reconnect + // and renew it, or to let its TTL run out. }); ``` @@ -154,11 +189,16 @@ doesn't end up holding the result. This is recorded as a known gap in 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 the ADR §6 for why: that would - release every held lease on the machine. `PROTOCOL_VERSION_UNSUPPORTED` - names the running daemon's version; the fix is `simlock daemon stop` when - it's idle, run by an operator or supervisor, not this client. +- 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 + 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 + is `simlock daemon stop` when it's idle, run by an operator or supervisor, + not this client. - It does not expose a role the daemon itself would reject — `simlock/admin` showing you `stopDaemon`/`runNuke`/etc. is a TypeScript-editor convenience, not the actual gate. The daemon's own role check is what diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3ef55814c..4a51d5fad 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -14,9 +14,8 @@ a warning. Inspect the effective, merged configuration at any time with | `warmPool.quarantine.retryBackoffMs` | Delay before the first quarantine purge retry. | `30 seconds` | | `warmPool.quarantine.retryBackoffMultiplier` | Growth factor applied to the backoff after each failed retry. | `2` | | `warmPool.quarantine.maxRetryBackoffMs` | Cap on the quarantine retry backoff. | `5 minutes` | -| `lease.heldTtlBackstopMs` | Backstop TTL for held-mode leases, in case the holding process dies without releasing. | `1 hour` | -| `lease.detachedTtlMs` | TTL for detached-mode leases before they must be renewed with `simlock lease renew`. | `15 minutes` | -| `lease.heartbeatIntervalMs` | How often the daemon pings a held-mode connection that declared the `heartbeat` capability; each pong slides that connection's leases' TTL back out to a full `heldTtlBackstopMs`. Must be `<= lease.heldTtlBackstopMs / 4`. | `5 minutes` | +| `lease.defaultTtlMs` | TTL applied to a lease whose `lease.request` carried no `ttlMs` — **that request only**. It is *not* the renew fallback: a renew given no explicit TTL re-applies the lease's own stored width, so a lease granted for longer keeps it. A lease not renewed before its deadline expires and its device is reclaimed. | `15 minutes` | +| `lease.maxTtlMs` | Largest TTL a request or a renew may ask for. A larger `ttlMs` is rejected with `BAD_REQUEST` rather than silently clamped, so a caller is never left believing it has more time than it does. | `4 hours` | | `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`. | `false` | | `http.host` | Address the HTTP listener binds. `127.0.0.1` keeps it loopback-only; reaching it remotely is the operator's own tunnel (Tailscale, cloudflared, reverse proxy) — Simlock does no TLS termination in v1. | `127.0.0.1` | | `http.port` | Port the HTTP listener binds. Must be an integer `1`-`65535`. | `4700` | @@ -49,9 +48,42 @@ must be non-negative numbers (milliseconds and bytes, respectively). integer in `1`-`65535`. `ios.slim.enabled` is a boolean, `ios.slim.categories` an array of non-empty strings, and `ios.slim.bootTimeoutMs` a positive number. +`lease.defaultTtlMs` and `lease.maxTtlMs` must be positive numbers, and +`lease.defaultTtlMs` must be `<=` `lease.maxTtlMs`. A config that violates +either rule is **rejected at load and the daemon does not start**, naming the +offending key — it is not clamped to something the operator did not write. +That is the opposite treatment from the retired keys below, which are only +warned about and ignored: an unrecognized key is a leftover, while a TTL pair +that contradicts itself has no safe interpretation to fall back on. + +`lease.maxTtlMs` bounds what a request or a renew may **ask for**; it is not +re-applied to leases that already exist. A lease holding a larger stored +`ttlMs` — granted before an operator lowered the cap, or carried over from an +older record — keeps re-applying that width on every body-less renew, so +lowering the cap does not shorten it. Release it, or renew it once with an +explicit smaller `--ttl`, and the new width sticks from then on. See [CLI.md](CLI.md#simlock-config-get-keyset-key-value) for the `simlock config` command 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. +**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 +new key's default, not the value it wrote: + +| Old key | What it did | What to write instead | +| --- | --- | --- | +| `lease.detachedTtlMs` | TTL for detached-mode leases. | `lease.defaultTtlMs`, which means the same thing for the one lease kind that is left. Copy the value across; it is not carried over for you. | +| `lease.heldTtlBackstopMs` | Backstop TTL behind a held lease. | Nothing. There is no separate backstop any more: a lease's TTL *is* its deadline. | +| `lease.heartbeatIntervalMs` | Daemon ping interval for held connections. | Nothing. The daemon-initiated heartbeat is gone; clients renew on their own timer. | + +A warning rather than a hard failure keeps an old config bootable, and a +warning rather than an alias keeps the key set honest — there is one name for +this setting, and it is the one in the table above. + ## Device roots Simlock keeps every device it creates inside a root it owns, one per platform, diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 5fef25874..d68ee3084 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -7,16 +7,26 @@ 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 | implemented | | `lease.queued` | request id, queue position | no capacity; request entered the wait queue | LeaseAcquisitionCoordinator | implemented | -| `lease.granted` | lease id, device id, requester, mode (held/detached) | a device was assigned and handed out | LeaseLifecycle | implemented | -| `lease.renewed` | lease id, new deadline | an explicit `simlock lease renew` succeeded (either mode), **or** a held-mode connection that declared the `heartbeat` capability answered a `lease.heartbeat` push (fires once per lease per `lease.heartbeatIntervalMs` while the holder stays alive) | LeaseLifecycle | implemented | -| `lease.released` | lease id, device id, reason (closed/explicit/killed/orphaned/device-lost), owner id | holder connection closed, explicit release, (orphaned) a `held` lease found still persisted at daemon startup, which cannot have a live holder across a restart, or (device-lost) a leased device could not be recovered after it stopped running outside simlock | LeaseLifecycle | implemented | -| `lease.expired` | lease id, device id, owner id | TTL backstop fired without a heartbeat sliding it first — for a capability-declaring holder this means it stopped ponging (crashed, hung, or lost its socket); for one that never declared the capability it means the grant-time TTL (or the last explicit `simlock lease renew`) simply ran out, exactly as before this change | LeaseLifecycle | 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 | implemented | ## Device lifecycle diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 92eb2d35e..cd5abafa3 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -19,14 +19,24 @@ 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 this actually changed. -## Leases are detached-only over HTTP - -Every lease granted through this API is **detached**: TTL-bound, kept alive -by `POST /v1/leases/:id/renew`, never by a held connection. HTTP is -stateless — "held lease = live connection" does not survive a real network — -so there is no held mode here and no WebSocket held-mode emulation. A lease -that stops renewing expires via the same TTL machinery `simlock lease ---detach` uses; the device is reclaimed normally. +## 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 +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 +transport. Closing a connection, dropping a tunnel, or losing the client +releases nothing; a lease that stops renewing expires at `expiresAt` and its +device is reclaimed normally. + +That is the whole liveness story here, and it is worth stating plainly what +it costs: a client that vanishes without calling `DELETE /v1/leases/:id` +holds its device until `expiresAt` — at most the lease's own TTL after its +last renew: `lease.defaultTtlMs` unless the request asked for more, never +more than `lease.maxTtlMs`. Ask for a shorter `ttlMs` on the request if you +want a tighter bound. Acquisition is an async resource, not a blocking call: `POST /v1/lease-requests` returns as soon as the request exists (queued, or already @@ -62,7 +72,21 @@ enforced per-resource rather than as a role gate. ## Endpoints All routes are under `/v1`, JSON bodies both ways, additive evolution only — -new fields, never removed or repurposed ones. +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 +it applies below: + +- **`mode` is gone** from the lease record the operator routes serialize + (`GET /v1/status`, `GET /v1/leases`), and **`lastRenewedAt` and the stored + `ttlMs` are new on it** — there is one kind of lease now, and the fields + that described the split went with it. +- **A `ttlMs` above `lease.maxTtlMs` is `400 BAD_REQUEST`** where it used to + be accepted. +- **The `ttlMs` a lease reports is the lease's own width**, not a value the + gateway remembered per request. + +Routes, status codes, and every other field are unchanged. ### `GET /v1/healthz` @@ -97,15 +121,15 @@ Role: `agent`. Enqueues a device request. ``` `platform` and `device` are required; `os` defaults to the newest installed -runtime; `ttlMs` defaults to `lease.detachedTtlMs`; `timeoutMs` (optional) is -enforced daemon-side so a vanished client can't hold a queue slot forever. -`full` (optional, default `false`) opts this request out of iOS slim mode — -platform-neutral in shape, but only the iOS driver acts on it (as "do not -slim"); Android ignores it. A `full: true` request never matches, and never -shares a pool key with, a slim device, so it can wait for a fresh device to -provision or force a re-provision of one already running, even while slim -devices sit idle in the warm pool. See [CONFIGURATION.md](CONFIGURATION.md) -for what slim mode disables. +runtime; `ttlMs` defaults to `lease.defaultTtlMs` and is `400 BAD_REQUEST` +above `lease.maxTtlMs`; `timeoutMs` (optional) is enforced daemon-side so a +vanished client can't hold a queue slot forever. `full` (optional, default +`false`) opts this request out of iOS slim mode — platform-neutral in shape, +but only the iOS driver acts on it (as "do not slim"); Android ignores it. A +`full: true` request never matches, and never shares a pool key with, a slim +device, so it can wait for a fresh device to provision or force a re-provision +of one already running, even while slim devices sit idle in the warm pool. See +[CONFIGURATION.md](CONFIGURATION.md) for what slim mode disables. `allowDownload` is now clamped through `config.downloads.policy` the same way the socket protocol always was (**bug fix, 0.3.0**): before this @@ -222,21 +246,32 @@ and still answer `403 FORBIDDEN` for another requester's request — that envelope stays HTTP-specific until [#72](https://github.com/callstackincubator/simlock/issues/72). -`expiresAt` is always the authoritative deadline. After a **daemon** restart -the gateway no longer remembers a per-request `ttlMs`, so the payload reports -the lease's mode default (the interval a body-less renew applies from then -on) and may omit `requestId`; schedule renewals from `expiresAt`, not from -`ttlMs`. +`expiresAt` is always the authoritative deadline, and `ttlMs` is always the +lease's own width — the TTL it was granted with, or last renewed with when a +renew carried one. The daemon stores it on the lease record, so it survives a +**daemon** restart along with the deadline and the restored TTL timer; a +payload served after a restart may still omit `requestId`, which was only +ever gateway-side. Schedule renewals from `expiresAt` rather than from +`ttlMs` all the same: the deadline is the fact, the width is how far the next +body-less renew will push it. ### `POST /v1/leases/{id}/renew` -Role: `agent` (own lease). Body `{ "ttlMs": 900000 }` (optional; defaults to -the lease's own mode default). Resets the deadline to now + ttl. +Role: `agent` (own lease). Body `{ "ttlMs": 900000 }` — optional, and +omitting it re-applies the lease's own `ttlMs` rather than +`lease.defaultTtlMs`, so a lease keeps the width it was granted with. A +`ttlMs` above `lease.maxTtlMs` is `400 BAD_REQUEST`; one below it changes the +lease's width from this renew on. Either way the deadline resets to now + ttl, +regardless of how much time was left. This is the only thing that keeps a +lease alive. → `200 { "leaseId": "lse_9f2c", "expiresAt": "...", "notices": [] }` -`notices` carries device-health facts observed since the previous renew for -this lease — `{"event":"device_unhealthy"}`, +`notices` is an HTTP-side convenience, not part of the socket contract's +`lease.renew` response: `LeaseNoticeBuffer` (`src/http/notices.ts`) collects +the owner-routed device-health facts a socket client would have received as +pushes, and drains them here. It carries the facts observed since the +previous renew for this lease — `{"event":"device_unhealthy"}`, `{"event":"device_recovered","attempts":1}` — so a polling-only client learns its device blinked without holding a stream open. @@ -244,7 +279,14 @@ learns its device blinked without holding a stream open. Role: `agent` (own lease). Server-Sent Events for live health pushes on this lease: `device_unhealthy`, `device_recovered`, `lease_lost` (ends the -stream). The same facts held mode relays on stderr today. +stream). The same facts a running `simlock lease` relays on stderr. Losing +this stream tells you nothing about the lease — it is still yours until +`expiresAt`; reconnect, or read the health facts from `renew`'s `notices`. + +`lease_lost` is the one fact `notices` cannot carry: it ends the lease, so +there is nothing left to renew and nothing to drain the buffer on. A polling +client learns it the other way round — the next `POST /v1/leases/{id}/renew` +against an ended lease answers `404 UNKNOWN_LEASE`. ### `DELETE /v1/leases/{id}` @@ -291,7 +333,7 @@ Every failure is the same shape the daemon protocol uses: - **Daemon restart.** In-flight lease requests are in-memory and do not survive, same as the socket protocol's queue today. A client polling a request id from before the restart gets `404 UNKNOWN_LEASE_REQUEST`; if its - grant had actually landed before the crash, the persisted detached lease + grant had actually landed before the crash, the persisted lease answers a retried `POST` with `409 REQUESTER_ALREADY_LEASED` naming the lease id, which the client then `GET`s to recover its state. This is the documented recovery loop: `404` → re-request → (maybe) `409` → `GET`. @@ -309,9 +351,11 @@ Every failure is the same shape the daemon protocol uses: request, instead of being refused — every route but the routes that don't dispatch at all (`GET /v1/healthz`) can block briefly on a cold start. - **Shutdown.** `simlock daemon stop` closes the HTTP listener (and any open - connection, in-flight SSE streams included) before releasing held leases - or tearing down the lease engine, so no HTTP request can run against a - stopping daemon. + connection, in-flight SSE streams included) before tearing down the lease + engine, so no HTTP request can run against a stopping daemon. Stopping the + daemon does not release anything: leases persist, and the next daemon + restores each one's TTL timer from its deadline. A lease whose deadline + passed while no daemon was running expires as soon as one is. ## Not implemented diff --git a/docs/adr/0004-ttl-first-leases-on-every-transport.md b/docs/adr/0004-ttl-first-leases-on-every-transport.md index e77939b1a..16017df5c 100644 --- a/docs/adr/0004-ttl-first-leases-on-every-transport.md +++ b/docs/adr/0004-ttl-first-leases-on-every-transport.md @@ -1,10 +1,15 @@ # 0004. TTL-first leases on every transport -- **Status:** Proposed +- **Status:** Accepted — not yet implemented - **Date:** 2026-09-05 - **Issue:** [#114](https://github.com/callstackincubator/simlock/issues/114) -- **Supersedes:** nothing (narrows ADR 0003 §8's `lease.heartbeat` push and - the held/detached split in `docs/CLI.md`) +- **Supersedes:** nothing. Narrows [ADR + 0003](0003-one-typed-daemon-contract-behind-every-frontend.md): §3's + `lease.heartbeat` operation row, §8's `lease.heartbeat` connection-scoped + push and the held set kept for release-on-close, §9's rule that a `ttlMs` + on a held `lease.request` is `BAD_REQUEST`, §10's `onLeaseLost` firing for + each held lease when a connection dies, and §10/§11's lazy-only MCP + reconnect. Also narrows the held/detached split in `docs/CLI.md`. ## Context @@ -36,9 +41,19 @@ for a `ttlMs` on the wrong mode are all costs of that one coupling. 2. **"Held" is a client policy, not a daemon mode.** The CLI's default `simlock lease` still prints one result line and stays alive; what it does while alive is renew on a timer (one third of the TTL) and release on - exit, parent death, or a catchable signal. `--detach` means "do not stay + exit, parent death, or a catchable signal. A transient renew failure is + retried on the next tick; a renew answered `UNKNOWN_LEASE` means the + daemon already ended the lease, and a holder exits the way a `lease-lost` + push ends it. `--detach` means "do not stay alive"; the lease it returns is not a different kind of lease. MCP does - the same for the session's lease. Nothing in the daemon knows or cares + the same for the session's lease. Its renew timer is what drives its + reconnect: when the timer fires against a dead client, the session + reconnects to a daemon that is already listening and renews, instead of + waiting for the next tool call and letting its own lease expire while + idle. The timer never launches a daemon; auto-launch stays a tool-call + concern (an operator's `daemon stop` must not be undone by an idle + session), so a lease held across a stopped daemon expires unless the + daemon is back before its deadline. Nothing in the daemon knows or cares which policy a client follows. 3. **Connection close means nothing to a lease.** The daemon keeps no per-connection lease state and releases nothing when a connection @@ -48,10 +63,16 @@ for a `ttlMs` on the wrong mode are all costs of that one coupling. 4. **The daemon-initiated heartbeat goes away.** `lease.heartbeat`, the `heartbeat` hello capability, `lease.heldTtlBackstopMs`, and `lease.heartbeatIntervalMs` are removed. `lease.detachedTtlMs` becomes - `lease.defaultTtlMs` (default 15 minutes, applied when a request carries - no `ttlMs`) and a new `lease.maxTtlMs` (default 4 hours) caps what a - request or renew may ask for; a larger value is `BAD_REQUEST`. `mode` on - `lease.request` is removed; `ttlMs` is accepted on every request. + `lease.defaultTtlMs` (renamed in the key set, not aliased: an old key + warns and is ignored, and its value is not carried over; default 15 + minutes, applied when a request carries no `ttlMs`). A lease records the + width it was granted with, or last renewed with; a `lease.renew` that + names no `ttlMs` re-applies that width rather than `lease.defaultTtlMs`, + so a lease granted for four hours does not shrink to fifteen minutes the + first time something renews it. A new `lease.maxTtlMs` (default 4 hours) + caps what a request or renew may ask for; a larger value is + `BAD_REQUEST`. `mode` on `lease.request` is removed; `ttlMs` is accepted + on every request. 5. **Lease-scoped pushes stay.** `lease-lost`, `device-unhealthy`, and `device-recovered` still go to every live connection whose principal owns the lease (ADR 0003 §8), and polling clients still read them from renew's @@ -66,13 +87,35 @@ for a `ttlMs` on the wrong mode are all costs of that one coupling. - A CLI or MCP holder that exits normally still releases at once, because release-on-exit is its own policy. A holder killed with `SIGKILL` or lost with its machine no longer frees its device on socket close; the device - sits until `expiresAt`, at most `lease.defaultTtlMs` after the last renew - (15 minutes by default, against today's immediate release). This is the - one behaviour change a local user can notice, and the price of a single - mechanism. A machine-sleep or socket hiccup, conversely, no longer costs a - held lease. + sits until `expiresAt` — at most the lease's own TTL after the last renew: + `lease.defaultTtlMs` (15 minutes by default) unless the request asked for + more, never more than `lease.maxTtlMs`. That is the one behaviour change a + local user can notice, and the price of a single mechanism. A machine-sleep + or socket hiccup, conversely, no longer costs a held lease. - The daemon's held-lease bookkeeping (the held set kept for 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 + 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 + one-off exception, under this ADR's "Breaking for 0.x" consequence below: + `mode` leaves the lease record the operator routes serialize, and + `lastRenewedAt` and the stored `ttlMs` arrive on it; a `ttlMs` above + `lease.maxTtlMs` becomes `400` where it used to be accepted; and the + `ttlMs` a lease reports is its own width rather than a value the gateway + remembered per request. `docs/HTTP-API.md` states it where it applies. +- The lease record gains `lastRenewedAt`, set at grant and on every renew, + replacing the derived `lastHeartbeatAt` decoration — which was computed as + `ttlDeadline - heldTtlBackstopMs` and has no answer once TTLs are + per-lease. +- The socket wire moves to protocol 4 with no compatibility shim; under ADR + 0003 §6's honesty rule both sides advertise `{min: 4, max: 4}`. +- `lease.defaultTtlMs` and `lease.maxTtlMs` are validated together at load + (`defaultTtlMs <= maxTtlMs`, both positive); a violating config fails the + daemon start, the same way an invalid `lease.*` value already does today. + Retired keys warn and are ignored. - 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`, diff --git a/docs/adr/README.md b/docs/adr/README.md index eb39f9b9f..d1600078a 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,5 +23,5 @@ Status values: | [0001](0001-simlock-owned-device-roots.md) | Simlock-owned device roots | Accepted | | [0002](0002-opt-in-slim-ios-simulators.md) | Opt-in slim iOS simulators | Accepted | | [0003](0003-one-typed-daemon-contract-behind-every-frontend.md) | One typed daemon contract behind every frontend | Accepted | -| [0004](0004-ttl-first-leases-on-every-transport.md) | TTL-first leases on every transport | Proposed | +| [0004](0004-ttl-first-leases-on-every-transport.md) | TTL-first leases on every transport | Accepted — not yet implemented | | [0005](0005-gateway-and-worker-modes.md) | Gateway and worker modes | Proposed | diff --git a/docs/known-pitfalls.md b/docs/known-pitfalls.md index 90cb05bd8..23088f8c6 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -1,19 +1,53 @@ # Known pitfalls +## A SIGKILLed lease holder keeps its device until the TTL expires + +A lease ends in exactly one of two ways: somebody releases it, or its TTL +runs out ([ADR 0004](adr/0004-ttl-first-leases-on-every-transport.md)). A +running `simlock lease` — or an MCP session — releases on the way out, so a +normal exit, a `SIGINT`/`SIGTERM`, or the death of the holder's parent all +free the device at once, exactly as before. That is the holder's own policy, +though, and it needs the holder to run code. + +**The pitfall:** a holder killed with `SIGKILL`, or lost with its machine, +runs nothing. Nothing else steps in for it — the daemon released leases on +socket close before ADR 0004 and no longer does, on any transport — so the +device stays `leased` until `ttlDeadline`, at most the lease's own TTL after +its last renew: `lease.defaultTtlMs` (15 minutes by default) unless the +request asked for more, never more than `lease.maxTtlMs`. `simlock status` shows +the lease and its "last renewed" time throughout; an operator who does not +want to wait can end it now with `simlock release `. + +**Why it is accepted:** the alternative is a `releaseOnDisconnect` flag +honoured only by transports that have a connection, which puts +per-connection lease state back into the daemon and at every gateway hop, and +gives "when does this lease end" a second answer that HTTP can never provide. +ADR 0004 considered and rejected it; a short default TTL is the accepted +trade, and it buys the reverse case too — a machine sleep, a daemon upgrade, +or a socket hiccup no longer costs a live holder its device. + +**The knob:** `lease.defaultTtlMs` bounds the leak globally, and `--ttl` (or +`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). + ## Orphaned lease holders (resolved) -The primary lease mechanism is process-held: `simlock lease` runs in the -background, holds an open socket to the daemon (connection-alive acts as the -heartbeat), and the agent kills the process to release the lease. +`simlock lease` runs in the background, renews its lease on a timer, and +releases it when it exits. **The pitfall:** if the agent crashed or was killed, its backgrounded `lease` process did *not* die with it — it got reparented (to launchd on macOS) and -kept the socket open, holding the lease indefinitely. This silently -reintroduced the "crashed agent holds a device forever" problem the tool -exists to solve, and it blocked CLI held mode from declaring the heartbeat -capability: a reparented holder is alive and would answer heartbeats -forever, which would have turned the bounded TTL-backstop leak into an -unbounded one. +kept running, holding the lease indefinitely. This silently reintroduced the +"crashed agent holds a device forever" problem the tool exists to solve. + +Under ADR 0004 it is the one failure the TTL cannot bound. Every other way of +losing a holder ends at the deadline, because nothing is renewing (see the +section above). A reparented holder is *alive*: its renew timer keeps firing +against a lease nobody wants any more, pushing the deadline out ahead of +itself forever. The TTL is a bound on silence, and this holder is not +silent. **Fix:** the holder watches its parent through the `ParentWatch` port (`src/ports/parent-watch.ts`) and self-terminates the moment that parent @@ -29,11 +63,11 @@ native addon, which this package does not take on, so the shipped adapter (`NodeParentWatch`) instead polls `process.kill(pid, 0)` for liveness — portable across platforms with no native dependency. It satisfies the same `ParentWatch` port a future native adapter would, so replacing it later -touches only that one file. CLI held mode now declares the `heartbeat` -capability, same as MCP. +touches only that one file. -Machine sleep and zombie sockets still fall back to the daemon-side TTL -backstop; this fix is about a holder outliving its owner, nothing more. +This fix is about a holder outliving its owner, nothing more. A holder that +dies without running its release path is the section above, and the TTL is +what bounds that one. ## Crash recovery cannot restore in-device session state @@ -46,8 +80,11 @@ the process and a reboot cannot bring it back: a launched app, a `log stream`, an Appium/XCUITest session, a port forward. Simlock has no visibility into what was running there, so it cannot even enumerate what was lost, let alone restore it. This is why recovery notifies the holder -(`device-unhealthy` / `device-recovered` in held mode) rather than healing -silently — the agent has to notice and re-establish its own session state. +(`device-unhealthy` / `device-recovered` — pushed to a running `simlock +lease`'s stderr, and drained from the `notices` array on `POST +/v1/leases/{id}/renew` by a polling HTTP client, which has no connection to +push to) rather than healing silently — the agent has to notice and +re-establish its own session state. Detection also has residual latency by design: a crash isn't declared until `health.stableObservations` consecutive `stopped` observations, spaced @@ -227,7 +264,7 @@ JSON lines and MCP `notifications/progress`) has no `downloading` stage. Both drivers' `resolveSpec` — where a runtime or system-image install actually happens — runs before `LeaseAcquisitionCoordinator#drive`'s provisioning step, and `Driver.resolveSpec`'s signature carries no progress callback the -way `provision`/`makeReady` do. A held-mode CLI or MCP caller waiting on a +way `provision`/`makeReady` do. A CLI or MCP caller waiting on a multi-minute install today sees nothing on the wire between its request and either the eventual grant or a timeout; the only visibility is the daemon's own `component.install-started` bus event (`simlock events --follow`) and log @@ -291,12 +328,18 @@ the daemon's core: **The pitfall:** both reset on a daemon restart (in-memory, no persistence), and both are HTTP-specific reimplementations of "track something about a -request/lease across calls" that the socket frontends don't need because -they hold a live connection instead. 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 (`404` → re-request → maybe `409` → `GET`), -which exists specifically because the tracker does not survive a restart. +request/lease across calls". The socket frontends need neither, but not because +a connection holds anything — under ADR 0004 it holds nothing. They need +neither because a socket client is *there* when the fact happens: the daemon +pushes a device-health fact to whatever connections own the lease at that +moment, and a request's progress rides the call that made it. A polling HTTP +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 +(`404` → re-request → maybe `409` → `GET`), which exists specifically because +the tracker does not survive a restart. **Status:** known, and explicitly called out as the ADR's own unfinished seam, not an oversight: "the HTTP tracker and notice buffer remain the known