Skip to content

Commit 5645905

Browse files
thymikeeclaude
andcommitted
feat(daemon): daemon status lists the registered provider plugins
`daemon status [--json]` reads the daemon record without contacting the daemon and reports every provider it registered, with the reason any plugin failed. `plugins list --json` reports the running daemon's inventory next to the store selections. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1 parent 9096044 commit 5645905

9 files changed

Lines changed: 362 additions & 15 deletions

File tree

‎packages/daemon-contracts/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@
4444
"types": "./src/daemon-shutdown-report.ts",
4545
"default": "./src/daemon-shutdown-report.ts"
4646
},
47+
"./daemon-status": {
48+
"types": "./src/daemon-status.ts",
49+
"default": "./src/daemon-status.ts"
50+
},
4751
"./daemon-stop": {
4852
"types": "./src/daemon-stop.ts",
4953
"default": "./src/daemon-stop.ts"
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
import fs from 'node:fs';
2+
import path from 'node:path';
3+
import { expect, test, vi } from 'vitest';
4+
const processProbe = vi.hoisted(() => ({ startTimeUnreadable: false }));
5+
vi.mock('@agent-device/host-kit/process', async (importOriginal) => {
6+
const actual = await importOriginal<typeof import('@agent-device/host-kit/process')>();
7+
return {
8+
...actual,
9+
readProcessStartTime: (pid: number) =>
10+
processProbe.startTimeUnreadable ? null : actual.readProcessStartTime(pid),
11+
};
12+
});
13+
14+
import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process';
15+
import { mkdtempForTestSync } from '@agent-device/test-kit';
16+
import { resolveDaemonPaths } from './daemon-resolution.ts';
17+
import { readDaemonStatus } from './daemon-status.ts';
18+
19+
const FAILED = {
20+
provider: 'broken',
21+
source: 'store',
22+
package: '@example/broken',
23+
version: '1.0.0',
24+
state: 'failed',
25+
error: {
26+
code: 'INVALID_ARGS',
27+
message: 'Plugin must export a default factory',
28+
reason: 'invalid_plugin',
29+
},
30+
credentials: { variables: [], byBackend: {} },
31+
};
32+
const ACTIVE = {
33+
provider: 'browserstack',
34+
source: 'builtin',
35+
state: 'active',
36+
credentials: { variables: ['BROWSERSTACK_USERNAME'], byBackend: { 'ios-instance': ['A'] } },
37+
};
38+
39+
function publish(stateDir: string, record: Record<string, unknown>): void {
40+
fs.mkdirSync(stateDir, { recursive: true });
41+
fs.writeFileSync(path.join(stateDir, 'daemon.json'), JSON.stringify(record));
42+
}
43+
44+
test('a state dir without a daemon record reports no running daemon', () => {
45+
const paths = resolveDaemonPaths(mkdtempForTestSync('agent-device-daemon-status-'));
46+
expect(readDaemonStatus(paths)).toEqual({ running: false, stateDir: paths.baseDir, plugins: [] });
47+
});
48+
49+
test('a live registered daemon reports its identity and the plugin inventory it published', () => {
50+
const stateDir = mkdtempForTestSync('agent-device-daemon-status-');
51+
const owner = readCurrentOwnerIdentity();
52+
publish(stateDir, {
53+
token: 't',
54+
port: 1,
55+
pid: owner.pid,
56+
processStartTime: owner.startTime,
57+
version: '0.21.30',
58+
transport: 'http',
59+
plugins: [ACTIVE, FAILED, { state: 'unknown' }],
60+
});
61+
62+
expect(readDaemonStatus(resolveDaemonPaths(stateDir))).toEqual({
63+
running: true,
64+
stateDir,
65+
pid: owner.pid,
66+
version: '0.21.30',
67+
transport: 'http',
68+
plugins: [ACTIVE, FAILED],
69+
});
70+
});
71+
72+
test('a record whose process is gone or was replaced is not a running daemon', () => {
73+
const stateDir = mkdtempForTestSync('agent-device-daemon-status-');
74+
const owner = readCurrentOwnerIdentity();
75+
publish(stateDir, {
76+
token: 't',
77+
port: 1,
78+
pid: owner.pid,
79+
processStartTime: 'Thu Jan 1 00:00:00 1970',
80+
plugins: [ACTIVE],
81+
});
82+
expect(readDaemonStatus(resolveDaemonPaths(stateDir)).running).toBe(false);
83+
publish(stateDir, {
84+
token: 't',
85+
port: 1,
86+
pid: 2_147_483_000,
87+
processStartTime: owner.startTime,
88+
plugins: [ACTIVE],
89+
});
90+
expect(readDaemonStatus(resolveDaemonPaths(stateDir))).toMatchObject({
91+
running: false,
92+
plugins: [],
93+
});
94+
});
95+
96+
test('a live process whose start time cannot be read still counts as the running daemon', () => {
97+
const stateDir = mkdtempForTestSync('agent-device-daemon-status-');
98+
const owner = readCurrentOwnerIdentity();
99+
publish(stateDir, {
100+
token: 't',
101+
port: 1,
102+
pid: owner.pid,
103+
processStartTime: owner.startTime,
104+
plugins: [ACTIVE],
105+
});
106+
processProbe.startTimeUnreadable = true;
107+
try {
108+
expect(readDaemonStatus(resolveDaemonPaths(stateDir))).toMatchObject({
109+
running: true,
110+
plugins: [ACTIVE],
111+
});
112+
} finally {
113+
processProbe.startTimeUnreadable = false;
114+
}
115+
});
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import fs from 'node:fs';
2+
import {
3+
readPluginInventory,
4+
type PluginInventoryEntry,
5+
} from '@agent-device/contracts/plugin-inventory';
6+
import {
7+
isProcessAlive,
8+
isProcessPid,
9+
ownerIdentityDiffers,
10+
readProcessStartTime,
11+
} from '@agent-device/host-kit/process';
12+
import type { DaemonPaths, DaemonServerMode } from './daemon-resolution.ts';
13+
14+
/** What a state dir's `daemon.json` says about the daemon serving it, checked against the process. */
15+
export type DaemonStatus = Readonly<{
16+
running: boolean;
17+
stateDir: string;
18+
pid?: number;
19+
version?: string;
20+
transport?: DaemonServerMode;
21+
/** The provider plugins the running daemon registered; empty when none is running. */
22+
plugins: readonly PluginInventoryEntry[];
23+
}>;
24+
25+
/**
26+
* Reads the daemon's published record without contacting it. The record counts while its pid names
27+
* a live process, unless the process start time can be read and differs from the recorded one: a
28+
* record a crashed daemon left behind, or whose pid was reused, reports `running: false`, while a
29+
* failed start-time read does not end the record.
30+
*/
31+
export function readDaemonStatus(paths: DaemonPaths): DaemonStatus {
32+
const notRunning: DaemonStatus = { running: false, stateDir: paths.baseDir, plugins: [] };
33+
const record = readRecord(paths.infoPath);
34+
const { pid, processStartTime } = record;
35+
if (!isProcessPid(pid) || typeof processStartTime !== 'string' || !isProcessAlive(pid)) {
36+
return notRunning;
37+
}
38+
// Only positive proof of a different process ends the record: a failed start-time read does not.
39+
const recorded = { pid, startTime: processStartTime };
40+
if (ownerIdentityDiffers(recorded, { pid, startTime: readProcessStartTime(pid) })) {
41+
return notRunning;
42+
}
43+
return {
44+
running: true,
45+
stateDir: paths.baseDir,
46+
pid,
47+
...(typeof record.version === 'string' ? { version: record.version } : {}),
48+
...(isTransport(record.transport) ? { transport: record.transport } : {}),
49+
plugins: readPluginInventory(record.plugins),
50+
};
51+
}
52+
53+
function readRecord(infoPath: string): Record<string, unknown> {
54+
try {
55+
const parsed: unknown = JSON.parse(fs.readFileSync(infoPath, 'utf8'));
56+
return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {};
57+
} catch {
58+
return {};
59+
}
60+
}
61+
62+
function isTransport(value: unknown): value is DaemonServerMode {
63+
return value === 'socket' || value === 'http' || value === 'dual';
64+
}

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

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { mkdtempForTestSync } from '@agent-device/test-kit';
77
const mocks = vi.hoisted(() => ({
88
cleanupDaemonOwner: vi.fn(async () => undefined),
99
readDaemonShutdownReport: vi.fn(),
10+
readDaemonStatus: vi.fn(),
1011
readDaemonStopIdentity: vi.fn(),
1112
stopDaemon: vi.fn(),
1213
writeCommandOutput: vi.fn(),
@@ -25,6 +26,9 @@ vi.mock('@agent-device/daemon-contracts/daemon-shutdown-report', () => ({
2526
vi.mock('../../../platform-runtime-daemon-owner-cleanup.ts', () => ({
2627
createDaemonOwnerCleanup: () => ({ cleanup: mocks.cleanupDaemonOwner }),
2728
}));
29+
vi.mock('@agent-device/daemon-contracts/daemon-status', () => ({
30+
readDaemonStatus: mocks.readDaemonStatus,
31+
}));
2832
vi.mock('../shared.ts', () => ({ writeCommandOutput: mocks.writeCommandOutput }));
2933

3034
import { daemonCommand } from '../daemon.ts';
@@ -45,7 +49,7 @@ afterEach(() => {
4549
vi.clearAllMocks();
4650
});
4751

48-
test('accepts only daemon stop', async () => {
52+
test('accepts only daemon stop and status', async () => {
4953
await assert.rejects(
5054
async () =>
5155
await daemonCommand({
@@ -223,3 +227,51 @@ test('routes an unattributable claim to the default status view, never to --stal
223227
fs.rmSync(stateDir, { recursive: true, force: true });
224228
}
225229
});
230+
231+
test('daemon status reads the daemon record without stopping or contacting the daemon', async () => {
232+
const stateDir = mkdtempForTestSync('agent-device-daemon-command-');
233+
const status = {
234+
running: true,
235+
stateDir,
236+
pid: 321,
237+
version: '0.21.30',
238+
plugins: [
239+
{
240+
provider: 'browserstack',
241+
source: 'builtin',
242+
state: 'active',
243+
credentials: { variables: [], byBackend: {} },
244+
},
245+
{
246+
provider: 'testmu',
247+
source: 'store',
248+
package: '@agent-device/testmu',
249+
version: '1.0.0',
250+
state: 'failed',
251+
error: { code: 'INVALID_ARGS', message: 'bad plugin' },
252+
credentials: { variables: [], byBackend: {} },
253+
},
254+
],
255+
};
256+
mocks.readDaemonStatus.mockReturnValue(status);
257+
258+
try {
259+
await daemonCommand({
260+
positionals: ['status'],
261+
flags: { help: false, json: true, stateDir, version: false },
262+
client: {} as never,
263+
});
264+
265+
expect(mocks.stopDaemon).not.toHaveBeenCalled();
266+
expect(mocks.writeCommandOutput).toHaveBeenCalledWith(
267+
expect.objectContaining({ json: true }),
268+
status,
269+
expect.any(Function),
270+
);
271+
const render = mocks.writeCommandOutput.mock.calls[0]![2] as () => string;
272+
expect(render()).toContain('testmu [store] @agent-device/[email protected] - failed: bad plugin');
273+
expect(render()).toContain('browserstack [builtin] builtin - active');
274+
} finally {
275+
fs.rmSync(stateDir, { recursive: true, force: true });
276+
}
277+
});

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

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ import fs from 'node:fs';
33
import path from 'node:path';
44
import { afterEach, test, vi } from 'vitest';
55
import { runCli } from '../../../cli.ts';
6+
import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process';
67
import { pluginHome, selectPlugin } from '@agent-device/test-kit';
7-
import { parseRawArgs, usageForCommand } from '../../parser/args.ts';
8+
import { parseArgs, parseRawArgs, usageForCommand } from '../../parser/args.ts';
89
import { beginStdoutCapture } from '../../../__tests__/test-utils/stream-capture.ts';
910

1011
vi.mock('../../../provider-device-runtimes.ts', () => {
@@ -57,5 +58,65 @@ test('plugin schema exposes operator help and preserves scoped npm package specs
5758
assert.deepEqual(args.positionals, ['add', '@example/provider@^1.0.0']);
5859
const help = await usageForCommand('plugins');
5960
assert.ok(help);
60-
assert.match(help, /plugins list\|add/);
61+
assert.match(help, /plugins list \[--state-dir <path>\]\|add/);
62+
});
63+
64+
test('plugins list reports the running daemon inventory next to the store selections', async () => {
65+
const { home } = pluginHome();
66+
const stateDir = path.join(home, 'state');
67+
vi.stubEnv('AGENT_DEVICE_HOME', home);
68+
vi.stubEnv('AGENT_DEVICE_STATE_DIR', stateDir);
69+
vi.stubEnv('AGENT_DEVICE_NO_UPDATE_NOTIFIER', '1');
70+
const owner = readCurrentOwnerIdentity();
71+
const failed = {
72+
provider: 'example',
73+
source: 'store',
74+
package: 'example',
75+
version: '1.2.3',
76+
state: 'failed',
77+
error: { code: 'INVALID_ARGS', message: 'bad plugin', reason: 'invalid_plugin' },
78+
credentials: { variables: [], byBackend: {} },
79+
};
80+
fs.mkdirSync(stateDir, { recursive: true });
81+
fs.writeFileSync(
82+
path.join(stateDir, 'daemon.json'),
83+
JSON.stringify({
84+
token: 't',
85+
port: 1,
86+
pid: owner.pid,
87+
processStartTime: owner.startTime,
88+
plugins: [failed],
89+
}),
90+
);
91+
selectPlugin(home, 'example', 'example', 'export default () => {};');
92+
const stdoutCapture = beginStdoutCapture();
93+
try {
94+
await runCli(['plugins', 'list', '--json'], {
95+
sendToDaemon: vi.fn(async () => {
96+
throw new Error('unexpected daemon access');
97+
}),
98+
});
99+
const { data } = JSON.parse(stdoutCapture.read());
100+
assert.deepEqual(data.daemon, { pid: owner.pid, stateDir, plugins: [failed] });
101+
assert.equal(data.plugins[0].name, 'example');
102+
} finally {
103+
stdoutCapture.restore();
104+
}
105+
});
106+
107+
test('--state-dir belongs to plugins list and daemon status, not to the commands that change the store', async () => {
108+
assert.equal(
109+
parseArgs(['plugins', 'list', '--state-dir', '/tmp/state']).flags.stateDir,
110+
'/tmp/state',
111+
);
112+
assert.throws(() => parseArgs(['plugins', 'add', 'example', '--state-dir', '/tmp/state']), {
113+
code: 'INVALID_ARGS',
114+
});
115+
assert.equal(
116+
parseArgs(['daemon', 'status', '--state-dir', '/tmp/state']).flags.stateDir,
117+
'/tmp/state',
118+
);
119+
assert.throws(() => parseArgs(['daemon', 'status', '--clean']), { code: 'INVALID_ARGS' });
120+
const help = await usageForCommand('daemon');
121+
assert.match(help ?? '', /daemon status \[--state-dir <path>\]/);
61122
});

0 commit comments

Comments
 (0)