diff --git a/docs/CLI.md b/docs/CLI.md index 8f150e3f7..76babe5b0 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -189,7 +189,7 @@ granted. force a re-provision of one already running, even while slim devices sit idle in the warm pool. - `--detach` — print the lease result (the same JSON shape as the grant line - below, including `device.featureProfile`) and exit instead of staying + below, including `device.mode`) and exit instead of staying alive. Nothing then renews the lease on your behalf: keep it with `simlock lease renew` before `ttlDeadline`, and end it with `simlock release`. From an invocation other than the one granted the @@ -226,7 +226,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,"ttlMs":900000,"lastRenewedAt":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":"...","mode":"slim"},"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 @@ -275,15 +275,15 @@ 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 +`driverDeviceId`, `spec`, `address?`, `mode` — not the full record `status.get`/`list.get` return to an admin caller. Internal bookkeeping fields (`driverData`, `quarantine*`, `foreign*`, `recovering*`, the derived `transitionAgeMs`) never appear on a grant; a caller that wants those needs the admin-role `list.get`/`status.get`, not `lease.request`'s -output. `device.featureProfile` is `"reduced"` when the granted device had -its feature set reduced (iOS slim mode applied and this request did not pass -`--full`), and `"full"` or absent otherwise — always absent for Android. It -lets an agent explain a feature-loss failure (missing push notification, +output. `device.mode` is the device mode the granted device actually has: +`"slim"` when its feature set was reduced (iOS slim mode applied and this +request did not pass `--full`), and `"full"` otherwise — always `"full"` for +Android. It lets an agent explain a feature-loss failure (missing push notification, Spotlight result, StoreKit sheet, universal link, or system picker) instead of misreading it as a bug. See `src/contract/schemas.ts` (`deviceRecordSchema`, `leaseRecordSchema`, `leaseGrantSchema`) for the full @@ -731,7 +731,7 @@ simlock worker remove ```json {"workers":[{"id":"3f81a2c4","label":"mac-studio-2","state":"connected","drained":false, - "daemonVersion":"0.4.0","protocol":{"min":6,"max":6}, + "daemonVersion":"0.4.0","protocol":{"min":7,"max":7}, "connectedAt":1735689600000,"lastSeenAt":1735689930000, "capacity":{"ios":{"running":2,"limit":4},"android":{"running":0,"limit":2}}, "downloads":{"policy":"on-request"}, @@ -742,7 +742,7 @@ simlock worker remove `config.get` when its uplink connects — routing needs it to know whether a machine may install a missing runtime before sending it a request that needs one. `protocol` is the range that worker negotiated; the wire moves -to `{min: 6, max: 6}` with no shim, so a worker older than it does not +to `{min: 7, max: 7}` with no shim, so a worker older than it does not overlap and shows as `incompatible`. Worker ids are UUIDs — the examples here abbreviate them to their first segment. @@ -860,12 +860,11 @@ caller: small" unless you know to check the unit. Update every caller's timeout field name *and* multiply its value by 1000. - **The top-level `slim: boolean` on a grant is gone; it's now - `device.featureProfile`** (`"full" | "reduced" | undefined`, undefined - meaning "not applicable" — always undefined for Android). A caller - checking `result.slim === true` now silently never sees a feature-loss - signal at all — `result.slim` is simply `undefined` on every response, - which is falsy, not an error. Check `result.device.featureProfile === - "reduced"` instead. + `device.mode`** (`"slim"` or `"full"`, always `"full"` for Android). A + caller checking `result.slim === true` now silently never sees a + feature-loss signal at all — `result.slim` is simply `undefined` on every + response, which is falsy, not an error. Check `result.device.mode === + "slim"` instead. Every other field keeps the contract's own camelCase names it already had under the pre-0.3.0 hand-written schemas (`leaseId`, `deviceId`, @@ -892,7 +891,8 @@ and `list --devices` well before it crosses the threshold that would make Human-oriented overview: daemon health *and mode*, 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 +platform), every managed device with its state and device mode +(`Device dev_7: ready, mode slim`), 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 @@ -902,12 +902,13 @@ Against a **gateway** (`config.mode: "gateway"`) the same command answers for the whole fleet, in the same shape: the daemon line reads `running (gateway)`, capacity is summed across the connected workers, one line per worker precedes the devices, and every device and lease names the worker it -lives on (`Device dev_7 on wrk_a: leased`). `--json` gains a `workers` array of +lives on (`Device dev_7 on wrk_a: leased, mode full`). `--json` gains a `workers` array of [worker views](#simlock-worker-listdrainundrainremove) and a `workerId` on each device and lease; `daemon.mode` says which kind of daemon answered. The daemon block carries `mode` (`"worker"` or `"gateway"`) — the one field -that tells a client which kind of daemon answered. Against a **gateway** the +that tells a client which kind of daemon answered. Do not confuse it with each +device's own `mode`, the device mode (`"slim"` or `"full"`). Against a **gateway** the same view is the fleet's: capacity summed over the connected workers, every lease and device tagged with the `workerId` it lives on, the gateway queue's depth, plus a `workers` array of worker views (the same records @@ -923,7 +924,8 @@ nothing at all: cleanup rules run where the devices and the reaper are, and a gateway has neither. Each lease record's `requesterId` is the 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". +every renew) — the same field `status` renders as "last renewed". Each device +record carries its device mode, `mode`: `"slim"` or `"full"`. Against a gateway, `--devices` and `--leases` list the whole fleet with a `workerId` on every row. The device rows are the narrower shape `status` diff --git a/docs/CLIENT.md b/docs/CLIENT.md index f1563f654..12255686d 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -38,6 +38,13 @@ await client.releaseLease({ leaseId: grant.lease.id }); await client.close(); ``` +`grant.device.mode` is the device mode the granted device actually has: +`"slim"` when its driver reduced its feature set (iOS slim mode), `"full"` +otherwise. A slim device lacks some system features — push notifications, +Spotlight, StoreKit sheets, universal links, system pickers — so check it +before treating such a failure as a bug. Every device in `getStatus()` and in +an admin's `list({ kind: "devices" })` carries the same `mode`. + **Keeping the lease alive is yours to do.** Every lease is TTL-bound: it expires at `grant.lease.ttlDeadline` unless a `renewLease` call lands first, and the daemon does nothing on its own to keep it. `requestLease` takes an optional @@ -377,7 +384,8 @@ gateway implementing the same contract: nothing in this module knows the difference, and neither does code written against it. **The one way to tell is `mode` in `getStatus()`'s daemon block** -(`"worker" | "gateway"`). Everything else you might reach for is a leaky +(`"worker" | "gateway"`) — not each device's own `mode`, which is the device +mode (`"slim" | "full"`). Everything else you might reach for is a leaky inference rather than an answer: a lease from a gateway carries an additive `worker: { id, label }` block, but so might a future single-machine daemon's; a lease id from a gateway names its worker, but ids are opaque and parsing diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 3452b32a3..2b4b5bdc5 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -95,9 +95,9 @@ that machine. ## Endpoints All routes are under `/v1`, JSON bodies both ways, additive evolution only — -new fields, never removed or repurposed ones. That rule was broken once, -as a deliberate 0.x-only exception, and each break is called out where -it applies below: +new fields, never removed or repurposed ones. That rule has been broken +twice, each time as a deliberate 0.x-only exception, and each break is +called out where it applies below: - **`mode` is gone** from the lease record the operator routes serialize (`GET /v1/status`, `GET /v1/leases`), and **`lastRenewedAt` and the stored @@ -107,6 +107,9 @@ it applies below: be accepted. - **The `ttlMs` a lease reports is the lease's own width**, not a value the HTTP frontend remembered per request. +- **The lease's `slim` boolean is gone; it carries `mode` instead** — + `"slim"` or `"full"`, the device mode of the granted device. Every device in + `GET /v1/status` carries the same `mode`. Routes, status codes, and every other field are unchanged. @@ -125,8 +128,8 @@ Unauthenticated liveness for tunnels/load balancers. → `200 {"ok":true}`. ### `GET /v1/status` Role: `agent`. The same view `simlock status --json` reads: a `daemon` block, -managed/running capacity per platform, active leases, managed devices, queue -depth. +managed/running capacity per platform, active leases, managed devices (each +with its device mode, `mode`: `"slim"` or `"full"`), queue depth. The daemon block carries `health` (`starting`/`running`) and **`mode`** (`"worker" | "gateway"`), the one field that tells a client which kind of @@ -296,7 +299,7 @@ without the `workerId` and `worker` fields: "workerId": "3f81a2c4", "worker": { "id": "3f81a2c4", "label": "mac-studio-2" }, "createdAt": "2026-09-01T09:14:07Z", "expiresAt": "2026-09-01T09:29:07Z", "ttlMs": 900000, - "dataPlane": null, "slim": true + "dataPlane": null, "mode": "slim" } } ``` @@ -323,9 +326,10 @@ implemented](#not-implemented) below. It is in the schema now so its arrival is additive rather than a breaking shape change. Running a *command* on the device is not part of it and does not wait for it: that is `exec`, below. -`slim` is `true` when the granted device had its feature set reduced (iOS -slim mode applied and the request did not carry `full: true`), `false` -otherwise — always `false` for Android. It lets a client explain a +`mode` is the device mode the granted device actually has: `"slim"` when its +feature set was reduced (iOS slim mode applied and the request did not carry +`full: true`), `"full"` otherwise — always `"full"` for Android. It lets a +client explain a feature-loss failure (missing push notification, Spotlight result, StoreKit sheet, universal link, or system picker) instead of misreading it as a bug. @@ -585,7 +589,7 @@ workers of its own and does not implement the underlying operations at all. { "workers": [ { "id": "3f81a2c4", "label": "mac-studio-2", "state": "connected", "drained": false, - "daemonVersion": "0.4.0", "protocol": { "min": 6, "max": 6 }, + "daemonVersion": "0.4.0", "protocol": { "min": 7, "max": 7 }, "connectedAt": "2026-09-01T09:00:00Z", "lastSeenAt": "2026-09-01T09:14:30Z", "capacity": { "ios": { "running": 2, "limit": 4 }, "android": { "running": 0, "limit": 2 } }, "downloads": { "policy": "on-request" }, @@ -600,7 +604,7 @@ depends on one; it is never an override, since the worker clamps `allowDownload` through the same policy regardless. `protocol` is the range that worker negotiated. The wire moves to -`{min: 6, max: 6}` with no compatibility shim, so a worker from before it +`{min: 7, max: 7}` with no compatibility shim, so a worker from before it does not overlap and shows as `incompatible` — the ordinary upgrade path, not a fault. diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index ddafad5d4..85d8e0390 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -224,16 +224,17 @@ 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). -Two changes have moved it since. ADR 0004 removed `lease.heartbeat` and +Four changes have moved it since. ADR 0004 removed `lease.heartbeat` and `mode` from the contract with no shim behind them, taking the wire to protocol 4; ADR 0005 adds `device.exec`, its `output` push family, and a `mode` field `status.get` now always carries, again with no compatibility path kept, taking it to 5; ADR 0008 makes the catalog's `modelRuntimes` -required, taking it to 6. So the range both sides -advertise is `{min: 6, max: 6}`, an older client and a current daemon simply +required, taking it to 6; ADR 0007 makes every device report its device mode +as a required `mode`, taking it to 7. So the range both sides advertise is +`{min: 7, max: 7}`, an older client and a current daemon simply do not overlap, and `hello` fails with `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges. The same negotiation runs over a worker's uplink, which is why a -worker older than ADR 0008 shows up in a gateway's views as `incompatible` +worker older than ADR 0007 shows up in a gateway's views as `incompatible` rather than as a mystery (see [Gateway and worker modes](#gateway-and-worker-modes-adr-0005)). `daemon.stop` stays the frozen exception, accepted at any version the daemon has ever spoken, so the upgrade @@ -731,8 +732,9 @@ emits its own facts — `worker.connected`, `worker.disconnected`, widens only where a compatibility path is actually kept — so **every worker older than ADR 0005 is `incompatible` by range**, by construction rather than by accident. ADR 0008 moves it again, to `{min: 6, max: 6}`, because - the catalog's `modelRuntimes` is required; a worker on 5 is `incompatible` - the same way. That is the ordinary upgrade path, not a failure mode: + the catalog's `modelRuntimes` is required, and ADR 0007 to + `{min: 7, max: 7}`, because a device's `mode` is required; a worker on an + older version is `incompatible` the same way. That is the ordinary upgrade path, not a failure mode: upgrade the worker. An incompatible worker is marked `incompatible` in its view with both ranges shown and is never dispatched to, and it is not hidden either — that is the machine an operator has to go and upgrade, and diff --git a/docs/internal/KNOWN-PITFALLS.md b/docs/internal/KNOWN-PITFALLS.md index 67b23eacd..f90367ede 100644 --- a/docs/internal/KNOWN-PITFALLS.md +++ b/docs/internal/KNOWN-PITFALLS.md @@ -722,7 +722,7 @@ the commands and drop them on the post-slim reboot, so slimming would cost a second boot for no effect. `planSlimBoot` (`src/drivers/ios/index.ts`) gates on this and skips the apply pass entirely rather than paying that cost — silently, from the requester's point of view: the lease still grants, just -with `slim: false`. `simlock doctor`'s `driver-advisory` / +with `mode: "full"`. `simlock doctor`'s `driver-advisory` / `slim-runtime-unsupported` finding is what makes an unsupported runtime visible to an operator instead of it only ever showing up as an unexpectedly non-slim lease. @@ -733,12 +733,10 @@ universal links, Siri/Apple Intelligence, iCloud sync, and some system pickers to not work on a slim device — the categories that back them are exactly the ones slimming disables. Mitigations: `simlock lease --full` (MCP `full: true`, HTTP `full: true`) opts a single lease out of slimming, and -every lease response carries a feature-profile signal so a caller can tell a +every lease response carries the device mode so a caller can tell a feature-loss failure apart from an actual bug instead of guessing — -`device.featureProfile === "reduced"` on the CLI/MCP/client contract shape -(`slim` as a top-level boolean grant field is gone as of 0.3.0, ADR 0003 -§11), or HTTP's own `lease.slim` boolean, which is still derived from the -same underlying signal. +`device.mode === "slim"` on the CLI/MCP/client contract shape, and +`lease.mode === "slim"` on HTTP (ADR 0007 §9: one word on every surface). **Mixing slim and full devices under one spec can make `--full` wait or re-provision.** `full` is part of spec identity (`DeviceSpec.full`, compared by `sameSpec`, @@ -779,7 +777,7 @@ gates re-applying the disable pass changes, so an existing device re-applies the now-narrower set on its next boot — but the `launchctl disable` overrides already written for the *removed* category are never undone. They live in the simulator's own launchd database and only disappear on `simctl erase`. The -device keeps reporting `slim: true` and keeps missing that category's +device keeps reporting `mode: "slim"` and keeps missing that category's functionality, with no error surfaced anywhere. The real consequence is stronger than the flag alone suggests: the device ends up slimmer than *any* configuration ever asked for — it carries both the newly-narrower disable set @@ -801,6 +799,14 @@ on the same timers as any other idle device, since neither rule cares what a device's spec matches. Until those timers fire, though, it occupies a pool slot doing nothing. +**A device slimmed before the upgrade to `mode` reports `full`.** A device +record written before devices carried a `mode` loads as `full`, and nothing +is derived from its old feature-profile field (ADR 0007 §11). A worker that +ran with `ios.slim.enabled` on therefore holds slimmed devices that report +`mode: "full"` on grants, `status`, and `list` until their next boot rewrites +the mode. Empty such a worker with `simlock nuke --delete-devices` before +upgrading it. + ## A dispatched request whose uplink drops may have granted a lease anyway The gateway dispatches a queued request to a worker with `noWait: true` and diff --git a/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index ce6e88b3a..86371a36d 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -14,12 +14,11 @@ interface SimctlDevice { readonly state: string; } +/** The fields of a `simlock lease --detach` grant this lane reads, flattened. */ interface LeaseGrant { readonly lease: string; readonly udid: string; - readonly slim: boolean; - readonly device: string; - readonly os: string; + readonly mode: "slim" | "full"; } interface DoctorReport { @@ -124,7 +123,11 @@ async function leaseDetached( { timeout: 600_000 }, ); expect(lease.code, `lease failed: ${lease.stderr}`).toBe(0); - return lease.json as LeaseGrant; + const grant = lease.json as { + device: { driverDeviceId: string; mode: "slim" | "full" }; + lease: { id: string }; + }; + return { lease: grant.lease.id, mode: grant.device.mode, udid: grant.device.driverDeviceId }; } const ALL_LABELS = new Set(labelsFor(SLIM_CATEGORIES)); @@ -145,9 +148,7 @@ describe.skipIf(process.platform !== "darwin")( const { model, os } = await catalogModelAndOs(env); const grant = await leaseDetached(env, model, os, "slim-off-default"); - expect(grant.slim, "grant.slim must be false when ios.slim is not configured").toBe( - false, - ); + expect(grant.mode, "a lease must be full when ios.slim is not configured").toBe("full"); const disabled = await printDisabled(grant.udid); const overlap = [...ALL_LABELS].filter((label) => disabled.has(label)); @@ -188,7 +189,7 @@ describe.skipIf(process.platform !== "darwin")( const fullStart = Date.now(); const fullGrant = await leaseDetached(env, model, os, "slim-full-opt-out", ["--full"]); const fullDurationMs = Date.now() - fullStart; - expect(fullGrant.slim, "a --full lease must never be slim").toBe(false); + expect(fullGrant.mode, "a --full lease's grant must carry mode: full").toBe("full"); const fullDisabled = await printDisabled(fullGrant.udid); const fullOverlap = [...ALL_LABELS].filter((label) => fullDisabled.has(label)); expect( @@ -216,7 +217,7 @@ describe.skipIf(process.platform !== "darwin")( const slimGrant = await leaseDetached(env, model, os, "slim-cold"); const slimDurationMs = Date.now() - slimStart; - expect(slimGrant.slim, "a plain lease under ios.slim.enabled must be slim").toBe(true); + expect(slimGrant.mode, "a slim lease's grant must carry mode: slim").toBe("slim"); expect(slimGrant.udid).not.toBe(fullGrant.udid); const slimDisabled = await printDisabled(slimGrant.udid); @@ -290,7 +291,7 @@ describe.skipIf(process.platform !== "darwin")( const relet = await leaseDetached(env, model, os, "slim-cold"); expect(relet.udid, "expected the warm-pooled device to be reused").toBe(slimGrant.udid); - expect(relet.slim, "re-leased device must still report slim: true").toBe(true); + expect(relet.mode, "re-leased device must still report mode: slim").toBe("slim"); const eventsAfterRelease = await env.expectEvents(["device.slimmed", "device.slimmed"], { since: "1h", @@ -336,7 +337,7 @@ describe.skipIf(process.platform !== "darwin")( // --- scenario 5 --- const grant = await leaseDetached(env, model, os, "slim-subset"); - expect(grant.slim).toBe(true); + expect(grant.mode).toBe("slim"); const disabled = await printDisabled(grant.udid); const missingSiri = [...siriLabels].filter((label) => !disabled.has(label)); @@ -363,7 +364,7 @@ describe.skipIf(process.platform !== "darwin")( { ios: { slim: { enabled: true, categories: ["siri", "no-such-category"] } } }, async () => { const grant2 = await leaseDetached(env, model, os, "slim-unknown-category"); - expect(grant2.slim, "lease must still succeed and be slim").toBe(true); + expect(grant2.mode, "lease must still succeed and be slim").toBe("slim"); const disabled2 = await printDisabled(grant2.udid); const missingSiri2 = [...siriLabels].filter((label) => !disabled2.has(label)); expect(missingSiri2, "expected every siri label disabled").toEqual([]); @@ -391,7 +392,7 @@ describe.skipIf(process.platform !== "darwin")( try { const { model, os } = await catalogModelAndOs(env); const grant = await leaseDetached(env, model, os, "slim-recovery", []); - expect(grant.slim).toBe(true); + expect(grant.mode).toBe("slim"); const disabledBefore = await printDisabled(grant.udid); expect([...ALL_LABELS].filter((label) => !disabledBefore.has(label)).length).toBe(0); @@ -435,7 +436,7 @@ describe.skipIf(process.platform !== "darwin")( }, ); - it("scenario 9: MCP carries the slim flag both ways", { timeout: 600_000 }, async () => { + it("scenario 9: MCP carries the device mode both ways", { timeout: 600_000 }, async () => { const env = await withDaemon({ driver: "real", configOverrides: { ios: { slim: { enabled: true } } }, @@ -458,13 +459,10 @@ describe.skipIf(process.platform !== "darwin")( leaseCallOptions, ); const fullLeased = fullResult.structuredContent as { - device: { featureProfile?: "full" | "reduced" }; + device: { mode: "slim" | "full" }; lease: { id: string }; }; - expect( - fullLeased.device.featureProfile, - "MCP full:true lease must report a full feature profile", - ).toBe("full"); + expect(fullLeased.device.mode, "MCP full:true lease must report mode: full").toBe("full"); await mcp.client.callTool({ name: "release_simulator", @@ -480,13 +478,13 @@ describe.skipIf(process.platform !== "darwin")( leaseCallOptions, ); const slimLeased = slimResult.structuredContent as { - device: { featureProfile?: "full" | "reduced" }; + device: { mode: "slim" | "full" }; lease: { id: string }; }; expect( - slimLeased.device.featureProfile, - "MCP plain lease under ios.slim.enabled must report a reduced feature profile", - ).toBe("reduced"); + slimLeased.device.mode, + "MCP plain lease under ios.slim.enabled must report mode: slim", + ).toBe("slim"); await mcp.client.callTool({ name: "release_simulator", @@ -503,7 +501,7 @@ describe.skipIf(process.platform !== "darwin")( // HTTP is skipped here: it needs a real reserved port plus its own auth-token setup // (see http-api.test.ts) on top of another real cold iOS lease, which -- given MCP - // already exercises the same `grant.slim` plumbing through a second transport -- was + // already exercises the same `grant.device.mode` plumbing through a second transport -- was // judged not worth a third real boot cycle in this already-expensive slow lane. }); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 7d15b4e8d..99f4235e1 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -71,6 +71,7 @@ const detachedGrant: LeaseGrant = { id: "device-1", driverDeviceId: "ABCD", spec: { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + mode: "full", }, environment: {}, lease: { @@ -1903,6 +1904,7 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = { id: "dev_1", spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" as const }, + mode: "full" as const, state: "leased" as const, workerId: "wrk_1", }, @@ -1942,7 +1944,7 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = expect(output.stdout).toContain("Daemon: running (gateway)"); expect(output.stdout).toContain("wrk_1: connected, drained"); - expect(output.stdout).toContain("Device dev_1 on wrk_1: leased"); + expect(output.stdout).toContain("Device dev_1 on wrk_1: leased, mode full"); expect(output.stdout).toContain("Lease lease_1: agent-1 on wrk_1"); }); @@ -1955,6 +1957,26 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = expect(output.stdout).toContain("Daemon: running (worker)"); expect(output.stdout).not.toContain(" on wrk_"); }); + + it("prints each device's mode", async () => { + const output = outputCapture(); + const spec = { model: "iPhone 17", osVersion: "26.0", platform: "ios" as const }; + const status: StatusGetOutput = { + ...EMPTY_STATUS, + devices: [ + { id: "dev_slim", mode: "slim", spec, state: "ready" }, + { id: "dev_full", mode: "full", spec, state: "leased" }, + ], + }; + const environment = output.environmentWith({ + connectAdmin: async () => fakeClient({ getStatus: () => Promise.resolve(status) }), + }); + + await runCli(["status"], environment); + + expect(output.stdout).toContain("Device dev_slim: ready, mode slim"); + expect(output.stdout).toContain("Device dev_full: leased, mode full"); + }); }); describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", () => { @@ -2046,6 +2068,7 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( id: "dev_1", driverDeviceId: "dev_1", spec: { platform: "ios", model: "x", osVersion: "26.5" }, + mode: "full", }, environment: {}, lease: { @@ -2100,6 +2123,7 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( id: "dev_1", driverDeviceId: "dev_1", spec: { platform: "ios", model: "x", osVersion: "26.5" }, + mode: "full", }, environment: {}, lease: { @@ -2149,6 +2173,7 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( id: "dev_1", driverDeviceId: "dev_1", spec: { platform: "ios", model: "x", osVersion: "26.5" }, + mode: "full", }, environment: {}, lease: { @@ -2647,6 +2672,7 @@ describe("CLI: holder renew and release (ADR 0004 §2)", () => { id: "dev_1", driverDeviceId: "dev_1", spec: { platform: "ios", model: "x", osVersion: "26.5" }, + mode: "full", }, // A driver-supplied key that is not a shell identifier fails the command rather than // being silently dropped -- and that throw must not cost the device. @@ -3436,6 +3462,7 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl id: "dev_1", driverDeviceId: "dev_1", spec: { platform: "ios", model: "iPhone 17 Pro", osVersion: "26.5" }, + mode: "full", }, lease: { id: "lse_1", diff --git a/src/cli/index.ts b/src/cli/index.ts index 8b8932454..c16495418 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -1995,7 +1995,7 @@ function formatStatus(status: StatusGetOutput): string { ].filter((marker) => marker !== undefined); const suffix = markers.length === 0 ? "" : ` (${markers.join(", ")})`; const where = device.workerId === undefined ? "" : ` on ${device.workerId}`; - return `Device ${device.id}${where}: ${device.state}${suffix}`; + return `Device ${device.id}${where}: ${device.state}, mode ${device.mode}${suffix}`; }); // ADR 0004: `lastRenewedAt` is a stored field written at grant and on every renew, so unlike // the derived `lastHeartbeatAt` it replaces, every lease has one to render. diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 46b6d7b3b..05c1d3400 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -215,6 +215,7 @@ describe("operation input/output round trips", () => { id: "dev_1", driverDeviceId: "sim-1", spec: { platform: "ios", model: "iPhone 17 Pro", osVersion: "18.0" }, + mode: "full", state: "leased", driverData: { udid: "abc" }, createdAt: 1, @@ -313,6 +314,7 @@ describe("operation input/output round trips", () => { { id: "dev_1", spec: { platform: "ios", model: "iPhone 17", osVersion: "26.0" }, + mode: "full", state: "leased", workerId: "wrk_1", }, diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 7343a47d5..4f0e2060b 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -14,14 +14,15 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** - * The range this contract's daemon speaks. Both ends are 6, and every move that got it there + * The range this contract's daemon speaks. Both ends are 7, and every move that got it there * was breaking with no shim kept behind them, which is exactly when ADR 0003 §6's honesty * rule says a range must *not* widen: ADR 0004 removed `lease.heartbeat` and `mode` from the * wire (taking it to 4), and ADR 0005 adds `device.exec` and its `output` push family, a * `mode` field `status.get` now always carries, and the gateway surface -- `worker.*`, * `workerId`, the `worker` token role -- on top (taking it to 5). ADR 0008 makes the catalog * carry a required `modelRuntimes` per platform (taking it to 6), which a gateway reading a - * worker's catalog depends on. It only ever widens once a + * worker's catalog depends on. ADR 0007 makes a device's mode a required `mode` on the grant, + * `status.get`, and `list.get` (taking it to 7). It only ever widens once a * second version is actually kept alive side by side with the first, which nothing here does. * * A client from before any of those changes simply does not overlap this daemon, and `hello` @@ -35,7 +36,7 @@ const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().in * gateway marks it `incompatible` -- with both ranges on the view -- and never dispatches to it. * A worker on 5 is marked `incompatible` the same way (ADR 0008 §10). */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 6, max: 6 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 7, max: 7 }; /** * The one protocol version that ever existed before ranges did. Used only to build the diff --git a/src/contract/schemas.test.ts b/src/contract/schemas.test.ts index 254474320..920a08baa 100644 --- a/src/contract/schemas.test.ts +++ b/src/contract/schemas.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from "vitest"; -import { grantedDeviceSchema, leaseGrantSchema, statusDeviceSchema } from "./schemas.js"; +import { + deviceRecordSchema, + grantedDeviceSchema, + leaseGrantSchema, + statusDeviceSchema, +} from "./schemas.js"; /** * Regression coverage for the defect fixed alongside ADR 0003 §1: a lease grant's device must @@ -51,7 +56,7 @@ describe("leaseGrantSchema's device projection", () => { quarantineAttempts: 3, quarantineNextRetryAt: 60, address: "127.0.0.1:1234", - featureProfile: "reduced", + mode: "slim", leaseIdentity: "fresh", transitionAgeMs: 70, }; @@ -87,7 +92,7 @@ describe("leaseGrantSchema's device projection", () => { driverDeviceId: "SIM-1", spec: { platform: "ios", model: "iPhone 17 Pro", osVersion: "26.5" }, address: "127.0.0.1:1234", - featureProfile: "reduced", + mode: "slim", }); }); @@ -95,18 +100,30 @@ describe("leaseGrantSchema's device projection", () => { expect(() => grantedDeviceSchema.parse({ id: "device-1" })).toThrow(); }); - it("keeps id, driverDeviceId, spec, and the optional address/featureProfile", () => { + it("keeps id, driverDeviceId, spec, and mode, with address optional", () => { const parsed = grantedDeviceSchema.parse({ id: "device-1", driverDeviceId: "SIM-1", + mode: "full", spec: { platform: "android", model: "Pixel 8", osVersion: "34" }, }); expect(parsed).toEqual({ id: "device-1", driverDeviceId: "SIM-1", + mode: "full", spec: { platform: "android", model: "Pixel 8", osVersion: "34" }, }); }); + + it("rejects a granted device without a mode, or with a mode other than slim or full", () => { + const device = { + id: "device-1", + driverDeviceId: "SIM-1", + spec: { platform: "ios", model: "iPhone 17 Pro", osVersion: "26.5" }, + }; + expect(() => grantedDeviceSchema.parse(device)).toThrow(); + expect(() => grantedDeviceSchema.parse({ ...device, mode: "reduced" })).toThrow(); + }); }); /** @@ -138,7 +155,7 @@ describe("statusDeviceSchema's device projection", () => { quarantineAttempts: 3, quarantineNextRetryAt: 60, address: "127.0.0.1:1234", - featureProfile: "reduced", + mode: "slim", leaseIdentity: "fresh", transitionAgeMs: 70, }; @@ -156,7 +173,6 @@ describe("statusDeviceSchema's device projection", () => { "recoveryAttempts", "quarantinedAt", "address", - "featureProfile", ] as const) { expect(device).not.toHaveProperty(field); } @@ -165,6 +181,7 @@ describe("statusDeviceSchema's device projection", () => { id: "device-1", spec: { platform: "ios", model: "iPhone 17 Pro", osVersion: "26.5" }, state: "quarantined", + mode: "slim", foreignStateDetectedAt: 20, foreignProvenanceDetectedAt: 30, quarantineAttempts: 3, @@ -176,4 +193,28 @@ describe("statusDeviceSchema's device projection", () => { it("rejects a device object that is missing the fields status.get must keep", () => { expect(() => statusDeviceSchema.parse({ id: "device-1" })).toThrow(); }); + + it("rejects a status device without a mode, or with a mode other than slim or full", () => { + const device = { + id: "device-1", + spec: { platform: "ios", model: "iPhone 17 Pro", osVersion: "26.5" }, + state: "ready", + }; + expect(() => statusDeviceSchema.parse(device)).toThrow(); + expect(() => statusDeviceSchema.parse({ ...device, mode: "reduced" })).toThrow(); + }); + + it("rejects a list.get device record without a mode, or with a mode other than slim or full", () => { + const record = { + id: "device-1", + driverDeviceId: "SIM-1", + spec: { platform: "ios", model: "iPhone 17 Pro", osVersion: "26.5" }, + state: "ready", + driverData: {}, + createdAt: 0, + }; + expect(deviceRecordSchema.parse({ ...record, mode: "full" })).toMatchObject({ mode: "full" }); + expect(() => deviceRecordSchema.parse(record)).toThrow(); + expect(() => deviceRecordSchema.parse({ ...record, mode: "reduced" })).toThrow(); + }); }); diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index d309b7b84..3c78cf3f8 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -32,7 +32,8 @@ const deviceStateSchema = z.enum([ "deleted", ]); -const featureProfileSchema = z.enum(["full", "reduced"]); +/** The mode a device actually has (ADR 0007 §9) -- the same two words on every surface. */ +const deviceModeSchema = z.enum(["slim", "full"]); const leaseIdentitySchema = z.enum(["reusable", "fresh"]); @@ -61,7 +62,7 @@ export const deviceRecordSchema = z.object({ quarantineAttempts: z.number().optional(), quarantineNextRetryAt: z.number().optional(), address: z.string().optional(), - featureProfile: featureProfileSchema.optional(), + mode: deviceModeSchema, leaseIdentity: leaseIdentitySchema.optional(), /** Decoration added by `status.get`/`list.get`; absent for a device not mid-transition. */ transitionAgeMs: z.number().optional(), @@ -96,13 +97,16 @@ export const deviceRecordSchema = z.object({ * reads), `recoveringSince`/`recoveryAttempts` (crash-recovery bookkeeping -- `safety.md` rule * 2 scopes that privilege narrowly, and broadcasting its progress to every agent is not part of * that scope), `quarantinedAt` (superseded by `quarantineAttempts`/`quarantineNextRetryAt` for - * what a caller needs), and `address`/`featureProfile` (only meaningful to whoever is driving - * the device, i.e. the lease holder, who gets them on the grant). + * what a caller needs), and `address` (only meaningful to whoever is driving the device, i.e. + * the lease holder, who gets it on the grant). `mode` stays: which kind of device it is matters + * to anyone reading the fleet. */ export const statusDeviceSchema = z.object({ id: z.string(), spec: deviceSpecSchema, state: deviceStateSchema, + /** The device mode (see `DeviceRecord.mode`) -- not the daemon's own `worker`/`gateway` mode. */ + mode: deviceModeSchema, foreignStateDetectedAt: z.number().optional(), foreignProvenanceDetectedAt: z.number().optional(), quarantineAttempts: z.number().optional(), @@ -126,7 +130,7 @@ export const statusDeviceSchema = z.object({ * * - `id`: the lease-facing device identity (what `lease.list`/`lease.renew` correlate against). * - `driverDeviceId`: the driver address a caller actually drives (simctl UDID / adb serial). - * - `spec`, `address`, `featureProfile`: same meanings as on `DeviceRecord` (src/core/domain.ts). + * - `spec`, `address`, `mode`: same meanings as on `DeviceRecord` (src/core/domain.ts). * * Everything else on `DeviceRecord` -- `driverData` (opaque driver-private blob), `state`, * `createdAt`, every `quarantine*`/`foreign*`/`recovering*` field, and the `status`/`list` @@ -149,13 +153,8 @@ export const grantedDeviceSchema = z.object({ * ever guesses at a value it wasn't told. */ address: z.string().optional(), - /** - * Mirrors `DriverDevice.featureProfile` (see `driver.ts`), current as of this device's last - * `ready` transition. Undefined for a device still `provisioning` (never made ready yet) - * and for any driver that does not reduce anything -- today's behaviour, and every non-iOS - * driver. - */ - featureProfile: featureProfileSchema.optional(), + /** The mode the device actually has (see `DeviceRecord.mode`). */ + mode: deviceModeSchema, }); /** @@ -320,7 +319,7 @@ const driverDeviceSchema = z.object({ deviceId: z.string(), driverData: z.unknown(), address: z.string(), - featureProfile: featureProfileSchema.optional(), + mode: deviceModeSchema.optional(), }); /** Mirrors the `DoctorFinding` discriminated union (src/core/doctor.ts) field for field. */ diff --git a/src/core/acquisition-planner.test.ts b/src/core/acquisition-planner.test.ts index c009c5a50..d0db36faf 100644 --- a/src/core/acquisition-planner.test.ts +++ b/src/core/acquisition-planner.test.ts @@ -76,6 +76,7 @@ function device( driverDeviceId: `driver-${id}`, id, spec: deviceSpec, + mode: "full", state, }; } diff --git a/src/core/cleanup/idle-destroy.test.ts b/src/core/cleanup/idle-destroy.test.ts index df93fd27e..75abec603 100644 --- a/src/core/cleanup/idle-destroy.test.ts +++ b/src/core/cleanup/idle-destroy.test.ts @@ -75,6 +75,7 @@ function view( id: "dev_1", lastLeaseEndedAt: 0, spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, + mode: "full", state: "shutdown", }, ], diff --git a/src/core/cleanup/idle-shutdown.test.ts b/src/core/cleanup/idle-shutdown.test.ts index f5ff7f5e7..06e2e5674 100644 --- a/src/core/cleanup/idle-shutdown.test.ts +++ b/src/core/cleanup/idle-shutdown.test.ts @@ -70,6 +70,7 @@ function view(now: number): RegistryView { id: "dev_1", lastLeaseEndedAt: 0, spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, + mode: "full", state: "ready", }, ], diff --git a/src/core/doctor.ts b/src/core/doctor.ts index effbec137..cb423fe8b 100644 --- a/src/core/doctor.ts +++ b/src/core/doctor.ts @@ -647,7 +647,7 @@ function registryDriftFindings( // `expectedRunState` ever commits. Without this guard a concurrent `doctor --fix` reads that // as foreign drift, "fixes" the record to `ready`, and the boot's own transition commit // afterwards finds the record changed underneath it and silently drops its - // `address`/`driverData`/`featureProfile`, dropping the waiter. The claim is held for the + // `address`/`driverData`/`mode`, dropping the waiter. The claim is held for the // whole boot, so it exactly brackets the window this needs to cover -- unlike // `stalledTransitionFinding`, this applies regardless of `device.state`, since the record can // be `shutdown`, `ready`, or `leased` while a claimed operation is in flight against it. diff --git a/src/core/domain.test.ts b/src/core/domain.test.ts index 9537d891e..d86b7c2da 100644 --- a/src/core/domain.test.ts +++ b/src/core/domain.test.ts @@ -9,6 +9,7 @@ const baseDevice: Omit = { driverDeviceId: "driver_test", id: "dev_test", spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, + mode: "full", }; describe("transition", () => { diff --git a/src/core/domain.ts b/src/core/domain.ts index 28b8a236e..4969840d4 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -2,6 +2,9 @@ import type { DeviceRequest } from "./driver.js"; export type Platform = "ios" | "android"; +/** The mode a device actually has: slimmed by its driver, or not. */ +export type DeviceMode = "slim" | "full"; + export interface DeviceSpec { readonly platform: Platform; readonly model: string; @@ -74,12 +77,11 @@ export interface DeviceRecord { */ readonly address?: string; /** - * Mirrors `DriverDevice.featureProfile` (see `driver.ts`), current as of this device's last - * `ready` transition. Undefined for a device still `provisioning` (never made ready yet) - * and for any driver that does not reduce anything -- today's behaviour, and every non-iOS - * driver. + * The mode the device actually has (see `DriverDevice.mode`), current as of its last `ready` + * transition. `registerDevice` writes `"full"` for a device that has not booted yet, and a + * record written before this field existed loads as `"full"`. */ - readonly featureProfile?: "full" | "reduced"; + readonly mode: DeviceMode; /** * The lease-identity policy this device was created under (see `LeaseIdentity`). The registry * stamps it on every device it registers and loads a record written before this field existed @@ -230,7 +232,7 @@ export class IllegalTransition extends Error { export interface DeviceTransitionUpdate { readonly address?: string; readonly driverData?: unknown; - readonly featureProfile?: "full" | "reduced"; + readonly mode?: DeviceMode; } export function transition( diff --git a/src/core/driver.ts b/src/core/driver.ts index 3c7340a9f..7e8121557 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -1,7 +1,7 @@ import type { EventMap } from "../bus/index.js"; import type { Filesystem } from "../ports/index.js"; import type { RootRejectionReason } from "./device-root.js"; -import type { DeviceSpec, DeviceTransitionUpdate, Platform } from "./domain.js"; +import type { DeviceMode, DeviceSpec, DeviceTransitionUpdate, Platform } from "./domain.js"; export interface DeviceRequest { readonly platform: Platform; @@ -27,39 +27,28 @@ export interface DriverDevice { */ readonly address: string; /** - * What the driver actually produced for this device, as of its last `makeReady` -- - * platform-neutral so the core can report feature loss without reading a driver's opaque - * `driverData`. `"reduced"` means the driver cut the device's feature set (the iOS driver's - * slim mode); `"full"` means it did not. `undefined` means the driver does not reduce - * anything at all -- today's behaviour, and every non-iOS driver. + * The mode the driver actually produced for this device, as of its last `makeReady` -- + * platform-neutral so the core can report it without reading a driver's opaque + * `driverData`. `"slim"` means the driver cut the device's feature set (the iOS driver's + * slim pass); `"full"` means it did not. `undefined` means the driver does not slim at all + * -- every non-iOS driver -- and is stored as `"full"` (see `readyTransitionUpdate`). */ - readonly featureProfile?: "full" | "reduced"; + readonly mode?: DeviceMode; } /** - * Builds a `DeviceTransitionUpdate` from a driver's freshly re-read device, always including - * `featureProfile` -- even when the driver returned `undefined`. `transition`'s - * `{...record, ...update}` spread only clears a stale value when the update object *has* the - * key; omitting it (as a conditional spread like `...(fp === undefined ? {} : { featureProfile: - * fp })` does) would let a previous `"reduced"` survive a re-boot where slimming wasn't applied - * this time, reporting `slim: true` on a device that is actually full-fat. - * `DeviceTransitionUpdate["featureProfile"]` itself can't say "present but undefined" under - * `exactOptionalPropertyTypes`, so the object is built with the wider type and cast at the - * boundary -- the explicit `undefined` here is a deliberate runtime value, not a type-checking - * gap. Shared by every readiness path that commits a driver's post-`makeReady` result - * (`ManagedDeviceLifecycle`, `WarmPoolCoordinator`) so they can't drift on this. + * Builds a `DeviceTransitionUpdate` from a driver's freshly re-read device. It always writes + * `mode`, defaulting a driver's `undefined` to `"full"` here and nowhere else, so a stale + * `"slim"` can never outlive a re-boot that did not slim. Shared by every readiness path that + * commits a driver's post-`makeReady` result (`ManagedDeviceLifecycle`, `WarmPoolCoordinator`) + * so they can't drift on this. */ export function readyTransitionUpdate(readyDevice: DriverDevice): DeviceTransitionUpdate { - const update: { - readonly address: string; - readonly driverData: unknown; - readonly featureProfile: "full" | "reduced" | undefined; - } = { + return { address: readyDevice.address, driverData: readyDevice.driverData, - featureProfile: readyDevice.featureProfile, + mode: readyDevice.mode ?? "full", }; - return update as DeviceTransitionUpdate; } /** diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index f7ee77700..f5f5e6678 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -1,5 +1,5 @@ import type { Clock } from "../ports/index.js"; -import type { DeviceSpec, Platform } from "./domain.js"; +import type { DeviceMode, DeviceSpec, Platform } from "./domain.js"; import { type DeviceRequest, type Driver, @@ -50,12 +50,11 @@ export interface FakeDriverOptions { */ readonly fullCleanReclaimEstimateMs?: number; /** - * The `DriverDevice.featureProfile` `makeReady` reports for every boot -- undefined by - * default (this fake, like every real driver except iOS, does not reduce anything), settable - * by a test that needs to exercise the core's `featureProfile` persistence without a real - * iOS driver. + * The `DriverDevice.mode` `makeReady` reports for every boot -- undefined by default (this + * fake, like every real driver except iOS, does not slim anything), settable by a test that + * needs to exercise the core's `mode` persistence without a real iOS driver. */ - readonly featureProfile?: "full" | "reduced"; + readonly mode?: DeviceMode | undefined; readonly knownModels?: readonly string[]; /** * What `listCatalog` reports a model pairs with. A model left out pairs with every available @@ -113,7 +112,7 @@ export class FakeDriver implements Driver { readonly #calls: FakeDriverCall[] = []; readonly #clock: Clock; readonly #estimateMs: FakeDriverOptions["estimateMs"]; - readonly #featureProfile: "full" | "reduced" | undefined; + readonly #mode: DeviceMode | undefined; readonly #fullCleanReclaimEstimateMs: number | undefined; readonly #failures = new Map(); #hangMakeReady = false; @@ -139,7 +138,7 @@ export class FakeDriver implements Driver { this.#availableOsVersions = new Set(options.availableOsVersions ?? ["latest"]); this.#clock = options.clock; this.#estimateMs = options.estimateMs; - this.#featureProfile = options.featureProfile; + this.#mode = options.mode; this.#fullCleanReclaimEstimateMs = options.fullCleanReclaimEstimateMs; this.#knownModels = options.knownModels === undefined ? undefined : new Set(options.knownModels); @@ -244,7 +243,7 @@ export class FakeDriver implements Driver { address: addressFor(device.deviceId, bootCount), deviceId: device.deviceId, driverData: device.driverData, - ...(this.#featureProfile === undefined ? {} : { featureProfile: this.#featureProfile }), + ...(this.#mode === undefined ? {} : { mode: this.#mode }), }; } diff --git a/src/core/index.ts b/src/core/index.ts index 30780c907..3b34ca3f9 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -9,6 +9,7 @@ export { loadConfig, } from "./config.js"; export { + type DeviceMode, type DeviceRecord, type DeviceSpec, type LeaseRecord, diff --git a/src/core/lease-request-book.test.ts b/src/core/lease-request-book.test.ts index ee354497e..0e3804506 100644 --- a/src/core/lease-request-book.test.ts +++ b/src/core/lease-request-book.test.ts @@ -158,6 +158,51 @@ describe("Registry lease requests", () => { expect(registry.leaseRequests().map((record) => record.id)).toEqual(["req_valid"]); }); + it("loads a granted record stored before mode existed with its grant's device as full, without featureProfile", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + const grant = (id: string, device: Record) => ({ + createdAt: 1_000, + grant: { + device: { + driverDeviceId: "udid", + id: "dev_1", + spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, + ...device, + }, + environment: {}, + lease: { id: "lse_1" }, + timing: {}, + }, + id, + ownerId: "agent", + request, + requesterId: "agent", + settledAt: 1_000, + state: "granted", + }); + await filesystem.writeFileAtomic( + statePath, + JSON.stringify({ + devices: [], + leaseRequests: [ + grant("req_legacy", { featureProfile: "reduced" }), + grant("req_slim", { mode: "slim" }), + grant("req_unknown", { mode: "reduced" }), + ], + leases: [], + }), + ); + + const { registry } = await loadRegistry({ filesystem }); + + const devices = registry.leaseRequests().map((record) => [record.id, record.grant?.device]); + expect(devices.map(([id]) => id)).toEqual(["req_legacy", "req_slim"]); + expect(devices[0]?.[1]).toMatchObject({ mode: "full" }); + expect(devices[0]?.[1]).not.toHaveProperty("featureProfile"); + expect(devices[1]?.[1]).toMatchObject({ mode: "slim" }); + }); + it("settles every open record as failed, leaving settled ones alone", async () => { const { registry } = await loadRegistry(); const open = await registry.createLeaseRequest(newRequest("open")); diff --git a/src/core/managed-device-lifecycle.test.ts b/src/core/managed-device-lifecycle.test.ts index 35e1eefad..4b15ffe2b 100644 --- a/src/core/managed-device-lifecycle.test.ts +++ b/src/core/managed-device-lifecycle.test.ts @@ -367,10 +367,10 @@ describe("ManagedDeviceLifecycle", () => { }); }); - it("persists a driver's featureProfile alongside address and driverData on boot (#makeReady path)", async () => { + it("persists a driver's reported mode on boot (#makeReady path)", async () => { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); - const driver = new FakeDriver({ clock, featureProfile: "reduced", platform: "ios" }); + const driver = new FakeDriver({ clock, mode: "slim", platform: "ios" }); let nextId = 0; const registry = await Registry.load({ clock, @@ -400,13 +400,13 @@ describe("ManagedDeviceLifecycle", () => { const ready = await lifecycle.readyProvisioned(device); - expect(ready).toMatchObject({ featureProfile: "reduced" }); + expect(ready).toMatchObject({ mode: "slim" }); }); - it("persists a driver's featureProfile via the bootForLease handoff path (#makeReadyForLease)", async () => { + it("persists a driver's reported mode via the bootForLease handoff path (#makeReadyForLease)", async () => { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); - const driver = new FakeDriver({ clock, featureProfile: "reduced", platform: "ios" }); + const driver = new FakeDriver({ clock, mode: "slim", platform: "ios" }); let nextId = 0; const registry = await Registry.load({ clock, @@ -437,13 +437,12 @@ describe("ManagedDeviceLifecycle", () => { const handoff = await lifecycle.readyProvisionedForLease(device); - expect(handoff?.device).toMatchObject({ featureProfile: "reduced" }); + expect(handoff?.device).toMatchObject({ mode: "slim" }); }); - it("boot clears a stale featureProfile when the driver now reports undefined (#makeReady, shutdown path)", async () => { - // Regression for the HIGH finding: a conditional spread that omitted `featureProfile` - // entirely whenever the driver returned `undefined` left a previously-stored "reduced" on - // the record, so a device slim mode no longer applies to kept reporting `slim: true`. + it("boot stores full, replacing a stored slim, when the driver reports no mode (#makeReady, shutdown path)", async () => { + // A driver that reports no mode must not leave a previously stored "slim" on the record, + // or a device that is no longer slim keeps reporting `mode: "slim"`. const harness = await createHarness(); const ready = await harness.registry.transitionDevice( harness.device.id, @@ -452,10 +451,10 @@ describe("ManagedDeviceLifecycle", () => { { address: harness.device.driverDeviceId, driverData: harness.device.driverData, - featureProfile: "reduced", + mode: "slim", }, ); - expect(ready.featureProfile).toBe("reduced"); + expect(ready.mode).toBe("slim"); await harness.driver.shutdown({ address: ready.address ?? "", deviceId: ready.driverDeviceId, @@ -465,16 +464,16 @@ describe("ManagedDeviceLifecycle", () => { event: "device.shutdown", payload: { deviceId: ready.id, initiator: "test" }, }); - expect(shutdown.featureProfile).toBe("reduced"); + expect(shutdown.mode).toBe("slim"); - // `harness.driver` (a plain `FakeDriver` with no `featureProfile` option) reports `undefined` - // on this boot -- the driver-side equivalent of slim mode having been switched off. + // `harness.driver` (a plain `FakeDriver` with no `mode` option) reports no mode on this + // boot -- the driver-side equivalent of a boot that did not slim. const booted = await harness.lifecycle.boot(shutdown); - expect(booted?.featureProfile).toBeUndefined(); + expect(booted?.mode).toBe("full"); }); - it("bootForLease clears a stale featureProfile when the driver now reports undefined (#makeReadyForLease, shutdown path)", async () => { + it("bootForLease stores full, replacing a stored slim, when the driver reports no mode (#makeReadyForLease, shutdown path)", async () => { const harness = await createHarness(); const ready = await harness.registry.transitionDevice( harness.device.id, @@ -483,7 +482,7 @@ describe("ManagedDeviceLifecycle", () => { { address: harness.device.driverDeviceId, driverData: harness.device.driverData, - featureProfile: "reduced", + mode: "slim", }, ); await harness.driver.shutdown({ @@ -500,10 +499,10 @@ describe("ManagedDeviceLifecycle", () => { const handoff = await harness.lifecycle.bootForLease(shutdown, claim); - expect(handoff?.device.featureProfile).toBeUndefined(); + expect(handoff?.device.mode).toBe("full"); }); - it("readyProvisioned clears a stale featureProfile when the driver now reports undefined (#makeReady, provisioning path)", async () => { + it("readyProvisioned stores full, replacing a stored slim, when the driver reports no mode (#makeReady, provisioning path)", async () => { // A device can't naturally re-enter "provisioning" once it leaves, so the persisted state is // seeded directly (as a restarted daemon would load it from disk) to exercise the same // provisioning-branch code path the "shutdown" tests above cover for the other branch. @@ -525,7 +524,7 @@ describe("ManagedDeviceLifecycle", () => { createdAt: 0, driverData: driverDevice.driverData, driverDeviceId: driverDevice.deviceId, - featureProfile: "reduced", + mode: "slim", id: "dev_stale", spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, state: "provisioning", @@ -550,14 +549,14 @@ describe("ManagedDeviceLifecycle", () => { ); const device = registry.snapshot.devices[0]; if (device === undefined) throw new Error("expected seeded device"); - expect(device.featureProfile).toBe("reduced"); + expect(device.mode).toBe("slim"); const readyDevice = await lifecycle.readyProvisioned(device); - expect(readyDevice?.featureProfile).toBeUndefined(); + expect(readyDevice?.mode).toBe("full"); }); - it("readyProvisionedForLease clears a stale featureProfile when the driver now reports undefined (#makeReadyForLease, provisioning path)", async () => { + it("readyProvisionedForLease stores full, replacing a stored slim, when the driver reports no mode (#makeReadyForLease, provisioning path)", async () => { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); const driver = new FakeDriver({ clock, platform: "ios" }); @@ -576,7 +575,7 @@ describe("ManagedDeviceLifecycle", () => { createdAt: 0, driverData: driverDevice.driverData, driverDeviceId: driverDevice.deviceId, - featureProfile: "reduced", + mode: "slim", id: "dev_stale_2", spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, state: "provisioning", @@ -604,6 +603,6 @@ describe("ManagedDeviceLifecycle", () => { const handoff = await lifecycle.readyProvisionedForLease(device); - expect(handoff?.device.featureProfile).toBeUndefined(); + expect(handoff?.device.mode).toBe("full"); }); }); diff --git a/src/core/nuke-service.test.ts b/src/core/nuke-service.test.ts index 6435d99a1..544a652bc 100644 --- a/src/core/nuke-service.test.ts +++ b/src/core/nuke-service.test.ts @@ -9,6 +9,7 @@ const device = (id: string, state: DeviceRecord["state"]): DeviceRecord => ({ driverDeviceId: `driver_${id}`, id, spec: { model: "Phone", osVersion: "1", platform: "ios" }, + mode: "full", state, }); diff --git a/src/core/quarantine-coordinator.test.ts b/src/core/quarantine-coordinator.test.ts index 636157e23..898678c71 100644 --- a/src/core/quarantine-coordinator.test.ts +++ b/src/core/quarantine-coordinator.test.ts @@ -104,7 +104,15 @@ class FakeRegistry implements QuarantineRegistry { } function device(id: string, driverDeviceId: string): DeviceRecord { - return { createdAt: 1, driverData: {}, driverDeviceId, id, spec, state: "quarantined" }; + return { + createdAt: 1, + driverData: {}, + driverDeviceId, + id, + mode: "full", + spec, + state: "quarantined", + }; } async function createHarness( diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index 31a2e3459..d8f1a69f3 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -60,6 +60,7 @@ describe("Registry", () => { id: "dev_test", leaseIdentity: "reusable", spec, + mode: "full", state: "provisioning", }, ]); @@ -595,6 +596,7 @@ describe("Registry", () => { lastLeaseEndedAt: 1_000, leaseIdentity: "reusable", spec, + mode: "full", state: "ready", }); await expect(registry.recoverFromQuarantine(device.id, "ready")).rejects.toThrow( @@ -788,7 +790,7 @@ describe("Registry", () => { ).rejects.toThrow("Invalid device record in registry state"); }); - it("survives a save/reload round-trip with featureProfile set", async () => { + it("survives a save/reload round-trip with mode set to slim", async () => { const clock = new FakeClock(1_000); const filesystem = new MemoryFilesystem(); const options = { @@ -809,48 +811,91 @@ describe("Registry", () => { device.id, "ready", { event: "device.ready", payload: { bootDuration: 5, deviceId: device.id } }, - { featureProfile: "reduced" }, + { mode: "slim" }, ); const reloaded = await Registry.load(options); expect(reloaded.snapshot).toEqual(registry.snapshot); - expect(reloaded.snapshot.devices[0]).toMatchObject({ featureProfile: "reduced" }); + expect(reloaded.snapshot.devices[0]).toMatchObject({ mode: "slim" }); }); - it("leaves featureProfile absent when the persisted record never set it", async () => { + it("registers a new device as full", async () => { const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - statePath, - JSON.stringify({ - devices: [ - { - createdAt: 500, - driverData: {}, - driverDeviceId: "driver_no_profile", - id: "dev_no_profile", - spec, - state: "ready", - }, - ], - leases: [], - }), - ); - const registry = await Registry.load({ clock, eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, + filesystem: new MemoryFilesystem(), + idGenerator: { generate: () => "test" }, statePath, }); - expect(registry.snapshot.devices[0]).not.toHaveProperty("featureProfile"); + const device = await registry.registerDevice({ + driverData: {}, + driverDeviceId: "driver_test", + provisionDuration: 0, + spec, + }); + + expect(device.mode).toBe("full"); }); - it("drops a garbage featureProfile rather than failing the whole registry load", async () => { + // ADR 0007 §11: no mode is derived from the old key, whatever it said, and the old key is not + // carried forward as an unknown field either. + it.each([ + ["no featureProfile", {}], + ['featureProfile "reduced"', { featureProfile: "reduced" }], + ['featureProfile "full"', { featureProfile: "full" }], + ])( + "loads a record written before mode existed as full (%s) and does not write featureProfile back", + async (_label, legacyFields) => { + const clock = new FakeClock(1_000); + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic( + statePath, + JSON.stringify({ + devices: [ + { + createdAt: 500, + driverData: {}, + driverDeviceId: "driver_legacy", + id: "dev_legacy", + spec, + state: "ready", + ...legacyFields, + }, + ], + leases: [], + }), + ); + const registry = await Registry.load({ + clock, + eventBus: new EventBus(clock), + filesystem, + idGenerator: { generate: () => "new" }, + statePath, + }); + + expect(registry.snapshot.devices[0]?.mode).toBe("full"); + + // Any commit rewrites the whole file, legacy record included. + await registry.registerDevice({ + driverData: {}, + driverDeviceId: "driver_new", + provisionDuration: 0, + spec, + }); + const written = JSON.parse(await filesystem.readFile(statePath)) as { + devices: Record[]; + }; + const legacy = written.devices.find((device) => device.id === "dev_legacy"); + expect(legacy).toMatchObject({ mode: "full" }); + expect(legacy).not.toHaveProperty("featureProfile"); + }, + ); + + it("fails the load when a stored mode is neither slim nor full", async () => { const clock = new FakeClock(1_000); const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); @@ -862,8 +907,8 @@ describe("Registry", () => { createdAt: 500, driverData: {}, driverDeviceId: "driver_garbage", - featureProfile: "not-a-real-profile", id: "dev_garbage", + mode: "reduced", spec, state: "ready", }, @@ -872,15 +917,15 @@ describe("Registry", () => { }), ); - const registry = await Registry.load({ - clock, - eventBus: new EventBus(clock), - filesystem, - idGenerator: { generate: () => "new" }, - statePath, - }); - - expect(registry.snapshot.devices[0]).not.toHaveProperty("featureProfile"); + await expect( + Registry.load({ + clock, + eventBus: new EventBus(clock), + filesystem, + idGenerator: { generate: () => "new" }, + statePath, + }), + ).rejects.toThrow("Invalid device record in registry state"); }); it("clears recovery markers as part of the same commit that ends a lease", async () => { diff --git a/src/core/registry.ts b/src/core/registry.ts index ba788c354..b1bcd75b3 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -6,6 +6,7 @@ import { DEFAULT_LEASE_TTL_MS, } from "./config.js"; import { + type DeviceMode, type DeviceRecord, type DeviceSpec, type DeviceState, @@ -174,6 +175,7 @@ export class Registry implements LeaseRequestStore { driverDeviceId, id: `dev_${this.options.idGenerator.generate()}`, leaseIdentity: this.options.leaseIdentity[spec.platform], + mode: "full", spec: { ...spec }, state: "provisioning", }; @@ -664,7 +666,10 @@ export class Registry implements LeaseRequestStore { this.#unknownState = unknownFields(parsed, ["devices", "leases", "leaseRequests"]); this.#devices = parsed.devices.map((device) => { const record = parseDevice(device); - this.#unknownDeviceFields.set(record.id, unknownFields(device, deviceRecordKeys)); + this.#unknownDeviceFields.set( + record.id, + unknownFields(device, [...deviceRecordKeys, ...retiredDeviceRecordKeys]), + ); return record; }); this.#leases = parsed.leases.map((lease) => { @@ -732,9 +737,15 @@ const deviceRecordKeys = [ "quarantineAttempts", "quarantineNextRetryAt", "address", - "featureProfile", + "mode", "leaseIdentity", ] as const; +/** + * Fields a device record written before ADR 0007 carries that this daemon neither reads nor + * keeps. `featureProfile` is stripped on load, not preserved as an unknown field, and no mode is + * derived from it (ADR 0007 §11). + */ +const retiredDeviceRecordKeys = ["featureProfile"] as const; const leaseRecordKeys = [ "id", "deviceId", @@ -838,7 +849,7 @@ function parseDevice(value: unknown): DeviceRecord { throw new RegistryLoadError("Invalid device record in registry state"); } - const { address, createdAt, driverData, driverDeviceId, featureProfile, id, spec, state } = value; + const { address, createdAt, driverData, driverDeviceId, id, spec, state } = value; if ( typeof id !== "string" || typeof driverDeviceId !== "string" || @@ -857,12 +868,12 @@ function parseDevice(value: unknown): DeviceRecord { return { ...parseOptionalDeviceNumbers(value), ...(address === undefined ? {} : { address }), - ...(isFeatureProfile(featureProfile) ? { featureProfile } : {}), createdAt, driverData, driverDeviceId, id, leaseIdentity: parseLeaseIdentity(value.leaseIdentity), + mode: parseDeviceMode(value.mode), spec, state: state === "warm" ? "reclaiming" : state, }; @@ -870,8 +881,8 @@ function parseDevice(value: unknown): DeviceRecord { /** * A record written before `leaseIdentity` existed was created under the only policy there was, - * so it loads as `reusable`. Unlike `featureProfile`, a present-but-unknown value fails the - * load: guessing `reusable` for it could hand a fresh identity out for a second lease. + * so it loads as `reusable`. A present-but-unknown value fails the load: guessing `reusable` for + * it could hand a fresh identity out for a second lease. */ function parseLeaseIdentity(value: unknown): LeaseIdentity { if (value === undefined) return "reusable"; @@ -880,12 +891,14 @@ function parseLeaseIdentity(value: unknown): LeaseIdentity { } /** - * Unlike `address`, a garbage `featureProfile` is dropped rather than failing the whole record -- - * it is a derived, re-derivable-on-next-boot hint (see `domain.ts`), not load-bearing identity, so - * a corrupt value should not stop the registry (and every other device in it) from loading. + * A record written before `mode` existed loads as `full` (ADR 0007 §11). A present-but-unknown + * value fails the load rather than being guessed at: a wrong `full` would let a slimmed device + * be granted as a full one. */ -function isFeatureProfile(value: unknown): value is "full" | "reduced" { - return value === "full" || value === "reduced"; +function parseDeviceMode(value: unknown): DeviceMode { + if (value === undefined) return "full"; + if (value === "slim" || value === "full") return value; + throw new RegistryLoadError("Invalid device record in registry state"); } /** @@ -927,8 +940,7 @@ function hasValidLeaseCore(value: Record): value is Record = { ...grant.device }; + for (const key of retiredDeviceRecordKeys) delete device[key]; + if (device.mode === undefined) device.mode = "full"; + if (device.mode !== "slim" && device.mode !== "full") return undefined; + return { ...grant, device } as unknown as LeaseGrant; +} + function isDeviceRequest(value: unknown): value is DeviceRequest { return ( isObject(value) && diff --git a/src/core/startup-converger.test.ts b/src/core/startup-converger.test.ts index feba98743..3c80f3549 100644 --- a/src/core/startup-converger.test.ts +++ b/src/core/startup-converger.test.ts @@ -19,6 +19,7 @@ function device( id, lastLeaseEndedAt, spec: { model: "test", osVersion: "1", platform }, + mode: "full", state, }; } diff --git a/src/core/warm-pool-coordinator.test.ts b/src/core/warm-pool-coordinator.test.ts index 437cd4500..43c27f148 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -195,7 +195,15 @@ function device( driverDeviceId: string, deviceSpec: DeviceSpec, ): DeviceRecord { - return { createdAt: 1, driverData: {}, driverDeviceId, id, spec: deviceSpec, state }; + return { + createdAt: 1, + driverData: {}, + driverDeviceId, + id, + mode: "full", + spec: deviceSpec, + state, + }; } function released(device: DeviceRecord): ReleasedLease { @@ -271,11 +279,11 @@ describe("WarmPoolCoordinator", () => { expect(harness.driver.calls.map((call) => call.operation)).toContain("makeReady"); }); - it("stores the driver's featureProfile when a warm re-boot slims the device", async () => { + it("stores the driver's mode when a warm re-boot slims the device", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ clock, - featureProfile: "reduced", + mode: "slim", platform: "ios", reclaimResult: "shutdown", }); @@ -284,26 +292,23 @@ describe("WarmPoolCoordinator", () => { await harness.coordinator.reclaim(released(harness.reclaiming)); expect(harness.registry.snapshot.devices[0]?.state).toBe("ready"); - expect(harness.registry.lastUpdate).toMatchObject({ featureProfile: "reduced" }); - expect(harness.registry.snapshot.devices[0]).toMatchObject({ featureProfile: "reduced" }); + expect(harness.registry.lastUpdate).toMatchObject({ mode: "slim" }); + expect(harness.registry.snapshot.devices[0]).toMatchObject({ mode: "slim" }); }); - it("clears a stale featureProfile when a warm re-boot's makeReady reports no reduction", async () => { + it("stores full, replacing a stored slim, when a warm re-boot's makeReady reports no mode", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ clock, platform: "ios", reclaimResult: "shutdown" }); const staleReclaiming = { ...device("reclaiming", "reclaiming", (await driver.provision(spec)).deviceId, spec), - featureProfile: "reduced" as const, + mode: "slim" as const, }; const harness = await createHarness({ devices: [staleReclaiming], driver }); await harness.coordinator.reclaim(released(staleReclaiming)); - // The update object carries the key with an explicit `undefined` value so the registry's - // spread actually clears the stale "reduced" rather than leaving it in place (see the - // comment in WarmPoolCoordinator#reclaim). - expect(harness.registry.lastUpdate).toHaveProperty("featureProfile", undefined); - expect(harness.registry.snapshot.devices[0]?.featureProfile).toBeUndefined(); + expect(harness.registry.lastUpdate).toHaveProperty("mode", "full"); + expect(harness.registry.snapshot.devices[0]?.mode).toBe("full"); }); it("hands a release-time purge failure to quarantine instead of readiness-checking the device back in", async () => { diff --git a/src/core/warm-pool.test.ts b/src/core/warm-pool.test.ts index 28bc41546..8d1cc1475 100644 --- a/src/core/warm-pool.test.ts +++ b/src/core/warm-pool.test.ts @@ -13,6 +13,7 @@ const device = ( driverDeviceId: id, id, lastLeaseEndedAt, + mode: "full" as const, spec: { model: id, osVersion: "1", platform }, state, }); diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 4b67f5ee2..cf47efb57 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -14,8 +14,9 @@ describe("daemon protocol", () => { // the `worker` token role) all land on the wire with nothing kept behind them, exactly as // ADR 0004's removals took it to 4, so under ADR 0003 §6's honesty rule the range does not // widen to keep speaking 4. ADR 0008 then makes the catalog's `modelRuntimes` required, - // taking it to 6 the same way. - expect(DAEMON_PROTOCOL_VERSION).toBe(6); + // taking it to 6, and ADR 0007 makes a device's mode a required `mode`, taking it to 7, each + // the same way. + expect(DAEMON_PROTOCOL_VERSION).toBe(7); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 66ad086a3..015159c5e 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -754,6 +754,68 @@ describe("Dispatcher: nuke.run", () => { }); }); +describe("Dispatcher: device mode on every surface", () => { + const request = { model: "iPhone 17 Pro", platform: "ios" } as const; + + it.each([ + ["slim", "a slim boot", "slim"], + ["full", "no mode", undefined], + ] as const)( + "a lease grant's device carries mode: %s when the driver reported %s", + async (expected, _reported, driverMode) => { + const { dispatcher } = await buildDispatcher({ driverOptions: { mode: driverMode } }); + + const grant = await dispatcher.dispatch("lease.request", request, session()); + + expect(grant.device.mode).toBe(expected); + }, + ); + + it("status.get and list.get return mode for every device, including one still provisioning", async () => { + const { dispatcher, registry } = await buildDispatcher({ driverOptions: { mode: "slim" } }); + const granted = await dispatcher.dispatch("lease.request", request, session()); + const provisioning = await registry.registerDevice({ + driverData: {}, + driverDeviceId: "driver-provisioning", + provisionDuration: 0, + spec: { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + }); + + const status = await dispatcher.dispatch("status.get", {}, session()); + const list = await dispatcher.dispatch( + "list.get", + { kind: "devices" }, + session({ role: "admin" }), + ); + + const expected = [ + { id: granted.device.id, mode: "slim" }, + { id: provisioning.id, mode: "full" }, + ]; + expect(status.devices.map(({ id, mode }) => ({ id, mode }))).toEqual(expected); + expect((list as { id: string; mode: string }[]).map(({ id, mode }) => ({ id, mode }))).toEqual( + expected, + ); + }); + + it("no lease.request, list.get, or status.get response carries featureProfile or slim", async () => { + const { dispatcher } = await buildDispatcher({ driverOptions: { mode: "slim" } }); + + const responses = [ + await dispatcher.dispatch("lease.request", request, session()), + await dispatcher.dispatch("list.get", { kind: "devices" }, session({ role: "admin" })), + await dispatcher.dispatch("status.get", {}, session()), + ]; + + for (const response of responses) { + const json = JSON.stringify(response); + expect(json).toContain('"mode":"slim"'); + expect(json).not.toContain('"featureProfile"'); + expect(json).not.toContain('"slim":'); + } + }); +}); + describe("Dispatcher: #parseOutput", () => { // ADR §1's central claim -- "the daemon maps its own records onto contract types in exactly // one place ... this is what keeps private types out of the public package surface" -- names diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 854477e7e..b00e7708d 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -16,7 +16,7 @@ import { Registry, RuntimeMissingError, } from "../core/index.js"; -import { PROTOCOL_VERSION_RANGE } from "../contract/index.js"; +import { PROTOCOL_VERSION_RANGE, type ProtocolRange } from "../contract/index.js"; import { AndroidLicenseNotAcceptedError } from "../drivers/android/index.js"; import { createConnectionPair, @@ -2679,6 +2679,29 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { details: { client: { min: 99, max: 99 }, daemon: PROTOCOL_VERSION_RANGE }, }); }); + it("refuses a gateway on the current protocol when this worker advertises the previous one (ADR 0007 §12)", async () => { + const previous = { min: PROTOCOL_VERSION_RANGE.min - 1, max: PROTOCOL_VERSION_RANGE.max - 1 }; + const harness = await createHarness({ + protocolVersion: previous, + resolveRole: { resolve: () => "admin" }, + }); + const [workerEnd, gatewayEnd] = createConnectionPair(); + harness.daemon.acceptUplink(workerEnd); + const gateway = driveConnection(gatewayEnd); + + const reply = await gateway.request("hello", { + clientVersion: "gateway", + protocolRange: PROTOCOL_VERSION_RANGE, + }); + + expect(reply).toMatchObject({ + ok: false, + error: { + code: "PROTOCOL_VERSION_UNSUPPORTED", + details: { client: PROTOCOL_VERSION_RANGE, daemon: previous }, + }, + }); + }); }); /** Drives an in-memory `IpcConnection` the way `createClient` drives a real socket -- enough to @@ -2768,6 +2791,8 @@ async function createHarness( readonly processRunner?: ProcessRunner; /** Replaces the real socket host, for a test that has to control a frame's write. */ readonly host?: ConnectionHost; + /** Overrides the protocol range this daemon advertises, to stand in for an older worker. */ + readonly protocolVersion?: ProtocolRange; } = {}, ) { const directory = @@ -2851,6 +2876,7 @@ async function createHarness( ...(options.logger === undefined ? {} : { logger: options.logger }), passthrough: engine, ...(options.processRunner === undefined ? {} : { processRunner: options.processRunner }), + ...(options.protocolVersion === undefined ? {} : { protocolVersion: options.protocolVersion }), queue: engine, reaper, registry, diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 42e53606c..9df6a174a 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -947,12 +947,11 @@ describe("IosSimctlDriver", () => { driverData, }), ).resolves.toEqual({ - // No `featureProfile` here: slim mode isn't configured at all for this driver, and - // `DriverDevice.featureProfile`'s contract is that `undefined` means "this driver does - // not reduce anything" -- only true while slim mode is off (finding #7, issue #87 review). address: driverData.udid, deviceId: driverData.udid, driverData, + // Slim mode is off, so this boot slimmed nothing: the device is full. + mode: "full", }); expect(runner.calls).toEqual([ { ...simctl("boot", driverData.udid), options: { timeoutMs: 30_000 } }, @@ -1737,11 +1736,11 @@ describe("IosSimctlDriver", () => { driverData, }), ).resolves.toEqual({ - // No `featureProfile`: slim mode is off entirely, so `undefined` is the correct - // "does not reduce anything" report (finding #7, issue #87 review). address: driverData.udid, deviceId: driverData.udid, driverData, + // Slim mode is off, so this boot slimmed nothing: the device is full. + mode: "full", }); expect(runner.calls.map((call) => call.args)).toEqual([ simctlArgs("boot", driverData.udid), @@ -1790,7 +1789,7 @@ describe("IosSimctlDriver", () => { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: { ...slim18_5, slimSignature: widgetsSignature }, - featureProfile: "reduced", + mode: "slim", }); expect(runner.calls.map((call) => call.args)).toEqual([ simctlArgs("boot", slim18_5.udid), @@ -1820,13 +1819,13 @@ describe("IosSimctlDriver", () => { // CHANGED EXPECTATIONS (second adversarial review, finding #2): the previous version of // this test asserted that a failed `#shutdown` call meant "nothing was actually rebooted, // so the device is still healthy" and stopped right there, returning the device as-is with - // `featureProfile: "full"`. That inference doesn't hold -- `#shutdown` fails on a + // `mode: "full"`. That inference doesn't hold -- `#shutdown` fails on a // *non-zero exit* the same way it fails on a *timeout*, and a timeout is exactly the case // where the shutdown may actually be in progress or have already completed. The fix stops // guessing: it always runs a boot+bootstatus afterward regardless of how `#shutdown` came // back, so the device handed back is verified running, not assumed running. Because // whether the disable list survived is now genuinely unknown, the outcome is also - // downgraded from "full" to "reduced" -- the safe direction under uncertainty (see the + // downgraded from "full" to "slim" -- the safe direction under uncertainty (see the // comment on `#applySlimAndReboot`). const filesystem = new MemoryFilesystem(); await plantManagedDevice(filesystem); @@ -1869,7 +1868,7 @@ describe("IosSimctlDriver", () => { deviceId: slim18_5.udid, // Unchanged: no marker written, so the next `makeReady` retries the whole label set. driverData: slim18_5, - featureProfile: "reduced", + mode: "slim", }); expect(runner.calls.map((call) => call.args)).toEqual([ simctlArgs("boot", slim18_5.udid), @@ -1939,7 +1938,7 @@ describe("IosSimctlDriver", () => { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: slim18_5, - featureProfile: "reduced", + mode: "slim", }); expect(runner.calls.map((call) => call.args)).toEqual([ simctlArgs("boot", slim18_5.udid), @@ -2079,7 +2078,7 @@ describe("IosSimctlDriver", () => { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: slimmedData, - featureProfile: "reduced", + mode: "slim", }); expect(runner.calls.map((call) => call.args)).toEqual([ simctlArgs("boot", slim18_5.udid), @@ -2188,7 +2187,7 @@ describe("IosSimctlDriver", () => { address: slim18_4.udid, deviceId: slim18_4.udid, driverData: slim18_4, - featureProfile: "full", + mode: "full", }); expect(runner.calls).toHaveLength(2); expect(onSlimSkipped).toHaveBeenCalledWith( @@ -2338,7 +2337,7 @@ describe("IosSimctlDriver", () => { // The marker IS written this time -- no `slimMarkToken` because no mark file exists yet // in this test (mirrors "boots, applies the disable list..." above). driverData: { ...slim18_5, slimSignature: widgetsSignature }, - featureProfile: "reduced", + mode: "slim", }); expect(runner.calls.map((call) => call.args)).toEqual([ simctlArgs("boot", slim18_5.udid), @@ -2390,7 +2389,7 @@ describe("IosSimctlDriver", () => { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: alreadySlimmedData, - featureProfile: "reduced", + mode: "slim", }); expect(runner.calls.map((call) => call.args)).toEqual([ simctlArgs("boot", slim18_5.udid), @@ -2410,7 +2409,7 @@ describe("IosSimctlDriver", () => { // write the idempotence marker: the device reboots (the labels that did apply are worth // keeping), but comes back exactly as it went in, so the very next `makeReady` sees no // stored `slimSignature` and re-applies the whole set again. CHANGED EXPECTATION - // (second-review finding #3): the outcome here is `"reduced"`, not `"full"` -- the labels + // (second-review finding #3): the outcome here is `"slim"`, not `"full"` -- the labels // that did apply really are gone, so "full" would be a lie in the dangerous direction. const allLabels = labelsFor(resolveSlimCategories(undefined).categories); const chunkSize = 50; @@ -2483,7 +2482,7 @@ describe("IosSimctlDriver", () => { // Unchanged: no `slimSignature`/`slimMarkToken` written, so the next `makeReady` will // find `#checkAlreadySlimmed` false and re-apply the whole set. driverData: slim18_5, - featureProfile: "reduced", + mode: "slim", }); expect(runner.calls.map((call) => call.args)).toEqual([ simctlArgs("boot", slim18_5.udid), @@ -2536,7 +2535,7 @@ describe("IosSimctlDriver", () => { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: slim18_5, - featureProfile: "full", + mode: "full", }); expect(runner.calls.map((call) => call.args)).toEqual([ simctlArgs("boot", slim18_5.udid), @@ -2575,7 +2574,7 @@ describe("IosSimctlDriver", () => { address: fullData.udid, deviceId: fullData.udid, driverData: fullData, - featureProfile: "full", + mode: "full", }); expect(runner.calls).toHaveLength(2); expect(runner.calls[1]?.options).toEqual({ timeoutMs: 120_000 }); @@ -2621,7 +2620,7 @@ describe("IosSimctlDriver", () => { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: slim18_5, - featureProfile: "full", + mode: "full", }); expect(runner.calls.map((call) => call.args)).toEqual([ simctlArgs("boot", slim18_5.udid), @@ -2652,10 +2651,11 @@ describe("IosSimctlDriver", () => { driverData, }), ).resolves.toEqual({ - // No `featureProfile`: slim mode is off here too. address: driverData.udid, deviceId: driverData.udid, driverData, + // Slim mode is off, so this boot slimmed nothing: the device is full. + mode: "full", }); }); diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 83cce01b2..a3b8d510b 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -24,7 +24,7 @@ import { UnknownModelError, } from "../../core/index.js"; import type { ObservedMark } from "../../core/driver.js"; -import type { DeviceSpec } from "../../core/index.js"; +import type { DeviceMode, DeviceSpec } from "../../core/index.js"; import { stableError } from "../../core/stable-error.js"; import type { Clock, @@ -772,28 +772,21 @@ export class IosSimctlDriver implements Driver { } if (plan.kind !== "apply") { - // `undefined` (not "full") whenever slim mode isn't enabled at all -- `DriverDevice. - // featureProfile`'s contract is that `undefined` means "this driver does not reduce - // anything", which is only true while slim mode is off. Once slim mode is on, "full" is - // meaningful (this particular boot didn't reduce anything -- a per-device `full: true` - // opt-out, a `"recover"` boot, or a runtime-gate skip) and is reported as such. - return this.#asIs(device, data, this.#slim?.enabled === true ? "full" : undefined); + // This boot slimmed nothing: slim mode is off, a per-device `full: true` opt-out, a + // `"recover"` boot, or a runtime-gate skip. The device is full. + return this.#asIs(device, data, "full"); } return this.#applySlimAndReboot(device, data, plan.slim, bootstatusTimeoutMs); } - /** The device's current `address`/`driverData`, unmodified, tagged with the feature profile. */ - #asIs( - device: DriverDevice, - data: IosDriverData, - featureProfile: "full" | "reduced" | undefined, - ): DriverDevice { + /** The device's current `address`/`driverData`, unmodified, tagged with the mode it has. */ + #asIs(device: DriverDevice, data: IosDriverData, mode: DeviceMode): DriverDevice { return { address: data.udid, deviceId: device.deviceId, driverData: device.driverData, - ...(featureProfile === undefined ? {} : { featureProfile }), + mode, }; } @@ -850,7 +843,7 @@ export class IosSimctlDriver implements Driver { const signature = slimSignature(resolved.categories); const idempotence = await this.#checkAlreadySlimmed(data, signature); if (idempotence.alreadySlimmed) { - return this.#asIs(device, data, "reduced"); + return this.#asIs(device, data, "slim"); } const labels = labelsFor(resolved.categories); @@ -888,7 +881,7 @@ export class IosSimctlDriver implements Driver { if (shutdownError !== undefined) { // The shutdown call itself failed, so whether the labels' reboot actually took effect is // unknown -- this is an uncertain apply, not a confirmed one. Never write the idempotence - // marker on it (same reasoning as the partial-apply case below), and report "reduced" (not + // marker on it (same reasoning as the partial-apply case below), and report "slim" (not // "full") under that uncertainty: telling a caller a device is slim when it is not is // benign -- it just avoids features it could have used -- while telling it a device is full // when it is not makes push / Spotlight / StoreKit fail with no explanation, exactly the @@ -897,7 +890,7 @@ export class IosSimctlDriver implements Driver { device, data, `slim shutdown failed: ${errorMessage(shutdownError)}`, - "reduced", + "slim", ); } @@ -910,13 +903,13 @@ export class IosSimctlDriver implements Driver { // never retry the labels that were never attempted, with no way back short of // `reclaim`/`erase`. So a partial apply deliberately costs a re-attempt of the *whole* // label set on the next `makeReady` instead -- applying an already-disabled label again is - // harmless (same comment on `#checkAlreadySlimmed`). "reduced" because the labels that did + // harmless (same comment on `#checkAlreadySlimmed`). "slim" because the labels that did // apply really are gone. return this.#skipApply( device, data, `${String(applyOutcome.unattemptedLabels.length)} of ${String(labels.length)} labels were never attempted (a chunk failed to run)`, - "reduced", + "slim", ); } @@ -943,10 +936,10 @@ export class IosSimctlDriver implements Driver { device: DriverDevice, data: IosDriverData, detail: string, - featureProfile: "full" | "reduced", + mode: DeviceMode, ): DriverDevice { this.#onSlimSkipped?.({ deviceId: device.deviceId, detail, reason: "apply-failed" }); - return this.#asIs(device, data, featureProfile); + return this.#asIs(device, data, mode); } /** @@ -1012,7 +1005,7 @@ export class IosSimctlDriver implements Driver { address: data.udid, deviceId: device.deviceId, driverData: newDriverData, - featureProfile: "reduced", + mode: "slim", }; } diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 8a795005e..91d2b5146 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -257,6 +257,29 @@ describe("GatewayDispatcher", () => { expect(status.leases).toEqual([expect.objectContaining({ workerId: "wrk_1" })]); }); + it("reports each worker device's mode on status.get and worker.list", async () => { + const { dispatcher, workers } = harness(); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { + capacity: statusFixture().capacity, + devices: [deviceFixture("dev_slim", "leased", "slim"), deviceFixture("dev_full")], + health: "running", + leases: [], + queueDepth: 0, + }); + + const status = await dispatcher.dispatch("status.get", {}, session()); + const list = await dispatcher.dispatch("worker.list", {}, session()); + + const expected = [ + { id: "dev_slim", mode: "slim" }, + { id: "dev_full", mode: "full" }, + ]; + expect(status.devices.map(({ id, mode }) => ({ id, mode }))).toEqual(expected); + expect(status.workers?.[0]?.devices.map(({ id, mode }) => ({ id, mode }))).toEqual(expected); + expect(list.workers[0]?.devices.map(({ id, mode }) => ({ id, mode }))).toEqual(expected); + }); + it("answers catalog.get as the union of the fleet's catalogs", async () => { const { dispatcher, workers } = harness(); workers.connected("wrk_1", undefined, undefined); diff --git a/src/gateway/routing/warm-then-free.test.ts b/src/gateway/routing/warm-then-free.test.ts index ee0cbe162..4b4b83d38 100644 --- a/src/gateway/routing/warm-then-free.test.ts +++ b/src/gateway/routing/warm-then-free.test.ts @@ -105,6 +105,7 @@ function generateFleet(random: () => number): { ).platforms; const devices = Array.from({ length: Math.floor(random() * 3) }, (_, n) => ({ id: `dev_${index}_${n}`, + mode: pick(["slim", "full"] as const), spec: { model: pick(MODELS), osVersion: pick(RUNTIMES), platform: pick(PLATFORMS) }, state: pick(["ready", "leased"] as const), })); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 6db19b200..b7ea6423a 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -22,6 +22,11 @@ import { import { MAX_CONSECUTIVE_REFRESH_TIMEOUTS, WORKER_CALL_TIMEOUT_MS } from "./worker-link.js"; const RETENTION_MS = 24 * 60 * 60_000; +/** A worker one protocol version behind this gateway (ADR 0007 §12: no shim, no widened range). */ +const previousProtocol = { + min: PROTOCOL_VERSION_RANGE.min - 1, + max: PROTOCOL_VERSION_RANGE.max - 1, +}; const REFRESH_MS = 30_000; /** Matches `core/config.ts`'s own default (ADR 0005 §15's own cap). */ const DEFAULT_LEASE_MAX_TTL_MS = 4 * 60 * 60_000; @@ -182,6 +187,28 @@ describe("GatewayService", () => { await harness.service.stop(); }); + it("keeps each worker device's mode in the view", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + worker.devices = [ + { ...deviceFixture("dev_slim", "ready", "slim"), createdAt: 1, driverData: {} }, + { ...deviceFixture("dev_full", "ready", "full"), createdAt: 1, driverData: {} }, + ]; + + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.devices).toHaveLength(2)); + + expect( + harness.service.workers.view("wrk_1")?.devices.map(({ id, mode }) => ({ id, mode })), + ).toEqual([ + { id: "dev_slim", mode: "slim" }, + { id: "dev_full", mode: "full" }, + ]); + + await harness.service.stop(); + }); + it("republishes a worker's events with its workerId, into its own ring buffer", async () => { const harness = fleet(); await harness.service.start(); @@ -441,7 +468,7 @@ describe("GatewayService", () => { const worker = new ScriptedWorkerClient(); // What `connectSimlockAdmin`'s degraded client does after a failed negotiation: every call // rejects with the captured error, carrying both ranges. - worker.failWith = protocolMismatchError({ min: 4, max: 4 }); + worker.failWith = protocolMismatchError(previousProtocol); await harness.join("wrk_1", worker); await vi.waitFor(() => @@ -449,7 +476,7 @@ describe("GatewayService", () => { ); expect(harness.service.workers.view("wrk_1")).toMatchObject({ - protocol: { gateway: PROTOCOL_VERSION_RANGE, worker: { min: 4, max: 4 } }, + protocol: { gateway: PROTOCOL_VERSION_RANGE, worker: previousProtocol }, }); expect(worker.calls).toEqual(["status.get"]); expect(worker.subscribed).toBe(false); diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index cef1635e7..848bb9f53 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -70,9 +70,14 @@ export function leaseFixture(id: string, deviceId: string) { }; } -export function deviceFixture(id: string, state: "ready" | "leased" = "ready") { +export function deviceFixture( + id: string, + state: "ready" | "leased" = "ready", + mode: "slim" | "full" = "full", +) { return { id, + mode, spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" as const }, state, }; @@ -102,6 +107,7 @@ export function grantFixture(overrides: Partial = {}): LeaseGrant { id: "dev_1", driverDeviceId: "udid-1", spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" }, + mode: "full", }, environment: {}, lease: leaseFixture("lse_1", "dev_1") as LeaseRecord, diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index 994b9d622..1d141f720 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -91,6 +91,7 @@ export function makeDevice(overrides: Partial = {}): DeviceRecord driverDeviceId: "ABCD-1234", id: "dev_1", spec: { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + mode: "full", state: "leased", ...overrides, }; diff --git a/src/http/tracker.test.ts b/src/http/tracker.test.ts index c0761cc04..5e7d53e7f 100644 --- a/src/http/tracker.test.ts +++ b/src/http/tracker.test.ts @@ -289,27 +289,21 @@ describe("LeaseRequestTracker.submit with full", () => { }); describe("LeaseRequestTracker granted lease payload", () => { - it("reports slim: false when the granted device's featureProfile is absent", async () => { - const { dispatcher, tracker } = buildTracker(); - const { view, callIndex } = await createTracked(tracker, dispatcher); - dispatcher.calls[callIndex]?.resolve(makeGrant()); - await Promise.resolve(); - await Promise.resolve(); - const state = tracker.get(view.id)?.state; - if (state?.stage !== "granted") throw new Error("expected granted"); - expect(state.lease.slim).toBe(false); - }); - - it("reports slim: true when the granted device's featureProfile is reduced", async () => { - const { dispatcher, tracker } = buildTracker(); - const { view, callIndex } = await createTracked(tracker, dispatcher); - dispatcher.calls[callIndex]?.resolve(makeGrant({ device: { featureProfile: "reduced" } })); - await Promise.resolve(); - await Promise.resolve(); - const state = tracker.get(view.id)?.state; - if (state?.stage !== "granted") throw new Error("expected granted"); - expect(state.lease.slim).toBe(true); - }); + it.each(["slim", "full"] as const)( + "reports the granted device's mode (%s) as the lease's mode, with no slim flag", + async (mode) => { + const { dispatcher, tracker } = buildTracker(); + const { view, callIndex } = await createTracked(tracker, dispatcher); + dispatcher.calls[callIndex]?.resolve(makeGrant({ device: { mode } })); + await Promise.resolve(); + await Promise.resolve(); + const state = tracker.get(view.id)?.state; + if (state?.stage !== "granted") throw new Error("expected granted"); + expect(state.lease.mode).toBe(mode); + expect(state.lease).not.toHaveProperty("slim"); + expect(state.lease).not.toHaveProperty("featureProfile"); + }, + ); }); describe("LeaseRequestTracker.waitForChange abort", () => { diff --git a/src/http/tracker.ts b/src/http/tracker.ts index e862f2a1d..75ef9e620 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -38,8 +38,8 @@ export interface LeasePayload { readonly expiresAt: string; readonly ttlMs: number; readonly dataPlane: null; - /** Whether the granted device had its feature set reduced -- see `DeviceRecord.featureProfile`. */ - readonly slim: boolean; + /** The mode the granted device actually has -- see `DeviceRecord.mode`. */ + readonly mode: "slim" | "full"; } /** @@ -71,7 +71,7 @@ export function buildLeasePayload( expiresAt: new Date(lease.ttlDeadline).toISOString(), ttlMs: lease.ttlMs, dataPlane: null, - slim: device.featureProfile === "reduced", + mode: device.mode, }; } @@ -345,7 +345,7 @@ interface HttpLeaseDevice { readonly id: string; readonly driverDeviceId: string; readonly spec: { readonly platform: string; readonly model: string; readonly osVersion: string }; - readonly featureProfile?: "full" | "reduced" | undefined; + readonly mode: "slim" | "full"; } interface HttpLeaseRecord { diff --git a/src/mcp/contracts.test.ts b/src/mcp/contracts.test.ts index 6697afe17..bd4ccbea3 100644 --- a/src/mcp/contracts.test.ts +++ b/src/mcp/contracts.test.ts @@ -64,6 +64,7 @@ describe("MCP contracts", () => { driverDeviceId: "SIM-1", id: "device-1", spec: { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + mode: "full", state: "leased", }, environment: {}, diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index 6a7573ad1..e052922b7 100644 --- a/src/mcp/test-support.ts +++ b/src/mcp/test-support.ts @@ -202,6 +202,7 @@ export function sampleGrant(overrides: { readonly leaseId?: string } = {}): Leas driverDeviceId: "SIM-1", id: "device-1", spec: { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + mode: "full", }, environment: {}, lease: { diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index aba460bd8..99c747871 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -19,6 +19,7 @@ function sampleGrant( driverDeviceId: "sim-1", id: deviceId, spec: { model: "iPhone 17", osVersion: "18.0", platform: "ios" }, + mode: "full", }, environment: {}, lease: {