Skip to content

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

Rust

fix: scope shutdown to its own daemon tree (#3601)

Sebastian Müller3407a54d8070
diff --git a/crates/pa-cli/src/daemon_discovery/kill.rs b/crates/pa-cli/src/daemon_discovery/kill.rs
index 1ac957e50d..24912f7ee9 100644
--- a/crates/pa-cli/src/daemon_discovery/kill.rs
+++ b/crates/pa-cli/src/daemon_discovery/kill.rs
@@ -120,7 +120,9 @@ pub(super) fn stop_tracked_process(pid: u32, expected_start_id: Option<&str>) ->
/// the invocation's state root until the set quiets down or proves stuck;
/// report the survivors as failures. The sweep re-scans with the same root,
/// so daemons in any other root — or on the never-touch list — are never
-/// candidates.
+/// candidates, and worker sockets never appear in the census (a supervisor's
+/// workers stop through their tracked descriptors; deliberate TS divergence:
+/// TS's sweep killed worker listeners too).
pub(super) fn terminate_verified_residuals(
root: &DaemonStateRoot,
stopped: &mut Vec<(String, String)>,
@@ -245,7 +247,7 @@ mod tests {
fn fixture_root(dir: &Path) -> DaemonStateRoot {
DaemonStateRoot {
agent_dir: dir.join("agent"),
- socket_dir: dir.join("agent").join("sockets"),
+ socket_dir: Some(dir.join("agent").join("sockets")),
default_socket_path: dir.join("agent").join("sockets").join("daemon.sock"),
}
}
@@ -270,7 +272,7 @@ mod tests {
for dir in ["/tmp/mission-tmp/prime-agent-1000", "/tmp/prime-agent-1000"] {
let root = DaemonStateRoot {
agent_dir: PathBuf::from(dir),
- socket_dir: PathBuf::from(dir),
+ socket_dir: Some(PathBuf::from(dir)),
default_socket_path: PathBuf::from(dir).join("daemon.sock"),
};
let mut stopped: Vec<(String, String)> = Vec::new();
diff --git a/crates/pa-cli/src/daemon_discovery/mod.rs b/crates/pa-cli/src/daemon_discovery/mod.rs
index ce9d823730..3736f10e22 100644
--- a/crates/pa-cli/src/daemon_discovery/mod.rs
+++ b/crates/pa-cli/src/daemon_discovery/mod.rs
@@ -29,12 +29,17 @@ pub(crate) struct DiscoveredDaemonProcess {
pub uptime_seconds: Option<u64>,
}
-/// The state root an invocation reads: the agent dir and the default socket
-/// dir, both following HOME/TMPDIR/agent-dir overrides.
+/// The state root an invocation reads: the agent dir and the daemon socket
+/// it points at (flag > env > default). Deliberate TS divergence: TS pins
+/// the root to the shared default socket dir regardless of the pin, so an
+/// isolated daemon's `shutdown` also stops the shared daemon.
#[derive(Debug, Clone)]
pub(crate) struct DaemonStateRoot {
pub agent_dir: PathBuf,
- pub socket_dir: PathBuf,
+ /// The product-default socket dir, `Some` only when the resolved
+ /// socket is the product default. A root pinned elsewhere owns its
+ /// socket, never the pinned socket's directory.
+ pub socket_dir: Option<PathBuf>,
pub default_socket_path: PathBuf,
}
@@ -105,16 +110,27 @@ pub(crate) struct DaemonInfo {
pub has_tracked_workers: Option<bool>,
}
+/// The root this invocation reads, from the same socket resolution every
+/// other mode uses (flag > env > default). The root always owns the
+/// resolved socket and the agent dir; the product-default socket dir joins
+/// the root only when the resolved socket IS the product default (an
+/// explicit pin to the default included) — a pinned root owns its socket,
+/// never the pinned socket's directory (two isolated daemons in one shared
+/// directory would otherwise stop each other).
pub(crate) fn current_state_root() -> DaemonStateRoot {
+ let default_socket_path = config::resolve_daemon_socket_path(None);
+ let socket_dir = (default_socket_path == pa_daemon::platform::default_daemon_socket_path())
+ .then_some(pa_daemon::platform::socket_dir());
DaemonStateRoot {
agent_dir: config::get_agent_dir(),
- socket_dir: pa_daemon::platform::socket_dir(),
- default_socket_path: pa_daemon::platform::default_daemon_socket_path(),
+ socket_dir,
+ default_socket_path,
}
}
-/// A socket belongs to the root when it is the default path, sits in the socket
-/// dir, or anywhere inside the agent dir (TS ownership registry not ported).
+/// A socket belongs to the root when it is the resolved default path, sits
+/// in the product-default socket dir (a pinned root has none), or anywhere
+/// inside the agent dir (TS ownership registry not ported).
fn state_root_matches(root: &DaemonStateRoot, socket_path: &Path) -> bool {
if is_never_touch(socket_path) {
return false;
@@ -128,7 +144,11 @@ fn state_root_matches(root: &DaemonStateRoot, socket_path: &Path) -> bool {
}
#[cfg(not(windows))]
{
- if socket_path == root.default_socket_path || socket_path.parent() == Some(&root.socket_dir)
+ if socket_path == root.default_socket_path
+ || root
+ .socket_dir
+ .as_ref()
+ .is_some_and(|dir| socket_path.parent() == Some(dir))
{
return true;
}
@@ -148,7 +168,8 @@ fn inside(directory: Option<&Path>, parent: &Path) -> bool {
}
/// Worker sockets: `worker-*.sock` in the given socket dir (never the
-/// supervisor's own). The dir comes from the state root, never the ambient env.
+/// supervisor's own). Callers pass the actual worker directory, which need
+/// not be owned by the discovery root.
pub(crate) fn is_worker_socket_path(socket_path: &Path, socket_dir: &Path) -> bool {
if socket_path.parent() != Some(socket_dir) {
return false;
@@ -163,9 +184,19 @@ pub(crate) fn is_worker_socket_path(socket_path: &Path, socket_dir: &Path) -> bo
}
/// Listening daemons in this state root. The census is filtered to the root
-/// inside the scan: a scan from one root can never see another root's daemon.
+/// inside the scan: a scan from one root can never see another root's
+/// daemon. Worker sockets never appear: a worker belongs to its supervisor
+/// and stops through its tracked descriptors, so every consumer — discovery,
+/// the shutdown actions, and the `--force` residual sweep — acts on
+/// supervisors only. The worker directory is independent of the optional
+/// discovery directory: an agent-dir override can contain the shared worker
+/// directory even when the root is pinned elsewhere.
pub(crate) fn scan_listening_daemons(root: &DaemonStateRoot) -> Vec<DiscoveredDaemonProcess> {
+ let worker_socket_dir = pa_daemon::platform::socket_dir();
scan::scan_all_listening_daemons(config::APP_NAME, root)
+ .into_iter()
+ .filter(|daemon| !is_worker_socket_path(&daemon.socket_path, &worker_socket_dir))
+ .collect()
}
/// True when the pid still listens on exactly this socket: a fresh scan against
@@ -180,10 +211,15 @@ pub(crate) fn is_daemon_process_listening(
.any(|daemon| daemon.pid == pid && daemon.socket_path == socket_path)
}
-/// Socket files in the given socket dir: live daemons and orphaned files alike.
-/// Never-touch paths are filtered here too.
+/// Socket files in the root's socket dir: live daemons and orphaned files
+/// alike. A pinned root has no socket dir (`None`), so it sweeps nothing
+/// but its own socket file (added by the caller). Never-touch paths are
+/// filtered here too.
#[cfg(unix)]
-fn scan_socket_dir(socket_dir: &Path) -> Vec<PathBuf> {
+fn scan_socket_dir(socket_dir: Option<&Path>) -> Vec<PathBuf> {
+ let Some(socket_dir) = socket_dir else {
+ return Vec::new();
+ };
let Ok(entries) = std::fs::read_dir(socket_dir) else {
return Vec::new();
};
@@ -202,7 +238,7 @@ fn scan_socket_dir(socket_dir: &Path) -> Vec<PathBuf> {
/// default pipe (see [`discover_daemons_with`]; TS `scanSocketDir` returns
/// [] on win32).
#[cfg(not(unix))]
-fn scan_socket_dir(_socket_dir: &Path) -> Vec<PathBuf> {
+fn scan_socket_dir(_socket_dir: Option<&Path>) -> Vec<PathBuf> {
Vec::new()
}
@@ -417,28 +453,42 @@ pub(crate) fn discover_daemons(root: &DaemonStateRoot) -> Vec<DaemonInfo> {
/// it, so an unanswered one with no listener or tracked worker is simply
/// absent - there is no orphan file to report or remove.
fn discover_daemons_with(root: &DaemonStateRoot, named_pipes: bool) -> Vec<DaemonInfo> {
- let mut process_by_socket = std::collections::HashMap::new();
- for daemon in scan_listening_daemons(root) {
- if is_worker_socket_path(&daemon.socket_path, &root.socket_dir) {
- continue;
- }
- process_by_socket.insert(daemon.socket_path.clone(), daemon);
- }
+ // The census itself excludes worker sockets (see [`scan_listening_daemons`]).
+ let process_by_socket: std::collections::HashMap<PathBuf, DiscoveredDaemonProcess> =
+ scan_listening_daemons(root)
+ .into_iter()
+ .map(|daemon| (daemon.socket_path.clone(), daemon))
+ .collect();
let tracked = find_all_tracked_workers(&root.agent_dir);
let worker_sockets: BTreeSet<PathBuf> = tracked
.iter()
.map(|worker| worker.supervisor_socket_path.clone())
.collect();
+ // The product-default socket dir's orphan sweep (worker socket files
+ // belong to their supervisors); a pinned root has no dir to sweep and
+ // considers only its own socket file, so a dead pinned daemon's stale
+ // file is still found and removable.
+ #[cfg(unix)]
+ let pinned_socket_file = is_socket_file(&root.default_socket_path);
+ #[cfg(not(unix))]
+ let pinned_socket_file = false;
+ let orphan_files: Vec<PathBuf> = root
+ .socket_dir
+ .as_deref()
+ .map(|dir| {
+ scan_socket_dir(Some(dir))
+ .into_iter()
+ .filter(|path| !is_worker_socket_path(path, dir))
+ .collect()
+ })
+ .unwrap_or_default();
let mut sockets: BTreeSet<PathBuf> = process_by_socket
.keys()
.cloned()
- .chain(
- scan_socket_dir(&root.socket_dir)
- .into_iter()
- .filter(|path| !is_worker_socket_path(path, &root.socket_dir)),
- )
+ .chain(orphan_files)
.chain(worker_sockets.iter().cloned())
.chain(named_pipes.then(|| root.default_socket_path.clone()))
+ .chain(pinned_socket_file.then(|| root.default_socket_path.clone()))
.collect();
sockets.retain(|path| state_root_matches(root, path));
@@ -521,7 +571,7 @@ mod tests {
fn fixture_root(dir: &Path) -> DaemonStateRoot {
DaemonStateRoot {
agent_dir: dir.join("agent"),
- socket_dir: dir.join("agent").join("sockets"),
+ socket_dir: Some(dir.join("agent").join("sockets")),
default_socket_path: dir.join("agent").join("sockets").join("daemon.sock"),
}
}
@@ -545,11 +595,9 @@ mod tests {
#[test]
fn state_root_matches_own_paths_only() {
let root = fixture_root(Path::new("/fixture"));
+ let socket_dir = root.socket_dir.as_deref().expect("fixture socket dir");
assert!(state_root_matches(&root, &root.default_socket_path));
- assert!(state_root_matches(
- &root,
- &root.socket_dir.join("daemon.sock")
- ));
+ assert!(state_root_matches(&root, &socket_dir.join("daemon.sock")));
assert!(state_root_matches(
&root,
&root.agent_dir.join("nested/daemon.sock")
@@ -560,22 +608,38 @@ mod tests {
));
}
+ #[cfg(not(windows))]
+ #[test]
+ fn a_pinned_root_claims_only_its_pinned_socket() {
+ let mut root = fixture_root(Path::new("/fixture"));
+ root.default_socket_path = PathBuf::from("/pins/b.sock");
+ root.socket_dir = None;
+ assert!(state_root_matches(&root, &root.default_socket_path));
+ assert!(state_root_matches(
+ &root,
+ &root.agent_dir.join("nested/daemon.sock")
+ ));
+ assert!(!state_root_matches(&root, Path::new("/pins/c.sock")));
+ assert!(!state_root_matches(&root, Path::new("/pins/daemon.sock")));
+ }
+
#[test]
fn never_touch_paths_are_excluded_even_when_the_root_points_at_them() {
for dir in NEVER_TOUCH_SOCKET_DIRS {
let dir = Path::new(dir);
let root = DaemonStateRoot {
agent_dir: dir.to_path_buf(),
- socket_dir: dir.to_path_buf(),
+ socket_dir: Some(dir.to_path_buf()),
default_socket_path: dir.join("daemon.sock"),
};
+ let socket_dir = root.socket_dir.clone().expect("never-touch socket dir");
assert!(
!state_root_matches(&root, &root.default_socket_path),
"containment must beat root matching for {dir:?}"
);
assert!(!state_root_matches(
&root,
- &root.socket_dir.join("worker-x.sock")
+ &socket_dir.join("worker-x.sock")
));
}
assert!(is_never_touch(Path::new("/tmp/mission-daemon")));
@@ -593,7 +657,7 @@ mod tests {
let dir = *dir;
let root = DaemonStateRoot {
agent_dir: PathBuf::from(dir),
- socket_dir: PathBuf::from(dir),
+ socket_dir: Some(PathBuf::from(dir)),
default_socket_path: PathBuf::from(dir).join("daemon.sock"),
};
assert!(
@@ -616,16 +680,16 @@ mod tests {
fn discovery_reports_orphan_files_inside_the_given_root_only() {
let tmp = tempfile::tempdir().expect("tempdir");
let root = fixture_root(tmp.path());
- std::fs::create_dir_all(&root.socket_dir).expect("socket dir");
+ let socket_dir = root.socket_dir.clone().expect("fixture socket dir");
+ std::fs::create_dir_all(&socket_dir).expect("socket dir");
// Bind and drop: the listener's socket file stays behind (std
// does not unlink it), an orphan file in the fixture root.
drop(
- std::os::unix::net::UnixListener::bind(root.socket_dir.join("leftover.sock"))
- .expect("bind"),
+ std::os::unix::net::UnixListener::bind(socket_dir.join("leftover.sock")).expect("bind"),
);
let infos = discover_daemons(&root);
assert_eq!(infos.len(), 1);
- assert_eq!(infos[0].socket_path, root.socket_dir.join("leftover.sock"));
+ assert_eq!(infos[0].socket_path, socket_dir.join("leftover.sock"));
assert_eq!(infos[0].status, DaemonStatus::OrphanFile);
assert!(!infos[0].is_default);
}
@@ -639,7 +703,8 @@ mod tests {
// only the named-pipe arm's fixed endpoint does, like the Windows
// daemon pipe.
root.default_socket_path = root.agent_dir.join("daemon-pipe.sock");
- std::fs::create_dir_all(&root.socket_dir).expect("socket dir");
+ let socket_dir = root.socket_dir.clone().expect("fixture socket dir");
+ std::fs::create_dir_all(&socket_dir).expect("socket dir");
// No daemon on the pipe: nothing is reported, not a fake orphan.
assert!(discover_daemons_with(&root, true).is_empty());
@@ -653,10 +718,12 @@ mod tests {
drop(stream);
}
});
- assert!(
- discover_daemons_with(&root, false).is_empty(),
- "the unix arm only sees socket-dir files and listeners"
- );
+ // The unix arm also considers the root's own socket file (a pinned
+ // socket's orphan file must stay discoverable); only a file that does
+ // not exist is left to the named-pipe arm above.
+ let infos = discover_daemons_with(&root, false);
+ assert_eq!(infos.len(), 1);
+ assert_eq!(infos[0].socket_path, root.default_socket_path);
let infos = discover_daemons_with(&root, true);
assert_eq!(infos.len(), 1);
assert_eq!(infos[0].socket_path, root.default_socket_path);
diff --git a/crates/pa-cli/src/daemon_discovery/stop.rs b/crates/pa-cli/src/daemon_discovery/stop.rs
index cd79406b36..4dc076b4bf 100644
--- a/crates/pa-cli/src/daemon_discovery/stop.rs
+++ b/crates/pa-cli/src/daemon_discovery/stop.rs
@@ -21,9 +21,7 @@ use super::plan::{
plan_reap, plan_shutdown_all, plan_shutdown_confirmation, ReapActionKind,
ShutdownConfirmationPlan,
};
-use super::{
- discover_daemons, is_daemon_process_listening, probe_daemon, DaemonInfo, DaemonStateRoot,
-};
+use super::{discover_daemons, is_daemon_process_listening, probe_daemon, DaemonStateRoot};
/// `status`: the daemons discovered in the given state root as JSON or
/// as the table.
@@ -198,10 +196,7 @@ fn run_shutdown_converging(json: bool, force: bool, root: &DaemonStateRoot) -> i
let mut failed: Vec<(String, String)> = Vec::new();
let mut handled_pids: std::collections::HashSet<u32> = std::collections::HashSet::new();
- let daemons: Vec<DaemonInfo> = discover_daemons(root)
- .into_iter()
- .filter(|daemon| !super::is_worker_socket_path(&daemon.socket_path, &root.socket_dir))
- .collect();
+ let daemons = discover_daemons(root);
let action_order = |kind: &ReapActionKind| match kind {
ReapActionKind::Shutdown => 0,
ReapActionKind::RemoveFile => 1,
diff --git a/crates/pa-cli/src/interactive_mode/daemon.rs b/crates/pa-cli/src/interactive_mode/daemon.rs
index 5475c52664..04c0a8349e 100644
--- a/crates/pa-cli/src/interactive_mode/daemon.rs
+++ b/crates/pa-cli/src/interactive_mode/daemon.rs
@@ -174,25 +174,12 @@ fn spawn_supervisor_detached(socket_path: &Path, spawn_cwd: &Path, exe: &Path) -
.current_dir(spawn_cwd)
.stdin(Stdio::null())
.stdout(Stdio::null())
- .stderr(Stdio::null())
- // Strip inherited worker/supervisor role env vars so the spawned
- // supervisor never starts in worker mode (a CLI inside a worker would
- // otherwise launch a supervisor that listens but never handshakes) —
- // the TS launcher deletes the same set.
- .env_remove(pa_daemon::worker::WORKER_ROLE_ENV)
- .env_remove(pa_daemon::worker::WORKER_TOKEN_ENV)
- .env_remove(pa_daemon::worker::WORKER_ACTIVE_SESSION_ID_ENV)
- .env_remove(pa_daemon::worker::WORKER_RECOVERY_JOURNAL_ENV)
- .env_remove(pa_daemon::worker::WORKER_SUPERVISOR_SOCKET_ENV)
- .env_remove(pa_daemon::worker::WORKER_SOCKET_ENV)
- .env_remove(pa_daemon::worker::WORKER_INSTANCE_ID_ENV)
- .env_remove(pa_daemon::worker::WORKER_SCRIPT_ENV)
- // A lease owner id inherited from an ancestor would name a stale session in every
- // lease this daemon's workers write — TS deletes the same var before spawning.
- .env_remove(pa_daemon::lease::SESSION_LEASE_OWNER_ID_ENV);
- // A daemon must not share the launching TUI's terminal session: a
- // session-wide terminal cleanup could hang it up after the TUI exits.
- // On Unix, setsid also creates its own process group.
+ .stderr(Stdio::null());
+ // The binary entry strips any inherited worker handshake env, so the
+ // spawned supervisor never starts in worker mode. A daemon must also not
+ // share the launching TUI's terminal session: a session-wide terminal
+ // cleanup could hang it up after the TUI exits; on Unix, setsid also
+ // creates its own process group.
#[cfg(unix)]
pa_core::platform::process::set_new_session(&mut command);
#[cfg(not(unix))]
diff --git a/crates/pa-cli/src/lib.rs b/crates/pa-cli/src/lib.rs
index bb954da1dd..b06a2baaad 100644
--- a/crates/pa-cli/src/lib.rs
+++ b/crates/pa-cli/src/lib.rs
@@ -172,13 +172,13 @@ fn main_impl(args: &[String], runtime: &dyn mode::Runtime) -> Result<i32, String
}
// Daemon worker processes start with the worker role env var set: route
- // straight into the worker runtime.
+ // straight into the worker runtime. The binary entry keeps the worker
+ // handshake env only for the supervisor-spawned `worker` subcommand (it
+ // strips an inherited one from every other invocation), so the routing
+ // reads that subcommand alone.
let is_worker_process =
std::env::var(pa_daemon::worker::WORKER_ROLE_ENV).unwrap_or_default() == "1";
- if is_worker_process
- && (args.first().map(String::as_str) == Some("worker")
- || args.windows(2).any(|pair| pair == ["--mode", "daemon"]))
- {
+ if is_worker_process && args.first().map(String::as_str) == Some("worker") {
return run_worker_mode();
}
diff --git a/crates/pa-cli/src/main.rs b/crates/pa-cli/src/main.rs
index e7df156408..20488f1ffa 100644
--- a/crates/pa-cli/src/main.rs
+++ b/crates/pa-cli/src/main.rs
@@ -5,6 +5,13 @@ fn main() {
// resident for the process lifetime.
pa_types::memory_release::cap_thread_arenas();
let args: Vec<String> = std::env::args().skip(1).collect();
+ // A fresh top-level invocation sheds an inherited worker identity before
+ // any thread exists (edition 2021 makes `remove_var` safe, but it must
+ // still run single-threaded): everything but the supervisor-spawned
+ // `worker` subcommand.
+ if args.first().map(String::as_str) != Some("worker") {
+ pa_daemon::worker::strip_inherited_worker_env();
+ }
let code = pa_cli::main_with_runtime(&args, &pa_cli::PrintRuntime);
// Restore the Windows VT bit before process exit.
pa_types::platform::console_restore();
diff --git a/crates/pa-cli/src/update_flow/successor.rs b/crates/pa-cli/src/update_flow/successor.rs
index 890a0344bd..a8abf2ea93 100644
--- a/crates/pa-cli/src/update_flow/successor.rs
+++ b/crates/pa-cli/src/update_flow/successor.rs
@@ -37,8 +37,8 @@ pub fn identity_from_hello(hello: &Value) -> UpdateProcessIdentity {
}
}
-/// Spawn the successor supervisor detached (the TS launcher deletes the worker
-/// role env; the roster path is the one addition, spec §6).
+/// Spawn the successor supervisor detached (the roster path is the one
+/// addition, spec §6); the binary entry strips any inherited worker env.
///
/// # Errors
/// Returns an error when the successor supervisor cannot be spawned.
@@ -55,15 +55,7 @@ pub fn spawn_supervisor(
.current_dir(cwd)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- .env_remove(pa_daemon::worker::WORKER_ROLE_ENV)
- .env_remove(pa_daemon::worker::WORKER_TOKEN_ENV)
- .env_remove(pa_daemon::worker::WORKER_ACTIVE_SESSION_ID_ENV)
- .env_remove(pa_daemon::worker::WORKER_RECOVERY_JOURNAL_ENV)
- .env_remove(pa_daemon::worker::WORKER_SUPERVISOR_SOCKET_ENV)
- .env_remove(pa_daemon::worker::WORKER_SOCKET_ENV)
- .env_remove(pa_daemon::worker::WORKER_INSTANCE_ID_ENV)
- .env_remove(pa_daemon::worker::WORKER_SCRIPT_ENV);
+ .stderr(std::process::Stdio::null());
if let Some(roster_path) = roster_path {
command.env(UPDATE_ROSTER_ENV, roster_path);
}
diff --git a/crates/pa-cli/src/update_flow/update_command.rs b/crates/pa-cli/src/update_flow/update_command.rs
index a72ebef74e..f5bd48bdd3 100644
--- a/crates/pa-cli/src/update_flow/update_command.rs
+++ b/crates/pa-cli/src/update_flow/update_command.rs
@@ -186,17 +186,7 @@ pub async fn run_update_command(options: &UpdateCommandOptions) -> Result<i32> {
.env(super::coordinator::UPDATE_CANDIDATE_DIR_ENV, &candidate_dir)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- // The coordinator inherits this CLI's environment minus the worker role markers (the TS
- // launcher deletes the same set).
- .env_remove(pa_daemon::worker::WORKER_ROLE_ENV)
- .env_remove(pa_daemon::worker::WORKER_TOKEN_ENV)
- .env_remove(pa_daemon::worker::WORKER_ACTIVE_SESSION_ID_ENV)
- .env_remove(pa_daemon::worker::WORKER_RECOVERY_JOURNAL_ENV)
- .env_remove(pa_daemon::worker::WORKER_SUPERVISOR_SOCKET_ENV)
- .env_remove(pa_daemon::worker::WORKER_SOCKET_ENV)
- .env_remove(pa_daemon::worker::WORKER_INSTANCE_ID_ENV)
- .env_remove(pa_daemon::worker::WORKER_SCRIPT_ENV);
+ .stderr(std::process::Stdio::null());
// The coordinator must survive the CLI and its terminal closing.
#[cfg(unix)]
pa_core::platform::process::set_new_session(&mut command);
diff --git a/crates/pa-cli/tests/daemon_discovery_e2e.rs b/crates/pa-cli/tests/daemon_discovery_e2e.rs
index a0f5e6fbdf..9f685e6309 100644
--- a/crates/pa-cli/tests/daemon_discovery_e2e.rs
+++ b/crates/pa-cli/tests/daemon_discovery_e2e.rs
@@ -15,12 +15,13 @@
//! stop it — nor any other live daemon on the machine.
#![cfg(unix)]
+use std::io::{BufRead as _, BufReader, Write as _};
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::time::{Duration, Instant};
-use serde_json::Value;
+use serde_json::{json, Value};
/// Environment keys this box's own prime-agent worker sets; they must not
/// leak into spawned supervisors.
@@ -109,6 +110,9 @@ fn run_cli(root: &Path, args: &[&str]) -> Output {
for key in SCRUB_ENV {
command.env_remove(key);
}
+ // The state root follows this var (the env-pinned root contract), so a
+ // root-less invocation must not inherit an ambient pin.
+ command.env_remove("PRIME_AGENT_DAEMON_SOCKET");
command.output().expect("spawn CLI binary")
}
@@ -526,3 +530,525 @@ fn wait_until_stopped(socket: &Path, daemon: &mut Daemon) {
socket.display()
);
}
+
+/// The env-pinned invocation shape: the CLI runs with daemon B's state
+/// environment — B's agent dir, the shared TMPDIR, and B's socket through
+/// `PRIME_AGENT_DAEMON_SOCKET` (a root-less invocation scrubs an ambient
+/// pin so it resolves the default root).
+fn run_cli_state_env(
+ tmp: &Path,
+ agent_dir: &Path,
+ daemon_socket: Option<&Path>,
+ args: &[&str],
+) -> Output {
+ std::fs::create_dir_all(agent_dir).expect("agent dir");
+ let mut command = Command::new(cli_binary());
+ command
+ .args(args)
+ .env("PRIME_AGENT_CODING_AGENT_DIR", agent_dir)
+ .env("TMPDIR", tmp)
+ .stdin(Stdio::null());
+ for key in SCRUB_ENV {
+ command.env_remove(key);
+ }
+ match daemon_socket {
+ Some(socket) => command.env("PRIME_AGENT_DAEMON_SOCKET", socket),
+ None => command.env_remove("PRIME_AGENT_DAEMON_SOCKET"),
+ };
+ command.output().expect("spawn CLI binary")
+}
+
+/// A raw JSONL protocol client: connect, then wait for the response
+/// carrying the request id (the hello line on a fresh connection is
+/// skipped on the way).
+struct Wire {
+ reader: BufReader<UnixStream>,
+ writer: UnixStream,
+}
+
+impl Wire {
+ fn connect(socket: &Path) -> Wire {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ loop {
+ match UnixStream::connect(socket) {
+ Ok(stream) => {
+ stream
+ .set_read_timeout(Some(Duration::from_secs(10)))
+ .expect("set read timeout");
+ let writer = stream.try_clone().expect("clone socket");
+ return Wire {
+ reader: BufReader::new(stream),
+ writer,
+ };
+ }
+ Err(_) if Instant::now() < deadline => {
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ Err(error) => panic!("connect daemon at {}: {error}", socket.display()),
+ }
+ }
+ }
+
+ fn request(&mut self, id: &str, command: &Value) -> Value {
+ let envelope = json!({
+ "type": "command",
+ "id": id,
+ "protocol": { "name": "prime-agent.daemon", "version": pa_types::daemon::DAEMON_PROTOCOL_VERSION },
+ "command": command,
+ });
+ let mut line = serde_json::to_string(&envelope).expect("serialize command");
+ line.push('\n');
+ self.writer.write_all(line.as_bytes()).expect("send");
+ self.writer.flush().expect("flush");
+ loop {
+ let mut line = String::new();
+ self.reader.read_line(&mut line).expect("read daemon line");
+ if let Ok(value) = serde_json::from_str::<Value>(line.trim()) {
+ if value.get("id").and_then(Value::as_str) == Some(id) {
+ return value;
+ }
+ }
+ }
+ }
+}
+
+/// One live scripted (faux) session: the supervisor spawns a real worker
+/// whose engine answers from the script file, so a worker process exists
+/// without any model traffic.
+fn create_scripted_session(socket: &Path, agent_dir: &Path) -> String {
+ let sessions = agent_dir.join("sessions");
+ std::fs::create_dir_all(&sessions).expect("sessions dir");
+ let script = agent_dir.join("faux-script.json");
+ std::fs::write(
+ &script,
+ json!({ "responses": [{ "text": "ok", "delayMs": 0 }] }).to_string(),
+ )
+ .expect("write script");
+ let mut wire = Wire::connect(socket);
+ let response = wire.request(
+ "create-faux",
+ &json!({
+ "type": "create",
+ "name": "scope",
+ "config": {
+ "cwd": agent_dir.to_string_lossy(),
+ "sessionDir": sessions.to_string_lossy(),
+ "script": script.to_string_lossy(),
+ }
+ }),
+ );
+ assert_eq!(response["success"], true, "create failed: {response}");
+ response["data"]["activeSessionId"]
+ .as_str()
+ .or_else(|| response["data"]["id"].as_str())
+ .expect("session id")
+ .to_string()
+}
+
+fn pid_alive(pid: u32) -> bool {
+ // Signal 0 is a pure liveness probe (the test binary runs as the same
+ // user as the daemons it spawned).
+ unsafe { libc::kill(pid as i32, 0) == 0 }
+}
+
+fn wait_for_pid_exit(pid: u32, bound: Duration) -> bool {
+ let deadline = Instant::now() + bound;
+ while pid_alive(pid) && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ !pid_alive(pid)
+}
+
+/// The worker descriptors a supervisor persists under
+/// `<agent-dir>/daemon-workers/<key>/` (`supervisor-config` has no .json and
+/// is skipped); unreadable or unparsable files are not safe targets either.
+fn worker_descriptors(agent_dir: &Path) -> Vec<Value> {
+ let mut descriptors = Vec::new();
+ let Ok(directories) = std::fs::read_dir(agent_dir.join("daemon-workers")) else {
+ return descriptors;
+ };
+ for directory in directories.flatten() {
+ let Ok(files) = std::fs::read_dir(directory.path()) else {
+ continue;
+ };
+ for file in files.flatten() {
+ if !file.file_name().to_string_lossy().ends_with(".json") {
+ continue;
+ }
+ if let Ok(content) = std::fs::read_to_string(file.path()) {
+ if let Ok(descriptor) = serde_json::from_str::<Value>(&content) {
+ descriptors.push(descriptor);
+ }
+ }
+ }
+ }
+ descriptors
+}
+
+/// The pid of the live worker a supervisor tracks for its own socket.
+fn tracked_worker_pid(agent_dir: &Path, supervisor_socket: &Path) -> u32 {
+ let supervisor = supervisor_socket.to_string_lossy().to_string();
+ let deadline = Instant::now() + Duration::from_secs(20);
+ loop {
+ if let Some(pid) = worker_descriptors(agent_dir)
+ .into_iter()
+ .filter(|descriptor| {
+ descriptor["supervisorSocketPath"].as_str() == Some(supervisor.as_str())
+ })
+ .find_map(|descriptor| {
+ descriptor["pid"]
+ .as_u64()
+ .filter(|pid| *pid > 0 && pid_alive(*pid as u32))
+ })
+ {
+ return pid as u32;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "no live tracked worker for {}",
+ supervisor_socket.display()
+ );
+ std::thread::sleep(Duration::from_millis(50));
+ }
+}
+
+/// The 2026-10-14 incident, end to end: an isolated test daemon's
+/// `shutdown --force` stopped the shared default daemon and killed every
+/// live worker on the machine — the state root ignored
+/// `PRIME_AGENT_DAEMON_SOCKET`, and the residual sweep treated worker
+/// sockets as daemons. One shared TMPDIR, so every worker socket any daemon
+/// spawns listens in the shared product socket dir, exactly like a real
+/// machine: A owns the product-default socket, B and C are pinned to
+/// sockets inside one shared directory outside the product socket dir, with
+/// live workers of their own. A shutdown must stop only the daemons its
+/// root owns — the pinned socket, never the pinned directory — and never
+/// another daemon's workers.
+#[test]
+fn force_shutdown_from_an_env_pinned_root_stops_only_that_daemon_tree() {
+ let shared_tmp = tempfile::tempdir().expect("shared tmpdir");
+ let fixture_a = tempfile::tempdir().expect("fixture A");
+ let fixture_b = tempfile::tempdir().expect("fixture B");
+ let fixture_c = tempfile::tempdir().expect("fixture C");
+ // SAFETY: getuid is a pure identity query.
+ let socket_dir = shared_tmp
+ .path()
+ .join(format!("prime-agent-{}", unsafe { libc::getuid() }));
+
+ let socket_a = socket_dir.join("daemon.sock"); // the product default
+ let agent_a = fixture_a.path().join("agent");
+ let mut daemon_a = spawn_daemon(&socket_a, &agent_a, shared_tmp.path());
+ let _session_a = create_scripted_session(&socket_a, &agent_a);
+ let worker_a = tracked_worker_pid(&agent_a, &socket_a);
+
+ // B and C are pinned inside one shared pins directory OUTSIDE the
+ // product socket dir: a pinned root must own its pinned socket, never
+ // the whole directory (B's shutdown must not see C in there).
+ let pins_dir = shared_tmp.path().join("pins");
+ std::fs::create_dir_all(&pins_dir).expect("pins dir");
+
+ let agent_b = fixture_b.path().join("agent");
+ let socket_b = pins_dir.join("b.sock"); // env-pinned, isolated
+ let mut daemon_b = spawn_daemon(&socket_b, &agent_b, shared_tmp.path());
+ let _session_b = create_scripted_session(&socket_b, &agent_b);
+ let worker_b = tracked_worker_pid(&agent_b, &socket_b);
+
+ // Like the launcher-pinned daemon of the incident: C's supervisor socket
+ // sits outside the product socket dir, but its worker still listens
+ // there. C shares B's pins directory.
+ let agent_c = fixture_c.path().join("agent");
+ let socket_c = pins_dir.join("c.sock");
+ let mut daemon_c = spawn_daemon(&socket_c, &agent_c, shared_tmp.path());
+ let _session_c = create_scripted_session(&socket_c, &agent_c);
+ let worker_c = tracked_worker_pid(&agent_c, &socket_c);
+
+ assert!(
+ pid_alive(worker_a) && pid_alive(worker_b) && pid_alive(worker_c),
+ "all three workers must be live before any shutdown"
+ );
+
+ // (a) B's env-pinned shutdown stops only B: A and C — supervisors and
+ // workers alike — are outside B's root.
+ let shutdown = run_cli_state_env(
+ shared_tmp.path(),
+ &agent_b,
+ Some(&socket_b),
+ &["shutdown", "--force", "--json"],
+ );
+ assert_eq!(
+ shutdown.status.code(),
+ Some(0),
+ "shutdown stdout: {} stderr: {}",
+ stdout(&shutdown),
+ stderr(&shutdown)
+ );
+ let report: Value = serde_json::from_str(&stdout(&shutdown)).expect("shutdown report");
+ assert_eq!(
+ reported_socket_paths(&report),
+ vec![socket_b.to_string_lossy().to_string()],
+ "the B-rooted report must name only B: {}",
+ stdout(&shutdown)
+ );
+ wait_until_stopped(&socket_b, &mut daemon_b);
+ assert!(
+ wait_for_pid_exit(worker_b, Duration::from_secs(10)),
+ "B's worker must stop with B (through its tracked descriptor)"
+ );
+ assert!(
+ daemon_a
+ .child
+ .try_wait()
+ .expect("wait on daemon A")
+ .is_none(),
+ "A's supervisor must survive B's env-pinned shutdown"
+ );
+ assert!(
+ UnixStream::connect(&socket_a).is_ok(),
+ "A must still accept connections"
+ );
+ assert!(
+ pid_alive(worker_a),
+ "A's worker must survive B's env-pinned shutdown"
+ );
+ assert!(
+ daemon_c
+ .child
+ .try_wait()
+ .expect("wait on daemon C")
+ .is_none(),
+ "C's supervisor must survive B's env-pinned shutdown"
+ );
+ assert!(
+ UnixStream::connect(&socket_c).is_ok(),
+ "C must still accept connections"
+ );
+ assert!(
+ pid_alive(worker_c),
+ "C's worker must survive B's env-pinned shutdown"
+ );
+
+ // (b) The default-rooted shutdown from A stops A and its worker, and
+ // must leave C's worker alone even though it listens in A's socket dir:
+ // the sweep only ever sees supervisors.
+ let shutdown = run_cli_state_env(
+ shared_tmp.path(),
+ &agent_a,
+ None,
+ &["shutdown", "--force", "--json"],
+ );
+ assert_eq!(
+ shutdown.status.code(),
+ Some(0),
+ "shutdown stdout: {} stderr: {}",
+ stdout(&shutdown),
+ stderr(&shutdown)
+ );
+ assert!(
+ daemon_c
+ .child
+ .try_wait()
+ .expect("wait on daemon C")
+ .is_none(),
+ "C's supervisor must survive A's default-rooted shutdown"
+ );
+ assert!(
+ pid_alive(worker_c),
+ "C's worker must survive A's default-rooted shutdown (the residual sweep may not stop another daemon's workers)"
+ );
+ let report: Value = serde_json::from_str(&stdout(&shutdown)).expect("shutdown report");
+ assert_eq!(
+ reported_socket_paths(&report),
+ vec![socket_a.to_string_lossy().to_string()],
+ "the A-rooted report must name only A: {}",
+ stdout(&shutdown)
+ );
+ wait_until_stopped(&socket_a, &mut daemon_a);
+ assert!(
+ wait_for_pid_exit(worker_a, Duration::from_secs(10)),
+ "A's worker must stop with A (through its tracked descriptor)"
+ );
+ assert!(
+ UnixStream::connect(&socket_c).is_ok(),
+ "C must still accept connections"
+ );
+
+ // (c) Cleanup: C's own env-pinned shutdown stops C and its worker.
+ let shutdown = run_cli_state_env(
+ shared_tmp.path(),
+ &agent_c,
+ Some(&socket_c),
+ &["shutdown", "--force", "--json"],
+ );
+ assert_eq!(
+ shutdown.status.code(),
+ Some(0),
+ "shutdown stdout: {} stderr: {}",
+ stdout(&shutdown),
+ stderr(&shutdown)
+ );
+ let report: Value = serde_json::from_str(&stdout(&shutdown)).expect("shutdown report");
+ assert_eq!(
+ reported_socket_paths(&report),
+ vec![socket_c.to_string_lossy().to_string()],
+ "the C-rooted report must name only C: {}",
+ stdout(&shutdown)
+ );
+ wait_until_stopped(&socket_c, &mut daemon_c);
+ assert!(
+ wait_for_pid_exit(worker_c, Duration::from_secs(10)),
+ "C's worker must stop with C (through its tracked descriptor)"
+ );
+}
+
+/// An agent-dir override can contain the shared worker directory while its
+/// own supervisor is pinned elsewhere. Such a root must still exclude other
+/// supervisors' workers from both discovery and the force residual sweep.
+#[test]
+fn a_pinned_root_with_an_overlapping_agent_dir_never_stops_foreign_workers() {
+ let shared_tmp = tempfile::tempdir().expect("shared worker tmpdir");
+ let pins = tempfile::tempdir().expect("supervisor pins outside agent dir");
+ let foreign_fixture = tempfile::tempdir().expect("foreign agent dir");
+ let own_socket = pins.path().join("own.sock");
+ let foreign_socket = pins.path().join("foreign.sock");
+ // Every worker socket is below shared_tmp, which is also this root's
+ // agent dir. Neither supervisor socket is below it.
+ let own_agent = shared_tmp.path();
+ let foreign_agent = foreign_fixture.path().join("agent");
+ let mut own_daemon = spawn_daemon(&own_socket, own_agent, shared_tmp.path());
+ let _own_session = create_scripted_session(&own_socket, own_agent);
+ let own_worker = tracked_worker_pid(own_agent, &own_socket);
+ let mut foreign_daemon = spawn_daemon(&foreign_socket, &foreign_agent, shared_tmp.path());
+ let _foreign_session = create_scripted_session(&foreign_socket, &foreign_agent);
+ let foreign_worker = tracked_worker_pid(&foreign_agent, &foreign_socket);
+
+ let status = run_cli_state_env(
+ shared_tmp.path(),
+ own_agent,
+ Some(&own_socket),
+ &["status", "--json"],
+ );
+ assert!(status.status.success(), "{}", stderr(&status));
+ let services: Vec<Value> = serde_json::from_str(&stdout(&status)).expect("status report");
+ let sockets: Vec<&str> = services
+ .iter()
+ .map(|service| service["socketPath"].as_str().expect("socket path"))
+ .collect();
+ assert_eq!(
+ sockets,
+ vec![own_socket.to_str().expect("fixture path")],
+ "a pinned root must discover supervisors only: {}",
+ stdout(&status)
+ );
+
+ let shutdown = run_cli_state_env(
+ shared_tmp.path(),
+ own_agent,
+ Some(&own_socket),
+ &["shutdown", "--force", "--json"],
+ );
+ assert!(shutdown.status.success(), "{}", stderr(&shutdown));
+ wait_until_stopped(&own_socket, &mut own_daemon);
+ assert!(wait_for_pid_exit(own_worker, Duration::from_secs(10)));
+ assert!(
+ foreign_daemon
+ .child
+ .try_wait()
+ .expect("foreign supervisor wait")
+ .is_none()
+ && pid_alive(foreign_worker),
+ "the foreign supervisor and its original worker must survive"
+ );
+ assert!(UnixStream::connect(&foreign_socket).is_ok());
+
+ // Teardown names the exact fixture socket; no machine-wide discovery.
+ run_shutdown_on_socket(&foreign_socket).expect("foreign shutdown handshake");
+ wait_until_stopped(&foreign_socket, &mut foreign_daemon);
+ assert!(wait_for_pid_exit(foreign_worker, Duration::from_secs(10)));
+}
+
+/// A fresh top-level invocation must not inherit an ancestor worker's
+/// identity: a kernel bash hands a worker's full environment to every
+/// child, so `prime-agent --mode daemon --daemon-socket B` launched from
+/// inside a worker must come up as B's supervisor — never as a second
+/// worker of the live supervisor the inherited env points at.
+#[test]
+fn a_daemon_launched_with_an_inherited_worker_env_comes_up_as_a_supervisor() {
+ let fixture = tempfile::tempdir().expect("fixture");
+ let agent_dir = fixture.path().join("agent");
+ let tmp_dir = fixture.path().join("tmp");
+ let socket = fixture.path().join("daemon.sock");
+ let worker_socket = fixture.path().join("worker.sock");
+ let ancestor_socket = fixture.path().join("ancestor-supervisor.sock");
+ std::fs::create_dir_all(&agent_dir).expect("agent dir");
+ std::fs::create_dir_all(&tmp_dir).expect("tmp dir");
+ let mut command = Command::new(cli_binary());
+ command
+ .args(["--mode", "daemon", "--daemon-socket"])
+ .arg(&socket)
+ .env("PRIME_AGENT_CODING_AGENT_DIR", &agent_dir)
+ .env("TMPDIR", &tmp_dir)
+ // The inherited worker handshake set (what a kernel bash sees).
+ .env(pa_daemon::worker::WORKER_ROLE_ENV, "1")
+ .env(
+ pa_daemon::worker::WORKER_TOKEN_ENV,
+ "inherited-worker-token",
+ )
+ .env(
+ pa_daemon::worker::WORKER_INSTANCE_ID_ENV,
+ "inherited-instance",
+ )
+ .env(
+ pa_daemon::worker::WORKER_ACTIVE_SESSION_ID_ENV,
+ "inherited-session",
+ )
+ .env(pa_daemon::worker::WORKER_CWD_ENV, fixture.path())
+ .env(
+ pa_daemon::worker::WORKER_SUPERVISOR_SOCKET_ENV,
+ &ancestor_socket,
+ )
+ .env(pa_daemon::worker::WORKER_SOCKET_ENV, &worker_socket)
+ .env(
+ pa_daemon::worker::WORKER_RECOVERY_JOURNAL_ENV,
+ fixture.path().join("recovery.jsonl"),
+ )
+ .env(pa_daemon::worker::WORKER_TELEMETRY_DISABLED_ENV, "1")
+ .env(
+ pa_daemon::lease::SESSION_LEASE_OWNER_ID_ENV,
+ "inherited-session",
+ )
+ .env(
+ pa_core::kernel::orphan_journal::ORPHAN_PROCESS_JOURNAL_ENV,
+ fixture.path().join("orphans.jsonl"),
+ )
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+ let child = command.spawn().expect("spawn the daemon");
+ let pid = child.id();
+ let _daemon = Daemon { child };
+
+ // The invocation must come up as B's supervisor. On a routing
+ // regression the process starts as a worker instead and this socket
+ // never appears.
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while !socket.exists() && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ assert!(
+ socket.exists(),
+ "the daemon must come up as a supervisor on {} (an inherited worker env must not reroute it into worker mode)",
+ socket.display()
+ );
+
+ // The hello names this child as the supervisor.
+ let stream = UnixStream::connect(&socket).expect("connect the supervisor");
+ let mut hello = String::new();
+ BufReader::new(stream)
+ .read_line(&mut hello)
+ .expect("read the daemon hello");
+ let hello: Value = serde_json::from_str(hello.trim()).expect("parse the daemon hello");
+ assert_eq!(
+ hello["supervisorPid"].as_i64(),
+ Some(i64::from(pid)),
+ "the hello must name this child as the supervisor: {hello}"
+ );
+}
diff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rs
index 1fbd77fd77..b2410db25b 100644
--- a/crates/pa-daemon/src/worker.rs
+++ b/crates/pa-daemon/src/worker.rs
@@ -48,9 +48,9 @@ use turn::TurnRunner;
mod commands;
pub use env::{
- WORKER_ACTIVE_SESSION_ID_ENV, WORKER_CWD_ENV, WORKER_INSTANCE_ID_ENV,
- WORKER_RECOVERY_JOURNAL_ENV, WORKER_ROLE_ENV, WORKER_SCRIPT_ENV, WORKER_SOCKET_ENV,
- WORKER_SUPERVISOR_LOST_EXIT_MS_ENV, WORKER_SUPERVISOR_SOCKET_ENV,
+ strip_inherited_worker_env, WORKER_ACTIVE_SESSION_ID_ENV, WORKER_CWD_ENV,
+ WORKER_INSTANCE_ID_ENV, WORKER_RECOVERY_JOURNAL_ENV, WORKER_ROLE_ENV, WORKER_SCRIPT_ENV,
+ WORKER_SOCKET_ENV, WORKER_SUPERVISOR_LOST_EXIT_MS_ENV, WORKER_SUPERVISOR_SOCKET_ENV,
WORKER_TELEMETRY_DISABLED_ENV, WORKER_TOKEN_ENV,
};
use serde_json::Map;
diff --git a/crates/pa-daemon/src/worker/env.rs b/crates/pa-daemon/src/worker/env.rs
index 1315864fd2..e8cb9af28d 100644
--- a/crates/pa-daemon/src/worker/env.rs
+++ b/crates/pa-daemon/src/worker/env.rs
@@ -66,3 +66,39 @@ pub const WORKER_TELEMETRY_DISABLED_ENV: &str =
/// unreachable for this long exits instead of lingering orphaned.
pub const WORKER_SUPERVISOR_LOST_EXIT_MS_ENV: &str =
"PRIME_AGENT_INTERNAL_WORKER_SUPERVISOR_LOST_EXIT_MS";
+
+/// The worker identity/handshake set the supervisor stamps on a worker
+/// spawn ([`crate::descriptor::worker_launch_env`]), minus the public
+/// agent/session dir overrides and the operator knobs that legitimately
+/// propagate by inheritance (the supervisor-lost window, the leases
+/// switch, the registry dir). One list next to the constants it names: a
+/// new handshake var joins `worker_launch_env` and this list together.
+/// Private — [`strip_inherited_worker_env`] is its only reader, so the
+/// binary entry stays the one owner of the strip.
+const INHERITED_WORKER_ENV: &[&str] = &[
+ WORKER_ROLE_ENV,
+ WORKER_TOKEN_ENV,
+ WORKER_INSTANCE_ID_ENV,
+ WORKER_ACTIVE_SESSION_ID_ENV,
+ WORKER_CWD_ENV,
+ WORKER_SUPERVISOR_SOCKET_ENV,
+ WORKER_SOCKET_ENV,
+ WORKER_RECOVERY_JOURNAL_ENV,
+ WORKER_SCRIPT_ENV,
+ WORKER_TELEMETRY_DISABLED_ENV,
+ crate::lease::SESSION_LEASE_OWNER_ID_ENV,
+ pa_core::kernel::orphan_journal::ORPHAN_PROCESS_JOURNAL_ENV,
+];
+
+/// Remove [`INHERITED_WORKER_ENV`] from this process's environment: a
+/// fresh top-level invocation launched from inside a worker (a kernel bash
+/// inherits the worker's full env) must not carry the ancestor's identity —
+/// the routing would turn it into a second worker of the live supervisor,
+/// and every process it spawns would inherit a live token and stale socket
+/// paths. Call at the binary entry, before any thread exists, for every
+/// invocation that is not the supervisor-spawned `worker` subcommand.
+pub fn strip_inherited_worker_env() {
+ for key in INHERITED_WORKER_ENV {
+ std::env::remove_var(key);
+ }
+}
diff --git a/scripts/review_shutdown_scope_parity.py b/scripts/review_shutdown_scope_parity.py
new file mode 100644
index 0000000000..376f40ffc9
--- /dev/null
+++ b/scripts/review_shutdown_scope_parity.py
@@ -0,0 +1,300 @@
+#!/usr/bin/env python3
+"""Owned real TS/Rust shutdown fixtures; root scoping is an intentional safety delta."""
+import argparse
+import json
+import os
+from pathlib import Path
+import signal
+import subprocess
+import tempfile
+import threading
+import time
+
+from review_agent_bounce_parity import Client, Provider, Handler, LIMIT
+from review_draft_disconnect_parity import digest, env_for, stop, TS_ARCHIVE_SHA256
+
+
+class CompletionHandler(Handler):
+ def do_POST(self):
+ if self.path != '/v1/chat/completions':
+ self.send_error(404)
+ return
+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ with self.server.arrived:
+ self.server.requests.append(body)
+ self.server.arrived.notify_all()
+ gate = self.server.foreign_release if 'SHUTDOWN_SCOPE_BUSY_foreign' in json.dumps(body) else self.server.release
+ gate.wait(LIMIT * 3)
+ self.send_response(200)
+ self.send_header('Content-Type', 'text/event-stream')
+ self.end_headers()
+ frames = [
+ {'choices': [{'index': 0, 'delta': {'role': 'assistant',
+ 'content': 'Fixture turn completed.'}, 'finish_reason': None}]},
+ {'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]},
+ ]
+ try:
+ for frame in frames:
+ self.wfile.write(('data: ' + json.dumps(frame) + '\n\n').encode())
+ self.wfile.write(b'data: [DONE]\n\n')
+ self.wfile.flush()
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+
+def process_identity(pid):
+ try:
+ fields = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()
+ return fields[19] if fields[0] != 'Z' else None
+ except (FileNotFoundError, ProcessLookupError):
+ return None
+
+
+def owned_identity(pid, root):
+ expected = ('PRIME_AGENT_CODING_AGENT_DIR=' + str(root / 'agent')).encode()
+ try:
+ if expected not in Path(f'/proc/{pid}/environ').read_bytes().split(b'\0'):
+ return None
+ return process_identity(pid)
+ except (FileNotFoundError, ProcessLookupError, PermissionError):
+ return None
+
+
+def process_command(pid):
+ try:
+ return Path(f'/proc/{pid}/cmdline').read_bytes().replace(b'\0', b' ').decode(errors='replace')
+ except (FileNotFoundError, ProcessLookupError):
+ return '<exited during role capture>'
+
+
+def owned_processes(root):
+ return {int(path.name): identity for path in Path('/proc').iterdir()
+ if path.name.isdigit()
+ and (identity := owned_identity(int(path.name), root)) is not None}
+
+
+def survivors(original, root):
+ return {pid: identity for pid, identity in original.items()
+ if owned_identity(pid, root) == identity}
+
+
+def wait_stopped(process):
+ process.wait(timeout=LIMIT)
+
+
+def close_client(tree):
+ client = tree.get('client')
+ if client is not None:
+ tree.setdefault('closed_wire', []).extend(client.wire)
+ client.close()
+ tree['client'] = None
+
+
+def finish_tree(tree, observed):
+ process, client, root = tree['process'], tree.get('client'), tree['root']
+ error = None
+ if process.poll() is None:
+ try:
+ if tree.get('shutdown_acknowledged'):
+ observed['shutdown_already_acknowledged'] = True
+ else:
+ if client is None:
+ client = tree['client'] = Client(tree['socket'], process)
+ observed['cleanup_shutdown_response'] = client.call('shutdown', force=True)
+ tree['shutdown_acknowledged'] = True
+ close_client(tree)
+ wait_stopped(process)
+ except Exception as caught:
+ error = caught
+ stop(process)
+ deadline = time.monotonic() + LIMIT
+ while owned_processes(root) and time.monotonic() < deadline:
+ threading.Event().wait(0.025)
+ remaining = owned_processes(root)
+ observed['remaining_owned_processes'] = remaining
+ if remaining:
+ # Fallback touches only this fixture's exact environment and captured
+ # start identity; PID reuse or unrelated processes are never targets.
+ for sig in (signal.SIGTERM, signal.SIGKILL):
+ for pid, identity in remaining.items():
+ if owned_identity(pid, root) == identity:
+ try:
+ os.kill(pid, sig)
+ except ProcessLookupError:
+ pass
+ error = error or RuntimeError('detached fixture processes survived: ' + str(remaining))
+ close_client(tree)
+ observed['wire'] = tree.get('closed_wire', [])
+ tree['log'].close()
+ observed['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')[-6000:]
+ if error:
+ raise RuntimeError('owned cleanup failed: ' + str(error)) from error
+
+
+def launch(binary, kind, root, socket_path, shared_tmp, provider, trees):
+ env = env_for(root, kind)
+ env['TMPDIR'] = str(shared_tmp)
+ env['PRIME_AGENT_DAEMON_SOCKET'] = str(socket_path)
+ env['PRIME_AGENT_INTERNAL_WORKER_SUPERVISOR_LOST_EXIT_MS'] = '15000'
+ (root / 'agent/models.json').write_text(json.dumps({'providers': {'parity-local': {
+ 'api': 'openai-completions', 'apiKey': 'fixture-only',
+ 'baseUrl': f'http://127.0.0.1:{provider.server_port}/v1',
+ 'models': [{'id': 'parity-1', 'name': 'Parity 1', 'reasoning': False,
+ 'contextWindow': 128000, 'maxTokens': 4096}]}}}))
+ (root / 'agent/settings.json').write_text(json.dumps({'prewarmPythonKernel': False,
+ 'defaultProvider': 'parity-local', 'defaultModel': 'parity-1',
+ 'onboardingCompleted': True, 'telemetry': {'noticeShown': True}}))
+ log = open(root / 'daemon.log', 'wb')
+ process = subprocess.Popen([str(binary), '--mode', 'daemon', '--daemon-socket', str(socket_path)],
+ cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+ tree = {'root': root, 'env': env, 'process': process, 'log': log, 'socket': socket_path}
+ trees.append(tree)
+ client = tree['client'] = Client(socket_path, process)
+ created = client.call('create', config={'cwd': str(root), 'agentDir': str(root / 'agent'),
+ 'provider': 'parity-local', 'model': 'parity-1', 'noExtensions': True,
+ 'noSkills': True, 'noTools': True, 'noContextFiles': True, 'telemetryDisabled': True})
+ active = created.get('activeSessionId') or created.get('id')
+ worker_pid = created.get('workerPid')
+ assert isinstance(worker_pid, int), 'create did not identify its worker'
+ assert active, created
+ marker = 'SHUTDOWN_SCOPE_BUSY_' + root.name
+ client.call('prompt', activeSessionId=active, message=marker)
+ provider.wait_for(marker)
+ original = tree['original_processes'] = owned_processes(root)
+ assert process.pid in original and worker_pid in original, 'live supervisor and worker not observed'
+ tree['critical_processes'] = {pid: original[pid] for pid in (process.pid, worker_pid)}
+ tree['process_roles'] = {str(pid): {'role': 'supervisor' if pid == process.pid else 'worker' if pid == worker_pid else 'other inherited-environment process', 'cmdline': process_command(pid)} for pid in original}
+ return tree
+
+
+def invoke(binary, args, tree):
+ result = subprocess.run([str(binary), *args], cwd=tree['root'], env=tree['env'],
+ capture_output=True, text=True, timeout=LIMIT, check=False)
+ return {'returncode': result.returncode, 'stdout': result.stdout, 'stderr': result.stderr}
+
+
+def run_case(binary, kind, root, mode, observed):
+ shared_tmp = root / 'shared-tmp'
+ shared_tmp.mkdir(parents=True)
+ default_socket = shared_tmp / f'prime-agent-{os.getuid()}' / 'daemon.sock'
+ default_socket.parent.mkdir()
+ pins = root / 'pins'
+ pins.mkdir()
+ provider = Provider()
+ provider.RequestHandlerClass = CompletionHandler
+ provider.foreign_release = threading.Event()
+ threading.Thread(target=provider.serve_forever, daemon=True).start()
+ trees = []
+ primary_error = None
+ try:
+ foreign = launch(binary, kind, root / 'foreign', default_socket, shared_tmp, provider, trees)
+ own = launch(binary, kind, root / 'own', pins / 'own.sock', shared_tmp, provider, trees)
+ observed['process_roles'] = {name: tree['process_roles'] for name, tree in [('own', own), ('foreign', foreign)]}
+ observed['critical_processes'] = {name: tree['critical_processes'] for name, tree in [('own', own), ('foreign', foreign)]}
+ observed['original_processes'] = {name: tree['original_processes']
+ for name, tree in [('own', own), ('foreign', foreign)]}
+ if mode == 'exact_socket':
+ provider.release.set()
+ observed['action_response'] = own['client'].call('shutdown', force=True)
+ own['shutdown_acknowledged'] = True
+ close_client(own)
+ wait_stopped(own['process'])
+ kept = survivors(foreign['original_processes'], foreign['root'])
+ observed['foreign_original_processes_after'] = kept
+ assert survivors(foreign['critical_processes'], foreign['root']) == foreign['critical_processes'], 'exact socket shutdown harmed foreign supervisor or worker'
+ else:
+ status = observed['status_cli'] = invoke(binary, ['status', '--json'], own)
+ assert status['returncode'] == 0, status
+ services = observed['discovered_services'] = json.loads(status['stdout'])
+ paths = [service['socketPath'] for service in services]
+ if kind == 'rust':
+ assert paths == [str(own['socket'])], paths
+ else:
+ assert str(foreign['socket']) in paths, 'TS shared default tree was not discovered'
+ provider.release.set()
+ # Root CLI creates its own shutdown client. Close fixture observers
+ # beforehand so TS net.Server.close can retire acknowledged trees.
+ close_client(own)
+ if kind == 'ts':
+ close_client(foreign)
+ provider.foreign_release.set()
+ shutdown = observed['shutdown_cli'] = invoke(binary, ['shutdown', '--force', '--json'], own)
+ assert shutdown['returncode'] == 0, shutdown
+ report = json.loads(shutdown['stdout'])
+ assert report['failed'] == [], report
+ stopped_paths = {row['socketPath'] for row in report['stopped']}
+ assert str(own['socket']) in stopped_paths, 'root shutdown omitted own supervisor'
+ for tree in trees:
+ if str(tree['socket']) in stopped_paths:
+ tree['shutdown_acknowledged'] = True
+ # A successful root report must settle before cleanup; a new
+ # connection must never re-pin a supervisor already in server.close.
+ wait_stopped(own['process'])
+ kept = survivors(foreign['original_processes'], foreign['root'])
+ observed['foreign_original_processes_after'] = kept
+ observed['own_supervisor_stopped'] = own['process'].poll() is not None
+ if kind == 'rust':
+ observed['own_supervisor_stopped'] = True
+ assert survivors(foreign['critical_processes'], foreign['root']) == foreign['critical_processes'], 'pinned root shutdown harmed foreign supervisor or worker'
+ else:
+ wait_stopped(foreign['process'])
+ deadline = time.monotonic() + LIMIT
+ while survivors(foreign['original_processes'], foreign['root']) and time.monotonic() < deadline:
+ threading.Event().wait(0.025)
+ assert not survivors(foreign['original_processes'], foreign['root']), 'TS global root did not stop default tree'
+ observed['provider_requests'] = provider.requests
+ except Exception as error:
+ primary_error = error
+ observed['primary_error'] = str(error)
+ raise
+ finally:
+ provider.release.set()
+ provider.foreign_release.set()
+ errors = []
+ for index, tree in enumerate(trees):
+ cleanup = observed.setdefault('cleanup', {})[str(index)] = {}
+ try:
+ finish_tree(tree, cleanup)
+ except Exception as error:
+ errors.append(str(error))
+ provider.shutdown()
+ provider.server_close()
+ if errors:
+ observed['cleanup_errors'] = errors
+ if primary_error is None:
+ raise RuntimeError('; '.join(errors))
+ observed['verified'] = True
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--receipt', required=True, type=Path)
+ args = parser.parse_args()
+ receipt = {'scenario': 'shutdown_scope', 'verified': False, 'cases': {},
+ 'scope': 'real supervisor and busy worker identities, exact-socket shutdown baseline, pinned-root status and shutdown',
+ 'intentional_difference': 'TS 0.9.8 discovers/stops the shared default tree; Rust pinned root discovers/stops only its own supervisor tree',
+ 'process_scope': 'original supervisor and worker identities must survive Rust isolation; other inherited-environment processes are role/cmdline captured but can complete naturally',
+ 'not_covered': 'doctor output, inherited worker environment routing, overlapping agent-dir regression (separate Rust hosted red/green test)'}
+ try:
+ archive = Path(os.environ['PA_TS_ARCHIVE'])
+ assert digest(archive) == TS_ARCHIVE_SHA256, 'TS archive digest mismatch'
+ receipt['ts_archive_sha256'] = digest(archive)
+ with tempfile.TemporaryDirectory(prefix='pa-shutdown-scope-', dir='/tmp') as folder:
+ for kind in ('ts', 'rust'):
+ binary = Path(os.environ['PA_' + kind.upper() + '_BINARY']).resolve()
+ receipt[kind + '_binary_sha256'] = digest(binary)
+ for mode in ('exact_socket', 'pinned_root'):
+ observed = receipt['cases'][kind + '_' + mode] = {}
+ run_case(binary, kind, Path(folder) / (kind + '_' + mode), mode, observed)
+ assert receipt['cases']['ts_exact_socket']['action_response'] == receipt['cases']['rust_exact_socket']['action_response'], 'exact-socket shutdown response data differs'
+ receipt['verified'] = True
+ except Exception as error:
+ receipt['error'] = str(error)
+ raise
+ finally:
+ args.receipt.parent.mkdir(parents=True, exist_ok=True)
+ args.receipt.write_text(json.dumps(receipt, ensure_ascii=False, indent=2))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/test_review_shutdown_scope_parity.py b/scripts/test_review_shutdown_scope_parity.py
new file mode 100644
index 0000000000..dce3b993ca
--- /dev/null
+++ b/scripts/test_review_shutdown_scope_parity.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python3
+"""Guards on process identity and cleanup failure, with no actual processes."""
+import io
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import Mock, patch
+import review_shutdown_scope_parity as verifier
+
+
+class OwnershipTests(unittest.TestCase):
+ def test_pid_reuse_is_not_an_original_survivor(self):
+ with patch.object(verifier, 'owned_identity', side_effect=lambda pid, root: {10: 'new-start', 20: 'same-start'}[pid]):
+ self.assertEqual(verifier.survivors({10: 'old-start', 20: 'same-start'}, Path('/fixture')),
+ {20: 'same-start'})
+
+ def test_an_unowned_process_has_no_identity(self):
+ with patch.object(Path, 'read_bytes', return_value=b'PRIME_AGENT_CODING_AGENT_DIR=/another/agent\0'), patch.object(verifier, 'process_identity') as identity:
+ self.assertIsNone(verifier.owned_identity(10, Path('/fixture')))
+ identity.assert_not_called()
+
+ def test_shutdown_ack_closes_client_before_waiting_for_supervisor(self):
+ with tempfile.TemporaryDirectory() as folder:
+ root = Path(folder)
+ (root / 'daemon.log').write_text('fixture')
+ client = Mock(wire=[{'type': 'response', 'success': True}])
+ process = Mock(poll=Mock(return_value=None))
+ tree = {'root': root, 'process': process, 'client': client, 'log': io.BytesIO()}
+ def waited(timeout):
+ client.close.assert_called_once()
+ self.assertIsNone(tree['client'])
+ process.wait.side_effect = waited
+ observed = {}
+ with patch.object(verifier, 'stop'), patch.object(verifier, 'owned_processes', return_value={}):
+ verifier.finish_tree(tree, observed)
+ self.assertEqual(observed['wire'], [{'type': 'response', 'success': True}])
+ self.assertEqual(observed['remaining_owned_processes'], {})
+
+ def test_acknowledged_shutdown_never_reconnects_and_timeout_stays_red(self):
+ for timeout in (False, True):
+ with tempfile.TemporaryDirectory() as folder:
+ root = Path(folder)
+ (root / 'daemon.log').write_text('fixture')
+ process = Mock(poll=Mock(return_value=None))
+ if timeout:
+ process.wait.side_effect = TimeoutError('acknowledged process still alive')
+ tree = {'root': root, 'process': process, 'client': None,
+ 'shutdown_acknowledged': True, 'log': io.BytesIO()}
+ observed = {}
+ with patch.object(verifier, 'Client') as connect, patch.object(verifier, 'stop'), patch.object(verifier, 'owned_processes', return_value={}):
+ if timeout:
+ with self.assertRaisesRegex(RuntimeError, 'acknowledged process still alive'):
+ verifier.finish_tree(tree, observed)
+ else:
+ verifier.finish_tree(tree, observed)
+ connect.assert_not_called()
+ process.wait.assert_called_once()
+ self.assertTrue(tree['shutdown_acknowledged'])
+ self.assertTrue(observed['shutdown_already_acknowledged'])
+
+ def test_cleanup_survival_fails_and_pid_reuse_is_not_signaled(self):
+ with tempfile.TemporaryDirectory() as folder:
+ root = Path(folder)
+ (root / 'daemon.log').write_text('fixture')
+ tree = {'root': root, 'process': Mock(poll=Mock(return_value=0)), 'log': io.BytesIO()}
+ observed = {}
+ with patch.object(verifier, 'stop'), patch.object(verifier, 'owned_processes', return_value={10: 'old-start'}), patch.object(verifier, 'owned_identity', return_value='new-start'), patch.object(verifier.time, 'monotonic', side_effect=[0, verifier.LIMIT + 1]), patch.object(verifier.os, 'kill') as kill:
+ with self.assertRaisesRegex(RuntimeError, 'detached fixture processes survived'):
+ verifier.finish_tree(tree, observed)
+ kill.assert_not_called()
+ self.assertEqual(observed['remaining_owned_processes'], {10: 'old-start'})
+ self.assertTrue(tree['log'].closed)
+
+
+if __name__ == '__main__':
+ unittest.main()