Skip to content

Commit 1767adc

Browse files
thymikeeclaude
andcommitted
fix(exec): run on the captured HostEnvironment after the host migration
#3763 and #3798 made claim storage and recovery read an explicit host. exec now takes the host from the CLI entry like web does, and passes host.env and host.cwd to the claim store, the recovery gateway, device inventory, and the child process. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent cac07aa commit 1767adc

7 files changed

Lines changed: 62 additions & 36 deletions

File tree

‎packages/daemon-contracts/src/device-claims-wrapper.test.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ function useClaimsRoot(): string {
4444
}
4545

4646
function storedClaimFile(): string {
47-
return resolveDeviceClaimPath(canonicalLocalDeviceKey(device));
47+
return resolveDeviceClaimPath(canonicalLocalDeviceKey(device), process.env);
4848
}
4949

5050
/**
@@ -65,6 +65,7 @@ test('a wrapper claim records its owner kind and names the wrapped command', asy
6565
const root = useClaimsRoot();
6666
const acquired = await acquireWrapperDeviceClaim({
6767
device,
68+
env: process.env,
6869
command: 'expo',
6970
workspace: '/worktrees/wrapper',
7071
stateDir: root,
@@ -73,7 +74,7 @@ test('a wrapper claim records its owner kind and names the wrapped command', asy
7374
assert.equal(acquired.status, 'acquired');
7475
const stored = JSON.parse(fs.readFileSync(storedClaimFile(), 'utf8')) as Record<string, unknown>;
7576
assert.equal(stored.claimOwnerKind, 'wrapper');
76-
const inspected = inspectDeviceClaims({ serial: device.id })[0];
77+
const inspected = inspectDeviceClaims({ serial: device.id }, process.env)[0];
7778
assert.equal(inspected?.claim?.session, 'exec:expo');
7879
assert.equal(inspected?.claim?.ownerPid, process.pid);
7980
assert.equal(inspected?.classification, 'live');
@@ -89,6 +90,7 @@ test('a live wrapper claim survives a daemon registration published for its stat
8990
fs.mkdirSync(stateDir, { recursive: true });
9091
const wrapper = await acquireWrapperDeviceClaim({
9192
device,
93+
env: process.env,
9294
command: 'expo',
9395
workspace: '/worktrees/wrapper',
9496
stateDir,
@@ -101,6 +103,7 @@ test('a live wrapper claim survives a daemon registration published for its stat
101103

102104
const second = await acquireDeviceClaim({
103105
device,
106+
env: process.env,
104107
session: 'foreign-session',
105108
workspace: '/worktrees/foreign',
106109
stateDir: path.join(root, 'foreign-state'),
@@ -122,6 +125,7 @@ test('a daemon-served claim is still reclaimed from a superseded registration',
122125
fs.mkdirSync(stateDir, { recursive: true });
123126
const seeded = await acquireDeviceClaim({
124127
device,
128+
env: process.env,
125129
session: 'superseded-daemon-session',
126130
workspace: '/w',
127131
stateDir,
@@ -134,6 +138,7 @@ test('a daemon-served claim is still reclaimed from a superseded registration',
134138

135139
const second = await acquireDeviceClaim({
136140
device,
141+
env: process.env,
137142
session: 'successor-session',
138143
workspace: '/w',
139144
stateDir,

‎packages/daemon-contracts/src/device-claims.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,12 +129,14 @@ export async function acquireWrapperDeviceClaim(params: {
129129
command: string;
130130
workspace: string;
131131
stateDir: string;
132+
env: EnvMap;
132133
reconcileOrphanedDeviceClaim: DeviceClaimReconciler;
133134
}): Promise<DeviceClaimAcquireResult> {
134135
const identity = deviceClaimIdentity(params.device);
135136
const deviceKey = canonicalLocalDeviceKey(identity);
136137
return await withDeviceClaimLock(
137138
deviceKey,
139+
params.env,
138140
async () =>
139141
await claimHeldDevice({
140142
...params,

‎src/cli.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@ async function runCliOnHost(argv: string[], deps: CliDeps, host: HostEnvironment
203203
await runExecCommand(positionals, {
204204
flags: ctx.effectiveFlags,
205205
stateDir: ctx.daemonPaths.baseDir,
206+
host,
206207
}),
207208
);
208209
return;

‎src/cli/commands/__tests__/exec-cli-fixture.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import fs from 'node:fs';
22
import path from 'node:path';
33
import { withTestDeviceInventory } from '@agent-device/device-selection/inventory-gateways-fixtures';
4-
import { ANDROID_EMULATOR } from '@agent-device/test-kit';
4+
import { ANDROID_EMULATOR, createTestHostEnvironment } from '@agent-device/test-kit';
55
import type { CliFlags } from '@agent-device/contracts/command';
66
import { runExecCommand } from '../exec.ts';
77

@@ -36,6 +36,11 @@ fs.mkdirSync(path.join(stateDir, 'exec'), { recursive: true });
3636
// outlives the direct child is exactly what must not keep the device fenced.
3737
const exitCode = await withTestDeviceInventory(
3838
{ local: async () => [ANDROID_EMULATOR] },
39-
async () => await runExecCommand(['sh', '-c', 'sleep 10'], { flags, stateDir }),
39+
async () =>
40+
await runExecCommand(['sh', '-c', 'sleep 10'], {
41+
flags,
42+
stateDir,
43+
host: createTestHostEnvironment(),
44+
}),
4045
);
4146
process.exit(exitCode);

‎src/cli/commands/__tests__/exec-hup-fixture.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import fs from 'node:fs';
22
import path from 'node:path';
33
import { withTestDeviceInventory } from '@agent-device/device-selection/inventory-gateways-fixtures';
4-
import { ANDROID_EMULATOR } from '@agent-device/test-kit';
4+
import { ANDROID_EMULATOR, createTestHostEnvironment } from '@agent-device/test-kit';
55
import type { CliFlags } from '@agent-device/contracts/command';
66
import { runExecCommand } from '../exec.ts';
77

@@ -39,6 +39,7 @@ const exitCode = await withTestDeviceInventory(
3939
await runExecCommand(['sh', '-c', `echo $$ > ${JSON.stringify(childPidFile)}; exec sleep 8`], {
4040
flags,
4141
stateDir,
42+
host: createTestHostEnvironment(),
4243
}),
4344
);
4445
process.exit(exitCode);

‎src/cli/commands/__tests__/exec.test.ts‎

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ import crypto from 'node:crypto';
33
import fs from 'node:fs';
44
import path from 'node:path';
55
import { afterEach, test } from 'vitest';
6-
import { ANDROID_EMULATOR, mkdtempForTestSync } from '@agent-device/test-kit';
6+
import {
7+
ANDROID_EMULATOR,
8+
createTestHostEnvironment,
9+
mkdtempForTestSync,
10+
} from '@agent-device/test-kit';
711
import { withTestDeviceInventory } from '@agent-device/device-selection/inventory-gateways-fixtures';
812
import {
913
acquireDeviceClaim,
@@ -68,7 +72,12 @@ function runExec(args: readonly string[], dirs: ExecDirs): RunningExec {
6872
return [ANDROID_EMULATOR];
6973
},
7074
},
71-
async () => await runExecCommand(args, { flags: execFlags(), stateDir: dirs.stateDir }),
75+
async () =>
76+
await runExecCommand(args, {
77+
flags: execFlags(),
78+
stateDir: dirs.stateDir,
79+
host: createTestHostEnvironment(),
80+
}),
7281
);
7382
return { promise, inventoryReady: () => inventoryReady };
7483
}
@@ -90,7 +99,7 @@ function storedClaim(claimsDir: string): Record<string, unknown> | undefined {
9099
}
91100

92101
function claimEntry(): ReturnType<typeof inspectDeviceClaims>[number] | undefined {
93-
return inspectDeviceClaims({ serial: ANDROID_EMULATOR.id })[0];
102+
return inspectDeviceClaims({ serial: ANDROID_EMULATOR.id }, process.env)[0];
94103
}
95104

96105
/**
@@ -101,6 +110,7 @@ async function foreignAcquireAttempt(dirs: ExecDirs): Promise<unknown> {
101110
return await withTestDeviceInventory({ local: async () => [] }, async () =>
102111
acquireDeviceClaim({
103112
device: ANDROID_EMULATOR,
113+
env: process.env,
104114
session: 'other-workspace',
105115
workspace: '/worktrees/other',
106116
stateDir: path.join(dirs.stateDir, 'other'),
@@ -206,20 +216,14 @@ test('runs a command named by relative path and reports a missing command as she
206216
const script = path.join(dirs.stateDir, 'build.sh');
207217
fs.writeFileSync(script, '#!/bin/sh\nexit 3\n');
208218
fs.chmodSync(script, 0o755);
209-
const previousCwd = process.cwd();
210219
const exitCode = await withTestDeviceInventory(
211220
{ local: async () => [ANDROID_EMULATOR] },
212-
async () => {
213-
process.chdir(dirs.stateDir);
214-
try {
215-
return await runExecCommand(['./build.sh'], {
216-
flags: execFlags(),
217-
stateDir: dirs.stateDir,
218-
});
219-
} finally {
220-
process.chdir(previousCwd);
221-
}
222-
},
221+
async () =>
222+
await runExecCommand(['./build.sh'], {
223+
flags: execFlags(),
224+
stateDir: dirs.stateDir,
225+
host: createTestHostEnvironment({ cwd: dirs.stateDir }),
226+
}),
223227
);
224228
assert.equal(exitCode, 3);
225229
assert.equal(storedClaim(dirs.claimsDir), undefined);
@@ -243,6 +247,7 @@ test('refuses to start while a foreign live claim holds the device, and runs aft
243247
const foreign = await withTestDeviceInventory({ local: async () => [] }, async () =>
244248
acquireDeviceClaim({
245249
device: ANDROID_EMULATOR,
250+
env: process.env,
246251
session: 'other-workspace',
247252
workspace: '/worktrees/other',
248253
stateDir: foreignStateDir,
@@ -263,7 +268,7 @@ test('refuses to start while a foreign live claim holds the device, and runs aft
263268
});
264269
assert.equal(claimEntry()?.claim?.session, 'other-workspace');
265270

266-
await clearDeviceClaim(foreign.ownership);
271+
await clearDeviceClaim(foreign.ownership, process.env);
267272
assert.equal(await runExec(['true'], dirs).promise, 0);
268273
assert.equal(storedClaim(dirs.claimsDir), undefined);
269274
});

‎src/cli/commands/exec.ts‎

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import path from 'node:path';
33
import os from 'node:os';
44
import type { CliFlags } from '@agent-device/contracts/command';
55
import type { DeviceInfo } from '@agent-device/kernel/device';
6+
import type { HostEnvironment } from '@agent-device/kernel/source-value';
67
import { AppError } from '@agent-device/kernel/errors';
78
import {
89
acquireWrapperDeviceClaim,
@@ -28,6 +29,8 @@ export type ExecCommandOptions = Readonly<{
2829
flags: CliFlags;
2930
/** The CLI's resolved daemon state dir; the wrapper's claim lives under it. */
3031
stateDir: string;
32+
/** The host captured at the CLI entry point; it locates the claim store and the workspace. */
33+
host: HostEnvironment;
3134
}>;
3235

3336
/**
@@ -68,12 +71,12 @@ export async function runExecCommand(
6871
}
6972
const termination = attachSignalForwarding();
7073
try {
71-
const device = await resolveExecDevice(options.flags);
74+
const device = await resolveExecDevice(options.flags, options.host);
7275
if (termination.signal) return signalExitCode(termination.signal);
7376
const ownership = await acquireExecDeviceClaim(device, command, options);
7477
try {
7578
if (termination.signal) return signalExitCode(termination.signal);
76-
return await runClaimedChild(command, args, termination);
79+
return await runClaimedChild(command, args, termination, options.host);
7780
} catch (error) {
7881
// A command missing from PATH is the child failing to start; shells report
7982
// that as 127, and `exec` promises the command's exit code.
@@ -83,21 +86,21 @@ export async function runExecCommand(
8386
}
8487
throw error;
8588
} finally {
86-
await releaseExecDeviceClaim(ownership);
89+
await releaseExecDeviceClaim(ownership, options.host);
8790
}
8891
} finally {
8992
termination.dispose();
9093
}
9194
}
9295

93-
async function resolveExecDevice(flags: CliFlags): Promise<DeviceInfo> {
96+
async function resolveExecDevice(flags: CliFlags, host: HostEnvironment): Promise<DeviceInfo> {
9497
if (hasDeviceInventoryContext()) return await resolveTargetDevice(flags);
9598
// Claims exist only for local devices, so the wrapper composes the local
9699
// inventory itself; a scope installed by a host (a test or embedding caller)
97100
// is reused as-is. Platform modules are named by the gateway composition, so
98101
// it is imported only on this path.
99102
const { createPlatformDeviceInventoryGateways } = await import('../../platform-runtime.ts');
100-
const gateways = await createPlatformDeviceInventoryGateways();
103+
const gateways = await createPlatformDeviceInventoryGateways(host);
101104
return await withDeviceInventoryContext(
102105
{ ...gateways, requestScope: createRecoveryPlatformScope() },
103106
async () => await resolveTargetDevice(flags),
@@ -114,15 +117,17 @@ async function acquireExecDeviceClaim(
114117
// common claim-free path stays as light as `device release --stale` keeps it.
115118
const { createOwnerScopedDeviceClaimReconciler } =
116119
await import('@agent-device/daemon-contracts/device-claim-recovery');
117-
const { createClaimRecoveryGateway } = await import('../../platform-runtime-claim-recovery.ts');
120+
const { createClaimRecoveryGatewayFor } =
121+
await import('../../platform-runtime-claim-recovery.ts');
118122
const result = await acquireWrapperDeviceClaim({
119123
device,
120124
command,
121-
workspace: process.cwd(),
125+
workspace: options.host.cwd,
122126
stateDir: prepareExecClaimStateDir(options.stateDir),
127+
env: options.host.env,
123128
reconcileOrphanedDeviceClaim: createOwnerScopedDeviceClaimReconciler({
124129
scope: createRecoveryPlatformScope(),
125-
composeGateway: createClaimRecoveryGateway,
130+
composeGateway: createClaimRecoveryGatewayFor(options.host),
126131
}),
127132
});
128133
if (result.status === 'conflict') throw deviceClaimConflictError(device, result.conflict);
@@ -145,20 +150,19 @@ async function runClaimedChild(
145150
command: string,
146151
args: readonly string[],
147152
termination: SignalForwarding,
153+
host: HostEnvironment,
148154
): Promise<number> {
149155
// A build tool named with a path (`./gradlew`, `./scripts/build.sh`) is how the
150156
// fence is used day to day; resolve it against the cwd the way a shell would,
151157
// because the spawn helper keeps bare PATH names and absolute paths only.
152158
const executable =
153-
!path.isAbsolute(command) && command.includes('/')
154-
? path.resolve(process.cwd(), command)
155-
: command;
159+
!path.isAbsolute(command) && command.includes('/') ? path.resolve(host.cwd, command) : command;
156160
// The child leads its own process group so a forwarded signal reaches the
157161
// build tools it spawns — the grandchildren the fence exists to cover — not
158162
// just its direct process.
159163
const child = runCmdBackground(executable, args, {
160-
cwd: process.cwd(),
161-
env: process.env,
164+
cwd: host.cwd,
165+
env: host.env,
162166
stdio: 'inherit',
163167
captureOutput: false,
164168
allowFailure: true,
@@ -231,10 +235,13 @@ function signalExitCode(signal: NodeJS.Signals): number {
231235
return 128 + (signum ?? 0);
232236
}
233237

234-
async function releaseExecDeviceClaim(ownership: DeviceClaimSessionOwnership): Promise<void> {
238+
async function releaseExecDeviceClaim(
239+
ownership: DeviceClaimSessionOwnership,
240+
host: HostEnvironment,
241+
): Promise<void> {
235242
let outcome: DeviceClaimClearOutcome;
236243
try {
237-
outcome = await clearDeviceClaim(ownership);
244+
outcome = await clearDeviceClaim(ownership, host.env);
238245
} catch (error) {
239246
process.stderr.write(
240247
`agent-device exec: could not release the device claim: ${

0 commit comments

Comments
 (0)