Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

test(apktool): own lifecycle fixtures and process observations

morluto23def0409686
diff --git a/src/apktool/ApktoolVersionProbe.lifecycle.test.ts b/src/apktool/ApktoolVersionProbe.lifecycle.test.ts
index b77ad65f1..5b645a101 100644
--- a/src/apktool/ApktoolVersionProbe.lifecycle.test.ts
+++ b/src/apktool/ApktoolVersionProbe.lifecycle.test.ts
@@ -1,107 +1,61 @@
import { ApktoolCommandCleanup } from "./ApktoolCommandCleanup.js";
-import { execFile } from "node:child_process";
-import { chmod, readFile, writeFile } from "node:fs/promises";
-import { join } from "node:path";
-import { setTimeout as delay } from "node:timers/promises";
-import { promisify } from "node:util";
import { afterEach, expect, it } from "vitest";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
+import {
+ awaitApktoolOperation,
+ createApktoolProcessFixture,
+} from "../../tests/fixtures/apktoolProcessTree.js";
+import { observePosixProcess } from "../../tests/support/process/observePosixProcess.js";
import { inspectApktoolClient } from "./ApktoolConfiguration.js";
-/**
- * Only an exited process counts as stopped: it is gone, a zombie waiting to
- * be reaped, or absent from `ps`. A failed inspection is not proof of exit.
- */
-const alive = async (pid: number): Promise<boolean> => {
- try {
- process.kill(pid, 0);
- } catch (cause: unknown) {
- if ((cause as NodeJS.ErrnoException).code === "ESRCH") return false;
- return true;
- }
- return promisify(execFile)("ps", ["-o", "stat=", "-p", `${pid}`]).then(
- ({ stdout }) => {
- const state = stdout.trim();
- return state !== "" && !state.startsWith("Z");
- },
- // `ps` exits 1 when no process matches; any other failure is unknown.
- (cause: unknown) => (cause as { code?: unknown }).code !== 1,
- );
-};
-
-const waitFor = async (check: () => Promise<boolean>, ms: number) => {
- const deadline = Date.now() + ms;
- while (Date.now() < deadline) {
- if (await check()) return true;
- await delay(25);
- }
- return false;
-};
-
-const readPids = async (path: string): Promise<readonly number[]> =>
- readFile(path, "utf8")
- .then((text) => JSON.parse(text) as number[])
- .catch(() => []);
-
// The interpreter is the test runtime itself, so its environment (and the
// ownership run token) is readable on both Linux and macOS.
it.skipIf(process.platform === "win32")(
"stops an interpreter launcher and its pipe-holding child when the probe is cancelled",
async () => {
const root = await createTestTempDirectory("rea-apktool-probe-");
- const pids = join(root, "pids.json");
- const launcher = join(root, "apktool");
- await writeFile(
- launcher,
- [
- `#!${process.execPath}`,
- 'const { spawn } = require("node:child_process");',
- 'const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "inherit" });',
- `require("node:fs").writeFileSync(${JSON.stringify(pids)}, JSON.stringify([process.pid, child.pid]));`,
- "setInterval(() => {}, 1000);",
- ].join("\n"),
- );
- await chmod(launcher, 0o755);
+ const fixture = await createApktoolProcessFixture(root, "probe");
const controller = new AbortController();
const started = performance.now();
const probe = inspectApktoolClient(
- { command: launcher, commandSource: "environment" },
+ { command: fixture.command, commandSource: "environment" },
commands,
{ signal: controller.signal, environment: process.env },
).catch((cause: unknown) => cause);
try {
- expect(
- await waitFor(async () => (await readPids(pids)).length === 2, 10_000),
- ).toBe(true);
- const launched = await readPids(pids);
+ let launched: readonly number[] = [];
+ await expect
+ .poll(
+ async () => {
+ const marker = await fixture.readMarker();
+ if (marker?.ready !== true) return false;
+ launched = [marker.rootPid, marker.childPid];
+ return (await Promise.all(launched.map(observePosixProcess))).every(
+ ({ kind }) => kind === "running",
+ );
+ },
+ { timeout: 10_000, interval: 25 },
+ )
+ .toBe(true);
controller.abort();
// A regressed probe never settles; bound the wait so cleanup still runs.
- const outcome = await Promise.race([
- probe,
- delay(15_000).then(() => "still pending"),
- ]);
+ const outcome = await awaitApktoolOperation(probe, 15_000);
expect(outcome).toBeInstanceOf(AnalysisCancelledError);
expect(performance.now() - started).toBeLessThan(15_000);
- expect(
- await waitFor(
+ await expect
+ .poll(
async () =>
- (await Promise.all(launched.map(alive))).every((live) => !live),
- 5_000,
- ),
- ).toBe(true);
+ (await Promise.all(launched.map(observePosixProcess))).every(
+ ({ kind }) => kind !== "running",
+ ),
+ { timeout: 5_000, interval: 25 },
+ )
+ .toBe(true);
} finally {
- // A failed assertion must not leave the fixture's processes running.
controller.abort();
- await Promise.race([probe, delay(10_000)]);
- for (const pid of await readPids(pids))
- if (await alive(pid))
- try {
- process.kill(pid, "SIGKILL");
- } catch {
- // Already exited between the check and the signal.
- }
+ await fixture.cleanup([probe]);
}
},
30_000,
diff --git a/tests/boundary/providers/apktoolDecodeDeadline.test.ts b/tests/boundary/providers/apktoolDecodeDeadline.test.ts
index ef54e6734..1390e4756 100644
--- a/tests/boundary/providers/apktoolDecodeDeadline.test.ts
+++ b/tests/boundary/providers/apktoolDecodeDeadline.test.ts
@@ -1,53 +1,18 @@
-import { execFile } from "node:child_process";
-import { chmod, readFile, writeFile } from "node:fs/promises";
+import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { performance } from "node:perf_hooks";
-import { setTimeout as delay } from "node:timers/promises";
-import { promisify } from "node:util";
import { expect, it } from "vitest";
+import {
+ awaitApktoolOperation,
+ createApktoolProcessFixture,
+} from "../../fixtures/apktoolProcessTree.js";
+import { observePosixProcess } from "../../support/process/observePosixProcess.js";
import { ApktoolProvider } from "../../../src/apktool/ApktoolProvider.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
-/**
- * Only an exited process counts as stopped: it is gone, a zombie waiting to
- * be reaped, or absent from `ps`. A failed inspection is not proof of exit.
- */
-const alive = async (pid: number): Promise<boolean> => {
- try {
- process.kill(pid, 0);
- } catch (cause: unknown) {
- if ((cause as NodeJS.ErrnoException).code === "ESRCH") return false;
- return true;
- }
- return promisify(execFile)("ps", ["-o", "stat=", "-p", `${pid}`]).then(
- ({ stdout }) => {
- const state = stdout.trim();
- return state !== "" && !state.startsWith("Z");
- },
- // `ps` exits 1 when no process matches; any other failure is unknown.
- (cause: unknown) => (cause as { code?: unknown }).code !== 1,
- );
-};
-
-const waitFor = async (check: () => Promise<boolean>, ms: number) => {
- const deadline = Date.now() + ms;
- while (Date.now() < deadline) {
- if (await check()) return true;
- await delay(25);
- }
- return false;
-};
-
-const readPids = async (path: string): Promise<readonly number[]> =>
- readFile(path, "utf8")
- .then((text) => JSON.parse(text) as number[])
- .catch(() => []);
-
const DECODE_TIMEOUT_MS = 2_500;
-const CHILD_SCRIPT =
- "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000);";
// Windows Job Object cleanup is a separate owned-command lane. This observes
// the POSIX process group the apktool decode launcher actually uses.
@@ -55,29 +20,11 @@ it.skipIf(process.platform === "win32")(
"stops a hanging launcher and its pipe-holding child when the decode deadline elapses",
async () => {
const root = await createTestTempDirectory("rea-apktool-decode-deadline-");
- const pidsPath = join(root, "pids.json");
- const launcher = join(root, "apktool");
- await writeFile(
- launcher,
- [
- `#!${process.execPath}`,
- 'const { spawn } = require("node:child_process");',
- 'const { writeFileSync } = require("node:fs");',
- 'if (process.argv[2] === "--version") { process.stdout.write("2.9.3\\n"); process.exit(0); }',
- 'if (process.argv[2] !== "d") { process.stderr.write("unexpected " + process.argv.slice(2).join(" ")); process.exit(1); }',
- `const child = spawn(process.execPath, ["-e", ${JSON.stringify(CHILD_SCRIPT)}], { stdio: "inherit" });`,
- "if (child.pid === undefined) process.exit(1);",
- `writeFileSync(${JSON.stringify(pidsPath)}, JSON.stringify([process.pid, child.pid]));`,
- 'process.on("SIGTERM", () => {});',
- "setInterval(() => {}, 1000);",
- "",
- ].join("\n"),
- );
- await chmod(launcher, 0o755);
+ const fixture = await createApktoolProcessFixture(root, "decode");
const apk = join(root, "probe.apk");
await writeFile(apk, "apk-bytes");
const provider = new ApktoolProvider({
- environment: { REA_APKTOOL_COMMAND: launcher },
+ environment: { REA_APKTOOL_COMMAND: fixture.command },
});
const started = performance.now();
const pending = provider.execute({
@@ -90,20 +37,20 @@ it.skipIf(process.platform === "win32")(
});
let launched: readonly number[] = [];
try {
- expect(
- await waitFor(async () => {
- const pids = await readPids(pidsPath);
- if (pids.length !== 2) return false;
- launched = pids;
- return (await Promise.all(pids.map(alive))).every(Boolean);
- }, 8_000),
- ).toBe(true);
- const outcome = await Promise.race([
- pending,
- delay(15_000).then(() => "still pending" as const),
- ]);
- if (outcome === "still pending")
- throw new Error("apktool decode deadline did not settle");
+ await expect
+ .poll(
+ async () => {
+ const marker = await fixture.readMarker();
+ if (marker?.ready !== true) return false;
+ launched = [marker.rootPid, marker.childPid];
+ return (await Promise.all(launched.map(observePosixProcess))).every(
+ ({ kind }) => kind === "running",
+ );
+ },
+ { timeout: 8_000, interval: 25 },
+ )
+ .toBe(true);
+ const outcome = await awaitApktoolOperation(pending, 15_000);
const elapsed = performance.now() - started;
expect(outcome.ok).toBe(false);
if (outcome.ok) return;
@@ -119,24 +66,17 @@ it.skipIf(process.platform === "win32")(
// Settlement includes the owned-command deadline, so the timer elapsed.
expect(elapsed).toBeGreaterThanOrEqual(DECODE_TIMEOUT_MS - 50);
expect(elapsed).toBeLessThan(15_000);
- expect(
- await waitFor(
+ await expect
+ .poll(
async () =>
- (await Promise.all(launched.map(alive))).every((live) => !live),
- 5_000,
- ),
- ).toBe(true);
+ (await Promise.all(launched.map(observePosixProcess))).every(
+ ({ kind }) => kind !== "running",
+ ),
+ { timeout: 5_000, interval: 25 },
+ )
+ .toBe(true);
} finally {
- const closing = provider.close();
- await Promise.race([pending, delay(10_000)]).catch(() => undefined);
- for (const pid of await readPids(pidsPath))
- if (await alive(pid))
- try {
- process.kill(pid, "SIGKILL");
- } catch {
- // Already exited between the check and the signal.
- }
- await Promise.race([closing, delay(10_000)]).catch(() => undefined);
+ await fixture.cleanup([pending, provider.close()]);
}
},
30_000,
diff --git a/tests/boundary/providers/apktoolProcessFixture.test.ts b/tests/boundary/providers/apktoolProcessFixture.test.ts
new file mode 100644
index 000000000..185597549
--- /dev/null
+++ b/tests/boundary/providers/apktoolProcessFixture.test.ts
@@ -0,0 +1,64 @@
+import { mkdir, rm, writeFile } from "node:fs/promises";
+import { expect, it } from "vitest";
+
+import { ApktoolCommandCleanup } from "../../../src/apktool/ApktoolCommandCleanup.js";
+import { inspectApktoolClient } from "../../../src/apktool/ApktoolConfiguration.js";
+import { createApktoolProcessFixture } from "../../fixtures/apktoolProcessTree.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { observePosixProcess } from "../../support/process/observePosixProcess.js";
+
+it
+ .skipIf(process.platform === "win32")
+ .each(["malformed", "unreadable"] as const)(
+ "retains fixture cleanup ownership when its published marker becomes %s",
+ async (failure) => {
+ const root = await createTestTempDirectory("rea-apktool-marker-failure-");
+ const fixture = await createApktoolProcessFixture(root, "probe");
+ await expect(fixture.readMarker()).resolves.toBeUndefined();
+ const commands = new ApktoolCommandCleanup();
+ const controller = new AbortController();
+ const probe = inspectApktoolClient(
+ { command: fixture.command, commandSource: "environment" },
+ commands,
+ { signal: controller.signal, environment: process.env },
+ ).catch((cause: unknown) => cause);
+ try {
+ await expect
+ .poll(async () => (await fixture.readMarker())?.ready, {
+ timeout: 10_000,
+ interval: 25,
+ })
+ .toBe(true);
+ const marker = await fixture.readMarker();
+ if (marker === undefined) throw new Error("Fixture marker disappeared");
+ const pids = [marker.rootPid, marker.childPid];
+ expect(await Promise.all(pids.map(observePosixProcess))).toEqual([
+ expect.objectContaining({ kind: "running" }),
+ expect.objectContaining({ kind: "running" }),
+ ]);
+ if (failure === "malformed") {
+ await writeFile(fixture.markerPath, "not-json");
+ } else {
+ await rm(fixture.markerPath);
+ await mkdir(fixture.markerPath);
+ }
+ await expect(fixture.readMarker()).rejects.toThrow();
+ // No cancellation has run: fallback teardown must use the last valid
+ // token owner even when the current marker cannot be read or parsed.
+ await expect(fixture.cleanup()).rejects.toThrow();
+ await expect
+ .poll(
+ async () =>
+ (await Promise.all(pids.map(observePosixProcess))).every(
+ ({ kind }) => kind !== "running",
+ ),
+ { timeout: 5_000, interval: 25 },
+ )
+ .toBe(true);
+ } finally {
+ controller.abort();
+ await fixture.cleanup([probe, commands.close()]);
+ }
+ },
+ 30_000,
+);
diff --git a/tests/boundary/providers/posixProcessObservation.test.ts b/tests/boundary/providers/posixProcessObservation.test.ts
new file mode 100644
index 000000000..968e3aee5
--- /dev/null
+++ b/tests/boundary/providers/posixProcessObservation.test.ts
@@ -0,0 +1,84 @@
+import { chmod, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { observePosixProcess } from "../../support/process/observePosixProcess.js";
+
+it.skipIf(process.platform === "win32")(
+ "distinguishes absent, zombie, running, and unknown ps observations",
+ async () => {
+ const directory = await createTestTempDirectory("rea-posix-process-state-");
+ const checker = join(directory, "ps");
+ const previousPath = process.env.PATH;
+ const setChecker = async (body: string): Promise<void> => {
+ await writeFile(checker, `#!/bin/sh\n${body}\n`);
+ await chmod(checker, 0o700);
+ process.env.PATH = directory;
+ };
+
+ try {
+ await setChecker("printf 'S\\n'");
+ await expect(observePosixProcess(123)).resolves.toEqual({
+ kind: "running",
+ state: "S",
+ });
+
+ await setChecker("printf 'Z+\\n'");
+ await expect(observePosixProcess(123)).resolves.toEqual({
+ kind: "zombie",
+ state: "Z+",
+ });
+
+ await setChecker(":");
+ await expect(observePosixProcess(123)).resolves.toEqual({
+ kind: "absent",
+ });
+
+ await setChecker("exit 1");
+ await expect(observePosixProcess(123)).resolves.toEqual({
+ kind: "absent",
+ });
+
+ await setChecker("printf 'checker failed\\n' >&2");
+ await expect(observePosixProcess(123)).rejects.toThrow(
+ "Process observation emitted diagnostics",
+ );
+
+ await setChecker("printf ' \\n' >&2; exit 1");
+ await expect(observePosixProcess(123)).rejects.toMatchObject({
+ code: 1,
+ });
+
+ await setChecker("printf 'permission denied\\n' >&2; exit 1");
+ await expect(observePosixProcess(123)).rejects.toMatchObject({
+ code: 1,
+ });
+
+ await setChecker("printf 'S\\n'; exit 1");
+ await expect(observePosixProcess(123)).rejects.toMatchObject({
+ code: 1,
+ });
+
+ await setChecker("printf 'checker failed\\n' >&2; exit 2");
+ await expect(observePosixProcess(123)).rejects.toMatchObject({
+ code: 2,
+ });
+
+ process.env.PATH = directory;
+ await rm(checker);
+ await expect(observePosixProcess(123)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+
+ if (previousPath === undefined) delete process.env.PATH;
+ else process.env.PATH = previousPath;
+ await expect(observePosixProcess(process.pid)).resolves.toMatchObject({
+ kind: "running",
+ });
+ } finally {
+ if (previousPath === undefined) delete process.env.PATH;
+ else process.env.PATH = previousPath;
+ }
+ },
+);
diff --git a/tests/fixtures/apktoolProcessTree.mjs b/tests/fixtures/apktoolProcessTree.mjs
new file mode 100644
index 000000000..3d2850311
--- /dev/null
+++ b/tests/fixtures/apktoolProcessTree.mjs
@@ -0,0 +1,59 @@
+import { spawn } from "node:child_process";
+import { writeFileSync, renameSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+
+const keepAlive = () => setInterval(() => {}, 1_000);
+
+export const run = ({ mode, markerPath }) => {
+ const operation = process.argv[2];
+ if (mode === "decode" && operation === "--version") {
+ process.stdout.write("2.9.3\n");
+ return;
+ }
+ if (
+ (mode !== "probe" && mode !== "decode") ||
+ operation !== (mode === "probe" ? "--version" : "d")
+ )
+ throw new Error(`Unexpected Apktool fixture invocation: ${operation}`);
+ const runId = process.env.REA_PROCESS_RUN_ID;
+ if (typeof runId !== "string" || runId.length === 0)
+ throw new Error("Apktool fixture has no owned process run token");
+ if (mode === "decode") process.on("SIGTERM", () => {});
+ const child = spawn(
+ process.execPath,
+ [fileURLToPath(import.meta.url), "child", mode],
+ {
+ stdio: ["ignore", "inherit", "inherit", "ipc"],
+ },
+ );
+ const timer = keepAlive();
+ const publish = (ready) => {
+ if (child.pid === undefined) throw new Error("Fixture child has no PID");
+ const temporary = `${markerPath}.tmp`;
+ writeFileSync(
+ temporary,
+ JSON.stringify({
+ rootPid: process.pid,
+ childPid: child.pid,
+ runId,
+ ready,
+ }),
+ );
+ renameSync(temporary, markerPath);
+ };
+ child.once("spawn", () => publish(false));
+ child.on("message", (message) => {
+ if (message === "ready") publish(true);
+ });
+ child.once("error", (cause) => {
+ clearInterval(timer);
+ process.stderr.write(`${cause.message}\n`);
+ process.exitCode = 1;
+ });
+};
+
+if (process.argv[2] === "child") {
+ if (process.argv[3] === "decode") process.on("SIGTERM", () => {});
+ keepAlive();
+ process.send("ready");
+}
diff --git a/tests/fixtures/apktoolProcessTree.ts b/tests/fixtures/apktoolProcessTree.ts
new file mode 100644
index 000000000..3b367c93e
--- /dev/null
+++ b/tests/fixtures/apktoolProcessTree.ts
@@ -0,0 +1,120 @@
+import { readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { onTestFinished } from "vitest";
+import { z } from "zod";
+import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js";
+
+const markerSchema = z.object({
+ rootPid: z.int().positive(),
+ childPid: z.int().positive(),
+ runId: z.string().min(1),
+ ready: z.boolean(),
+});
+
+/** Bound the observation, clearing its timer on both settlement paths. */
+export const awaitApktoolOperation = async <T>(
+ pending: Promise<T>,
+ timeoutMs: number,
+): Promise<T> => {
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ return await Promise.race([
+ pending,
+ new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(
+ () =>
+ reject(
+ new Error(
+ `Apktool fixture operation did not settle within ${String(timeoutMs)} ms`,
+ ),
+ ),
+ timeoutMs,
+ );
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
+/** One public-command fixture, its published identity, and token-verified teardown. */
+export const createApktoolProcessFixture = async (
+ root: string,
+ mode: "probe" | "decode",
+) => {
+ const command = join(root, "apktool");
+ const markerPath = join(root, "pids.json");
+ const producer = new URL("./apktoolProcessTree.mjs", import.meta.url).href;
+ await writeFile(
+ command,
+ [
+ `#!${process.execPath}`,
+ `import(${JSON.stringify(producer)}).then(({ run }) => run(${JSON.stringify({ mode, markerPath })}));`,
+ "",
+ ].join("\n"),
+ { mode: 0o700, flag: "wx" },
+ );
+ let owner: z.infer<typeof markerSchema> | undefined;
+ let released = false;
+ const readMarker = async () => {
+ let text: string;
+ try {
+ text = await readFile(markerPath, "utf8");
+ } catch (cause: unknown) {
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
+ return undefined;
+ throw cause;
+ }
+ const marker = markerSchema.parse(JSON.parse(text));
+ if (
+ owner !== undefined &&
+ (marker.rootPid !== owner.rootPid ||
+ marker.childPid !== owner.childPid ||
+ marker.runId !== owner.runId)
+ )
+ throw new Error("Apktool fixture marker changed its process identity");
+ owner = marker;
+ return marker;
+ };
+ const cleanup = async (operations: readonly Promise<unknown>[] = []) => {
+ const settled = await Promise.allSettled(
+ operations.map((operation) => awaitApktoolOperation(operation, 10_000)),
+ );
+ const failures = settled.flatMap((outcome) =>
+ outcome.status === "rejected" ? [outcome.reason as unknown] : [],
+ );
+ if (!released) {
+ try {
+ await readMarker();
+ } catch (cause: unknown) {
+ failures.push(cause);
+ }
+ if (owner !== undefined) {
+ try {
+ const result = await cleanupOwnedProcessGroup({
+ runId: owner.runId,
+ leaderPid: owner.rootPid,
+ processGroupId: owner.rootPid,
+ });
+ if (result.cleaned) released = true;
+ else
+ failures.push(
+ new Error(
+ `Apktool fixture cleanup remains unverified: ${result.reason}`,
+ ),
+ );
+ } catch (cause: unknown) {
+ failures.push(cause);
+ }
+ }
+ }
+ if (failures.length === 1) throw failures[0];
+ if (failures.length > 1)
+ throw new AggregateError(
+ failures,
+ "Apktool fixture settlement and cleanup failures",
+ );
+ };
+ onTestFinished(() => cleanup());
+ return { command, markerPath, readMarker, cleanup };
+};
diff --git a/tests/support/process/observePosixProcess.ts b/tests/support/process/observePosixProcess.ts
new file mode 100644
index 000000000..5f6b373f4
--- /dev/null
+++ b/tests/support/process/observePosixProcess.ts
@@ -0,0 +1,49 @@
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+
+const execFileAsync = promisify(execFile);
+
+/** Observable POSIX process state; unknown states remain rejected by the caller. */
+export type PosixProcessObservation =
+ | { readonly kind: "absent" }
+ | { readonly kind: "zombie"; readonly state: string }
+ | { readonly kind: "running"; readonly state: string };
+
+/** Observe one PID with ps without signaling it or treating checker faults as absence. */
+export const observePosixProcess = async (
+ pid: number,
+): Promise<PosixProcessObservation> => {
+ let stdout: string;
+ try {
+ const result = await execFileAsync("ps", [
+ "-o",
+ "stat=",
+ "-p",
+ String(pid),
+ ]);
+ if (result.stderr !== "")
+ throw new Error(
+ `Process observation emitted diagnostics: ${result.stderr}`,
+ );
+ stdout = result.stdout;
+ } catch (cause: unknown) {
+ if (
+ cause instanceof Error &&
+ "code" in cause &&
+ cause.code === 1 &&
+ "stdout" in cause &&
+ typeof cause.stdout === "string" &&
+ cause.stdout.trim() === "" &&
+ "stderr" in cause &&
+ cause.stderr === ""
+ )
+ return { kind: "absent" };
+ throw cause;
+ }
+
+ const state = stdout.trim();
+ if (state === "") return { kind: "absent" };
+ return state.startsWith("Z")
+ ? { kind: "zombie", state }
+ : { kind: "running", state };
+};