From 16b0d092d8150ad6f4354bba4e5b047271279f89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 14 Nov 2026 12:54:16 +0100 Subject: [PATCH 1/8] feat(device-status): report per device whether a new session can take it `device status --json` answered how many claim records name a device, not whether `open` accepts one now, so a caller that read the hidden stale-claim count as a block gave up on devices whose owner had provably exited (#4524). Report each claimed device once with `acquirable`, `blockedBy` when it is not, and the `owner` to act on. The answer comes from the decisions an acquisition already applies: the owner half of `foreignClaimSettlement` and the pre-gateway resource check `open` and `device release --stale` run, so no second classifier decides ownership. `status` never touches a device, so it passes no boot observer and reads a live owner as blocking, as `boot`, `install` and `shutdown` do. Share one refusal vocabulary: the table `device release --stale` kept privately is now `deviceClaimRefusalReason`, and retention reasons are typed as `ClaimRecoveryRetentionReason`, so status and release name a block identically. Co-Authored-By: Claude Opus 5.5 --- CONTEXT.md | 5 + packages/daemon-contracts/package.json | 4 + .../src/device-claim-acquirability.test.ts | 184 ++++++++++++++++++ .../src/device-claim-acquirability.ts | 179 +++++++++++++++++ .../src/device-claim-inspection.ts | 41 ++++ .../src/device-claim-reconciliation.ts | 16 +- .../src/device-claim-settlement.ts | 34 ++++ .../daemon-contracts/src/device-claims.ts | 24 +-- .../device-claim-owner-recovery.test.ts | 4 +- src/__tests__/cli-device-status.test.ts | 92 ++++++++- src/cli/commands/device.ts | 71 ++++++- src/commands/schema/cli-help.ts | 2 +- website/docs/docs/commands.md | 1 + website/docs/docs/sessions.md | 5 + 14 files changed, 628 insertions(+), 34 deletions(-) create mode 100644 packages/daemon-contracts/src/device-claim-acquirability.test.ts create mode 100644 packages/daemon-contracts/src/device-claim-acquirability.ts diff --git a/CONTEXT.md b/CONTEXT.md index 95f81d678d..eba6d5efad 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -79,6 +79,11 @@ A command's observation, ownership, or exclusive-mutation rule. The per-owner-kind decision at the claim gate: ordinary or none. _Avoid_: Claim policy, device-claim policy +**Device acquirability**: +Whether a new session can take a device now, answered through the claim gate's own decisions. It is +an inspection, not a reservation. +_Avoid_: Device availability, free device + **Human-control hold**: A device-scoped pause on agent mutations during human operation. diff --git a/packages/daemon-contracts/package.json b/packages/daemon-contracts/package.json index 56faa64f4f..9cfae584a1 100644 --- a/packages/daemon-contracts/package.json +++ b/packages/daemon-contracts/package.json @@ -52,6 +52,10 @@ "types": "./src/daemon-stop.ts", "default": "./src/daemon-stop.ts" }, + "./device-claim-acquirability": { + "types": "./src/device-claim-acquirability.ts", + "default": "./src/device-claim-acquirability.ts" + }, "./device-claim-recovery": { "types": "./src/device-claim-recovery.ts", "default": "./src/device-claim-recovery.ts" diff --git a/packages/daemon-contracts/src/device-claim-acquirability.test.ts b/packages/daemon-contracts/src/device-claim-acquirability.test.ts new file mode 100644 index 0000000000..a80313b91e --- /dev/null +++ b/packages/daemon-contracts/src/device-claim-acquirability.test.ts @@ -0,0 +1,184 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { afterEach, test } from 'vitest'; +import * as hostProcess from '@agent-device/host-kit/process'; +import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; +import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; +import { appLogResourceStore } from '@agent-device/capture-kit/app-log-durable-resource'; +import { screenRecordingDurableResource } from '@agent-device/capture-kit/screen-recording-session-resource'; +import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; +import { mkdtempForTestSync, pinOwnProcessStartTime } from '@agent-device/test-kit'; +import { inspectDeviceAcquirability } from './device-claim-acquirability.ts'; +import { canonicalLocalDeviceKey, resolveDeviceClaimPath } from './device-claim-paths.ts'; +import { writeDeviceClaim } from './device-claim-store.ts'; +import { inspectDeviceClaims, type DeviceClaim } from './device-claims.ts'; +import { hostAppDeviceId, type DeviceIdentity } from '@agent-device/kernel/device'; + +pinOwnProcessStartTime(hostProcess); + +const DEAD_OWNER_PID = 999_999_999; +const DEVICE: DeviceIdentity = { id: 'emulator-5554', family: 'android', kind: 'emulator' }; + +const roots: string[] = []; + +afterEach(() => { + delete process.env.AGENT_DEVICE_CLAIMS_DIR; + for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); +}); + +function useClaimsRoot(): string { + const root = mkdtempForTestSync('device-claim-acquirability-'); + roots.push(root); + process.env.AGENT_DEVICE_CLAIMS_DIR = root; + return root; +} + +function claimFor( + device: DeviceIdentity, + owner: { pid: number; startTime: string | null }, + stateDir: string, +): DeviceClaim { + return { + schemaVersion: 3, + deviceKey: canonicalLocalDeviceKey(device), + device: { ...device, name: device.id }, + session: 'owner-session', + workspace: '/worktrees/owner', + stateDir, + ownerPid: owner.pid, + ownerStartTime: owner.startTime, + ownerToken: 'owner-token', + createdAtMs: 1, + updatedAtMs: 1, + claimOwnerKind: 'open-session', + }; +} + +function deadClaim(device: DeviceIdentity = DEVICE, stateDir = process.cwd()): DeviceClaim { + return claimFor(device, { pid: DEAD_OWNER_PID, startTime: 'old-start-time' }, stateDir); +} + +function liveClaim(device: DeviceIdentity = DEVICE, stateDir = process.cwd()): DeviceClaim { + return claimFor(device, readCurrentOwnerIdentity(), stateDir); +} + +/** What `device status` answers for `device`: every stored claim, weighed by the same inspection. */ +async function acquirabilityFor(device: DeviceIdentity) { + return await inspectDeviceAcquirability({ + device, + claims: inspectDeviceClaims({}, process.env), + env: process.env, + }); +} + +test('a live owner makes the device not acquirable and names that owner', async () => { + useClaimsRoot(); + writeDeviceClaim(liveClaim(), process.env); + + const result = await acquirabilityFor(DEVICE); + assert.equal(result.acquirable, false); + assert.equal(result.blockedBy, 'live-owner'); + assert.equal(result.claim?.classification, 'live'); + assert.equal(result.claim?.session, 'owner-session'); +}); + +test('a claim whose owner is provably dead and retains nothing is acquirable', async () => { + const stateDir = useClaimsRoot(); + writeDeviceClaim(deadClaim(DEVICE, stateDir), process.env); + + const result = await acquirabilityFor(DEVICE); + assert.equal(result.acquirable, true); + assert.equal(result.blockedBy, undefined); + assert.equal(result.claim?.classification, 'owner-process-dead'); +}); + +test('a live claim of a host device blocks one of its app devices', async () => { + useClaimsRoot(); + const host: DeviceIdentity = { id: 'chrome', family: 'web', kind: 'device' }; + const app: DeviceIdentity = { ...host, id: hostAppDeviceId(host.id, 'com.example.app') }; + writeDeviceClaim(liveClaim(host), process.env); + + const result = await acquirabilityFor(app); + assert.equal(result.acquirable, false); + assert.equal(result.blockedBy, 'live-owner'); +}); + +test('a dead owner that still owns an open screen recording is not acquirable with that reason', async () => { + const stateDir = useClaimsRoot(); + const claim = deadClaim(DEVICE, stateDir); + writeDeviceClaim(claim, process.env); + screenRecordingDurableResource.store.write( + screenRecordingDurableResource.store.resolvePath( + path.join(stateDir, 'sessions', claim.session), + ), + createDurableResourceEnvelope({ + resourceKind: 'screen-recording', + sessionId: claim.session, + device: claim.device, + owner: localRuntimeOwner('android'), + fence: { token: 'fence', generation: 1 }, + lifecycle: 'open', + descriptor: { version: 1, body: {} }, + }), + ); + + const result = await acquirabilityFor(DEVICE); + assert.equal(result.acquirable, false); + assert.equal(result.blockedBy, 'screen-recording-cleanup-pending'); +}); + +test('a dead owner whose recording reached its terminal state leaves the device acquirable', async () => { + const stateDir = useClaimsRoot(); + const claim = deadClaim(DEVICE, stateDir); + writeDeviceClaim(claim, process.env); + appLogResourceStore.write( + appLogResourceStore.resolvePath(path.join(stateDir, 'sessions', claim.session)), + createDurableResourceEnvelope({ + resourceKind: 'app-log', + sessionId: claim.session, + device: claim.device, + owner: localRuntimeOwner('android'), + fence: { token: 'fence', generation: 1 }, + lifecycle: 'completed', + descriptor: { version: 1, body: { pid: 123 } }, + }), + ); + + assert.equal((await acquirabilityFor(DEVICE)).acquirable, true); +}); + +test('unreadable resource evidence blocks a dead owner with its own reason', async () => { + const stateDir = useClaimsRoot(); + const claim = deadClaim(DEVICE, stateDir); + writeDeviceClaim(claim, process.env); + const resourcePath = appLogResourceStore.resolvePath( + path.join(stateDir, 'sessions', claim.session), + ); + fs.mkdirSync(path.dirname(resourcePath), { recursive: true }); + fs.writeFileSync(resourcePath, '{'); + + const result = await acquirabilityFor(DEVICE); + assert.equal(result.acquirable, false); + assert.equal(result.blockedBy, 'app-log-descriptor-invalid'); +}); + +test('an unreadable claim record blocks the device its key points at, not another one', async () => { + useClaimsRoot(); + fs.writeFileSync(resolveDeviceClaimPath(canonicalLocalDeviceKey(DEVICE), process.env), '{bad'); + + const blocked = await acquirabilityFor(DEVICE); + assert.equal(blocked.acquirable, false); + assert.equal(blocked.blockedBy, 'claim-record-inconsistent'); + + const other: DeviceIdentity = { id: 'emulator-5556', family: 'android', kind: 'emulator' }; + assert.deepEqual(await acquirabilityFor(other), { acquirable: true }); +}); + +test('a device no claim names is acquirable', async () => { + useClaimsRoot(); + writeDeviceClaim(deadClaim(), process.env); + const other: DeviceIdentity = { id: 'emulator-5556', family: 'android', kind: 'emulator' }; + + assert.deepEqual(await acquirabilityFor(other), { acquirable: true }); +}); diff --git a/packages/daemon-contracts/src/device-claim-acquirability.ts b/packages/daemon-contracts/src/device-claim-acquirability.ts new file mode 100644 index 0000000000..df6d9764f6 --- /dev/null +++ b/packages/daemon-contracts/src/device-claim-acquirability.ts @@ -0,0 +1,179 @@ +import path from 'node:path'; +import { devicesOverlap, type DeviceIdentity } from '@agent-device/kernel/device'; +import type { DeviceBootObservationService } from '@agent-device/contracts/device-boot'; +import type { EnvMap } from '@agent-device/kernel/source-value'; + +import { + deviceClaimRefusalReason, + type DeviceClaimClassification, + type DeviceClaimRefusalReason, + type InspectedDeviceClaim, +} from './device-claim-inspection.ts'; +import { canonicalLocalDeviceKey, resolveDeviceClaimPath } from './device-claim-paths.ts'; +import { + inspectDeviceClaimRecovery, + type ClaimRecoveryRetentionReason, +} from './device-claim-reconciliation.ts'; +import { inspectDeviceClaimOwnerSettlement } from './device-claim-settlement.ts'; + +/** + * Whether a NEW session can take a device right now, answered through the same decisions an + * acquisition applies rather than a second classifier. Claim counts answer "how many records name + * this device"; this answers "will `open` accept it", which is what a caller choosing a device needs. + * + * The answer is an inspection, not a reservation: an owner can appear or die between it and the + * caller's `open`, which decides for itself. Nothing here deletes, clears, or renews a claim. + */ +export type DeviceAcquirability = Readonly<{ + acquirable: boolean; + /** Why the device is not acquirable now; absent exactly when `acquirable` is true. */ + blockedBy?: DeviceAcquirabilityBlockReason; + /** + * The owner to act on: the holder that blocks the device, or, when it is acquirable, the + * reclaimable owner whose claim an acquisition would settle. + */ + claim?: DeviceAcquirabilityOwner; +}>; + +/** + * Why the device is held, in the vocabulary the acquisition and release paths already use: an owner + * that can still release the device, an owner the host cannot prove dead, an unreadable record, or a + * durable resource the dead owner still owns that keeps its settlement pending (#4238). + */ +export type DeviceAcquirabilityBlockReason = + | DeviceClaimRefusalReason + | ClaimRecoveryRetentionReason; + +/** The owner projection a caller needs to act on the answer. */ +export type DeviceAcquirabilityOwner = Readonly<{ + fileName: string; + classification: DeviceClaimClassification; + deviceKey?: string; + session?: string; + workspace?: string; + stateDir?: string; +}>; + +/** + * One device's acquirability, judged from the claims that concern it. + * + * A claim concerns the device when it is recorded against that device key, when it is recorded + * against a device this one cannot be held apart from, or when it is a record that never decoded and + * sits exactly where this device's key tells `open` to read. The middle case is why an acquisition of + * a host-scoped device — one app of a macOS host, or one web session (ADR 0035) — refuses a live host + * claim and settles a reclaimable one, and a host acquisition weighs its apps the same way. + * + * Each claim answers with the two halves an acquisition asks of a claim its caller does not own: + * {@link inspectDeviceClaimOwnerSettlement}, the very decision `resolveExistingClaim` reaches + * through, so a provably dead or superseded owner counts as acquirable here and there; then + * {@link inspectDeviceClaimRecovery}, the pre-gateway check `open` and `device release --stale` run, + * so a dead owner that still owns a recording blocks all three. + * + * A reporter that cannot reach the device — `device status` never touches one — omits + * `observeDeviceBoot` and so reads no reboot as proof, answering as `boot`, `install` and `shutdown` + * do: a live owner holds the device. `open` passes the observer and also takes a claim a reboot + * invalidated. + */ +export async function inspectDeviceAcquirability(params: { + device: DeviceIdentity; + /** Every inspected claim to weigh, in a stable order; the ones that concern `device` are picked. */ + claims: readonly InspectedDeviceClaim[]; + env: EnvMap; + observeDeviceBoot?: DeviceBootObservationService; +}): Promise { + const reclaimable: InspectedDeviceClaim[] = []; + for (const inspected of claimsConcerningDevice(params.device, params.claims, params.env)) { + const decision = await decideInspectedClaim(inspected, params.observeDeviceBoot); + if (decision.status === 'blocked') return decision.outcome; + if (decision.status === 'reclaimable') reclaimable.push(inspected); + } + const reclaimableClaim = reclaimable[0]; + return reclaimableClaim + ? { acquirable: true, claim: ownerOf(reclaimableClaim) } + : { acquirable: true }; +} + +function claimsConcerningDevice( + device: DeviceIdentity, + claims: readonly InspectedDeviceClaim[], + env: EnvMap, +): InspectedDeviceClaim[] { + const ownClaimFileName = path.basename( + resolveDeviceClaimPath(canonicalLocalDeviceKey(device), env), + ); + return claims.filter((entry) => { + // A record that never decoded names no device, so it blocks exactly the device whose key hashes + // to its file name — the one file `open` would read and refuse to guess at. + if (!entry.claim) return entry.fileName === ownClaimFileName; + return ( + entry.claim.device.family === device.family && + entry.claim.device.appleOs === device.appleOs && + devicesOverlap(entry.claim.device.id, device.id) + ); + }); +} + +async function decideInspectedClaim( + inspected: InspectedDeviceClaim, + observeDeviceBoot: DeviceBootObservationService | undefined, +): Promise<{ status: 'blocked'; outcome: DeviceAcquirability } | { status: 'reclaimable' }> { + const claim = inspected.claim; + if (!claim) { + return { + status: 'blocked', + outcome: { + acquirable: false, + blockedBy: 'claim-record-inconsistent', + claim: ownerOf(inspected), + }, + }; + } + const owner = await inspectDeviceClaimOwnerSettlement({ + inspected, + ...(observeDeviceBoot ? { observeDeviceBoot } : {}), + }); + if (owner.status === 'conflicts') { + return { + status: 'blocked', + outcome: { + acquirable: false, + blockedBy: deviceClaimRefusalReason(inspected.classification), + claim: ownerOf(inspected), + }, + }; + } + const recovery = inspectDeviceClaimRecovery(claim); + if (recovery.status === 'retained') { + return { + status: 'blocked', + outcome: { acquirable: false, blockedBy: recovery.reason, claim: ownerOf(inspected) }, + }; + } + // A reclaimable owner still owns a resource it never closed, and acquisition settles resources + // before it clears the claim (#4238). `status` composes no recovery gateway, so it reports such a + // device as pending disposal rather than guessing whether that recovery would succeed. + const pendingDisposal = recovery.recoveryKinds[0]; + if (pendingDisposal !== undefined) { + return { + status: 'blocked', + outcome: { + acquirable: false, + blockedBy: `${pendingDisposal}-cleanup-pending`, + claim: ownerOf(inspected), + }, + }; + } + return { status: 'reclaimable' }; +} + +function ownerOf(inspected: InspectedDeviceClaim): DeviceAcquirabilityOwner { + const claim = inspected.claim; + return { + fileName: inspected.fileName, + classification: inspected.classification, + ...(inspected.deviceKey ? { deviceKey: inspected.deviceKey } : {}), + ...(claim + ? { session: claim.session, workspace: claim.workspace, stateDir: claim.stateDir } + : {}), + }; +} diff --git a/packages/daemon-contracts/src/device-claim-inspection.ts b/packages/daemon-contracts/src/device-claim-inspection.ts index 59c979ef32..60390736f6 100644 --- a/packages/daemon-contracts/src/device-claim-inspection.ts +++ b/packages/daemon-contracts/src/device-claim-inspection.ts @@ -228,6 +228,47 @@ export function deviceClaimRequiresStaleInspection( } } +/** + * The typed reason a caller gives when it refuses to take a device from the owner a classification + * describes, or refuses to settle that owner's claim. `device release --stale` reports these for the + * claims it leaves alone, and `device status` reports them as the reason a device is not acquirable, + * so one vocabulary answers both. + * + * The dead and superseded entries are the answer for a claim whose owner is provably gone yet which + * still cannot be settled for a reason the owner is not: a claim file named for a different device, + * or a settlement that never reached this claim. + * + * A lookup rather than a switch: a `Record` stays a flat table TypeScript still checks for + * exhaustiveness, so a classification dropped from `DeviceClaimClassification` fails to compile here + * exactly as it would a missing `case`. + */ +const DEVICE_CLAIM_REFUSAL_REASONS: Readonly< + Record +> = Object.freeze({ + live: 'live-owner', + 'owner-process-reused': 'owner-pid-reused', + 'owner-state-dir-gone': 'owner-process-still-running', + unknown: 'owner-liveness-unknown', + inconsistent: 'claim-record-inconsistent', + 'owner-process-dead': 'claim-record-unreadable', + 'owner-daemon-superseded': 'claim-record-unreadable', +}); + +export type DeviceClaimRefusalReason = + | 'live-owner' + | 'owner-pid-reused' + | 'owner-process-still-running' + | 'owner-liveness-unknown' + | 'claim-record-inconsistent' + | 'claim-record-unreadable'; + +/** The refusal reason a classification names. A total lookup, so no caller re-derives it. */ +export function deviceClaimRefusalReason( + classification: DeviceClaimClassification, +): DeviceClaimRefusalReason { + return DEVICE_CLAIM_REFUSAL_REASONS[classification]; +} + /** * Claims whose recorded owner can no longer release them, and which * reconciliation may therefore settle once exact-owner resource recovery diff --git a/packages/daemon-contracts/src/device-claim-reconciliation.ts b/packages/daemon-contracts/src/device-claim-reconciliation.ts index 04f9bdd076..42673a0015 100644 --- a/packages/daemon-contracts/src/device-claim-reconciliation.ts +++ b/packages/daemon-contracts/src/device-claim-reconciliation.ts @@ -82,7 +82,19 @@ export type ClaimRecoveryInspection = resourcePath: string; }>[]; } - | { status: 'retained'; reason: string }; + | { status: 'retained'; reason: ClaimRecoveryRetentionReason }; + +/** + * Why a claim's durable resources keep it un-settled. The reconciliation transaction and + * `device status`'s acquirability report both answer with it, so a caller reads one vocabulary: + * a reason named here is the reason `open` would refuse the device. + */ +export type ClaimRecoveryRetentionReason = + | `${DurableSessionResourceKind}-cleanup-pending` + | `${DurableSessionResourceKind}-owner-mismatch` + | `${DurableSessionResourceKind}-descriptor-invalid` + | `${DurableSessionResourceKind}-descriptor-version-unsupported` + | 'durable-resource-reconciliation-failed'; /** Inspect exact-owner durable manifests without composing a gateway or settling a resource. */ export function inspectDeviceClaimRecovery(claim: DeviceClaim): ClaimRecoveryInspection { @@ -185,7 +197,7 @@ function inspectResourceOwnership( ): | { status: 'missing' } | { status: 'owned'; resourcePath: string; requiresRecovery: boolean } - | { status: 'retained'; reason: string } { + | { status: 'retained'; reason: ClaimRecoveryRetentionReason } { const resourcePath = resource.store.resolvePath(sessionDir); const record = resource.store.read(resourcePath); if (record.status === 'missing') return { status: 'missing' }; diff --git a/packages/daemon-contracts/src/device-claim-settlement.ts b/packages/daemon-contracts/src/device-claim-settlement.ts index 9f91dcdc1a..39c8c0145a 100644 --- a/packages/daemon-contracts/src/device-claim-settlement.ts +++ b/packages/daemon-contracts/src/device-claim-settlement.ts @@ -198,6 +198,40 @@ async function foreignClaimSettlement(params: { return tookOver ? { settles: true, tookOver } : { settles: false }; } +/** + * The owner half of the acquisition decision, asked of a claim somebody already inspected and + * answered by the same {@link foreignClaimSettlement} an acquisition runs. `settles` says the + * recorded owner cannot hold the device against a new session, so acquisition would take it once + * that claim's durable resources reach a terminal state — the caller answers that half. + * `conflicts` says a live or uncertain owner holds it. The caller-scoped halves an acquisition also + * weighs (`held` by this very session, an abandoned claim of this daemon) decide nothing about a + * NEW session, so they stay out of this question. A reporter that never touches the device omits + * `observeDeviceBoot` and therefore never reads a reboot as proof, exactly as `boot`, `install` and + * `shutdown` refuse a live foreign owner instead of asking. The device an acquisition targets only + * reaches the decision through `observeDeviceBoot`, so a caller that passes none needs no device of + * its own: the claim's own record describes the device the question is about. + */ +export async function inspectDeviceClaimOwnerSettlement(params: { + inspected: InspectedDeviceClaim; + observeDeviceBoot?: DeviceBootObservationService; +}): Promise<{ status: 'settles' } | { status: 'conflicts' }> { + const claim = params.inspected.claim; + if (!claim) return { status: 'conflicts' }; + const settlement = await foreignClaimSettlement({ + classification: params.inspected.classification, + claim, + device: deviceInfoFromClaim(claim), + observeDeviceBoot: params.observeDeviceBoot, + }); + return settlement.settles ? { status: 'settles' } : { status: 'conflicts' }; +} + +/** The device a claim's record describes, in the shape a boot observation asks for. */ +function deviceInfoFromClaim(claim: DeviceClaim): DeviceInfo { + const { family, ...identity } = claim.device; + return { ...identity, platform: family }; +} + /** * Clears the claim only once its durable resources are settled, so a claim never disappears while * something owned by its session is still running. diff --git a/packages/daemon-contracts/src/device-claims.ts b/packages/daemon-contracts/src/device-claims.ts index 741e74de0a..bd32cb944f 100644 --- a/packages/daemon-contracts/src/device-claims.ts +++ b/packages/daemon-contracts/src/device-claims.ts @@ -19,6 +19,7 @@ import { ownerIdentityMatches, readCurrentOwnerIdentity } from '@agent-device/ho import { classifyDeviceClaimEntry, deviceClaimOwnerCannotRelease, + deviceClaimRefusalReason, inspectDeviceClaimFile, inspectDeviceClaimsAsync, readDeviceClaimEntry, @@ -589,7 +590,7 @@ async function releaseInspectedStaleClaim( : {}), }; if (!claim || !deviceClaimOwnerCannotRelease(entry.classification)) { - return { ...base, status: 'refused', reason: staleReleaseRefusalReason(entry.classification) }; + return { ...base, status: 'refused', reason: deviceClaimRefusalReason(entry.classification) }; } // A file whose name is not the hash of its own device key is not the file // the claim lock protects; releasing through it could unlink something else. @@ -622,27 +623,6 @@ async function releaseInspectedStaleClaim( }); } -/** - * A lookup rather than a switch: the branch count a switch this size carries reads as complexity - * fallow's health gate flags, while a `Record` stays a flat table TypeScript still checks for - * exhaustiveness (a classification dropped from `DeviceClaimClassification` fails to compile here - * exactly as it would a missing `case`). - */ -const STALE_RELEASE_REFUSAL_REASONS: Readonly> = - Object.freeze({ - live: 'live-owner', - 'owner-process-reused': 'owner-pid-reused', - 'owner-state-dir-gone': 'owner-process-still-running', - unknown: 'owner-liveness-unknown', - inconsistent: 'claim-record-inconsistent', - 'owner-process-dead': 'claim-record-unreadable', - 'owner-daemon-superseded': 'claim-record-unreadable', - }); - -function staleReleaseRefusalReason(classification: DeviceClaimClassification): string { - return STALE_RELEASE_REFUSAL_REASONS[classification]; -} - /** * What releasing a claim actually did. Resolving is not the same as releasing: * clearing deliberately leaves a claim it does not own in place, so a caller diff --git a/packages/daemon/src/server/device/__tests__/device-claim-owner-recovery.test.ts b/packages/daemon/src/server/device/__tests__/device-claim-owner-recovery.test.ts index 91e65dfc52..15a11844dc 100644 --- a/packages/daemon/src/server/device/__tests__/device-claim-owner-recovery.test.ts +++ b/packages/daemon/src/server/device/__tests__/device-claim-owner-recovery.test.ts @@ -80,7 +80,7 @@ test('a retained owner decision stops recovery before gateway composition', asyn beforeGateway: async (current) => { assert.equal(current, claim); events.push('inspect'); - return { status: 'retained', reason: 'resource-recovery-requires-standalone' }; + return { status: 'retained', reason: 'screen-recording-cleanup-pending' }; }, composeGateway: () => { events.push('gateway'); @@ -89,7 +89,7 @@ test('a retained owner decision stops recovery before gateway composition', asyn }); assert.deepEqual(await reconcile(claim), { status: 'retained', - reason: 'resource-recovery-requires-standalone', + reason: 'screen-recording-cleanup-pending', }); assert.deepEqual(events, ['inspect']); }); diff --git a/src/__tests__/cli-device-status.test.ts b/src/__tests__/cli-device-status.test.ts index 3f43042e9c..f7c5f6b1f9 100644 --- a/src/__tests__/cli-device-status.test.ts +++ b/src/__tests__/cli-device-status.test.ts @@ -1,9 +1,13 @@ import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { test } from 'vitest'; import * as hostProcess from '@agent-device/host-kit/process'; import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; +import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; +import { screenRecordingDurableResource } from '@agent-device/capture-kit/screen-recording-session-resource'; +import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; import { runCliCapture } from './cli-capture.ts'; import { mkdtempForTestSync, @@ -18,7 +22,10 @@ test('device status is daemonless and does not send a daemon request', async () assert.equal(result.code, null); assert.equal(result.calls.length, 0); const payload = JSON.parse(result.stdout); - assert.deepEqual(payload, { success: true, data: { claims: [], hiddenStaleClaims: 0 } }); + assert.deepEqual(payload, { + success: true, + data: { claims: [], hiddenStaleClaims: 0, devices: [] }, + }); }); test('keeps normal status compact while retaining proven-stale claims for explicit inspection', async () => { @@ -97,6 +104,89 @@ test('keeps normal status compact while retaining proven-stale claims for explic } }); +test('reports per device whether a new session can take it, with the blocking reason', async () => { + const claimsDir = mkdtempForTestSync('agent-device-cli-claims-'); + const ownerStateDir = mkdtempForTestSync('agent-device-cli-claims-owner-'); + const owner = readCurrentOwnerIdentity(); + const write = ( + deviceKey: string, + id: string, + params: { ownerPid: number; ownerStartTime: string | null; stateDir: string }, + ) => + fs.writeFileSync( + path.join(claimsDir, `${cryptoHashForTest(deviceKey)}.json`), + JSON.stringify({ + schemaVersion: 1, + deviceKey, + device: { platform: 'android', id, name: id, kind: 'emulator' }, + session: `session-${id}`, + workspace: '/worktrees/owner', + stateDir: params.stateDir, + ownerPid: params.ownerPid, + ownerStartTime: params.ownerStartTime, + ownerToken: 'owner-token', + createdAtMs: 1, + updatedAtMs: 1, + }), + ); + try { + write('local:android:none:held', 'held', { + ownerPid: owner.pid, + ownerStartTime: owner.startTime, + stateDir: process.cwd(), + }); + write('local:android:none:reclaimable', 'reclaimable', { + ownerPid: 999_999_999, + ownerStartTime: 'old-start-time', + stateDir: ownerStateDir, + }); + write('local:android:none:retained', 'retained', { + ownerPid: 999_999_999, + ownerStartTime: 'old-start-time', + stateDir: ownerStateDir, + }); + const recordingPath = screenRecordingDurableResource.store.resolvePath( + path.join(ownerStateDir, 'sessions', 'session-retained'), + ); + screenRecordingDurableResource.store.write( + recordingPath, + createDurableResourceEnvelope({ + resourceKind: 'screen-recording', + sessionId: 'session-retained', + device: { id: 'retained', family: 'android', kind: 'emulator' }, + owner: localRuntimeOwner('android'), + fence: { token: 'fence', generation: 1 }, + lifecycle: 'open', + descriptor: { version: 1, body: {} }, + }), + ); + + const result = await runCliCapture(['device', 'status', '--json'], { + env: { AGENT_DEVICE_CLAIMS_DIR: claimsDir }, + }); + assert.equal(result.code, null); + const devices = JSON.parse(result.stdout).data.devices; + const byId = Object.fromEntries( + devices.map((entry: { device: { id: string } }) => [entry.device.id, entry]), + ); + assert.equal(byId.held.acquirable, false); + assert.equal(byId.held.blockedBy, 'live-owner'); + assert.equal(byId.held.owner.session, 'session-held'); + // #4524: the Expo Explore case. A provably dead owner is no longer read as blocking. + assert.equal(byId.reclaimable.acquirable, true); + assert.equal(byId.reclaimable.blockedBy, undefined); + assert.equal(byId.retained.acquirable, false); + assert.equal(byId.retained.blockedBy, 'screen-recording-cleanup-pending'); + } finally { + fs.rmSync(claimsDir, { recursive: true, force: true }); + fs.rmSync(ownerStateDir, { recursive: true, force: true }); + } +}); + +function cryptoHashForTest(deviceKey: string): string { + return crypto.createHash('sha256').update(deviceKey).digest('hex'); +} + test('keeps corrupt claims visible and requires --stale for uncertain reclaimable views', async () => { const claimsDir = mkdtempForTestSync('agent-device-cli-claims-'); const owner = readCurrentOwnerIdentity(); diff --git a/src/cli/commands/device.ts b/src/cli/commands/device.ts index b3d1932f02..50fe20c3db 100644 --- a/src/cli/commands/device.ts +++ b/src/cli/commands/device.ts @@ -1,4 +1,4 @@ -import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import { AppError } from '@agent-device/kernel/errors'; import { publicPlatformString } from '@agent-device/kernel/device'; import { @@ -8,6 +8,10 @@ import { type InspectedDeviceClaim, type DeviceClaimStaleReleaseOutcome, } from '@agent-device/daemon-contracts/device-claims'; +import { + inspectDeviceAcquirability, + type DeviceAcquirabilityBlockReason, +} from '@agent-device/daemon-contracts/device-claim-acquirability'; import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell'; import { writeCommandOutput } from './shared.ts'; import type { CliFlags } from '@agent-device/contracts/command'; @@ -31,14 +35,15 @@ export const deviceCommand: ClientCommandHandler = async ({ positionals, flags, const staleClaims = inspectedClaims.filter((claim) => deviceClaimRequiresStaleInspection(claim.classification), ); - const claims = ( - flags.stale - ? staleClaims - : inspectedClaims.filter((claim) => !deviceClaimRequiresStaleInspection(claim.classification)) - ).map(serializeClaim); + const visible = flags.stale + ? staleClaims + : inspectedClaims.filter((claim) => !deviceClaimRequiresStaleInspection(claim.classification)); + const claims = visible.map(serializeClaim); + const devices = await reportDeviceAcquirability(inspectedClaims, host.env); const data = { claims, ...(flags.stale ? {} : { hiddenStaleClaims: staleClaims.length }), + devices, }; await writeCommandOutput(flags, data, () => renderDeviceStatus(claims, { @@ -54,6 +59,60 @@ export const deviceCommand: ClientCommandHandler = async ({ positionals, flags, return true; }; +type DeviceAcquirabilityReport = { + deviceKey: string; + device: Record; + acquirable: boolean; + /** Why a new session cannot take it now, and the holder to act on; absent when it can. */ + blockedBy?: DeviceAcquirabilityBlockReason; + owner?: { session: string; workspace: string; stateDir: string }; +}; + +/** + * Whether a new session can take each device a claim names, weighed against every claim this run + * inspected so a host's app device sees its host's owner. One entry per device, in inspection order. + * + * Every device a claim names is reported, including one whose only claims are the stale ones this + * view hides: their owner being reclaimable is exactly why they are hidden, and a caller choosing a + * device needs that answer without asking for the hidden records. A device no claim names is + * acquirable and absent; `agent-device devices` is what enumerates devices. + */ +async function reportDeviceAcquirability( + inspectedClaims: readonly InspectedDeviceClaim[], + env: EnvMap, +): Promise { + const reports: DeviceAcquirabilityReport[] = []; + const seen = new Set(); + for (const entry of inspectedClaims) { + const deviceKey = entry.deviceKey; + const device = entry.claim?.device; + if (!deviceKey || !device || seen.has(deviceKey)) continue; + seen.add(deviceKey); + const acquirability = await inspectDeviceAcquirability({ + device, + claims: inspectedClaims, + env, + }); + const holder = acquirability.blockedBy ? acquirability.claim : undefined; + reports.push({ + deviceKey, + device: serializeClaimDevice(device), + acquirable: acquirability.acquirable, + ...(acquirability.blockedBy ? { blockedBy: acquirability.blockedBy } : {}), + ...(holder?.session + ? { + owner: { + session: holder.session, + workspace: holder.workspace ?? '', + stateDir: holder.stateDir ?? '', + }, + } + : {}), + }); + } + return reports; +} + /** * `device release --stale`: settle and clear matching claims whose owner * provably cannot release them. Everything else fails closed and is reported diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 869e8455b6..078a69e07a 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -311,7 +311,7 @@ Example: Device busy and ownership: DEVICE_IN_USE has two flavors. "already in use by session X" is this daemon's session table: reuse it with --session X, or run close --session X first. "owned by session X in workspace Y" is the host-global device claim another session — from this daemon or another worktree's daemon — or an in-flight command holds; there may be no session to close, and it is never retriable, so run the error's exact recovery command instead of retrying. - Inspect ownership without any daemon: agent-device device status (add --stale for proven-dead owners; settle and release those with agent-device device release --stale). devices marks rows that are claimed, so pick an unclaimed device instead of contending. + Inspect ownership without any daemon: agent-device device status (add --stale for proven-dead owners; settle and release those with agent-device device release --stale). Its devices list answers whether a new session can take each device now: acquirable true means open accepts it, false names the reason in blockedBy (live-owner, an owner whose liveness is unknown, claim-record-inconsistent, or a resource such as screen-recording-cleanup-pending that still waits for disposal). A claim whose owner is provably dead and retains nothing is acquirable, so hiddenStaleClaims alone never means the device is unavailable. devices marks rows that are claimed, so pick an unclaimed device instead of contending. A live foreign owner is released by closing its session from its own workspace or stopping its daemon: agent-device daemon stop --state-dir (the error names the state dir). The device itself can settle a claim: when it rebooted after that claim was taken, its app, runner, and accessibility session were destroyed, so open reconciles the owner's resources, takes the claim, and reports the release in warnings. Never recover by hunting PIDs with ps/kill. boot/install/shutdown take the same claims as open and refuse foreign-claimed devices identically; they do not ask the device about its boot. Use snapshot, screenshot, logs, network, perf frames, and perf memory for device/app runtime evidence. Use react-devtools when component internals or React rendering performance matter.`, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index f0abcae1df..afc13082fb 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -87,6 +87,7 @@ Select a device: Device claims and the daemon: - `device status` lists host-local device claims without starting or contacting a daemon; `--stale` shows the stale claims it hides by default (owner exited, PID reused, state directory deleted, or daemon replaced), some of whose owners may still be running. Scope it with `--platform` plus `--udid` (Apple) or `--serial` (Android). A claim held by another live or uncertain owner blocks `open`, unless the device rebooted after the claim was taken: then `open` settles that owner's durable resources, takes the claim, and reports the release in `warnings`. +- `device status --json` also reports each claimed device once, with `acquirable` for whether a new session can take it now. When it cannot, `blockedBy` names why, from the same decision `open` applies, and `owner` names the holder to act on. A claim whose owner provably exited or was replaced and that retains no durable resource is acquirable, so a non-zero `hiddenStaleClaims` alone does not mean the device is unavailable. - `device release --stale` settles the durable resources of an owner that provably can't release its claim (its process exited or a newer daemon replaced it), then clears the claim. Live, uncertain, PID-reused, corrupt, and deleted-state-directory claims are refused with the reason. See [Sessions](/docs/sessions#release-a-device-another-session-or-workspace-holds). - A command that needs the shared local daemon starts it for its state directory when none runs; `device status` and `device release --stale` never contact one. When the running daemon comes from another version or build, the command replaces it only if it reports no work: no request in flight, no session, no repair session and no live lease. A resumable upload still streaming and a host human-control hold that names no lease are not counted, so a replacement can end them. Otherwise the command fails with `daemon-busy` and leaves the daemon alone. A daemon from a release that predates this check is never replaced, and fails with `daemon-incompatible`. End a busy or older daemon deliberately with `daemon stop`. Node.js clients choose this per client; see [Daemon lifecycle](/docs/client-api#daemon-lifecycle). - `daemon stop --state-dir ` stops a detached local daemon with process signals after verifying its identity. `--clean` also removes the Apple runner processes and leases that daemon retained. diff --git a/website/docs/docs/sessions.md b/website/docs/docs/sessions.md index e9d85bf3f8..ffb82f0711 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -186,6 +186,11 @@ another process, its state directory was deleted, or a newer daemon replaced it. cases the owner process can still be running, so inspect each one before you act. Scope either view with `--platform` plus `--udid` (Apple) or `--serial` (Android). +`--json` reports each device once as `acquirable`, which answers whether a new session can take that +device now. `blockedBy` names why not, and `owner` identifies the claim that holds it. A stale claim +whose owner is provably gone leaves the device acquirable, so a non-zero hidden stale-claim count is +not a block on its own. + To free a device: - If the owner is still running, close its session from its own workspace, or stop its daemon with From 22b06fc11a8079f89f1acf6811c0f1a9f832c835 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 14 Nov 2026 14:15:41 +0100 Subject: [PATCH 2/8] docs(context): keep the glossary within its context budget The acquirability term is defined where device status documents it. Co-Authored-By: Claude Opus 5.5 --- CONTEXT.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/CONTEXT.md b/CONTEXT.md index eba6d5efad..95f81d678d 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -79,11 +79,6 @@ A command's observation, ownership, or exclusive-mutation rule. The per-owner-kind decision at the claim gate: ordinary or none. _Avoid_: Claim policy, device-claim policy -**Device acquirability**: -Whether a new session can take a device now, answered through the claim gate's own decisions. It is -an inspection, not a reservation. -_Avoid_: Device availability, free device - **Human-control hold**: A device-scoped pause on agent mutations during human operation. From 3b30861c6111a1a1bab7fecb76956841bbdb20e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 14 Nov 2026 14:21:40 +0100 Subject: [PATCH 3/8] fix(device): weigh every overlapping claim and keep the classification in device status Co-Authored-By: Claude Sonnet 5.5 --- .../src/device-claim-acquirability.test.ts | 15 +++++++ .../src/device-claim-acquirability.ts | 2 +- .../src/device-claim-inspection.ts | 6 +-- src/__tests__/cli-device-status.test.ts | 44 +++++++++++++++++++ src/cli/commands/device.ts | 33 ++++++++------ src/commands/schema/cli-help.ts | 2 +- website/docs/docs/commands.md | 2 +- website/docs/docs/sessions.md | 10 +++-- 8 files changed, 90 insertions(+), 24 deletions(-) diff --git a/packages/daemon-contracts/src/device-claim-acquirability.test.ts b/packages/daemon-contracts/src/device-claim-acquirability.test.ts index a80313b91e..10d7818fa7 100644 --- a/packages/daemon-contracts/src/device-claim-acquirability.test.ts +++ b/packages/daemon-contracts/src/device-claim-acquirability.test.ts @@ -175,6 +175,21 @@ test('an unreadable claim record blocks the device its key points at, not anothe assert.deepEqual(await acquirabilityFor(other), { acquirable: true }); }); +test('an undecodable claim record keeps its own classification as the blocking reason', async () => { + useClaimsRoot(); + const fileName = path.basename( + resolveDeviceClaimPath(canonicalLocalDeviceKey(DEVICE), process.env), + ); + + const result = await inspectDeviceAcquirability({ + device: DEVICE, + claims: [{ fileName, classification: 'unknown', error: 'EACCES' }], + env: process.env, + }); + assert.equal(result.acquirable, false); + assert.equal(result.blockedBy, 'owner-liveness-unknown'); +}); + test('a device no claim names is acquirable', async () => { useClaimsRoot(); writeDeviceClaim(deadClaim(), process.env); diff --git a/packages/daemon-contracts/src/device-claim-acquirability.ts b/packages/daemon-contracts/src/device-claim-acquirability.ts index df6d9764f6..48026dec38 100644 --- a/packages/daemon-contracts/src/device-claim-acquirability.ts +++ b/packages/daemon-contracts/src/device-claim-acquirability.ts @@ -123,7 +123,7 @@ async function decideInspectedClaim( status: 'blocked', outcome: { acquirable: false, - blockedBy: 'claim-record-inconsistent', + blockedBy: deviceClaimRefusalReason(inspected.classification), claim: ownerOf(inspected), }, }; diff --git a/packages/daemon-contracts/src/device-claim-inspection.ts b/packages/daemon-contracts/src/device-claim-inspection.ts index 60390736f6..b0e681b442 100644 --- a/packages/daemon-contracts/src/device-claim-inspection.ts +++ b/packages/daemon-contracts/src/device-claim-inspection.ts @@ -234,9 +234,9 @@ export function deviceClaimRequiresStaleInspection( * claims it leaves alone, and `device status` reports them as the reason a device is not acquirable, * so one vocabulary answers both. * - * The dead and superseded entries are the answer for a claim whose owner is provably gone yet which - * still cannot be settled for a reason the owner is not: a claim file named for a different device, - * or a settlement that never reached this claim. + * The dead and superseded entries describe owners that can no longer release their claim, for a claim + * that still cannot be settled for a reason the owner is not: a claim file named for a different + * device, or a settlement that never reached this claim. * * A lookup rather than a switch: a `Record` stays a flat table TypeScript still checks for * exhaustiveness, so a classification dropped from `DeviceClaimClassification` fails to compile here diff --git a/src/__tests__/cli-device-status.test.ts b/src/__tests__/cli-device-status.test.ts index f7c5f6b1f9..e5edf195d5 100644 --- a/src/__tests__/cli-device-status.test.ts +++ b/src/__tests__/cli-device-status.test.ts @@ -175,6 +175,7 @@ test('reports per device whether a new session can take it, with the blocking re // #4524: the Expo Explore case. A provably dead owner is no longer read as blocking. assert.equal(byId.reclaimable.acquirable, true); assert.equal(byId.reclaimable.blockedBy, undefined); + assert.equal(byId.reclaimable.owner.session, 'session-reclaimable'); assert.equal(byId.retained.acquirable, false); assert.equal(byId.retained.blockedBy, 'screen-recording-cleanup-pending'); } finally { @@ -183,6 +184,49 @@ test('reports per device whether a new session can take it, with the blocking re } }); +test('a device selector still weighs the host claim that overlaps the selected app device', async () => { + const claimsDir = mkdtempForTestSync('agent-device-cli-claims-'); + const owner = readCurrentOwnerIdentity(); + const write = (id: string, name: string, ownerPid: number, ownerStartTime: string | null) => { + const deviceKey = `local:web:none:${id}`; + fs.writeFileSync( + path.join(claimsDir, `${cryptoHashForTest(deviceKey)}.json`), + JSON.stringify({ + schemaVersion: 1, + deviceKey, + device: { platform: 'web', id, name, kind: 'device' }, + session: `session-${name}`, + workspace: '/worktrees/owner', + stateDir: process.cwd(), + ownerPid, + ownerStartTime, + ownerToken: 'owner-token', + createdAtMs: 1, + updatedAtMs: 1, + }), + ); + }; + try { + write('chrome', 'Host Chrome', owner.pid, owner.startTime); + write('chrome:app:com.example.app', 'Example App', 999_999_999, 'old-start-time'); + + const result = await runCliCapture(['device', 'status', '--device', 'Example App', '--json'], { + env: { AGENT_DEVICE_CLAIMS_DIR: claimsDir }, + }); + const data = JSON.parse(result.stdout).data; + // The selector scopes the listing to the app's own (stale, hidden) claim. + assert.deepEqual(data.claims, []); + assert.equal(data.hiddenStaleClaims, 1); + assert.equal(data.devices.length, 1); + assert.equal(data.devices[0].device.id, 'chrome:app:com.example.app'); + assert.equal(data.devices[0].acquirable, false); + assert.equal(data.devices[0].blockedBy, 'live-owner'); + assert.equal(data.devices[0].owner.session, 'session-Host Chrome'); + } finally { + fs.rmSync(claimsDir, { recursive: true, force: true }); + } +}); + function cryptoHashForTest(deviceKey: string): string { return crypto.createHash('sha256').update(deviceKey).digest('hex'); } diff --git a/src/cli/commands/device.ts b/src/cli/commands/device.ts index 50fe20c3db..79947dea60 100644 --- a/src/cli/commands/device.ts +++ b/src/cli/commands/device.ts @@ -23,15 +23,14 @@ export const deviceCommand: ClientCommandHandler = async ({ positionals, flags, throw new AppError('INVALID_ARGS', 'device accepts only: status, release'); } if (positionals[0] === 'release') return await runDeviceRelease(flags, host); - const inspectedClaims = inspectDeviceClaims( - { - platform: flags.platform, - device: flags.device, - udid: flags.udid, - serial: flags.serial, - }, - host.env, - ); + const selectors = { + platform: flags.platform, + device: flags.device, + udid: flags.udid, + serial: flags.serial, + }; + const inspectedClaims = inspectDeviceClaims(selectors, host.env); + const hasSelector = Object.values(selectors).some((value) => value !== undefined); const staleClaims = inspectedClaims.filter((claim) => deviceClaimRequiresStaleInspection(claim.classification), ); @@ -39,7 +38,11 @@ export const deviceCommand: ClientCommandHandler = async ({ positionals, flags, ? staleClaims : inspectedClaims.filter((claim) => !deviceClaimRequiresStaleInspection(claim.classification)); const claims = visible.map(serializeClaim); - const devices = await reportDeviceAcquirability(inspectedClaims, host.env); + const devices = await reportDeviceAcquirability( + inspectedClaims, + hasSelector ? inspectDeviceClaims({}, host.env) : inspectedClaims, + host.env, + ); const data = { claims, ...(flags.stale ? {} : { hiddenStaleClaims: staleClaims.length }), @@ -69,8 +72,9 @@ type DeviceAcquirabilityReport = { }; /** - * Whether a new session can take each device a claim names, weighed against every claim this run - * inspected so a host's app device sees its host's owner. One entry per device, in inspection order. + * Whether a new session can take each device a selected claim names, weighed against every claim on + * the host, as `open` does, so a selector that hides a host's or an app's claim never hides its + * owner. One entry per device, in inspection order. * * Every device a claim names is reported, including one whose only claims are the stale ones this * view hides: their owner being reclaimable is exactly why they are hidden, and a caller choosing a @@ -79,6 +83,7 @@ type DeviceAcquirabilityReport = { */ async function reportDeviceAcquirability( inspectedClaims: readonly InspectedDeviceClaim[], + weighedClaims: readonly InspectedDeviceClaim[], env: EnvMap, ): Promise { const reports: DeviceAcquirabilityReport[] = []; @@ -90,10 +95,10 @@ async function reportDeviceAcquirability( seen.add(deviceKey); const acquirability = await inspectDeviceAcquirability({ device, - claims: inspectedClaims, + claims: weighedClaims, env, }); - const holder = acquirability.blockedBy ? acquirability.claim : undefined; + const holder = acquirability.claim; reports.push({ deviceKey, device: serializeClaimDevice(device), diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 078a69e07a..3c19d4e372 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -311,7 +311,7 @@ Example: Device busy and ownership: DEVICE_IN_USE has two flavors. "already in use by session X" is this daemon's session table: reuse it with --session X, or run close --session X first. "owned by session X in workspace Y" is the host-global device claim another session — from this daemon or another worktree's daemon — or an in-flight command holds; there may be no session to close, and it is never retriable, so run the error's exact recovery command instead of retrying. - Inspect ownership without any daemon: agent-device device status (add --stale for proven-dead owners; settle and release those with agent-device device release --stale). Its devices list answers whether a new session can take each device now: acquirable true means open accepts it, false names the reason in blockedBy (live-owner, an owner whose liveness is unknown, claim-record-inconsistent, or a resource such as screen-recording-cleanup-pending that still waits for disposal). A claim whose owner is provably dead and retains nothing is acquirable, so hiddenStaleClaims alone never means the device is unavailable. devices marks rows that are claimed, so pick an unclaimed device instead of contending. + Inspect ownership without any daemon: agent-device device status (add --stale to list the claims it hides: dead, PID-reused, missing-state-directory, and daemon-replaced owners, some of which may still run; agent-device device release --stale settles and releases only owners proven unable to release). Its devices list inspects whether a new session can take each claimed device: acquirable true means no claim blocks it, false names the reason in blockedBy (live-owner, owner-pid-reused, owner-process-still-running, owner-liveness-unknown, claim-record-inconsistent, or a resource such as screen-recording-cleanup-pending that still waits for disposal). owner appears only when the blocking record decodes. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so open may decide differently. A dead owner that retains nothing does not block by itself, so hiddenStaleClaims alone never means the device is unavailable, but another live overlapping claim still can. devices marks rows that are claimed, so pick an unclaimed device instead of contending. A live foreign owner is released by closing its session from its own workspace or stopping its daemon: agent-device daemon stop --state-dir (the error names the state dir). The device itself can settle a claim: when it rebooted after that claim was taken, its app, runner, and accessibility session were destroyed, so open reconciles the owner's resources, takes the claim, and reports the release in warnings. Never recover by hunting PIDs with ps/kill. boot/install/shutdown take the same claims as open and refuse foreign-claimed devices identically; they do not ask the device about its boot. Use snapshot, screenshot, logs, network, perf frames, and perf memory for device/app runtime evidence. Use react-devtools when component internals or React rendering performance matter.`, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index afc13082fb..ba3875a034 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -87,7 +87,7 @@ Select a device: Device claims and the daemon: - `device status` lists host-local device claims without starting or contacting a daemon; `--stale` shows the stale claims it hides by default (owner exited, PID reused, state directory deleted, or daemon replaced), some of whose owners may still be running. Scope it with `--platform` plus `--udid` (Apple) or `--serial` (Android). A claim held by another live or uncertain owner blocks `open`, unless the device rebooted after the claim was taken: then `open` settles that owner's durable resources, takes the claim, and reports the release in `warnings`. -- `device status --json` also reports each claimed device once, with `acquirable` for whether a new session can take it now. When it cannot, `blockedBy` names why, from the same decision `open` applies, and `owner` names the holder to act on. A claim whose owner provably exited or was replaced and that retains no durable resource is acquirable, so a non-zero `hiddenStaleClaims` alone does not mean the device is unavailable. +- `device status --json` also reports each claimed device once, with `acquirable` for whether a new session can take it now. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so `open` may decide differently. When the device is not acquirable, `blockedBy` names why, and `owner` names the holder when that record decodes. A dead or replaced owner that retains no durable resource does not block by itself, so a non-zero `hiddenStaleClaims` alone does not mean the device is unavailable, but another live overlapping claim or pending resource cleanup still can. - `device release --stale` settles the durable resources of an owner that provably can't release its claim (its process exited or a newer daemon replaced it), then clears the claim. Live, uncertain, PID-reused, corrupt, and deleted-state-directory claims are refused with the reason. See [Sessions](/docs/sessions#release-a-device-another-session-or-workspace-holds). - A command that needs the shared local daemon starts it for its state directory when none runs; `device status` and `device release --stale` never contact one. When the running daemon comes from another version or build, the command replaces it only if it reports no work: no request in flight, no session, no repair session and no live lease. A resumable upload still streaming and a host human-control hold that names no lease are not counted, so a replacement can end them. Otherwise the command fails with `daemon-busy` and leaves the daemon alone. A daemon from a release that predates this check is never replaced, and fails with `daemon-incompatible`. End a busy or older daemon deliberately with `daemon stop`. Node.js clients choose this per client; see [Daemon lifecycle](/docs/client-api#daemon-lifecycle). - `daemon stop --state-dir ` stops a detached local daemon with process signals after verifying its identity. `--clean` also removes the Apple runner processes and leases that daemon retained. diff --git a/website/docs/docs/sessions.md b/website/docs/docs/sessions.md index ffb82f0711..4416fe099b 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -186,10 +186,12 @@ another process, its state directory was deleted, or a newer daemon replaced it. cases the owner process can still be running, so inspect each one before you act. Scope either view with `--platform` plus `--udid` (Apple) or `--serial` (Android). -`--json` reports each device once as `acquirable`, which answers whether a new session can take that -device now. `blockedBy` names why not, and `owner` identifies the claim that holds it. A stale claim -whose owner is provably gone leaves the device acquirable, so a non-zero hidden stale-claim count is -not a block on its own. +`--json` reports each claimed device once as `acquirable`, an inspection of whether a new session can +take it now. It cannot see a reboot and runs no recovery, so `open` may decide differently. +`blockedBy` names why not, and `owner` identifies the holder when the blocking record decodes. A +stale claim whose owner is provably gone and retains no resource does not block by itself, so a +non-zero hidden stale-claim count is not a block on its own. Another live overlapping claim or +pending resource cleanup still can. To free a device: From df46b2f3cce8c5606203f53681109056a0b26435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 14 Nov 2026 14:23:47 +0100 Subject: [PATCH 4/8] fix(daemon-contracts): load device acquirability on demand instead of as a new entry Co-Authored-By: Claude Sonnet 5.5 --- packages/daemon-contracts/package.json | 4 ---- .../src/device-claim-recovery.ts | 16 ++++++++++++++++ src/cli/commands/device.ts | 2 +- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/daemon-contracts/package.json b/packages/daemon-contracts/package.json index 9cfae584a1..56faa64f4f 100644 --- a/packages/daemon-contracts/package.json +++ b/packages/daemon-contracts/package.json @@ -52,10 +52,6 @@ "types": "./src/daemon-stop.ts", "default": "./src/daemon-stop.ts" }, - "./device-claim-acquirability": { - "types": "./src/device-claim-acquirability.ts", - "default": "./src/device-claim-acquirability.ts" - }, "./device-claim-recovery": { "types": "./src/device-claim-recovery.ts", "default": "./src/device-claim-recovery.ts" diff --git a/packages/daemon-contracts/src/device-claim-recovery.ts b/packages/daemon-contracts/src/device-claim-recovery.ts index 6b273ef119..b8d134aa75 100644 --- a/packages/daemon-contracts/src/device-claim-recovery.ts +++ b/packages/daemon-contracts/src/device-claim-recovery.ts @@ -1,4 +1,10 @@ +import type { + DeviceAcquirability, + inspectDeviceAcquirability as InspectDeviceAcquirability, +} from './device-claim-acquirability.ts'; + export type { ClaimRecoveryGatewayFactory } from './claim-recovery-gateway.ts'; +export type { DeviceAcquirabilityBlockReason } from './device-claim-acquirability.ts'; export { inspectDeviceClaimRecovery, type ClaimRecoveryInspection, @@ -8,3 +14,13 @@ export { type OwnerScopedClaimRecoveryComposer, } from './device-claim-owner-recovery.ts'; export { createRecoveryPlatformScope } from './recovery-platform-scope.ts'; + +/** + * {@link InspectDeviceAcquirability}, loaded on demand: only `device status` asks, and the daemon + * that evaluates this entry never does. + */ +export async function inspectDeviceAcquirability( + params: Parameters[0], +): Promise { + return (await import('./device-claim-acquirability.ts')).inspectDeviceAcquirability(params); +} diff --git a/src/cli/commands/device.ts b/src/cli/commands/device.ts index 79947dea60..ab366bf60d 100644 --- a/src/cli/commands/device.ts +++ b/src/cli/commands/device.ts @@ -11,7 +11,7 @@ import { import { inspectDeviceAcquirability, type DeviceAcquirabilityBlockReason, -} from '@agent-device/daemon-contracts/device-claim-acquirability'; +} from '@agent-device/daemon-contracts/device-claim-recovery'; import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell'; import { writeCommandOutput } from './shared.ts'; import type { CliFlags } from '@agent-device/contracts/command'; From 7c57b46696fafbaa58fa7cc459cc5ca572020ef1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 14 Nov 2026 14:31:40 +0100 Subject: [PATCH 5/8] refactor(device): answer status from the admission verdict open's check reads Co-Authored-By: Claude Sonnet 5.5 --- .../src/device-claim-acquirability.ts | 179 ---------------- ...test.ts => device-claim-admission.test.ts} | 105 +++++----- .../src/device-claim-admission.ts | 75 +++++++ .../src/device-claim-recovery.ts | 28 ++- .../daemon-contracts/src/device-claims.ts | 4 +- .../src/core/composite-resource-admission.ts | 21 +- src/__tests__/cli-device-status.test.ts | 194 ++++++++++++++++++ src/cli/commands/device.ts | 81 +++++--- src/commands/schema/cli-help.ts | 2 +- website/docs/docs/commands.md | 2 +- website/docs/docs/sessions.md | 4 +- 11 files changed, 400 insertions(+), 295 deletions(-) delete mode 100644 packages/daemon-contracts/src/device-claim-acquirability.ts rename packages/daemon-contracts/src/{device-claim-acquirability.test.ts => device-claim-admission.test.ts} (59%) create mode 100644 packages/daemon-contracts/src/device-claim-admission.ts diff --git a/packages/daemon-contracts/src/device-claim-acquirability.ts b/packages/daemon-contracts/src/device-claim-acquirability.ts deleted file mode 100644 index 48026dec38..0000000000 --- a/packages/daemon-contracts/src/device-claim-acquirability.ts +++ /dev/null @@ -1,179 +0,0 @@ -import path from 'node:path'; -import { devicesOverlap, type DeviceIdentity } from '@agent-device/kernel/device'; -import type { DeviceBootObservationService } from '@agent-device/contracts/device-boot'; -import type { EnvMap } from '@agent-device/kernel/source-value'; - -import { - deviceClaimRefusalReason, - type DeviceClaimClassification, - type DeviceClaimRefusalReason, - type InspectedDeviceClaim, -} from './device-claim-inspection.ts'; -import { canonicalLocalDeviceKey, resolveDeviceClaimPath } from './device-claim-paths.ts'; -import { - inspectDeviceClaimRecovery, - type ClaimRecoveryRetentionReason, -} from './device-claim-reconciliation.ts'; -import { inspectDeviceClaimOwnerSettlement } from './device-claim-settlement.ts'; - -/** - * Whether a NEW session can take a device right now, answered through the same decisions an - * acquisition applies rather than a second classifier. Claim counts answer "how many records name - * this device"; this answers "will `open` accept it", which is what a caller choosing a device needs. - * - * The answer is an inspection, not a reservation: an owner can appear or die between it and the - * caller's `open`, which decides for itself. Nothing here deletes, clears, or renews a claim. - */ -export type DeviceAcquirability = Readonly<{ - acquirable: boolean; - /** Why the device is not acquirable now; absent exactly when `acquirable` is true. */ - blockedBy?: DeviceAcquirabilityBlockReason; - /** - * The owner to act on: the holder that blocks the device, or, when it is acquirable, the - * reclaimable owner whose claim an acquisition would settle. - */ - claim?: DeviceAcquirabilityOwner; -}>; - -/** - * Why the device is held, in the vocabulary the acquisition and release paths already use: an owner - * that can still release the device, an owner the host cannot prove dead, an unreadable record, or a - * durable resource the dead owner still owns that keeps its settlement pending (#4238). - */ -export type DeviceAcquirabilityBlockReason = - | DeviceClaimRefusalReason - | ClaimRecoveryRetentionReason; - -/** The owner projection a caller needs to act on the answer. */ -export type DeviceAcquirabilityOwner = Readonly<{ - fileName: string; - classification: DeviceClaimClassification; - deviceKey?: string; - session?: string; - workspace?: string; - stateDir?: string; -}>; - -/** - * One device's acquirability, judged from the claims that concern it. - * - * A claim concerns the device when it is recorded against that device key, when it is recorded - * against a device this one cannot be held apart from, or when it is a record that never decoded and - * sits exactly where this device's key tells `open` to read. The middle case is why an acquisition of - * a host-scoped device — one app of a macOS host, or one web session (ADR 0035) — refuses a live host - * claim and settles a reclaimable one, and a host acquisition weighs its apps the same way. - * - * Each claim answers with the two halves an acquisition asks of a claim its caller does not own: - * {@link inspectDeviceClaimOwnerSettlement}, the very decision `resolveExistingClaim` reaches - * through, so a provably dead or superseded owner counts as acquirable here and there; then - * {@link inspectDeviceClaimRecovery}, the pre-gateway check `open` and `device release --stale` run, - * so a dead owner that still owns a recording blocks all three. - * - * A reporter that cannot reach the device — `device status` never touches one — omits - * `observeDeviceBoot` and so reads no reboot as proof, answering as `boot`, `install` and `shutdown` - * do: a live owner holds the device. `open` passes the observer and also takes a claim a reboot - * invalidated. - */ -export async function inspectDeviceAcquirability(params: { - device: DeviceIdentity; - /** Every inspected claim to weigh, in a stable order; the ones that concern `device` are picked. */ - claims: readonly InspectedDeviceClaim[]; - env: EnvMap; - observeDeviceBoot?: DeviceBootObservationService; -}): Promise { - const reclaimable: InspectedDeviceClaim[] = []; - for (const inspected of claimsConcerningDevice(params.device, params.claims, params.env)) { - const decision = await decideInspectedClaim(inspected, params.observeDeviceBoot); - if (decision.status === 'blocked') return decision.outcome; - if (decision.status === 'reclaimable') reclaimable.push(inspected); - } - const reclaimableClaim = reclaimable[0]; - return reclaimableClaim - ? { acquirable: true, claim: ownerOf(reclaimableClaim) } - : { acquirable: true }; -} - -function claimsConcerningDevice( - device: DeviceIdentity, - claims: readonly InspectedDeviceClaim[], - env: EnvMap, -): InspectedDeviceClaim[] { - const ownClaimFileName = path.basename( - resolveDeviceClaimPath(canonicalLocalDeviceKey(device), env), - ); - return claims.filter((entry) => { - // A record that never decoded names no device, so it blocks exactly the device whose key hashes - // to its file name — the one file `open` would read and refuse to guess at. - if (!entry.claim) return entry.fileName === ownClaimFileName; - return ( - entry.claim.device.family === device.family && - entry.claim.device.appleOs === device.appleOs && - devicesOverlap(entry.claim.device.id, device.id) - ); - }); -} - -async function decideInspectedClaim( - inspected: InspectedDeviceClaim, - observeDeviceBoot: DeviceBootObservationService | undefined, -): Promise<{ status: 'blocked'; outcome: DeviceAcquirability } | { status: 'reclaimable' }> { - const claim = inspected.claim; - if (!claim) { - return { - status: 'blocked', - outcome: { - acquirable: false, - blockedBy: deviceClaimRefusalReason(inspected.classification), - claim: ownerOf(inspected), - }, - }; - } - const owner = await inspectDeviceClaimOwnerSettlement({ - inspected, - ...(observeDeviceBoot ? { observeDeviceBoot } : {}), - }); - if (owner.status === 'conflicts') { - return { - status: 'blocked', - outcome: { - acquirable: false, - blockedBy: deviceClaimRefusalReason(inspected.classification), - claim: ownerOf(inspected), - }, - }; - } - const recovery = inspectDeviceClaimRecovery(claim); - if (recovery.status === 'retained') { - return { - status: 'blocked', - outcome: { acquirable: false, blockedBy: recovery.reason, claim: ownerOf(inspected) }, - }; - } - // A reclaimable owner still owns a resource it never closed, and acquisition settles resources - // before it clears the claim (#4238). `status` composes no recovery gateway, so it reports such a - // device as pending disposal rather than guessing whether that recovery would succeed. - const pendingDisposal = recovery.recoveryKinds[0]; - if (pendingDisposal !== undefined) { - return { - status: 'blocked', - outcome: { - acquirable: false, - blockedBy: `${pendingDisposal}-cleanup-pending`, - claim: ownerOf(inspected), - }, - }; - } - return { status: 'reclaimable' }; -} - -function ownerOf(inspected: InspectedDeviceClaim): DeviceAcquirabilityOwner { - const claim = inspected.claim; - return { - fileName: inspected.fileName, - classification: inspected.classification, - ...(inspected.deviceKey ? { deviceKey: inspected.deviceKey } : {}), - ...(claim - ? { session: claim.session, workspace: claim.workspace, stateDir: claim.stateDir } - : {}), - }; -} diff --git a/packages/daemon-contracts/src/device-claim-acquirability.test.ts b/packages/daemon-contracts/src/device-claim-admission.test.ts similarity index 59% rename from packages/daemon-contracts/src/device-claim-acquirability.test.ts rename to packages/daemon-contracts/src/device-claim-admission.test.ts index 10d7818fa7..7cdcc7e6fc 100644 --- a/packages/daemon-contracts/src/device-claim-acquirability.test.ts +++ b/packages/daemon-contracts/src/device-claim-admission.test.ts @@ -9,11 +9,11 @@ import { appLogResourceStore } from '@agent-device/capture-kit/app-log-durable-r import { screenRecordingDurableResource } from '@agent-device/capture-kit/screen-recording-session-resource'; import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; import { mkdtempForTestSync, pinOwnProcessStartTime } from '@agent-device/test-kit'; -import { inspectDeviceAcquirability } from './device-claim-acquirability.ts'; +import { inspectNewSessionAdmission } from './device-claim-admission.ts'; import { canonicalLocalDeviceKey, resolveDeviceClaimPath } from './device-claim-paths.ts'; import { writeDeviceClaim } from './device-claim-store.ts'; -import { inspectDeviceClaims, type DeviceClaim } from './device-claims.ts'; -import { hostAppDeviceId, type DeviceIdentity } from '@agent-device/kernel/device'; +import { deviceClaimRefusalReason, type DeviceClaim } from './device-claims.ts'; +import { hostAppDeviceId, type DeviceIdentity, type DeviceInfo } from '@agent-device/kernel/device'; pinOwnProcessStartTime(hostProcess); @@ -28,7 +28,7 @@ afterEach(() => { }); function useClaimsRoot(): string { - const root = mkdtempForTestSync('device-claim-acquirability-'); + const root = mkdtempForTestSync('device-claim-admission-'); roots.push(root); process.env.AGENT_DEVICE_CLAIMS_DIR = root; return root; @@ -63,48 +63,50 @@ function liveClaim(device: DeviceIdentity = DEVICE, stateDir = process.cwd()): D return claimFor(device, readCurrentOwnerIdentity(), stateDir); } -/** What `device status` answers for `device`: every stored claim, weighed by the same inspection. */ -async function acquirabilityFor(device: DeviceIdentity) { - return await inspectDeviceAcquirability({ - device, - claims: inspectDeviceClaims({}, process.env), - env: process.env, - }); +function infoOf(device: DeviceIdentity): DeviceInfo { + const { family, ...rest } = device; + return { ...rest, platform: family, name: device.id }; } -test('a live owner makes the device not acquirable and names that owner', async () => { +/** What `device status` asks: the admission verdict of a new session of a daemon holding nothing. */ +async function admissionFor(device: DeviceIdentity) { + return await inspectNewSessionAdmission({ device: infoOf(device), env: process.env }); +} + +function refusedReason(admission: Awaited>): string | undefined { + if (admission.status !== 'refused') return undefined; + return admission.retainedBy ?? deviceClaimRefusalReason(admission.conflict.classification); +} + +test('a live owner refuses the device and names that owner', async () => { useClaimsRoot(); writeDeviceClaim(liveClaim(), process.env); - const result = await acquirabilityFor(DEVICE); - assert.equal(result.acquirable, false); - assert.equal(result.blockedBy, 'live-owner'); - assert.equal(result.claim?.classification, 'live'); - assert.equal(result.claim?.session, 'owner-session'); + const result = await admissionFor(DEVICE); + assert.equal(result.status, 'refused'); + assert.equal(refusedReason(result), 'live-owner'); + assert.equal(result.status === 'refused' && result.conflict.claim?.session, 'owner-session'); }); -test('a claim whose owner is provably dead and retains nothing is acquirable', async () => { +test('a claim whose owner is provably dead and retains nothing is admitted', async () => { const stateDir = useClaimsRoot(); writeDeviceClaim(deadClaim(DEVICE, stateDir), process.env); - const result = await acquirabilityFor(DEVICE); - assert.equal(result.acquirable, true); - assert.equal(result.blockedBy, undefined); - assert.equal(result.claim?.classification, 'owner-process-dead'); + const result = await admissionFor(DEVICE); + assert.equal(result.status, 'admitted'); + assert.equal(result.status === 'admitted' && result.reclaimed[0]?.claim.session, 'owner-session'); }); -test('a live claim of a host device blocks one of its app devices', async () => { +test('a live claim of a host device refuses one of its app devices', async () => { useClaimsRoot(); const host: DeviceIdentity = { id: 'chrome', family: 'web', kind: 'device' }; const app: DeviceIdentity = { ...host, id: hostAppDeviceId(host.id, 'com.example.app') }; writeDeviceClaim(liveClaim(host), process.env); - const result = await acquirabilityFor(app); - assert.equal(result.acquirable, false); - assert.equal(result.blockedBy, 'live-owner'); + assert.equal(refusedReason(await admissionFor(app)), 'live-owner'); }); -test('a dead owner that still owns an open screen recording is not acquirable with that reason', async () => { +test('a dead owner whose recording is still open is admitted with the recovery it needs', async () => { const stateDir = useClaimsRoot(); const claim = deadClaim(DEVICE, stateDir); writeDeviceClaim(claim, process.env); @@ -123,12 +125,15 @@ test('a dead owner that still owns an open screen recording is not acquirable wi }), ); - const result = await acquirabilityFor(DEVICE); - assert.equal(result.acquirable, false); - assert.equal(result.blockedBy, 'screen-recording-cleanup-pending'); + const result = await admissionFor(DEVICE); + assert.equal(result.status, 'admitted'); + const recovery = result.status === 'admitted' ? result.reclaimed[0]?.recovery : undefined; + assert.deepEqual(recovery?.status === 'inspectable' && recovery.recoveryKinds, [ + 'screen-recording', + ]); }); -test('a dead owner whose recording reached its terminal state leaves the device acquirable', async () => { +test('a dead owner whose resource reached its terminal state needs no recovery', async () => { const stateDir = useClaimsRoot(); const claim = deadClaim(DEVICE, stateDir); writeDeviceClaim(claim, process.env); @@ -145,10 +150,12 @@ test('a dead owner whose recording reached its terminal state leaves the device }), ); - assert.equal((await acquirabilityFor(DEVICE)).acquirable, true); + const result = await admissionFor(DEVICE); + const recovery = result.status === 'admitted' ? result.reclaimed[0]?.recovery : undefined; + assert.deepEqual(recovery?.status === 'inspectable' && recovery.recoveryKinds, []); }); -test('unreadable resource evidence blocks a dead owner with its own reason', async () => { +test('unreadable resource evidence refuses a dead owner with its own reason', async () => { const stateDir = useClaimsRoot(); const claim = deadClaim(DEVICE, stateDir); writeDeviceClaim(claim, process.env); @@ -158,42 +165,22 @@ test('unreadable resource evidence blocks a dead owner with its own reason', asy fs.mkdirSync(path.dirname(resourcePath), { recursive: true }); fs.writeFileSync(resourcePath, '{'); - const result = await acquirabilityFor(DEVICE); - assert.equal(result.acquirable, false); - assert.equal(result.blockedBy, 'app-log-descriptor-invalid'); + assert.equal(refusedReason(await admissionFor(DEVICE)), 'app-log-descriptor-invalid'); }); -test('an unreadable claim record blocks the device its key points at, not another one', async () => { +test('an unreadable claim record refuses the device its key points at, not another one', async () => { useClaimsRoot(); fs.writeFileSync(resolveDeviceClaimPath(canonicalLocalDeviceKey(DEVICE), process.env), '{bad'); - const blocked = await acquirabilityFor(DEVICE); - assert.equal(blocked.acquirable, false); - assert.equal(blocked.blockedBy, 'claim-record-inconsistent'); - + assert.equal(refusedReason(await admissionFor(DEVICE)), 'claim-record-inconsistent'); const other: DeviceIdentity = { id: 'emulator-5556', family: 'android', kind: 'emulator' }; - assert.deepEqual(await acquirabilityFor(other), { acquirable: true }); -}); - -test('an undecodable claim record keeps its own classification as the blocking reason', async () => { - useClaimsRoot(); - const fileName = path.basename( - resolveDeviceClaimPath(canonicalLocalDeviceKey(DEVICE), process.env), - ); - - const result = await inspectDeviceAcquirability({ - device: DEVICE, - claims: [{ fileName, classification: 'unknown', error: 'EACCES' }], - env: process.env, - }); - assert.equal(result.acquirable, false); - assert.equal(result.blockedBy, 'owner-liveness-unknown'); + assert.deepEqual(await admissionFor(other), { status: 'admitted', reclaimed: [] }); }); -test('a device no claim names is acquirable', async () => { +test('a device no claim names is admitted', async () => { useClaimsRoot(); writeDeviceClaim(deadClaim(), process.env); const other: DeviceIdentity = { id: 'emulator-5556', family: 'android', kind: 'emulator' }; - assert.deepEqual(await acquirabilityFor(other), { acquirable: true }); + assert.deepEqual(await admissionFor(other), { status: 'admitted', reclaimed: [] }); }); diff --git a/packages/daemon-contracts/src/device-claim-admission.ts b/packages/daemon-contracts/src/device-claim-admission.ts new file mode 100644 index 0000000000..b1c3a53365 --- /dev/null +++ b/packages/daemon-contracts/src/device-claim-admission.ts @@ -0,0 +1,75 @@ +import path from 'node:path'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import type { EnvMap } from '@agent-device/kernel/source-value'; + +import type { InspectedDeviceClaim } from './device-claim-inspection.ts'; +import { + inspectDeviceClaimRecovery, + type ClaimRecoveryInspection, + type ClaimRecoveryRetentionReason, +} from './device-claim-reconciliation.ts'; +import type { DeviceClaim } from './device-claim-record.ts'; +import { + inspectDeviceClaimAcquisition, + type ClaimAcquisitionInspectionParams, +} from './device-claims.ts'; + +/** + * What the acquisition path would do with the claims of a device, decided without a side effect: + * `refused` names the claim that wins the refusal, in the order an acquisition reaches the claims; + * `admitted` lists the claims it would settle first. Admission and `device status` both ask this, + * so neither restates the order, the canonical claim path, or the abandoned-claim and read-failure + * rules {@link inspectDeviceClaimAcquisition} applies. Acquisition itself decides again under its + * claim locks. + */ +export type DeviceClaimAdmission = + | { + status: 'admitted'; + reclaimed: readonly Readonly<{ claim: DeviceClaim; recovery?: ClaimRecoveryInspection }>[]; + } + | { + status: 'refused'; + conflict: InspectedDeviceClaim; + retainedBy?: ClaimRecoveryRetentionReason; + }; + +export async function inspectDeviceClaimAdmission( + params: ClaimAcquisitionInspectionParams & { + /** Checks a claim's durable resources before a gateway is composed; defaults to the plain inspection. */ + inspectRecovery?: (claim: DeviceClaim) => ClaimRecoveryInspection | undefined; + }, +): Promise { + const { inspectRecovery = inspectDeviceClaimRecovery, ...acquisition } = params; + const reclaimed: { claim: DeviceClaim; recovery?: ClaimRecoveryInspection }[] = []; + for (const settlement of await inspectDeviceClaimAcquisition(acquisition)) { + if (settlement.status === 'conflict') + return { status: 'refused', conflict: settlement.conflict }; + if (settlement.status !== 'reconcile') continue; + const recovery = inspectRecovery(settlement.claim); + if (recovery?.status === 'retained') { + return { status: 'refused', conflict: settlement.conflict, retainedBy: recovery.reason }; + } + reclaimed.push({ claim: settlement.claim, ...(recovery ? { recovery } : {}) }); + } + return { status: 'admitted', reclaimed }; +} + +/** + * {@link inspectDeviceClaimAdmission} for a NEW session of a daemon that holds nothing: no claim is + * its own, and no abandoned claim belongs to it, so a running owner of any claim blocks. A reporter + * passes no boot observer and never reads a reboot as proof. + */ +export async function inspectNewSessionAdmission(params: { + device: DeviceInfo; + env: EnvMap; +}): Promise { + return await inspectDeviceClaimAdmission({ + device: params.device, + command: 'open', + session: 'device-status', + workspace: path.sep, + stateDir: '', + env: params.env, + coveredClaimIsOwnedByRequest: () => false, + }); +} diff --git a/packages/daemon-contracts/src/device-claim-recovery.ts b/packages/daemon-contracts/src/device-claim-recovery.ts index b8d134aa75..ca591a71d9 100644 --- a/packages/daemon-contracts/src/device-claim-recovery.ts +++ b/packages/daemon-contracts/src/device-claim-recovery.ts @@ -1,10 +1,12 @@ import type { - DeviceAcquirability, - inspectDeviceAcquirability as InspectDeviceAcquirability, -} from './device-claim-acquirability.ts'; + DeviceClaimAdmission, + inspectDeviceClaimAdmission as InspectDeviceClaimAdmission, + inspectNewSessionAdmission as InspectNewSessionAdmission, +} from './device-claim-admission.ts'; +import type { ClaimRecoveryRetentionReason } from './device-claim-reconciliation.ts'; export type { ClaimRecoveryGatewayFactory } from './claim-recovery-gateway.ts'; -export type { DeviceAcquirabilityBlockReason } from './device-claim-acquirability.ts'; +export type { ClaimRecoveryRetentionReason, DeviceClaimAdmission }; export { inspectDeviceClaimRecovery, type ClaimRecoveryInspection, @@ -16,11 +18,17 @@ export { export { createRecoveryPlatformScope } from './recovery-platform-scope.ts'; /** - * {@link InspectDeviceAcquirability}, loaded on demand: only `device status` asks, and the daemon - * that evaluates this entry never does. + * The acquisition admission verdict, loaded on demand: only the admission check and + * `device status` ask, and the daemon evaluating this entry never loads it eagerly. */ -export async function inspectDeviceAcquirability( - params: Parameters[0], -): Promise { - return (await import('./device-claim-acquirability.ts')).inspectDeviceAcquirability(params); +export async function inspectDeviceClaimAdmission( + params: Parameters[0], +): Promise { + return (await import('./device-claim-admission.ts')).inspectDeviceClaimAdmission(params); +} + +export async function inspectNewSessionAdmission( + params: Parameters[0], +): Promise { + return (await import('./device-claim-admission.ts')).inspectNewSessionAdmission(params); } diff --git a/packages/daemon-contracts/src/device-claims.ts b/packages/daemon-contracts/src/device-claims.ts index bd32cb944f..3072743a63 100644 --- a/packages/daemon-contracts/src/device-claims.ts +++ b/packages/daemon-contracts/src/device-claims.ts @@ -53,12 +53,14 @@ import { withDeviceClaimLock, writeDeviceClaim } from './device-claim-store.ts'; export { canonicalLocalDeviceKey } from './device-claim-paths.ts'; export { deviceClaimOwnerCannotRelease, + deviceClaimRefusalReason, deviceClaimRequiresStaleInspection, inspectDeviceClaims, inspectDeviceClaimsAsync, } from './device-claim-inspection.ts'; export type { DeviceClaimClassification, + DeviceClaimRefusalReason, DeviceClaimSelectors, InspectedDeviceClaim, } from './device-claim-inspection.ts'; @@ -87,7 +89,7 @@ export type TransientDeviceClaimResult = | DeviceClaimAcquireResult | { status: 'covered-by-owned-claim' }; -type ClaimAcquisitionInspectionParams = { +export type ClaimAcquisitionInspectionParams = { device: DeviceInfo; command: string; session: string; diff --git a/packages/daemon/src/core/composite-resource-admission.ts b/packages/daemon/src/core/composite-resource-admission.ts index e745d67d01..ea51f0cfec 100644 --- a/packages/daemon/src/core/composite-resource-admission.ts +++ b/packages/daemon/src/core/composite-resource-admission.ts @@ -19,12 +19,12 @@ import { isBoundedCompositeRequest, refuseBoundedCompositeResourceOperation, } from './lease-context.ts'; -import { - inspectDeviceClaimAcquisition, - type DeviceClaim, - type InspectedDeviceClaim, +import type { + DeviceClaim, + InspectedDeviceClaim, } from '@agent-device/daemon-contracts/device-claims'; import { + inspectDeviceClaimAdmission, inspectDeviceClaimRecovery, type ClaimRecoveryInspection, } from '@agent-device/daemon-contracts/device-claim-recovery'; @@ -127,7 +127,7 @@ async function assertBoundedClaimRecovery( const device = await params.resolveDevice(); if (req.command === 'open' && params.hasInMemorySessionOwner(device)) return; if (isActiveProviderDevice(device)) return; - const settlements = await inspectDeviceClaimAcquisition({ + const admission = await inspectDeviceClaimAdmission({ device, command: req.command, session: params.session, @@ -135,17 +135,10 @@ async function assertBoundedClaimRecovery( stateDir: params.stateDir, env: params.env, coveredClaimIsOwnedByRequest: params.coveredClaimIsOwnedByRequest, + inspectRecovery: (claim) => inspectBoundedClaimBeforeGateway(req, claim), ...(policy === 'acquire-session' ? { observeDeviceBoot: params.observeDeviceBoot } : {}), }); - for (const settlement of settlements) { - if (settlement.status === 'conflict') - throw params.claimConflictError(device, settlement.conflict); - if (settlement.status !== 'reconcile') continue; - const inspection = inspectBoundedClaimBeforeGateway(req, settlement.claim); - if (inspection?.status === 'retained') { - throw params.claimConflictError(device, settlement.conflict); - } - } + if (admission.status === 'refused') throw params.claimConflictError(device, admission.conflict); } function inspectBoundedClaimBeforeGateway( diff --git a/src/__tests__/cli-device-status.test.ts b/src/__tests__/cli-device-status.test.ts index e5edf195d5..b78f1bac09 100644 --- a/src/__tests__/cli-device-status.test.ts +++ b/src/__tests__/cli-device-status.test.ts @@ -8,6 +8,7 @@ import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; import { screenRecordingDurableResource } from '@agent-device/capture-kit/screen-recording-session-resource'; import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; +import { inspectDeviceClaimAdmission } from '@agent-device/daemon-contracts/device-claim-recovery'; import { runCliCapture } from './cli-capture.ts'; import { mkdtempForTestSync, @@ -227,6 +228,199 @@ test('a device selector still weighs the host claim that overlaps the selected a } }); +// Status and `open` read one admission verdict. These tests ask it the way `open` does, as a session of +// another daemon, and require the status report to name the same refusal. +async function openAdmissionFor( + claimsDir: string, + device: { id: string; platform: 'android' | 'web' }, +) { + const admission = await inspectDeviceClaimAdmission({ + device: { ...device, name: device.id, kind: 'device' }, + command: 'open', + session: 'other-session', + workspace: '/worktrees/other', + stateDir: '/other-daemon-state', + env: { AGENT_DEVICE_CLAIMS_DIR: claimsDir }, + coveredClaimIsOwnedByRequest: () => false, + }); + return admission.status === 'refused' + ? { acquirable: false, session: admission.conflict.claim?.session } + : { acquirable: true }; +} + +function claimJson(params: { + deviceKey: string; + id: string; + platform: 'android' | 'web'; + session: string; + stateDir: string; + ownerPid: number; + ownerStartTime: string | null; + abandonedAtMs?: number; +}): string { + return JSON.stringify({ + schemaVersion: 1, + device: { platform: params.platform, id: params.id, name: params.id, kind: 'device' }, + workspace: '/worktrees/owner', + ownerToken: 'owner-token', + createdAtMs: 1, + updatedAtMs: 1, + ...params, + }); +} + +async function statusDevices(claimsDir: string) { + const result = await runCliCapture(['device', 'status', '--json'], { + env: { AGENT_DEVICE_CLAIMS_DIR: claimsDir }, + }); + return JSON.parse(result.stdout).data as { + claims: { classification: string }[]; + devices: { + device: { id: string }; + acquirable: boolean; + blockedBy?: string; + owner?: { session: string }; + }[]; + }; +} + +test('status and open agree on an abandoned claim of a running daemon', async () => { + const claimsDir = mkdtempForTestSync('agent-device-cli-claims-'); + const owner = readCurrentOwnerIdentity(); + try { + const deviceKey = 'local:android:none:emulator-5562'; + fs.writeFileSync( + path.join(claimsDir, `${cryptoHashForTest(deviceKey)}.json`), + claimJson({ + deviceKey, + id: 'emulator-5562', + platform: 'android', + session: 'abandoned-session', + stateDir: process.cwd(), + ownerPid: owner.pid, + ownerStartTime: owner.startTime, + abandonedAtMs: 5, + }), + ); + + const [entry] = (await statusDevices(claimsDir)).devices; + const open = await openAdmissionFor(claimsDir, { id: 'emulator-5562', platform: 'android' }); + assert.equal(entry?.acquirable, false); + assert.equal(entry?.blockedBy, 'live-owner'); + assert.equal(open.acquirable, false); + assert.equal(entry?.owner?.session, open.session); + } finally { + fs.rmSync(claimsDir, { recursive: true, force: true }); + } +}); + +test('status and open agree on a claim stored under a noncanonical file name', async () => { + const claimsDir = mkdtempForTestSync('agent-device-cli-claims-'); + const owner = readCurrentOwnerIdentity(); + try { + fs.writeFileSync( + path.join(claimsDir, 'renamed.json'), + claimJson({ + deviceKey: 'local:android:none:emulator-5564', + id: 'emulator-5564', + platform: 'android', + session: 'renamed-session', + stateDir: process.cwd(), + ownerPid: owner.pid, + ownerStartTime: owner.startTime, + }), + ); + + const [entry] = (await statusDevices(claimsDir)).devices; + const open = await openAdmissionFor(claimsDir, { id: 'emulator-5564', platform: 'android' }); + assert.equal(open.acquirable, true); + assert.equal(entry?.acquirable, true); + } finally { + fs.rmSync(claimsDir, { recursive: true, force: true }); + } +}); + +test.skipIf(process.getuid?.() === 0)( + 'status and open agree that an unreadable claim root holds every device', + async () => { + const claimsDir = mkdtempForTestSync('agent-device-cli-claims-'); + try { + fs.chmodSync(claimsDir, 0o000); + const status = await statusDevices(claimsDir); + const open = await openAdmissionFor(claimsDir, { id: 'emulator-5566', platform: 'android' }); + assert.equal(open.acquirable, false); + // The root names no device, so status answers with the unreadable record, never acquirable. + assert.deepEqual(status.devices, []); + assert.deepEqual( + status.claims.map((claim) => claim.classification), + ['unknown'], + ); + } finally { + fs.chmodSync(claimsDir, 0o700); + fs.rmSync(claimsDir, { recursive: true, force: true }); + } + }, +); + +test('status and open name the host claim before the app claim', async () => { + const claimsDir = mkdtempForTestSync('agent-device-cli-claims-'); + const ownerStateDir = mkdtempForTestSync('agent-device-cli-claims-owner-'); + const owner = readCurrentOwnerIdentity(); + try { + const hostKey = 'local:web:none:chrome'; + const appId = 'chrome:app:com.example.app'; + const appKey = `local:web:none:${appId}`; + fs.writeFileSync( + path.join(claimsDir, `${cryptoHashForTest(hostKey)}.json`), + claimJson({ + deviceKey: hostKey, + id: 'chrome', + platform: 'web', + session: 'host-session', + stateDir: process.cwd(), + ownerPid: owner.pid, + ownerStartTime: owner.startTime, + }), + ); + fs.writeFileSync( + path.join(claimsDir, `${cryptoHashForTest(appKey)}.json`), + claimJson({ + deviceKey: appKey, + id: appId, + platform: 'web', + session: 'app-session', + stateDir: ownerStateDir, + ownerPid: 999_999_999, + ownerStartTime: 'old-start-time', + }), + ); + // A dead app owner with an open recording would refuse on its own; the live host claim wins. + screenRecordingDurableResource.store.write( + screenRecordingDurableResource.store.resolvePath( + path.join(ownerStateDir, 'sessions', 'app-session'), + ), + createDurableResourceEnvelope({ + resourceKind: 'screen-recording', + sessionId: 'app-session', + device: { id: appId, family: 'web', kind: 'device' }, + owner: localRuntimeOwner('web'), + fence: { token: 'fence', generation: 1 }, + lifecycle: 'open', + descriptor: { version: 1, body: {} }, + }), + ); + + const entry = (await statusDevices(claimsDir)).devices.find((d) => d.device.id === appId); + const open = await openAdmissionFor(claimsDir, { id: appId, platform: 'web' }); + assert.equal(open.session, 'host-session'); + assert.equal(entry?.blockedBy, 'live-owner'); + assert.equal(entry?.owner?.session, 'host-session'); + } finally { + fs.rmSync(claimsDir, { recursive: true, force: true }); + fs.rmSync(ownerStateDir, { recursive: true, force: true }); + } +}); + function cryptoHashForTest(deviceKey: string): string { return crypto.createHash('sha256').update(deviceKey).digest('hex'); } diff --git a/src/cli/commands/device.ts b/src/cli/commands/device.ts index ab366bf60d..b6f5e7702a 100644 --- a/src/cli/commands/device.ts +++ b/src/cli/commands/device.ts @@ -1,16 +1,20 @@ import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import { AppError } from '@agent-device/kernel/errors'; -import { publicPlatformString } from '@agent-device/kernel/device'; +import { publicPlatformString, type DeviceInfo } from '@agent-device/kernel/device'; import { deviceClaimOwnerCannotRelease, + deviceClaimRefusalReason, deviceClaimRequiresStaleInspection, inspectDeviceClaims, + type DeviceClaim, + type DeviceClaimRefusalReason, type InspectedDeviceClaim, type DeviceClaimStaleReleaseOutcome, } from '@agent-device/daemon-contracts/device-claims'; import { - inspectDeviceAcquirability, - type DeviceAcquirabilityBlockReason, + inspectNewSessionAdmission, + type ClaimRecoveryRetentionReason, + type DeviceClaimAdmission, } from '@agent-device/daemon-contracts/device-claim-recovery'; import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell'; import { writeCommandOutput } from './shared.ts'; @@ -23,14 +27,15 @@ export const deviceCommand: ClientCommandHandler = async ({ positionals, flags, throw new AppError('INVALID_ARGS', 'device accepts only: status, release'); } if (positionals[0] === 'release') return await runDeviceRelease(flags, host); - const selectors = { - platform: flags.platform, - device: flags.device, - udid: flags.udid, - serial: flags.serial, - }; - const inspectedClaims = inspectDeviceClaims(selectors, host.env); - const hasSelector = Object.values(selectors).some((value) => value !== undefined); + const inspectedClaims = inspectDeviceClaims( + { + platform: flags.platform, + device: flags.device, + udid: flags.udid, + serial: flags.serial, + }, + host.env, + ); const staleClaims = inspectedClaims.filter((claim) => deviceClaimRequiresStaleInspection(claim.classification), ); @@ -38,11 +43,7 @@ export const deviceCommand: ClientCommandHandler = async ({ positionals, flags, ? staleClaims : inspectedClaims.filter((claim) => !deviceClaimRequiresStaleInspection(claim.classification)); const claims = visible.map(serializeClaim); - const devices = await reportDeviceAcquirability( - inspectedClaims, - hasSelector ? inspectDeviceClaims({}, host.env) : inspectedClaims, - host.env, - ); + const devices = await reportDeviceAcquirability(inspectedClaims, host.env); const data = { claims, ...(flags.stale ? {} : { hiddenStaleClaims: staleClaims.length }), @@ -62,6 +63,8 @@ export const deviceCommand: ClientCommandHandler = async ({ positionals, flags, return true; }; +type DeviceAcquirabilityBlockReason = DeviceClaimRefusalReason | ClaimRecoveryRetentionReason; + type DeviceAcquirabilityReport = { deviceKey: string; device: Record; @@ -72,18 +75,20 @@ type DeviceAcquirabilityReport = { }; /** - * Whether a new session can take each device a selected claim names, weighed against every claim on - * the host, as `open` does, so a selector that hides a host's or an app's claim never hides its - * owner. One entry per device, in inspection order. + * Whether a new session can take each device a selected claim names, answered by the admission + * verdict acquisition checks first, so claim order, canonical claim paths and unreadable claims + * follow `open`. One entry per device, in inspection order. * * Every device a claim names is reported, including one whose only claims are the stale ones this * view hides: their owner being reclaimable is exactly why they are hidden, and a caller choosing a * device needs that answer without asking for the hidden records. A device no claim names is * acquirable and absent; `agent-device devices` is what enumerates devices. + * + * A reclaimable owner with an open durable resource is reported as blocked by that resource's + * pending cleanup: `open` settles it through recovery, which status never runs. */ async function reportDeviceAcquirability( inspectedClaims: readonly InspectedDeviceClaim[], - weighedClaims: readonly InspectedDeviceClaim[], env: EnvMap, ): Promise { const reports: DeviceAcquirabilityReport[] = []; @@ -93,23 +98,23 @@ async function reportDeviceAcquirability( const device = entry.claim?.device; if (!deviceKey || !device || seen.has(deviceKey)) continue; seen.add(deviceKey); - const acquirability = await inspectDeviceAcquirability({ - device, - claims: weighedClaims, + const { family, ...identity } = device; + const admission = await inspectNewSessionAdmission({ + device: { ...identity, platform: family } satisfies DeviceInfo, env, }); - const holder = acquirability.claim; + const { blockedBy, holder } = describeAdmission(admission); reports.push({ deviceKey, device: serializeClaimDevice(device), - acquirable: acquirability.acquirable, - ...(acquirability.blockedBy ? { blockedBy: acquirability.blockedBy } : {}), - ...(holder?.session + acquirable: blockedBy === undefined, + ...(blockedBy ? { blockedBy } : {}), + ...(holder ? { owner: { session: holder.session, - workspace: holder.workspace ?? '', - stateDir: holder.stateDir ?? '', + workspace: holder.workspace, + stateDir: holder.stateDir, }, } : {}), @@ -118,6 +123,24 @@ async function reportDeviceAcquirability( return reports; } +function describeAdmission(admission: DeviceClaimAdmission): { + blockedBy?: DeviceAcquirabilityBlockReason; + holder?: DeviceClaim; +} { + if (admission.status === 'refused') { + return { + blockedBy: + admission.retainedBy ?? deviceClaimRefusalReason(admission.conflict.classification), + holder: admission.conflict.claim, + }; + } + for (const { claim, recovery } of admission.reclaimed) { + const kind = recovery?.status === 'inspectable' ? recovery.recoveryKinds[0] : undefined; + if (kind) return { blockedBy: `${kind}-cleanup-pending`, holder: claim }; + } + return { holder: admission.reclaimed[0]?.claim }; +} + /** * `device release --stale`: settle and clear matching claims whose owner * provably cannot release them. Everything else fails closed and is reported diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 3c19d4e372..29bc2a2eab 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -311,7 +311,7 @@ Example: Device busy and ownership: DEVICE_IN_USE has two flavors. "already in use by session X" is this daemon's session table: reuse it with --session X, or run close --session X first. "owned by session X in workspace Y" is the host-global device claim another session — from this daemon or another worktree's daemon — or an in-flight command holds; there may be no session to close, and it is never retriable, so run the error's exact recovery command instead of retrying. - Inspect ownership without any daemon: agent-device device status (add --stale to list the claims it hides: dead, PID-reused, missing-state-directory, and daemon-replaced owners, some of which may still run; agent-device device release --stale settles and releases only owners proven unable to release). Its devices list inspects whether a new session can take each claimed device: acquirable true means no claim blocks it, false names the reason in blockedBy (live-owner, owner-pid-reused, owner-process-still-running, owner-liveness-unknown, claim-record-inconsistent, or a resource such as screen-recording-cleanup-pending that still waits for disposal). owner appears only when the blocking record decodes. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so open may decide differently. A dead owner that retains nothing does not block by itself, so hiddenStaleClaims alone never means the device is unavailable, but another live overlapping claim still can. devices marks rows that are claimed, so pick an unclaimed device instead of contending. + Inspect ownership without any daemon: agent-device device status (add --stale to list the claims it hides: dead, PID-reused, missing-state-directory, and daemon-replaced owners, some of which may still run; agent-device device release --stale settles and releases only owners proven unable to release). Its devices list inspects whether a new session can take each claimed device: acquirable true means no claim blocks it, false names the reason in blockedBy (live-owner, owner-pid-reused, owner-process-still-running, owner-liveness-unknown, claim-record-inconsistent, or a resource such as screen-recording-cleanup-pending that still waits for disposal). owner names the claim's owner when its record decodes: the holder that blocks the device, or, when acquirable, the reclaimable dead owner open would settle. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so open may decide differently, and a daemon's own abandoned claim, which status reports as blocked by that live owner, open through that same daemon may still take. A dead owner that retains nothing does not block by itself, so hiddenStaleClaims alone never means the device is unavailable, but another live overlapping claim still can. devices marks rows that are claimed, so pick an unclaimed device instead of contending. A live foreign owner is released by closing its session from its own workspace or stopping its daemon: agent-device daemon stop --state-dir (the error names the state dir). The device itself can settle a claim: when it rebooted after that claim was taken, its app, runner, and accessibility session were destroyed, so open reconciles the owner's resources, takes the claim, and reports the release in warnings. Never recover by hunting PIDs with ps/kill. boot/install/shutdown take the same claims as open and refuse foreign-claimed devices identically; they do not ask the device about its boot. Use snapshot, screenshot, logs, network, perf frames, and perf memory for device/app runtime evidence. Use react-devtools when component internals or React rendering performance matter.`, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index ba3875a034..a0d3cd3ff4 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -87,7 +87,7 @@ Select a device: Device claims and the daemon: - `device status` lists host-local device claims without starting or contacting a daemon; `--stale` shows the stale claims it hides by default (owner exited, PID reused, state directory deleted, or daemon replaced), some of whose owners may still be running. Scope it with `--platform` plus `--udid` (Apple) or `--serial` (Android). A claim held by another live or uncertain owner blocks `open`, unless the device rebooted after the claim was taken: then `open` settles that owner's durable resources, takes the claim, and reports the release in `warnings`. -- `device status --json` also reports each claimed device once, with `acquirable` for whether a new session can take it now. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so `open` may decide differently. When the device is not acquirable, `blockedBy` names why, and `owner` names the holder when that record decodes. A dead or replaced owner that retains no durable resource does not block by itself, so a non-zero `hiddenStaleClaims` alone does not mean the device is unavailable, but another live overlapping claim or pending resource cleanup still can. +- `device status --json` also reports each claimed device once, with `acquirable` for whether a new session can take it now. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so `open` may decide differently. When the device is not acquirable, `blockedBy` names why, and `owner` names the claim's owner when its record decodes: the holder that blocks the device or, on an acquirable device, the reclaimable dead owner `open` would settle. A daemon's own abandoned claim is reported as blocked by that live owner, but `open` through that same daemon may still take it. A dead or replaced owner that retains no durable resource does not block by itself, so a non-zero `hiddenStaleClaims` alone does not mean the device is unavailable, but another live overlapping claim or pending resource cleanup still can. - `device release --stale` settles the durable resources of an owner that provably can't release its claim (its process exited or a newer daemon replaced it), then clears the claim. Live, uncertain, PID-reused, corrupt, and deleted-state-directory claims are refused with the reason. See [Sessions](/docs/sessions#release-a-device-another-session-or-workspace-holds). - A command that needs the shared local daemon starts it for its state directory when none runs; `device status` and `device release --stale` never contact one. When the running daemon comes from another version or build, the command replaces it only if it reports no work: no request in flight, no session, no repair session and no live lease. A resumable upload still streaming and a host human-control hold that names no lease are not counted, so a replacement can end them. Otherwise the command fails with `daemon-busy` and leaves the daemon alone. A daemon from a release that predates this check is never replaced, and fails with `daemon-incompatible`. End a busy or older daemon deliberately with `daemon stop`. Node.js clients choose this per client; see [Daemon lifecycle](/docs/client-api#daemon-lifecycle). - `daemon stop --state-dir ` stops a detached local daemon with process signals after verifying its identity. `--clean` also removes the Apple runner processes and leases that daemon retained. diff --git a/website/docs/docs/sessions.md b/website/docs/docs/sessions.md index 4416fe099b..90c882b3ad 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -188,7 +188,9 @@ with `--platform` plus `--udid` (Apple) or `--serial` (Android). `--json` reports each claimed device once as `acquirable`, an inspection of whether a new session can take it now. It cannot see a reboot and runs no recovery, so `open` may decide differently. -`blockedBy` names why not, and `owner` identifies the holder when the blocking record decodes. A +`blockedBy` names why not, and `owner` identifies the claim's owner when its record decodes: the holder that blocks the device or, +on an acquirable device, the reclaimable dead owner `open` would settle. A daemon's own abandoned +claim is reported as blocked by that live owner, but `open` through that same daemon may still take it. A stale claim whose owner is provably gone and retains no resource does not block by itself, so a non-zero hidden stale-claim count is not a block on its own. Another live overlapping claim or pending resource cleanup still can. From aa910dfb32ffeecce033eb58f2cda82735873db3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 14 Nov 2026 14:34:58 +0100 Subject: [PATCH 6/8] refactor(device-claims): drop the owner-settlement helper the shared verdict replaced Co-Authored-By: Claude Opus 5.5 --- .../src/device-claim-settlement.ts | 34 ------------------- 1 file changed, 34 deletions(-) diff --git a/packages/daemon-contracts/src/device-claim-settlement.ts b/packages/daemon-contracts/src/device-claim-settlement.ts index 39c8c0145a..9f91dcdc1a 100644 --- a/packages/daemon-contracts/src/device-claim-settlement.ts +++ b/packages/daemon-contracts/src/device-claim-settlement.ts @@ -198,40 +198,6 @@ async function foreignClaimSettlement(params: { return tookOver ? { settles: true, tookOver } : { settles: false }; } -/** - * The owner half of the acquisition decision, asked of a claim somebody already inspected and - * answered by the same {@link foreignClaimSettlement} an acquisition runs. `settles` says the - * recorded owner cannot hold the device against a new session, so acquisition would take it once - * that claim's durable resources reach a terminal state — the caller answers that half. - * `conflicts` says a live or uncertain owner holds it. The caller-scoped halves an acquisition also - * weighs (`held` by this very session, an abandoned claim of this daemon) decide nothing about a - * NEW session, so they stay out of this question. A reporter that never touches the device omits - * `observeDeviceBoot` and therefore never reads a reboot as proof, exactly as `boot`, `install` and - * `shutdown` refuse a live foreign owner instead of asking. The device an acquisition targets only - * reaches the decision through `observeDeviceBoot`, so a caller that passes none needs no device of - * its own: the claim's own record describes the device the question is about. - */ -export async function inspectDeviceClaimOwnerSettlement(params: { - inspected: InspectedDeviceClaim; - observeDeviceBoot?: DeviceBootObservationService; -}): Promise<{ status: 'settles' } | { status: 'conflicts' }> { - const claim = params.inspected.claim; - if (!claim) return { status: 'conflicts' }; - const settlement = await foreignClaimSettlement({ - classification: params.inspected.classification, - claim, - device: deviceInfoFromClaim(claim), - observeDeviceBoot: params.observeDeviceBoot, - }); - return settlement.settles ? { status: 'settles' } : { status: 'conflicts' }; -} - -/** The device a claim's record describes, in the shape a boot observation asks for. */ -function deviceInfoFromClaim(claim: DeviceClaim): DeviceInfo { - const { family, ...identity } = claim.device; - return { ...identity, platform: family }; -} - /** * Clears the claim only once its durable resources are settled, so a claim never disappears while * something owned by its session is still running. From 693882c1757c73ef74cd451f7c68d55ef2d8fea8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 14 Nov 2026 15:00:04 +0100 Subject: [PATCH 7/8] docs(device-status): say hiddenStaleClaims is not an availability signal The sentence claimed a hidden stale claim alone never means a device is unavailable. Only a dead or superseded owner settles, so a hidden claim whose owner PID was reused, or whose state directory is gone, still reports acquirable:false and `open` refuses it with DEVICE_IN_USE, as does a dead owner whose recording still awaits disposal. State one rule in the owning help text and match both docs pages: the count names hidden records and answers nothing about availability, so read acquirable. Name the hidden owner kinds and pending cleanup that do block. Co-Authored-By: Claude Opus 5.5 --- src/commands/schema/cli-help.ts | 2 +- website/docs/docs/commands.md | 2 +- website/docs/docs/sessions.md | 13 +++++++------ 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 29bc2a2eab..eec2f27b69 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -311,7 +311,7 @@ Example: Device busy and ownership: DEVICE_IN_USE has two flavors. "already in use by session X" is this daemon's session table: reuse it with --session X, or run close --session X first. "owned by session X in workspace Y" is the host-global device claim another session — from this daemon or another worktree's daemon — or an in-flight command holds; there may be no session to close, and it is never retriable, so run the error's exact recovery command instead of retrying. - Inspect ownership without any daemon: agent-device device status (add --stale to list the claims it hides: dead, PID-reused, missing-state-directory, and daemon-replaced owners, some of which may still run; agent-device device release --stale settles and releases only owners proven unable to release). Its devices list inspects whether a new session can take each claimed device: acquirable true means no claim blocks it, false names the reason in blockedBy (live-owner, owner-pid-reused, owner-process-still-running, owner-liveness-unknown, claim-record-inconsistent, or a resource such as screen-recording-cleanup-pending that still waits for disposal). owner names the claim's owner when its record decodes: the holder that blocks the device, or, when acquirable, the reclaimable dead owner open would settle. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so open may decide differently, and a daemon's own abandoned claim, which status reports as blocked by that live owner, open through that same daemon may still take. A dead owner that retains nothing does not block by itself, so hiddenStaleClaims alone never means the device is unavailable, but another live overlapping claim still can. devices marks rows that are claimed, so pick an unclaimed device instead of contending. + Inspect ownership without any daemon: agent-device device status (add --stale to list the claims it hides: dead, PID-reused, missing-state-directory, and daemon-replaced owners, some of which may still run; agent-device device release --stale settles and releases only owners proven unable to release). Its devices list inspects whether a new session can take each claimed device: acquirable true means no claim blocks it, false names the reason in blockedBy (live-owner, owner-pid-reused, owner-process-still-running, owner-liveness-unknown, claim-record-inconsistent, or a resource such as screen-recording-cleanup-pending that still waits for disposal). owner names the claim's owner when its record decodes: the holder that blocks the device, or, when acquirable, the reclaimable dead owner open would settle. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so open may decide differently, and a daemon's own abandoned claim, which status reports as blocked by that live owner, open through that same daemon may still take. A dead or replaced owner that retains nothing does not block by itself. hiddenStaleClaims counts the claim records this view hides and is not an availability signal, so read acquirable: a hidden owner whose PID was reused or whose state directory is gone, and pending resource cleanup, each still block the device. devices marks rows that are claimed, so pick an unclaimed device instead of contending. A live foreign owner is released by closing its session from its own workspace or stopping its daemon: agent-device daemon stop --state-dir (the error names the state dir). The device itself can settle a claim: when it rebooted after that claim was taken, its app, runner, and accessibility session were destroyed, so open reconciles the owner's resources, takes the claim, and reports the release in warnings. Never recover by hunting PIDs with ps/kill. boot/install/shutdown take the same claims as open and refuse foreign-claimed devices identically; they do not ask the device about its boot. Use snapshot, screenshot, logs, network, perf frames, and perf memory for device/app runtime evidence. Use react-devtools when component internals or React rendering performance matter.`, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index a0d3cd3ff4..41e2ca2218 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -87,7 +87,7 @@ Select a device: Device claims and the daemon: - `device status` lists host-local device claims without starting or contacting a daemon; `--stale` shows the stale claims it hides by default (owner exited, PID reused, state directory deleted, or daemon replaced), some of whose owners may still be running. Scope it with `--platform` plus `--udid` (Apple) or `--serial` (Android). A claim held by another live or uncertain owner blocks `open`, unless the device rebooted after the claim was taken: then `open` settles that owner's durable resources, takes the claim, and reports the release in `warnings`. -- `device status --json` also reports each claimed device once, with `acquirable` for whether a new session can take it now. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so `open` may decide differently. When the device is not acquirable, `blockedBy` names why, and `owner` names the claim's owner when its record decodes: the holder that blocks the device or, on an acquirable device, the reclaimable dead owner `open` would settle. A daemon's own abandoned claim is reported as blocked by that live owner, but `open` through that same daemon may still take it. A dead or replaced owner that retains no durable resource does not block by itself, so a non-zero `hiddenStaleClaims` alone does not mean the device is unavailable, but another live overlapping claim or pending resource cleanup still can. +- `device status --json` also reports each claimed device once, with `acquirable` for whether a new session can take it now. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so `open` may decide differently. `blockedBy` names why a device is not acquirable. `owner` names the claim's owner when its record decodes: the holder that blocks the device or, on an acquirable device, the reclaimable dead owner `open` would settle. A daemon's own abandoned claim is reported as blocked by that live owner, but `open` through that same daemon may still take it. A dead or replaced owner that retains no durable resource does not block by itself. `hiddenStaleClaims` counts the claim records this view hides and is not an availability signal, so read `acquirable`: a hidden owner whose PID was reused or whose state directory is gone, and pending resource cleanup, each still block the device. - `device release --stale` settles the durable resources of an owner that provably can't release its claim (its process exited or a newer daemon replaced it), then clears the claim. Live, uncertain, PID-reused, corrupt, and deleted-state-directory claims are refused with the reason. See [Sessions](/docs/sessions#release-a-device-another-session-or-workspace-holds). - A command that needs the shared local daemon starts it for its state directory when none runs; `device status` and `device release --stale` never contact one. When the running daemon comes from another version or build, the command replaces it only if it reports no work: no request in flight, no session, no repair session and no live lease. A resumable upload still streaming and a host human-control hold that names no lease are not counted, so a replacement can end them. Otherwise the command fails with `daemon-busy` and leaves the daemon alone. A daemon from a release that predates this check is never replaced, and fails with `daemon-incompatible`. End a busy or older daemon deliberately with `daemon stop`. Node.js clients choose this per client; see [Daemon lifecycle](/docs/client-api#daemon-lifecycle). - `daemon stop --state-dir ` stops a detached local daemon with process signals after verifying its identity. `--clean` also removes the Apple runner processes and leases that daemon retained. diff --git a/website/docs/docs/sessions.md b/website/docs/docs/sessions.md index 90c882b3ad..f8540e6caa 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -188,12 +188,13 @@ with `--platform` plus `--udid` (Apple) or `--serial` (Android). `--json` reports each claimed device once as `acquirable`, an inspection of whether a new session can take it now. It cannot see a reboot and runs no recovery, so `open` may decide differently. -`blockedBy` names why not, and `owner` identifies the claim's owner when its record decodes: the holder that blocks the device or, -on an acquirable device, the reclaimable dead owner `open` would settle. A daemon's own abandoned -claim is reported as blocked by that live owner, but `open` through that same daemon may still take it. A -stale claim whose owner is provably gone and retains no resource does not block by itself, so a -non-zero hidden stale-claim count is not a block on its own. Another live overlapping claim or -pending resource cleanup still can. +`blockedBy` names why not, and `owner` identifies the claim's owner when its record decodes: the +holder that blocks the device or, on an acquirable device, the reclaimable dead owner `open` would +settle. A daemon's own abandoned claim is reported as blocked by that live owner, but `open` through +that same daemon may still take it. A stale claim whose owner is provably gone and retains no resource +does not block by itself. `hiddenStaleClaims` counts the claim records this view hides and is not an +availability signal, so read `acquirable`: a hidden owner whose PID was reused or whose state +directory is gone, and pending resource cleanup, each still block the device. To free a device: From fd61024fcfbfb151cf3124789b0e74575c285e6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 14 Nov 2026 15:00:04 +0100 Subject: [PATCH 8/8] fix(device-status): report acquirability only where it is read Acquirability is a --json answer, and each device weighs every claim, so the human view, which renders claims and notices, should not pay for it. Drop the claim that a device no claim names is acquirable: a device can be unreported for another reason, such as a host whose live claims name only its own app devices. Say what the agreement tests pin: the shared inspection, asked as `open` asks it, not a claim taken through `acquireDeviceClaim`. Note why the reporter's acquirer is deliberately unadoptable. Co-Authored-By: Claude Opus 5.5 --- .../daemon-contracts/src/device-claim-admission.ts | 3 +++ src/__tests__/cli-device-status.test.ts | 5 +++-- src/cli/commands/device.ts | 10 +++++++--- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/packages/daemon-contracts/src/device-claim-admission.ts b/packages/daemon-contracts/src/device-claim-admission.ts index b1c3a53365..eff6cbb1ab 100644 --- a/packages/daemon-contracts/src/device-claim-admission.ts +++ b/packages/daemon-contracts/src/device-claim-admission.ts @@ -63,6 +63,9 @@ export async function inspectNewSessionAdmission(params: { device: DeviceInfo; env: EnvMap; }): Promise { + // The acquirer below is deliberately unadoptable: no claim records this session, workspace, or + // state dir, so every half of the decision that asks "is this claim already the caller's?" answers + // no, which is the question a reporter with no session of its own must ask. return await inspectDeviceClaimAdmission({ device: params.device, command: 'open', diff --git a/src/__tests__/cli-device-status.test.ts b/src/__tests__/cli-device-status.test.ts index b78f1bac09..ed1e32800b 100644 --- a/src/__tests__/cli-device-status.test.ts +++ b/src/__tests__/cli-device-status.test.ts @@ -228,8 +228,9 @@ test('a device selector still weighs the host claim that overlaps the selected a } }); -// Status and `open` read one admission verdict. These tests ask it the way `open` does, as a session of -// another daemon, and require the status report to name the same refusal. +// Status and `open` read one admission verdict. These tests pin the status report to that shared +// inspection, asked as `open` asks it — as a session of another daemon — rather than to a claim +// actually taken through `acquireDeviceClaim`, which would also settle the claim under test. async function openAdmissionFor( claimsDir: string, device: { id: string; platform: 'android' | 'web' }, diff --git a/src/cli/commands/device.ts b/src/cli/commands/device.ts index b6f5e7702a..bbf4fb2981 100644 --- a/src/cli/commands/device.ts +++ b/src/cli/commands/device.ts @@ -43,7 +43,9 @@ export const deviceCommand: ClientCommandHandler = async ({ positionals, flags, ? staleClaims : inspectedClaims.filter((claim) => !deviceClaimRequiresStaleInspection(claim.classification)); const claims = visible.map(serializeClaim); - const devices = await reportDeviceAcquirability(inspectedClaims, host.env); + // Acquirability is a --json answer: each device weighs every claim, so the human view, which + // renders claims and notices, never pays for it. + const devices = flags.json ? await reportDeviceAcquirability(inspectedClaims, host.env) : []; const data = { claims, ...(flags.stale ? {} : { hiddenStaleClaims: staleClaims.length }), @@ -81,8 +83,10 @@ type DeviceAcquirabilityReport = { * * Every device a claim names is reported, including one whose only claims are the stale ones this * view hides: their owner being reclaimable is exactly why they are hidden, and a caller choosing a - * device needs that answer without asking for the hidden records. A device no claim names is - * acquirable and absent; `agent-device devices` is what enumerates devices. + * device needs that answer without asking for the hidden records. A device no claim names is absent; + * `agent-device devices` is what enumerates devices. Only a reported entry carries an answer, so a + * device that is unreported for another reason, such as a host whose live claims name only its own + * app devices, is not thereby acquirable. * * A reclaimable owner with an open durable resource is reported as blocked by that resource's * pending cleanup: `open` settles it through recovery, which status never runs.