diff --git a/e2e/image-tag.test.ts b/e2e/image-tag.test.ts deleted file mode 100644 index 83d45d976..000000000 --- a/e2e/image-tag.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { withDaemon } from "./helpers/index.js"; - -/** API 34 has a google_apis and a google_apis_playstore image; API 35 only google_apis. */ -const ANDROID_IMAGES = { - android: { - availableOsVersions: ["34", "35"], - images: [ - { abi: "arm64-v8a", runtime: "34", tag: "google_apis" }, - { abi: "arm64-v8a", runtime: "34", tag: "google_apis_playstore" }, - { abi: "arm64-v8a", runtime: "35", tag: "google_apis" }, - ], - }, -}; - -function lease(extra: readonly string[]): string[] { - return ["lease", "--platform", "android", "--device", "Pixel 8", "--detach", ...extra]; -} - -describe("lease --image-tag", () => { - it("grants a device whose spec names the tag, at the newest API level with an image of that tag", async () => { - const env = await withDaemon({ driverScript: ANDROID_IMAGES }); - - const result = await env.cli(lease(["--image-tag", "google_apis_playstore"])); - - expect(result.code).toBe(0); - expect((result.json as { device: { spec: unknown } }).device.spec).toEqual({ - imageTag: "google_apis_playstore", - model: "Pixel 8", - osVersion: "34", - platform: "android", - }); - }); - - it("fails a tag not installed for the API level with RUNTIME_MISSING (exit 12), --allow-download or not, and never installs", async () => { - const env = await withDaemon({ driverScript: ANDROID_IMAGES }); - await env.driverLog.clear(); - const tagged = ["--os", "35", "--image-tag", "google_apis_playstore"]; - - const plain = await env.cli(lease(tagged)); - const allowed = await env.cli(lease([...tagged, "--allow-download"])); - - for (const result of [plain, allowed]) { - expect(result.code).toBe(12); - expect(JSON.parse(result.stderr)).toMatchObject({ error: { code: "RUNTIME_MISSING" } }); - } - const operations = (await env.driverLog.calls()).map((call) => call.operation); - expect(operations).toContain("resolveSpec"); - expect(operations).not.toContain("installComponent"); - expect(operations).not.toContain("provision"); - }); -}); diff --git a/e2e/lease-environment-passthrough.test.ts b/e2e/lease-environment-passthrough.test.ts index 1d8fdc3cd..2e769bb34 100644 --- a/e2e/lease-environment-passthrough.test.ts +++ b/e2e/lease-environment-passthrough.test.ts @@ -101,18 +101,16 @@ describe("reaching a leased device", () => { }, ); - it.each([ - [["simctl", "delete", "ABCD"], "simctl delete"], - [["adb", "kill-server"], "adb kill-server"], - [["adb", "-s", "emulator-5586", "emu", "kill"], "adb emu kill"], - ])("refuses %s with a usage error naming what to run instead", async (args, refused) => { + // One verb is enough: which verbs are refused is each driver's decision, tested with the + // drivers. What only separate processes show is the refusal reaching the shell as exit 2. + it("refuses a destructive passthrough with a usage error naming what to run instead", async () => { const env = await withDaemon(); - const refusal = await env.cli(args); + const refusal = await env.cli(["simctl", "delete", "ABCD"]); expect(refusal.code).toBe(2); expect(refusal.error?.code).toBe("USAGE"); - expect(refusal.error?.message).toContain(refused); + expect(refusal.error?.message).toContain("simctl delete"); expect(refusal.error?.message).toContain("simlock release"); expect(refusal.stdout).toBe(""); }); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 68410d4d0..be54c0b1d 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -19,7 +19,6 @@ import { NodeFilesystem, NodeIpcTransport, NoopLogger, - SocketPathTooLongError, type Filesystem, type IdGenerator, } from "../ports/index.js"; @@ -49,7 +48,6 @@ import { connectSimlockAdmin } from "../admin/index.js"; import { RELEASE_TIMEOUT_MS } from "../lease-policy/index.js"; import { buildCliEnvironment, - errorExitCode, parseDuration, readLogFile, readPipedStdin, @@ -164,8 +162,6 @@ describe("CLI: exit codes", () => { ["UNKNOWN_LEASE", 1], ] as const)("maps %s to exit %d, from ERROR_TABLE not a second map", async (code, expected) => { const error = simlockError(code); - expect(errorExitCode(error)).toBe(expected); - const output = outputCapture(); await expect( runCli( @@ -4338,28 +4334,11 @@ describe("CLI: a SIMLOCK_HOME the kernel could not bind", () => { expect(reported.error.code).toBe("USAGE"); expect(reported.error.message).toContain("SIMLOCK_HOME"); }); - - it("maps the error to the documented usage exit code", () => { - expect(errorExitCode(new SocketPathTooLongError(`${tooDeep}/daemon.sock`, 103))).toBe(2); - }); }); describe("CLI: requester id from the agent session", () => { const sessionEnv = { CLAUDE_CODE_SESSION_ID: "abc" }; - it("buildCliEnvironment resolves requesterId to the session-derived id when SIMLOCK_AGENT_ID is unset", () => { - expect(buildCliEnvironment(realCliEnvironmentPorts(), sessionEnv).requesterId).toBe( - "claude-code:abc", - ); - }); - - it("buildCliEnvironment prefers SIMLOCK_AGENT_ID over a session-derived id", () => { - expect( - buildCliEnvironment(realCliEnvironmentPorts(), { ...sessionEnv, SIMLOCK_AGENT_ID: "agent-7" }) - .requesterId, - ).toBe("agent-7"); - }); - it("buildCliEnvironment falls back to the pid when no agent id or session id is set", () => { expect(buildCliEnvironment(realCliEnvironmentPorts(), {}).requesterId).toBe( String(process.pid), diff --git a/src/cli/index.ts b/src/cli/index.ts index 11074d81d..30881004f 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -885,7 +885,7 @@ async function resolveRemoteLeaseId( /** ADR §7: "CLI exit codes and HTTP status codes are columns of the same error table, not * second mappings" -- driven from `ERROR_TABLE`'s `cliExitCode` column rather than a second, * CLI-maintained map. */ -export function errorExitCode(error: unknown): number { +function errorExitCode(error: unknown): number { if (error instanceof UsageError || error instanceof SocketPathTooLongError) return 2; if (isSimlockError(error)) return ERROR_TABLE[error.code].cliExitCode; return 1; diff --git a/src/contract/errors.test.ts b/src/contract/errors.test.ts index ce13ebbd6..c59742c8e 100644 --- a/src/contract/errors.test.ts +++ b/src/contract/errors.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { ERROR_TABLE, fromWireError, isSimlockError, SimlockError } from "./errors.js"; +import { ERROR_TABLE, fromWireError, isSimlockError } from "./errors.js"; describe("SimlockError", () => { it("narrows details by code", () => { @@ -41,17 +41,4 @@ describe("SimlockError", () => { it("isSimlockError rejects a plain Error", () => { expect(isSimlockError(new Error("boom"))).toBe(false); }); - - it("every table entry's code matches its own key", () => { - for (const [key, entry] of Object.entries(ERROR_TABLE)) { - expect(entry.code).toBe(key); - } - }); - - it("constructs directly with typed details", () => { - const error = new SimlockError("UNKNOWN_LEASE", "domain", "no such lease", { - leaseId: "lease_9", - }); - expect(error.details.leaseId).toBe("lease_9"); - }); }); diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index e11739dee..920743750 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -1,24 +1,8 @@ -import { z } from "zod"; import { describe, expect, it } from "vitest"; -import { defineOperation, OPERATIONS, type Effect, type OperationName } from "./operations.js"; +import { OPERATIONS, type Effect, type OperationName } from "./operations.js"; import { PUSH_SCHEMAS } from "./pushes.js"; -import { ROLES, type Role } from "./roles.js"; - -describe("defineOperation", () => { - it("returns the definition unchanged, typed from its zod schemas", () => { - const echo = defineOperation({ - name: "test.echo", - role: "agent", - effect: "read", - input: z.object({ value: z.string() }), - output: z.object({ value: z.string() }), - }); - expect(echo.input.parse({ value: "hi" })).toEqual({ value: "hi" }); - expect(echo.output.parse({ value: "hi" })).toEqual({ value: "hi" }); - expect(echo.role).toBe("agent"); - }); -}); +import type { Role } from "./roles.js"; /** * The ADR §3 operation matrix, name -> role. A table-driven test against this makes @@ -84,10 +68,6 @@ describe("operation role matrix", () => { expect(declaredNames).toEqual(matrixNames); }); - it("only ever resolves to one of the two declared roles", () => { - for (const row of ROLE_MATRIX) expect(ROLES).toContain(row.role); - }); - it.each(ROLE_MATRIX)("$name with $input resolves to role $role", ({ name, input, role }) => { const operation = OPERATIONS[name]; const roleFn = operation.role as Role | ((input: unknown) => Role); @@ -163,14 +143,6 @@ describe("operation effects", () => { expect(new Set(EFFECT_MATRIX.map((row) => row.name))).toEqual(new Set(Object.keys(OPERATIONS))); }); - it("doctor.run is a write only with fix or purgeOrphans, and cleanup.run is a read only with dryRun", () => { - expect(resolvedEffect("doctor.run", {})).toBe("read"); - expect(resolvedEffect("doctor.run", { fix: true })).toBe("write"); - expect(resolvedEffect("doctor.run", { purgeOrphans: true })).toBe("write"); - expect(resolvedEffect("cleanup.run", {})).toBe("write"); - expect(resolvedEffect("cleanup.run", { dryRun: true })).toBe("read"); - }); - it.each(EFFECT_MATRIX)("$name with $input is a $effect", ({ name, input, effect }) => { expect(resolvedEffect(name, input)).toBe(effect); }); diff --git a/src/contract/operations.ts b/src/contract/operations.ts index d59fae97f..eb58f1c3c 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -59,7 +59,7 @@ export interface OperationDefinition< readonly authorize?: (input: z.infer, context: AuthorizeContext) => boolean; } -export function defineOperation< +function defineOperation< Name extends string, InputSchema extends z.ZodTypeAny, OutputSchema extends z.ZodTypeAny, diff --git a/src/contract/protocol.test.ts b/src/contract/protocol.test.ts index 6ac9b5eff..32b05af41 100644 --- a/src/contract/protocol.test.ts +++ b/src/contract/protocol.test.ts @@ -2,11 +2,8 @@ import { describe, expect, it } from "vitest"; import { helloRequestSchema, - LEGACY_DAEMON_PROTOCOL_VERSION, - mapLegacyProtocolMismatch, negotiateProtocolVersion, normalizeProtocolVersion, - PROTOCOL_VERSION_RANGE, } from "./protocol.js"; describe("negotiateProtocolVersion", () => { @@ -30,21 +27,6 @@ describe("normalizeProtocolVersion", () => { }); }); -describe("mapLegacyProtocolMismatch", () => { - it("reports the daemon range as {2, 2} and an unknown daemon version", () => { - const error = mapLegacyProtocolMismatch( - PROTOCOL_VERSION_RANGE, - "Protocol version 3 is not supported", - ); - expect(error.code).toBe("PROTOCOL_VERSION_UNSUPPORTED"); - expect(error.details).toEqual({ - client: PROTOCOL_VERSION_RANGE, - daemon: { min: LEGACY_DAEMON_PROTOCOL_VERSION, max: LEGACY_DAEMON_PROTOCOL_VERSION }, - daemonVersion: "unknown", - }); - }); -}); - describe("helloRequestSchema", () => { it("accepts a bare legacy protocolVersion with no range", () => { expect(() => diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 102a94e2c..4089f2365 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -51,7 +51,7 @@ export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 9, max: 9 }; * in this repository to negotiate with; this constant documents the historical fact the ADR's * compatibility note depends on. */ -export const LEGACY_DAEMON_PROTOCOL_VERSION = 2; +const LEGACY_DAEMON_PROTOCOL_VERSION = 2; /** Highest version present in both ranges, or `undefined` if they do not overlap at all. */ export function negotiateProtocolVersion( diff --git a/src/contract/roles.ts b/src/contract/roles.ts index c55099034..22d00ead4 100644 --- a/src/contract/roles.ts +++ b/src/contract/roles.ts @@ -3,7 +3,7 @@ * below an operation's -- is the dispatcher's job (§2), which is PR 2. This module only * declares the vocabulary the rest of the contract is typed against. */ -export const ROLES = ["agent", "admin"] as const; +const ROLES = ["agent", "admin"] as const; export type Role = (typeof ROLES)[number]; /** diff --git a/src/core/capacity/strategies/fixed/index.test.ts b/src/core/capacity/strategies/fixed/index.test.ts index 63345cea3..fc8ebcac0 100644 --- a/src/core/capacity/strategies/fixed/index.test.ts +++ b/src/core/capacity/strategies/fixed/index.test.ts @@ -78,18 +78,6 @@ describe("fixed strategy", () => { }); }); - it("ignores deleted devices when counting against the pin", () => { - const fixed = strategy({ maxRunning: 1 }); - - expect( - fixed.canProvision({ mode: "full", platform: "ios" }, [ - { mode: "full" as const, platform: "ios", state: "deleted" }, - ]), - ).toEqual({ - ok: true, - }); - }); - it("grants up to maxRunning whatever the modes, never refuses a boot, and reports no RAM budget", () => { const fixed = strategy({ maxRunning: 3 }); const mixed = [...ready("ios", 1, "slim"), ...ready("ios", 1, "full")]; diff --git a/src/core/capacity/strategies/resource/index.test.ts b/src/core/capacity/strategies/resource/index.test.ts index 4beefa369..451b99fde 100644 --- a/src/core/capacity/strategies/resource/index.test.ts +++ b/src/core/capacity/strategies/resource/index.test.ts @@ -74,16 +74,6 @@ describe("resource strategy provisioning", () => { }); }); - it("does not count deleted devices against capacity", () => { - const devices: CapacityDevice[] = [ - { mode: "full" as const, platform: "ios", state: "deleted" }, - ]; - - expect(withRam(32 * gibibyte).canProvision({ mode: "full", platform: "ios" }, devices)).toEqual( - { ok: true }, - ); - }); - it("accounts for active devices on both platforms in the shared RAM budget", () => { const devices: CapacityDevice[] = [ { mode: "full" as const, platform: "android", state: "ready" }, diff --git a/src/core/config.test.ts b/src/core/config.test.ts index dab1e9d00..db287a17f 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -125,66 +125,6 @@ describe("loadConfig", () => { expect(Object.isFrozen(resourceOptions(config).limits)).toBe(true); }); - it("defaults mode to worker and accepts only the two it knows", async () => { - // ADR 0005 §1: one daemon, one mode, and it decides what the process *is* -- so it is - // config rather than a flag, and a typo has to fail at load rather than leave a daemon - // running as something nobody asked for. - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - - const defaulted = await loadConfig({ configPath, filesystem, systemStats: createStats() }); - expect(defaulted.mode).toBe("worker"); - - // `http.enabled: true` here because a gateway with HTTP off is its own rejection -- - // see the next test -- and this one is only about the two spellings `mode` accepts. - await filesystem.writeFileAtomic( - configPath, - JSON.stringify({ http: { enabled: true }, mode: "gateway" }), - ); - const gateway = await loadConfig({ configPath, filesystem, systemStats: createStats() }); - expect(gateway.mode).toBe("gateway"); - - await filesystem.writeFileAtomic(configPath, JSON.stringify({ mode: "broker" })); - await expect( - loadConfig({ configPath, filesystem, systemStats: createStats() }), - ).rejects.toThrow("mode"); - }); - - it("defaults a gateway to http.enabled and rejects one that turns it off at load", async () => { - // ADR 0005 §2: a gateway is the fleet's contact point over both HTTP and its unix socket, - // so one with HTTP off is unreachable by any worker or agent -- a config with no safe - // reading, rejected the same way a self-contradicting lease TTL pair is (naming the key, - // daemon does not start) rather than started and left silently useless. - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - - // A gateway defaults `http.enabled` to true (it is the fleet's contact point), so naming - // only `mode` is a complete, valid gateway config rather than a rejected one. Only a - // config that says `false` out loud is refused -- a value the operator wrote and the - // daemon quietly inverted would be worse than a start that says why. - await filesystem.writeFileAtomic(configPath, JSON.stringify({ mode: "gateway" })); - await expect( - loadConfig({ configPath, filesystem, systemStats: createStats() }), - ).resolves.toMatchObject({ http: { enabled: true }, mode: "gateway" }); - - await filesystem.writeFileAtomic( - configPath, - JSON.stringify({ http: { enabled: false }, mode: "gateway" }), - ); - await expect( - loadConfig({ configPath, filesystem, systemStats: createStats() }), - ).rejects.toThrow("http.enabled"); - - // A worker with HTTP off is unaffected: HTTP is genuinely optional for that mode. - await filesystem.writeFileAtomic( - configPath, - JSON.stringify({ http: { enabled: false }, mode: "worker" }), - ); - await expect( - loadConfig({ configPath, filesystem, systemStats: createStats() }), - ).resolves.toMatchObject({ http: { enabled: false }, mode: "worker" }); - }); - it("defaults exec.timeoutMs to ten minutes and rejects a non-positive one", async () => { // ADR 0005 §19e's per-command bound. Rejected rather than clamped, like every other // duration here: a caller given a limit it did not write cannot tell which one applied. @@ -1262,10 +1202,15 @@ describe("loadConfig modes (ADR 0005)", () => { expect(config.http.port).toBe(4700); }); - it("refuses a gateway that switches HTTP off, naming the key", async () => { + it("refuses a gateway that switches HTTP off, naming the key, and loads a worker that does", async () => { await expect(load({ mode: "gateway", http: { enabled: false } })).rejects.toThrow( "http.enabled", ); + // HTTP is genuinely optional for a worker. + await expect(load({ mode: "worker", http: { enabled: false } })).resolves.toMatchObject({ + http: { enabled: false }, + mode: "worker", + }); }); it("keeps an explicit gateway http host/port", async () => { @@ -1388,14 +1333,6 @@ describe("loadConfig modes (ADR 0005)", () => { ); }); - it("defaults the gateway exec backstop above the worker's own ten minutes", async () => { - // ADR 0005 §19e: the worker's timeout is authoritative, so the gateway's must not fire - // first -- a gateway that timed out earlier would report a failure for a command still - // running on the machine that owns the device. #118 is what reads it. - const config = await load({ mode: "gateway" }); - expect(config.gateway.execTimeoutMs).toBe(11 * 60_000); - }); - it("rejects a non-positive lease-request timeout", async () => { // P2 (round 2 review): bounds the one forwarded uplink call that used to have none of its // own -- see FleetLeaseCoordinator#withLeaseRequestTimeout. @@ -1404,9 +1341,8 @@ describe("loadConfig modes (ADR 0005)", () => { ); }); - it("defaults the gateway lease-request timeout to five minutes, well under the exec backstop", async () => { + it("defaults the gateway lease-request timeout well under the exec backstop", async () => { const config = await load({ mode: "gateway" }); - expect(config.gateway.leaseRequestTimeoutMs).toBe(5 * 60_000); expect(config.gateway.leaseRequestTimeoutMs).toBeLessThan(config.gateway.execTimeoutMs); }); diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index bc92a10db..63ffbf329 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -37,12 +37,7 @@ import { LeaseLifecycle } from "./lease-lifecycle.js"; import { ManagedDeviceLifecycle } from "./managed-device-lifecycle.js"; import { Registry } from "./registry.js"; import { SerializedDecision } from "./serialized-decision.js"; -import { - type LeaseRequestOptions, - QueueTimeoutError, - RequesterAlreadyLeasedError, - WaitQueue, -} from "./wait-queue.js"; +import { type LeaseRequestOptions, RequesterAlreadyLeasedError, WaitQueue } from "./wait-queue.js"; const gibibyte = 1024 ** 3; const statePath = "/home/agent/.simlock/state.json"; @@ -783,58 +778,6 @@ describe("LeaseAcquisitionCoordinator", () => { expect(harness.coordinator.queueDepth).toBe(0); }); - it("enforces FIFO, rejects no-wait demand, and skips timed-out waiters", async () => { - const harness = await createHarness(); - const first = await harness.coordinator.request(request, { - requesterId: "first", - ownerId: "first", - }); - const timedOut = harness.coordinator.request(request, { - requesterId: "timed-out", - ownerId: "timed-out", - timeoutMs: 10, - }); - const next = harness.coordinator.request(request, { - ownerId: "next", - requesterId: "next", - }); - await flush(); - await expect( - harness.coordinator.request(request, { - noWait: true, - ownerId: "no-wait", - requesterId: "no-wait", - }), - ).rejects.toBeInstanceOf(NoCapacityError); - - harness.clock.advance(10); - await expect(timedOut).rejects.toBeInstanceOf(QueueTimeoutError); - await harness.registry.beginRelease(first.lease.id); - const device = harness.registry.snapshot.devices[0]; - if (device === undefined) throw new Error("expected device"); - await harness.registry.transitionDevice(device.id, "ready", { - event: "device.reclaimed", - payload: { deviceId: device.id, duration: 0, strategy: "wipe" }, - }); - harness.coordinator.kick(); - await expect(next).resolves.toMatchObject({ lease: { ownerId: "next", requesterId: "next" } }); - }); - - it("grants an existing ready device and preserves request progress semantics", async () => { - const harness = await createHarness(); - const ready = await seedReady(harness); - const progress: string[] = []; - - const grant = await harness.coordinator.request(request, { - onProgress: (update) => progress.push(update.stage), - requesterId: "agent", - ownerId: "agent", - }); - - expect(grant.device.id).toBe(ready.id); - expect(progress).toEqual([]); - }); - it("grants a request queued while a new device was booting a second new device once the first is granted, with no release", async () => { const harness = await createHarness({ maxDevices: 2, maxRunning: 2 }); harness.driver.hangMakeReady(); @@ -930,26 +873,6 @@ describe("LeaseAcquisitionCoordinator", () => { }).toEqual({ progress: ["queued"], provisions: 1, queueDepth: 1, queuedEvents: 1 }); }); - it("retries provisioning once and rejects boot failures", async () => { - const harness = await createHarness(); - harness.driver.failOn("provision", 1, new DriverCrashError("temporary")); - const grant = await harness.coordinator.request(request, { - requesterId: "retry", - ownerId: "retry", - }); - expect(grant.device.state).toBe("leased"); - expect(harness.driver.calls.filter((call) => call.operation === "provision")).toHaveLength(2); - - const failing = await createHarness(); - failing.driver.failOn("makeReady", 1, new DriverCrashError("boot failure")); - await expect( - failing.coordinator.request(request, { - ownerId: "boot-failure", - requesterId: "boot-failure", - }), - ).rejects.toMatchObject({ name: "BootTimeoutError" }); - }); - it("boots shutdown inventory and evicts managed demand before provisioning", async () => { const bootHarness = await createHarness(); const ready = await seedReady(bootHarness); diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 7d2d7a74e..5013384e8 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -190,6 +190,14 @@ async function flush(): Promise { } } +/** The value or error `promise` settles with within a flush, or "still pending". */ +async function settledOrPending(promise: Promise): Promise { + return Promise.race([ + promise.catch((error: unknown) => error), + flush().then(() => "still pending"), + ]); +} + describe("LeaseEngine", () => { it("hands the caller back before the purge, keeps the device reclaiming, then re-leases it without another boot", async () => { const clock = new FakeClock(1_000); @@ -994,32 +1002,21 @@ describe("LeaseEngine", () => { ownerId: "agent-1", requesterId: "agent-1", }); - const second = harness.engine.request(request, { - ownerId: "agent-2", - requesterId: "agent-2", - }); - const third = harness.engine.request(request, { - ownerId: "agent-3", - requesterId: "agent-3", - }); - const fourth = harness.engine.request(request, { - ownerId: "agent-4", - requesterId: "agent-4", - }); + // Each waiter records its grant and hands the device straight back, so the queue drains in + // whatever order it serves and the assertion below sees that order rather than hanging. + const granted: string[] = []; + const waiters = ["agent-2", "agent-3", "agent-4"].map((requesterId) => + harness.engine.request(request, { ownerId: requesterId, requesterId }).then(async (grant) => { + granted.push(grant.lease.requesterId); + await harness.engine.release(grant.lease.id, "explicit"); + }), + ); await flush(); await harness.engine.release(first.lease.id, "explicit"); - const secondGrant = await second; - await harness.engine.release(secondGrant.lease.id, "explicit"); - const thirdGrant = await third; - await harness.engine.release(thirdGrant.lease.id, "explicit"); - const fourthGrant = await fourth; - - expect([secondGrant, thirdGrant, fourthGrant].map((grant) => grant.lease.requesterId)).toEqual([ - "agent-2", - "agent-3", - "agent-4", - ]); + await Promise.all(waiters); + + expect(granted).toEqual(["agent-2", "agent-3", "agent-4"]); }); it("wakes exactly the queue head on release and reuses its reclaimed ready device", async () => { @@ -1085,13 +1082,12 @@ describe("LeaseEngine", () => { requesterId: "agent-1", }); - await expect( - harness.engine.request(request, { - noWait: true, - ownerId: "agent-2", - requesterId: "agent-2", - }), - ).rejects.toBeInstanceOf(NoCapacityError); + // A no-wait request that queued instead would leave an await hanging; this names it. + const outcome = await settledOrPending( + harness.engine.request(request, { noWait: true, ownerId: "agent-2", requesterId: "agent-2" }), + ); + + expect(outcome).toBeInstanceOf(NoCapacityError); }); it("rejects a timed-out queue entry and skips it on a later release", async () => { @@ -1113,12 +1109,14 @@ describe("LeaseEngine", () => { }); await flush(); + // Each outcome settles against a flush rather than an await, so a waiter left pending + // fails the assertion that names it instead of hanging the test. harness.clock.advance(10); - await expect(timedOut).rejects.toBeInstanceOf(QueueTimeoutError); + expect(await settledOrPending(timedOut)).toBeInstanceOf(QueueTimeoutError); expect(progress).toEqual(["queued"]); await harness.engine.release(first.lease.id, "explicit"); - await expect(next).resolves.toMatchObject({ + expect(await settledOrPending(next)).toMatchObject({ lease: { ownerId: "agent-3", requesterId: "agent-3" }, }); }); @@ -1142,20 +1140,6 @@ describe("LeaseEngine", () => { }); }); - it("keeps a renewed lease past the deadline it was granted with", async () => { - const harness = await createHarness({ lease: { defaultTtlMs: 20 } }); - const granted = await harness.engine.request(request, { - requesterId: "agent-3", - ownerId: "agent-3", - }); - const renewed = await harness.engine.renew(granted.lease.id, 30); - harness.clock.advance(20); - await flush(); - - expect(renewed.ttlDeadline).toBe(1_030); - expect(harness.registry.snapshot.leases).toHaveLength(1); - }); - it("renews via the engine, re-arming the expiry timer at the new deadline", async () => { const harness = await createHarness({ lease: { defaultTtlMs: 10 } }); const granted = await harness.engine.request(request, { @@ -1224,12 +1208,12 @@ describe("LeaseEngine", () => { driver.failOn("provision", 1, new DriverCrashError("simulator exited")); const harness = await createHarness({ driver }); - const grant = await harness.engine.request(request, { - ownerId: "agent-1", - requesterId: "agent-1", - }); + // A request that never retried would sit pending; settling against a flush names that. + const grant = await settledOrPending( + harness.engine.request(request, { ownerId: "agent-1", requesterId: "agent-1" }), + ); - expect(grant.device.state).toBe("leased"); + expect(grant).toMatchObject({ device: { state: "leased" } }); expect(driver.calls.filter((call) => call.operation === "provision")).toHaveLength(2); expect( harness.registry.snapshot.devices.filter((device) => device.state !== "deleted"), diff --git a/src/core/lease-release-coordinator.test.ts b/src/core/lease-release-coordinator.test.ts index d652620d0..00fbfbe69 100644 --- a/src/core/lease-release-coordinator.test.ts +++ b/src/core/lease-release-coordinator.test.ts @@ -74,7 +74,6 @@ async function createHarness() { async function grant( harness: Awaited>, - ttlMs?: number, ): Promise<{ readonly device: DeviceRecord; readonly lease: LeaseRecord }> { const device = await harness.registry.registerDevice({ driverData: {}, @@ -90,7 +89,6 @@ async function grant( deviceId: device.id, requesterId: `agent_${device.id}`, ownerId: `agent_${device.id}`, - ...(ttlMs === undefined ? {} : { ttlMs }), }); return result; } @@ -136,27 +134,6 @@ describe("LeaseReleaseCoordinator", () => { ); }); - it("delegates renewal to the lifecycle, applying the TTL the caller named", async () => { - const harness = await createHarness(); - const granted = await grant(harness); - await expect(harness.coordinator.renew(granted.lease.id, 30)).resolves.toMatchObject({ - ttlDeadline: 1_030, - ttlMs: 30, - }); - }); - - it("delegates a body-less renewal, which re-applies the lease's own stored width", async () => { - const harness = await createHarness(); - const granted = await grant(harness, 50); - - harness.clock.advance(3); - await expect(harness.coordinator.renew(granted.lease.id)).resolves.toMatchObject({ - ttlDeadline: 1_053, - ttlMs: 50, - }); - expect(harness.registry.snapshot.leases).toMatchObject([{ ttlDeadline: 1_053 }]); - }); - it("ignores an expiry delivery for a deadline replaced by renewal", async () => { const harness = await createHarness(); const granted = await grant(harness); diff --git a/src/core/startup-converger.test.ts b/src/core/startup-converger.test.ts index 7a55424a8..e4070e277 100644 --- a/src/core/startup-converger.test.ts +++ b/src/core/startup-converger.test.ts @@ -347,19 +347,4 @@ describe("StartupConverger", () => { ]); expect(harness.devices.find((item) => item.id === reusableShutdown.id)?.state).toBe("shutdown"); }); - - it("restores timers before quarantine and interrupted-reclaim recovery", async () => { - const reclaiming = device("reclaiming", "ios", "reclaiming", 1); - const harness = createHarness([reclaiming], [], { android: 1, global: 3, ios: 3 }); - - await harness.converger.converge(); - - expect(harness.order.indexOf("timers")).toBe(0); - expect(harness.order.indexOf("quarantine-restore")).toBeGreaterThan( - harness.order.indexOf("timers"), - ); - expect(harness.order.indexOf("recover:reclaiming")).toBeGreaterThan( - harness.order.indexOf("quarantine-restore"), - ); - }); }); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index cb8fcf9b9..e4ff24822 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -332,9 +332,9 @@ function session(overrides: Partial = {}): DispatchSession { describe("Dispatcher: parsing", () => { it("rejects a malformed input with BAD_REQUEST before the handler runs", async () => { const { dispatcher } = await buildDispatcher(); - await expect( - dispatcher.dispatch("lease.request", { platform: "ios" }, session()), - ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + const rejection = dispatcher.dispatch("lease.request", { platform: "ios" }, session()); + await expect(rejection).rejects.toBeInstanceOf(DispatchError); + await expect(rejection).rejects.toMatchObject({ code: "BAD_REQUEST" }); }); it.each([ @@ -355,11 +355,11 @@ describe("Dispatcher: parsing", () => { }, ); - it("rejects a ttlMs above lease.maxTtlMs on a request, rather than clamping it", async () => { + it("rejects a ttlMs above lease.maxTtlMs on a request, rather than clamping it, and creates no lease", async () => { // ADR 0004 §4: the cap is enforced here rather than in the contract schema, because // `lease.maxTtlMs` is a daemon config value the contract module cannot see -- and every // transport reaches leases through this one dispatcher, so HTTP inherits the same answer. - const { dispatcher } = await buildDispatcher({ lease: { maxTtlMs: 1_000 } }); + const { dispatcher, registry } = await buildDispatcher({ lease: { maxTtlMs: 1_000 } }); await expect( dispatcher.dispatch( "lease.request", @@ -367,13 +367,23 @@ describe("Dispatcher: parsing", () => { session(), ), ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + expect(registry.snapshot.leases).toEqual([]); }); - it("rejects a ttlMs above lease.maxTtlMs on a renew too", async () => { - const { dispatcher } = await buildDispatcher({ lease: { maxTtlMs: 1_000 } }); + it("rejects a ttlMs above lease.maxTtlMs on a renew too, leaving the lease's deadline as it was", async () => { + const { clock, dispatcher, registry } = await buildDispatcher({ lease: { maxTtlMs: 1_000 } }); + const grant = await dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", platform: "ios", ttlMs: 1_000 }, + session(), + ); + // Time has passed, so a renew that went through would have moved the deadline. + clock.advance(10); + await expect( - dispatcher.dispatch("lease.renew", { leaseId: "lse_1", ttlMs: 1_001 }, session()), + dispatcher.dispatch("lease.renew", { leaseId: grant.lease.id, ttlMs: 1_001 }, session()), ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + expect(registry.snapshot.leases).toMatchObject([{ ttlDeadline: grant.lease.ttlDeadline }]); }); it("accepts a ttlMs at the cap on a request (ADR 0004 §4)", async () => { @@ -1291,17 +1301,6 @@ describe("Dispatcher: #parseOutput", () => { }); describe("Dispatcher: error codes", () => { - it("wraps a malformed request as DispatchError with the BAD_REQUEST code", async () => { - const { dispatcher } = await buildDispatcher(); - try { - await dispatcher.dispatch("lease.request", {}, session()); - expect.unreachable(); - } catch (error) { - expect(error).toBeInstanceOf(DispatchError); - expect((error as DispatchError).code).toBe("BAD_REQUEST"); - } - }); - it("lets a domain error (e.g. RUNTIME_MISSING) propagate untouched from the handler", async () => { const { dispatcher } = await buildDispatcher(); await expect( diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 3b004dbcd..1713ed35c 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -11,14 +11,12 @@ import { type Config, type DriverRejection, FakeDriver, - InsufficientDiskSpaceError, LeaseEngine, PassthroughRefusedError, Registry, RuntimeMissingError, } from "../core/index.js"; import { PROTOCOL_VERSION_RANGE, type ProtocolRange } from "../contract/index.js"; -import { AndroidLicenseNotAcceptedError } from "../drivers/android/index.js"; import { createConnectionPair, CryptoTokenSecrets, @@ -162,8 +160,8 @@ describe("DaemonServer", () => { // with no overlap against the daemon's range is `PROTOCOL_VERSION_UNSUPPORTED`, carrying // both ranges and the daemon version -- there is no more exact-match // `PROTOCOL_VERSION_MISMATCH` on this daemon (a real protocol-2 daemon out in the world - // still answers with the old code; see `contract/protocol.test.ts`'s - // `mapLegacyProtocolMismatch` for how a client maps that). + // still answers with the old code; see `simlock-client/client.test.ts`'s legacy-daemon test + // for how a client maps that). const wrongVersion = await createClient(harness.socketPath); await expect( wrongVersion.request("hello", { @@ -1723,40 +1721,6 @@ describe("DaemonServer lease liveness (ADR 0004)", () => { await client.close(); }); - it("rejects a ttlMs above lease.maxTtlMs on a request and on a renew, rather than clamping", async () => { - const harness = await createHarness({ lease: { defaultTtlMs: 40, maxTtlMs: 100 } }); - const client = await createClient(harness.socketPath); - await hello(client); - - await expect( - client.request("lease.request", { - requesterId: "agent-1", - model: "iPhone 16", - osVersion: "26.5", - platform: "ios", - ttlMs: 101, - }), - ).resolves.toMatchObject({ error: { code: "BAD_REQUEST" }, ok: false }); - expect(harness.registry.snapshot.leases).toEqual([]); - - const grant = await client.request("lease.request", { - requesterId: "agent-1", - model: "iPhone 16", - osVersion: "26.5", - platform: "ios", - ttlMs: 100, - }); - const leaseId = leaseIdOf(grant); - expect((grant.payload as { lease: { ttlMs: number } }).lease.ttlMs).toBe(100); - - await expect(client.request("lease.renew", { leaseId, ttlMs: 101 })).resolves.toMatchObject({ - error: { code: "BAD_REQUEST" }, - ok: false, - }); - expect(harness.registry.snapshot.leases).toMatchObject([{ ttlDeadline: 1_100 }]); - await client.close(); - }); - it("keeps a lease across a daemon restart and restores its timer from the persisted deadline", async () => { const leaseOverrides = { defaultTtlMs: 40 }; const first = await createHarness({ lease: leaseOverrides }); @@ -2348,52 +2312,6 @@ describe("DaemonServer lease request mode", () => { }); }); -describe("DaemonServer error code mapping", () => { - it("maps InsufficientDiskSpaceError to INSUFFICIENT_DISK_SPACE", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - driver.failOn("resolveSpec", 1, new InsufficientDiskSpaceError("ios", 8 * 1024 ** 3, 0)); - const harness = await createHarness({ clock, downloads: { policy: "always" }, driver }); - const client = await createClient(harness.socketPath); - await hello(client); - - const response = await client.request("lease.request", { - requesterId: "agent-1", - model: "iPhone 16", - osVersion: "26.5", - platform: "ios", - }); - - expect(response.ok).toBe(false); - expect(response.error).toMatchObject({ code: "INSUFFICIENT_DISK_SPACE" }); - await client.close(); - }); - - it("maps LicenseNotAcceptedError to LICENSE_NOT_ACCEPTED", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "android" }); - driver.failOn( - "resolveSpec", - 1, - new AndroidLicenseNotAcceptedError("system-images;android-35;google_apis;arm64-v8a"), - ); - const harness = await createHarness({ clock, downloads: { policy: "always" }, driver }); - const client = await createClient(harness.socketPath); - await hello(client); - - const response = await client.request("lease.request", { - requesterId: "agent-1", - model: "Pixel 8", - osVersion: "35", - platform: "android", - }); - - expect(response.ok).toBe(false); - expect(response.error).toMatchObject({ code: "LICENSE_NOT_ACCEPTED" }); - await client.close(); - }); -}); - describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { it("rejects an admin-only operation from an agent session with FORBIDDEN, and reports the resolved role at hello", async () => { const harness = await createHarness({ resolveRole: { resolve: () => "agent" } }); diff --git a/src/drivers/android/device-profile-source.test.ts b/src/drivers/android/device-profile-source.test.ts index e6095c404..c678cd8f0 100644 --- a/src/drivers/android/device-profile-source.test.ts +++ b/src/drivers/android/device-profile-source.test.ts @@ -281,12 +281,8 @@ describe("parseDevicesXml", () => { expect(parseDevicesXml(xml)).toEqual([]); }); - it("rejects a device name containing an embedded line break or NUL byte", () => { - const withNewline = - '' + - "Evil\nPhone"; - expect(() => parseDevicesXml(withNewline)).toThrow(); - + // An embedded line break is covered through UserDeviceProfileSource's diagnostic test above. + it("rejects a device name containing a NUL byte", () => { const withNul = '' + "Evil\u0000Phone"; @@ -308,9 +304,10 @@ describe("parseDevicesXml", () => { expect(parseDevicesXml(" \n ")).toEqual([]); }); - it("throws for content with no recognizable root", () => { + // Content that is not XML at all is covered through UserDeviceProfileSource's malformed-file + // diagnostic test above. + it("throws for well-formed XML with no recognizable root", () => { expect(() => parseDevicesXml("")).toThrow(); - expect(() => parseDevicesXml("this is not xml")).toThrow(); }); }); diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 13a1c678d..120baa00b 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -1190,7 +1190,9 @@ describe("AndroidDriver", () => { ]); const driver = await createDriver(filesystem, runner); - await expect(driver.listCatalog()).resolves.toEqual({ + // Strict: with no custom device profile there is no `customModels` key at all, not one + // present as undefined. + await expect(driver.listCatalog()).resolves.toStrictEqual({ defaultRuntime: "35", images: [ { abi: "x86_64", runtime: "34", tag: "google_apis" }, @@ -1369,18 +1371,6 @@ describe("AndroidDriver", () => { expect(catalog.customModels).toEqual(["My Tablet"]); }); - it("has no customModels field when there is no custom profile", async () => { - const runner = new ScriptedProcessRunner([ - processResult(binaries.avdmanager, ["list", "device"], twoPixelDevices), - ]); - const driver = await createDriver(await androidFilesystem(), runner); - - const catalog = await driver.listCatalog(); - - expect(catalog.models).toEqual(["Pixel 8", "Pixel 9"]); - expect(catalog).not.toHaveProperty("customModels"); - }); - it("lists the built-in models and no customModels field when devices.xml cannot be parsed", async () => { const filesystem = await androidFilesystem(); await filesystem.mkdirp(`${home}/.android`); diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 116515f6a..0878d8309 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -1026,7 +1026,9 @@ describe("IosSimctlDriver", () => { it("lists resolvable models and installed runtimes, defaulting to the newest", async () => { const driver = await createDriver(scriptedListRunner()); - await expect(driver.listCatalog()).resolves.toEqual({ + // Strict: a catalog key an iOS driver does not fill (`images`, `customModels`) must be + // absent, not present as undefined. + await expect(driver.listCatalog()).resolves.toStrictEqual({ defaultRuntime: "26.5", modelAliases: {}, modelRuntimes: { @@ -1039,25 +1041,6 @@ describe("IosSimctlDriver", () => { }); }); - it("reports no other names and no images", async () => { - const driver = await createDriver(scriptedListRunner()); - - const catalog = await driver.listCatalog(); - - expect(catalog.models.length).toBeGreaterThan(0); - expect(catalog.modelAliases).toEqual({}); - expect(catalog).not.toHaveProperty("images"); - }); - - it("has no customModels field", async () => { - const driver = await createDriver(scriptedListRunner()); - - const catalog = await driver.listCatalog(); - - expect(catalog.models.length).toBeGreaterThan(0); - expect(catalog).not.toHaveProperty("customModels"); - }); - describe("model and runtime pairing", () => { function pairingRunner(calls = 1): ScriptedProcessRunner { return new ScriptedProcessRunner( @@ -1159,18 +1142,9 @@ describe("IosSimctlDriver", () => { driver.resolveSpec({ model: "iphone 16", osVersion: "26.0", platform: "ios" }), ).resolves.toEqual({ model: "iPhone 16", osVersion: "26.0", platform: "ios" }); }); - - it("still shells out to simctl exactly once per listCatalog call", async () => { - const runner = pairingRunner(); - const driver = await createDriver(runner); - - await driver.listCatalog(); - - expect(runner.calls).toEqual([{ ...listInvocation, options: { timeoutMs: 30_000 } }]); - }); }); - it("shells out to simctl exactly once per listCatalog call, reusing the catalog parse", async () => { + it("shells out to simctl exactly once per listCatalog call", async () => { const runner = scriptedListRunner(); const driver = await createDriver(runner); @@ -1704,6 +1678,8 @@ describe("IosSimctlDriver", () => { { match: { command: "xcrun", args: simctlArgs("bootstatus", driverData.udid, "-b") } }, ]); + // `driverData` has no `slimSignature`/`slimMarkToken`, exactly what a registry written + // before slim mode shipped holds, so this also proves such data still loads. await expect( (await createDriver(runner)).makeReady( { @@ -2746,35 +2722,6 @@ describe("IosSimctlDriver", () => { expect(onSlimSkipped).not.toHaveBeenCalled(); }); - it("loads driverData that predates the slim fields without throwing (backwards compatibility)", async () => { - const runner = new ScriptedProcessRunner([ - { match: { command: "xcrun", args: simctlArgs("boot", driverData.udid) } }, - { match: { command: "xcrun", args: simctlArgs("bootstatus", driverData.udid, "-b") } }, - ]); - - // `driverData` has no `full`/`slimSignature`/`slimMarkToken` -- exactly what a `state.json` - // registry written before slim mode shipped looks like. Slim is off here, so this is just - // proving `iosDriverData` doesn't choke on the missing fields (a slim-on equivalent is - // covered by "boots, applies the disable list..." above, which starts from data with no - // prior slim markers either). - await expect( - (await createDriver(runner)).makeReady( - { - address: driverData.udid, - deviceId: driverData.udid, - driverData, - }, - prepareFull, - ), - ).resolves.toEqual({ - address: driverData.udid, - deviceId: driverData.udid, - driverData, - // Slim mode is off, so this boot slimmed nothing: the device is full. - mode: "full", - }); - }); - it("times out the post-slim bootstatus using slim.bootTimeoutMs, not the default 120s", async () => { const filesystem = new MemoryFilesystem(); await plantManagedDevice(filesystem); diff --git a/src/drivers/ios/slim-labels.test.ts b/src/drivers/ios/slim-labels.test.ts index fac323e3c..052ae1257 100644 --- a/src/drivers/ios/slim-labels.test.ts +++ b/src/drivers/ios/slim-labels.test.ts @@ -64,21 +64,9 @@ describe("labelsFor", () => { it("returns an empty array for no categories", () => { expect(labelsFor([])).toEqual([]); }); - - it("is deterministic across calls", () => { - const first = labelsFor(SLIM_CATEGORIES); - const second = labelsFor(SLIM_CATEGORIES); - expect(first).toEqual(second); - }); }); describe("slimSignature", () => { - it("is stable for the same input", () => { - const a = slimSignature(SLIM_CATEGORIES); - const b = slimSignature(SLIM_CATEGORIES); - expect(a).toBe(b); - }); - it("is stable regardless of input category order", () => { const forward = slimSignature(SLIM_CATEGORIES); const reversed = slimSignature([...SLIM_CATEGORIES].reverse()); @@ -102,8 +90,4 @@ describe("slimSignature", () => { const after = slimSignature([mutated]); expect(before).not.toBe(after); }); - - it("returns the same signature for an empty category list regardless of call site", () => { - expect(slimSignature([])).toBe(slimSignature([])); - }); }); diff --git a/src/gateway/lease-index.test.ts b/src/gateway/lease-index.test.ts index 13a2bcf21..e155ddbb6 100644 --- a/src/gateway/lease-index.test.ts +++ b/src/gateway/lease-index.test.ts @@ -302,10 +302,4 @@ describe("FleetLeaseIndex", () => { }); }); }); - - describe("requesterPrefix", () => { - it("exposes exactly the prefix it was constructed with", () => { - expect(new FleetLeaseIndex(PREFIX).requesterPrefix).toBe(PREFIX); - }); - }); }); diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 406538ef1..f16d09823 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -1,16 +1,10 @@ import { describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; -import { - InsufficientDiskSpaceError, - LicenseNotAcceptedError, - NoCapacityError, - RequesterAlreadyLeasedError, - UnknownLeaseError, -} from "../core/index.js"; +import { NoCapacityError, RequesterAlreadyLeasedError, UnknownLeaseError } from "../core/index.js"; import { runDispatch } from "../daemon/dispatch.js"; -import { DispatchError, DoctorUnavailableError } from "../daemon/dispatcher.js"; -import { describeLeaseRequestFailure, StartupFailedError } from "../daemon/error-code.js"; +import { DispatchError } from "../daemon/dispatcher.js"; +import { describeLeaseRequestFailure } from "../daemon/error-code.js"; import { OwnerRoutedFactBus } from "../daemon/owner-routed-facts.js"; import { LeaseRequestBook } from "../core/lease-request-book.js"; import { Registry } from "../core/registry.js"; @@ -517,60 +511,6 @@ describe("POST /v1/lease-requests", () => { expect(response.headers.get("Retry-After")).toBeTruthy(); }); - // Review finding B5: HTTP collapsed these four thrown-from-`lease.request` codes to a bare - // 500 INTERNAL while the socket transport reported the real code and `ERROR_TABLE`'s own - // status -- because `mapError` (this file's target) kept its own hand-written `instanceof` - // chain instead of reading the one shared table `errorCode` (in `daemon/server.ts`) already - // used. Each of these now goes through `classifyError` + `ERROR_TABLE`, the same as the - // socket transport. - it("maps a fast InsufficientDiskSpaceError to 422 INSUFFICIENT_DISK_SPACE, not 500 INTERNAL", async () => { - const { app, dispatcher } = buildHarness(); - const responsePromise = postLeaseRequest(app, defaultBody); - const call = await waitForDispatch(dispatcher, "lease.request"); - call.reject(new InsufficientDiskSpaceError("ios", 8 * 1024 ** 3, 0)); - const response = await responsePromise; - - expect(response.status).toBe(422); - const body = (await response.json()) as { error: { code: string } }; - expect(body.error.code).toBe("INSUFFICIENT_DISK_SPACE"); - }); - - it("maps a fast LicenseNotAcceptedError to 422 LICENSE_NOT_ACCEPTED, not 500 INTERNAL", async () => { - const { app, dispatcher } = buildHarness(); - const responsePromise = postLeaseRequest(app, defaultBody); - const call = await waitForDispatch(dispatcher, "lease.request"); - call.reject(new LicenseNotAcceptedError("android", "system-images;android-35;google_apis")); - const response = await responsePromise; - - expect(response.status).toBe(422); - const body = (await response.json()) as { error: { code: string } }; - expect(body.error.code).toBe("LICENSE_NOT_ACCEPTED"); - }); - - it("maps a fast StartupFailedError to 503 DAEMON_STARTUP_FAILED, not 500 INTERNAL", async () => { - const { app, dispatcher } = buildHarness(); - const responsePromise = postLeaseRequest(app, defaultBody); - const call = await waitForDispatch(dispatcher, "lease.request"); - call.reject(new StartupFailedError()); - const response = await responsePromise; - - expect(response.status).toBe(503); - const body = (await response.json()) as { error: { code: string } }; - expect(body.error.code).toBe("DAEMON_STARTUP_FAILED"); - }); - - it("maps a fast DoctorUnavailableError to 503 DOCTOR_UNAVAILABLE, not 500 INTERNAL", async () => { - const { app, dispatcher } = buildHarness(); - const responsePromise = postLeaseRequest(app, defaultBody); - const call = await waitForDispatch(dispatcher, "lease.request"); - call.reject(new DoctorUnavailableError()); - const response = await responsePromise; - - expect(response.status).toBe(503); - const body = (await response.json()) as { error: { code: string } }; - expect(body.error.code).toBe("DOCTOR_UNAVAILABLE"); - }); - it("replays an identical Idempotency-Key without a second dispatch call", async () => { const { app, dispatcher } = buildHarness(); const { id: firstId } = await createLeaseRequest(app, dispatcher, defaultBody, { diff --git a/src/mcp/session.test.ts b/src/mcp/session.test.ts index 69c1b4e02..d132fc3e2 100644 --- a/src/mcp/session.test.ts +++ b/src/mcp/session.test.ts @@ -4,7 +4,7 @@ import { SimlockError } from "../client/index.js"; import { RELEASE_TIMEOUT_MS } from "../lease-policy/index.js"; import { FakeClock } from "../ports/index.js"; import { FakeSimlockClient, sampleGrant } from "./test-support.js"; -import { McpSession, toMcpErrorResult } from "./session.js"; +import { McpSession } from "./session.js"; /** Lets an awaited renewal settle; the fake clock never moves on its own. */ async function flushMicrotasks(times = 10): Promise { @@ -1149,21 +1149,6 @@ describe("McpSession", () => { }); }); -describe("toMcpErrorResult", () => { - it("maps a SimlockError to its code and message", () => { - expect( - toMcpErrorResult(new SimlockError("NO_CAPACITY", "domain", "No matching devices", {})), - ).toEqual({ code: "NO_CAPACITY", message: "No matching devices" }); - }); - - it("sanitizes any other error to a generic INTERNAL result", () => { - expect(toMcpErrorResult(new Error("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/private/secret-stack-path"))).toEqual({ - code: "INTERNAL", - message: "Simlock could not complete the request", - }); - }); -}); - /** * The double itself: MCP's tests are only worth what it is faithful to, and the one thing it * has to get right is that a closed connection is dead (ADR 0003 §10) -- a fake that kept diff --git a/src/ports/daemon-launcher.test.ts b/src/ports/daemon-launcher.test.ts index dc377de7c..9e69daac4 100644 --- a/src/ports/daemon-launcher.test.ts +++ b/src/ports/daemon-launcher.test.ts @@ -3,19 +3,7 @@ import { mkdtemp, readFile, readdir, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { FakeDaemonLauncher, NodeDaemonLauncher } from "./daemon-launcher.js"; - -describe("FakeDaemonLauncher", () => { - it("records launches and delegates to its deterministic callback", async () => { - let started = false; - const launcher = new FakeDaemonLauncher(() => { - started = true; - }); - await launcher.launch(); - expect(launcher.launches).toBe(1); - expect(started).toBe(true); - }); -}); +import { NodeDaemonLauncher } from "./daemon-launcher.js"; describe("NodeDaemonLauncher", () => { it("rejects asynchronous spawn failures", async () => { diff --git a/src/ports/filesystem.test.ts b/src/ports/filesystem.test.ts index 2f9732681..dbf41f031 100644 --- a/src/ports/filesystem.test.ts +++ b/src/ports/filesystem.test.ts @@ -146,6 +146,26 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link }) await expect(filesystem.exists(`${temporaryDirectory}/dangling`)).resolves.toBe(false); }); + it("reports a symlink as a symlink, and resolves it to what it points at", async () => { + const filesystem = create(); + await filesystem.mkdirp(`${temporaryDirectory}/devices/real`); + await link( + filesystem, + `${temporaryDirectory}/devices/ios`, + `${temporaryDirectory}/devices/real`, + ); + + await expect(filesystem.lstat(`${temporaryDirectory}/devices/ios`)).resolves.toMatchObject({ + kind: "symlink", + }); + await expect(filesystem.stat(`${temporaryDirectory}/devices/ios`)).resolves.toMatchObject({ + kind: "directory", + }); + await expect(filesystem.realpath(`${temporaryDirectory}/devices/ios`)).resolves.toBe( + await filesystem.realpath(`${temporaryDirectory}/devices/real`), + ); + }); + it("refuses to answer for a path that runs through a file", async () => { // A mistyped device root -- `/notes.txt/ios` -- is a different problem from one // that is simply not there yet, and callers can only tell them apart by the errno. @@ -237,22 +257,6 @@ describe.each(implementations)("Filesystem ownership contract: $name", ({ create }); describe("MemoryFilesystem", () => { - it("reports its configured free disk space", async () => { - const filesystem = new MemoryFilesystem(42_000); - - await expect(filesystem.diskFree("/")).resolves.toBe(42_000); - }); - - it("reports a defined symlink as a symlink rather than as what it points at", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("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/devices/real"); - filesystem.defineSymlink("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/devices/ios", "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/devices/real"); - - await expect(filesystem.lstat("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/devices/ios")).resolves.toMatchObject({ kind: "symlink" }); - await expect(filesystem.stat("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/devices/ios")).resolves.toMatchObject({ kind: "directory" }); - await expect(filesystem.realpath("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/devices/ios")).resolves.toBe("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/devices/real"); - }); - it("resolves symlinked path components, not just the last one", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/private/devices/ios"); @@ -303,18 +307,3 @@ describe("MemoryFilesystem", () => { await expect(filesystem.lstat("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/devices/ios")).resolves.toMatchObject({ mode: 0o700 }); }); }); - -describe("NodeFilesystem", () => { - it("reports a symlink without following it", async () => { - const filesystem = new NodeFilesystem(); - await filesystem.mkdirp(`${temporaryDirectory}/devices/real`); - await symlink(`${temporaryDirectory}/devices/real`, `${temporaryDirectory}/devices/ios`); - - await expect(filesystem.lstat(`${temporaryDirectory}/devices/ios`)).resolves.toMatchObject({ - kind: "symlink", - }); - await expect(filesystem.realpath(`${temporaryDirectory}/devices/ios`)).resolves.toBe( - await filesystem.realpath(`${temporaryDirectory}/devices/real`), - ); - }); -}); diff --git a/src/ports/ipc.test.ts b/src/ports/ipc.test.ts index 167f46d64..935a96195 100644 --- a/src/ports/ipc.test.ts +++ b/src/ports/ipc.test.ts @@ -1,72 +1,73 @@ -import { describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { MemoryIpcTransport, NodeIpcTransport } from "./ipc.js"; -describe("MemoryIpcTransport", () => { - it("delivers bidirectional data and closure", async () => { - const ipc = new MemoryIpcTransport(); - let serverConnection: Awaited> | undefined; - await ipc.listen("/daemon.sock", (connection) => { - serverConnection = connection; - }); - const client = await ipc.connect("/daemon.sock"); - const received: string[] = []; - serverConnection?.onData((chunk) => received.push(chunk)); - await client.write("hello"); - expect(received).toEqual(["hello"]); - await client.close(); - expect(serverConnection?.closed).toBe(true); +const implementations = [ + { name: "memory transport", create: () => new MemoryIpcTransport() }, + { name: "node transport", create: () => new NodeIpcTransport() }, +]; + +describe.each(implementations)("IpcTransport contract: $name", ({ create }) => { + let directory: string; + let endpoint: string; + + beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), "simlock-ipc-")); + endpoint = join(directory, "daemon.sock"); }); - it("normalizes missing endpoints and duplicate listeners", async () => { - const ipc = new MemoryIpcTransport(); - await expect(ipc.connect("/missing")).rejects.toMatchObject({ - code: "endpoint-not-found", - }); - await ipc.listen("/daemon.sock", () => undefined); - await expect(ipc.listen("/daemon.sock", () => undefined)).rejects.toMatchObject({ - code: "address-in-use", + afterEach(async () => { + await rm(directory, { force: true, recursive: true }); + }); + + it("delivers what a client writes to the server, and the client's close", async () => { + const ipc = create(); + let server: Awaited> | undefined; + const listener = await ipc.listen(endpoint, (connection) => { + server = connection; }); + try { + const client = await ipc.connect(endpoint); + await expect.poll(() => server).toBeDefined(); + const received: string[] = []; + server?.onData((chunk) => received.push(chunk)); + + await client.write("hello"); + await expect.poll(() => received).toEqual(["hello"]); + + await client.close(); + await expect.poll(() => server?.closed).toBe(true); + } finally { + await listener.close(); + } }); - it("prevents new connections after its listener closes", async () => { - const ipc = new MemoryIpcTransport(); - const listener = await ipc.listen("/daemon.sock", () => undefined); - await listener.close(); - await expect(ipc.connect("/daemon.sock")).rejects.toMatchObject({ + it("reports an endpoint nothing listens on as endpoint-not-found", async () => { + await expect(create().connect(endpoint)).rejects.toMatchObject({ code: "endpoint-not-found", }); }); -}); -describe("NodeIpcTransport", () => { - it("connects, exchanges data, closes, and normalizes setup failures", async () => { - const directory = await mkdtemp(join(tmpdir(), "simlock-ipc-")); - const endpoint = join(directory, "daemon.sock"); - const ipc = new NodeIpcTransport(); + it("refuses a second listener on one endpoint as address-in-use", async () => { + const ipc = create(); + const listener = await ipc.listen(endpoint, () => undefined); try { - await expect(ipc.connect(endpoint)).rejects.toMatchObject({ code: "endpoint-not-found" }); - let server: Awaited> | undefined; - const listener = await ipc.listen(endpoint, (connection) => { - server = connection; - }); await expect(ipc.listen(endpoint, () => undefined)).rejects.toMatchObject({ code: "address-in-use", }); - const client = await ipc.connect(endpoint); - await expect.poll(() => server).toBeDefined(); - const received: string[] = []; - server?.onData((chunk) => received.push(chunk)); - await client.write("ping"); - await expect.poll(() => received).toEqual(["ping"]); - await client.close(); - await listener.close(); - await expect(ipc.connect(endpoint)).rejects.toMatchObject({ code: "endpoint-not-found" }); } finally { - await rm(directory, { force: true, recursive: true }); + await listener.close(); } }); + + it("refuses new connections once its listener closes", async () => { + const ipc = create(); + const listener = await ipc.listen(endpoint, () => undefined); + await listener.close(); + + await expect(ipc.connect(endpoint)).rejects.toMatchObject({ code: "endpoint-not-found" }); + }); }); diff --git a/src/ports/logger.test.ts b/src/ports/logger.test.ts index 1bcf78934..1717dfdcc 100644 --- a/src/ports/logger.test.ts +++ b/src/ports/logger.test.ts @@ -102,7 +102,7 @@ describe("JsonLinesLogger", () => { }); describe("NoopLogger", () => { - it("discards every record and returns itself for child()", () => { + it("accepts a record at every level without throwing, and returns itself for child()", () => { const logger = new NoopLogger(); expect(() => { logger.debug("x"); diff --git a/src/ports/process-supervisor.test.ts b/src/ports/process-supervisor.test.ts index c43331605..92162042e 100644 --- a/src/ports/process-supervisor.test.ts +++ b/src/ports/process-supervisor.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { FakeProcessSupervisor, NodeProcessRunner, NodeProcessSupervisor } from "./index.js"; +import { NodeProcessRunner, NodeProcessSupervisor } from "./index.js"; /** * Runs a process to completion and hands back the pid it no longer occupies. `wait()` can @@ -61,33 +61,3 @@ describe("NodeProcessSupervisor", () => { expect(() => supervisor.signal(pid, "SIGTERM")).not.toThrow(); }); }); - -describe("FakeProcessSupervisor", () => { - it("answers with the liveness a test gave it", () => { - const supervisor = new FakeProcessSupervisor([17]); - - expect(supervisor.isAlive(17)).toBe(true); - expect(supervisor.isAlive(18)).toBe(false); - - supervisor.markDead(17); - supervisor.markAlive(18); - - expect(supervisor.isAlive(17)).toBe(false); - expect(supervisor.isAlive(18)).toBe(true); - }); - - it("records signals without deciding whether they killed anything", () => { - const supervisor = new FakeProcessSupervisor([17]); - - supervisor.signal(17, "SIGTERM"); - supervisor.signal(17, "SIGKILL"); - - expect(supervisor.signals).toEqual([ - { pid: 17, signal: "SIGTERM" }, - { pid: 17, signal: "SIGKILL" }, - ]); - // Whether a process dies on SIGTERM, ignores it, or dies only on SIGKILL is what the - // code under test has to cope with, so the test says which happened -- not the double. - expect(supervisor.isAlive(17)).toBe(true); - }); -}); diff --git a/src/ports/tcp-probe.test.ts b/src/ports/tcp-probe.test.ts index 916a18468..3f4af5453 100644 --- a/src/ports/tcp-probe.test.ts +++ b/src/ports/tcp-probe.test.ts @@ -2,7 +2,7 @@ import { createServer, type Server, type Socket } from "node:net"; import { afterEach, describe, expect, it } from "vitest"; -import { FakeTcpProbe, NodeTcpProbe } from "./index.js"; +import { NodeTcpProbe } from "./index.js"; let server: Server | undefined; const accepted = new Set(); @@ -97,26 +97,3 @@ describe("NodeTcpProbe.send", () => { await expect(new NodeTcpProbe().send(port, "ping", 50)).rejects.toThrow(); }); }); - -describe("FakeTcpProbe", () => { - it("answers with the ports a test declared, as they come and go", async () => { - const probe = new FakeTcpProbe([5038]); - - await expect(probe.isListening(5038)).resolves.toBe(true); - await expect(probe.isListening(5039)).resolves.toBe(false); - - probe.stopListening(5038); - probe.startListening(5039); - - await expect(probe.isListening(5038)).resolves.toBe(false); - await expect(probe.isListening(5039)).resolves.toBe(true); - }); - - it("records what was sent and answers with what the test scripted", async () => { - const probe = new FakeTcpProbe(); - probe.replyWith("OKAY"); - - await expect(probe.send(5038, "0012host:emulator:5587")).resolves.toBe("OKAY"); - expect(probe.sends).toEqual([{ payload: "0012host:emulator:5587", port: 5038 }]); - }); -}); diff --git a/src/ports/tcp-probe.ts b/src/ports/tcp-probe.ts index 92bbe5085..3b9fae78b 100644 --- a/src/ports/tcp-probe.ts +++ b/src/ports/tcp-probe.ts @@ -142,8 +142,4 @@ export class FakeTcpProbe implements TcpProbe { startListening(port: number): void { this.#listening.add(port); } - - stopListening(port: number): void { - this.#listening.delete(port); - } } diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index 0db0b7504..a71965662 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -98,7 +98,13 @@ describe("connectSimlock: handshake", () => { await expect(client.getStatus()).rejects.toMatchObject({ code: "PROTOCOL_VERSION_UNSUPPORTED", - details: { daemon: { max: 2, min: 2 }, daemonVersion: "unknown" }, + details: { + // The range this client offered at hello; the legacy daemon's is the one that predates + // ranges. + client: (hello.payload as { protocolRange: unknown }).protocolRange, + daemon: { max: 2, min: 2 }, + daemonVersion: "unknown", + }, }); expect(connection.sent).toHaveLength(1); });