Skip to content
Merged
186 changes: 186 additions & 0 deletions packages/daemon-contracts/src/device-claim-admission.test.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType<typeof admissionFor>>): 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: [] });
});
78 changes: 78 additions & 0 deletions packages/daemon-contracts/src/device-claim-admission.ts
Original file line number Diff line number Diff line change
@@ -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<DeviceClaimAdmission> {
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<DeviceClaimAdmission> {
// 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,
});
}
41 changes: 41 additions & 0 deletions packages/daemon-contracts/src/device-claim-inspection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<DeviceClaimClassification, DeviceClaimRefusalReason>
> = 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
Expand Down
16 changes: 14 additions & 2 deletions packages/daemon-contracts/src/device-claim-reconciliation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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' };
Expand Down
24 changes: 24 additions & 0 deletions packages/daemon-contracts/src/device-claim-recovery.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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<typeof InspectDeviceClaimAdmission>[0],
): Promise<DeviceClaimAdmission> {
return (await import('./device-claim-admission.ts')).inspectDeviceClaimAdmission(params);
}

export async function inspectNewSessionAdmission(
params: Parameters<typeof InspectNewSessionAdmission>[0],
): Promise<DeviceClaimAdmission> {
return (await import('./device-claim-admission.ts')).inspectNewSessionAdmission(params);
}
Loading
Loading