From 892d7a9479f611d58e8d2b12db4b93494ebc34ad Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 19:31:51 +0000 Subject: [PATCH 1/8] docs: describe TTL-first leases end state, accept ADR 0004 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rewrite every user-facing document for the lease model ADR 0004 decides: one kind of lease, TTL-bound on every transport, kept alive only by a client-initiated lease.renew. Held mode stops being 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 — and connection close releases nothing anywhere. Flip ADR 0004 to "Accepted — not yet implemented" in the ADR and in the index, so the docs below are the specification the code catches up to. Config: lease.defaultTtlMs and lease.maxTtlMs documented; the three retired lease.* keys get a migration table. Contract: lease.heartbeat, the heartbeat capability, and mode are gone; protocol 4. Behaviour: a holder killed with SIGKILL keeps its device until the TTL expires, stated wherever held mode used to promise instant release, and recorded as a known pitfall with its knob. Docs only; no src/ or e2e/ changes. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- CHANGELOG.md | 94 ++++++++++ README.md | 8 +- docs/ABOUT.md | 13 +- docs/ARCHITECTURE.md | 166 +++++++++--------- docs/CLI.md | 141 +++++++++------ docs/CLIENT.md | 52 ++++-- docs/CONFIGURATION.md | 21 ++- docs/EVENTS.md | 8 +- docs/HTTP-API.md | 57 +++--- ...004-ttl-first-leases-on-every-transport.md | 2 +- docs/adr/README.md | 2 +- docs/known-pitfalls.md | 63 +++++-- 12 files changed, 427 insertions(+), 200 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e863c81f..bbf451f8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,99 @@ # 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. + +### ⚠ 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. +- **`lastHeartbeatAt` on the lease record is now `lastRenewedAt`**, set at + grant and on every renew. `simlock status` renders it as "last renewed". +- **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:** `lease.detachedTtlMs` is renamed `lease.defaultTtlMs` (same + 15-minute default; a config file still carrying the old key is read as the + new one, with a warning naming it). `lease.heldTtlBackstopMs` and + `lease.heartbeatIntervalMs` are removed — `simlock config` warns about + them and ignores them, like any other unrecognized key. New: + `lease.maxTtlMs`, default 4 hours. See `docs/CONFIGURATION.md#retired-lease-keys`. +- **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 `lease.defaultTtlMs` after its last + renew, 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. + +### Features + +- **cli:** `simlock lease` (without `--detach`) renews its own lease at one + third of the remaining TTL for as long as it runs, 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 below describes the decided end + state, and the code catches up to it. +- 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..a4992f78a 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,6 @@ simlock lease --platform ios --device "iPhone 16" --detach "deviceId": "dev_1a2b", "requesterId": "agent-1", "ownerId": "agent-1", - "mode": "detached", "grantedAt": 1735689600000, "ttlDeadline": 1735690500000 }, @@ -76,8 +75,10 @@ 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 +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 both of those 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)). @@ -104,7 +105,6 @@ 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, "ttlDeadline": 1735690530000 }, 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..933c81945 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -38,10 +38,11 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ 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 + 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 @@ -50,9 +51,13 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ 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. +- **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 remaining + 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 @@ -60,8 +65,9 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ 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 + 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 @@ -70,14 +76,11 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ 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. + mismatch or a refused handshake, only on "nothing is listening". The + session's lease survives that reconnect untouched: the daemon released + nothing when the old connection died, so the new client's first act is to + renew the lease it already has (`lease.list` tells it which), not to ask + whether the old one is still there or to request a second device. - **Daemon**: owns all state, serializes all decisions. Started on demand, reachable over a unix socket. @@ -275,29 +278,24 @@ 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 -warm-pool recovery port — a backgrounded reclaim marks its device with a +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): a holder that is still running renews against the new daemon +and never notices, and one that is gone loses its device at the deadline it +already had. 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. It 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 +389,45 @@ 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 lease record also + carries `lastRenewedAt`, set at grant and on every renew, which is what + `simlock status` renders as "last renewed". +- **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. This is what lets a gateway hop, a + suspended laptop, or a daemon upgrade cost a client its stream and not its + device. +- **"Holding" is a frontend policy over that one lease.** `simlock lease` + and the MCP session both renew at one third of the remaining TTL and + release on exit; 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 `lease.defaultTtlMs` after its last + renew. 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 +441,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,9 +496,8 @@ 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 +- `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. @@ -576,9 +580,11 @@ 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 +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), and a +polling-only client reads the same facts from `lease.renew`'s `notices` — +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. @@ -700,7 +706,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 (CLI lease-holder self-termination) ``` Real implementations are thin adapters wired up once at daemon startup; @@ -735,9 +741,9 @@ 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 +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..ceb7ac0e9 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,12 +42,13 @@ 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. @@ -56,8 +57,8 @@ still reports the specific code. ## 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 +78,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 +105,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,12 +140,13 @@ 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, +- `--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`. +- `--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. @@ -144,8 +154,8 @@ 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): @@ -160,9 +170,36 @@ 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,"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. + +Then the process stays alive, and while it is alive it does two things for +you. It **renews** the lease every third of the remaining TTL, so the +deadline keeps moving out for as long as the process is there. 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 `lease.defaultTtlMs` (15 minutes by default) after +the last renew. 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). +Dropping the connection is not itself a release: a daemon restart, a +suspended machine, or a socket hiccup costs you nothing but the renewals you +miss while it lasts. + `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,12 +216,8 @@ 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 +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 @@ -204,9 +237,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"} @@ -216,7 +249,7 @@ 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 +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: @@ -228,9 +261,9 @@ 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 +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. 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 @@ -239,21 +272,17 @@ 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. +Extend a lease's TTL. 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`). +Without `--ttl`, the new deadline is now + `lease.defaultTtlMs` (15m) — not +the TTL this lease was granted with, which the daemon does not keep. A +`--ttl` larger than `lease.maxTtlMs` (4h) is a `BAD_REQUEST` (exit 2). 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. +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`. ## Reaching a leased device @@ -346,7 +375,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 +383,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. @@ -373,9 +402,10 @@ 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` +tool surface for one agent session. The session renews its 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. @@ -441,7 +471,8 @@ 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` +[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. @@ -481,8 +512,8 @@ each rule *would* take (rule name, target, reason) without executing. 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 +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 diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 4f3179111..cf21a1ee8 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -38,6 +38,18 @@ 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 a frontend that means to hold a device for a while +runs its own renew timer over it — the CLI and the MCP server both renew at +one third of the remaining 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,11 +82,22 @@ 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: @@ -92,13 +115,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. }); ``` @@ -155,10 +180,13 @@ doesn't end up holding the result. This is recorded as a known gap in 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. + [ARCHITECTURE.md](ARCHITECTURE.md) and [ADR + 0003](adr/0003-one-typed-daemon-contract-behind-every-frontend.md) §6 for + why: stopping a daemon out from under its users kills every queued lease + request on the machine, and leaves every lease it was serving to burn 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..816fdc972 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`, and to a `lease renew` given no explicit TTL. 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,25 @@ 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. 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: + +| Old key | What happens now | +| --- | --- | +| `lease.detachedTtlMs` | Renamed. A config file that still carries it is read as `lease.defaultTtlMs` — same meaning, same default — and `simlock config` warns once, naming the new key. | +| `lease.heldTtlBackstopMs` | Removed. There is no separate backstop any more: a lease's TTL *is* its deadline. Warned about and ignored, like any other unrecognized key. | +| `lease.heartbeatIntervalMs` | Removed with the daemon-initiated heartbeat itself. Warned about and ignored. | + +The mapping exists so an existing config keeps working rather than silently +falling back to a default; it is not a compatibility path to build on. Set +`lease.defaultTtlMs` and delete the old key. + ## 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..a74528e73 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -13,10 +13,10 @@ in short: `subject.past-tense-fact`, emitted post-commit, facts not commands. |---|---|---|---|---| | `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 | +| `lease.renewed` | lease id, new deadline | a `lease.renew` succeeded — whether it came from `simlock lease renew`, `POST /v1/leases/{id}/renew`, or the renew timer a running `simlock lease` / MCP session keeps over its own lease. There is one renew path and this is it | LeaseLifecycle | implemented | +| `lease.released` | lease id, device id, reason (explicit/killed/device-lost), owner id | an explicit `lease.release` (which is what a `simlock lease` holder does on its way out), (killed) an operator `release --all` or `nuke`, or (device-lost) a leased device could not be recovered after it stopped running outside simlock. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented | +| `lease.expired` | lease id, device id, owner id | the lease's deadline passed with no `lease.renew` behind it — the grant-time TTL, or the TTL of the last renew, simply ran out. This is the one way a lease ends without somebody asking, and the only bound on a holder that was killed outright | LeaseLifecycle | implemented | | `lease.rejected` | request spec, reason (timeout/no-wait/unresolvable-spec/already-leased/boot-timeout/killed/cancelled) | a request ended without a grant; `cancelled` is an explicit single-request cancel (`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..16c0d4749 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -19,14 +19,23 @@ 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 `lease.defaultTtlMs` after its +last renew. 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 @@ -97,7 +106,8 @@ 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 +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 @@ -222,16 +232,19 @@ 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. The lease itself survives a +**daemon** restart — the next daemon restores its TTL timer from the +persisted deadline — but the gateway no longer remembers a per-request +`ttlMs`, so the payload reports `lease.defaultTtlMs` (the interval a +body-less renew applies from then on) and may omit `requestId`; schedule +renewals from `expiresAt`, not from `ttlMs`. ### `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. +`lease.defaultTtlMs`, and is `400 BAD_REQUEST` above `lease.maxTtlMs`). +Resets the deadline 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": [] }` @@ -244,7 +257,9 @@ 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 same facts from `renew`'s `notices`. ### `DELETE /v1/leases/{id}` @@ -291,7 +306,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 +324,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..68c744273 100644 --- a/docs/adr/0004-ttl-first-leases-on-every-transport.md +++ b/docs/adr/0004-ttl-first-leases-on-every-transport.md @@ -1,6 +1,6 @@ # 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 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..89b7d235a 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -1,19 +1,49 @@ # 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 `lease.defaultTtlMs` +(15 minutes by default) after the holder's last renew. `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 renewing, holding the lease indefinitely. This silently reintroduced the +"crashed agent holds a device forever" problem the tool exists to solve, and +it is worse under a TTL-only lease model than it was under connection-held +leases: a live reparented holder renews before every deadline, so the TTL +that bounds every *other* kind of lost holder (see the section above) never +bounds this one. A bounded leak became an unbounded one. **Fix:** the holder watches its parent through the `ParentWatch` port (`src/ports/parent-watch.ts`) and self-terminates the moment that parent @@ -29,11 +59,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 +76,9 @@ 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`, on a running `simlock lease`'s +stderr and in `lease.renew`'s `notices` for a polling client) 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 +258,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 From 250e479d42e276f4fea42c5bab5821b6631edeaf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 19:35:10 +0000 Subject: [PATCH 2/8] docs: tighten the TTL-lease rewrite after review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four fixes from an adversarial pass over the ADR 0004 doc rewrite: - ARCHITECTURE.md no longer prescribes an MCP reconnect sequence the ADR does not decide; it states the fact (the lease survives, the session picks it back up and keeps renewing) instead. - CLIENT.md stops attributing to ADR 0003 §6 a reason ADR 0004 invalidated. The decision is 0003's; what a daemon stop costs is now stated in 0004's terms - queued requests die, leases burn TTL with nothing to renew against. - CLI.md's `daemon stop` section says plainly that stopping the daemon does not touch leases, where an operator actually reads about it. - Re-wrap prose the rewrite left over the file's line width. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- CHANGELOG.md | 3 ++- README.md | 3 ++- docs/ARCHITECTURE.md | 39 +++++++++++++++++++++------------------ docs/CLI.md | 22 +++++++++++++++------- docs/CLIENT.md | 14 ++++++++------ docs/known-pitfalls.md | 3 ++- 6 files changed, 50 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbf451f8a..4c31826e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,7 +37,8 @@ keys, and one user-visible behaviour; see below. new one, with a warning naming it). `lease.heldTtlBackstopMs` and `lease.heartbeatIntervalMs` are removed — `simlock config` warns about them and ignores them, like any other unrecognized key. New: - `lease.maxTtlMs`, default 4 hours. See `docs/CONFIGURATION.md#retired-lease-keys`. + `lease.maxTtlMs`, default 4 hours. See + `docs/CONFIGURATION.md#retired-lease-keys`. - **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 diff --git a/README.md b/README.md index a4992f78a..7ce987b1a 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,8 @@ That's the whole interaction: ask for a platform and a device model, get 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 both of those for you — -renewing on a timer and releasing when it exits. This is the contract's own `LeaseGrant` shape, serialized +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)). diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 933c81945..041c88c8c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -42,8 +42,8 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ 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 + 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 @@ -67,8 +67,8 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ session does not own surfaces the daemon's own `FORBIDDEN` rather than a 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` + 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 @@ -77,10 +77,11 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ — 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". The - session's lease survives that reconnect untouched: the daemon released - nothing when the old connection died, so the new client's first act is to - renew the lease it already has (`lease.list` tells it which), not to ask - whether the old one is still there or to request a second device. + session's lease survives that 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) and keeps renewing it, 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. @@ -288,8 +289,9 @@ already had. 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. It 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 +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 @@ -497,8 +499,9 @@ capacity coordinator into these direct transactional call chains: lease/state safety, and delegates the driver operation to `ManagedDeviceLifecycle`. - `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. + 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 @@ -583,9 +586,9 @@ no way to know that state existed, let alone restore it. So the monitor emits 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), and a -polling-only client reads the same facts from `lease.renew`'s `notices` — -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 +polling-only client reads the same facts from `lease.renew`'s `notices` — 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. @@ -706,7 +709,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 lease-holder 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; @@ -743,8 +746,8 @@ 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) — 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 +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 ceb7ac0e9..d544c2bf4 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -146,9 +146,10 @@ granted. `simlock lease renew` before `ttlDeadline`, and end it with `simlock release`. - `--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. + 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 @@ -249,7 +250,8 @@ stderr 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 yours, still on its TTL, and must still be released the normal way. Recovery can instead +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: @@ -405,7 +407,8 @@ server auto-starts the daemon when needed and exposes the focused tool surface for one agent session. The session renews its 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` +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. @@ -513,7 +516,8 @@ each rule *would* take (rule name, target, reason) without executing. 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 leases whose -device is still marked `leased`, devices stuck mid-transition, and orphans. `--fix` applies the safe +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 @@ -586,7 +590,11 @@ 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 +`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, so a holder that is still running renews against the new daemon and +never notices. 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 diff --git a/docs/CLIENT.md b/docs/CLIENT.md index cf21a1ee8..387cb0837 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -179,14 +179,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 +- 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 - why: stopping a daemon out from under its users kills every queued lease - request on the machine, and leaves every lease it was serving to burn 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. + 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/known-pitfalls.md b/docs/known-pitfalls.md index 89b7d235a..e840ee271 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -78,7 +78,8 @@ 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`, on a running `simlock lease`'s stderr and in `lease.renew`'s `notices` for a polling client) rather than -healing silently — the agent has to notice and re-establish its own session state. +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 From 146c910b86b5dd71ed0786ca768a1fc100652cc5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 19:53:48 +0000 Subject: [PATCH 3/8] docs: settle the TTL-lease decisions the ADR left implicit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Apply the second review round's 15 findings. Six of them were places the docs hedged or guessed where ADR 0004 was silent; those are now stated as the end state PR A and PR B implement. - A running `simlock lease` does not reconnect (ADR 0003 §10 stands). On a dead connection it writes one DAEMON_CONNECTION_LOST line naming the lease and its ttlDeadline and exits 1, leaving the lease standing for a later invocation to renew. Exit 14 keeps its narrower meaning: the daemon ended the lease while the connection was alive. - The lease record stores its ttlMs, and a body-less renew re-applies that width. lease.defaultTtlMs applies only to a request that names no ttlMs, so a four-hour lease no longer shrinks to fifteen minutes on its first renew. This is what makes the holder's timer safe: it sends no TTL at all. - Renew cadence is "one third of the lease's TTL" everywhere, per ADR §2. - The MCP session reconnects eagerly from its renew timer rather than lazily on the next tool call, which would let its own lease expire in between. - lastRenewedAt is a new stored field, not a rename: lastHeartbeatAt was derived as ttlDeadline - heldTtlBackstopMs, which per-lease TTLs break. - No lease.detachedTtlMs alias. All three retired keys warn and are ignored like unknown keys, as the ADR says; the migration table says to copy the value across. Load-time rule added: both TTL keys positive, default <= max, rejected rather than clamped. Also: notices is HTTP-side (LeaseNoticeBuffer), never the socket lease.renew response; the protocol range {min: 4, max: 4} is stated in ARCHITECTURE's contract section, not only the changelog; EVENTS declares the lease payload removals a deliberate one-off exception to the additive-only rule and marks the four rows payload-pending; ADR 0004's Supersedes line names every ADR 0003 section it narrows; and the reparented-holder pitfall now explains that a TTL bounds silence, which a live renewing holder is not. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- CHANGELOG.md | 65 +++++++++---- docs/ARCHITECTURE.md | 96 +++++++++++++------ docs/CLI.md | 63 ++++++++---- docs/CLIENT.md | 17 ++-- docs/CONFIGURATION.md | 31 +++--- docs/EVENTS.md | 20 +++- docs/HTTP-API.md | 39 +++++--- ...004-ttl-first-leases-on-every-transport.md | 9 +- docs/known-pitfalls.md | 29 +++--- 9 files changed, 252 insertions(+), 117 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c31826e7..68be228ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,28 +24,48 @@ keys, and one user-visible behaviour; see below. `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. -- **`lastHeartbeatAt` on the lease record is now `lastRenewedAt`**, set at - grant and on every renew. `simlock status` renders it as "last renewed". +- **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:** `lease.detachedTtlMs` is renamed `lease.defaultTtlMs` (same - 15-minute default; a config file still carrying the old key is read as the - new one, with a warning naming it). `lease.heldTtlBackstopMs` and - `lease.heartbeatIntervalMs` are removed — `simlock config` warns about - them and ignores them, like any other unrecognized key. New: - `lease.maxTtlMs`, default 4 hours. See +- **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 rather than clamped. See `docs/CONFIGURATION.md#retired-lease-keys`. - **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 `lease.defaultTtlMs` after its last - renew, against today's immediate release on socket close. A holder that - exits normally, is `SIGTERM`ed, or whose parent dies still releases at + 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 @@ -65,14 +85,25 @@ keys, and one user-visible behaviour; see below. 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. +- **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 remaining TTL for as long as it runs, 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. + 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 @@ -86,8 +117,8 @@ keys, and one user-visible behaviour; see below. - 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 below describes the decided end - state, and the code catches up to it. + `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), diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 041c88c8c..485b3a599 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -76,12 +76,16 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ 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". The - session's lease survives that 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) and keeps renewing it, rather - than treating a dead connection as a lost device and requesting a second - one. + mismatch or a refused handshake, only on "nothing is listening". Under ADR + 0004 that reconnect is **eager, driven by the renew timer** rather than + lazy: when the timer fires against a dead client, `McpSession` rebuilds one + immediately, renews, and continues, instead of waiting for the next tool + call — a session that waited would let its own lease expire between tool + calls, which is exactly what the timer exists to prevent. The lease itself + 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. @@ -120,6 +124,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`, @@ -283,12 +297,15 @@ 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): a holder that is still running renews against the new daemon -and never notices, and one that is gone loses its device at the deadline it -already had. 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. It then recovers unleased +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. It 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 @@ -401,9 +418,16 @@ There is **one kind of lease**, on every transport ([ADR 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 lease record also - carries `lastRenewedAt`, set at grant and on every renew, which is what - `simlock status` renders as "last renewed". + 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 @@ -412,12 +436,18 @@ There is **one kind of lease**, on every transport ([ADR - **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. This is what lets a gateway hop, a - suspended laptop, or a daemon upgrade cost a client its stream and not its - device. + 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 remaining TTL and - release on exit; the CLI holder additionally watches its parent through + 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; 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 @@ -425,10 +455,12 @@ There is **one kind of lease**, on every transport ([ADR 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 `lease.defaultTtlMs` after its last - renew. 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 + 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). @@ -585,12 +617,16 @@ 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 every live connection whose principal owns the lease (`device-unhealthy` / -`device-recovered` on the wire, ADR 0003 §8 and ADR 0004 §5), and a -polling-only client reads the same facts from `lease.renew`'s `notices` — 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. +`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 diff --git a/docs/CLI.md b/docs/CLI.md index d544c2bf4..52d984b02 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -161,6 +161,8 @@ 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"}} @@ -179,13 +181,15 @@ The full line, with every field the contract defines: `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. +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 remaining TTL, so the -deadline keeps moving out for as long as the process is there. 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 +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. +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. @@ -193,13 +197,26 @@ 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 `lease.defaultTtlMs` (15 minutes by default) after -the last renew. If that matters, lower `lease.defaultTtlMs` or pass a shorter -`--ttl`; see +`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). -Dropping the connection is not itself a release: a daemon restart, a -suspended machine, or a socket hiccup costs you nothing but the renewals you -miss while it lasts. + +**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 ` from any +invocation picks it straight back up. 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 @@ -266,8 +283,10 @@ driver-level `udid` the grant returns on stdout. A `lease-lost` line is 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. The `reason` is whatever ended it — `device-lost` here, but equally -`expired` or `killed`. See [known-pitfalls.md](known-pitfalls.md) +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. @@ -277,10 +296,14 @@ forward) is gone whether or not recovery succeeds. Extend a lease's TTL. Renewal always resets the deadline to now plus the TTL, regardless of how much time was left. -Without `--ttl`, the new deadline is now + `lease.defaultTtlMs` (15m) — not -the TTL this lease was granted with, which the daemon does not keep. A -`--ttl` larger than `lease.maxTtlMs` (4h) is a `BAD_REQUEST` (exit 2). Exit 1 -if the lease is unknown or already expired (error code `UNKNOWN_LEASE`). +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 @@ -592,8 +615,10 @@ lines. `--follow` keeps streaming; `--since 1h` replays recent history. 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, so a holder that is still running renews against the new daemon and -never notices. A lease whose deadline passed while no daemon was running +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 diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 387cb0837..7900419e0 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -43,10 +43,12 @@ await client.close(); `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 a frontend that means to hold a device for a while -runs its own renew timer over it — the CLI and the MCP server both renew at -one third of the remaining TTL and release on exit, and that is ordinary -frontend code, not something this client does for you. There is no heartbeat +`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. @@ -105,8 +107,11 @@ 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. +- **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. diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 816fdc972..ef210e891 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -48,24 +48,31 @@ 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. +`lease.defaultTtlMs` and `lease.maxTtlMs` must be positive numbers, and +`lease.defaultTtlMs` must be `<=` `lease.maxTtlMs` — a config that violates +either rule is rejected when it loads, naming the offending key, rather than +being clamped to something the operator did not write. 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: - -| Old key | What happens now | -| --- | --- | -| `lease.detachedTtlMs` | Renamed. A config file that still carries it is read as `lease.defaultTtlMs` — same meaning, same default — and `simlock config` warns once, naming the new key. | -| `lease.heldTtlBackstopMs` | Removed. There is no separate backstop any more: a lease's TTL *is* its deadline. Warned about and ignored, like any other unrecognized key. | -| `lease.heartbeatIntervalMs` | Removed with the daemon-initiated heartbeat itself. Warned about and ignored. | - -The mapping exists so an existing config keeps working rather than silently -falling back to a default; it is not a compatibility path to build on. Set -`lease.defaultTtlMs` and delete the old key. +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 diff --git a/docs/EVENTS.md b/docs/EVENTS.md index a74528e73..58ec94253 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -7,16 +7,28 @@ 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. +> **Payload removals in the lease rows are a deliberate one-off exception** +> to events rule 6 ("treat payload shape as a public contract: additive +> changes only"). [ADR +> 0004](adr/0004-ttl-first-leases-on-every-transport.md) deletes the concept +> `lease.granted`'s `mode` reported, and makes two of `lease.released`'s +> reasons (`closed`, `orphaned`) unreachable — there is no connection close +> to release on and no startup sweep to orphan anything. Keeping dead fields +> and unreachable enum values to honour additive-only would leave the +> catalogue lying about what a consumer can observe. The exception is taken +> once, while the project is 0.x and the removal is already breaking for the +> contract, and it does not loosen the rule for anything else. + ## 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 | a device was assigned and handed out | LeaseLifecycle | implemented | -| `lease.renewed` | lease id, new deadline | a `lease.renew` succeeded — whether it came from `simlock lease renew`, `POST /v1/leases/{id}/renew`, or the renew timer a running `simlock lease` / MCP session keeps over its own lease. There is one renew path and this is it | LeaseLifecycle | implemented | -| `lease.released` | lease id, device id, reason (explicit/killed/device-lost), owner id | an explicit `lease.release` (which is what a `simlock lease` holder does on its way out), (killed) an operator `release --all` or `nuke`, or (device-lost) a leased device could not be recovered after it stopped running outside simlock. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented | -| `lease.expired` | lease id, device id, owner id | the lease's deadline passed with no `lease.renew` behind it — the grant-time TTL, or the TTL of the last renew, simply ran out. This is the one way a lease ends without somebody asking, and the only bound on a holder that was killed outright | LeaseLifecycle | implemented | +| `lease.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 16c0d4749..737b80ed5 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -33,9 +33,10 @@ 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 `lease.defaultTtlMs` after its -last renew. Ask for a shorter `ttlMs` on the request if you want a tighter -bound. +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 @@ -232,24 +233,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. The lease itself survives a -**daemon** restart — the next daemon restores its TTL timer from the -persisted deadline — but the gateway no longer remembers a per-request -`ttlMs`, so the payload reports `lease.defaultTtlMs` (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 -`lease.defaultTtlMs`, and is `400 BAD_REQUEST` above `lease.maxTtlMs`). -Resets the deadline to now + ttl, regardless of how much time was left. This -is the only thing that keeps a lease alive. +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. 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 68c744273..fb6bcabfc 100644 --- a/docs/adr/0004-ttl-first-leases-on-every-transport.md +++ b/docs/adr/0004-ttl-first-leases-on-every-transport.md @@ -3,8 +3,13 @@ - **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`, and §10's `onLeaseLost` firing + for each held lease when a connection dies. Also narrows the held/detached + split in `docs/CLI.md`. ## Context diff --git a/docs/known-pitfalls.md b/docs/known-pitfalls.md index e840ee271..1f0a62635 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -12,8 +12,9 @@ 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 `lease.defaultTtlMs` -(15 minutes by default) after the holder's last renew. `simlock status` shows +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 `. @@ -38,12 +39,15 @@ 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 renewing, holding the lease indefinitely. This silently reintroduced the -"crashed agent holds a device forever" problem the tool exists to solve, and -it is worse under a TTL-only lease model than it was under connection-held -leases: a live reparented holder renews before every deadline, so the TTL -that bounds every *other* kind of lost holder (see the section above) never -bounds this one. A bounded leak became 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 @@ -76,10 +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`, on a running `simlock lease`'s -stderr and in `lease.renew`'s `notices` for a polling client) 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 From 0ce1dba382570482b72843a48b0945800b4bff19 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 20:10:37 +0000 Subject: [PATCH 4/8] docs: record the MCP reconnect and events-payload decisions in ADR 0004 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Third review round, 14 findings. Two were decisions the docs had invented rather than inherited, so they are recorded in ADR 0004 itself — this PR is what accepts it — and every other doc now follows the record instead of leading it. - MCP's reconnect is timer-driven but never launches a daemon. ADR 0003 §10/§11 gave MCP one lazy trigger, the next tool call; Decision 2 now adds the renew timer as a second, so an idle session does not lose its lease waiting for a call that never comes, and restricts it to a daemon that is already listening. Auto-launch stays a tool-call concern, because an operator's `daemon stop` must not be undone by an idle session. The Supersedes line names §10/§11, and ARCHITECTURE, CLIENT and the changelog say the same thing. - The events payload removals are the ADR's exception to take, not EVENTS.md's. A Consequences bullet grants it once, while the package is 0.x; the EVENTS.md note now cites that bullet rather than granting it. Also settled: a renew that fails transiently on a live connection is retried on the next tick, while one answered UNKNOWN_LEASE ends the holder at exit 14 like a lease-lost push (CLI.md, ARCHITECTURE); and a TTL config that contradicts itself is rejected at load and the daemon does not start, which is deliberately not the warn-and-ignore treatment the retired keys get (CONFIGURATION, changelog). Corrections: the `lease.defaultTtlMs` config cell no longer claims to be the renew fallback, which was the round's most load-bearing error; cross-process `lease renew` needs an admin credential, so it joins the admin command list and the two places that showed it as a bare follow-up invocation; HTTP's additive-evolution promise names the one break ADR 0004 makes in it; `lease_lost` is documented as the fact `notices` cannot carry, since an ended lease answers renew with 404; the HTTP-tracker pitfall no longer explains itself by a connection holding something, since none does; MCP's README paragraph says manual lease renewal and that the server renews its own; `lease_simulator` takes the contract's `ttlMs`; and the stranded half-lines the rewrite left behind are re-flowed. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- CHANGELOG.md | 125 ++++++------ README.md | 28 +-- docs/ARCHITECTURE.md | 190 +++++++++--------- docs/CLI.md | 114 ++++++----- docs/CLIENT.md | 11 +- docs/CONFIGURATION.md | 11 +- docs/EVENTS.md | 20 +- docs/HTTP-API.md | 33 ++- ...004-ttl-first-leases-on-every-transport.md | 20 +- docs/known-pitfalls.md | 18 +- 10 files changed, 315 insertions(+), 255 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 68be228ab..4b624cace 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,87 +11,100 @@ 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** +- **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. + `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`. + `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 rather than clamped. See - `docs/CONFIGURATION.md#retired-lease-keys`. + 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`. - **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 + 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`. + 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. + 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. + 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. + `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. + 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 diff --git a/README.md b/README.md index 7ce987b1a..5c8e011b8 100644 --- a/README.md +++ b/README.md @@ -77,11 +77,10 @@ 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, renew it before `ttlDeadline` to keep it, or let its TTL expire. Drop `--detach` and -`simlock lease` stays running instead, doing both of those 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)). +`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 @@ -161,11 +160,12 @@ 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 @@ -173,10 +173,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/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 485b3a599..cfd4e977f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -37,27 +37,26 @@ 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, 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. + 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 remaining - 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 + 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. + 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 @@ -66,26 +65,32 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ `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. 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 §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". Under ADR - 0004 that reconnect is **eager, driven by the renew timer** rather than - lazy: when the timer fires against a dead client, `McpSession` rebuilds one - immediately, renews, and continues, instead of waiting for the next tool - call — a session that waited would let its own lease expire between tool - calls, which is exactly what the timer exists to prevent. The lease itself - 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. + 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 §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. @@ -200,9 +205,12 @@ 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. +`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 four 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 @@ -298,17 +306,16 @@ 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. It 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 +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 @@ -413,54 +420,55 @@ There is **one kind of lease**, on every transport ([ADR - **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 + `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. + 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; 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 + 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). diff --git a/docs/CLI.md b/docs/CLI.md index 52d984b02..fd19f8466 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -184,15 +184,19 @@ 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. -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. +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 @@ -213,8 +217,11 @@ one error line naming the lease and its deadline, and exits `1`: ``` Nothing was released. The lease is still granted to you on the daemon, still -counting down, and a later `simlock lease renew ` from any -invocation picks it straight back up. This is not exit `14`: `14` means the +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. @@ -235,8 +242,8 @@ field list — this is the one vocabulary every frontend (CLI, MCP, HTTP, the `simlock/client` package) now shares. 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: +request. A queued request reports its position without speculative work stages; +reclaiming work is reported separately: ```json {"push":"progress","stage":"queued","queuePosition":1} @@ -266,12 +273,11 @@ stderr 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 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: +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"} @@ -423,18 +429,19 @@ 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. The session renews its lease on a timer -and releases it when the process ends, the same policy `simlock lease` +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. `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. +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 @@ -496,12 +503,11 @@ 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 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. +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]` @@ -537,11 +543,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 leases whose -device is still marked `leased`, 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 @@ -612,21 +617,20 @@ 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. `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". +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". The daemon writes one structured JSON line per record to `~/.simlock/daemon.log` (timestamp, level, module, message, and any fields) covering startup (version, diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 7900419e0..498cbfe50 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -104,9 +104,14 @@ 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`). +- **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 diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index ef210e891..8452bff84 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -14,7 +14,7 @@ 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.defaultTtlMs` | TTL applied to a lease whose `lease.request` carried no `ttlMs`, and to a `lease renew` given no explicit TTL. A lease not renewed before its deadline expires and its device is reclaimed. | `15 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` | @@ -49,9 +49,12 @@ 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 when it loads, naming the offending key, rather than -being clamped to something the operator did not write. +`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. See [CLI.md](CLI.md#simlock-config-get-keyset-key-value) for the `simlock config` command itself. diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 58ec94253..d68ee3084 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -7,17 +7,15 @@ 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. -> **Payload removals in the lease rows are a deliberate one-off exception** -> to events rule 6 ("treat payload shape as a public contract: additive -> changes only"). [ADR -> 0004](adr/0004-ttl-first-leases-on-every-transport.md) deletes the concept -> `lease.granted`'s `mode` reported, and makes two of `lease.released`'s -> reasons (`closed`, `orphaned`) unreachable — there is no connection close -> to release on and no startup sweep to orphan anything. Keeping dead fields -> and unreachable enum values to honour additive-only would leave the -> catalogue lying about what a consumer can observe. The exception is taken -> once, while the project is 0.x and the removal is already breaking for the -> contract, and it does not loosen the rule for anything else. +> **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 diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 737b80ed5..422907579 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -72,7 +72,14 @@ 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) makes one break in +that rule, called out where it applies below: a `ttlMs` above +`lease.maxTtlMs` is now `400 BAD_REQUEST` where it used to be accepted, and +the `ttlMs` a lease reports is now always the lease's own width rather than a +value the gateway remembered per request. No field is added or removed; two +change meaning, which is why they are stated rather than left to be +discovered. ### `GET /v1/healthz` @@ -108,15 +115,14 @@ Role: `agent`. Enqueues a device request. `platform` and `device` are required; `os` defaults to the newest installed 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. +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 @@ -268,7 +274,12 @@ 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 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 same facts from `renew`'s `notices`. +`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}` 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 fb6bcabfc..f9d656c09 100644 --- a/docs/adr/0004-ttl-first-leases-on-every-transport.md +++ b/docs/adr/0004-ttl-first-leases-on-every-transport.md @@ -7,9 +7,9 @@ 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`, and §10's `onLeaseLost` firing - for each held lease when a connection dies. Also narrows the held/detached - split in `docs/CLI.md`. + 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 @@ -43,7 +43,14 @@ for a `ttlMs` on the wrong mode are all costs of that one coupling. 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 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 @@ -78,6 +85,11 @@ for a `ttlMs` on the wrong mode are all costs of that one coupling. 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. - 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/known-pitfalls.md b/docs/known-pitfalls.md index 1f0a62635..23088f8c6 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -328,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 From dba8292a79486602a338fd6056b7da9053bb6ebb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 20:24:28 +0000 Subject: [PATCH 5/8] docs: make ADR 0004 record what the docs settle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fourth review round. Every blocking finding was the same shape: the docs stated a decision the ADR did not record, which inverts the rule that the ADR is the specification. So the decisions move into ADR 0004, and the docs cite it. New in the ADR: - Decision 4 carries the renew rule — a lease records the width it was granted with, and a renew naming no ttlMs re-applies that width rather than lease.defaultTtlMs, so a four-hour lease does not shrink to fifteen minutes the first time something renews it — and says the config key is renamed in the key set, not aliased. - Consequences gain four bullets: the HTTP additive-evolution exception, lastRenewedAt replacing the derived lastHeartbeatAt decoration, protocol 4 advertised as {min: 4, max: 4} under ADR 0003 §6's honesty rule, and the two TTL keys validated together at load with a violating config failing the daemon start. - The SIGKILL consequence no longer says "at most lease.defaultTtlMs", which was wrong for any lease that asked for more. HTTP-API's additive-evolution paragraph was itself wrong to claim no field is added or removed: mode leaves the lease record the operator routes serialize, and lastRenewedAt and the stored ttlMs arrive on it. It now lists all three breaks and cites the ADR bullet that grants them. Cross-process `lease renew` needs an admin credential exactly as cross-process `release` does, so it joins the admin command list, the --detach bullet, the renew section, and the worked example that had only ever shown release. Also: list --leases documents lastRenewedAt as status already does; a daemon refusing to boot on a bad TTL pair surfaces through an auto-starting command as DAEMON_STARTUP_FAILED with the reason in daemon logs; the exit-code note records that a running holder's renew is the exception that exits 14; the MCP section says which trigger may launch a daemon and which may not; two bare "ADR §10/§11" references are spelled out as ADR 0003; and README's MCP link points at CLI.md's real heading anchor. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- README.md | 2 +- docs/ARCHITECTURE.md | 6 +-- docs/CLI.md | 46 ++++++++++++++----- docs/HTTP-API.md | 21 ++++++--- ...004-ttl-first-leases-on-every-transport.md | 41 +++++++++++++---- 5 files changed, 85 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 5c8e011b8..04576e167 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ 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) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cfd4e977f..1794667ef 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -60,7 +60,7 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ - **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 @@ -70,8 +70,8 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ 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, once its current client's + 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: diff --git a/docs/CLI.md b/docs/CLI.md index fd19f8466..dd77b2a75 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -51,7 +51,8 @@ maintain a second mapping; 14 is not a daemon error code but an outcome of a 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`. --- @@ -144,7 +145,9 @@ granted. 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`. + `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 @@ -315,6 +318,13 @@ 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 Simlock's simulators live in a device set Xcode does not read, and its @@ -433,7 +443,9 @@ 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. `lease_simulator` accepts the contract's optional `ttlMs` — +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` @@ -513,7 +525,9 @@ running slots. 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]` @@ -632,6 +646,15 @@ auto-starts the daemon and distinguishes two failure shapes: 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. A command that auto-starts +the daemon (`simlock lease`, the MCP server) surfaces that as +`DAEMON_STARTUP_FAILED` and exit 1; 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, protocol version, socket path, effective config), socket claim/stale-endpoint @@ -655,9 +678,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. @@ -672,10 +695,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/HTTP-API.md b/docs/HTTP-API.md index 422907579..cd5abafa3 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -73,13 +73,20 @@ enforced per-resource rather than as a role gate. All routes are under `/v1`, JSON bodies both ways, additive evolution only — new fields, never removed or repurposed ones. [ADR -0004](adr/0004-ttl-first-leases-on-every-transport.md) makes one break in -that rule, called out where it applies below: a `ttlMs` above -`lease.maxTtlMs` is now `400 BAD_REQUEST` where it used to be accepted, and -the `ttlMs` a lease reports is now always the lease's own width rather than a -value the gateway remembered per request. No field is added or removed; two -change meaning, which is why they are stated rather than left to be -discovered. +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` 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 f9d656c09..135b387a5 100644 --- a/docs/adr/0004-ttl-first-leases-on-every-transport.md +++ b/docs/adr/0004-ttl-first-leases-on-every-transport.md @@ -60,10 +60,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 @@ -78,11 +84,11 @@ 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 @@ -90,6 +96,23 @@ for a `ttlMs` on the wrong mode are all costs of that one coupling. 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`, From 7b3d244a1e1d4ffac9ddf3c006ad2e40c7f6d797 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 20:35:50 +0000 Subject: [PATCH 6/8] docs: show the new lease fields in the grant examples Confirmation round. The grant JSON in CLI.md is introduced as every field the contract defines, so it has to carry the two fields ADR 0004 adds: ttlMs and lastRenewedAt, the latter equal to grantedAt at grant time. Both README examples get them too. All three samples parse and agree with each other: ttlDeadline is grantedAt + ttlMs, and mode is gone. Also: drop a sentence about auto-starting the daemon that had been left duplicated in the MCP section; indent and rewrap a changelog continuation line; and say "none of the CLI's three sources" where the count had picked up the programmatic `credential` option, which is not one of them. ADR 0004's Decision 2 gains the renew-failure rule the docs already state, so the record carries it: a transient failure is retried on the next tick, and a renew answered UNKNOWN_LEASE ends the holder the way a lease-lost push does. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- CHANGELOG.md | 6 +++--- README.md | 4 ++++ docs/ARCHITECTURE.md | 4 ++-- docs/CLI.md | 19 +++++++++---------- ...004-ttl-first-leases-on-every-transport.md | 5 ++++- 5 files changed, 22 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b624cace..d5104806a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,9 +102,9 @@ rename, and protocol bump). 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. + 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 diff --git a/README.md b/README.md index 04576e167..567f11931 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,8 @@ simlock lease --platform ios --device "iPhone 16" --detach "requesterId": "agent-1", "ownerId": "agent-1", "grantedAt": 1735689600000, + "ttlMs": 900000, + "lastRenewedAt": 1735689600000, "ttlDeadline": 1735690500000 }, "timing": { @@ -106,6 +108,8 @@ the lease result lands on stdout the moment the new device is ready: "requesterId": "agent-2", "ownerId": "agent-2", "grantedAt": 1735689630000, + "ttlMs": 900000, + "lastRenewedAt": 1735689630000, "ttlDeadline": 1735690530000 }, "timing": { diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1794667ef..7a8176199 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -211,8 +211,8 @@ 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 four sources resolves (a different OS user, or the file -genuinely missing), the CLI falls back to an agent-role session with a +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. diff --git a/docs/CLI.md b/docs/CLI.md index dd77b2a75..7fcb8d8ba 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -179,7 +179,7 @@ default, so a bare `simctl` or `adb` will not find them. See 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,"ttlDeadline":1735690500000},"timing":{"estimatedProvisionMs":0,"estimatedBootMs":0,"estimatedReclaimMs":0,"estimatedReadyMs":0},"role":"agent"} +{"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 @@ -441,15 +441,14 @@ startup to recover. 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. 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), +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 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 135b387a5..16017df5c 100644 --- a/docs/adr/0004-ttl-first-leases-on-every-transport.md +++ b/docs/adr/0004-ttl-first-leases-on-every-transport.md @@ -41,7 +41,10 @@ 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. Its renew timer is what drives its reconnect: when the timer fires against a dead client, the session From 679ebcc25fadac2899181ef61140e119805a4e6f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 23:28:31 +0000 Subject: [PATCH 7/8] docs: correct how a config-rejected daemon start surfaces Two corrections from PR B's code review. A daemon that refuses to boot on its TTL config fails validation before it claims the socket, so an auto-starting command never gets a daemon to talk to: the launch times out and the command fails with exit 1 (INTERNAL), not DAEMON_STARTUP_FAILED, which only reaches a caller whose request was already parked on a daemon that had claimed its socket and then failed convergence. The error line therefore says nothing about the config -- nothing answered -- and the reason is in `simlock daemon logs`. The DAEMON_CONNECTION_LOST example also used an em dash in its message where the code writes ASCII, so the sample now matches what a caller would parse. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- docs/CLI.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 7fcb8d8ba..4de8aca4f 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -216,7 +216,7 @@ 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"}} +{"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 @@ -648,11 +648,13 @@ 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. A command that auto-starts -the daemon (`simlock lease`, the MCP server) surfaces that as -`DAEMON_STARTUP_FAILED` and exit 1; the reason is in `simlock daemon logs`, -which reads the log file directly and so works even though the daemon never -came up. +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, From c8ff5b4d695a91200501e736bf8aa59909abcf99 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 00:03:25 +0000 Subject: [PATCH 8/8] docs: note what lease.maxTtlMs does not reach, and the upgrade case Two additions from PR B's second code review, both about a lease that already exists when something changes around it. Lowering lease.maxTtlMs does not shorten leases already granted. The cap bounds what a request or a renew may ask for; a lease holding a larger stored ttlMs -- granted under a higher cap, or carried over from an older record -- keeps re-applying that width on every body-less renew. Releasing it, or renewing it once with an explicit smaller --ttl, is what changes it. And a lease a pre-ADR-0004 daemon persisted in held mode survives the upgrade with its deadline intact, up to the old one-hour backstop, but nothing can renew it: its holder speaks protocol 3 and the new daemon advertises {min: 4, max: 4}, so its hello fails. It expires on that deadline, or `simlock release ` ends it sooner -- and stopping the old daemon while idle, which the protocol-mismatch error already advises, avoids the situation altogether. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- CHANGELOG.md | 8 ++++++++ docs/CONFIGURATION.md | 7 +++++++ 2 files changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d5104806a..064f1ba4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,14 @@ rename, and protocol bump). 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 diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 8452bff84..4a51d5fad 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -55,6 +55,13 @@ 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.