diff --git a/packages/daemon-contracts/src/device-claim-admission.test.ts b/packages/daemon-contracts/src/device-claim-admission.test.ts new file mode 100644 index 0000000000..7cdcc7e6fc --- /dev/null +++ b/packages/daemon-contracts/src/device-claim-admission.test.ts @@ -0,0 +1,186 @@ +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 { inspectNewSessionAdmission } from './device-claim-admission.ts'; +import { canonicalLocalDeviceKey, resolveDeviceClaimPath } from './device-claim-paths.ts'; +import { writeDeviceClaim } from './device-claim-store.ts'; +import { deviceClaimRefusalReason, type DeviceClaim } from './device-claims.ts'; +import { hostAppDeviceId, type DeviceIdentity, type DeviceInfo } 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-admission-'); + 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); +} + +function infoOf(device: DeviceIdentity): DeviceInfo { + const { family, ...rest } = device; + return { ...rest, platform: family, name: device.id }; +} + +/** 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 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 admitted', async () => { + const stateDir = useClaimsRoot(); + writeDeviceClaim(deadClaim(DEVICE, stateDir), process.env); + + 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 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); + + assert.equal(refusedReason(await admissionFor(app)), 'live-owner'); +}); + +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); + 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 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 resource reached its terminal state needs no recovery', 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 } }, + }), + ); + + 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 refuses 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, '{'); + + assert.equal(refusedReason(await admissionFor(DEVICE)), 'app-log-descriptor-invalid'); +}); + +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'); + + assert.equal(refusedReason(await admissionFor(DEVICE)), 'claim-record-inconsistent'); + const other: DeviceIdentity = { id: 'emulator-5556', family: 'android', kind: 'emulator' }; + assert.deepEqual(await admissionFor(other), { status: 'admitted', reclaimed: [] }); +}); + +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 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..eff6cbb1ab --- /dev/null +++ b/packages/daemon-contracts/src/device-claim-admission.ts @@ -0,0 +1,78 @@ +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 { + // 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', + session: 'device-status', + workspace: path.sep, + stateDir: '', + env: params.env, + coveredClaimIsOwnedByRequest: () => false, + }); +} diff --git a/packages/daemon-contracts/src/device-claim-inspection.ts b/packages/daemon-contracts/src/device-claim-inspection.ts index 59c979ef32..b0e681b442 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 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 + * 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-recovery.ts b/packages/daemon-contracts/src/device-claim-recovery.ts index 6b273ef119..ca591a71d9 100644 --- a/packages/daemon-contracts/src/device-claim-recovery.ts +++ b/packages/daemon-contracts/src/device-claim-recovery.ts @@ -1,4 +1,12 @@ +import type { + 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 { ClaimRecoveryRetentionReason, DeviceClaimAdmission }; export { inspectDeviceClaimRecovery, type ClaimRecoveryInspection, @@ -8,3 +16,19 @@ export { type OwnerScopedClaimRecoveryComposer, } from './device-claim-owner-recovery.ts'; export { createRecoveryPlatformScope } from './recovery-platform-scope.ts'; + +/** + * 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 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 741e74de0a..3072743a63 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, @@ -52,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'; @@ -86,7 +89,7 @@ export type TransientDeviceClaimResult = | DeviceClaimAcquireResult | { status: 'covered-by-owned-claim' }; -type ClaimAcquisitionInspectionParams = { +export type ClaimAcquisitionInspectionParams = { device: DeviceInfo; command: string; session: string; @@ -589,7 +592,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 +625,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/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/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..ed1e32800b 100644 --- a/src/__tests__/cli-device-status.test.ts +++ b/src/__tests__/cli-device-status.test.ts @@ -1,9 +1,14 @@ 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 { inspectDeviceClaimAdmission } from '@agent-device/daemon-contracts/device-claim-recovery'; import { runCliCapture } from './cli-capture.ts'; import { mkdtempForTestSync, @@ -18,7 +23,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 +105,327 @@ 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.reclaimable.owner.session, 'session-reclaimable'); + 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 }); + } +}); + +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 }); + } +}); + +// 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' }, +) { + 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'); +} + 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..bbf4fb2981 100644 --- a/src/cli/commands/device.ts +++ b/src/cli/commands/device.ts @@ -1,13 +1,21 @@ -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 { 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 { + 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'; import type { CliFlags } from '@agent-device/contracts/command'; @@ -31,14 +39,17 @@ 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); + // 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 }), + devices, }; await writeCommandOutput(flags, data, () => renderDeviceStatus(claims, { @@ -54,6 +65,86 @@ export const deviceCommand: ClientCommandHandler = async ({ positionals, flags, return true; }; +type DeviceAcquirabilityBlockReason = DeviceClaimRefusalReason | ClaimRecoveryRetentionReason; + +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 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 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. + */ +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 { family, ...identity } = device; + const admission = await inspectNewSessionAdmission({ + device: { ...identity, platform: family } satisfies DeviceInfo, + env, + }); + const { blockedBy, holder } = describeAdmission(admission); + reports.push({ + deviceKey, + device: serializeClaimDevice(device), + acquirable: blockedBy === undefined, + ...(blockedBy ? { blockedBy } : {}), + ...(holder + ? { + owner: { + session: holder.session, + workspace: holder.workspace, + stateDir: holder.stateDir, + }, + } + : {}), + }); + } + 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 869e8455b6..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 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 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 f0abcae1df..41e2ca2218 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. 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 e9d85bf3f8..f8540e6caa 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -186,6 +186,16 @@ 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 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. `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: - If the owner is still running, close its session from its own workspace, or stop its daemon with