Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 48 additions & 3 deletions packages/host-kit/src/internal/host-process-liveness.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import assert from 'node:assert/strict';
import { beforeEach, test, vi } from 'vitest';
import fs from 'node:fs';
import { afterEach, beforeEach, test, vi } from 'vitest';

const { mockRunCmdSync, mockRunCmd } = vi.hoisted(() => ({
mockRunCmdSync: vi.fn(),
Expand Down Expand Up @@ -29,11 +30,23 @@ function psAnswersEachField(fields: Record<string, string>): void {
});
}

const PINNED_PS_COMMANDS: readonly string[] = ['/bin/ps', '/run/current-system/sw/bin/ps'];

function psInstalledAt(installed: readonly string[]): void {
vi.spyOn(fs, 'accessSync').mockImplementation((candidate) => {
if (!installed.includes(String(candidate))) throw new Error(`ENOENT: ${String(candidate)}`);
});
}

beforeEach(() => {
mockRunCmdSync.mockReset();
mockRunCmd.mockReset();
});

afterEach(() => {
vi.restoreAllMocks();
});

test('isProcessZombie detects the Z state code with trailing flags', () => {
psReturns('ZN \n');
assert.equal(isProcessZombie(4242), true);
Expand Down Expand Up @@ -71,7 +84,7 @@ test('reads many process identities from one ps snapshot', () => {
startTime: 'Mon Aug 10 20:01:00 2026',
});
assert.equal(mockRunCmdSync.mock.calls.length, 1);
assert.equal(mockRunCmdSync.mock.calls[0]?.[0], '/bin/ps');
assert.ok(PINNED_PS_COMMANDS.includes(mockRunCmdSync.mock.calls[0]?.[0]));
Comment thread
wongcallum marked this conversation as resolved.
Resolved
assert.deepEqual(mockRunCmdSync.mock.calls[0]?.[1], [
'-p',
'4242,4343',
Expand Down Expand Up @@ -171,6 +184,38 @@ test('the ownership read answers the zombie question from the state field', asyn
command: 'y',
zombie: true,
});
assert.equal(mockRunCmd.mock.calls[0]?.[0], '/bin/ps');
assert.ok(PINNED_PS_COMMANDS.includes(mockRunCmd.mock.calls[0]?.[0]));
assert.equal(mockRunCmd.mock.calls[0]?.[2]?.timeoutMs, 1_000);
});

test('a host without /bin/ps reads identity through the NixOS system profile procps', async () => {
psInstalledAt(['/run/current-system/sw/bin/ps']);
psReturns('4242 Ss Mon Aug 10 20:00:00 2026\n');
psAnswersEachField({ 'lstart=': 'x', 'command=': 'y', 'state=': 'Ss' });

assert.equal(
readHostProcessIdentityObservations([4242]).get(4242)?.startTime,
'Mon Aug 10 20:00:00 2026',
);
assert.equal((await readProcessIdentityFacts(4242)).startTime, 'x');
assert.equal(mockRunCmdSync.mock.calls[0]?.[0], '/run/current-system/sw/bin/ps');
for (const call of mockRunCmd.mock.calls) {
assert.equal(call[0], '/run/current-system/sw/bin/ps');
}
});

test('a host with no pinned ps still runs /bin/ps and never resolves ps from PATH', () => {
psInstalledAt([]);
psReturns('', 1);

assert.equal(isProcessZombie(4242), false);
assert.equal(mockRunCmdSync.mock.calls[0]?.[0], '/bin/ps');
});

test('a host with both pinned ps binaries keeps running /bin/ps', () => {
psInstalledAt(['/bin/ps', '/run/current-system/sw/bin/ps']);
psReturns('Ss \n');

assert.equal(isProcessZombie(4242), false);
assert.equal(mockRunCmdSync.mock.calls[0]?.[0], '/bin/ps');
});
29 changes: 20 additions & 9 deletions packages/host-kit/src/internal/host-process.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import fs from 'node:fs';
import type { ExecOptions, ExecResult } from './exec.ts';
import { runCmd, runCmdSync, withoutCommandExecutorOverride } from './exec.ts';
import { sleep } from './retry.ts';
import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value';

const PS_TIMEOUT_MS = 1_000;
// The one binary behind every POSIX probe: pinning it keeps a hostile PATH from
// substituting another `ps`. Windows hosts branch to the CIM query at every call
// site before this constant is consulted, so it names no Windows tool.
const HOST_PS_COMMAND = '/bin/ps';
// Every POSIX probe runs the first of these that exists, never a PATH lookup, so a hostile PATH
// cannot substitute another `ps`. NixOS keeps procps only in its root-owned system profile. With
// neither present, `/bin/ps` runs and fails closed. Windows hosts take the CIM query instead.
const HOST_PS_COMMANDS = ['/bin/ps', '/run/current-system/sw/bin/ps'] as const;
// PowerShell pays a fixed startup cost before the CIM query even runs, so every
// Windows process-table read gets at least this budget instead of the `ps` one.
const WINDOWS_PS_TIMEOUT_MS = 2_000;
Expand Down Expand Up @@ -77,6 +78,16 @@ export function hostProcessId(): number {
return process.pid;
}

function hostPsCommand(): string {
for (const candidate of HOST_PS_COMMANDS) {
try {
fs.accessSync(candidate, fs.constants.X_OK);
Comment thread
wongcallum marked this conversation as resolved.
Resolved
return candidate;
} catch {}
}
return HOST_PS_COMMANDS[0];
}

export type ListHostProcessesOptions = {
timeoutMs: number;
runCommand?: HostProcessRunCommand;
Expand Down Expand Up @@ -212,7 +223,7 @@ function readHostProcessIdentityRowsSync(
return windowsProcessIdentityRows(readWindowsProcessRows(pids, WINDOWS_PS_TIMEOUT_MS));
}
try {
const result = runCmdSync(HOST_PS_COMMAND, HOST_PROCESS_IDENTITY_PS_ARGS(pids), {
const result = runCmdSync(hostPsCommand(), HOST_PROCESS_IDENTITY_PS_ARGS(pids), {
allowFailure: true,
timeoutMs: PS_TIMEOUT_MS,
});
Expand All @@ -234,7 +245,7 @@ async function readHostProcessIdentityRowsAsync(
);
}
try {
const result = await runCmd(HOST_PS_COMMAND, HOST_PROCESS_IDENTITY_PS_ARGS(selected), {
const result = await runCmd(hostPsCommand(), HOST_PROCESS_IDENTITY_PS_ARGS(selected), {
allowFailure: true,
timeoutMs: PS_TIMEOUT_MS,
});
Expand Down Expand Up @@ -272,7 +283,7 @@ function readProcessField(pid: number, field: HostProcessField): string | null {
if (!Number.isInteger(pid) || pid <= 0) return null;
if (isWindowsHostPlatform()) return readWindowsProcessField(pid, field);
try {
const result = runCmdSync(HOST_PS_COMMAND, ['-p', String(pid), '-o', field], {
const result = runCmdSync(hostPsCommand(), ['-p', String(pid), '-o', field], {
allowFailure: true,
timeoutMs: PS_TIMEOUT_MS,
});
Expand All @@ -289,7 +300,7 @@ async function readProcessFieldAsync(
): Promise<string | null> {
if (!Number.isInteger(pid) || pid <= 0) return null;
try {
const result = await runCmd(HOST_PS_COMMAND, ['-p', String(pid), '-o', field], {
const result = await runCmd(hostPsCommand(), ['-p', String(pid), '-o', field], {
allowFailure: true,
timeoutMs,
});
Expand Down Expand Up @@ -492,7 +503,7 @@ export async function listHostProcesses(
): Promise<HostProcessInfo[]> {
if (isWindowsHostPlatform()) return await listWindowsHostProcesses(options);
const result = await (options.runCommand ?? runCmd)(
options.runCommand ? 'ps' : HOST_PS_COMMAND,
options.runCommand ? 'ps' : hostPsCommand(),
['-ax', '-o', 'pid=,ppid=,command='],
{
allowFailure: true,
Expand Down
Loading