Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

Async bash() tool for the kernel runtime (#1684)

Sebastian Müller0940833b771f
diff --git a/packages/coding-agent/.changes/repl-01-bash-tool.md b/packages/coding-agent/.changes/repl-01-bash-tool.md
new file mode 100644
index 0000000000..ad96ec1dcb
--- /dev/null
+++ b/packages/coding-agent/.changes/repl-01-bash-tool.md
@@ -0,0 +1,2 @@
+- Added an async-by-default `bash()` callable to the kernel runtime: it returns a live handle immediately (pid/tail/poll/kill/await), bounds in-memory output, and enrolls children in the orphan-process journal so kernel teardown reaps them.
+- Fixed bash() orphan-journal writes marking a child inactive even when the kill signal was not delivered; the record now stays active on delivery failure so the host reaper still owns the process (on Windows a shell that already exited counts as delivered, so clean exits still retire their record).
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index fabcb73bf2..cbb4dd7875 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -1,5 +1,16 @@
# Changelog
+## [Unreleased]
+
+- Fixed bash() cells failing under strict-POSIX shells (dash) when the status pipe landed on a multi-digit fd.
+- Fixed two bash() spawn races: status-channel fds no longer leak when pipe creation fails mid-setup, and a status-socket gate keeps the command from starting until its pid is journaled (a kernel kill in that window now stops the child instead of orphaning it past the reaper).
+- Fixed the Windows orphan reaper killing only the journaled bash() shell pid; it now uses taskkill /T so descendants die with the tree, matching the in-kernel bash() kill paths, and resolves taskkill via an absolute System32 path (with NoDefaultCurrentDirectoryInExePath) so a planted CWD taskkill.exe cannot hijack cleanup.
+- Hardened bash(): cancelling `await bash(cmd)` now kills the command's process group (background handles are unaffected), Windows helper binaries resolve via absolute System32 paths, kill() retries taskkill for already-reaped Windows trees, and orphan-journal enrollment fails closed when configured.
+- Hardened bash() further: the host now injects an absolute default shell into the kernel (no PATH lookup; /bin/bash else /bin/sh on POSIX), macOS start-id lookup uses /bin/ps, and Windows worker-teardown orphan kills go through hardened taskkill /T.
+- Hardened Windows bash execution: the kernel shell is resolved only from trusted absolute paths (never PATH), and bash children are contained by kill-on-close job objects so a crashed kernel cannot leak process trees (taskkill remains only as a fallback when job creation fails).
+- Hardened Windows bash() containment: children are now created directly inside the kill-on-close job (PROC_THREAD_ATTRIBUTE_JOB_LIST at CreateProcessW time), so no window exists in which a kernel kill can leak a suspended, never-run process; handle inheritance is restricted to exactly the child's stdio handles (PROC_THREAD_ATTRIBUTE_HANDLE_LIST), so concurrent spawns cannot leak each other's handles; the journal start-id query still runs only while the job-contained child is suspended, and bash() still raises instead of falling back to jobless taskkill when containment fails.
+- Fixed a Windows bash() PID-reuse hazard: the child process handle is now retained through job cleanup and every taskkill-by-pid fallback (watch reap, kill(), cancel escalation, shutdown cleanup) and closed exactly once only after the handle is marked reaped, so a recycled pid can never be killed by the fallback.
+
## [0.8.1] - 2026-08-26
- Fixed syntax highlighting in the expanded python tool-call view: triple-quoted strings spanning multiple lines now keep their string color instead of only the first line.
diff --git a/packages/coding-agent/src/cli/daemon-ps.ts b/packages/coding-agent/src/cli/daemon-ps.ts
index 518329622d..42c05f9a73 100644
--- a/packages/coding-agent/src/cli/daemon-ps.ts
+++ b/packages/coding-agent/src/cli/daemon-ps.ts
@@ -3,7 +3,12 @@ import { existsSync, lstatSync, readdirSync, readFileSync, rmSync, unlinkSync }
import { basename, dirname, join, resolve } from "node:path";
import chalk from "chalk";
import { APP_NAME, getAgentDir, VERSION } from "../config.js";
-import { isOrphanProcessIdentityCurrent, readActiveOrphanProcesses } from "../core/orphan-process-journal.js";
+import {
+ isOrphanProcessIdentityCurrent,
+ killOrphanProcess,
+ readActiveOrphanProcesses,
+ shouldReapOrphanProcess,
+} from "../core/orphan-process-journal.js";
import { getProcessStartId } from "../core/session-lease.js";
import { DaemonClient } from "../modes/daemon/daemon-client.js";
import {
@@ -938,9 +943,28 @@ async function forceStopTrackedWorkers(
failures.push(`could not read child process records for worker ${descriptor.workerId}: ${String(error)}`);
}
for (const orphan of orphans) {
+ // Pid-only records go through the platform predicate (stopTrackedProcess needs a startId).
+ if (orphan.processStartId === undefined) {
+ if (shouldReapOrphanProcess(orphan)) {
+ killOrphanProcess(orphan.pid);
+ }
+ continue;
+ }
if (!isOrphanProcessIdentityCurrent(orphan)) {
continue;
}
+ if (process.platform === "win32") {
+ // taskkill /T, like the sibling reapers: signalling only the shell pid leaves its descendants alive.
+ await assertAdmission();
+ if (isOrphanProcessIdentityCurrent(orphan)) {
+ killOrphanProcess(orphan.pid);
+ if (isProcessAlive(orphan.pid)) {
+ cleanupWorkerRecords = false;
+ failures.push(`could not stop child process ${orphan.pid} for worker ${descriptor.workerId}`);
+ }
+ }
+ continue;
+ }
if (!(await stopTrackedProcess(orphan.pid, orphan.processStartId, assertAdmission))) {
cleanupWorkerRecords = false;
failures.push(`could not stop child process ${orphan.pid} for worker ${descriptor.workerId}`);
diff --git a/packages/coding-agent/src/cli/owned-session-worker.ts b/packages/coding-agent/src/cli/owned-session-worker.ts
index f7ab375355..26937ae3db 100644
--- a/packages/coding-agent/src/cli/owned-session-worker.ts
+++ b/packages/coding-agent/src/cli/owned-session-worker.ts
@@ -7,9 +7,10 @@ import type { AgentSession } from "../core/agent-session.js";
import type { AgentSessionRuntime } from "../core/agent-session-runtime.js";
import {
clearOrphanProcessJournal,
- isOrphanProcessIdentityCurrent,
+ killOrphanProcess,
ORPHAN_PROCESS_JOURNAL_ENV,
readActiveOrphanProcesses,
+ shouldReapOrphanProcess,
} from "../core/orphan-process-journal.js";
import { SESSION_LEASE_OWNER_ID_ENV, SESSION_LEASES_ENABLED_ENV } from "../core/session-lease.js";
import { attachJsonlLineReader, serializeJsonLine } from "../modes/rpc/jsonl.js";
@@ -297,19 +298,10 @@ export async function runOwnedSessionWorkerFrontend(
}
}
for (const orphan of readActiveOrphanProcesses(orphanProcessJournalPath, workerPid)) {
- if (!isOrphanProcessIdentityCurrent(orphan)) {
+ if (!shouldReapOrphanProcess(orphan)) {
continue;
}
- const { pid } = orphan;
- try {
- process.kill(process.platform === "win32" ? pid : -pid, "SIGKILL");
- } catch {
- try {
- process.kill(pid, "SIGKILL");
- } catch {
- // The detached resource may already have exited.
- }
- }
+ killOrphanProcess(orphan.pid);
}
clearOrphanProcessJournal(orphanProcessJournalPath);
};
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index 96a4dce54d..2025bc9464 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -8956,6 +8956,8 @@ export class AgentSession {
const notifyRestore = !this._ipythonRuntimeBuilt;
this._ipythonKernelProvisioner = new IpythonKernelProvisioner(this._cwd, {
env: this._rlmKernelEnv(),
+ commandPrefix: this.settingsManager.getShellCommandPrefix(),
+ shellPath: this.settingsManager.getShellPath(),
sessionId: this.sessionId,
hostHandlers: this._createKernelHostHandlers(),
pythonSkills,
diff --git a/packages/coding-agent/src/core/kernel/bootstrap.ts b/packages/coding-agent/src/core/kernel/bootstrap.ts
index b3f6d3adcd..ac73b943eb 100644
--- a/packages/coding-agent/src/core/kernel/bootstrap.ts
+++ b/packages/coding-agent/src/core/kernel/bootstrap.ts
@@ -51,7 +51,7 @@ const REQUIRED_HARNESS_METHODS = [
"delete_prompt_note",
"record_refinement",
];
-const RUNTIME_READY_CHECK = `import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ${JSON.stringify(REQUIRED_HARNESS_METHODS)}; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert hasattr(rlm, 'run'); assert callable(rlm); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background')`;
+const RUNTIME_READY_CHECK = `import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ${JSON.stringify(REQUIRED_HARNESS_METHODS)}; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert hasattr(rlm, 'run'); assert callable(rlm); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__)`;
const BOOTSTRAP_VERSION_FILE = ".bootstrap-version";
const BOOTSTRAP_LOCK_NAME = ".bootstrap.lock";
const BOOTSTRAP_LOCK_RETRY_MS = 100;
diff --git a/packages/coding-agent/src/core/kernel/index.ts b/packages/coding-agent/src/core/kernel/index.ts
index e12cde055d..3bf9254b21 100644
--- a/packages/coding-agent/src/core/kernel/index.ts
+++ b/packages/coding-agent/src/core/kernel/index.ts
@@ -7,7 +7,7 @@ import { setTimeout as sleep } from "node:timers/promises";
import { registerSessionResourceCleanup } from "@earendil-works/pi-ai";
import { v4 as uuid } from "uuid";
import { Dealer, Subscriber } from "zeromq";
-import { recordOrphanProcessState } from "../orphan-process-journal.js";
+import { reapKernelOrphanProcesses, recordOrphanProcessState } from "../orphan-process-journal.js";
import { ensureKernelPython, type KernelBootstrapProgressHandler, type KernelPythonSkill } from "./bootstrap.js";
import { type ForkedKernelHandle, ForkServerUnavailable, forkKernel, isForkServerEnabled } from "./fork-server.js";
import {
@@ -708,7 +708,7 @@ export class KernelManager {
cwd: this.options.cwd,
// Applied fresh in the child (the template's env snapshot may be stale).
// No JPY_PARENT_PID: forked children watch the forkserver by getppid().
- env: { ...process.env, ...this.options.env },
+ env: { ...process.env, ...this.options.env, PRIME_AGENT_KERNEL_OWNER_PID: String(process.pid) },
});
if (this.startStale(generation)) {
// Nobody owns this kernel; the protocol kill is id-keyed and safe.
@@ -742,7 +742,12 @@ export class KernelManager {
const kernel = spawn(python, ["-m", "ipykernel_launcher", "-f", connection.path], {
cwd: this.options.cwd,
// ipykernel's parent poller exits the kernel if this pid dies (covers SIGKILL of the owner).
- env: { ...process.env, ...this.options.env, JPY_PARENT_PID: String(process.pid) },
+ env: {
+ ...process.env,
+ ...this.options.env,
+ JPY_PARENT_PID: String(process.pid),
+ PRIME_AGENT_KERNEL_OWNER_PID: String(process.pid),
+ },
stdio: ["ignore", "pipe", "pipe"],
});
this.kernel = kernel;
@@ -1542,6 +1547,9 @@ export class KernelManager {
}
// Same rule as the forked branch below: inactive only when the signal proved the pid still ours.
if (directPid !== undefined && signaled) recordOrphanProcessState(directPid, false);
+ // A killed/crashed kernel cannot run its own shutdown hook, so the host
+ // reaps the bash() process groups it journaled under this kernel pid.
+ if (directPid !== undefined) reapKernelOrphanProcesses(directPid);
} else if (this.forkedKernel) {
const forked = this.forkedKernel;
// The journal is raw-pid keyed, so inactive is written only on "signaled"
@@ -1553,8 +1561,12 @@ export class KernelManager {
.kill(killSignal === "SIGKILL" ? "KILL" : "TERM")
.then((outcome) => {
if (outcome === "signaled") recordOrphanProcessState(forked.pid, false);
+ // Reap again: bash children journaled while the async kill was in flight.
+ reapKernelOrphanProcesses(forked.pid);
})
.catch(() => this.appendKernelDiagnostic("forkserver kill unconfirmed; leaving orphan record active"));
+ // Same reaping as the direct branch: bash() children journaled under this kernel pid.
+ reapKernelOrphanProcesses(forked.pid);
}
this.kernel = undefined;
this.forkedKernel = undefined;
diff --git a/packages/coding-agent/src/core/kernel/state-snapshot.ts b/packages/coding-agent/src/core/kernel/state-snapshot.ts
index 1aced70711..5da948e132 100644
--- a/packages/coding-agent/src/core/kernel/state-snapshot.ts
+++ b/packages/coding-agent/src/core/kernel/state-snapshot.ts
@@ -83,9 +83,9 @@ def _prime_agent_snapshot_state():
ip = None
ns = ip.user_ns if ip is not None else _b.globals()
hidden = _b.set(_b.getattr(ip, "user_ns_hidden", {}) or {}) if ip is not None else _b.set()
- # rlm, mcp, and asyncio are re-created by the kernel bootstrap on every
- # start; never snapshot them.
- always_skip = {"rlm", "mcp", "asyncio", "In", "Out", "get_ipython", "exit", "quit", "open"}
+ # rlm, mcp, bash, and asyncio are re-created by the kernel bootstrap on
+ # every start; never snapshot them.
+ always_skip = {"rlm", "mcp", "bash", "asyncio", "In", "Out", "get_ipython", "exit", "quit", "open"}
class SnapshotSizeLimitExceeded(_b.Exception):
pass
@@ -262,7 +262,7 @@ def _prime_agent_list_state_names():
ip = None
ns = ip.user_ns if ip is not None else _b.globals()
hidden = _b.set(_b.getattr(ip, "user_ns_hidden", {}) or {}) if ip is not None else _b.set()
- always_skip = {"rlm", "mcp", "asyncio", "In", "Out", "get_ipython", "exit", "quit", "open"}
+ always_skip = {"rlm", "mcp", "bash", "asyncio", "In", "Out", "get_ipython", "exit", "quit", "open"}
names = []
for name in _b.list(ns.keys()):
if name.startswith("_") or name in hidden or name in always_skip:
diff --git a/packages/coding-agent/src/core/orphan-process-journal.ts b/packages/coding-agent/src/core/orphan-process-journal.ts
index bb9c5e4a46..e336f2200c 100644
--- a/packages/coding-agent/src/core/orphan-process-journal.ts
+++ b/packages/coding-agent/src/core/orphan-process-journal.ts
@@ -1,4 +1,6 @@
+import { spawnSync } from "node:child_process";
import { closeSync, fsyncSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
+import { win32 } from "node:path";
import { getProcessStartId } from "./session-lease.js";
export const ORPHAN_PROCESS_JOURNAL_ENV = "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL";
@@ -7,6 +9,8 @@ interface OrphanProcessRecord {
version: 1;
pid: number;
ownerPid: number;
+ /** Set on records written by a kernel (e.g. bash() children) so the host can reap per kernel. */
+ kernelPid?: number;
processStartId?: string;
active: boolean;
recordedAt: string;
@@ -14,7 +18,9 @@ interface OrphanProcessRecord {
export interface ActiveOrphanProcess {
pid: number;
- processStartId: string;
+ kernelPid?: number;
+ /** Missing on identity-free records: old journals or host writes whose start-id query failed (kernels no longer write pid-only records). */
+ processStartId?: string;
}
export function recordOrphanProcessState(pid: number, active: boolean): void {
@@ -75,18 +81,96 @@ export function readActiveOrphanProcesses(path: string, ownerPid: number): Activ
// A crash can truncate only the final append.
}
}
+ // Pid-only actives (no processStartId) still surface from old journals or
+ // host writes whose start-id query failed; reapers decide per-platform.
return [...latest.values()]
.filter(
- (record): record is OrphanProcessRecord & { processStartId: string } =>
- record.active && typeof record.processStartId === "string",
+ (record) =>
+ record.active && (record.processStartId === undefined || typeof record.processStartId === "string"),
)
- .map((record) => ({ pid: record.pid, processStartId: record.processStartId }));
+ .map((record) => ({
+ pid: record.pid,
+ ...(Number.isInteger(record.kernelPid) ? { kernelPid: record.kernelPid } : {}),
+ ...(typeof record.processStartId === "string" ? { processStartId: record.processStartId } : {}),
+ }));
}
export function isOrphanProcessIdentityCurrent(orphan: ActiveOrphanProcess): boolean {
- return getProcessStartId(orphan.pid) === orphan.processStartId;
+ // Pid-only records can never claim identity (undefined === undefined must not match).
+ return orphan.processStartId !== undefined && getProcessStartId(orphan.pid) === orphan.processStartId;
+}
+
+/**
+ * Identity-free records cannot prove the pid still names the journaled process.
+ * On win32 the kernel's kill-on-close job already reaped its tree when it died,
+ * so a bare-pid taskkill only risks killing a reused pid. POSIX keeps the
+ * best-effort kill (group-scoped, and the spawn gate makes pid-only actives
+ * host-written rarities there).
+ */
+export function shouldReapOrphanProcess(orphan: ActiveOrphanProcess): boolean {
+ if (orphan.processStartId === undefined) {
+ return process.platform !== "win32";
+ }
+ return isOrphanProcessIdentityCurrent(orphan);
}
export function clearOrphanProcessJournal(path: string): void {
rmSync(path, { force: true });
}
+
+// Kills still-active bash() children journaled by the given kernel pid; sibling kernels' records are untouched.
+export function reapKernelOrphanProcesses(kernelPid: number): void {
+ const path = process.env[ORPHAN_PROCESS_JOURNAL_ENV];
+ if (!path || !Number.isInteger(kernelPid) || kernelPid <= 0) {
+ return;
+ }
+ let orphans: ActiveOrphanProcess[];
+ try {
+ orphans = readActiveOrphanProcesses(path, process.pid);
+ } catch {
+ return;
+ }
+ for (const orphan of orphans) {
+ if (orphan.kernelPid !== kernelPid || orphan.pid === kernelPid) {
+ continue;
+ }
+ if (!shouldReapOrphanProcess(orphan)) {
+ continue;
+ }
+ // Inactive only after a delivered signal; a stale record is neutralized by the startId check.
+ if (killOrphanProcess(orphan.pid)) {
+ recordOrphanProcessState(orphan.pid, false);
+ }
+ }
+}
+
+// Hardened cross-platform tree kill for journaled orphans: absolute System32
+// taskkill /T on win32 (a bare name could resolve a planted CWD taskkill.exe),
+// process-group then pid SIGKILL elsewhere.
+export function killOrphanProcess(pid: number): boolean {
+ if (process.platform === "win32") {
+ // In-kernel bash() kill paths use taskkill /T; the reaper must kill the same tree, not just the shell pid.
+ const result = spawnSync(
+ win32.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "taskkill.exe"),
+ ["/F", "/T", "/PID", String(pid)],
+ {
+ stdio: "ignore",
+ timeout: 10_000,
+ env: { ...process.env, NoDefaultCurrentDirectoryInExePath: "1" },
+ },
+ );
+ return result.status === 0;
+ }
+ try {
+ process.kill(-pid, "SIGKILL");
+ return true;
+ } catch {
+ try {
+ process.kill(pid, "SIGKILL");
+ return true;
+ } catch {
+ // The orphan may already have exited.
+ }
+ }
+ return false;
+}
diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.ts
index fb3c95c4d3..c4e619306c 100644
--- a/packages/coding-agent/src/core/prompts/rlm.ts
+++ b/packages/coding-agent/src/core/prompts/rlm.ts
@@ -34,6 +34,8 @@ const IPYTHON_CONTROL_PROMPT = [
"",
"When running shell commands from IPython, use `%%bash` cells. If you use `%%bash`, it must be the first line of the code cell: no comments, spaces, blank lines, imports, or Python statements before it. Avoid `!cmd` shell escapes for project commands so shell behavior is explicit and multi-line commands share one shell context.",
"",
+ "`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working; `%%bash` remains the way to run quick inline shell with cell-visible output.",
+ "",
"Important: do not install dependencies into the IPython kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.",
"",
"Use Python for reading, searching, and editing files — it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.",
diff --git a/packages/coding-agent/src/core/tools/ipython.ts b/packages/coding-agent/src/core/tools/ipython.ts
index fd651451ed..6ec1eed9ee 100644
--- a/packages/coding-agent/src/core/tools/ipython.ts
+++ b/packages/coding-agent/src/core/tools/ipython.ts
@@ -3,6 +3,7 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
import { type Static, Type } from "typebox";
import { IMAGE_MIME_TYPES } from "../../utils/mime.js";
+import { resolveKernelBashShell } from "../../utils/shell.js";
import type { ExtensionContext, ToolDefinition } from "../extensions/types.js";
import { withKernelBootPermit } from "../kernel/boot-gate.js";
import type { KernelBootstrapProgressHandler } from "../kernel/bootstrap.js";
@@ -36,6 +37,7 @@ except Exception:
try:
import rlm as _prime_agent_rlm_module
rlm = _prime_agent_rlm_module.rlm
+ bash = _prime_agent_rlm_module.bash
import rlm.mcp as mcp
mcp.install_shutdown_hook()
except Exception as _prime_agent_rlm_error:
@@ -66,6 +68,9 @@ except Exception as _prime_agent_rlm_error:
return await self.run(prompt, **kwargs)
rlm = _PrimeAgentMissingRlm()
+
+ def bash(command):
+ rlm._raise_missing()
`.trim();
export function buildRlmBootstrapCode(pythonSkills: readonly PythonSkillRuntimeInfo[] = []): string {
@@ -483,10 +488,19 @@ export class IpythonKernelProvisioner {
);
}
const snapshotDir = this.options?.snapshotDir;
+ // Always inject an absolute trusted shell (undefined only on win32
+ // without bash, where the runtime's teaching error fires instead).
+ const shellPath = resolveKernelBashShell(this.options?.shellPath);
+ const commandPrefix = this.options?.commandPrefix;
const m = new KernelManager({
python: this.options?.python,
cwd: this.cwd,
- env: this.options?.env,
+ // bash() reads these so it applies the same shell settings as %%bash cells.
+ env: {
+ ...this.options?.env,
+ ...(shellPath ? { PRIME_AGENT_BASH_SHELL: shellPath } : {}),
+ ...(commandPrefix ? { PRIME_AGENT_BASH_COMMAND_PREFIX: commandPrefix } : {}),
+ },
sessionId: this.options?.sessionId,
hostHandlers: this.options?.hostHandlers,
pythonSkills: this.options?.pythonSkills,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 729ec6b3ac..f96cc010fc 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -36,9 +36,10 @@ import {
} from "../../core/cron-jobs.js";
import {
clearOrphanProcessJournal,
- isOrphanProcessIdentityCurrent,
+ killOrphanProcess,
ORPHAN_PROCESS_JOURNAL_ENV,
readActiveOrphanProcesses,
+ shouldReapOrphanProcess,
} from "../../core/orphan-process-journal.js";
import { PromptAdmissionCancelledError, waitForPromptAdmission } from "../../core/prompt-admission.js";
import {
@@ -3176,19 +3177,10 @@ export class DaemonSupervisor {
if (orphanProcessJournalPath) {
try {
for (const orphan of readActiveOrphanProcesses(orphanProcessJournalPath, worker.descriptor.pid)) {
- if (!isOrphanProcessIdentityCurrent(orphan)) {
+ if (!shouldReapOrphanProcess(orphan)) {
continue;
}
- const { pid } = orphan;
- try {
- process.kill(-pid, "SIGKILL");
- } catch {
- try {
- process.kill(pid, "SIGKILL");
- } catch {
- // The detached resource may already have exited.
- }
- }
+ killOrphanProcess(orphan.pid);
}
clearOrphanProcessJournal(orphanProcessJournalPath);
} catch (error) {
diff --git a/packages/coding-agent/src/utils/shell.ts b/packages/coding-agent/src/utils/shell.ts
index cbf289d86a..3a85440011 100644
--- a/packages/coding-agent/src/utils/shell.ts
+++ b/packages/coding-agent/src/utils/shell.ts
@@ -106,6 +106,34 @@ export function getShellConfig(customShellPath?: string): ShellConfig {
return { shell: "sh", args: ["-c"] };
}
+// Hardcoded literals: ProgramFiles env vars are ambient attacker-influenceable
+// input, the same trust-laundering class as PATH.
+const WINDOWS_GIT_BASH_PATHS = ["C:\\Program Files\\Git\\bin\\bash.exe", "C:\\Program Files (x86)\\Git\\bin\\bash.exe"];
+
+/**
+ * Absolute default shell for the kernel's bash(): explicit shellPath wins; POSIX
+ * uses /bin/bash else /bin/sh (absolute, never PATH — the kernel inherits a
+ * user-influenced PATH); win32 uses only the canonical Git Bash install paths,
+ * never PATH (a repo-controlled PATH/where.exe must not pick the kernel shell).
+ * undefined = no shell found: kernel startup must not fail, bash() raises its
+ * teaching error.
+ */
+export function resolveKernelBashShell(customShellPath?: string): string | undefined {
+ const explicit = customShellPath?.trim();
+ if (explicit) {
+ return explicit;
+ }
+ if (process.platform !== "win32") {
+ return existsSync("/bin/bash") ? "/bin/bash" : "/bin/sh";
+ }
+ for (const path of WINDOWS_GIT_BASH_PATHS) {
+ if (existsSync(path)) {
+ return path;
+ }
+ }
+ return undefined;
+}
+
export function getShellEnv(): NodeJS.ProcessEnv {
const binDir = getBinDir();
const pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === "path") ?? "PATH";
diff --git a/packages/coding-agent/test/ipython-bootstrap.test.ts b/packages/coding-agent/test/ipython-bootstrap.test.ts
index 8aba99b463..17358a3bf8 100644
--- a/packages/coding-agent/test/ipython-bootstrap.test.ts
+++ b/packages/coding-agent/test/ipython-bootstrap.test.ts
@@ -23,6 +23,13 @@ describe("IPython RLM bootstrap", () => {
expect(buildRlmBootstrapCode()).toContain('_prime_agent_os.environ["NO_COLOR"] = "1"');
});
+ it("binds bash from the runtime with a missing-runtime stub fallback", () => {
+ const code = buildRlmBootstrapCode();
+ expect(code).toContain("bash = _prime_agent_rlm_module.bash");
+ expect(code).toContain("def bash(command):");
+ expect(code).toContain("rlm._raise_missing()");
+ });
+
it("guards Python skill imports so a broken skill does not abort bootstrap", () => {
const code = buildRlmBootstrapCode([
{
diff --git a/packages/coding-agent/test/kernel-bash-shell.test.ts b/packages/coding-agent/test/kernel-bash-shell.test.ts
new file mode 100644
index 0000000000..bced79ae99
--- /dev/null
+++ b/packages/coding-agent/test/kernel-bash-shell.test.ts
@@ -0,0 +1,63 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ existsSync: vi.fn(),
+ spawnSync: vi.fn(),
+}));
+
+vi.mock("node:fs", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:fs")>();
+ // Module-load reads (config.ts) must see the real fs; tests override per case.
+ mocks.existsSync.mockImplementation(actual.existsSync);
+ return { ...actual, existsSync: mocks.existsSync };
+});
+
+vi.mock("child_process", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("child_process")>();
+ return { ...actual, spawnSync: mocks.spawnSync };
+});
+
+import { resolveKernelBashShell } from "../src/utils/shell.js";
+
+const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");
+
+function stubWin32(): void {
+ Object.defineProperty(process, "platform", { value: "win32" });
+}
+
+afterEach(() => {
+ if (originalPlatform) {
+ Object.defineProperty(process, "platform", originalPlatform);
+ }
+ mocks.existsSync.mockClear();
+ mocks.spawnSync.mockClear();
+});
+
+describe("resolveKernelBashShell on win32", () => {
+ it("returns undefined without consulting PATH when no Git Bash is installed", () => {
+ stubWin32();
+ mocks.existsSync.mockReturnValue(false);
+
+ expect(resolveKernelBashShell()).toBeUndefined();
+ // The old fallback shelled out to `where bash.exe`; a repo-controlled
+ // PATH/where.exe must never pick the kernel shell.
+ expect(mocks.spawnSync).not.toHaveBeenCalled();
+ });
+
+ it("returns the canonical Git Bash install path when present", () => {
+ stubWin32();
+ const canonical = "C:\\Program Files\\Git\\bin\\bash.exe";
+ mocks.existsSync.mockImplementation((path: string) => path === canonical);
+
+ expect(resolveKernelBashShell()).toBe(canonical);
+ expect(mocks.spawnSync).not.toHaveBeenCalled();
+ });
+
+ it("returns an explicit shellPath as-is", () => {
+ stubWin32();
+ mocks.existsSync.mockReturnValue(false);
+
+ expect(resolveKernelBashShell("D:\\tools\\bash.exe")).toBe("D:\\tools\\bash.exe");
+ expect(mocks.existsSync).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/coding-agent/test/orphan-process-journal.test.ts b/packages/coding-agent/test/orphan-process-journal.test.ts
index af60218b25..60733dd320 100644
--- a/packages/coding-agent/test/orphan-process-journal.test.ts
+++ b/packages/coding-agent/test/orphan-process-journal.test.ts
@@ -1,4 +1,5 @@
-import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { spawn } from "node:child_process";
+import { appendFileSync, existsSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
@@ -7,8 +8,11 @@ import {
isOrphanProcessIdentityCurrent,
ORPHAN_PROCESS_JOURNAL_ENV,
readActiveOrphanProcesses,
+ reapKernelOrphanProcesses,
recordOrphanProcessState,
+ shouldReapOrphanProcess,
} from "../src/core/orphan-process-journal.js";
+import { getProcessStartId } from "../src/core/session-lease.js";
const tempDirs: string[] = [];
const originalJournalPath = process.env[ORPHAN_PROCESS_JOURNAL_ENV];
@@ -44,4 +48,148 @@ describe("orphan process journal", () => {
clearOrphanProcessJournal(path);
expect(existsSync(path)).toBe(false);
});
+
+ it("reaps only the given kernel's still-active bash children", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-orphan-journal-test-"));
+ tempDirs.push(directory);
+ const path = join(directory, "orphans.jsonl");
+ process.env[ORPHAN_PROCESS_JOURNAL_ENV] = path;
+
+ // Stands in for a detached bash() child: own session so SIGKILL of the group is observable.
+ const child = spawn("sleep", ["300"], { detached: true, stdio: "ignore" });
+ child.unref();
+ const childPid = child.pid;
+ expect(childPid).toBeTypeOf("number");
+ const kernelPid = 999_999;
+ const appendRecord = (pid: number, recordKernelPid: number) => {
+ appendFileSync(
+ path,
+ `${JSON.stringify({
+ version: 1,
+ pid,
+ ownerPid: process.pid,
+ kernelPid: recordKernelPid,
+ processStartId: getProcessStartId(pid),
+ active: true,
+ recordedAt: new Date().toISOString(),
+ })}\n`,
+ );
+ };
+ appendRecord(childPid!, kernelPid);
+ // A sibling kernel's record and the kernel's own pid record must be untouched.
+ appendRecord(process.pid, kernelPid + 1);
+ appendRecord(kernelPid, kernelPid);
+
+ reapKernelOrphanProcesses(kernelPid);
+ // Double reaping an already-dead pid must be a no-op.
+ reapKernelOrphanProcesses(kernelPid);
+
+ const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
+ await exited;
+ expect(child.signalCode).toBe("SIGKILL");
+ const remaining = readActiveOrphanProcesses(path, process.pid).map((orphan) => orphan.pid);
+ expect(remaining).not.toContain(childPid);
+ expect(remaining).toContain(process.pid);
+ });
+
+ it("accepts pid-only active records and lets enriched records supersede them", () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-orphan-journal-test-"));
+ tempDirs.push(directory);
+ const path = join(directory, "orphans.jsonl");
+ const appendRecord = (record: Record<string, unknown>) => {
+ appendFileSync(path, `${JSON.stringify(record)}\n`);
+ };
+ const base = { version: 1, pid: process.pid, ownerPid: process.pid, recordedAt: new Date().toISOString() };
+
+ // Pid-only pre-record (Windows pre-enrollment window): returned, never identity-current.
+ appendRecord({ ...base, active: true });
+ let active = readActiveOrphanProcesses(path, process.pid);
+ expect(active).toHaveLength(1);
+ expect(active[0]?.processStartId).toBeUndefined();
+ expect(active[0] && isOrphanProcessIdentityCurrent(active[0])).toBe(false);
+
+ // The enriched record supersedes the pid-only one (last record per pid wins).
+ appendRecord({ ...base, active: true, processStartId: getProcessStartId(process.pid) });
+ active = readActiveOrphanProcesses(path, process.pid);
+ expect(active).toHaveLength(1);
+ expect(active[0]?.processStartId).toBeTypeOf("string");
+ expect(active[0] && isOrphanProcessIdentityCurrent(active[0])).toBe(true);
+
+ // An inactive record supersedes both.
+ appendRecord({ ...base, active: false });
+ expect(readActiveOrphanProcesses(path, process.pid)).toEqual([]);
+ });
+
+ // POSIX behavior: CI runs Ubuntu, so this exercises the real kill path.
+ it("best-effort kills pid-only records in the kernel crash-reap path", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-orphan-journal-test-"));
+ tempDirs.push(directory);
+ const path = join(directory, "orphans.jsonl");
+ process.env[ORPHAN_PROCESS_JOURNAL_ENV] = path;
+
+ const child = spawn("sleep", ["300"], { detached: true, stdio: "ignore" });
+ child.unref();
+ const childPid = child.pid;
+ expect(childPid).toBeTypeOf("number");
+ const kernelPid = 999_999;
+ // Pid-only record: the kernel crashed before the start-id query landed.
+ appendFileSync(
+ path,
+ `${JSON.stringify({
+ version: 1,
+ pid: childPid,
+ ownerPid: process.pid,
+ kernelPid,
+ active: true,
+ recordedAt: new Date().toISOString(),
+ })}\n`,
+ );
+
+ reapKernelOrphanProcesses(kernelPid);
+
+ const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
+ await exited;
+ expect(child.signalCode).toBe("SIGKILL");
+ });
+
+ it("win32 reapers ignore identity-free records", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-orphan-journal-test-"));
+ tempDirs.push(directory);
+ const path = join(directory, "orphans.jsonl");
+ process.env[ORPHAN_PROCESS_JOURNAL_ENV] = path;
+
+ const child = spawn("sleep", ["300"], { detached: true, stdio: "ignore" });
+ child.unref();
+ const childPid = child.pid;
+ expect(childPid).toBeTypeOf("number");
+ const kernelPid = 999_999;
+ appendFileSync(
+ path,
+ `${JSON.stringify({
+ version: 1,
+ pid: childPid,
+ ownerPid: process.pid,
+ kernelPid,
+ active: true,
+ recordedAt: new Date().toISOString(),
+ })}\n`,
+ );
+
+ const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");
+ try {
+ Object.defineProperty(process, "platform", { value: "win32" });
+ expect(shouldReapOrphanProcess({ pid: childPid!, kernelPid })).toBe(false);
+ // The kernel's kill-on-close job already reaped the tree; a bare-pid
+ // taskkill could only hit a reused pid, so the reaper must skip it.
+ reapKernelOrphanProcesses(kernelPid);
+ } finally {
+ if (originalPlatform) {
+ Object.defineProperty(process, "platform", originalPlatform);
+ }
+ }
+
+ expect(child.exitCode).toBeNull();
+ expect(child.signalCode).toBeNull();
+ process.kill(childPid!, "SIGKILL");
+ });
});
diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.py
index 1633374f29..ada3f4bb20 100644
--- a/prime-agent-runtime/src/rlm/__init__.py
+++ b/prime-agent-runtime/src/rlm/__init__.py
@@ -9,6 +9,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any
+from .bash import BashHandle, BashResult, bash
from .harness import HarnessEntry, HarnessScope, HarnessState, RefinementEvent, get_harness_state
try:
@@ -320,6 +321,8 @@ class _CallableModule(types.ModuleType):
sys.modules[__name__].__class__ = _CallableModule
__all__ = [
+ "BashHandle",
+ "BashResult",
"HarnessEntry",
"HarnessScope",
"HarnessState",
@@ -330,6 +333,7 @@ __all__ = [
"RLMSpawnHandle",
"RLMSubagent",
"RefinementEvent",
+ "bash",
"delete_subagent",
"find_models",
"get_harness_state",
diff --git a/prime-agent-runtime/src/rlm/_winjob.py b/prime-agent-runtime/src/rlm/_winjob.py
new file mode 100644
index 0000000000..6cdf40e37d
--- /dev/null
+++ b/prime-agent-runtime/src/rlm/_winjob.py
@@ -0,0 +1,378 @@
+"""Windows Job Object containment for bash() children: one kill-on-close job
+per BashHandle, so the child and every descendant (breakaway is never set)
+dies when the job is terminated or its last handle closes -- including on
+kernel crash, since the OS closes handles. spawn_in_job() creates the child
+CREATE_SUSPENDED and atomically inside its job (PROC_THREAD_ATTRIBUTE_JOB_LIST
+at CreateProcessW time), so no assignment window exists. Stdlib ctypes only;
+degrades to None/False where kernel32 is missing. Honest note: CI is
+Ubuntu-only, so all tests mock the kernel32 boundary (`_kernel32`)."""
+
+from __future__ import annotations
+
+import ctypes
+import ctypes.wintypes as wintypes
+import os
+import subprocess
+import threading
+from typing import BinaryIO
+
+JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
+_JobObjectBasicAccountingInformation, _JobObjectExtendedLimitInformation = 1, 9
+_INT64, _SIZE_T, _DWORD = ctypes.c_int64, ctypes.c_size_t, wintypes.DWORD
+_INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
+_RESUME_FAILED = 0xFFFFFFFF # (DWORD)-1 from ResumeThread
+_PROC_THREAD_ATTRIBUTE_JOB_LIST = 0x2000D # value 13 | PROC_THREAD_ATTRIBUTE_INPUT
+_PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x20002 # value 2 | PROC_THREAD_ATTRIBUTE_INPUT
+_EXTENDED_STARTUPINFO_PRESENT = 0x00080000
+_CREATE_SUSPENDED = 0x4
+_CREATE_UNICODE_ENVIRONMENT = 0x400
+_STARTF_USESTDHANDLES = 0x100
+_HANDLE_FLAG_INHERIT = 0x1
+_GENERIC_READ = 0x80000000
+_FILE_SHARE_READ_WRITE = 0x3
+_OPEN_EXISTING = 3
+_WAIT_OBJECT_0 = 0
+_WAIT_TIMEOUT = 0x102
+_INFINITE = 0xFFFFFFFF
+
+
+class _JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
+ _fields_ = [
+ ("PerProcessUserTimeLimit", _INT64), ("PerJobUserTimeLimit", _INT64),
+ ("LimitFlags", _DWORD), ("MinimumWorkingSetSize", _SIZE_T),
+ ("MaximumWorkingSetSize", _SIZE_T), ("ActiveProcessLimit", _DWORD),
+ ("Affinity", _SIZE_T), ("PriorityClass", _DWORD), ("SchedulingClass", _DWORD)]
+
+
+class _IO_COUNTERS(ctypes.Structure):
+ _fields_ = [(name, ctypes.c_uint64) for name in (
+ "ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
+ "ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]
+
+
+class _JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
+ _fields_ = [
+ ("BasicLimitInformation", _JOBOBJECT_BASIC_LIMIT_INFORMATION),
+ ("IoInfo", _IO_COUNTERS), ("ProcessMemoryLimit", _SIZE_T),
+ ("JobMemoryLimit", _SIZE_T), ("PeakProcessMemoryUsed", _SIZE_T),
+ ("PeakJobMemoryUsed", _SIZE_T)]
+
+
+class _JOBOBJECT_BASIC_ACCOUNTING_INFORMATION(ctypes.Structure):
+ _fields_ = [
+ ("TotalUserTime", _INT64), ("TotalKernelTime", _INT64),
+ ("ThisPeriodTotalUserTime", _INT64), ("ThisPeriodTotalKernelTime", _INT64),
+ ("TotalPageFaultCount", _DWORD), ("TotalProcesses", _DWORD),
+ ("ActiveProcesses", _DWORD), ("TotalTerminatedProcesses", _DWORD)]
+
+
+# Fixed-width Win64 ABI types on every host: wintypes.DWORD is 8-byte c_ulong on LP64 POSIX.
+_DWORD32, _WORD16, _PTR, _WSTR = ctypes.c_uint32, ctypes.c_uint16, ctypes.c_void_p, ctypes.c_wchar_p
+
+
+class _STARTUPINFOW(ctypes.Structure):
+ _fields_ = [
+ ("cb", _DWORD32), ("lpReserved", _WSTR), ("lpDesktop", _WSTR),
+ ("lpTitle", _WSTR), ("dwX", _DWORD32), ("dwY", _DWORD32),
+ ("dwXSize", _DWORD32), ("dwYSize", _DWORD32), ("dwXCountChars", _DWORD32),
+ ("dwYCountChars", _DWORD32), ("dwFillAttribute", _DWORD32), ("dwFlags", _DWORD32),
+ ("wShowWindow", _WORD16), ("cbReserved2", _WORD16),
+ ("lpReserved2", _PTR), ("hStdInput", _PTR),
+ ("hStdOutput", _PTR), ("hStdError", _PTR)]
+
+
+class _STARTUPINFOEXW(ctypes.Structure):
+ _fields_ = [("StartupInfo", _STARTUPINFOW), ("lpAttributeList", _PTR)]
+
+
+class _PROCESS_INFORMATION(ctypes.Structure):
+ _fields_ = [
+ ("hProcess", _PTR), ("hThread", _PTR),
+ ("dwProcessId", _DWORD32), ("dwThreadId", _DWORD32)]
+
+
+_kernel32_cache: ctypes.WinDLL | None = None # type: ignore[name-defined]
+
+
+def _kernel32():
+ global _kernel32_cache
+ if _kernel32_cache is None:
+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ # HANDLE argtypes/restype are mandatory: c_int truncates 64-bit handles.
+ h, b, i, p = wintypes.HANDLE, wintypes.BOOL, ctypes.c_int, wintypes.LPVOID
+ w = wintypes.LPCWSTR
+ for name, argtypes, restype in (
+ ("CreateJobObjectW", [p, w], h),
+ ("SetInformationJobObject", [h, i, p, _DWORD], b),
+ ("QueryInformationJobObject", [h, i, p, _DWORD, p], b),
+ ("TerminateJobObject", [h, wintypes.UINT], b),
+ ("CloseHandle", [h], b),
+ ("CreatePipe", [p, p, p, _DWORD], b),
+ ("SetHandleInformation", [h, _DWORD, _DWORD], b),
+ ("CreateFileW", [w, _DWORD, _DWORD, p, _DWORD, _DWORD, h], h),
+ ("InitializeProcThreadAttributeList", [p, _DWORD, _DWORD, p], b),
+ ("UpdateProcThreadAttribute", [p, _DWORD, _SIZE_T, p, _SIZE_T, p, p], b),
+ ("DeleteProcThreadAttributeList", [p], None),
+ ("CreateProcessW", [w, wintypes.LPWSTR, p, p, b, _DWORD, p, w, p, p], b),
+ ("ResumeThread", [h], _DWORD), # (DWORD)-1 on failure
+ ("WaitForSingleObject", [h, _DWORD], _DWORD),
+ ("GetExitCodeProcess", [h, p], b),
+ ("TerminateProcess", [h, wintypes.UINT], b),
+ ):
+ fn = getattr(k32, name)
+ fn.argtypes, fn.restype = argtypes, restype
+ _kernel32_cache = k32
+ return _kernel32_cache
+
+
+def _last_error() -> int:
+ return ctypes.get_last_error() if hasattr(ctypes, "get_last_error") else 0
+
+
+def _open_reader(handle: int) -> BinaryIO:
+ """Wrap the pipe HANDLE in a binary reader, consuming the HANDLE on every path."""
+ # Windows-only module, so the import cannot live at the top on POSIX.
+ import msvcrt
+
+ try:
+ fd = msvcrt.open_osfhandle(handle, os.O_RDONLY)
+ except BaseException:
+ _kernel32().CloseHandle(handle)
+ raise
+ try:
+ return os.fdopen(fd, "rb")
+ except BaseException:
+ os.close(fd) # the CRT fd owns the handle now; closing it closes both
+ raise
+
+
+def create_job() -> int | None:
+ """A new kill-on-close job handle, or None when jobs are unavailable."""
+ try:
+ k32 = _kernel32()
+ if not (job := k32.CreateJobObjectW(None, None)):
+ return None
+ info = _JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
+ info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ if not k32.SetInformationJobObject(
+ job, _JobObjectExtendedLimitInformation, ctypes.byref(info), ctypes.sizeof(info)):
+ k32.CloseHandle(job)
+ return None
+ return job
+ except (OSError, AttributeError):
+ return None
+
+
+class JobProcess:
+ """Minimal Popen-like surface for a child spawn_in_job() created suspended."""
+
+ def __init__(self, hprocess: int, hthread: int, pid: int, stdout: BinaryIO) -> None:
+ self.pid = pid
+ self.stdout: BinaryIO | None = stdout
+ # Guards every (_exit_code, _hprocess, _hthread, _waiters) transition; never held blocking.
+ self._lock = threading.Lock()
+ self._hprocess: int | None = hprocess
+ self._hthread: int | None = hthread
+ self._exit_code: int | None = None
+ self._waiters = 0 # wait() calls with a blocking WFSO in flight
+ self._close_requested = False
+
+ def resume(self) -> bool:
+ """Release the suspended primary thread; the handle stays open on failure."""
+ with self._lock:
+ if self._hthread is None or _kernel32().ResumeThread(self._hthread) == _RESUME_FAILED:
+ return False
+ _kernel32().CloseHandle(self._hthread)
+ self._hthread = None
+ return True
+
+ def close(self) -> None:
+ """Release the process handle (idempotent); owned by BashHandle after reap."""
+ with self._lock:
+ self._close_requested = True
+ self._close_hprocess_locked()
+
+ def _cache_exit_code_locked(self) -> int:
+ # Runs under the lock after a signaled wait, so never the STILL_ACTIVE(259) sentinel.
+ k32 = _kernel32()
+ code = _DWORD()
+ if not k32.GetExitCodeProcess(self._hprocess, ctypes.byref(code)):
+ # Handles stay open (nothing cached) so a retry is possible.
+ raise OSError(f"GetExitCodeProcess failed: {_last_error()}")
+ self._exit_code = int(code.value)
+ if self._hthread is not None:
+ k32.CloseHandle(self._hthread)
+ self._hthread = None
+ return self._exit_code
+
+ def _close_hprocess_locked(self) -> None:
+ # Closing a handle mid-WaitForSingleObject is UB: the last returning waiter closes it.
+ if self._close_requested and self._waiters == 0 and self._hprocess is not None:
+ _kernel32().CloseHandle(self._hprocess)
+ self._hprocess = None
+
+ def poll(self) -> int | None:
+ # WaitForSingleObject(0) never blocks, so it may run under the lock.
+ with self._lock:
+ if self._exit_code is not None:
+ return self._exit_code
+ if self._hprocess is None:
+ raise OSError("process handle closed")
+ result = _kernel32().WaitForSingleObject(self._hprocess, 0)
+ if result == _WAIT_TIMEOUT:
+ return None
+ if result != _WAIT_OBJECT_0:
+ raise OSError(f"WaitForSingleObject failed: {_last_error()}")
+ return self._cache_exit_code_locked()
+
+ def wait(self, timeout: float | None = None) -> int:
+ # Convert before registering: int(nan/inf) raises and would leak _waiters forever.
+ millis = _INFINITE if timeout is None else max(0, int(timeout * 1000))
+ with self._lock:
+ if self._exit_code is not None:
+ return self._exit_code
+ if self._hprocess is None:
+ raise OSError("process handle closed")
+ hprocess = self._hprocess
+ self._waiters += 1 # keeps the handle open while the wait runs
+ result = None
+ try:
+ result = _kernel32().WaitForSingleObject(hprocess, millis)
+ finally:
+ with self._lock:
+ try:
+ # Cache while the handle is still valid: the deferred close
+ # fires the moment _waiters drops to zero.
+ if result == _WAIT_OBJECT_0 and self._exit_code is None:
+ self._cache_exit_code_locked()
+ finally:
+ self._waiters -= 1
+ self._close_hprocess_locked() # last waiter after a close() request closes
+ with self._lock:
+ # A code cached concurrently during the wait wins, even over WAIT_FAILED.
+ if self._exit_code is not None:
+ return self._exit_code
+ if result == _WAIT_TIMEOUT:
+ raise subprocess.TimeoutExpired(f"pid {self.pid}", timeout or 0)
+ raise OSError(f"WaitForSingleObject failed: {_last_error()}")
+
+ def kill(self) -> None:
+ with self._lock:
+ if self._exit_code is not None or self._hprocess is None:
+ return
+ ok = bool(_kernel32().TerminateProcess(self._hprocess, 1))
+ if not ok and self.poll() is None:
+ raise OSError(f"TerminateProcess failed: {_last_error()}")
+
+
+def spawn_in_job(job: int, argv: list[str], cwd: str, env: dict[str, str]) -> JobProcess:
+ """Create argv suspended and atomically inside the caller-owned job (JOB_LIST
+ attribute, no assignment window); raises OSError on any failure (nothing spawned)."""
+ try:
+ k32 = _kernel32()
+ except (OSError, AttributeError) as exc:
+ raise OSError("kernel32 unavailable") from exc
+ read_handle = write_handle = nul_handle = None
+ attr_list = None
+ proc = None
+ try:
+ read_out, write_out = wintypes.HANDLE(), wintypes.HANDLE()
+ if not k32.CreatePipe(ctypes.byref(read_out), ctypes.byref(write_out), None, 0):
+ raise OSError(f"CreatePipe failed: {_last_error()}")
+ read_handle, write_handle = int(read_out.value or 0), int(write_out.value or 0)
+ if not k32.SetHandleInformation(write_handle, _HANDLE_FLAG_INHERIT, _HANDLE_FLAG_INHERIT):
+ raise OSError(f"SetHandleInformation failed: {_last_error()}")
+ nul = k32.CreateFileW(
+ "NUL", _GENERIC_READ, _FILE_SHARE_READ_WRITE, None, _OPEN_EXISTING, 0, None)
+ if not nul or nul == _INVALID_HANDLE_VALUE:
+ raise OSError(f"CreateFileW(NUL) failed: {_last_error()}")
+ nul_handle = int(nul)
+ if not k32.SetHandleInformation(nul_handle, _HANDLE_FLAG_INHERIT, _HANDLE_FLAG_INHERIT):
+ raise OSError(f"SetHandleInformation failed: {_last_error()}")
+ # Two-call protocol: the sizing call fails with ERROR_INSUFFICIENT_BUFFER.
+ size = ctypes.c_size_t(0)
+ k32.InitializeProcThreadAttributeList(None, 2, 0, ctypes.byref(size))
+ if not size.value:
+ raise OSError(f"InitializeProcThreadAttributeList sizing failed: {_last_error()}")
+ buffer = ctypes.create_string_buffer(size.value)
+ if not k32.InitializeProcThreadAttributeList(buffer, 2, 0, ctypes.byref(size)):
+ raise OSError(f"InitializeProcThreadAttributeList failed: {_last_error()}")
+ attr_list = buffer
+ jobs = (wintypes.HANDLE * 1)(job)
+ if not k32.UpdateProcThreadAttribute(
+ attr_list, 0, _PROC_THREAD_ATTRIBUTE_JOB_LIST, ctypes.byref(jobs),
+ ctypes.sizeof(jobs), None, None):
+ raise OSError(f"UpdateProcThreadAttribute failed: {_last_error()}")
+ # HANDLE_LIST blocks concurrent spawns' handle leaks; both arrays outlive CreateProcessW.
+ inheritable = (wintypes.HANDLE * 2)(write_handle, nul_handle)
+ if not k32.UpdateProcThreadAttribute(
+ attr_list, 0, _PROC_THREAD_ATTRIBUTE_HANDLE_LIST, ctypes.byref(inheritable),
+ ctypes.sizeof(inheritable), None, None):
+ raise OSError(f"UpdateProcThreadAttribute failed: {_last_error()}")
+ startup = _STARTUPINFOEXW()
+ startup.StartupInfo.cb = ctypes.sizeof(_STARTUPINFOEXW)
+ startup.StartupInfo.dwFlags = _STARTF_USESTDHANDLES
+ startup.StartupInfo.hStdInput = nul_handle
+ startup.StartupInfo.hStdOutput = startup.StartupInfo.hStdError = write_handle
+ startup.lpAttributeList = ctypes.cast(attr_list, wintypes.LPVOID)
+ # CreateProcessW may rewrite lpCommandLine in place: a writable buffer is mandatory.
+ cmdline = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv))
+ # Sorted case-insensitively per CreateProcessW; the implicit terminator is the second NUL.
+ env_block = ctypes.create_unicode_buffer(
+ "\0".join(
+ f"{key}={value}" for key, value in sorted(env.items(), key=lambda kv: kv[0].upper())
+ ) + "\0")
+ info = _PROCESS_INFORMATION()
+ flags = _EXTENDED_STARTUPINFO_PRESENT | _CREATE_SUSPENDED | _CREATE_UNICODE_ENVIRONMENT
+ if not k32.CreateProcessW(
+ None, cmdline, None, None, True, flags, env_block, cwd,
+ ctypes.byref(startup), ctypes.byref(info)):
+ raise OSError(f"CreateProcessW failed: {_last_error()}")
+ try:
+ # _open_reader consumes the read handle on every path: drop it at the call.
+ reader_handle, read_handle = read_handle, None
+ proc = JobProcess(
+ int(info.hProcess or 0), int(info.hThread or 0), int(info.dwProcessId),
+ _open_reader(reader_handle))
+ except BaseException:
+ # No JobProcess owns these yet; the caller's kill-on-close job reaps the child.
+ for handle in (info.hProcess, info.hThread):
+ if handle:
+ k32.CloseHandle(handle)
+ raise
+ finally:
+ if attr_list is not None:
+ k32.DeleteProcThreadAttributeList(attr_list)
+ for handle in (write_handle, nul_handle):
+ if handle is not None:
+ k32.CloseHandle(handle)
+ if read_handle is not None: # only when _open_reader was never invoked
+ k32.CloseHandle(read_handle)
+ return proc
+
+
+def is_empty(job: int) -> bool | None:
+ """True/False = job has no/some live processes; None = query failed."""
+ try:
+ info = _JOBOBJECT_BASIC_ACCOUNTING_INFORMATION()
+ ok = _kernel32().QueryInformationJobObject(
+ job, _JobObjectBasicAccountingInformation, ctypes.byref(info), ctypes.sizeof(info), None
+ )
+ return info.ActiveProcesses == 0 if ok else None
+ except (OSError, AttributeError):
+ return None
+
+
+def terminate(job: int, exit_code: int = 1) -> bool:
+ try:
+ return bool(_kernel32().TerminateJobObject(job, exit_code))
+ except (OSError, AttributeError):
+ return False
+
+
+def close(job: int) -> None:
+ """Close the handle; closing the LAST handle fires kill-on-close."""
+ try:
+ _kernel32().CloseHandle(job)
+ except (OSError, AttributeError):
+ pass
diff --git a/prime-agent-runtime/src/rlm/bash.py b/prime-agent-runtime/src/rlm/bash.py
new file mode 100644
index 0000000000..fbdc223dff
--- /dev/null
+++ b/prime-agent-runtime/src/rlm/bash.py
@@ -0,0 +1,844 @@
+"""Async-by-default shell execution: bash() spawns immediately and returns a live handle."""
+
+from __future__ import annotations
+
+import asyncio
+import atexit
+import json
+import os
+import selectors
+import shutil
+import signal
+import socket
+import struct
+import subprocess
+import sys
+import threading
+import time
+from collections import deque
+from collections.abc import Callable, Generator
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Any, cast
+
+from . import _winjob
+
+_IS_POSIX = os.name == "posix"
+
+if _IS_POSIX:
+ import fcntl
+ import termios
+
+_HEAD_CAP = 512 * 1024
+_TAIL_CAP = 3 * 512 * 1024
+_READ_CHUNK = 65536
+# Fixed child-side fd for the status channel; POSIX shells (notably dash) only
+# guarantee single-digit fds in redirection syntax.
+_STATUS_FD = 9
+# Cancelled one-shot awaits: TERM grace before the group KILL, then the bounded
+# wait for a confirmed group exit before CancelledError propagates.
+_CANCEL_TERM_GRACE = 0.5
+_CANCEL_KILL_WAIT = 2.0
+
+_live_handles: set["BashHandle"] = set()
+_live_lock = threading.Lock()
+_hook_installed = False
+_hook_lock = threading.Lock()
+
+
+@dataclass(frozen=True)
+class BashResult:
+ exit_code: int
+ output: str
+ duration: float
+
+
+class _BoundedBuffer:
+ """First _HEAD_CAP bytes plus a rolling _TAIL_CAP-byte tail; the middle is dropped."""
+
+ def __init__(self) -> None:
+ self._head = bytearray()
+ self._tail: deque[bytes] = deque()
+ self._tail_size = 0
+ self._dropped = 0
+ self._lock = threading.Lock()
+
+ def write(self, chunk: bytes) -> None:
+ with self._lock:
+ if len(self._head) < _HEAD_CAP:
+ take = _HEAD_CAP - len(self._head)
+ self._head.extend(chunk[:take])
+ chunk = chunk[take:]
+ if not chunk:
+ return
+ self._tail.append(chunk)
+ self._tail_size += len(chunk)
+ # Trim the oldest chunk instead of dropping it whole so exactly _TAIL_CAP bytes stay.
+ while self._tail_size > _TAIL_CAP:
+ excess = self._tail_size - _TAIL_CAP
+ oldest = self._tail[0]
+ if len(oldest) <= excess:
+ self._tail.popleft()
+ self._tail_size -= len(oldest)
+ self._dropped += len(oldest)
+ else:
+ self._tail[0] = oldest[excess:]
+ self._tail_size -= excess
+ self._dropped += excess
+
+ def size(self) -> int:
+ with self._lock:
+ return len(self._head) + self._tail_size
+
+ def text(self) -> str:
+ with self._lock:
+ head = bytes(self._head)
+ tail = b"".join(self._tail)
+ dropped = self._dropped
+ if not dropped:
+ return (head + tail).decode("utf-8", errors="replace")
+ marker = f"\n... [{dropped} bytes dropped] ...\n"
+ return head.decode("utf-8", errors="replace") + marker + tail.decode("utf-8", errors="replace")
+
+
+class BashHandle:
+ """Live handle to a shell command; await it for the BashResult.
+
+ A handle awaited before any other API use (the `await bash(cmd)` one-shot
+ form, including `h = bash(cmd)` awaited immediately) owns the command:
+ cancelling that await kills the process group. Touching .pid/.running/
+ .output()/.tail()/.poll()/.kill() first marks the handle as a background
+ handle; later awaits only wait and cancelling them leaves it running.
+ """
+
+ def __init__(self, command: str) -> None:
+ self.command = command
+ self._buffer = _BoundedBuffer()
+ self._done = threading.Event()
+ self._eof = threading.Event()
+ self._status: int | None = None
+ self._status_known = threading.Event()
+ self._reaped = False
+ self._result: BashResult | None = None
+ self._callbacks: list[Callable[[], None]] = []
+ self._callback_lock = threading.Lock()
+ # Serializes kill/reap so a pid fallback can never outlive the process handle.
+ self._kill_lock = threading.Lock()
+ self._started = time.monotonic()
+ # POSIX: own process group so kill() signals the whole pipeline; Windows
+ # contains the tree in a kill-on-close job object.
+ self._status_read = -1
+ self._wake_read = -1
+ self._wake_write = -1
+ # True only while the pump moves a chunk from the pipe into the buffer.
+ self._pump_transfer = False
+ self._job: int | None = None
+ status_write = -1
+ if _IS_POSIX:
+ # Full-duplex status channel: the child end rides in as stdin (fd 0)
+ # and the script remaps it to _STATUS_FD before swapping in /dev/null
+ # (dash rejects multi-digit fds in redirections at parse time). The
+ # parent end doubles as the gate: the child blocks on it until the
+ # pid is journaled, so a kernel kill in that window cannot leak an
+ # unjournaled command (parent death closes the socket -> child exits).
+ parent_sock, child_sock = socket.socketpair()
+ self._status_read = parent_sock.detach()
+ status_write = child_sock.detach()
+ try:
+ self._wake_read, self._wake_write = os.pipe()
+ except BaseException:
+ os.close(self._status_read)
+ os.close(status_write)
+ raise
+ script = _status_script(_with_prefix(command))
+ else:
+ # Windows: the child is created suspended, atomically inside the kill-on-close job.
+ script = _with_prefix(command)
+ self._job = _winjob.create_job()
+ if self._job is None:
+ # Nothing spawned yet, so nothing can leak: refuse to start.
+ raise RuntimeError("bash(): Windows job containment could not be established")
+ try:
+ self._proc: subprocess.Popen[bytes] | _winjob.JobProcess
+ if _IS_POSIX:
+ self._proc = subprocess.Popen(
+ [_shell(), "-c", script],
+ cwd=os.getcwd(),
+ env=_child_env(),
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ stdin=status_write,
+ )
+ else:
+ self._proc = _winjob.spawn_in_job(
+ self._job, [_shell(), "-c", script], cwd=os.getcwd(), env=_child_env()
+ )
+ except BaseException:
+ for fd in (self._status_read, self._wake_read, self._wake_write):
+ if fd >= 0:
+ os.close(fd)
+ if self._job is not None:
+ job, self._job = self._job, None
+ _winjob.close(job)
+ raise
+ finally:
+ if status_write >= 0:
+ os.close(status_write)
+ self._pid: int = self._proc.pid
+ self._released = False
+ with _live_lock:
+ _live_handles.add(self)
+ enrolled = _record_journal(self._pid, active=True)
+ if not enrolled:
+ # Fail closed: a configured journal that cannot enroll the pid must
+ # not let the command run (the host reaper would never see it).
+ self._abort_spawn()
+ raise RuntimeError(
+ "bash(): orphan-journal enrollment failed (journal configured but the "
+ "pid could not be recorded); the spawned process was killed"
+ )
+ if _IS_POSIX:
+ # Journal first, then open the gate: the child does not run the user
+ # command until this byte arrives. A failed write means the child
+ # already died; the status/EOF paths report that normally.
+ try:
+ os.write(self._status_read, b"\n")
+ except OSError:
+ pass
+ else:
+ # The child is already job-contained and journaled; resume is the
+ # last step. A failed resume would strand a permanently suspended
+ # child: fail closed via the assigned job.
+ if not cast("_winjob.JobProcess", self._proc).resume():
+ self._abort_spawn()
+ raise RuntimeError("bash(): Windows job containment could not be established")
+ threading.Thread(target=self._pump, daemon=True).start()
+ threading.Thread(target=self._report, daemon=True).start()
+ threading.Thread(target=self._watch, daemon=True).start()
+
+ @property
+ def pid(self) -> int:
+ self._released = True
+ return self._pid
+
+ @property
+ def running(self) -> bool:
+ # Group liveness, matching kill()'s guard and the journal; poll()/await
+ # keep foreground result semantics after `cmd &` returns early.
+ self._released = True
+ return not self._reaped
+
+ def output(self) -> str:
+ self._released = True
+ return self._buffer.text()
+
+ def tail(self, n: int = 50) -> str:
+ self._released = True
+ return "\n".join(self._buffer.text().splitlines()[-n:])
+
+ def poll(self) -> BashResult | None:
+ self._released = True
+ return self._result if self._done.is_set() else None
+
+ def kill(self, sig: int = signal.SIGTERM, grace: float = 5.0) -> None:
+ # Guard on group death, not _done: kill() must still reach a lingering
+ # background group after the foreground result was already delivered.
+ self._released = True
+ if self._reaped:
+ return
+ if not _IS_POSIX:
+ with self._kill_lock:
+ if self._reaped: # re-check: _watch may have reaped while we waited
+ return
+ if self._job is not None and _winjob.terminate(self._job):
+ return
+ # TerminateJobObject failed or reap raced: taskkill fallback.
+ if not _taskkill_tree(self._pid):
+ try:
+ self._proc.kill()
+ except OSError:
+ pass
+ return
+ _signal_group(self._pid, sig)
+ if sig == signal.SIGTERM:
+ timer = threading.Timer(grace, self._force_kill)
+ timer.daemon = True
+ timer.start()
+
+ def _force_kill(self) -> None:
+ if not self._reaped:
+ _signal_group(self._pid, signal.SIGKILL)
+
+ def _pump(self) -> None:
+ stdout = self._proc.stdout
+ assert stdout is not None
+ if not _IS_POSIX:
+ # Windows: no FIONREAD fence; the drain keeps its quiescence
+ # heuristic (best-effort parity).
+ try:
+ while chunk := stdout.read1(_READ_CHUNK):
+ self._buffer.write(chunk)
+ except (OSError, ValueError):
+ pass
+ stdout.close()
+ self._eof.set()
+ return
+ # POSIX: select-gate the read and flag the read->commit window, so the
+ # drain fence never sees "pipe empty + buffer quiescent" while a chunk
+ # is in flight between the pipe read and the buffer commit.
+ fd = stdout.fileno()
+ try:
+ with selectors.DefaultSelector() as sel:
+ sel.register(fd, selectors.EVENT_READ)
+ while True:
+ sel.select()
+ self._pump_transfer = True
+ try:
+ chunk = os.read(fd, _READ_CHUNK)
+ if not chunk:
+ break
+ self._buffer.write(chunk)
+ finally:
+ self._pump_transfer = False
+ except (OSError, ValueError):
+ pass
+ try:
+ stdout.close()
+ except OSError:
+ pass
+ self._eof.set()
+
+ def _report(self) -> None:
+ # Finalize at foreground completion (status channel), not EOF, so
+ # `cmd &` does not hang the await; the shell then `wait`s for its
+ # background jobs, keeping the journaled group identity alive.
+ status: int | None = None
+ try:
+ status = self._read_status()
+ # Reserve the delivered status before draining so a shell death during
+ # the drain window cannot override it with wait()'s signal exit code.
+ with self._callback_lock:
+ self._status = status
+ finally:
+ # _watch blocks on this event without a timeout, so every exit path
+ # (parsed status, EOF, garbage, exception) must set it.
+ self._status_known.set()
+ if status is not None:
+ self._drain_grace()
+ self._finalize(status)
+
+ def _watch(self) -> None:
+ # Observe shell death independently of the status socket: an early
+ # `exit`/`exec`/`set -e`/fatal signal skips `printf`, and background
+ # children can hold the socket open past the shell's lifetime.
+ exit_code = self._proc.wait()
+ if self._wake_write >= 0:
+ # Unblock _read_status: background children can hold the status socket
+ # open past the shell's lifetime via bash's saved-fd duplicate.
+ try:
+ os.write(self._wake_write, b"x")
+ except OSError:
+ pass
+ os.close(self._wake_write)
+ # _report always sets _status_known (try/finally), so wait indefinitely:
+ # a slow reporter can never lose a delivered status to wait()'s code.
+ self._status_known.wait()
+ with self._callback_lock:
+ delivered = self._status
+ if delivered is None and not self._done.is_set():
+ self._drain_grace()
+ self._finalize(exit_code)
+ with self._kill_lock:
+ delivered = self._reap_group()
+ self._reaped = True
+ if not _IS_POSIX:
+ # Reaped: pid fallbacks are gone, so the handle may finally close.
+ cast("_winjob.JobProcess", self._proc).close()
+ if delivered:
+ _record_journal(self._pid, active=False)
+ with _live_lock:
+ _live_handles.discard(self)
+
+ def _reap_group(self) -> bool:
+ # Group liveness, not leader death, gates the inactive record: members
+ # that outlive the leader would leak behind a stale journal anchor.
+ if not _IS_POSIX:
+ # Terminate then close the last handle: kill-on-close reaps
+ # stragglers. An unproven terminate falls back to taskkill; if
+ # that also fails the record stays active for the host reaper.
+ delivered = False
+ if self._job is not None:
+ delivered = _winjob.terminate(self._job)
+ job, self._job = self._job, None
+ _winjob.close(job)
+ return delivered or _taskkill_tree(self._pid)
+ try:
+ os.killpg(self._pid, 0)
+ except ProcessLookupError:
+ return True # group already gone
+ except PermissionError:
+ pass
+ return _signal_group(self._pid, signal.SIGKILL)
+
+ def _read_status(self) -> int | None:
+ if self._status_read < 0:
+ return None
+ try:
+ # DefaultSelector (kqueue/epoll) instead of select(): select() rejects
+ # fds >= FD_SETSIZE (1024) even when the process fd limit is higher.
+ with selectors.DefaultSelector() as sel:
+ sel.register(self._status_read, selectors.EVENT_READ)
+ sel.register(self._wake_read, selectors.EVENT_READ)
+ line = b""
+ while b"\n" not in line:
+ ready = {key.fd for key, _ in sel.select()}
+ # Prefer status bytes: any status write happens before shell exit,
+ # so it is already readable whenever the wake fd fires.
+ if self._status_read not in ready:
+ break # shell died without writing a status
+ chunk = os.read(self._status_read, 64)
+ if not chunk:
+ break # EOF without a full status line
+ line += chunk
+ return int(line)
+ except (OSError, ValueError):
+ return None
+ finally:
+ os.close(self._status_read)
+ os.close(self._wake_read)
+
+ def _drain_grace(self) -> None:
+ # Bounded wait so the result includes foreground output still in the pipe:
+ # EOF arrives immediately without background jobs, otherwise stop once the
+ # buffer is quiescent for one tick AND the pipe holds no unread bytes (a
+ # slow pump must not lose output the shell wrote before its status).
+ deadline = time.monotonic() + 0.5
+ size = self._buffer.size()
+ while time.monotonic() < deadline:
+ if self._eof.wait(0.05):
+ return
+ # A chunk between pipe read and buffer commit (transfer flag) is
+ # invisible to both FIONREAD and the buffer size; wait it out.
+ if self._pipe_pending() or self._pump_transfer:
+ size = self._buffer.size()
+ continue
+ current = self._buffer.size()
+ if current == size:
+ return
+ size = current
+
+ def _pipe_pending(self) -> bool:
+ # POSIX only: FIONREAD on the capture pipe; Windows keeps the
+ # quiescence heuristic (best-effort parity).
+ if not _IS_POSIX or self._eof.is_set():
+ return False
+ stdout = self._proc.stdout
+ if stdout is None:
+ return False
+ try:
+ pending = struct.unpack("i", fcntl.ioctl(stdout.fileno(), termios.FIONREAD, struct.pack("i", 0)))[0]
+ except (OSError, ValueError):
+ return False
+ return pending > 0
+
+ def _finalize(self, exit_code: int) -> None:
+ with self._callback_lock:
+ if self._done.is_set():
+ return
+ self._result = BashResult(
+ exit_code=exit_code,
+ output=self._buffer.text(),
+ duration=time.monotonic() - self._started,
+ )
+ self._done.set()
+ callbacks = self._callbacks
+ self._callbacks = []
+ for callback in callbacks:
+ callback()
+
+ def _add_done_callback(self, callback: Callable[[], None]) -> None:
+ with self._callback_lock:
+ if not self._done.is_set():
+ self._callbacks.append(callback)
+ return
+ callback()
+
+ async def _wait(self) -> BashResult:
+ # Asyncio-native wakeup: no executor thread is parked for the command's
+ # duration, so many concurrent awaits cannot exhaust the default pool.
+ loop = asyncio.get_running_loop()
+ fut: asyncio.Future[None] = loop.create_future()
+
+ def _wake() -> None:
+ try:
+ loop.call_soon_threadsafe(lambda: fut.done() or fut.set_result(None))
+ except RuntimeError:
+ pass # awaiting loop already closed
+
+ self._add_done_callback(_wake)
+ await fut
+ assert self._result is not None
+ return self._result
+
+ async def _wait_owned(self) -> BashResult:
+ # One-shot `await bash(cmd)` owns the process: a cancelled await (e.g.
+ # a kernel interrupt) must not leave the command running. TERM, bounded
+ # grace, group KILL, then a bounded confirmed-exit wait before the
+ # CancelledError propagates, so no side effect can land after it.
+ try:
+ return await self._wait()
+ except asyncio.CancelledError:
+ # Signal synchronously first: even if the cleanup awaits below are
+ # re-cancelled, TERM is already delivered and the escalation timer
+ # armed. The confirm wait runs as a shielded task so repeated
+ # cancels of this task cannot skip it (they re-raise into awaits
+ # inside this except block); the loop re-awaits until it finishes
+ # (the confirm coroutine itself is bounded).
+ self.kill(grace=_CANCEL_TERM_GRACE)
+ confirm = asyncio.ensure_future(self._confirm_group_exit())
+ while not confirm.done():
+ try:
+ await asyncio.shield(confirm)
+ except asyncio.CancelledError:
+ continue
+ raise
+
+ async def _confirm_group_exit(self) -> None:
+ if not await self._await_group_death(_CANCEL_TERM_GRACE):
+ if _IS_POSIX:
+ _signal_group(self._pid, signal.SIGKILL)
+ else:
+ # kill() holds the escalation lock; to_thread keeps the loop free.
+ await asyncio.to_thread(self.kill)
+ await self._await_group_death(_CANCEL_KILL_WAIT)
+
+ def _group_alive(self) -> bool:
+ if not _IS_POSIX:
+ job = self._job # snapshot: _watch may clear it concurrently
+ if job is not None:
+ # Job accounting sees detached descendants a dead leader hides.
+ empty = _winjob.is_empty(job)
+ if empty is not None:
+ return not empty
+ return self._proc.poll() is None
+ try:
+ os.killpg(self._pid, 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ pass
+ return True
+
+ async def _await_group_death(self, timeout: float) -> bool:
+ deadline = time.monotonic() + timeout
+ while self._group_alive():
+ if time.monotonic() >= deadline:
+ return False
+ await asyncio.sleep(0.02)
+ return True
+
+ def _abort_spawn(self) -> None:
+ # Enrollment or containment failed before the gate opened (POSIX) or
+ # while the child is still suspended, before resume (Windows): kill
+ # the child and unwind the handle before threads start.
+ if _IS_POSIX:
+ for fd in (self._status_read, self._wake_read, self._wake_write):
+ if fd >= 0:
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ self._status_read = self._wake_read = self._wake_write = -1
+ delivered = _signal_group(self._pid, signal.SIGKILL)
+ else:
+ with self._kill_lock:
+ delivered = False
+ if self._job is not None:
+ delivered = _winjob.terminate(self._job)
+ job, self._job = self._job, None
+ _winjob.close(job)
+ if not delivered:
+ # Pre-resume abort: the never-run leader has no descendants, so a
+ # delivered kill retires the journal record.
+ try:
+ self._proc.kill()
+ delivered = True
+ except OSError:
+ pass
+ if self._proc.stdout is not None:
+ self._proc.stdout.close()
+ # The blocking wait stays outside the lock: hProcess is still open, so a
+ # concurrent raw-pid fallback stays pinned to the right process.
+ try:
+ self._proc.wait(timeout=5)
+ except (OSError, subprocess.SubprocessError):
+ pass
+ with self._kill_lock:
+ self._reaped = True
+ if not _IS_POSIX:
+ # Reaped commits before close: later lock holders skip raw-pid fallbacks.
+ cast("_winjob.JobProcess", self._proc).close()
+ with _live_lock:
+ _live_handles.discard(self)
+ if delivered:
+ _record_journal(self._pid, active=False)
+
+ def __await__(self) -> Generator[Any, None, BashResult]:
+ # A handle awaited before any other API use is a one-shot command tied
+ # to the await (kill-on-cancel); touching the handle API first marks it
+ # as a deliberate background handle whose awaits only wait.
+ if self._released:
+ return self._wait().__await__()
+ self._released = True
+ return self._wait_owned().__await__()
+
+ def __repr__(self) -> str:
+ state = f"exit_code={self._result.exit_code}" if self._result else "running"
+ return f"<BashHandle pid={self._pid} {state} command={self.command!r}>"
+
+
+def bash(command: str) -> BashHandle:
+ """Start a shell command immediately; await the handle for the result.
+
+ `await bash(cmd)` is a one-shot: cancelling the await (e.g. an interrupt)
+ kills the command's process group. `h = bash(cmd)` used as a background
+ handle (any .pid/.running/.output()/.tail()/.poll()/.kill() access before
+ the first await) survives cancellation; awaiting it only waits. Leak
+ containment is per-platform: process groups plus the orphan journal on
+ POSIX; a kill-on-close job object on Windows entered while the child is
+ still suspended, so no descendant can escape it and kill()/crash cleanup
+ are unconditional -- bash() raises if containment cannot be established.
+ """
+ if not isinstance(command, str) or not command:
+ raise TypeError("command must be a non-empty str")
+ _install_shutdown_hook()
+ return BashHandle(command)
+
+
+def _shell() -> str:
+ # Read per call: the forkserver applies session env after the fork.
+ override = os.environ.get("PRIME_AGENT_BASH_SHELL")
+ if override:
+ if not os.path.isabs(override):
+ raise ValueError("PRIME_AGENT_BASH_SHELL must be an absolute path")
+ return override
+ if not _IS_POSIX:
+ # Never consult PATH on Windows: a repo-controlled PATH could supply
+ # the shell. The host injects PRIME_AGENT_BASH_SHELL when one exists.
+ raise RuntimeError(
+ "bash() needs PRIME_AGENT_BASH_SHELL set to the absolute path of a "
+ "POSIX shell on Windows (e.g. install Git Bash in its default "
+ "location so the host injects it)"
+ )
+ # PATH fallback only serves bare/standalone POSIX runtime use: the host
+ # always injects PRIME_AGENT_BASH_SHELL (an absolute path) when a shell exists.
+ shell = shutil.which("bash")
+ return shell or "/bin/sh"
+
+
+def _with_prefix(command: str) -> str:
+ prefix = os.environ.get("PRIME_AGENT_BASH_COMMAND_PREFIX")
+ return f"{prefix}\n{command}" if prefix else command
+
+
+def _status_script(command: str) -> str:
+ # The status socket arrives as stdin (fd 0); the prologue dups it to the
+ # single-digit _STATUS_FD (dash rejects multi-digit fds in redirections at
+ # parse time) and points stdin at /dev/null, so no other copy remains. The
+ # gate read blocks until the parent has journaled the pid; EOF (parent died
+ # first) exits without running the command. The brace group runs the command
+ # with the status fd closed so `&` children do not inherit it; the trailing
+ # `wait` keeps the shell alive as group leader until its own jobs exit
+ # (double-forked daemons stay out of scope).
+ return (
+ f"exec {_STATUS_FD}>&0 0</dev/null\n"
+ f"read -r _prime_agent_gate <&{_STATUS_FD} || exit 127\n"
+ "{\n"
+ f"{command}\n"
+ f"}} {_STATUS_FD}>&-\n"
+ "__prime_status=$?\n"
+ f"printf '%s\\n' \"$__prime_status\" >&{_STATUS_FD}\n"
+ f"exec {_STATUS_FD}>&-\n"
+ "wait\n"
+ 'exit "$__prime_status"\n'
+ )
+
+
+def _child_env() -> dict[str, str]:
+ return {**os.environ, "NO_COLOR": "1", "TERM": "dumb", "CLICOLOR": "0", "FORCE_COLOR": "0"}
+
+
+def _signal_group(pid: int, sig: int) -> bool:
+ """True when the signal was delivered or the group is already gone."""
+ try:
+ os.killpg(pid, sig)
+ except ProcessLookupError:
+ return True # already dead: safe to mark the journal record inactive
+ except OSError:
+ return False # not delivered: the record must stay active for the host reaper
+ return True
+
+
+def _system32(*parts: str) -> str:
+ # Absolute paths for Windows helper binaries: PATH (and CWD on Windows
+ # CPython) lookup could resolve a planted taskkill.exe/powershell.exe.
+ root = os.environ.get("SystemRoot", r"C:\Windows")
+ return os.path.join(root, "System32", *parts)
+
+
+def _helper_env() -> dict[str, str]:
+ return {**os.environ, "NoDefaultCurrentDirectoryInExePath": "1"}
+
+
+def _taskkill_tree(pid: int) -> bool:
+ # Windows has no process groups to signal; taskkill /T kills the whole tree.
+ try:
+ return (
+ subprocess.run(
+ [_system32("taskkill.exe"), "/PID", str(pid), "/T", "/F"],
+ capture_output=True,
+ timeout=10,
+ env=_helper_env(),
+ ).returncode
+ == 0
+ )
+ except (OSError, subprocess.SubprocessError):
+ return False
+
+
+def _process_start_id(pid: int) -> str | None:
+ if os.name == "nt":
+ # Mirrors getWindowsProcessStartId in session-lease.ts byte-for-byte so
+ # the host's identity comparison matches the journaled string.
+ try:
+ out = subprocess.run(
+ [
+ _system32("WindowsPowerShell", "v1.0", "powershell.exe"),
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ f"([System.Diagnostics.Process]::GetProcessById({pid})).StartTime.ToUniversalTime().Ticks",
+ ],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ env=_helper_env(),
+ ).stdout.strip()
+ return f"win:{out}" if out.isdigit() else None
+ except (OSError, subprocess.SubprocessError):
+ return None
+ try:
+ with open(f"/proc/{pid}/stat", "r") as f:
+ stat = f.read()
+ fields = stat[stat.rindex(")") + 2 :].split(" ")
+ if len(fields) > 19 and fields[19]:
+ return f"proc:{fields[19]}"
+ except (OSError, ValueError):
+ pass
+ try:
+ # macOS has no /proc; /bin/ps is always present there, so use the
+ # absolute path (bare `ps` stays only as the exotic-POSIX last resort).
+ ps = "/bin/ps" if sys.platform == "darwin" else "ps"
+ out = subprocess.run(
+ [ps, "-p", str(pid), "-o", "lstart="], capture_output=True, text=True, timeout=5
+ ).stdout.strip()
+ return f"ps:{out}" if out else None
+ except (OSError, subprocess.SubprocessError):
+ return None
+
+
+def _record_journal(pid: int, active: bool) -> bool:
+ # Returns False only when the journal is configured but enrollment failed;
+ # active-record callers must then fail closed. Active records always carry
+ # a processStartId so host reaping stays identity-verified.
+ path = os.environ.get("PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL")
+ owner = os.environ.get("PRIME_AGENT_KERNEL_OWNER_PID")
+ if not path or not owner:
+ return True
+ try:
+ owner_pid = int(owner)
+ except ValueError:
+ return False
+ start_id = _process_start_id(pid) if active else None
+ if active and start_id is None:
+ return False
+ record: dict[str, Any] = {
+ "version": 1,
+ "pid": pid,
+ "ownerPid": owner_pid,
+ # The host reaps bash children per kernel pid when it kills or loses this kernel.
+ "kernelPid": os.getpid(),
+ **({"processStartId": start_id} if start_id else {}),
+ "active": active,
+ "recordedAt": datetime.now(timezone.utc).isoformat(),
+ }
+ data = (json.dumps(record) + "\n").encode()
+ try:
+ fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
+ try:
+ # Complete-write loop: a short write would leave a truncated JSON
+ # line that the host discards, which must count as failure.
+ view = memoryview(data)
+ while view:
+ written = os.write(fd, view)
+ if written <= 0:
+ return False
+ view = view[written:]
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+ except OSError:
+ return False
+ return True
+
+
+def _kill_live_handles() -> None:
+ with _live_lock:
+ handles = list(_live_handles)
+ for handle in handles:
+ if _IS_POSIX:
+ delivered = _signal_group(handle._pid, signal.SIGKILL)
+ else:
+ with handle._kill_lock:
+ if handle._reaped:
+ continue
+ delivered = handle._job is not None and _winjob.terminate(handle._job)
+ if not delivered:
+ delivered = _taskkill_tree(handle._pid)
+ if not delivered:
+ # Leader-only fallback cannot prove the tree died: never
+ # justifies an inactive record.
+ try:
+ handle._proc.kill()
+ except OSError:
+ pass
+ if delivered:
+ _record_journal(handle._pid, active=False)
+
+
+def _install_shutdown_hook() -> None:
+ global _hook_installed
+ with _hook_lock:
+ if _hook_installed:
+ return
+ _hook_installed = True
+ atexit.register(_kill_live_handles)
+ try:
+ kernel = get_ipython().kernel # type: ignore[name-defined]
+ except (AttributeError, NameError):
+ return
+ if getattr(kernel, "_prime_agent_bash_shutdown", False):
+ return
+ original = kernel.do_shutdown
+
+ async def do_shutdown(restart: bool):
+ _kill_live_handles()
+ result = original(restart)
+ if hasattr(result, "__await__"):
+ return await result
+ return result
+
+ kernel.do_shutdown = do_shutdown
+ kernel._prime_agent_bash_shutdown = True
diff --git a/prime-agent-runtime/test/test_bash.py b/prime-agent-runtime/test/test_bash.py
new file mode 100644
index 0000000000..6fc4233247
--- /dev/null
+++ b/prime-agent-runtime/test/test_bash.py
@@ -0,0 +1,1221 @@
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import resource
+import signal
+import socket
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import unittest
+from concurrent.futures import ThreadPoolExecutor
+from unittest import mock
+
+from rlm import bash
+
+# The package re-exports the bash() function under the same name, so reach the
+# module through sys.modules for internals.
+bash_module = sys.modules["rlm.bash"]
+
+
+def _win_spawn(procs=None, resume=True):
+ # POSIX stand-in for _winjob.spawn_in_job: a real Popen plus a resume() mock (Ubuntu CI).
+ def spawn_in_job(job, argv, cwd, env):
+ proc = subprocess.Popen(
+ argv,
+ cwd=cwd,
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ stdin=subprocess.DEVNULL,
+ )
+ proc.resume = mock.Mock(return_value=resume)
+ proc.close = mock.Mock()
+ proc.spawn_job = job
+ proc.spawn_argv = argv
+ if procs is not None:
+ procs.append(proc)
+ return proc
+
+ return spawn_in_job
+
+
+class BashTest(unittest.IsolatedAsyncioTestCase):
+ async def test_await_returns_result(self):
+ result = await bash("echo hi")
+ self.assertEqual(result.exit_code, 0)
+ self.assertIn("hi", result.output)
+ self.assertGreaterEqual(result.duration, 0)
+
+ handle = bash("echo again")
+ awaited = await handle
+ self.assertEqual(handle.poll(), awaited)
+
+ async def test_status_pipe_survives_high_fds_and_strict_posix_shell(self):
+ # Regression: dash rejects multi-digit fds in redirections at parse
+ # time, so the script must never reference the raw status-pipe fd.
+ dummies = [os.open(os.devnull, os.O_RDONLY) for _ in range(30)]
+ self.addCleanup(lambda: [os.close(fd) for fd in dummies])
+ if os.path.exists("/bin/dash"):
+ with mock.patch.dict(os.environ, {"PRIME_AGENT_BASH_SHELL": "/bin/dash"}):
+ result = await bash("echo ok")
+ self.assertEqual(result.exit_code, 0)
+ self.assertIn("ok", result.output)
+ result = await bash("echo ok-default")
+ self.assertEqual(result.exit_code, 0)
+ self.assertIn("ok-default", result.output)
+
+ async def test_backgrounded_tail_and_kill(self):
+ handle = bash("echo start; sleep 30")
+ self.assertIsNone(handle.poll())
+ for _ in range(100):
+ if "start" in handle.tail():
+ break
+ await asyncio.sleep(0.05)
+ self.assertIn("start", handle.tail())
+ self.assertTrue(handle.running)
+ handle.kill(grace=0.2)
+ result = await asyncio.wait_for(handle, timeout=5)
+ self.assertNotEqual(result.exit_code, 0)
+
+ async def test_kill_escalates_to_sigkill(self):
+ handle = bash("trap '' TERM; echo up; sleep 30")
+ for _ in range(100):
+ if "up" in handle.output():
+ break
+ await asyncio.sleep(0.05)
+ handle.kill(grace=0.2)
+ result = await asyncio.wait_for(handle, timeout=10)
+ self.assertEqual(result.exit_code, -9)
+
+ async def test_buffer_cap_keeps_head_and_tail(self):
+ result = await bash("seq 1 400000")
+ self.assertLessEqual(len(result.output), 2 * 1024 * 1024 + 256)
+ self.assertTrue(result.output.startswith("1\n"))
+ self.assertIn("400000", result.output)
+ self.assertIn("bytes dropped", result.output)
+
+ async def test_env_prefix_and_journal(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ journal = os.path.join(tmp, "journal.jsonl")
+ with mock.patch.dict(
+ os.environ,
+ {
+ "PRIME_AGENT_BASH_COMMAND_PREFIX": "echo prefixed",
+ "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL": journal,
+ "PRIME_AGENT_KERNEL_OWNER_PID": str(os.getpid()),
+ },
+ ):
+ handle = bash('echo "$NO_COLOR $TERM"')
+ result = await handle
+ # The inactive record lands slightly after finalize, once the group exits.
+ records = await _poll_journal(journal, count=2)
+ self.assertEqual(result.exit_code, 0)
+ lines = result.output.splitlines()
+ self.assertEqual(lines[0], "prefixed")
+ self.assertIn("1 dumb", lines[1])
+
+ self.assertEqual([r["active"] for r in records], [True, False])
+ for record in records:
+ self.assertEqual(record["pid"], handle.pid)
+ self.assertEqual(record["ownerPid"], os.getpid())
+ self.assertEqual(record["kernelPid"], os.getpid())
+ self.assertTrue(records[0]["processStartId"].startswith(("proc:", "ps:")))
+
+ async def test_await_returns_when_shell_backgrounds_child(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ journal = os.path.join(tmp, "journal.jsonl")
+ with mock.patch.dict(
+ os.environ,
+ {
+ "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL": journal,
+ "PRIME_AGENT_KERNEL_OWNER_PID": str(os.getpid()),
+ },
+ ):
+ handle = bash("echo fg; sleep 30 &")
+ result = await asyncio.wait_for(handle, timeout=5)
+ self.assertEqual(result.exit_code, 0)
+ self.assertIn("fg", result.output)
+ # The shell stays alive as group leader, anchoring its background job.
+ os.killpg(handle.pid, 0)
+ records = await _poll_journal(journal, count=1)
+ self.assertTrue(records[-1]["active"])
+ handle.kill(signal.SIGKILL)
+ records = await _poll_journal(journal, count=2)
+ self.assertFalse(records[-1]["active"])
+
+ async def test_early_shell_exit_returns_and_kills_group(self):
+ handle = bash("sleep 30 & exit 7")
+ result = await asyncio.wait_for(handle, timeout=5)
+ self.assertEqual(result.exit_code, 7)
+ # The leader died without draining, so the stale group must be killed.
+ await _poll_group_dead(handle.pid)
+
+ async def test_term_ignoring_child_is_escalated(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ journal = os.path.join(tmp, "journal.jsonl")
+ with mock.patch.dict(
+ os.environ,
+ {
+ "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL": journal,
+ "PRIME_AGENT_KERNEL_OWNER_PID": str(os.getpid()),
+ },
+ ):
+ handle = bash("sh -c 'trap \"\" TERM; echo ready; sleep 30' &")
+ await asyncio.wait_for(handle, timeout=5)
+ for _ in range(100):
+ if "ready" in handle.output():
+ break
+ await asyncio.sleep(0.05)
+ handle.kill(signal.SIGTERM)
+ records = await _poll_journal(journal, count=2, timeout=10)
+ self.assertFalse(records[-1]["active"])
+ await _poll_group_dead(handle.pid)
+
+ async def test_delivered_status_wins_when_shell_dies_during_drain(self):
+ entered = threading.Event()
+ release = threading.Event()
+ original = bash_module.BashHandle._drain_grace
+
+ def held_drain(handle_self):
+ # Hold only the first caller (the reporter, which drains right after
+ # reading status 0); any later caller must proceed normally.
+ if not entered.is_set():
+ entered.set()
+ release.wait(10)
+ original(handle_self)
+
+ with mock.patch.object(bash_module.BashHandle, "_drain_grace", held_drain):
+ # Background job keeps the shell alive in `wait` after status 0 is delivered.
+ handle = bash("sleep 30 & true")
+ try:
+ self.assertTrue(await asyncio.to_thread(entered.wait, 5))
+ os.kill(handle.pid, signal.SIGTERM)
+ # _watch must fully finish its finalize decision while _report is held.
+ for _ in range(200):
+ with bash_module._live_lock:
+ if handle not in bash_module._live_handles:
+ break
+ await asyncio.sleep(0.05)
+ else:
+ self.fail("watcher did not complete while reporter was held")
+ finally:
+ release.set()
+ result = await asyncio.wait_for(handle, timeout=5)
+ self.assertEqual(result.exit_code, 0)
+
+ async def test_delivered_status_wins_when_reporter_is_slow(self):
+ parsed = threading.Event()
+ release = threading.Event()
+ original = bash_module.BashHandle._read_status
+
+ def slow_read(handle_self):
+ # Pause after read+parse but before the status is reserved, longer
+ # than the old 1.0s _watch timeout, while the shell dies.
+ status = original(handle_self)
+ parsed.set()
+ release.wait(10)
+ return status
+
+ with mock.patch.object(bash_module.BashHandle, "_read_status", slow_read):
+ # Background job keeps the shell alive in `wait` after status 0 is written.
+ handle = bash("sleep 30 & true")
+ try:
+ self.assertTrue(await asyncio.to_thread(parsed.wait, 5))
+ os.kill(handle.pid, signal.SIGTERM)
+ # Outlast the old timeout so a timed wait would have finalized -15.
+ await asyncio.sleep(1.5)
+ self.assertIsNone(handle.poll())
+ finally:
+ release.set()
+ result = await asyncio.wait_for(handle, timeout=5)
+ self.assertEqual(result.exit_code, 0)
+
+ async def test_status_survives_pipe_fds_above_fd_setsize(self):
+ # select.select() rejects fds >= FD_SETSIZE (1024); the delivered status
+ # must still win when the status/wake pipes land above that boundary.
+ limits = resource.getrlimit(resource.RLIMIT_NOFILE)
+ if limits[0] < 1100:
+ try:
+ resource.setrlimit(resource.RLIMIT_NOFILE, (1100, limits[1]))
+ except (ValueError, OSError):
+ self.skipTest("cannot raise RLIMIT_NOFILE above FD_SETSIZE")
+ self.addCleanup(resource.setrlimit, resource.RLIMIT_NOFILE, limits)
+ held: list[int] = []
+ self.addCleanup(lambda: [os.close(fd) for fd in held])
+ while True:
+ fd = os.open(os.devnull, os.O_RDONLY)
+ held.append(fd)
+ if fd >= 1024:
+ break
+ handle = bash("echo hi; sleep 30 & true")
+ self.addCleanup(handle.kill, signal.SIGKILL)
+ result = await asyncio.wait_for(handle, timeout=5)
+ self.assertEqual(result.exit_code, 0)
+ self.assertIn("hi", result.output)
+
+ async def test_awaits_do_not_hold_executor_threads(self):
+ loop = asyncio.get_running_loop()
+ executor = ThreadPoolExecutor(max_workers=1)
+ loop.set_default_executor(executor)
+ tasks = [asyncio.ensure_future(bash("sleep 0.5")._wait()) for _ in range(3)]
+ await asyncio.sleep(0.1)
+ # Old executor-parked waits would deadlock this 1-thread pool.
+ value = await asyncio.wait_for(loop.run_in_executor(None, lambda: 42), timeout=0.3)
+ self.assertEqual(value, 42)
+ results = await asyncio.gather(*tasks)
+ self.assertTrue(all(r.exit_code == 0 for r in results))
+
+ def test_buffer_tail_retention_is_exact(self):
+ buffer = bash_module._BoundedBuffer()
+ buffer.write(b"x" * bash_module._HEAD_CAP)
+ buffer.write(b"a" * bash_module._TAIL_CAP)
+ buffer.write(b"b" * 1000)
+ self.assertEqual(buffer._tail_size, bash_module._TAIL_CAP)
+ text = buffer.text()
+ self.assertTrue(text.endswith("b" * 1000))
+ self.assertIn("a" * 1000 + "b" * 1000, text)
+
+ async def test_running_reflects_group_liveness(self):
+ handle = bash("echo fg; sleep 30 &")
+ result = await asyncio.wait_for(handle, timeout=5)
+ self.assertEqual(result.exit_code, 0)
+ # The foreground result is in, but the group still anchors `sleep 30 &`.
+ self.assertIsNotNone(handle.poll())
+ self.assertTrue(handle.running)
+ handle.kill(signal.SIGKILL)
+ for _ in range(100):
+ if not handle.running:
+ break
+ await asyncio.sleep(0.05)
+ self.assertFalse(handle.running)
+
+ async def test_windows_kill_terminates_tree(self):
+ # Pins the taskkill fallback when TerminateJobObject failed or raced.
+ handle = bash("sleep 30")
+ try:
+ handle._job = None
+ completed = mock.Mock(returncode=0)
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(handle._proc, "kill") as proc_kill:
+ patched_run = mock.patch.object(
+ bash_module.subprocess, "run", return_value=completed
+ )
+ with mock.patch.dict(os.environ, {"SystemRoot": r"C:\WinTest"}):
+ with patched_run as run:
+ handle.kill()
+ taskkill = os.path.join(r"C:\WinTest", "System32", "taskkill.exe")
+ self.assertEqual(
+ run.call_args.args[0], [taskkill, "/PID", str(handle.pid), "/T", "/F"]
+ )
+ self.assertEqual(
+ run.call_args.kwargs["env"]["NoDefaultCurrentDirectoryInExePath"], "1"
+ )
+ proc_kill.assert_not_called()
+ # No SystemRoot in the env falls back to C:\Windows.
+ with mock.patch.dict(os.environ):
+ os.environ.pop("SystemRoot", None)
+ with patched_run as run:
+ handle.kill()
+ self.assertTrue(run.call_args.args[0][0].startswith(r"C:\Windows"))
+ # taskkill unavailable or failing must fall back to Popen.kill().
+ with mock.patch.object(bash_module.subprocess, "run", side_effect=OSError):
+ handle.kill()
+ proc_kill.assert_called_once()
+ finally:
+ handle.kill(signal.SIGKILL)
+ await asyncio.wait_for(handle, timeout=5)
+
+ def test_gate_eof_without_journal_prevents_command_execution(self):
+ # A kernel SIGKILL between Popen and journaling closes the parent socket;
+ # the child's gate read must then EOF and exit before running the command.
+ if not bash_module._IS_POSIX:
+ self.skipTest("POSIX-only gate")
+ with tempfile.TemporaryDirectory() as tmp:
+ marker = os.path.join(tmp, "ran")
+ script = bash_module._status_script(f"touch {marker}")
+ parent, child = socket.socketpair()
+ proc = subprocess.Popen(
+ [bash_module._shell(), "-c", script],
+ stdin=child.fileno(),
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ child.close()
+ parent.close() # simulate parent death before the gate byte
+ proc.communicate(timeout=10)
+ self.assertEqual(proc.returncode, 127)
+ self.assertFalse(os.path.exists(marker))
+
+ def test_status_socket_closed_when_wake_pipe_fails(self):
+ if not bash_module._IS_POSIX:
+ self.skipTest("POSIX-only fds")
+ acquired: list[int] = []
+ closed: list[int] = []
+ real_socketpair = socket.socketpair
+ real_close = os.close
+
+ def capturing_socketpair(*args, **kwargs):
+ pair = real_socketpair(*args, **kwargs)
+ acquired.extend((pair[0].fileno(), pair[1].fileno()))
+ return pair
+
+ def recording_close(fd):
+ closed.append(fd)
+ real_close(fd)
+
+ with mock.patch.object(bash_module.socket, "socketpair", capturing_socketpair):
+ with mock.patch.object(bash_module.os, "close", recording_close):
+ with mock.patch.object(bash_module.os, "pipe", side_effect=OSError("boom")):
+ with self.assertRaises(OSError):
+ bash("echo never")
+ self.assertEqual(len(acquired), 2)
+ for fd in acquired:
+ self.assertIn(fd, closed)
+
+ def test_windows_process_start_id(self):
+ completed = mock.Mock(stdout="638000000000000000\n")
+ with mock.patch.dict(os.environ, {"SystemRoot": r"C:\WinTest"}):
+ with mock.patch.object(bash_module.os, "name", "nt"):
+ with mock.patch.object(
+ bash_module.subprocess, "run", return_value=completed
+ ) as run:
+ self.assertEqual(bash_module._process_start_id(1234), "win:638000000000000000")
+ argv = run.call_args.args[0]
+ self.assertEqual(
+ argv[0],
+ os.path.join(r"C:\WinTest", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
+ )
+ self.assertEqual(run.call_args.kwargs["env"]["NoDefaultCurrentDirectoryInExePath"], "1")
+ self.assertIn("GetProcessById(1234)", argv[-1])
+ garbage = mock.Mock(stdout="not a number\n")
+ with mock.patch.object(bash_module.os, "name", "nt"):
+ with mock.patch.object(bash_module.subprocess, "run", return_value=garbage):
+ self.assertIsNone(bash_module._process_start_id(1234))
+
+ async def test_cancelled_direct_await_kills_group(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ marker = os.path.join(tmp, "marker")
+ pids: list[int] = []
+ original_init = bash_module.BashHandle.__init__
+
+ def capturing_init(handle_self, command):
+ original_init(handle_self, command)
+ pids.append(handle_self._pid)
+
+ async def run_oneshot():
+ await bash(f"sleep 1.0 && touch {marker}")
+
+ with mock.patch.object(bash_module.BashHandle, "__init__", capturing_init):
+ task = asyncio.ensure_future(run_oneshot())
+ await asyncio.sleep(0.3)
+ task.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await task
+ # The cancel path awaits confirmed group death before propagating.
+ if bash_module._IS_POSIX:
+ with self.assertRaises(ProcessLookupError):
+ os.killpg(pids[0], 0)
+ await asyncio.sleep(1.0)
+ self.assertFalse(os.path.exists(marker))
+
+ async def test_cancelled_direct_await_escalates_past_term_trap(self):
+ # A TERM-trapping command must be group-KILLed before the cancel
+ # resolves, so its later side effects never land.
+ with tempfile.TemporaryDirectory() as tmp:
+ marker = os.path.join(tmp, "marker")
+ pids: list[int] = []
+ original_init = bash_module.BashHandle.__init__
+
+ def capturing_init(handle_self, command):
+ original_init(handle_self, command)
+ pids.append(handle_self._pid)
+
+ async def run_oneshot():
+ await bash(f"trap '' TERM; sleep 1.0; touch {marker}; sleep 30")
+
+ with mock.patch.object(bash_module, "_CANCEL_TERM_GRACE", 0.2):
+ with mock.patch.object(bash_module.BashHandle, "__init__", capturing_init):
+ task = asyncio.ensure_future(run_oneshot())
+ await asyncio.sleep(0.2)
+ task.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await task
+ if bash_module._IS_POSIX:
+ with self.assertRaises(ProcessLookupError):
+ os.killpg(pids[0], 0)
+ await asyncio.sleep(1.2)
+ self.assertFalse(os.path.exists(marker))
+
+ async def test_background_handle_survives_cancel_of_creating_context(self):
+ handles: list[bash_module.BashHandle] = []
+
+ async def run_background():
+ h = bash("sleep 30")
+ handles.append(h)
+ h.pid # released as a deliberate background handle
+ await asyncio.sleep(10)
+
+ task = asyncio.ensure_future(run_background())
+ await asyncio.sleep(0.3)
+ task.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await task
+ handle = handles[0]
+ try:
+ os.killpg(handle._pid, 0) # still alive
+ finally:
+ handle.kill(signal.SIGKILL)
+ await asyncio.wait_for(handle, timeout=5)
+
+ async def test_cancelling_await_on_released_handle_does_not_kill(self):
+ handle = bash("sleep 30")
+ self.assertTrue(handle.running) # release as background handle
+
+ async def wait_for_it():
+ await handle
+
+ task = asyncio.ensure_future(wait_for_it())
+ await asyncio.sleep(0.3)
+ task.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await task
+ try:
+ os.killpg(handle._pid, 0) # still alive
+ finally:
+ handle.kill(signal.SIGKILL)
+ await asyncio.wait_for(handle, timeout=5)
+
+ async def test_second_await_after_cancelled_oneshot_only_waits(self):
+ handle = bash("echo done")
+ # First await consumes the one-shot ownership; later awaits only wait.
+ result = await handle
+ self.assertEqual(result.exit_code, 0)
+ self.assertTrue(handle._released)
+ again = await handle
+ self.assertEqual(again, result)
+
+ async def test_second_cancel_during_cleanup_still_confirms_group_death(self):
+ # Python 3.11: an await inside an except-CancelledError block of a
+ # cancelled task is re-cancelled immediately; the shielded confirm task
+ # must survive repeated cancels and the group must be dead on return.
+ pids: list[int] = []
+ original_init = bash_module.BashHandle.__init__
+
+ def capturing_init(handle_self, command):
+ original_init(handle_self, command)
+ pids.append(handle_self._pid)
+
+ async def run_oneshot():
+ await bash("trap '' TERM; sleep 30")
+
+ with mock.patch.object(bash_module, "_CANCEL_TERM_GRACE", 0.2):
+ with mock.patch.object(bash_module.BashHandle, "__init__", capturing_init):
+ task = asyncio.ensure_future(run_oneshot())
+ await asyncio.sleep(0.2)
+ task.cancel()
+ await asyncio.sleep(0.05)
+ task.cancel() # lands inside the cleanup awaits
+ await asyncio.sleep(0.05)
+ task.cancel()
+ with self.assertRaises(asyncio.CancelledError):
+ await task
+ with self.assertRaises(ProcessLookupError):
+ os.killpg(pids[0], 0)
+
+ async def test_windows_without_bash_raises_teaching_error(self):
+ # Windows must raise without consulting PATH: a which() hit would be
+ # the same repo-controlled-PATH hole the host-side resolution closed.
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(
+ bash_module.shutil, "which", return_value=r"C:\evil\bash.exe"
+ ) as which:
+ with self.assertRaisesRegex(RuntimeError, "PRIME_AGENT_BASH_SHELL"):
+ bash_module._shell()
+ which.assert_not_called()
+
+ async def test_pump_paused_between_read_and_commit_does_not_lose_output(self):
+ # Reviewer repro: the chunk is out of the pipe (FIONREAD 0) but not yet
+ # in the buffer; the drain fence must wait for the commit.
+ original_write = bash_module._BoundedBuffer.write
+ delayed_once = threading.Event()
+
+ def delayed_write(buffer_self, chunk):
+ if not delayed_once.is_set():
+ delayed_once.set()
+ time.sleep(0.3)
+ original_write(buffer_self, chunk)
+
+ with mock.patch.object(bash_module._BoundedBuffer, "write", delayed_write):
+ result = await asyncio.wait_for(bash("printf between-read-and-write"), timeout=5)
+ self.assertEqual(result.exit_code, 0)
+ self.assertIn("between-read-and-write", result.output)
+
+ async def test_slow_pump_does_not_lose_foreground_output(self):
+ # A descheduled pump must not let _drain_grace conclude quiescence
+ # while the shell's output still sits unread in the pipe.
+ original_pump = bash_module.BashHandle._pump
+
+ def slow_pump(handle_self):
+ time.sleep(0.3)
+ original_pump(handle_self)
+
+ with mock.patch.object(bash_module.BashHandle, "_pump", slow_pump):
+ result = await asyncio.wait_for(bash("printf slow-pump-x"), timeout=5)
+ self.assertEqual(result.exit_code, 0)
+ self.assertIn("slow-pump-x", result.output)
+
+ async def test_relative_bash_shell_override_rejected(self):
+ with mock.patch.dict(os.environ, {"PRIME_AGENT_BASH_SHELL": "bash"}):
+ with self.assertRaises(ValueError):
+ bash("echo hi")
+
+ async def test_windows_journal_writes_only_enriched_record(self):
+ # No pid-only pre-record on Windows: the kill-on-close job replaces it
+ # (a kernel death reaps the tree via handle closure, so a bare-pid
+ # anchor would only ever justify killing a reused pid).
+ with tempfile.TemporaryDirectory() as tmp:
+ journal = os.path.join(tmp, "journal.jsonl")
+ with mock.patch.dict(
+ os.environ,
+ {
+ "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL": journal,
+ "PRIME_AGENT_KERNEL_OWNER_PID": str(os.getpid()),
+ "PRIME_AGENT_BASH_SHELL": "/bin/sh",
+ },
+ ):
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module._winjob, "spawn_in_job", _win_spawn()):
+ with mock.patch.object(bash_module._winjob, "create_job", return_value=7):
+ with mock.patch.object(
+ bash_module._winjob, "terminate", return_value=True
+ ):
+ with mock.patch.object(bash_module._winjob, "close"):
+ handle = bash("echo hi")
+ await asyncio.wait_for(handle, timeout=5)
+ for _ in range(100):
+ if handle._reaped:
+ break
+ await asyncio.sleep(0.05)
+ active = [r for r in await _poll_journal(journal, count=1) if r["active"]]
+ self.assertEqual(len(active), 1)
+ self.assertIn("processStartId", active[0])
+
+ async def test_windows_spawn_creates_child_inside_job(self):
+ sentinel = 4242
+ spawned = []
+ order = []
+ real_journal = bash_module._record_journal
+ base_spawn = _win_spawn(spawned)
+
+ def journal(pid, active):
+ order.append("journal")
+ return real_journal(pid, active)
+
+ def spawn(job, argv, cwd, env):
+ order.append("spawn")
+ proc = base_spawn(job, argv, cwd, env)
+ proc.resume = mock.Mock(side_effect=lambda: order.append("resume") or True)
+ return proc
+
+ self.enterContext(mock.patch.dict(os.environ, {"PRIME_AGENT_BASH_SHELL": "/bin/sh"}))
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module._winjob, "spawn_in_job", spawn):
+ with mock.patch.object(bash_module, "_record_journal", journal):
+ with mock.patch.object(
+ bash_module._winjob,
+ "create_job",
+ side_effect=lambda: order.append("create_job") or sentinel,
+ ):
+ handle = bash("sleep 30")
+ try:
+ # The journal write runs while the job-contained child is still suspended.
+ self.assertEqual(spawned[-1].spawn_job, sentinel)
+ self.assertEqual(
+ spawned[-1].spawn_argv,
+ ["/bin/sh", "-c", bash_module._with_prefix("sleep 30")],
+ )
+ spawned[-1].resume.assert_called_once_with()
+ self.assertEqual(order, ["create_job", "spawn", "journal", "resume"])
+ self.assertEqual(handle._job, sentinel)
+ finally:
+ handle._job = None
+ handle.kill(signal.SIGKILL)
+ await asyncio.wait_for(handle, timeout=5)
+
+ async def test_windows_create_job_failure_fails_closed(self):
+ journal_calls = []
+
+ def journal(pid, active):
+ journal_calls.append((pid, active))
+ return True
+
+ self.enterContext(mock.patch.dict(os.environ, {"PRIME_AGENT_BASH_SHELL": "/bin/sh"}))
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module._winjob, "spawn_in_job") as spawn:
+ with mock.patch.object(bash_module, "_record_journal", journal):
+ with mock.patch.object(bash_module._winjob, "create_job", return_value=None):
+ with self.assertRaisesRegex(RuntimeError, "job containment"):
+ bash("sleep 30")
+ # A create_job failure aborts before spawn_in_job: nothing spawned, nothing journaled.
+ spawn.assert_not_called()
+ self.assertEqual(journal_calls, [])
+
+ async def test_windows_resume_failure_fails_closed(self):
+ sentinel = 4343
+ spawned = []
+ journal_calls = []
+
+ def journal(pid, active):
+ journal_calls.append((pid, active))
+ return True
+
+ def terminate(job):
+ # The abort kills the suspended, job-contained child via the job.
+ spawned[0].kill()
+ return True
+
+ self.enterContext(mock.patch.dict(os.environ, {"PRIME_AGENT_BASH_SHELL": "/bin/sh"}))
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(
+ bash_module._winjob, "spawn_in_job", _win_spawn(spawned, resume=False)
+ ):
+ with mock.patch.object(bash_module, "_record_journal", journal):
+ with mock.patch.object(
+ bash_module._winjob, "create_job", return_value=sentinel
+ ):
+ with mock.patch.object(
+ bash_module._winjob, "terminate", side_effect=terminate
+ ) as term:
+ with mock.patch.object(bash_module._winjob, "close") as close:
+ with self.assertRaisesRegex(RuntimeError, "job containment"):
+ bash("sleep 30")
+ term.assert_called_once_with(sentinel)
+ close.assert_called_once_with(sentinel)
+ self.assertIsNotNone(spawned[0].poll())
+ spawned[0].close.assert_called_once()
+ self.assertEqual(journal_calls, [(spawned[0].pid, True), (spawned[0].pid, False)])
+
+ async def test_windows_journal_enrollment_failure_kills_suspended_leader(self):
+ # A journal failure must kill the suspended, job-contained leader and retire the record.
+ sentinel = 4545
+ spawned = []
+ journal_calls = []
+
+ def journal(pid, active):
+ journal_calls.append((pid, active))
+ return not active # enrollment fails; the retirement write succeeds
+
+ def terminate(job):
+ spawned[0].kill()
+ return True
+
+ self.enterContext(mock.patch.dict(os.environ, {"PRIME_AGENT_BASH_SHELL": "/bin/sh"}))
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module._winjob, "spawn_in_job", _win_spawn(spawned)):
+ with mock.patch.object(bash_module, "_record_journal", journal):
+ with mock.patch.object(
+ bash_module._winjob, "create_job", return_value=sentinel
+ ):
+ with mock.patch.object(
+ bash_module._winjob, "terminate", side_effect=terminate
+ ) as term:
+ with mock.patch.object(bash_module._winjob, "close") as close:
+ with self.assertRaisesRegex(RuntimeError, "journal enrollment"):
+ bash("sleep 30")
+ term.assert_called_once_with(sentinel)
+ close.assert_called_once_with(sentinel)
+ spawned[0].resume.assert_not_called()
+ self.assertIsNotNone(spawned[0].poll())
+ self.assertEqual(journal_calls, [(spawned[0].pid, True), (spawned[0].pid, False)])
+
+ async def test_windows_spawn_failure_closes_precreated_job(self):
+ # A spawn_in_job failure must close the pre-created job and never touch the journal.
+ sentinel = 4646
+ journal_calls = []
+
+ def journal(pid, active):
+ journal_calls.append((pid, active))
+ return True
+
+ def spawn(job, argv, cwd, env):
+ raise OSError("spawn failed")
+
+ self.enterContext(mock.patch.dict(os.environ, {"PRIME_AGENT_BASH_SHELL": "/bin/sh"}))
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module._winjob, "spawn_in_job", spawn):
+ with mock.patch.object(bash_module, "_record_journal", journal):
+ with mock.patch.object(
+ bash_module._winjob, "create_job", return_value=sentinel
+ ):
+ with mock.patch.object(bash_module._winjob, "close") as close:
+ with self.assertRaises(OSError):
+ bash("sleep 30")
+ close.assert_called_once_with(sentinel)
+ self.assertEqual(journal_calls, [])
+
+ async def test_windows_watch_taskkill_fallback_runs_before_process_handle_close(self):
+ # PID-reuse guard: every taskkill-by-pid must run before the handle closes.
+ order = []
+ spawned = []
+ handle_box = []
+ ready, closed_done = threading.Event(), threading.Event()
+
+ def spawn(job, argv, cwd, env):
+ proc = _win_spawn(spawned)(job, argv, cwd, env)
+
+ def record_close():
+ order.append(("proc-close", handle_box[0]._reaped))
+ closed_done.set()
+
+ proc.close = mock.Mock(side_effect=record_close)
+ return proc
+
+ def terminate(job):
+ assert ready.wait(timeout=5) # gate: handle_box is filled first
+ order.append("terminate")
+ return False
+
+ def taskkill(pid):
+ order.append(("taskkill", spawned[0].close.called))
+ return True
+
+ self.enterContext(mock.patch.dict(os.environ, {"PRIME_AGENT_BASH_SHELL": "/bin/sh"}))
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module._winjob, "spawn_in_job", spawn):
+ with mock.patch.object(bash_module._winjob, "create_job", return_value=777):
+ with mock.patch.object(bash_module._winjob, "terminate", terminate):
+ with mock.patch.object(
+ bash_module._winjob, "close",
+ side_effect=lambda job: order.append("job-close"),
+ ):
+ with mock.patch.object(bash_module, "_taskkill_tree", taskkill):
+ handle = bash("echo hi")
+ handle_box.append(handle)
+ ready.set()
+ await asyncio.wait_for(handle, timeout=5)
+ self.assertTrue(await asyncio.to_thread(closed_done.wait, 5))
+ self.assertEqual(
+ order, ["terminate", "job-close", ("taskkill", False), ("proc-close", True)]
+ )
+
+ async def test_windows_kill_blocked_during_watch_reap_never_taskkills_after_close(self):
+ # kill() blocked on the reap lock must become a no-op, never a raw-pid taskkill.
+ spawned = []
+ entered, release = threading.Event(), threading.Event()
+
+ def spawn(job, argv, cwd, env):
+ return _win_spawn(spawned)(job, argv, cwd, env)
+
+ def terminate(job):
+ entered.set()
+ assert release.wait(timeout=10)
+ return True
+
+ self.enterContext(mock.patch.dict(os.environ, {"PRIME_AGENT_BASH_SHELL": "/bin/sh"}))
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module._winjob, "spawn_in_job", spawn):
+ with mock.patch.object(bash_module._winjob, "create_job", return_value=778):
+ with mock.patch.object(
+ bash_module._winjob, "terminate", side_effect=terminate
+ ) as term:
+ with mock.patch.object(bash_module._winjob, "close"):
+ with mock.patch.object(bash_module, "_taskkill_tree") as taskkill:
+ handle = bash("echo hi")
+ await asyncio.wait_for(handle, timeout=5)
+ self.assertTrue(await asyncio.to_thread(entered.wait, 5))
+ fut = asyncio.get_running_loop().run_in_executor(
+ None, handle.kill
+ )
+ await asyncio.sleep(0.2)
+ self.assertFalse(fut.done()) # blocked on the reap lock
+ taskkill.assert_not_called()
+ release.set()
+ await asyncio.wait_for(fut, timeout=5)
+ for _ in range(100):
+ if handle._reaped:
+ break
+ await asyncio.sleep(0.05)
+ taskkill.assert_not_called()
+ term.assert_called_once()
+ spawned[0].close.assert_called_once()
+ self.assertTrue(handle._reaped)
+
+ async def test_kill_live_handles_skips_reaped_windows_handle(self):
+ stale = mock.Mock(_kill_lock=threading.Lock(), _reaped=True, _job=5, _pid=999)
+ with bash_module._live_lock:
+ bash_module._live_handles.add(stale)
+ try:
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module._winjob, "terminate") as term:
+ with mock.patch.object(bash_module, "_taskkill_tree") as taskkill:
+ with mock.patch.object(bash_module, "_record_journal") as journal:
+ bash_module._kill_live_handles()
+ finally:
+ with bash_module._live_lock:
+ bash_module._live_handles.discard(stale)
+ term.assert_not_called()
+ taskkill.assert_not_called()
+ stale._proc.kill.assert_not_called()
+ journal.assert_not_called()
+
+ async def test_kill_live_handles_blocked_on_abort_never_taskkills_after_close(self):
+ # PID-reuse guard on the abort path: abort's reaped+close section must block
+ # on _kill_lock while a raw-pid taskkill is in flight, so the handle can
+ # never close mid-taskkill.
+ order = []
+ spawned = []
+ journal_calls = []
+ entered, release_term = threading.Event(), threading.Event()
+ stdout_entered, stdout_release = threading.Event(), threading.Event()
+ tk_entered, tk_release = threading.Event(), threading.Event()
+
+ def spawn(job, argv, cwd, env):
+ proc = _win_spawn(spawned)(job, argv, cwd, env)
+ proc.kill = mock.Mock()
+ proc.close = mock.Mock(side_effect=lambda: order.append("proc-close"))
+ real_stdout = proc.stdout
+
+ def gated_close():
+ # Parks abort between its two locked sections (lock released).
+ stdout_entered.set()
+ assert stdout_release.wait(timeout=10)
+ real_stdout.close()
+
+ proc.stdout = mock.Mock(close=mock.Mock(side_effect=gated_close))
+ return proc
+
+ def journal(pid, active):
+ journal_calls.append((pid, active))
+ return not active # enrollment fails -> _abort_spawn; retirement succeeds
+
+ def terminate(job):
+ order.append("abort-terminate")
+ entered.set()
+ assert release_term.wait(timeout=10)
+ return True
+
+ def taskkill(pid):
+ # Blocks INSIDE the killer's locked section: abort must wait on the lock.
+ order.append(("killer-taskkill", spawned[0].close.called))
+ tk_entered.set()
+ assert tk_release.wait(timeout=10)
+ return True
+
+ self.enterContext(mock.patch.dict(os.environ, {"PRIME_AGENT_BASH_SHELL": "/bin/sh"}))
+ loop = asyncio.get_running_loop()
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module._winjob, "spawn_in_job", spawn):
+ with mock.patch.object(bash_module._winjob, "create_job", return_value=900):
+ with mock.patch.object(
+ bash_module._winjob, "terminate", side_effect=terminate
+ ) as term:
+ with mock.patch.object(
+ bash_module._winjob, "close",
+ side_effect=lambda job: order.append("abort-jobclose"),
+ ):
+ with mock.patch.object(bash_module, "_record_journal", journal):
+ with mock.patch.object(
+ bash_module, "_taskkill_tree", side_effect=taskkill
+ ):
+ ctor = loop.run_in_executor(
+ None, lambda: bash("echo hi")
+ )
+ self.assertTrue(await asyncio.to_thread(entered.wait, 5))
+ # Phase 1: abort holds _kill_lock -> the killer blocks.
+ killer = loop.run_in_executor(
+ None, bash_module._kill_live_handles
+ )
+ await asyncio.sleep(0.2)
+ self.assertFalse(killer.done())
+ self.assertFalse(tk_entered.is_set())
+ # Phase 2: abort parks at stdout; the killer takes the
+ # lock and blocks inside taskkill while holding it.
+ release_term.set()
+ self.assertTrue(
+ await asyncio.to_thread(tk_entered.wait, 5)
+ )
+ stdout_release.set()
+ # Abort finishes stdout/wait but must block on the
+ # lock: close cannot run while taskkill is in flight.
+ await asyncio.sleep(0.3)
+ self.assertFalse(ctor.done())
+ self.assertFalse(spawned[0].close.called)
+ # Phase 3: taskkill returns, killer releases the lock,
+ # abort's reaped+close section finally runs.
+ tk_release.set()
+ with self.assertRaisesRegex(RuntimeError, "journal"):
+ await asyncio.wait_for(ctor, timeout=10)
+ await asyncio.wait_for(killer, timeout=10)
+ self.assertEqual(
+ order,
+ ["abort-terminate", "abort-jobclose", ("killer-taskkill", False), "proc-close"],
+ )
+ self.assertEqual(spawned[0].close.call_count, 1) # once, only after taskkill returned
+ term.assert_called_once() # the killer saw _job None; no second terminate
+ spawned[0].kill.assert_not_called()
+ pid = spawned[0].pid
+ self.assertEqual(journal_calls, [(pid, True), (pid, False), (pid, False)])
+
+ async def test_windows_job_reap_and_kill(self):
+ handle = bash("sleep 30")
+ job = 777
+ handle._job = job
+ try:
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module, "_taskkill_tree") as taskkill:
+ with mock.patch.object(bash_module._winjob, "terminate", return_value=True) as term:
+ with mock.patch.object(bash_module._winjob, "close") as close:
+ with mock.patch.object(bash_module._winjob, "is_empty", return_value=False):
+ self.assertTrue(handle._group_alive())
+ with mock.patch.object(bash_module._winjob, "is_empty", return_value=True):
+ self.assertFalse(handle._group_alive())
+ handle.kill()
+ term.assert_called_once_with(job)
+ term.reset_mock()
+ # Reap terminates, closes the last handle, and
+ # retires the journal record (tree provably dead).
+ self.assertTrue(handle._reap_group())
+ term.assert_called_once_with(job)
+ close.assert_called_once_with(job)
+ self.assertIsNone(handle._job)
+ handle._reaped = True
+ handle.kill() # job-reaped: no taskkill second chance
+ taskkill.assert_not_called()
+ finally:
+ handle._reaped = False
+ handle._job = None
+ handle.kill(signal.SIGKILL)
+ await asyncio.wait_for(handle, timeout=5)
+
+ async def test_windows_failed_job_terminate_falls_back_to_taskkill(self):
+ handle = bash("sleep 30")
+ job = 888
+ handle._job = job
+ try:
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module._winjob, "terminate", return_value=False):
+ with mock.patch.object(bash_module._winjob, "close") as close:
+ with mock.patch.object(
+ bash_module, "_taskkill_tree", return_value=True
+ ) as taskkill:
+ handle.kill() # failed terminate must not strand the tree
+ taskkill.assert_called_once_with(handle._pid)
+ taskkill.reset_mock()
+ # Reap closes the handle anyway (a kill attempt) but
+ # only journals inactive via the taskkill result.
+ self.assertTrue(handle._reap_group())
+ close.assert_called_once_with(job)
+ taskkill.assert_called_once_with(handle._pid)
+ self.assertIsNone(handle._job)
+ finally:
+ handle._reaped = False
+ handle._job = None
+ handle.kill(signal.SIGKILL)
+ await asyncio.wait_for(handle, timeout=5)
+
+ async def test_windows_failed_terminate_and_taskkill_leaves_record_active(self):
+ # Failed terminate + failed taskkill on an exited leader: nothing
+ # proved the tree died, so the record stays active for the host reaper.
+ handle = bash("echo hi")
+ await asyncio.wait_for(handle, timeout=5)
+ for _ in range(100):
+ if handle._proc.poll() is not None:
+ break
+ await asyncio.sleep(0.05)
+ self.assertIsNotNone(handle._proc.poll())
+ handle._job = 999
+ try:
+ with mock.patch.object(bash_module, "_IS_POSIX", False):
+ with mock.patch.object(bash_module._winjob, "terminate", return_value=False):
+ with mock.patch.object(bash_module._winjob, "close"):
+ with mock.patch.object(
+ bash_module, "_taskkill_tree", return_value=False
+ ):
+ self.assertFalse(handle._reap_group())
+ self.assertIsNone(handle._job)
+ finally:
+ handle._job = None
+
+ def test_darwin_start_id_uses_absolute_ps(self):
+ completed = mock.Mock(stdout="Mon Jan 1 00:00:00 2026\n")
+ with mock.patch.object(bash_module.sys, "platform", "darwin"):
+ with mock.patch("builtins.open", side_effect=OSError):
+ with mock.patch.object(bash_module.subprocess, "run", return_value=completed) as run:
+ self.assertEqual(
+ bash_module._process_start_id(1234), "ps:Mon Jan 1 00:00:00 2026"
+ )
+ self.assertEqual(run.call_args.args[0][0], "/bin/ps")
+
+ async def test_undelivered_kill_leaves_journal_record_active(self):
+ if not bash_module._IS_POSIX:
+ self.skipTest("POSIX signal-delivery semantics")
+ with tempfile.TemporaryDirectory() as tmp:
+ journal = os.path.join(tmp, "journal.jsonl")
+ with mock.patch.dict(
+ os.environ,
+ {
+ "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL": journal,
+ "PRIME_AGENT_KERNEL_OWNER_PID": str(os.getpid()),
+ },
+ ):
+ handle = bash("sleep 30")
+ try:
+ records = await _poll_journal(journal, count=1)
+ self.assertTrue(records[-1]["active"])
+ with mock.patch.object(bash_module, "_signal_group", return_value=False):
+ bash_module._kill_live_handles()
+ await asyncio.sleep(0.2) # give any (wrong) inactive write time to land
+ records = await _poll_journal(journal, count=1)
+ self.assertEqual(len(records), 1)
+ self.assertTrue(records[-1]["active"])
+ finally:
+ handle.kill(signal.SIGKILL)
+ await asyncio.wait_for(handle, timeout=5)
+
+ async def test_signal_group_reports_delivery(self):
+ if not bash_module._IS_POSIX:
+ self.skipTest("POSIX signal-delivery semantics")
+ with mock.patch.object(bash_module.os, "killpg", side_effect=ProcessLookupError):
+ self.assertTrue(bash_module._signal_group(1234567, signal.SIGKILL))
+ with mock.patch.object(bash_module.os, "killpg", side_effect=PermissionError):
+ self.assertFalse(bash_module._signal_group(1234567, signal.SIGKILL))
+ with mock.patch.object(bash_module.os, "killpg", side_effect=OSError):
+ self.assertFalse(bash_module._signal_group(1234567, signal.SIGKILL))
+
+ async def test_journal_configured_but_unwritable_kills_child_and_raises(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ marker = os.path.join(tmp, "marker")
+ pids: list[int] = []
+ real_popen = subprocess.Popen
+
+ def capturing_popen(*args, **kwargs):
+ proc = real_popen(*args, **kwargs)
+ pids.append(proc.pid)
+ return proc
+
+ with mock.patch.dict(
+ os.environ,
+ {
+ "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL": tmp, # a directory: open fails
+ "PRIME_AGENT_KERNEL_OWNER_PID": str(os.getpid()),
+ },
+ ):
+ with mock.patch.object(bash_module.subprocess, "Popen", capturing_popen):
+ with self.assertRaises(RuntimeError):
+ bash(f"touch {marker}")
+ await _poll_group_dead(pids[0])
+ await asyncio.sleep(0.2)
+ self.assertFalse(os.path.exists(marker))
+ with bash_module._live_lock:
+ self.assertFalse(bash_module._live_handles)
+
+ async def test_journal_bad_owner_pid_rejects(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ journal = os.path.join(tmp, "journal.jsonl")
+ with mock.patch.dict(
+ os.environ,
+ {
+ "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL": journal,
+ "PRIME_AGENT_KERNEL_OWNER_PID": "notanint",
+ },
+ ):
+ with self.assertRaises(RuntimeError):
+ bash("echo hi")
+
+ async def test_missing_start_id_rejects_when_configured(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ journal = os.path.join(tmp, "journal.jsonl")
+ with mock.patch.dict(
+ os.environ,
+ {
+ "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL": journal,
+ "PRIME_AGENT_KERNEL_OWNER_PID": str(os.getpid()),
+ },
+ ):
+ with mock.patch.object(bash_module, "_process_start_id", return_value=None):
+ with self.assertRaises(RuntimeError):
+ bash("sleep 30")
+
+ async def test_journal_short_write_rejects_when_configured(self):
+ # A partial os.write would leave a truncated JSON line the host
+ # discards; enrollment must treat it as failure.
+ with tempfile.TemporaryDirectory() as tmp:
+ journal = os.path.join(tmp, "journal.jsonl")
+
+ def short_write(fd, data):
+ return 0 # no progress
+
+ with mock.patch.dict(
+ os.environ,
+ {
+ "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL": journal,
+ "PRIME_AGENT_KERNEL_OWNER_PID": str(os.getpid()),
+ },
+ ):
+ with mock.patch.object(bash_module.os, "write", short_write):
+ self.assertFalse(bash_module._record_journal(os.getpid(), active=False))
+
+ async def test_journal_partial_writes_complete_the_record(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ journal = os.path.join(tmp, "journal.jsonl")
+ real_write = os.write
+
+ def partial_write(fd, data):
+ # One byte at a time: the loop must still write the full record.
+ return real_write(fd, bytes(data)[:1])
+
+ with mock.patch.dict(
+ os.environ,
+ {
+ "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL": journal,
+ "PRIME_AGENT_KERNEL_OWNER_PID": str(os.getpid()),
+ },
+ ):
+ with mock.patch.object(bash_module.os, "write", partial_write):
+ self.assertTrue(bash_module._record_journal(os.getpid(), active=False))
+ with open(journal) as f:
+ record = json.loads(f.read())
+ self.assertEqual(record["pid"], os.getpid())
+ self.assertFalse(record["active"])
+
+ async def test_unconfigured_journal_stays_permissive(self):
+ # Permissiveness is about configuration, not start-id availability.
+ with mock.patch.object(bash_module, "_process_start_id", return_value=None):
+ result = await bash("echo ok")
+ self.assertEqual(result.exit_code, 0)
+ self.assertIn("ok", result.output)
+
+
+async def _poll_group_dead(pgid: int, timeout: float = 5.0) -> None:
+ deadline = asyncio.get_running_loop().time() + timeout
+ while asyncio.get_running_loop().time() < deadline:
+ try:
+ os.killpg(pgid, 0)
+ except ProcessLookupError:
+ return
+ except PermissionError:
+ pass # transient teardown state on macOS
+ await asyncio.sleep(0.05)
+ raise AssertionError(f"process group {pgid} still alive after {timeout}s")
+
+
+async def _poll_journal(path: str, count: int, timeout: float = 2.0) -> list[dict]:
+ deadline = asyncio.get_running_loop().time() + timeout
+ records: list[dict] = []
+ while asyncio.get_running_loop().time() < deadline:
+ with open(path) as f:
+ records = [json.loads(line) for line in f if line.strip()]
+ if len(records) >= count:
+ return records
+ await asyncio.sleep(0.05)
+ return records
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/prime-agent-runtime/test/test_winjob.py b/prime-agent-runtime/test/test_winjob.py
new file mode 100644
index 0000000000..c42cc48aa5
--- /dev/null
+++ b/prime-agent-runtime/test/test_winjob.py
@@ -0,0 +1,490 @@
+# All tests mock the kernel32 boundary: CI is Ubuntu-only, so the real Win32
+# calls are never exercised here (manual Windows runs only).
+from __future__ import annotations
+
+import ctypes
+import ctypes.wintypes as wintypes
+import os
+import subprocess
+import sys
+import threading
+import types
+import unittest
+from unittest import mock
+
+from rlm import _winjob
+
+
+class WinJobTest(unittest.TestCase):
+ def setUp(self):
+ self.k32 = mock.Mock()
+ patcher = mock.patch.object(_winjob, "_kernel32", return_value=self.k32)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def test_create_job_sets_kill_on_close(self):
+ self.k32.CreateJobObjectW.return_value = 314
+ self.k32.SetInformationJobObject.return_value = 1
+
+ self.assertEqual(_winjob.create_job(), 314)
+ self.k32.CreateJobObjectW.assert_called_once_with(None, None)
+ args = self.k32.SetInformationJobObject.call_args.args
+ self.assertEqual(args[0], 314)
+ self.assertEqual(args[1], 9) # JobObjectExtendedLimitInformation
+ info = ctypes.cast(
+ args[2], ctypes.POINTER(_winjob._JOBOBJECT_EXTENDED_LIMIT_INFORMATION)
+ ).contents
+ self.assertEqual(
+ info.BasicLimitInformation.LimitFlags, _winjob.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ )
+ self.assertEqual(info.BasicLimitInformation.LimitFlags, 0x2000)
+ self.assertEqual(args[3], ctypes.sizeof(_winjob._JOBOBJECT_EXTENDED_LIMIT_INFORMATION))
+ self.k32.CloseHandle.assert_not_called()
+
+ def test_create_job_failure_paths(self):
+ self.k32.CreateJobObjectW.return_value = None
+ self.assertIsNone(_winjob.create_job())
+
+ self.k32.CreateJobObjectW.return_value = 314
+ self.k32.SetInformationJobObject.return_value = 0
+ self.assertIsNone(_winjob.create_job())
+ self.k32.CloseHandle.assert_called_once_with(314)
+
+ def _wire_spawn_mocks(self, init_second=1, update=(1, 1), create_process=1,
+ create_pipe=1, create_file=103, set_handle=(1, 1),
+ sizing_writes=True):
+ # Happy-path plumbing for spawn_in_job; failure tests flip one return.
+ captured = {}
+
+ def create_pipe_fn(read_ptr, write_ptr, attrs, size):
+ if not create_pipe:
+ return 0
+ ctypes.cast(read_ptr, ctypes.POINTER(wintypes.HANDLE)).contents.value = 101
+ ctypes.cast(write_ptr, ctypes.POINTER(wintypes.HANDLE)).contents.value = 102
+ return 1
+
+ def init_attr_list(buffer, count, flags, size_ptr):
+ captured.setdefault("init_calls", []).append((buffer, count))
+ if buffer is None:
+ # Sizing call: FALSE (ERROR_INSUFFICIENT_BUFFER) after writing the size.
+ if sizing_writes:
+ ctypes.cast(size_ptr, ctypes.POINTER(ctypes.c_size_t)).contents.value = 48
+ return 0
+ return init_second
+
+ def update_attr(attr_list, flags, attribute, value_ptr, size, prev, ret):
+ handles = ctypes.cast(value_ptr, ctypes.POINTER(wintypes.HANDLE))
+ count = size // ctypes.sizeof(wintypes.HANDLE)
+ calls = captured.setdefault("updates", [])
+ calls.append((attribute, tuple(handles[i] for i in range(count)), size))
+ return update[len(calls) - 1]
+
+ def create_process_w(app, cmdline, pattr, tattr, inherit, flags, env, cwd, si_ptr, pi_ptr):
+ startup = ctypes.cast(si_ptr, ctypes.POINTER(_winjob._STARTUPINFOEXW)).contents
+ captured["create"] = {
+ "app": app, "cmdline": cmdline.value, "inherit": inherit, "flags": flags,
+ "env": env[:], "cwd": cwd, "cb": startup.StartupInfo.cb,
+ "dwFlags": startup.StartupInfo.dwFlags,
+ "hStdInput": startup.StartupInfo.hStdInput,
+ "hStdOutput": startup.StartupInfo.hStdOutput,
+ "hStdError": startup.StartupInfo.hStdError,
+ "lpAttributeList": startup.lpAttributeList,
+ }
+ info = ctypes.cast(pi_ptr, ctypes.POINTER(_winjob._PROCESS_INFORMATION)).contents
+ info.hProcess, info.hThread, info.dwProcessId = 201, 202, 4242
+ return create_process
+
+ self.k32.CreatePipe.side_effect = create_pipe_fn
+ self.k32.SetHandleInformation.side_effect = list(set_handle)
+ self.k32.CreateFileW.return_value = create_file
+ self.k32.InitializeProcThreadAttributeList.side_effect = init_attr_list
+ self.k32.UpdateProcThreadAttribute.side_effect = update_attr
+ self.k32.CreateProcessW.side_effect = create_process_w
+ return captured
+
+ def test_spawn_in_job_atomic_contract(self):
+ captured = self._wire_spawn_mocks()
+ argv = ["C:/shell.exe", "-c", "echo hi"]
+ env = {"A": "1", "B": "two"}
+ # _open_reader stays a mocked seam here; the fake-msvcrt tests exercise it directly.
+ with mock.patch.object(_winjob, "_open_reader") as open_reader:
+ proc = _winjob.spawn_in_job(314, argv, "C:/work", env)
+
+ # JOB_LIST carries the job; HANDLE_LIST caps inheritance to the write and NUL handles.
+ self.assertEqual(captured["updates"], [
+ (0x2000D, (314,), ctypes.sizeof(wintypes.HANDLE)),
+ (0x20002, (102, 103), 2 * ctypes.sizeof(wintypes.HANDLE)),
+ ])
+ # Both init calls (sizing + real) reserve two attribute slots.
+ self.assertEqual([count for _, count in captured["init_calls"]], [2, 2])
+ self.assertIsNone(captured["init_calls"][0][0])
+ self.assertIsNotNone(captured["init_calls"][1][0])
+
+ create = captured["create"]
+ self.assertIsNone(create["app"])
+ self.assertEqual(create["cmdline"], subprocess.list2cmdline(argv))
+ self.assertEqual(create["flags"], 0x00080000 | 0x4 | 0x400)
+ self.assertEqual(create["env"], "A=1\0B=two\0\0") # double-NUL terminated block
+ self.assertEqual(create["cwd"], "C:/work")
+ self.assertEqual(create["cb"], ctypes.sizeof(_winjob._STARTUPINFOEXW))
+ self.assertEqual(create["dwFlags"] & 0x100, 0x100) # STARTF_USESTDHANDLES
+ self.assertEqual(create["hStdInput"], 103)
+ self.assertEqual(create["hStdOutput"], 102)
+ self.assertEqual(create["hStdError"], 102)
+ self.assertIsNotNone(create["lpAttributeList"])
+
+ inherit_calls = [c.args for c in self.k32.SetHandleInformation.call_args_list]
+ self.assertEqual(inherit_calls, [(102, 0x1, 0x1), (103, 0x1, 0x1)])
+ self.k32.CreateFileW.assert_called_once_with("NUL", 0x80000000, 0x3, None, 3, 0, None)
+ self.k32.DeleteProcThreadAttributeList.assert_called_once()
+ closed = sorted(c.args[0] for c in self.k32.CloseHandle.call_args_list)
+ self.assertEqual(closed, [102, 103]) # parent copies only; never 101/201/202
+ open_reader.assert_called_once_with(101)
+ self.assertEqual(proc.pid, 4242)
+ self.assertIs(proc.stdout, open_reader.return_value)
+
+ def test_spawn_in_job_cleanup_on_failures(self):
+ scenarios = (
+ ({"create_pipe": 0}, [], False),
+ ({"create_file": _winjob._INVALID_HANDLE_VALUE}, [101, 102], False),
+ ({"set_handle": (0,)}, [101, 102], False), # write-handle inherit fails
+ ({"set_handle": (1, 0)}, [101, 102, 103], False), # NUL inherit fails
+ ({"sizing_writes": False}, [101, 102, 103], False), # sizing wrote nothing
+ ({"init_second": 0}, [101, 102, 103], False),
+ ({"update": (0,)}, [101, 102, 103], True),
+ ({"update": (1, 0)}, [101, 102, 103], True), # HANDLE_LIST update fails
+ ({"create_process": 0}, [101, 102, 103], True),
+ )
+ for kwargs, expected_closed, delete_called in scenarios:
+ with self.subTest(**kwargs):
+ self.k32.reset_mock(side_effect=True, return_value=True)
+ self._wire_spawn_mocks(**kwargs)
+ with mock.patch.object(_winjob, "_open_reader") as open_reader:
+ with self.assertRaises(OSError):
+ _winjob.spawn_in_job(314, ["sh"], "C:/work", {})
+ open_reader.assert_not_called()
+ closed = sorted(c.args[0] for c in self.k32.CloseHandle.call_args_list)
+ self.assertEqual(closed, expected_closed) # never the job handle
+ self.assertEqual(
+ self.k32.DeleteProcThreadAttributeList.called, delete_called
+ )
+ if not kwargs.get("create_pipe", 1):
+ self.k32.CreateFileW.assert_not_called() # nothing else touched
+
+ def test_spawn_in_job_sorts_environment_block(self):
+ captured = self._wire_spawn_mocks()
+ env = {"b": "2", "PATH": "p", "A": "1"} # deliberately unsorted
+ with mock.patch.object(_winjob, "_open_reader"):
+ _winjob.spawn_in_job(314, ["sh"], "C:/work", env)
+ # Sorted case-insensitively by name per CreateProcessW docs, double-NUL end.
+ self.assertEqual(captured["create"]["env"], "A=1\0b=2\0PATH=p\0\0")
+
+ def test_spawn_in_job_open_reader_failure_closes_process_handles(self):
+ self._wire_spawn_mocks()
+ with mock.patch.object(_winjob, "_open_reader", side_effect=OSError("bad handle")):
+ with self.assertRaises(OSError):
+ _winjob.spawn_in_job(314, ["sh"], "C:/work", {})
+ # 101 is absent: ownership moved to the mocked _open_reader, which does not consume it.
+ closed = sorted(c.args[0] for c in self.k32.CloseHandle.call_args_list)
+ self.assertEqual(closed, [102, 103, 201, 202])
+
+ def test_open_reader_osfhandle_failure_closes_handle(self):
+ self._wire_spawn_mocks()
+ fake = types.SimpleNamespace(open_osfhandle=mock.Mock(side_effect=OSError("bad handle")))
+ with mock.patch.dict(sys.modules, {"msvcrt": fake}):
+ with self.assertRaises(OSError):
+ _winjob.spawn_in_job(314, ["sh"], "C:/work", {})
+ fake.open_osfhandle.assert_called_once_with(101, os.O_RDONLY)
+ closed = [c.args[0] for c in self.k32.CloseHandle.call_args_list]
+ # _open_reader consumed the raw handle exactly once; never the caller.
+ self.assertEqual(closed.count(101), 1)
+ self.assertEqual(sorted(closed), [101, 102, 103, 201, 202])
+
+ def test_open_reader_fdopen_failure_closes_fd_not_handle(self):
+ self._wire_spawn_mocks()
+ fd = os.open(os.devnull, os.O_RDONLY)
+ fake = types.SimpleNamespace(open_osfhandle=mock.Mock(return_value=fd))
+ with mock.patch.dict(sys.modules, {"msvcrt": fake}):
+ with mock.patch.object(_winjob.os, "fdopen", side_effect=OSError("boom")):
+ with self.assertRaises(OSError):
+ _winjob.spawn_in_job(314, ["sh"], "C:/work", {})
+ fake.open_osfhandle.assert_called_once_with(101, os.O_RDONLY)
+ # The CRT fd owns the handle after open_osfhandle: fd closed (EBADF), never CloseHandle.
+ with self.assertRaises(OSError):
+ os.fstat(fd)
+ closed = sorted(c.args[0] for c in self.k32.CloseHandle.call_args_list)
+ self.assertEqual(closed, [102, 103, 201, 202])
+
+ def test_win64_abi_struct_layout(self):
+ # Fixed-width fields pin the Win64 layout on every host (LP64 DWORD would be vacuous).
+ self.assertEqual(ctypes.sizeof(_winjob._STARTUPINFOEXW), 112)
+ self.assertEqual(ctypes.sizeof(_winjob._PROCESS_INFORMATION), 24)
+ self.assertEqual(_winjob._STARTUPINFOEXW.lpAttributeList.offset, 104)
+ startup = _winjob._STARTUPINFOW
+ self.assertEqual(startup.hStdInput.offset, 80)
+ self.assertEqual(startup.hStdOutput.offset, 88)
+ self.assertEqual(startup.hStdError.offset, 96)
+
+ def test_job_process_resume(self):
+ proc = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ self.k32.ResumeThread.return_value = 1
+ self.assertTrue(proc.resume())
+ self.k32.ResumeThread.assert_called_once_with(202)
+ self.k32.CloseHandle.assert_called_once_with(202)
+
+ self.k32.reset_mock()
+ failed = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ self.k32.ResumeThread.return_value = 0xFFFFFFFF # (DWORD)-1
+ self.assertFalse(failed.resume())
+ # The thread handle stays open so the abort path still owns the child.
+ self.k32.CloseHandle.assert_not_called()
+
+ def test_job_process_poll_wait_kill(self):
+ def write_exit(handle, code_ptr):
+ ctypes.cast(code_ptr, ctypes.POINTER(wintypes.DWORD)).contents.value = 7
+ return 1
+
+ self.k32.GetExitCodeProcess.side_effect = write_exit
+
+ proc = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ self.k32.WaitForSingleObject.return_value = 0x102 # WAIT_TIMEOUT
+ self.assertIsNone(proc.poll())
+ self.k32.WaitForSingleObject.assert_called_once_with(201, 0)
+ self.k32.WaitForSingleObject.return_value = 0 # WAIT_OBJECT_0
+ self.assertEqual(proc.poll(), 7)
+ self.assertEqual(proc.poll(), 7) # second poll after signal: cached
+ # Caching happens exactly once; the process handle stays open for close().
+ self.assertEqual(self.k32.GetExitCodeProcess.call_count, 1)
+ closed = sorted(c.args[0] for c in self.k32.CloseHandle.call_args_list)
+ self.assertEqual(closed, [202])
+ proc.close()
+ closed = sorted(c.args[0] for c in self.k32.CloseHandle.call_args_list)
+ self.assertEqual(closed, [201, 202])
+ proc.close() # idempotent: no second CloseHandle
+ self.assertEqual(len(self.k32.CloseHandle.call_args_list), 2)
+ self.k32.reset_mock(side_effect=False)
+ self.assertEqual(proc.poll(), 7) # cached: no further kernel32 calls
+ self.assertEqual(proc.wait(), 7)
+ self.k32.WaitForSingleObject.assert_not_called()
+ proc.kill() # exit cached: killing is a no-op
+ self.k32.TerminateProcess.assert_not_called()
+
+ waiter = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ self.k32.WaitForSingleObject.return_value = 0x102
+ with self.assertRaises(subprocess.TimeoutExpired):
+ waiter.wait(timeout=1)
+ self.k32.WaitForSingleObject.assert_called_once_with(201, 1000)
+ self.k32.WaitForSingleObject.reset_mock()
+ self.k32.WaitForSingleObject.return_value = 0
+ self.assertEqual(waiter.wait(), 7)
+ self.k32.WaitForSingleObject.assert_called_once_with(201, 0xFFFFFFFF) # INFINITE
+
+ killer = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ self.k32.TerminateProcess.return_value = 1
+ killer.kill()
+ self.k32.TerminateProcess.assert_called_once_with(201, 1)
+
+ def test_job_process_poll_wait_failed_raises(self):
+ # WAIT_FAILED must surface, never masquerade as "still running".
+ proc = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ self.k32.WaitForSingleObject.return_value = 0xFFFFFFFF # WAIT_FAILED
+ with self.assertRaises(OSError):
+ proc.poll()
+ self.k32.CloseHandle.assert_not_called()
+
+ def test_job_process_exit_code_failure_raises_and_allows_retry(self):
+ proc = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ self.k32.WaitForSingleObject.return_value = 0 # WAIT_OBJECT_0
+ self.k32.GetExitCodeProcess.return_value = 0
+ with self.assertRaises(OSError):
+ proc.poll() # must not cache a false exit 0
+ self.k32.CloseHandle.assert_not_called() # handles stay open for retry
+
+ def write_exit(handle, code_ptr):
+ ctypes.cast(code_ptr, ctypes.POINTER(wintypes.DWORD)).contents.value = 5
+ return 1
+
+ self.k32.GetExitCodeProcess.side_effect = write_exit
+ self.assertEqual(proc.poll(), 5)
+
+ def test_job_process_wait_failed_returns_concurrently_cached_code(self):
+ proc = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+
+ def cache_then_fail(handle, millis):
+ # Simulates another thread caching and closing during the in-flight wait.
+ with proc._lock:
+ proc._exit_code, proc._hprocess, proc._hthread = 9, None, None
+ return 0xFFFFFFFF # WAIT_FAILED
+
+ self.k32.WaitForSingleObject.side_effect = cache_then_fail
+ self.assertEqual(proc.wait(timeout=5), 9)
+ self.k32.GetExitCodeProcess.assert_not_called()
+
+ def test_job_process_close_deferred_while_wait_in_flight(self):
+ # UB guard: a poll() cache during an in-flight wait() defers the close to the waiter.
+ proc = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ entered, release = threading.Event(), threading.Event()
+
+ def wfso(handle, millis):
+ if millis == 0:
+ return 0 # WAIT_OBJECT_0 for the main thread's poll()
+ entered.set()
+ assert release.wait(timeout=5)
+ return 0
+
+ def write_exit(handle, code_ptr):
+ ctypes.cast(code_ptr, ctypes.POINTER(wintypes.DWORD)).contents.value = 7
+ return 1
+
+ self.k32.WaitForSingleObject.side_effect = wfso
+ self.k32.GetExitCodeProcess.side_effect = write_exit
+ results: list[int] = []
+ waiter = threading.Thread(target=lambda: results.append(proc.wait()), daemon=True)
+ waiter.start()
+ try:
+ self.assertTrue(entered.wait(timeout=5))
+ self.assertEqual(proc.poll(), 7) # caches while the wait is blocked
+ proc.close() # close request while a waiter is blocked: must defer
+ closed = [c.args[0] for c in self.k32.CloseHandle.call_args_list]
+ self.assertNotIn(201, closed) # deferred: the waiter still uses it
+ self.assertIn(202, closed) # the thread handle may close at once
+ finally:
+ release.set()
+ waiter.join(timeout=5)
+ self.assertFalse(waiter.is_alive())
+ self.assertEqual(results, [7])
+ closed = [c.args[0] for c in self.k32.CloseHandle.call_args_list]
+ self.assertEqual(closed.count(201), 1) # the last waiter closed it
+
+ def test_job_process_close_during_wait_caches_exit_before_deferred_close(self):
+ # Reviewer schedule: close() during a blocked wait() must not release the
+ # handle before the signaled wait caches the exit code.
+ proc = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ entered, release = threading.Event(), threading.Event()
+ seen_handles: list[object] = []
+
+ def wfso(handle, millis):
+ entered.set()
+ assert release.wait(timeout=5)
+ return 0 # WAIT_OBJECT_0
+
+ def write_exit(handle, code_ptr):
+ seen_handles.append(handle)
+ ctypes.cast(code_ptr, ctypes.POINTER(wintypes.DWORD)).contents.value = 7
+ return 1
+
+ self.k32.WaitForSingleObject.side_effect = wfso
+ self.k32.GetExitCodeProcess.side_effect = write_exit
+ results: list[int] = []
+ waiter = threading.Thread(target=lambda: results.append(proc.wait()), daemon=True)
+ waiter.start()
+ try:
+ self.assertTrue(entered.wait(timeout=5))
+ proc.close()
+ self.k32.CloseHandle.assert_not_called() # deferred: waiter in flight
+ finally:
+ release.set()
+ waiter.join(timeout=5)
+ self.assertFalse(waiter.is_alive())
+ self.assertEqual(results, [7])
+ self.assertEqual(seen_handles, [201]) # never GetExitCodeProcess(None)
+ closed = [c.args[0] for c in self.k32.CloseHandle.call_args_list]
+ self.assertEqual(closed, [202, 201]) # hThread at cache, then the deferred close
+
+ def test_job_process_wait_invalid_timeout_does_not_leak_waiter(self):
+ # int(nan/inf) raising after waiter registration would leak _waiters and the handle.
+ proc = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ for bad in (float("nan"), float("inf")):
+ with self.assertRaises((ValueError, OverflowError)):
+ proc.wait(timeout=bad)
+ self.assertEqual(proc._waiters, 0)
+ self.k32.WaitForSingleObject.assert_not_called()
+
+ def write_exit(handle, code_ptr):
+ ctypes.cast(code_ptr, ctypes.POINTER(wintypes.DWORD)).contents.value = 3
+ return 1
+
+ self.k32.WaitForSingleObject.return_value = 0 # WAIT_OBJECT_0
+ self.k32.GetExitCodeProcess.side_effect = write_exit
+ self.assertEqual(proc.poll(), 3) # caches normally afterwards
+ proc.close()
+ closed = sorted(c.args[0] for c in self.k32.CloseHandle.call_args_list)
+ self.assertEqual(closed, [201, 202])
+
+ def test_job_process_wait_retains_handle_until_close(self):
+ # PID-reuse guard: exit observation must not release the process handle.
+ def write_exit(handle, code_ptr):
+ ctypes.cast(code_ptr, ctypes.POINTER(wintypes.DWORD)).contents.value = 7
+ return 1
+
+ proc = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ self.k32.WaitForSingleObject.return_value = 0 # WAIT_OBJECT_0
+ self.k32.GetExitCodeProcess.side_effect = write_exit
+ self.assertEqual(proc.wait(), 7)
+ closed = sorted(c.args[0] for c in self.k32.CloseHandle.call_args_list)
+ self.assertEqual(closed, [202]) # 201 stays open until close()
+ proc.close()
+ closed = sorted(c.args[0] for c in self.k32.CloseHandle.call_args_list)
+ self.assertEqual(closed, [201, 202])
+ self.assertEqual(len(self.k32.CloseHandle.call_args_list), 2)
+
+ def test_job_process_close_before_exit_cached_is_safe(self):
+ proc = _winjob.JobProcess(201, 202, 4242, mock.Mock())
+ proc.close()
+ self.k32.CloseHandle.assert_called_once_with(201)
+ proc.close() # idempotent
+ self.k32.CloseHandle.assert_called_once_with(201)
+ proc.kill() # closed without exit: killing is a no-op
+ self.k32.TerminateProcess.assert_not_called()
+ with self.assertRaises(OSError):
+ proc.poll()
+
+ def test_is_empty_maps_active_processes(self):
+ def query(job, info_class, buffer, size, returned):
+ info = ctypes.cast(
+ buffer, ctypes.POINTER(_winjob._JOBOBJECT_BASIC_ACCOUNTING_INFORMATION)
+ ).contents
+ info.ActiveProcesses = self.active
+ self.assertEqual(job, 314)
+ self.assertEqual(info_class, 1) # JobObjectBasicAccountingInformation
+ return 1
+
+ self.k32.QueryInformationJobObject.side_effect = query
+ self.active = 0
+ self.assertTrue(_winjob.is_empty(314))
+ self.active = 2
+ self.assertFalse(_winjob.is_empty(314))
+
+ self.k32.QueryInformationJobObject.side_effect = None
+ self.k32.QueryInformationJobObject.return_value = 0
+ self.assertIsNone(_winjob.is_empty(314))
+
+ def test_terminate_and_close(self):
+ self.k32.TerminateJobObject.return_value = 1
+ self.assertTrue(_winjob.terminate(314))
+ self.k32.TerminateJobObject.assert_called_once_with(314, 1)
+
+ self.k32.TerminateJobObject.return_value = 0
+ self.assertFalse(_winjob.terminate(314, exit_code=9))
+ self.assertEqual(self.k32.TerminateJobObject.call_args.args, (314, 9))
+
+ _winjob.close(314)
+ self.k32.CloseHandle.assert_called_once_with(314)
+
+
+class WinJobPosixDegradationTest(unittest.TestCase):
+ def test_every_function_degrades_without_kernel32(self):
+ # Unmocked on POSIX: ctypes has no WinDLL, so _kernel32 raises
+ # AttributeError and every public function degrades.
+ if hasattr(ctypes, "WinDLL"):
+ self.skipTest("Windows host: kernel32 exists")
+ self.assertIsNone(_winjob.create_job())
+ self.assertIsNone(_winjob.is_empty(1))
+ with self.assertRaises(OSError):
+ _winjob.spawn_in_job(1, ["sh"], "/", {})
+ self.assertFalse(_winjob.terminate(1))
+ _winjob.close(1) # must not raise
+
+
+if __name__ == "__main__":
+ unittest.main()