Skip to content

Commit 7a789be

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 5ccff7f commit 7a789be

10 files changed

Lines changed: 466 additions & 52 deletions

File tree

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
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-registration.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({
47+
state: 'stopped',
48+
stateDir: paths.baseDir,
49+
});
50+
});
51+
52+
test('a live registered daemon reports its identity and the plugin inventory it published', () => {
53+
const stateDir = mkdtempForTestSync('agent-device-daemon-status-');
54+
const owner = readCurrentOwnerIdentity();
55+
publish(stateDir, {
56+
token: 't',
57+
port: 1,
58+
pid: owner.pid,
59+
processStartTime: owner.startTime,
60+
version: '0.21.30',
61+
transport: 'http',
62+
plugins: [ACTIVE, FAILED, { state: 'unknown' }],
63+
});
64+
65+
expect(readDaemonStatus(resolveDaemonPaths(stateDir))).toEqual({
66+
state: 'running',
67+
stateDir,
68+
pid: owner.pid,
69+
version: '0.21.30',
70+
transport: 'http',
71+
plugins: [ACTIVE, FAILED, { state: 'unknown' }],
72+
});
73+
});
74+
75+
test('a record whose process is gone or was replaced is not a running daemon', () => {
76+
const stateDir = mkdtempForTestSync('agent-device-daemon-status-');
77+
const owner = readCurrentOwnerIdentity();
78+
publish(stateDir, {
79+
token: 't',
80+
port: 1,
81+
pid: owner.pid,
82+
processStartTime: 'Thu Jan 1 00:00:00 1970',
83+
plugins: [ACTIVE],
84+
});
85+
expect(readDaemonStatus(resolveDaemonPaths(stateDir)).state).toBe('stopped');
86+
publish(stateDir, {
87+
token: 't',
88+
port: 1,
89+
pid: 2_147_483_000,
90+
processStartTime: owner.startTime,
91+
plugins: [ACTIVE],
92+
});
93+
expect(readDaemonStatus(resolveDaemonPaths(stateDir))).toMatchObject({
94+
state: 'stopped',
95+
});
96+
});
97+
98+
test('a live process whose start time cannot be read still counts as the running daemon', () => {
99+
const stateDir = mkdtempForTestSync('agent-device-daemon-status-');
100+
const owner = readCurrentOwnerIdentity();
101+
publish(stateDir, {
102+
token: 't',
103+
port: 1,
104+
pid: owner.pid,
105+
processStartTime: owner.startTime,
106+
plugins: [ACTIVE],
107+
});
108+
processProbe.startTimeUnreadable = true;
109+
try {
110+
expect(readDaemonStatus(resolveDaemonPaths(stateDir))).toMatchObject({
111+
state: 'running',
112+
plugins: [ACTIVE],
113+
});
114+
} finally {
115+
processProbe.startTimeUnreadable = false;
116+
}
117+
});
118+
119+
test('text that is not a daemon record is invalid, not a stopped daemon', () => {
120+
const stateDir = mkdtempForTestSync('agent-device-daemon-status-');
121+
for (const text of ['{ not json', '[]', 'null']) {
122+
fs.mkdirSync(stateDir, { recursive: true });
123+
fs.writeFileSync(path.join(stateDir, 'daemon.json'), text);
124+
expect(readDaemonStatus(resolveDaemonPaths(stateDir))).toEqual({ state: 'invalid', stateDir });
125+
}
126+
});
127+
128+
test('a record that exists but cannot be read is unreadable, not a stopped daemon', () => {
129+
const stateDir = mkdtempForTestSync('agent-device-daemon-status-');
130+
publish(stateDir, { token: 't', port: 1, pid: 1, processStartTime: 'x' });
131+
const infoPath = path.join(stateDir, 'daemon.json');
132+
fs.chmodSync(infoPath, 0o000);
133+
try {
134+
if (process.getuid?.() === 0) return;
135+
expect(readDaemonStatus(resolveDaemonPaths(stateDir))).toEqual({
136+
state: 'unreadable',
137+
stateDir,
138+
});
139+
} finally {
140+
fs.chmodSync(infoPath, 0o600);
141+
}
142+
});

‎packages/daemon-contracts/src/daemon-registration.ts‎

Lines changed: 83 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,19 @@
1-
import fs from 'node:fs';
21
import type { ProcessLockInspection } from '@agent-device/host-kit/file';
32
import {
3+
isProcessAlive,
44
ownerIdentityDiffers,
55
isProcessPid,
66
ownerIdentityMatches,
7+
readProcessStartTime,
78
type OwnerIdentity,
89
} from '@agent-device/host-kit/process';
9-
import { resolveDaemonPaths } from './daemon-resolution.ts';
10+
import {
11+
readDaemonRecord,
12+
readRecordedDaemonTransport,
13+
resolveDaemonPaths,
14+
type DaemonPaths,
15+
type DaemonServerMode,
16+
} from './daemon-resolution.ts';
1017

1118
/**
1219
* The daemon identity published in a state dir's `daemon.json`. It is the only
@@ -34,32 +41,29 @@ export function processLockHoldsDaemonIdentity(
3441
/** The raw record's identity. A pid of `null` is a file that names no owner, not owner zero. */
3542
type ParsedRegistration = { pid: number | null; startTime: string | null };
3643

44+
type DaemonRecord = Readonly<Record<string, unknown>>;
45+
46+
/**
47+
* Whether `daemon.json` registers a daemon: a projection of the one record reader that adds the
48+
* identity, so a record that names no owner is `ownerless` however it came to.
49+
*/
3750
function readRegistration(
3851
infoPath: string,
3952
):
40-
| Readonly<{ status: 'registered'; identity: OwnerIdentity }>
53+
| Readonly<{ status: 'registered'; identity: OwnerIdentity; record: DaemonRecord }>
4154
| Readonly<{ status: 'absent' | 'unreadable' | 'ownerless' }> {
42-
let raw: string;
43-
try {
44-
raw = fs.readFileSync(infoPath, 'utf8');
45-
} catch (error) {
46-
// Only a path the host reports as gone proves there is no record. A permission error, an I/O
47-
// fault, or a read this process lost leaves a file present whose contents are unknown, which no
48-
// caller may read as "someone removed it".
49-
const code = (error as NodeJS.ErrnoException | null)?.code;
50-
return code === 'ENOENT' || code === 'ENOTDIR'
51-
? { status: 'absent' }
52-
: { status: 'unreadable' };
53-
}
54-
let parsed: ParsedRegistration;
55-
try {
56-
parsed = parseRegistration(JSON.parse(raw) as { pid?: unknown; processStartTime?: unknown });
57-
} catch {
58-
return { status: 'ownerless' };
55+
const read = readDaemonRecord(infoPath);
56+
if (read.status !== 'present') {
57+
return { status: read.status === 'invalid' ? 'ownerless' : read.status };
5958
}
59+
const parsed = parseRegistration(read.record);
6060
return parsed.pid === null
6161
? { status: 'ownerless' }
62-
: { status: 'registered', identity: { pid: parsed.pid, startTime: parsed.startTime } };
62+
: {
63+
status: 'registered',
64+
identity: { pid: parsed.pid, startTime: parsed.startTime },
65+
record: read.record,
66+
};
6367
}
6468

6569
function parseRegistration(parsed: {
@@ -110,6 +114,64 @@ export function readRegisteredDaemonOwnership(
110114
return { state: 'unproven' };
111115
}
112116

117+
/** What `daemon.json` says about the daemon serving a state dir, checked against the process. */
118+
export type DaemonStatus = Readonly<{
119+
/**
120+
* `unreadable`: the record exists but cannot be read; `invalid`: it is not a record. Either way
121+
* whether a daemon runs is unknown.
122+
*/
123+
state: 'running' | 'stopped' | 'unreadable' | 'invalid';
124+
stateDir: string;
125+
pid?: number;
126+
version?: string;
127+
transport?: DaemonServerMode;
128+
/**
129+
* The provider plugin inventory the running daemon published, as recorded; `readPluginInventory`
130+
* validates it where it is shown, so this module stays out of the inventory vocabulary's closure.
131+
*/
132+
plugins?: unknown;
133+
}>;
134+
135+
/**
136+
* Reads the daemon's published record without contacting it. The record counts while its pid names
137+
* a live process, unless a readable start time differs from the recorded one: a record a crashed
138+
* daemon left behind, or whose pid was reused, is `stopped`, and a failed start-time read does not
139+
* end the record.
140+
*/
141+
export function readDaemonStatus(paths: DaemonPaths): DaemonStatus {
142+
const base = { stateDir: paths.baseDir } as const;
143+
const read = readDaemonRecord(paths.infoPath);
144+
if (read.status !== 'present') {
145+
return read.status === 'absent'
146+
? { state: 'stopped', ...base }
147+
: { state: read.status, ...base };
148+
}
149+
const { record } = read;
150+
const parsed = parseRegistration(record);
151+
if (parsed.pid === null) return { state: 'stopped', ...base };
152+
const identity = { pid: parsed.pid, startTime: parsed.startTime };
153+
if (identity.startTime === null || !isProcessAlive(identity.pid)) {
154+
return { state: 'stopped', ...base };
155+
}
156+
if (
157+
ownerIdentityDiffers(identity, {
158+
pid: identity.pid,
159+
startTime: readProcessStartTime(identity.pid),
160+
})
161+
) {
162+
return { state: 'stopped', ...base };
163+
}
164+
const transport = readRecordedDaemonTransport(record.transport);
165+
return {
166+
state: 'running',
167+
stateDir: paths.baseDir,
168+
pid: identity.pid,
169+
...(typeof record.version === 'string' ? { version: record.version } : {}),
170+
...(transport ? { transport } : {}),
171+
plugins: record.plugins,
172+
};
173+
}
174+
113175
function readableStartTime(value: unknown): string | null {
114176
return typeof value === 'string' && value.trim().length > 0 ? value : null;
115177
}

‎packages/daemon-contracts/src/daemon-resolution.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,40 @@ function resolveRealPath(filePath: string): string {
8080
}
8181
}
8282

83+
/** What `daemon.json` holds: no file, a file that cannot be read, text that is not a record, or the record. */
84+
export type DaemonRecordRead =
85+
| Readonly<{ status: 'absent' | 'unreadable' | 'invalid' }>
86+
| Readonly<{ status: 'present'; record: Readonly<Record<string, unknown>> }>;
87+
88+
/**
89+
* The one reader of `daemon.json`; registration, status and the client's connection info are
90+
* projections of it. Only a path the host reports as gone proves there is no record: a permission
91+
* error or I/O fault leaves a file whose contents are unknown, which no caller may read as "someone
92+
* removed it".
93+
*/
94+
export function readDaemonRecord(infoPath: string): DaemonRecordRead {
95+
let raw: string;
96+
try {
97+
raw = fs.readFileSync(infoPath, 'utf8');
98+
} catch (error) {
99+
const code = (error as NodeJS.ErrnoException | null)?.code;
100+
return { status: code === 'ENOENT' || code === 'ENOTDIR' ? 'absent' : 'unreadable' };
101+
}
102+
try {
103+
const parsed: unknown = JSON.parse(raw);
104+
return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
105+
? { status: 'present', record: parsed as Record<string, unknown> }
106+
: { status: 'invalid' };
107+
} catch {
108+
return { status: 'invalid' };
109+
}
110+
}
111+
112+
/** The transport a daemon recorded in `daemon.json`; anything else is no recorded transport. */
113+
export function readRecordedDaemonTransport(value: unknown): DaemonServerMode | undefined {
114+
return value === 'socket' || value === 'http' || value === 'dual' ? value : undefined;
115+
}
116+
83117
export function resolveDaemonServerMode(raw: string | undefined): DaemonServerMode {
84118
const normalized = (raw ?? '').trim().toLowerCase();
85119
if (normalized === 'http') return 'http';

‎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-registration', () => ({
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+
state: 'running',
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+
});

0 commit comments

Comments
 (0)