Skip to content

Commit 012b50d

Browse files
committed
Merge branch 'refactor/host-environment' into refactor/daemon-runtime-no-process-globals
* refactor/host-environment: style: format the daemon policy reuse test fix(host): resolve the daemon policy path against the host working directory # Conflicts: # packages/daemon/src/server/http/daemon-runtime.ts
2 parents 817930f + f4616b9 commit 012b50d

8 files changed

Lines changed: 62 additions & 17 deletions

File tree

‎packages/daemon-contracts/src/daemon-policy-file.test.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,29 @@ import { DAEMON_POLICY_ENV, loadDaemonPolicy, parseDaemonPolicy } from './daemon
1010
const SOURCE = '/etc/agent-device/policy.json';
1111

1212
test('no configured policy leaves the daemon unrestricted', () => {
13-
expect(loadDaemonPolicy({})).toBeUndefined();
13+
expect(loadDaemonPolicy({}, process.cwd())).toBeUndefined();
1414
});
1515

1616
test('a policy file that cannot be read or parsed fails loading', () => {
1717
const dir = mkdtempForTestSync('agent-device-daemon-policy-load-');
1818
const policyPath = path.join(dir, 'policy.json');
1919
fs.writeFileSync(policyPath, '{ not json');
2020

21-
expect(() => loadDaemonPolicy({ [DAEMON_POLICY_ENV]: policyPath })).toThrow(
21+
expect(() => loadDaemonPolicy({ [DAEMON_POLICY_ENV]: policyPath }, dir)).toThrow(
2222
/Invalid daemon policy/,
2323
);
24-
expect(() => loadDaemonPolicy({ [DAEMON_POLICY_ENV]: path.join(dir, 'missing.json') })).toThrow(
25-
/cannot read policy JSON/,
26-
);
24+
expect(() =>
25+
loadDaemonPolicy({ [DAEMON_POLICY_ENV]: path.join(dir, 'missing.json') }, dir),
26+
).toThrow(/cannot read policy JSON/);
27+
});
28+
29+
test('a relative policy path resolves against the host working directory, not the process', () => {
30+
const dir = mkdtempForTestSync('agent-device-daemon-policy-relative-');
31+
fs.writeFileSync(path.join(dir, 'policy.json'), JSON.stringify({ version: 1 }));
32+
33+
const policy = loadDaemonPolicy({ [DAEMON_POLICY_ENV]: 'policy.json' }, dir);
34+
35+
expect(policy?.sourcePath).toBe(path.join(dir, 'policy.json'));
2736
});
2837

2938
test.each([

‎packages/daemon-contracts/src/daemon-policy-file.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,10 @@ export function resolveDaemonPolicyCommandName(command: string): string | undefi
7373

7474
const POLICY_KEYS = new Set(['version', 'devices', 'commands', 'capabilities', 'leases']);
7575

76-
export function loadDaemonPolicy(env: EnvMap): DaemonPolicy | undefined {
76+
export function loadDaemonPolicy(env: EnvMap, cwd: string): DaemonPolicy | undefined {
7777
const configured = env[DAEMON_POLICY_ENV]?.trim();
7878
if (!configured) return undefined;
79-
const sourcePath = path.resolve(configured);
79+
const sourcePath = path.resolve(cwd, configured);
8080
let raw: unknown;
8181
try {
8282
raw = JSON.parse(fs.readFileSync(sourcePath, 'utf8'));

‎packages/daemon/src/server/http/daemon-runtime.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -345,7 +345,7 @@ async function startDaemonRuntimeOnHost(
345345
// ADR 0029: a policy that cannot be read or validated stops startup; the daemon never runs
346346
// with a weaker policy than its operator named. The server loads it before composing any
347347
// runtime, so no capability is ever built under a policy that failed validation.
348-
const daemonPolicy: DaemonPolicy | undefined = loadDaemonPolicy(env);
348+
const daemonPolicy: DaemonPolicy | undefined = loadDaemonPolicy(env, host.cwd);
349349
// Derived here, beside the policy it reads: the server hands the same refusal to the root's
350350
// composition, so a runtime can never be built without the operator's shutdown gate.
351351
const assertShutdownAllowed = daemonPolicy

‎src/__tests__/daemon-registration-owner.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import {
2020
} from '@agent-device/daemon-contracts/daemon-resolution';
2121
import { readRegisteredDaemonOwnership } from '@agent-device/daemon-contracts/daemon-registration';
2222
import { readDaemonShutdownReport } from '@agent-device/daemon-contracts/daemon-shutdown-report';
23-
import { mkdtempForTestSync } from '@agent-device/test-kit';
23+
import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit';
2424
import { spawnLegacyDaemonFixture } from './daemon-registration-owner.fixtures.ts';
2525
import {
2626
registeredDaemonFixtureArgs,
@@ -835,7 +835,7 @@ test('cutover refuses an already-running legacy daemon before signaling or chang
835835
flags: { stateDir: paths.baseDir },
836836
},
837837
undefined,
838-
{ env: process.env, cwd: process.cwd() },
838+
createTestHostEnvironment(),
839839
),
840840
),
841841
(error: unknown) => {

‎src/daemon-client/__tests__/daemon-client-policy-reuse.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,10 @@ test('a caller naming a policy refuses a running daemon that enforces a differen
6969
assert.ok(error instanceof AppError);
7070
assert.equal(error.details?.reason, 'DAEMON_POLICY_MISMATCH');
7171
assert.equal(error.details?.daemonPolicyDigest, otherDigest);
72-
assert.equal(error.details?.expectedPolicyDigest, loadDaemonPolicy(process.env)?.digest);
72+
assert.equal(
73+
error.details?.expectedPolicyDigest,
74+
loadDaemonPolicy(process.env, process.cwd())?.digest,
75+
);
7376
return true;
7477
},
7578
);
@@ -154,7 +157,7 @@ async function startReusableDaemon(options: {
154157
processStartTime: readProcessStartTime(process.pid) ?? undefined,
155158
policyDigest:
156159
options.policyDigest === 'matching'
157-
? loadDaemonPolicy(process.env)?.digest
160+
? loadDaemonPolicy(process.env, process.cwd())?.digest
158161
: options.policyDigest,
159162
})}\n`,
160163
);

‎src/daemon-client/daemon-client-host.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import path from 'node:path';
2-
import { expect, test, vi } from 'vitest';
2+
import { afterEach, expect, test, vi } from 'vitest';
33

44
const ensured = vi.hoisted(() => ({ settings: undefined as unknown }));
55

@@ -11,10 +11,15 @@ vi.mock('./daemon-client-lifecycle.ts', async (importOriginal) => ({
1111
},
1212
}));
1313

14+
import { runCli } from '../cli.ts';
1415
import { createAgentDeviceClient } from '../agent-device-client.ts';
1516
import { createDaemonTransport } from './daemon-client.ts';
1617
import type { DaemonClientSettings } from './daemon-client-lifecycle.ts';
1718

19+
afterEach(() => {
20+
vi.restoreAllMocks();
21+
});
22+
1823
const request = { session: 'default', command: 'devices', positionals: [] };
1924

2025
test('a transport resolves its daemon from the host it was built for, not the process', async () => {
@@ -42,3 +47,27 @@ test('a client reports and uses the same state dir when its host and the process
4247

4348
expect((ensured.settings as DaemonClientSettings).paths.baseDir).toBe('/client/state');
4449
});
50+
51+
test('a CLI run builds its transport from the host it was given', async () => {
52+
const host = { env: { AGENT_DEVICE_STATE_DIR: '/cli/state' }, cwd: '/cli/workspace' };
53+
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
54+
const transportForHost = vi.fn(() => async () => ({ ok: true as const, data: { devices: [] } }));
55+
56+
await runCli(['devices', '--json'], { sendToDaemon: vi.fn(), transportForHost }, host);
57+
58+
expect(transportForHost).toHaveBeenCalledWith(host);
59+
});
60+
61+
test('a CLI run with the default transport resolves its daemon from the given host', async () => {
62+
vi.stubEnv('AGENT_DEVICE_STATE_DIR', '/process/state');
63+
const host = { env: { AGENT_DEVICE_STATE_DIR: '/cli/state' }, cwd: '/cli/workspace' };
64+
vi.spyOn(process, 'exit').mockImplementation((() => {
65+
throw new Error('exit');
66+
}) as never);
67+
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
68+
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
69+
70+
await runCli(['devices', '--json'], undefined, host).catch(() => undefined);
71+
72+
expect((ensured.settings as DaemonClientSettings).paths.baseDir).toBe('/cli/state');
73+
});

‎src/daemon-client/daemon-client-lifecycle.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ export async function ensureDaemon(settings: DaemonClientSettings): Promise<Ensu
172172

173173
const ensured = await ensureLocalDaemon(settings);
174174
// Checked on both branches: a startup can resolve to a daemon another caller raced in.
175-
await assertDaemonPolicyMatches(ensured.info, settings.paths.baseDir, settings.host.env);
175+
await assertDaemonPolicyMatches(ensured.info, settings.paths.baseDir, settings.host);
176176
return ensured;
177177
}
178178

@@ -319,11 +319,12 @@ async function canReachReusableDaemon(
319319
async function assertDaemonPolicyMatches(
320320
existing: DaemonInfo,
321321
stateDir: string,
322-
env: Readonly<EnvMap>,
322+
host: HostEnvironment,
323323
): Promise<void> {
324+
const { env } = host;
324325
if (!env.AGENT_DEVICE_DAEMON_POLICY?.trim()) return;
325326
const { loadDaemonPolicy } = await import('@agent-device/daemon-contracts/daemon-policy-file');
326-
const expected = loadDaemonPolicy(env)?.digest;
327+
const expected = loadDaemonPolicy(env, host.cwd)?.digest;
327328
if (expected === existing.policyDigest) return;
328329
throw new AppError(
329330
'COMMAND_FAILED',

‎src/daemon-client/daemon-client.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ export async function sendToDaemon(
3636
return await sendToDaemonOnHost(req, options, captureHostEnvironment(process));
3737
}
3838

39-
/** A transport whose every read of the environment and working directory is `host`'s. */
39+
/**
40+
* A transport whose daemon resolution, spawn, policy check and request preparation read `host`.
41+
* Remote artifact upload still reads the process (`packages/remote`, tracked by #3751).
42+
*/
4043
export function createDaemonTransport(host: HostEnvironment) {
4144
return async (
4245
req: Omit<DaemonRequest, 'token'>,

0 commit comments

Comments
 (0)