From 53bf26fcaba4c9920b399f28455434309130aaf6 Mon Sep 17 00:00:00 2001 From: rebuildup Date: Thu, 26 Nov 2026 23:30:35 +0900 Subject: [PATCH] fix(guard): unify pid liveness to alive/dead/unknown tri-state --- packages/ae-devtools-cli/devtools-cli/cli.mjs | 3 +- .../devtools-cli/session-guard.mjs | 205 ++++++++++++++---- .../devtools-cli/tests/run.mjs | 186 +++++++++++++++- .../recovery-orchestrator/cli.mjs | 14 +- .../recovery-orchestrator/orchestrator.mjs | 98 +++++++-- .../recovery-orchestrator/tests/run.mjs | 70 ++++++ 6 files changed, 496 insertions(+), 80 deletions(-) diff --git a/packages/ae-devtools-cli/devtools-cli/cli.mjs b/packages/ae-devtools-cli/devtools-cli/cli.mjs index 9ee6496..abc820f 100644 --- a/packages/ae-devtools-cli/devtools-cli/cli.mjs +++ b/packages/ae-devtools-cli/devtools-cli/cli.mjs @@ -298,7 +298,8 @@ async function main() { runsDir: RUNS_DIR, runs: runs.map((r) => ({ runId: r.runId, status: r.status, sessionKind: r.sessionKind, - runnerAlive: r.runnerAlive, reapable: r.reapable, + runnerAlive: r.runnerAlive, runnerLiveness: r.runnerLiveness ?? null, + reapable: r.reapable, reapBlockReason: r.reapBlockReason ?? null, ownership: r.session?.ownership?.kind ?? null, })), diff --git a/packages/ae-devtools-cli/devtools-cli/session-guard.mjs b/packages/ae-devtools-cli/devtools-cli/session-guard.mjs index 79a3f99..643fd16 100644 --- a/packages/ae-devtools-cli/devtools-cli/session-guard.mjs +++ b/packages/ae-devtools-cli/devtools-cli/session-guard.mjs @@ -32,7 +32,9 @@ * recovery-orchestrator workstream, not this file. * * Reap rules (fail-closed, mirrors ae-a8n ownership semantics): - * - runner pid alive → refuse (the owner may still clean up) + * - runner liveness "alive" → refuse (the owner may still clean up) + * - runner liveness "unknown" → refuse (unproven is never dead — + * reap/authorize require PROOF, not the absence of contradiction) * - runner pid dead + pid reuse → refuse unless start-time evidence matches * - ownership.kind !== "owned" → report only, NEVER quit (attached/unknown * hosts belong to someone else; ae-a8n pendingLaunch stays provenance) @@ -73,27 +75,67 @@ export const RUNS_DIR = process.env.AE_DEVTOOLS_CLI_RUNS_DIR export const RUN_ID_RE = /^run-[A-Za-z0-9-]+$/; /** - * pid liveness. Canonical rule (Issue #253 item 2): a pid counts as - * ALIVE only when kill(pid, 0) succeeds or fails with EPERM (the - * process exists but is not ours to signal). ESRCH proves death; ANY - * other error (EINVAL, unexpected errno) counts as dead because - * liveness is unproven — "dead unless proven alive" is the fail-closed - * direction for quit/recovery authorization. This is deliberately - * stricter than ae-a8n's defaultPidAlive (ESRCH-only death); the - * orchestrator's authorizeRecovery probes and the guard's - * reap/listRuns share THIS judgment — the divergence the issue - * resolved in favor of session-guard semantics. + * Tri-state pid liveness — the canonical judgment (Issue #423). + * + * "alive" — kill(pid, 0) succeeded, or failed with EPERM: the process + * exists (EPERM means it is not ours to signal, but it is + * provably there). + * "dead" — kill(pid, 0) failed with ESRCH: the ONE errno that proves + * no such process exists. + * "unknown" — EVERYTHING else: an unexpected errno (EINVAL, …), a + * thrown non-errno, an invalid pid argument. Liveness is + * unproven and must never be read as either alive or dead. + * + * This deliberately differs from BOTH previous local readings: + * ae-a8n's defaultPidAlive treats every non-ESRCH error as alive + * ("alive unless proven dead" — safe for lease inspection, but it can + * never prove death); the old pidAlive here treated every non-EPERM + * error as dead ("dead unless proven alive" — UNSAFE for reap, where a + * probe failure could be mistaken for a dead runner and authorize a + * quit). alive/dead/unknown are three distinct states; consumers pick + * the proof they require: + * + * - reap / verify-exit need DEATH proof → proceed only on "dead" + * - recover authorization needs ALIVE proof → proceed only on "alive" + * - anything else → refuse / report unknown */ -export function pidAlive(pid, kill = process.kill.bind(process)) { - if (!Number.isInteger(pid) || pid <= 0) return false; +export function pidLiveness(pid, kill = process.kill.bind(process)) { + if (!Number.isInteger(pid) || pid <= 0) return "unknown"; try { kill(pid, 0); - return true; + return "alive"; } catch (e) { - return e?.code === "EPERM"; + if (e?.code === "EPERM") return "alive"; + if (e?.code === "ESRCH") return "dead"; + return "unknown"; } } +/** + * Boolean view of pidLiveness: true ONLY when liveness is proven "alive". + * Kept for callers that only need the alive proof (session confirmation, + * ae-a8n lease probe fallback). Callers that require death proof must use + * pidLiveness — `false` here conflates "dead" and "unknown". + */ +export function pidAlive(pid, kill = process.kill.bind(process)) { + return pidLiveness(pid, kill) === "alive"; +} + +/** + * Normalize an injected liveness probe result. Probes may return the + * tri-state string ("alive"|"dead"|"unknown", preferred) or a legacy + * boolean (true = alive, false = dead — a boolean cannot express + * "unknown", so legacy injectors keep their historical meaning). + */ +export function livenessValue(probeResult) { + if (probeResult === "alive" || probeResult === "dead" || probeResult === "unknown") return probeResult; + if (probeResult === true) return "alive"; + if (probeResult === false) return "dead"; + // Anything else — null, undefined, numbers, arbitrary objects — is not + // a liveness answer at all: "unknown", never a guessed state. + return "unknown"; +} + /** Raw `ps lstart` string for pid-reuse detection; null when unreadable. */ export function processStartStamp(pid, exec = execFileAsync) { return exec("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 5_000 }) @@ -308,13 +350,57 @@ export function endRun(dir, runId, status) { } /** - * Classify every marker. `aliveFn(pid)` decides runner liveness; when the - * marker recorded a pidStartStamp, a live pid whose stamp differs is PID - * reuse and counts as dead. + * Call an injected liveness probe defensively: a probe that throws + * proves nothing — the result is "unknown", never a crash and never a + * guessed state. + */ +function probeLivenessSafe(aliveFn, pid) { + try { + return livenessValue(aliveFn(pid)); + } catch { + return "unknown"; + } +} + +/** + * Resolve the RUNNING runner's effective liveness for a marker, including + * the PID-reuse downgrade: a pid proven "alive" whose recorded start + * stamp no longer matches is reuse — the recorded runner is gone, so the + * residue is reapable ("dead" for our purposes). An alive pid whose + * stamp CANNOT be read is "unknown": it may be the recorded runner or a + * reuser, and neither death nor continued ownership is proven. + * + * `aliveFn(pid)` may return "alive"|"dead"|"unknown" (preferred) or a + * legacy boolean. Shared by listRuns and reapRun so the reported + * reapable flag can never disagree with the reap verdict. + */ +async function runnerLiveness(marker, { aliveFn = pidLiveness, stampFn = processStartStamp } = {}) { + let state = probeLivenessSafe(aliveFn, marker.pid); + if (state === "alive" && marker.pidStartStamp && stampFn) { + let stamp = null; + try { + stamp = await stampFn(marker.pid); + } catch { + stamp = null; // unreadable stamp → unknown below + } + if (stamp === null) { + state = "unknown"; + } else if (stamp !== marker.pidStartStamp) { + state = "dead"; // pid reuse — the recorded runner is gone + } + } + return state; +} + +/** + * Classify every marker. `aliveFn(pid)` decides runner liveness + * (tri-state preferred, legacy boolean accepted); when the marker + * recorded a pidStartStamp, a live pid whose stamp differs is PID + * reuse and counts as dead, while an unreadable stamp is "unknown". */ export async function listRuns({ dir = RUNS_DIR, - aliveFn = pidAlive, + aliveFn = pidLiveness, stampFn = processStartStamp, } = {}) { let files = []; @@ -328,11 +414,7 @@ export async function listRuns({ const runId = f.replace(/\.json$/, ""); const marker = readMarker(dir, runId); if (marker === null) continue; - let runnerAlive = aliveFn(marker.pid); - if (runnerAlive && marker.pidStartStamp && stampFn) { - const now = await stampFn(marker.pid); - if (now !== null && now !== marker.pidStartStamp) runnerAlive = false; - } + const runnerState = await runnerLiveness(marker, { aliveFn, stampFn }); const owned = marker.session?.ownership?.kind === "owned"; // reapable must mirror reap()'s gates, not just ownership: without // ae-a8n attestation and an app/install identity reap always @@ -343,19 +425,22 @@ export async function listRuns({ typeof att?.ownershipEvidence === "string" && att.ownershipEvidence.length > 0 && Number.isInteger(marker.session?.process?.aePid); const hasAppIdentity = marker.session?.appPath != null || marker.session?.installDir != null; - const reapBlockReason = runnerAlive + const reapBlockReason = runnerState === "alive" ? "RUNNER_ALIVE" - : owned !== true - ? "OWNERSHIP_NOT_OWNED" - : !attested - ? "NO_A8N_ATTESTATION" - : !hasAppIdentity - ? "NO_APP_IDENTITY" - : null; + : runnerState === "unknown" + ? "RUNNER_LIVENESS_UNKNOWN" + : owned !== true + ? "OWNERSHIP_NOT_OWNED" + : !attested + ? "NO_A8N_ATTESTATION" + : !hasAppIdentity + ? "NO_APP_IDENTITY" + : null; runs.push({ ...marker, markerPath: markerPath(dir, runId), - runnerAlive, + runnerAlive: runnerState === "alive", + runnerLiveness: runnerState, reapable: reapBlockReason === null && marker.status !== "closed", reapBlockReason, }); @@ -391,7 +476,7 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); export async function reapRun(runId, { dir = RUNS_DIR, confirm = false, - aliveFn = pidAlive, + aliveFn = pidLiveness, stampFn = processStartStamp, exec = execFileAsync, now = () => Date.now(), @@ -406,12 +491,21 @@ export async function reapRun(runId, { if (marker === null) return { runId, verdict: "NO_MARKER" }; if (marker.status === "closed") return { runId, verdict: "ALREADY_CLOSED" }; - let runnerAlive = aliveFn(marker.pid); - if (runnerAlive && marker.pidStartStamp && stampFn) { - const stamp = await stampFn(marker.pid); - if (stamp !== null && stamp !== marker.pidStartStamp) runnerAlive = false; + // Reap requires PROOF the runner is dead (ESRCH), not merely "not + // proven alive". "alive" refuses because the owner may still clean + // up; "unknown" (unexpected errno, unreadable start stamp, invalid + // pid) refuses because unproven is never dead (Issue #423). + const runnerState = await runnerLiveness(marker, { aliveFn, stampFn }); + if (runnerState === "alive") { + return { runId, verdict: "REFUSED", reason: "RUNNER_ALIVE", pid: marker.pid }; + } + if (runnerState === "unknown") { + return { + runId, verdict: "REFUSED", reason: "RUNNER_LIVENESS_UNKNOWN", pid: marker.pid, + pidStartStamp: marker.pidStartStamp ?? null, + note: "runner pid liveness/identity could not be proven (unexpected probe error or unreadable start stamp) — refusing to treat unknown as dead", + }; } - if (runnerAlive) return { runId, verdict: "REFUSED", reason: "RUNNER_ALIVE", pid: marker.pid }; const ownership = marker.session?.ownership; if (!ownership || ownership.kind !== "owned") { @@ -455,14 +549,23 @@ export async function reapRun(runId, { if (candidates.length === 0) { // No AE under the recorded install — but the attested pid itself may // still be alive somewhere the path-based scan cannot see. Declaring - // CLEAN then would be a lie. - if (aliveFn(proc.aePid)) { + // CLEAN then would be a lie, and so would declaring it on an + // UNPROVEN liveness: only a proven-dead attested pid allows CLEAN. + const aeState = probeLivenessSafe(aliveFn, proc.aePid); + if (aeState === "alive") { return { runId, verdict: "REFUSED", reason: "ATTESTED_PID_ALIVE_UNMATCHED", attestedPid: proc.aePid, note: "the attested aePid is still alive but was not found under the recorded install path — refusing to declare clean", }; } + if (aeState === "unknown") { + return { + runId, verdict: "REFUSED", reason: "ATTESTED_PID_LIVENESS_UNKNOWN", + attestedPid: proc.aePid, + note: "the attested aePid's liveness could not be proven (unexpected probe error) — refusing to declare clean on unknown", + }; + } endRun(dir, runId, "closed"); return { runId, verdict: "CLEAN", note: "no live AE process for the recorded install" }; } @@ -485,8 +588,24 @@ export async function reapRun(runId, { }; } if (proc.aePidStartStamp && stampFn) { - const stamp = await stampFn(candidate.pid); - if (stamp === null || stamp !== proc.aePidStartStamp) { + let stamp = null; + try { + stamp = await stampFn(candidate.pid); + } catch { + stamp = null; // unreadable stamp → identity unknown below + } + if (stamp === null) { + // The pid is alive (found by the scan) but its start stamp cannot + // be read — identity is unproven, which is NOT the same as proven + // reuse. Both refuse; the reasons stay distinct for forensics. + return { + runId, verdict: "REFUSED", reason: "PID_IDENTITY_UNKNOWN", + candidate, + attestedPid: proc.aePid, + note: "the attested pid's start stamp could not be read — process identity unproven, refusing to quit", + }; + } + if (stamp !== proc.aePidStartStamp) { return { runId, verdict: "REFUSED", reason: "PID_REUSED", candidate, diff --git a/packages/ae-devtools-cli/devtools-cli/tests/run.mjs b/packages/ae-devtools-cli/devtools-cli/tests/run.mjs index 7bfe30d..452376c 100644 --- a/packages/ae-devtools-cli/devtools-cli/tests/run.mjs +++ b/packages/ae-devtools-cli/devtools-cli/tests/run.mjs @@ -10,7 +10,7 @@ import { fileURLToPath } from "node:url"; import { beginRun, markSession, endRun, listRuns, reapRun, noteSessionProcess, - attachEvidence, pidAlive, processStartStampSync, ATTESTATION_SOURCE, + attachEvidence, pidAlive, pidLiveness, livenessValue, processStartStampSync, ATTESTATION_SOURCE, } from "../session-guard.mjs"; import { failureOutcome, isFailureResult, normalizedOutcome, isUnknownOutcome } from "../../dev-loop/outcomes.mjs"; import { parseArgs, arg as argvArg, hasFlag } from "../argv.mjs"; @@ -468,6 +468,144 @@ await at("guard: single AE candidate that is NOT the attested pid is never quit" } }); +// ---- liveness tri-state contract (Issue #423) ---- +// reap requires PROOF of runner death (ESRCH). "unknown" — unexpected +// errno, unreadable start stamp, invalid pid — must refuse BEFORE any +// process scan or osascript, and must leave the marker in place. + +async function attestedResidueMarker(dir) { + const { runId } = await beginRun({ dir, sessionKind: "a8n" }); + markSession(dir, runId, { + kind: "a8n", ownership: { kind: "owned", evidence: "t" }, + installDir: "/Applications/Adobe After Effects 2027", + appPath: "/Applications/Adobe After Effects 2027/Adobe After Effects 2027.app", + }); + endRun(dir, runId, "close-failed"); + noteSessionProcess(dir, runId, { + aePid: 4242, + aePidStartStamp: "stamp-ae", + guiSession: { uid: 501, asid: 42 }, + attestation: { + source: ATTESTATION_SOURCE, + ownershipKind: "owned", + ownershipEvidence: "probe answered in owned session", + }, + }); + // Pin the runner start stamp so stamp-probe behavior is deterministic + // regardless of whether the test host's `ps` succeeds inside beginRun. + const mf = join(dir, `${runId}.json`); + const m = JSON.parse(readFileSync(mf, "utf8")); + m.pidStartStamp = "stamp-runner"; + writeFileSync(mf, JSON.stringify(m)); + return runId; +} + +t("guard: reap refuses RUNNER_LIVENESS_UNKNOWN on unexpected probe errno — no scan, no quit, marker kept", async () => { + const dir = mkdtempSync(join(tmpdir(), "guard-test-")); + try { + const runId = await attestedResidueMarker(dir); + const errno = (code) => (pid) => { const e = new Error("x"); e.code = code; throw e; }; + let execCalls = 0; + const exec = async () => { execCalls += 1; return { stdout: "" }; }; + for (const kill of [errno("EINVAL"), () => { throw new Error("no code"); }]) { + const v = await reapRun(runId, { dir, confirm: true, aliveFn: kill, exec }); + assert.equal(v.verdict, "REFUSED"); + assert.equal(v.reason, "RUNNER_LIVENESS_UNKNOWN"); + assert.equal(v.pid, process.pid); + } + assert.equal(execCalls, 0, "reap must not scan or quit when runner liveness is unknown"); + assert.ok(existsSync(join(dir, `${runId}.json`)), "marker must be retained on refusal"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +t("guard: reap refuses when runner is alive but start stamp unreadable — unknown, not reuse", async () => { + const dir = mkdtempSync(join(tmpdir(), "guard-test-")); + try { + const runId = await attestedResidueMarker(dir); + // Runner pid alive; recorded stamp exists; ps cannot read it → + // identity unproven → refuse (previously this stayed RUNNER_ALIVE; + // now it is explicitly UNKNOWN and still refuses). + const v = await reapRun(runId, { + dir, confirm: true, + aliveFn: () => "alive", + stampFn: async () => null, + exec: async () => { throw new Error("must not exec"); }, + }); + assert.equal(v.verdict, "REFUSED"); + assert.equal(v.reason, "RUNNER_LIVENESS_UNKNOWN"); + assert.ok(existsSync(join(dir, `${runId}.json`))); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +t("guard: reap refuses ATTESTED_PID_LIVENESS_UNKNOWN instead of declaring CLEAN", async () => { + const dir = mkdtempSync(join(tmpdir(), "guard-test-")); + try { + const runId = await attestedResidueMarker(dir); + // Runner proven dead (ESRCH); no AE candidates under the install; + // the attested aePid's own liveness probe errors unexpectedly. + const v = await reapRun(runId, { + dir, confirm: true, + aliveFn: (pid) => (pid === 4242 + ? (() => { const e = new Error("x"); e.code = "EINVAL"; throw e; })() + : "dead"), + exec: async (cmd, args) => { + if (cmd === "ps" && args[0] === "-axo") return { stdout: "" }; + return { stdout: "" }; + }, + }); + assert.equal(v.verdict, "REFUSED"); + assert.equal(v.reason, "ATTESTED_PID_LIVENESS_UNKNOWN"); + assert.equal(v.attestedPid, 4242); + assert.ok(existsSync(join(dir, `${runId}.json`)), "marker must NOT be closed on unknown"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +t("guard: reap refuses PID_IDENTITY_UNKNOWN when attested stamp is unreadable", async () => { + const dir = mkdtempSync(join(tmpdir(), "guard-test-")); + try { + const runId = await attestedResidueMarker(dir); + const exec = async (cmd, args) => { + if (cmd === "ps" && args[0] === "-axo") { + return { stdout: " 4242 /Applications/Adobe After Effects 2027/Adobe After Effects 2027.app/Contents/MacOS/After Effects\n" }; + } + return { stdout: "" }; + }; + const v = await reapRun(runId, { + dir, confirm: true, + aliveFn: () => "dead", + stampFn: async () => null, // ps cannot read the live candidate's stamp + exec, + }); + assert.equal(v.verdict, "REFUSED"); + assert.equal(v.reason, "PID_IDENTITY_UNKNOWN"); + assert.ok(existsSync(join(dir, `${runId}.json`))); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +t("guard: listRuns reports RUNNER_LIVENESS_UNKNOWN and not reapable", async () => { + const dir = mkdtempSync(join(tmpdir(), "guard-test-")); + try { + await attestedResidueMarker(dir); + const errno = (pid) => { const e = new Error("x"); e.code = "EINVAL"; throw e; }; + const runs = await listRuns({ dir, aliveFn: errno, stampFn: async () => null }); + assert.equal(runs.length, 1); + assert.equal(runs[0].runnerLiveness, "unknown"); + assert.equal(runs[0].runnerAlive, false); + assert.equal(runs[0].reapable, false); + assert.equal(runs[0].reapBlockReason, "RUNNER_LIVENESS_UNKNOWN"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + // ---- failure diagnostics + diagnose (Issue #103, fake level only) ---- t("completed execute carries no diagnostics block (additive contract)", () => { @@ -957,18 +1095,36 @@ await at("guard: reap passes the quit target via osascript argv, never interpola } }); -// ---- pidAlive canonical semantics (Issue #253 item 2) ---- -// The guard and the recovery orchestrator share this probe; the pinned -// rule is "alive only on kill-success or EPERM" — stricter than -// ae-a8n's ESRCH-only defaultPidAlive. A non-ESRCH kill error must NOT -// count as alive: unproven liveness is the unsafe direction for -// quit/recovery authorization. +// ---- pidLiveness canonical semantics (Issues #253 item 2, #423) ---- +// The guard and the recovery orchestrator share this probe. alive/dead/ +// unknown are three DISTINCT states: "alive" only on kill-success or +// EPERM, "dead" ONLY on ESRCH, and EVERY other outcome — unexpected +// errno, a thrown non-errno, an invalid pid — is "unknown". Paths that +// require death proof (reap, verify-exit) must refuse on "unknown"; +// paths that require alive proof (authorizeRecovery) must refuse on +// anything but "alive". pidAlive remains the boolean "proven alive" +// view for alive-only consumers. + +t("guard: pidLiveness — success/EPERM alive, ESRCH dead, everything else unknown", () => { + const errno = (code) => () => { const e = new Error("x"); e.code = code; throw e; }; + assert.equal(pidLiveness(1234, () => {}), "alive"); + assert.equal(pidLiveness(1234, errno("EPERM")), "alive"); + assert.equal(pidLiveness(1234, errno("ESRCH")), "dead"); + assert.equal(pidLiveness(1234, errno("EINVAL")), "unknown"); + assert.equal(pidLiveness(1234, () => { throw new Error("no code"); }), "unknown"); + assert.equal(pidLiveness(0, () => {}), "unknown"); + assert.equal(pidLiveness(-1, () => {}), "unknown"); + assert.equal(pidLiveness(1.5, () => {}), "unknown"); + assert.equal(pidLiveness("1234", () => {}), "unknown"); + assert.equal(pidLiveness(NaN, () => {}), "unknown"); +}); -t("guard: pidAlive — success and EPERM alive, ESRCH/other errors dead", () => { +t("guard: pidAlive is the proven-alive boolean view of pidLiveness", () => { + const errno = (code) => () => { const e = new Error("x"); e.code = code; throw e; }; assert.equal(pidAlive(1234, () => {}), true); - assert.equal(pidAlive(1234, () => { const e = new Error("x"); e.code = "EPERM"; throw e; }), true); - assert.equal(pidAlive(1234, () => { const e = new Error("x"); e.code = "ESRCH"; throw e; }), false); - assert.equal(pidAlive(1234, () => { const e = new Error("x"); e.code = "EINVAL"; throw e; }), false); + assert.equal(pidAlive(1234, errno("EPERM")), true); + assert.equal(pidAlive(1234, errno("ESRCH")), false); + assert.equal(pidAlive(1234, errno("EINVAL")), false); assert.equal(pidAlive(1234, () => { throw new Error("no code"); }), false); assert.equal(pidAlive(0, () => {}), false); assert.equal(pidAlive(-1, () => {}), false); @@ -976,6 +1132,14 @@ t("guard: pidAlive — success and EPERM alive, ESRCH/other errors dead", () => assert.equal(pidAlive("1234", () => {}), false); }); +t("guard: livenessValue normalizes tri-state and legacy boolean probes", () => { + assert.equal(livenessValue("alive"), "alive"); + assert.equal(livenessValue("dead"), "dead"); + assert.equal(livenessValue("unknown"), "unknown"); + assert.equal(livenessValue(true), "alive"); + assert.equal(livenessValue(false), "dead"); +}); + t("guard: processStartStampSync returns trimmed stamp or null", () => { const stamp = processStartStampSync(1, () => " Mon Jan 1 00:00:00 2024\n"); assert.equal(stamp, "Mon Jan 1 00:00:00 2024"); diff --git a/packages/ae-devtools-cli/recovery-orchestrator/cli.mjs b/packages/ae-devtools-cli/recovery-orchestrator/cli.mjs index fe74bc9..135a0b3 100644 --- a/packages/ae-devtools-cli/recovery-orchestrator/cli.mjs +++ b/packages/ae-devtools-cli/recovery-orchestrator/cli.mjs @@ -72,6 +72,7 @@ import { RUNS_DIR, RUN_ID_RE, pidAlive, + pidLiveness, processStartStampSync, } from "../devtools-cli/session-guard.mjs"; import { parseArgs } from "../devtools-cli/argv.mjs"; @@ -191,10 +192,11 @@ function sessionFromFlags(a8n, flags) { /** * Confirm the claimed GUI session and the target pid's attribution via * ae-a8n's live surfaces. Delegates to orchestrator.confirmGuiSession; - * the pid-alive probe is the shared session-guard pidAlive (Issue #253 - * item 2: alive only on kill-success/EPERM — stricter than ae-a8n's - * ESRCH-only defaultPidAlive, which stays inside ae-a8n's own lease - * inspection below). + * the pid probe is the shared session-guard pidLiveness tri-state + * (Issue #423: alive/dead/unknown stay distinct — "unknown" refuses + * instead of being recorded as dead). pidAlive stays injected for the + * legacy boolean contract; ae-a8n's own defaultPidAlive (ESRCH-only + * death) stays inside ae-a8n's lease inspection below. */ function confirmSession(a8n, flags, pid) { const uid = Number(flags["session-uid"]); @@ -203,6 +205,7 @@ function confirmSession(a8n, flags, pid) { deps: { readGuiSession: (u) => a8n.readGuiSession(u), listAppInstances: () => a8n.listAppInstances(), + pidLiveness, pidAlive, }, uid, asid, pid, @@ -334,7 +337,7 @@ async function main() { marker: loaded.marker, requestId, method, - probes: { pidAlive, pidStartStamp: processStartStampSync }, + probes: { pidLiveness, pidAlive, pidStartStamp: processStartStampSync }, }); if (!auth.ok) return fail("RECOVERY_REFUSED", auth.reason, { runId: flags["run-id"] }); @@ -431,6 +434,7 @@ async function main() { const result = verifyHostExit({ pid, pidAlive, + pidLiveness, census, session: sessionCheck.confirmed ? { diff --git a/packages/ae-devtools-cli/recovery-orchestrator/orchestrator.mjs b/packages/ae-devtools-cli/recovery-orchestrator/orchestrator.mjs index 0bef1fd..e54f3e3 100644 --- a/packages/ae-devtools-cli/recovery-orchestrator/orchestrator.mjs +++ b/packages/ae-devtools-cli/recovery-orchestrator/orchestrator.mjs @@ -44,7 +44,7 @@ import { createHash } from "node:crypto"; import { copyFileSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { ATTESTATION_SOURCE, GUARD_SCHEMA, latestRequestEvent } from "../devtools-cli/session-guard.mjs"; +import { ATTESTATION_SOURCE, GUARD_SCHEMA, latestRequestEvent, livenessValue } from "../devtools-cli/session-guard.mjs"; import { supervisionEscalation, supervisionSnapshot, @@ -403,6 +403,28 @@ export function observeScreen({ gui, screenshotDir, requestId }) { // ------------------------------------------------------------ session confirm +/** + * Resolve a pid's liveness through the injected probes. `pidLiveness` + * (tri-state "alive"|"dead"|"unknown") is preferred; the legacy boolean + * `pidAlive` is still accepted — true maps to "alive", false to "dead" + * (a boolean cannot express "unknown"; legacy injectors keep their + * historical meaning). An absent/broken probe yields "unknown", never + * a guessed state. + */ +function probeLiveness(probes, pid) { + try { + if (typeof probes?.pidLiveness === "function") { + return livenessValue(probes.pidLiveness(pid)); + } + if (typeof probes?.pidAlive === "function") { + return probes.pidAlive(pid) ? "alive" : "dead"; + } + } catch { + // A throwing probe proves nothing. + } + return "unknown"; +} + /** * Confirm the claimed GUI session AND the target pid's attribution to it. * @@ -422,7 +444,8 @@ export function observeScreen({ gui, screenshotDir, requestId }) { * is not attributable still refuses. * * `deps` are injected for testing: `readGuiSession(uid)`, - * `listAppInstances()`, `pidAlive(pid)`. + * `listAppInstances()`, and a liveness probe — `pidLiveness(pid)` + * (tri-state, preferred) or legacy `pidAlive(pid)` (boolean). */ export function confirmGuiSession({ deps, uid, asid, pid }) { if (!Number.isFinite(uid)) return { confirmed: false, reason: "--session-uid missing or invalid" }; @@ -445,14 +468,15 @@ export function confirmGuiSession({ deps, uid, asid, pid }) { return { confirmed: false, reason: `claimed asid ${asid} but uid ${uid} GUI session is asid ${live.asid}` }; } - // Pid attribution is only defined for a live process. - let alive; - try { - alive = deps.pidAlive(pid); - } catch (error) { - return { confirmed: false, reason: `pid liveness probe failed: ${String(error?.message ?? error)}` }; + // Pid attribution is only defined for a live process. "unknown" + // liveness is NOT "dead": recording pidAttribution "dead" on an + // unproven probe would launder a probe failure into exit evidence + // (Issue #423) — refuse instead. + const pidState = probeLiveness(deps, pid); + if (pidState === "unknown") { + return { confirmed: false, reason: `pid ${pid} liveness could not be proven — session membership unproven` }; } - if (!alive) { + if (pidState === "dead") { return { confirmed: true, session: live, @@ -554,9 +578,14 @@ export function loadRunMarker(file) { * Authorize a recovery attempt against a loaded marker. * * `probes` are injected so the whole check is testable without live - * processes: `pidAlive(pid)` and `pidStartStamp(pid)` (ps lstart string - * or null). Both must be supplied — there is no "skip the liveness check" - * path. + * processes: a liveness probe — `pidLiveness(pid)` returning + * "alive"|"dead"|"unknown" (preferred) or legacy `pidAlive(pid)` + * boolean — and `pidStartStamp(pid)` (ps lstart string or null). + * Authorization requires PROOF of "alive" for both the runner and the + * AE process: "dead" means residue (reap/adopt, not GUI recovery) and + * "unknown" (unexpected errno, unreadable stamp, broken probe) refuses + * — unproven is never alive (Issue #423). A recorded start stamp that + * probes null is likewise unproven identity, not a pass. */ export function authorizeRecovery({ marker, requestId, method, probes }) { if (TERMINAL_MARKER_STATUSES.has(marker.status)) { @@ -595,25 +624,43 @@ export function authorizeRecovery({ marker, requestId, method, probes }) { // Runner liveness: the process that owns this run must still be alive // with the same start stamp, or this marker is residue for `reap`, not - // a live authorization. - if (!probes.pidAlive(marker.pid)) { + // a live authorization. Only proven "alive" authorizes — "dead" is + // residue and "unknown" is unproven (Issue #423). + const runnerState = probeLiveness(probes, marker.pid); + if (runnerState === "dead") { return { ok: false, reason: `run ${marker.runId} runner pid ${marker.pid} is dead — residue goes through reap/adopt, not GUI recovery` }; } + if (runnerState !== "alive") { + return { ok: false, reason: `run ${marker.runId} runner pid ${marker.pid} liveness is '${runnerState}' — the owning runner cannot be proven alive` }; + } + // A missing stamp probe reads as "unreadable" — identity unproven, + // never silently skipped. + const stampProbe = typeof probes?.pidStartStamp === "function" ? probes.pidStartStamp : () => null; if (marker.pidStartStamp) { - const now = probes.pidStartStamp(marker.pid); - if (now !== null && now !== marker.pidStartStamp) { + const now = stampProbe(marker.pid); + if (now === null) { + return { ok: false, reason: `run ${marker.runId} runner pid ${marker.pid} start stamp is unreadable — process identity unproven` }; + } + if (now !== marker.pidStartStamp) { return { ok: false, reason: `run ${marker.runId} runner pid ${marker.pid} was reused (start stamp changed) — marker is stale` }; } } // AE process liveness + identity: same pid AND same start stamp, or the // pid was reused by a different process. - if (!probes.pidAlive(proc.aePid)) { + const aeState = probeLiveness(probes, proc.aePid); + if (aeState === "dead") { return { ok: false, reason: `recorded aePid ${proc.aePid} is dead — nothing to recover` }; } + if (aeState !== "alive") { + return { ok: false, reason: `recorded aePid ${proc.aePid} liveness is '${aeState}' — the target process cannot be proven alive` }; + } if (proc.aePidStartStamp) { - const now = probes.pidStartStamp(proc.aePid); - if (now !== null && now !== proc.aePidStartStamp) { + const now = stampProbe(proc.aePid); + if (now === null) { + return { ok: false, reason: `aePid ${proc.aePid} start stamp is unreadable — process identity unproven` }; + } + if (now !== proc.aePidStartStamp) { return { ok: false, reason: `aePid ${proc.aePid} was reused (start stamp changed) — recorded process is gone` }; } } @@ -777,6 +824,7 @@ function verdictForRecovery(outcome) { export function verifyHostExit({ pid, pidAlive, + pidLiveness: pidLivenessProbe = null, census = null, session = null, evidenceDir = null, @@ -809,11 +857,21 @@ export function verifyHostExit({ result.channels.windows.pidAttribution = session?.pidAttribution ?? null; // --- channel 1: process liveness ------------------------------------- + // Tri-state probe preferred (Issue #423): "clean"/"crash-verified" + // require a PROVEN dead process — an unexpected probe error is + // "unknown", never laundered into "dead". The legacy boolean + // `pidAlive` cannot express unknown; false maps to "dead" for + // backward compatibility of injected test doubles. try { - result.channels.process.state = pidAlive(pid) ? "alive" : "dead"; + result.channels.process.state = typeof pidLivenessProbe === "function" + ? livenessValue(pidLivenessProbe(pid)) + : (pidAlive(pid) ? "alive" : "dead"); } catch (error) { result.channels.process.detail = `pid liveness probe failed: ${String(error?.message ?? error)}`; } + if (result.channels.process.state === "unknown" && result.channels.process.detail === null) { + result.channels.process.detail = "pid liveness could not be proven (unexpected probe result)"; + } if (result.channels.process.state === "alive") { result.channels.windows.state = "skipped"; result.channels.windows.detail = "process alive — window census not consulted"; diff --git a/packages/ae-devtools-cli/recovery-orchestrator/tests/run.mjs b/packages/ae-devtools-cli/recovery-orchestrator/tests/run.mjs index 66f6955..b49fa86 100644 --- a/packages/ae-devtools-cli/recovery-orchestrator/tests/run.mjs +++ b/packages/ae-devtools-cli/recovery-orchestrator/tests/run.mjs @@ -362,6 +362,58 @@ t("authorizeRecovery refuses dead runner, reused runner pid, dead/reused aePid", assert.match(authorizeRecovery({ marker: marker(), requestId: "req-1", method: "op.x", probes: reusedAe }).reason, /aePid 4242 was reused/); }); +t("authorizeRecovery refuses liveness 'unknown' for runner and aePid (Issue #423)", () => { + const tri = (state) => ({ ...liveProbes, pidLiveness: () => state }); + for (const state of ["unknown", "dead"]) { + const r = authorizeRecovery({ marker: marker(), requestId: "req-1", method: "op.x", probes: tri(state) }); + assert.equal(r.ok, false); + assert.match(r.reason, state === "dead" ? /runner pid 1000 is dead/ : /runner pid 1000 liveness is 'unknown'/); + } + // Runner alive but AE liveness unknown → still refused before any GUI op. + const probes = { + pidLiveness: (pid) => (pid === 1000 ? "alive" : "unknown"), + pidStartStamp: liveProbes.pidStartStamp, + }; + const r = authorizeRecovery({ marker: marker(), requestId: "req-1", method: "op.x", probes }); + assert.equal(r.ok, false); + assert.match(r.reason, /aePid 4242 liveness is 'unknown'/); + // A throwing liveness probe is unknown, never a crash or a pass. + const throwing = { ...liveProbes, pidLiveness: () => { throw new Error("probe exploded"); } }; + assert.equal(authorizeRecovery({ marker: marker(), requestId: "req-1", method: "op.x", probes: throwing }).ok, false); +}); + +t("authorizeRecovery refuses when a recorded start stamp probes unreadable", () => { + // Runner alive, stamp recorded, ps cannot read it → identity unproven. + const noRunnerStamp = { ...liveProbes, pidStartStamp: (pid) => (pid === 4242 ? "stamp-ae" : null) }; + assert.match( + authorizeRecovery({ marker: marker(), requestId: "req-1", method: "op.x", probes: noRunnerStamp }).reason, + /runner pid 1000 start stamp is unreadable/, + ); + // Same for the AE pid. + const noAeStamp = { ...liveProbes, pidStartStamp: (pid) => (pid === 1000 ? "stamp-runner" : null) }; + assert.match( + authorizeRecovery({ marker: marker(), requestId: "req-1", method: "op.x", probes: noAeStamp }).reason, + /aePid 4242 start stamp is unreadable/, + ); + // A missing stamp probe entirely reads as unreadable, not skipped. + const noStampProbe = { pidAlive: liveProbes.pidAlive }; + assert.match( + authorizeRecovery({ marker: marker(), requestId: "req-1", method: "op.x", probes: noStampProbe }).reason, + /start stamp is unreadable/, + ); +}); + +t("confirmGuiSession refuses pid liveness 'unknown' instead of recording dead", () => { + const deps = { + readGuiSession: () => ({ uid: 501, asid: 42, username: "u", kind: "Aqua" }), + listAppInstances: () => [], + pidLiveness: () => "unknown", + }; + const r = confirmGuiSession({ deps, uid: 501, asid: 42, pid: 4242 }); + assert.equal(r.confirmed, false); + assert.match(r.reason, /liveness could not be proven/); +}); + t("authorizeRecovery refuses markers without ae-a8n attestation provenance", () => { const noAtt = marker(); delete noAtt.session.process.attestation; @@ -455,6 +507,24 @@ t("verifyHostExit: alive process is residue regardless of other channels", () => assert.equal(r.channels.windows.state, "skipped"); }); +t("verifyHostExit: pid liveness 'unknown' is unknown, never clean (Issue #423)", () => { + const r = verifyHostExit({ + pid: 4242, pidLiveness: () => "unknown", + census: CENSUS_CLEAN, session: SESSION_OK, + evidenceDir: tmp(), target: {}, collectEvidence: fakeEvidence({ correlated: 0 }), + }); + assert.equal(r.channels.process.state, "unknown"); + assert.equal(r.verdict, "unknown"); + // Legacy boolean probe still maps false → dead for injected doubles. + const legacy = verifyHostExit({ + pid: 4242, pidAlive: () => false, + census: CENSUS_CLEAN, session: SESSION_OK, + evidenceDir: tmp(), target: {}, collectEvidence: fakeEvidence({ correlated: 0 }), + }); + assert.equal(legacy.channels.process.state, "dead"); + assert.equal(legacy.verdict, "clean"); +}); + t("verifyHostExit: dead + unconfirmed session is unknown, never clean", () => { const r = verifyHostExit({ pid: 4242, pidAlive: () => false,