A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
daemon: forward the client launch env to session workers; strip RLM_DEPTH (#3574)
Sebastian Müllere090862aae43
diff --git a/crates/pa-cli/src/print_runtime.rs b/crates/pa-cli/src/print_runtime.rsindex c80b1e24d2..b447fdd95e 100644--- a/crates/pa-cli/src/print_runtime.rs+++ b/crates/pa-cli/src/print_runtime.rs@@ -201,6 +201,14 @@ fn daemon_acp_create(create_config["childScript"] =serde_json::Value::String(child_script.to_string_lossy().to_string());}+ // TS main.ts `launchEnv` (:1092 via the daemon-client create): the+ // client's own environment travels on the create so the session's+ // worker runs in the environment of the terminal that invoked it,+ // not the daemon's boot environment.+ let launch_env = {+ let env = pa_types::daemon::launch_env::collect_process_launch_env();+ (!env.is_empty()).then_some(env)+ };let create = pa_types::daemon::DaemonCommand::Create {id: None,session_path: session_path.map(|path| path.display().to_string()),@@ -212,7 +220,7 @@ fn daemon_acp_create(runtime_metadata: None,lifecycle: Some(lifecycle),env: None,- launch_env: None,+ launch_env,rest: serde_json::Map::default(),};Ok((cwd, create))diff --git a/crates/pa-daemon/src/ownership.rs b/crates/pa-daemon/src/ownership.rsindex 8eeef625a9..6432c70bf9 100644--- a/crates/pa-daemon/src/ownership.rs+++ b/crates/pa-daemon/src/ownership.rs@@ -122,6 +122,8 @@ impl Supervisor {if let Err(error) = persist_worker(&resident.descriptor_path, &descriptor) {return Self::owned_failure(command_id, type_name, &error.to_string());}+ // The promotion clear (TS `promoteOwnedWorker`).+ resident.clear_launch_env();true}None => {diff --git a/crates/pa-daemon/src/registry.rs b/crates/pa-daemon/src/registry.rsindex c18b2104d4..667df288fe 100644--- a/crates/pa-daemon/src/registry.rs+++ b/crates/pa-daemon/src/registry.rs@@ -140,6 +140,14 @@ pub(crate) struct ResidentWorker {pub(crate) compaction: crate::compaction_supervision::CompactionSupervision,/// The pending owner-disconnect stop (TS `ownerCleanupTimer`).pub(crate) owner_cleanup: std::sync::Mutex<Option<tokio::task::AbortHandle>>,+ /// The client-forwarded launch env (TS `ResidentWorker.launchEnv`):+ /// in memory ONLY — never the descriptor, never the durable create+ /// command, never the update roster. The spawn merges it under the+ /// internal identity overrides. A resident worker loses it once its+ /// create completes (a crash relaunch runs on the daemon's env); an+ /// owned worker keeps it for the owner-driven recovery relaunch+ /// until ownership clears (promotion).+ pub(crate) launch_env: std::sync::Mutex<Option<std::collections::BTreeMap<String, String>>>,}/// The last-good heartbeats rows, tagged with the catalog generation they@@ -188,9 +196,24 @@ impl ResidentWorker {connection_epoch: AtomicU64::new(0),compaction: crate::compaction_supervision::CompactionSupervision::default(),owner_cleanup: std::sync::Mutex::new(None),+ launch_env: std::sync::Mutex::new(None),})}+ /// Set the client-forwarded launch env (the in-memory lifetime is+ /// documented on the field).+ pub(crate) fn set_launch_env(&self, env: Option<std::collections::BTreeMap<String, String>>) {+ *self+ .launch_env+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = env;+ }++ /// Drop the stored launch env (the ready-time and promotion clears).+ pub(crate) fn clear_launch_env(&self) {+ self.set_launch_env(None);+ }+pub(crate) fn route_state(&self) -> WorkerRouteState {*self.route_state_tx.borrow()}diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rsindex 08bf098a3c..0be796751b 100644--- a/crates/pa-daemon/src/rlm_children/host.rs+++ b/crates/pa-daemon/src/rlm_children/host.rs@@ -50,6 +50,32 @@ async fn resolve_child_model_allowlisted(}}+/// The `rlm.create_session` launch env (TS `createRlmRootSession`'s+/// minimal map: `collectDaemonLaunchEnv({ PATH })` plus the provider's+/// env API-key var plus `PRIME_TEAM_ID` for prime-inference).+fn create_session_launch_env(model: &str) -> std::collections::BTreeMap<String, String> {+ let mut env = std::collections::BTreeMap::new();+ if let Ok(path) = std::env::var("PATH") {+ env.insert("PATH".to_string(), path);+ }+ let provider = model+ .split_once('/')+ .map_or(model, |(provider, _)| provider);+ if let Some(env_key) =+ pa_ai::env_api_keys::find_env_keys(provider).and_then(|keys| keys.first().cloned())+ {+ if let Ok(value) = std::env::var(&env_key) {+ env.insert(env_key, value);+ }+ }+ if provider == "prime-inference" {+ if let Ok(team) = std::env::var("PRIME_TEAM_ID") {+ env.insert("PRIME_TEAM_ID".to_string(), team);+ }+ }+ env+}+impl RlmSubagentHost for SupervisorChildSessions {fn spawn(&self, request: RlmSpawnRequest) -> RlmHostFuture<RlmSpawnHandle> {let this = Arc::clone(&self.inner);@@ -115,6 +141,12 @@ impl RlmSubagentHost for SupervisorChildSessions {request.spawned_by_request_id.as_deref(),Some(runtime_metadata),&identity,+ // TS runs `rlm.spawn` children in-process+ // inside the parent worker, so they share its+ // env; the Rust child is a separate worker+ // process, so the spawn forwards the parent+ // worker's env (filtered) instead.+ Some(pa_types::daemon::launch_env::collect_process_launch_env()),).await?;let record = ChildRecord {@@ -310,6 +342,9 @@ impl RlmSubagentHost for SupervisorChildSessions {&sessions_dir,None,&identity,+ // The TS minimal map for a depth-0 root (the+ // env-key heuristic is stated in the PR).+ Some(create_session_launch_env(&model)),).await?;// The TS create-path summary validation: a resident depth-0diff --git a/crates/pa-daemon/src/rlm_children/lifecycle.rs b/crates/pa-daemon/src/rlm_children/lifecycle.rsindex 356f0782f3..7315365ea0 100644--- a/crates/pa-daemon/src/rlm_children/lifecycle.rs+++ b/crates/pa-daemon/src/rlm_children/lifecycle.rs@@ -55,6 +55,12 @@ fn custom_message_text(message: &CustomMessage) -> Option<String> {impl SupervisorChildSessionsInner {/// Create one child session over the supervisor link (no prompt yet);/// `model` is the resolved `provider/id` selector.+ ///+ /// `launch_env` is the environment the child's worker process runs+ /// in: the parent worker's own env (filtered) for an `rlm.spawn`+ /// child — TS runs those in-process inside the parent worker, so+ /// parity means the child inherits the parent's environment — or+ /// the minimal TS set for a depth-0 `create_session` root.#[allow(clippy::too_many_arguments)]pub(super) async fn create_child(&self,@@ -74,6 +80,7 @@ impl SupervisorChildSessionsInner {spawned_by_request_id: Option<&str>,runtime_metadata: Option<Value>,identity: &ParentIdentity,+ launch_env: Option<std::collections::BTreeMap<String, String>>,) -> Result<CreatedChild> {let mut config = json!({"cwd": cwd,@@ -136,7 +143,7 @@ impl SupervisorChildSessionsInner {runtime_metadata,lifecycle: Some(DaemonSessionLifecycle::Resident),env: None,- launch_env: None,+ launch_env,rest: Map::default(),};let summary = self@@ -162,6 +169,7 @@ impl SupervisorChildSessionsInner {session_dir: &Path,runtime_metadata: Option<Value>,identity: &ParentIdentity,+ launch_env: Option<std::collections::BTreeMap<String, String>>,) -> Result<CreatedChild> {let created = self.create_child(@@ -176,6 +184,7 @@ impl SupervisorChildSessionsInner {/*spawned_by_request_id*/ None,runtime_metadata,identity,+ launch_env,).await?;// A failed prompt tears the just-created session down (TS kills thediff --git a/crates/pa-daemon/src/scheduling_catalog.rs b/crates/pa-daemon/src/scheduling_catalog.rsindex cf5b100b13..03d7bb5170 100644--- a/crates/pa-daemon/src/scheduling_catalog.rs+++ b/crates/pa-daemon/src/scheduling_catalog.rs@@ -747,6 +747,8 @@ impl Supervisor {.insert("promotedOwnerClientId".to_string(), json!(owner));crate::descriptor::persist_worker(&resident.descriptor_path, &descriptor).map_err(|error| error.to_string())?;+ // The promotion clear (the TS `promoteOwnedWorker`).+ resident.clear_launch_env();Ok(())}// An already-promoted session stays promoted; a foreign ownerdiff --git a/crates/pa-daemon/src/supervisor/supervision.rs b/crates/pa-daemon/src/supervisor/supervision.rsindex fefc811a99..1b6fd49112 100644--- a/crates/pa-daemon/src/supervisor/supervision.rs+++ b/crates/pa-daemon/src/supervisor/supervision.rs@@ -52,6 +52,25 @@ pub(crate) struct SpawnedWorker {orphan_generation: OrphanGeneration,}+/// Compose the worker spawn env (TS `launchWorker`'s merged env,+/// `daemon-supervisor.ts`): the daemon's own process env stays the+/// inherited base, the client-forwarded launch env rides over it, and+/// the internal identity overrides ride over both — then `RLM_DEPTH`+/// never survives: a client may itself run inside an agent (its env+/// carries the recursion marker), and a worker that inherited it would+/// stamp every root session it creates with a stale depth (audit #9).+fn apply_worker_env(+ command: &mut Command,+ client_launch_env: Option<&std::collections::BTreeMap<String, String>>,+ internal_launch_env: std::collections::BTreeMap<String, String>,+) {+ if let Some(env) = client_launch_env {+ command.envs(env);+ }+ command.envs(internal_launch_env);+ command.env_remove("RLM_DEPTH");+}+impl SpawnedWorker {pub(crate) fn id(&self) -> Option<u32> {self.child.id()@@ -555,10 +574,16 @@ impl Supervisor {let stderr_log_path =crate::worker_stderr::log_path(&self.options.agent_dir, &resident.worker_id);let stderr_log = crate::worker_stderr::open_for_spawn(&stderr_log_path)?;+ // The client launch env travels from the resident (TS `launchEnv`).+ let client_launch_env = resident+ .launch_env+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone();let mut command = Command::new(&executable);+ command.arg("worker");+ apply_worker_env(&mut command, client_launch_env.as_ref(), launch_env);command- .arg("worker")- .envs(launch_env).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null())// The worker's stderr lands in its per-worker log (a detached supervisor has no@@ -991,3 +1016,84 @@ impl Supervisor {Ok(())}}++#[cfg(test)]+mod tests {+ use super::*;++ /// The spawn env precedence (TS `launchWorker`): the client's env+ /// rides over the inherited daemon base, the internal identity+ /// overrides ride over the client's env (a client-supplied worker+ /// token never wins), and `RLM_DEPTH` is an explicit removal even+ /// when the client forwarded one — the only removal, so the daemon's+ /// own env stays the inherited base.+ #[test]+ fn the_client_env_rides_under_the_internal_overrides() {+ let client = std::collections::BTreeMap::from([+ ("PA_MARKER".to_string(), "a-client".to_string()),+ ("RLM_DEPTH".to_string(), "3".to_string()),+ (+ crate::worker::WORKER_TOKEN_ENV.to_string(),+ "from-client".to_string(),+ ),+ ]);+ let internal = std::collections::BTreeMap::from([(+ crate::worker::WORKER_TOKEN_ENV.to_string(),+ "internal-token".to_string(),+ )]);+ let mut command = Command::new("x");+ apply_worker_env(&mut command, Some(&client), internal);+ let envs: std::collections::BTreeMap<&std::ffi::OsStr, Option<&std::ffi::OsStr>> =+ command.as_std().get_envs().collect();+ assert_eq!(+ envs.get(std::ffi::OsStr::new("PA_MARKER")),+ Some(&Some(std::ffi::OsStr::new("a-client"))),+ "the client env rides into the worker"+ );+ assert_eq!(+ envs.get(std::ffi::OsStr::new(crate::worker::WORKER_TOKEN_ENV)),+ Some(&Some(std::ffi::OsStr::new("internal-token"))),+ "the internal identity beats a client-supplied same key"+ );+ assert_eq!(+ envs.get(std::ffi::OsStr::new("RLM_DEPTH")),+ Some(&None),+ "a client-forwarded RLM_DEPTH is an explicit removal"+ );+ let removals: Vec<&std::ffi::OsStr> = envs+ .iter()+ .filter(|(_, value)| value.is_none())+ .map(|(key, _)| *key)+ .collect();+ assert_eq!(+ removals,+ vec![std::ffi::OsStr::new("RLM_DEPTH")],+ "RLM_DEPTH is the only removal: the daemon's own env stays inherited (the e2e's base-sentinel check proves the layer)"+ );+ }++ /// The recursion marker is stripped even with no client env at all+ /// (audit #9): a supervisor started inside an agent's shell spawns+ /// depth-0 workers.+ #[test]+ fn rlm_depth_is_stripped_without_a_client_env() {+ let internal = std::collections::BTreeMap::from([(+ crate::worker::WORKER_ROLE_ENV.to_string(),+ "1".to_string(),+ )]);+ let mut command = Command::new("x");+ apply_worker_env(&mut command, None, internal);+ let envs: std::collections::BTreeMap<&std::ffi::OsStr, Option<&std::ffi::OsStr>> =+ command.as_std().get_envs().collect();+ assert_eq!(+ envs.get(std::ffi::OsStr::new("RLM_DEPTH")),+ Some(&None),+ "RLM_DEPTH is stripped even with no launch env"+ );+ assert_eq!(+ envs.get(std::ffi::OsStr::new(crate::worker::WORKER_ROLE_ENV)),+ Some(&Some(std::ffi::OsStr::new("1"))),+ "the internal identity still rides"+ );+ }+}diff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rsindex 1ef8fa1be9..4b281a27d4 100644--- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs+++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs@@ -109,6 +109,7 @@ impl Supervisor {telemetry_disabled,runtime_metadata,env,+ launch_env,..} = createelse {@@ -125,6 +126,13 @@ impl Supervisor {.as_ref().map(crate::herdr::filter_client_env).filter(|env| !env.is_empty());+ // The client's launch env (TS `launchEnv`) re-filtered on receipt+ // (the socket peer is untrusted). In-memory only; the lifetime is+ // documented on the `ResidentWorker::launch_env` field.+ let client_launch_env = launch_env+ .clone()+ .map(pa_types::daemon::launch_env::collect_launch_env)+ .filter(|env| !env.is_empty());// The shutdown gate: a create dispatched while the supervisor is// stopping must never launch a worker the stop pass would miss (a// late create racing a shutdown would otherwise orphan its worker@@ -341,6 +349,8 @@ impl Supervisor {};let descriptor_path = self.descriptor_dir.join(format!("{worker_id}.json"));let resident = ResidentWorker::new(worker_id.clone(), descriptor, descriptor_path.clone());+ // TS stores `worker.launchEnv` before the spawn.+ resident.set_launch_env(client_launch_env);// Register the resident before spawning: the worker's boot self-registration must// find its identity in the registry (registration races the create replay).self.registry.insert(Arc::clone(&resident)).await;@@ -462,6 +472,11 @@ impl Supervisor {{let mut descriptor = resident.descriptor.lock().await;descriptor.lifecycle = DaemonWorkerLifecycle::Ready;+ // TS clears `launchEnv` at ready; an owned worker keeps it+ // for its recovery relaunch until ownership clears.+ if descriptor.owner_client_id.is_none() {+ resident.clear_launch_env();+ }descriptor.root_session_id = create_summary.get("sessionId").and_then(Value::as_str)diff --git a/crates/pa-daemon/tests/launch_env_e2e.rs b/crates/pa-daemon/tests/launch_env_e2e.rsnew file mode 100644index 0000000000..d7535d223a--- /dev/null+++ b/crates/pa-daemon/tests/launch_env_e2e.rs@@ -0,0 +1,662 @@+//! The client launch-env e2e (contract audit #1 + #9): the environment a+//! client forwards on its `create` reaches ITS session's worker process+//! (and the kernel under it) under the supervisor's internal identity+//! overrides; `RLM_DEPTH` never reaches a worker — not from the daemon's+//! own boot env, not from a client's forward (a daemon or client running+//! inside an agent must not stamp the new root's recursion identity);+//! one session's forwarded env never bleeds into another's worker; the+//! durable artifacts (descriptor, update-restart roster) never carry the+//! client env; and an `rlm.spawn` child inherits the parent worker's env.+// Pedantic-gate dispositions (fleet-uniform ruling; see kernel_dispose_e2e).+#![allow(clippy::large_futures)]+#![allow(clippy::too_many_lines)]+#![cfg(unix)]++use std::io::{BufRead, BufReader, Write};+use std::os::unix::net::UnixStream;+use std::path::{Path, PathBuf};+use std::process::{Child, Command, Stdio};+use std::time::{Duration, Instant};++use serde_json::{json, Value};++/// Remove one env var at scope end: a test that must run with a var in+/// its own process env (the parent-worker stand-in) restores the+/// process to its pre-test state (the supervisor tests'+/// save-and-restore pattern).+#[cfg(target_os = "linux")]+struct RemoveEnvVarAtDrop(&'static str);++#[cfg(target_os = "linux")]+impl Drop for RemoveEnvVarAtDrop {+ fn drop(&mut self) {+ std::env::remove_var(self.0);+ }+}++struct Daemon {+ child: Child,+}++impl Drop for Daemon {+ fn drop(&mut self) {+ let _ = self.child.kill();+ let _ = self.child.wait();+ }+}++/// The kernel Python (the same resolution the other kernel e2es use):+/// an explicit `PA_E2E_KERNEL_PYTHON`, else the machine's live install.+/// Skipped (with a note) on machines without one.+fn kernel_python() -> Option<PathBuf> {+ if let Some(explicit) = std::env::var_os("PA_E2E_KERNEL_PYTHON") {+ let explicit = PathBuf::from(explicit);+ assert!(+ explicit.exists(),+ "PA_E2E_KERNEL_PYTHON {} not found",+ explicit.display()+ );+ return Some(explicit);+ }+ let candidate = PathBuf::from(std::env::var("HOME").map_or_else(+ |_| "/home/ubuntu/.prime/agent/kernel-venv/bin/python".to_string(),+ |home| format!("{home}/.prime/agent/kernel-venv/bin/python"),+ ));+ if candidate.exists() {+ return Some(candidate);+ }+ eprintln!(+ "kernel python {} not found; skipping the launch-env kernel e2e",+ candidate.display()+ );+ None+}++/// Boot the real supervisor in the HOSTILE boot env (audit #9): the+/// daemon itself "runs inside an agent" (`RLM_DEPTH=1`) and has NEVER+/// seen the client's marker. `PA_MARKER` is scrubbed so the only path it+/// can ever take into a worker is the create's launch env.+fn spawn_supervisor(socket: &Path, agent_dir: &Path, kernel_python: Option<&Path>) -> Daemon {+ std::fs::create_dir_all(agent_dir).expect("agent dir");+ let log_file = std::fs::File::create(socket.with_extension("daemon.log")).expect("log file");+ let log_err = log_file.try_clone().expect("clone log file");+ let mut command = Command::new(env!("CARGO_BIN_EXE_pa-daemon"));+ command+ .arg("supervisor")+ .arg("--socket")+ .arg(socket)+ .arg("--agent-dir")+ .arg(agent_dir)+ .env("PRIME_AGENT_CODING_AGENT_DIR", agent_dir)+ .env_remove("PRIME_API_KEY")+ .env_remove("PA_MARKER")+ // THE HOSTILE BOOT CONTEXT (audit #9): a supervisor started from+ // inside an agent's shell. Every worker it spawns would inherit+ // the recursion marker without the spawn-time strip.+ .env("RLM_DEPTH", "1")+ // The daemon-base sentinel: a var only the daemon's own env+ // carries. It MUST still reach the workers (the inherited base+ // layer under the client env).+ .env("PA_DAEMON_BASE_SENTINEL", "daemon-boot")+ .stdout(Stdio::null())+ .stderr(Stdio::from(log_err));+ if let Some(kernel_python) = kernel_python {+ command.env("PRIME_AGENT_KERNEL_PYTHON", kernel_python);+ }+ // A supervisor killed at teardown must not leak its session workers+ // into later test binaries: the worker's supervisor-lost exit runs+ // on this short window instead of the 5-minute default.+ command.env(+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,+ "15000",+ );+ Daemon {+ child: command.spawn().expect("spawn pa-daemon supervisor"),+ }+}++fn wait_socket_ready(socket: &Path) {+ let deadline = Instant::now() + Duration::from_secs(15);+ loop {+ if UnixStream::connect(socket).is_ok() {+ return;+ }+ assert!(Instant::now() < deadline, "supervisor socket never came up");+ std::thread::sleep(Duration::from_millis(20));+ }+}++/// JSONL supervisor client (command envelopes, id-matched responses).+struct Client {+ reader: BufReader<UnixStream>,+ writer: UnixStream,+}++impl Client {+ fn connect(socket: &Path) -> (Self, Value) {+ let writer = UnixStream::connect(socket).expect("connect");+ let reader = BufReader::new(writer.try_clone().expect("clone"));+ let mut client = Self { reader, writer };+ let hello = client.read_line();+ (client, hello)+ }++ fn send_command(&mut self, id: &str, command: &Value) {+ let envelope = json!({+ "type": "command",+ "id": id,+ "protocol": {"name": "prime-agent.daemon", "version": 7},+ "command": command,+ });+ let mut line = serde_json::to_string(&envelope).expect("serialize");+ line.push('\n');+ self.writer.write_all(line.as_bytes()).expect("write");+ self.writer.flush().expect("flush");+ }++ fn read_line(&mut self) -> Value {+ let mut line = String::new();+ match self.reader.read_line(&mut line) {+ Ok(0) => panic!("daemon closed the socket"),+ Ok(_) => serde_json::from_str(line.trim()).expect("line json"),+ Err(error) => panic!("read failed: {error}"),+ }+ }++ fn read_response(&mut self, id: &str) -> Value {+ let deadline = Instant::now() + Duration::from_secs(60);+ loop {+ let line = self.read_line();+ if line.get("id").and_then(Value::as_str) == Some(id) {+ return line;+ }+ assert!(Instant::now() < deadline, "no response for {id}");+ }+ }++ fn request(&mut self, id: &str, command: &Value) -> Value {+ self.send_command(id, command);+ self.read_response(id)+ }+}++/// One scripted session on the supervisor: create with the given extra+/// create fields, then prompt its single turn and wait for idle.+fn create_session(+ client: &mut Client,+ dir: &Path,+ script: &Path,+ id: &str,+ extra: Value,+) -> (String, String) {+ let sessions_dir = dir.join("sessions");+ std::fs::create_dir_all(&sessions_dir).expect("sessions dir");+ let mut create = json!({+ "type": "create",+ "name": id,+ "config": {+ "cwd": dir.to_string_lossy(),+ "sessionDir": sessions_dir.to_string_lossy(),+ "script": script.to_string_lossy(),+ },+ });+ if let Value::Object(fields) = extra {+ for (key, value) in fields {+ create[key] = value;+ }+ }+ let created = client.request(&format!("create-{id}"), &create);+ assert_eq!(created["success"], true, "create {id} failed: {created}");+ let data = &created["data"];+ let session_id = data["activeSessionId"]+ .as_str()+ .or_else(|| data["id"].as_str())+ .expect("session id")+ .to_string();+ let session_file = data["sessionFile"]+ .as_str()+ .expect("session file")+ .to_string();+ (session_id, session_file)+}++fn run_one_turn(client: &mut Client, session_id: &str, id: &str) {+ let prompted = client.request(+ &format!("prompt-{id}"),+ &json!({ "type": "prompt_and_wait", "activeSessionId": session_id, "message": "run the turn" }),+ );+ assert_eq!(prompted["success"], true, "prompt {id} failed: {prompted}");+}++/// A plain one-text-turn script (no kernel).+fn write_plain_script(dir: &Path) -> PathBuf {+ let script = dir.join("plain-script.json");+ std::fs::write(+ &script,+ json!({ "responses": [ { "text": "turn done", "delayMs": 10 } ] }).to_string(),+ )+ .expect("write script");+ script+}++/// The pid of a live session worker, read from its on-disk descriptor+/// (written by the create path before the create response returns). A+/// descriptor that is not yet parseable, or whose pid is not a positive+/// number yet (a transitional rewrite), means "not yet": keep polling+/// until the deadline — never panic mid-write.+#[cfg(target_os = "linux")]+fn worker_pid(socket: &Path, agent_dir: &Path, active_session_id: &str) -> u32 {+ let descriptor_dir = pa_daemon::descriptor::descriptor_dir(agent_dir, socket);+ let descriptor_path = descriptor_dir.join(format!("{active_session_id}.json"));+ let deadline = Instant::now() + Duration::from_secs(10);+ loop {+ let pid = std::fs::read_to_string(&descriptor_path)+ .ok()+ .and_then(|bytes| serde_json::from_str::<Value>(&bytes).ok())+ .and_then(|descriptor| descriptor["pid"].as_u64())+ .filter(|pid| *pid > 0)+ .and_then(|pid| u32::try_from(pid).ok());+ if let Some(pid) = pid {+ return pid;+ }+ assert!(+ Instant::now() < deadline,+ "worker descriptor never appeared within 10s"+ );+ std::thread::sleep(Duration::from_millis(50));+ }+}++/// The raw NUL-separated environ bytes, one entry per line.+#[cfg(target_os = "linux")]+fn parse_environ(bytes: &[u8]) -> String {+ bytes+ .split(|byte| *byte == 0)+ .filter(|entry| !entry.is_empty())+ .map(|entry| String::from_utf8_lossy(entry).to_string())+ .collect::<Vec<_>>()+ .join("\n")+}++/// The raw environ of a live process.+#[cfg(target_os = "linux")]+fn proc_environ(pid: u32) -> String {+ parse_environ(&std::fs::read(format!("/proc/{pid}/environ")).expect("worker environ readable"))+}++/// The child descriptor's pid: the one descriptor whose session file+/// lives under the child's session dir. A descriptor that is not yet+/// parseable, or whose pid is missing or zero, means "not yet" — the+/// caller polls.+#[cfg(target_os = "linux")]+fn child_descriptor_pid(descriptor_dir: &Path, child_id: &str) -> Option<u32> {+ for entry in std::fs::read_dir(descriptor_dir).ok()?.flatten() {+ let Ok(bytes) = std::fs::read_to_string(entry.path()) else {+ continue;+ };+ let Ok(descriptor) = serde_json::from_str::<Value>(&bytes) else {+ continue;+ };+ if descriptor["sessionFile"]+ .as_str()+ .is_some_and(|file| file.contains(child_id))+ {+ if let Some(pid) = descriptor["pid"].as_u64().filter(|pid| *pid > 0) {+ return u32::try_from(pid).ok();+ }+ }+ }+ None+}++/// The `rlmDepth` of a session file's header line.+#[cfg(target_os = "linux")]+fn session_header_depth(session_file: &Path) -> u64 {+ let file = std::fs::File::open(session_file).expect("session file open");+ let mut first_line = String::new();+ std::io::BufRead::read_line(&mut std::io::BufReader::new(file), &mut first_line)+ .expect("header line");+ let header: Value = serde_json::from_str(first_line.trim()).expect("header json");+ header["rlmDepth"].as_u64().unwrap_or(0)+}++/// The client launch env travels only to the session it created: A's+/// worker runs in it, B's never sees it, the daemon's own env still+/// reaches both (the inherited base), `RLM_DEPTH` reaches NEITHER, the+/// workers stamp depth-0 root headers, and the durable descriptor for+/// A carries no trace of the client env.+#[cfg(target_os = "linux")] // /proc/<pid>/environ+#[test]+fn the_client_launch_env_reaches_only_its_own_worker() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("daemon.sock");+ let agent_dir = dir.path().join("agent");+ let script = write_plain_script(dir.path());+ let marker = format!("a-{}", uuid::Uuid::new_v4());+ let _daemon = spawn_supervisor(&socket, &agent_dir, None);+ wait_socket_ready(&socket);+ let (mut client, hello) = Client::connect(&socket);+ assert_eq!(hello["type"], "daemon_hello");++ // CREATE A: the client forwards its whole env (here: just the marker).+ let (session_a, file_a) = create_session(+ &mut client,+ dir.path(),+ &script,+ "a",+ json!({ "launchEnv": { "PA_MARKER": marker } }),+ );+ // CREATE B: no launch env at all.+ let (session_b, file_b) = create_session(&mut client, dir.path(), &script, "b", json!({}));++ let environ_a = proc_environ(worker_pid(&socket, &agent_dir, &session_a));+ let environ_b = proc_environ(worker_pid(&socket, &agent_dir, &session_b));++ // A's worker runs in the client's env (audit #1).+ assert!(+ environ_a.contains(&format!("PA_MARKER={marker}")),+ "session A's worker never received the client's launch env:\n{environ_a}"+ );+ // B's worker does NOT: one session's env never bleeds into another's.+ assert!(+ !environ_b.contains("PA_MARKER="),+ "session B's worker saw session A's client env:\n{environ_b}"+ );+ // The daemon-base var still reaches both (the inherited base layer).+ for (name, environ) in [("A", &environ_a), ("B", &environ_b)] {+ assert!(+ environ.contains("PA_DAEMON_BASE_SENTINEL=daemon-boot"),+ "session {name}'s worker lost the daemon's own env:\n{environ}"+ );+ // `RLM_DEPTH` never reaches a worker (audit #9): not from the+ // daemon's hostile boot env, not from any client forward.+ assert!(+ !environ.contains("RLM_DEPTH="),+ "session {name}'s worker inherited RLM_DEPTH:\n{environ}"+ );+ }++ // The recursion identity follows: a new root session is stamped+ // depth 0 even though the daemon itself "ran inside an agent".+ assert_eq!(+ session_header_depth(Path::new(&file_a)),+ 0,+ "session A's header is stamped with the daemon's RLM_DEPTH"+ );+ assert_eq!(+ session_header_depth(Path::new(&file_b)),+ 0,+ "session B's header is stamped with the daemon's RLM_DEPTH"+ );++ // The durable descriptor never carries the client env (TS parity:+ // `withoutSupervisorCreateFields` strips launchEnv from the durable+ // create command).+ let descriptor_dir = pa_daemon::descriptor::descriptor_dir(&agent_dir, &socket);+ let descriptor_bytes =+ std::fs::read_to_string(descriptor_dir.join(format!("{session_a}.json")))+ .expect("descriptor A");+ assert!(+ !descriptor_bytes.contains(&marker),+ "the worker descriptor leaked the client env"+ );+ let descriptor: Value = serde_json::from_str(&descriptor_bytes).expect("descriptor json");+ assert!(+ descriptor["createCommand"].get("launchEnv").is_none()+ && descriptor["createCommand"].get("launch_env").is_none(),+ "the durable create command carries a launch env"+ );+}++/// The kernel under the worker runs in the client's env too (the audit+/// #1 repro: `bash()`/kernel subprocesses see the terminal's PATH, not+/// the daemon's). One scripted cell writes its `os.environ` to a receipt.+#[test]+fn the_kernel_runs_in_the_client_launch_env() {+ let Some(kernel_python) = kernel_python() else {+ return;+ };+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("daemon.sock");+ let agent_dir = dir.path().join("agent");+ let marker = format!("a-{}", uuid::Uuid::new_v4());+ let receipt = dir.path().join("kernel-receipt.txt");+ // The cell records exactly the two vars the contract cares about.+ let cell = format!(+ "import os\nopen({receipt:?}, \"w\").write((os.environ.get(\"PA_MARKER\") or \"ABSENT\") + \"\\n\" + (os.environ.get(\"RLM_DEPTH\") or \"ABSENT\"))\nprint(\"cell done\")",+ receipt = receipt.to_string_lossy(),+ );+ let script = dir.path().join("kernel-script.json");+ std::fs::write(+ &script,+ json!({+ "engine": "faux",+ "responses": [+ { "content": [+ { "type": "toolCall", "name": "python_repl", "arguments": {+ "code": cell,+ } },+ ] },+ { "text": "done" },+ ],+ })+ .to_string(),+ )+ .expect("write faux script");+ let _daemon = spawn_supervisor(&socket, &agent_dir, Some(&kernel_python));+ wait_socket_ready(&socket);+ let (mut client, hello) = Client::connect(&socket);+ assert_eq!(hello["type"], "daemon_hello");++ let (session_a, _file_a) = create_session(+ &mut client,+ dir.path(),+ &script,+ "a",+ json!({ "launchEnv": { "PA_MARKER": marker } }),+ );+ run_one_turn(&mut client, &session_a, "a");++ // The receipt proves the kernel executed the cell (a skipped kernel+ // never writes it).+ let deadline = Instant::now() + Duration::from_secs(30);+ let content = loop {+ if let Ok(content) = std::fs::read_to_string(&receipt) {+ break content;+ }+ assert!(+ Instant::now() < deadline,+ "the kernel cell receipt never appeared at {}",+ receipt.display()+ );+ std::thread::sleep(Duration::from_millis(50));+ };+ assert_eq!(+ content,+ format!("{marker}\nABSENT"),+ "the kernel env must carry the client's marker and no RLM_DEPTH"+ );+ // The ran-proof (the skip gate must not be a hollow pass): the+ // receipt exists only because the live kernel executed the cell.+ eprintln!(+ "launch-env kernel e2e ran: kernel {} executed the cell, receipt={:?}",+ kernel_python.display(),+ content+ );+}++/// An `rlm.spawn` child is a separate worker process in the Rust port;+/// TS runs it in-process inside the parent worker. Parity: the child+/// create forwards the parent worker's own env (filtered), so the child+/// worker inherits it — while the parent's `RLM_DEPTH` never rides+/// along.+#[cfg(target_os = "linux")] // /proc/<pid>/environ+#[tokio::test]+async fn an_rlm_spawn_child_inherits_the_parent_worker_env() {+ use pa_core::session_engine::rlm_host::{RlmSpawnRequest, RlmSubagentHost};+ use pa_daemon::rlm_children::{ParentIdentity, SupervisorChildSessions};+ use pa_daemon::supervisor_link::SupervisorLink;++ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("daemon.sock");+ let agent_dir = dir.path().join("agent");+ let script = dir.path().join("child-script.json");+ std::fs::write(+ &script,+ json!({ "responses": [ { "text": "child answer", "delayMs": 30 } ] }).to_string(),+ )+ .expect("write script");+ let marker = format!("parent-worker-{}", uuid::Uuid::new_v4());+ let _daemon = spawn_supervisor(&socket, &agent_dir, None);+ wait_socket_ready(&socket);++ // The test process stands in for the parent worker: its env is what+ // the spawn arm forwards. The daemon itself was scrubbed of the+ // marker at boot, so the ONLY way the child can see it is the+ // spawn arm's forward. The var never leaks past this test: the+ // guard removes it at scope end.+ std::env::set_var("PA_MARKER", &marker);+ let _marker_guard = RemoveEnvVarAtDrop("PA_MARKER");+ let children = SupervisorChildSessions::new(+ std::sync::Arc::new(SupervisorLink::new(socket.clone())),+ agent_dir.clone(),+ "parent-active-id".to_string(),+ std::sync::Arc::new(pa_daemon::model_allowlist::ModelRefusalTelemetry::new(+ agent_dir.clone(),+ /*telemetry_disabled*/ true,+ )),+ );+ children.set_identity(ParentIdentity {+ rlm_depth: 0,+ rlm_max_depth: 2,+ model: Some("scripted/faux-1".to_string()),+ cwd: Some(agent_dir.to_string_lossy().to_string()),+ session_id: Some("parent-session-uuid".to_string()),+ session_file: Some(agent_dir.join("parent.jsonl").to_string_lossy().to_string()),+ thinking: None,+ child_script: Some(script.to_string_lossy().to_string()),+ });+ let handle = children+ .spawn(RlmSpawnRequest {+ prompt: "ship the lane".to_string(),+ name: Some("worker-a".to_string()),+ model: None,+ thinking: None,+ spawned_by_request_id: None,+ })+ .await+ .expect("spawn");+ // The child worker's env exists from its first exec: read it while+ // the worker is guaranteed alive — BEFORE the settle pass, after+ // which the child may passivate or exit (its pid can vanish from+ // /proc, and a mid-flight descriptor rewrite can read as pid-less).+ // A descriptor that is not yet parseable or pid-less, or a pid whose+ // /proc read fails, means "not yet": keep polling until the deadline,+ // never panic mid-transition.+ let descriptor_dir = pa_daemon::descriptor::descriptor_dir(&agent_dir, &socket);+ let deadline = Instant::now() + Duration::from_secs(15);+ let environ = loop {+ if let Some(pid) = child_descriptor_pid(&descriptor_dir, &handle.rlm_child_id) {+ if let Ok(bytes) = std::fs::read(format!("/proc/{pid}/environ")) {+ break parse_environ(&bytes);+ }+ }+ assert!(+ Instant::now() < deadline,+ "the child worker's env never became observable"+ );+ std::thread::sleep(Duration::from_millis(50));+ };+ assert!(+ environ.contains(&format!("PA_MARKER={marker}")),+ "the spawned child's worker never received the parent worker's env:\n{environ}"+ );+ // The supervisor itself "runs inside an agent" (the hostile boot+ // env): the child must not inherit that stale recursion marker.+ assert!(+ !environ.contains("RLM_DEPTH="),+ "the spawned child inherited the supervisor's RLM_DEPTH:\n{environ}"+ );+ // The registry sits outside a live worker turn here: release the+ // detached task prompt at the boundary the worker would signal (the+ // existing rlm-children e2e's contract), wait for the settle, and+ // clean the child up.+ children.notify_turn_done();+ let _ = children+ .collect(vec![handle.rlm_child_id.clone()], 5_000)+ .await;+ let _ = children.delete_subagent(handle.rlm_child_id.clone()).await;+}++/// The update-restart roster's `launch_env` rows respawn workers with the+/// supervisor's INTERNAL identity only: the client env a session was+/// created with never lands in the durable roster.+#[test]+fn the_update_roster_never_carries_the_client_env() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("daemon.sock");+ let agent_dir = dir.path().join("agent");+ let script = write_plain_script(dir.path());+ let marker = format!("roster-{}", uuid::Uuid::new_v4());+ let _daemon = spawn_supervisor(&socket, &agent_dir, None);+ wait_socket_ready(&socket);+ let (mut client, hello) = Client::connect(&socket);+ assert_eq!(hello["type"], "daemon_hello");+ let (session_a, _file_a) = create_session(+ &mut client,+ dir.path(),+ &script,+ "a",+ json!({ "launchEnv": { "PA_MARKER": marker } }),+ );+ run_one_turn(&mut client, &session_a, "a");++ // The prepare transaction snapshots every resident and writes the+ // roster (the same file a new binary revives workers from). The+ // update id stays disjoint from the marker: the marker's absence+ // must be about the env rows, not the id string.+ let prepared = client.request(+ "prepare",+ &json!({ "type": "prepare_update_restart", "updateId": format!("u-{}", uuid::Uuid::new_v4()) }),+ );+ assert_eq!(prepared["success"], true, "prepare failed: {prepared}");++ let restarts = agent_dir.join("update-restarts");+ let mut roster: Option<Value> = None;+ for entry in std::fs::read_dir(&restarts)+ .expect("update-restarts dir")+ .flatten()+ {+ let prepared_dir = entry.path().join("prepared");+ for update in std::fs::read_dir(&prepared_dir)+ .ok()+ .into_iter()+ .flatten()+ .flatten()+ {+ let bytes =+ std::fs::read_to_string(update.path().join("roster.json")).expect("roster.json");+ assert!(+ !bytes.contains(&marker),+ "the update roster leaked the client env:\n{bytes}"+ );+ roster = Some(serde_json::from_str(&bytes).expect("roster json"));+ }+ }+ let roster = roster.expect("the prepared roster file");+ for worker in roster["workers"].as_array().expect("worker rows") {+ let launch_env = worker["launch_env"].as_object().expect("launch_env row");+ // The row is the supervisor's internal identity only: the+ // client's marker key never lands in it (the raw-bytes check+ // above covers the value).+ assert!(+ !launch_env.contains_key("PA_MARKER"),+ "the roster row's launch env carries a client var: {worker}"+ );+ // And the row IS populated: the respawn env is really there.+ assert!(+ launch_env.contains_key(pa_daemon::worker::WORKER_TOKEN_ENV),+ "the roster row's launch env lost the internal identity: {worker}"+ );+ }+}diff --git a/crates/pa-tui/src/session_ui/sessions_fork.rs b/crates/pa-tui/src/session_ui/sessions_fork.rsindex 40e65847c7..cf4a266065 100644--- a/crates/pa-tui/src/session_ui/sessions_fork.rs+++ b/crates/pa-tui/src/session_ui/sessions_fork.rs@@ -513,6 +513,14 @@ pub(super) async fn create_session(let env = pa_types::daemon::herdr_env::collect_client_env(|key| std::env::var(key).ok());(!env.is_empty()).then_some(env)};+ // TS main.ts `launchEnv` (:1092): the client's own environment+ // travels on the create so the session's worker runs in the+ // environment of the terminal that opened it, not the daemon's+ // boot environment.+ let launch_env = {+ let env = pa_types::daemon::launch_env::collect_process_launch_env();+ (!env.is_empty()).then_some(env)+ };let data = match client.request_ok(DaemonCommand::Create {id: None,@@ -532,7 +540,7 @@ pub(super) async fn create_session(.then_some(DaemonSessionLifecycle::ClientOwned),// The client's Herdr pane identity travels on the create.env: client_env,- launch_env: None,+ launch_env,rest: Map::default(),}).awaitdiff --git a/crates/pa-types/src/daemon/launch_env.rs b/crates/pa-types/src/daemon/launch_env.rsnew file mode 100644index 0000000000..8155a825ba--- /dev/null+++ b/crates/pa-types/src/daemon/launch_env.rs@@ -0,0 +1,91 @@+//! The client launch-env wire contract (TS `collectDaemonLaunchEnv`,+//! `daemon-protocol.ts`): the environment a client forwards on a+//! session `create` — its whole process env minus the daemon-internal+//! vars.+//!+//! A session's worker runs as a separate process the supervisor spawns+//! with the daemon's own boot env; without this contract the session+//! would run in whatever environment the daemon booted in (the TS+//! port-parity gap): PATH changes, direnv, proxies, and certificate+//! paths from the terminal that opened the session would be lost.+//!+//! The trust model mirrors the Herdr client-env contract: any client+//! that can reach the user-scoped daemon socket can already run+//! commands through it, so the forwarded env crosses no privilege+//! boundary — but the daemon re-applies the same filter on receipt+//! (the socket peer is untrusted), and the daemon-internal+//! `PRIME_AGENT_INTERNAL_*` vars never ride the wire: a worker's+//! identity is stamped by the supervisor at spawn, never inherited+//! from a client, and a worker forwarding its own env to a spawned+//! child (the TS in-process-parity path) must not leak its internal+//! identity into it.++use std::collections::BTreeMap;++/// The daemon-internal env prefix (`PRIME_AGENT_INTERNAL_*`): the+/// supervisor's worker identity and protocol vars. Neither side of the+/// wire ever forwards them.+pub const INTERNAL_ENV_PREFIX: &str = "PRIME_AGENT_INTERNAL_";++/// Collect the launch env from a process-env-like source: everything+/// except the daemon-internal vars (the client side of the wire+/// contract). The daemon re-applies the same function to a received+/// map (the socket peer is untrusted): a forwarded map never carries+/// more than a client may legitimately forward.+#[must_use]+pub fn collect_launch_env(+ source: impl IntoIterator<Item = (String, String)>,+) -> BTreeMap<String, String> {+ source+ .into_iter()+ .filter(|(key, _)| !key.starts_with(INTERNAL_ENV_PREFIX))+ .collect()+}++/// Collect the launch env from THIS process's environment. Entries that+/// are not valid UTF-8 are skipped: the JSON wire cannot carry them,+/// and `std::env::vars` would panic on them.+#[must_use]+pub fn collect_process_launch_env() -> BTreeMap<String, String> {+ collect_launch_env(+ std::env::vars_os()+ .filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?))),+ )+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The client side forwards everything except the daemon-internal+ /// vars: no other var is special-cased (the whole point of the+ /// contract — PATH, proxies, credential paths ride along).+ #[test]+ fn the_client_collects_everything_but_the_internal_vars() {+ let env = collect_launch_env([+ ("PATH".to_string(), "/usr/bin".to_string()),+ ("SSL_CERT_FILE".to_string(), "/certs/ca.pem".to_string()),+ ("PA_MARKER".to_string(), "a-1".to_string()),+ (+ "PRIME_AGENT_INTERNAL_DAEMON_WORKER".to_string(),+ "1".to_string(),+ ),+ (+ "PRIME_AGENT_INTERNAL_DAEMON_WORKER_TOKEN".to_string(),+ "secret-token".to_string(),+ ),+ (+ "PRIME_AGENT_INTERNAL_".to_string(),+ "bare-prefix".to_string(),+ ),+ ]);+ assert_eq!(+ env,+ BTreeMap::from([+ ("PATH".to_string(), "/usr/bin".to_string()),+ ("SSL_CERT_FILE".to_string(), "/certs/ca.pem".to_string()),+ ("PA_MARKER".to_string(), "a-1".to_string()),+ ])+ );+ }+}diff --git a/crates/pa-types/src/daemon/mod.rs b/crates/pa-types/src/daemon/mod.rsindex 07d2fa9562..9349ee7b09 100644--- a/crates/pa-types/src/daemon/mod.rs+++ b/crates/pa-types/src/daemon/mod.rs@@ -97,6 +97,7 @@ pub mod agent_roster;mod command;pub mod framing;pub mod herdr_env;+pub mod launch_env;mod outbound;mod plane;pub mod update_flow;diff --git a/scripts/review_goal_backoff_parity.py b/scripts/review_goal_backoff_parity.pyindex fe5abbd638..6e2fcffa3e 100755--- a/scripts/review_goal_backoff_parity.py+++ b/scripts/review_goal_backoff_parity.py@@ -20,6 +20,9 @@ import tempfileimport threadingimport time+from review_agent_bounce_parity import Client+from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish+TS_ARCHIVE_SHA256 = "83fb09129bf78e3e60268212cd70932166591b15188caa70c1b0efbcc76235e2"TIMEOUT_SECONDS = 35@@ -75,8 +78,6 @@ class MockHandler(http.server.BaseHTTPRequestHandler):})if number >= MAX_REQUESTS:server.limit_hit = True- if server.process is not None:- os.killpg(server.process.pid, signal.SIGTERM)server.changed.notify_all()if server.scenario == "recover" and number == 2:@@ -115,7 +116,7 @@ class MockHandler(http.server.BaseHTTPRequestHandler):pass-def run_case(binary, label, scenario, base_dir):+def run_case(binary, label, scenario, base_dir, observation):home = base_dir / (label + "-" + scenario)home.mkdir()agent = home / "agent"@@ -147,6 +148,7 @@ def run_case(binary, label, scenario, base_dir):"PI_CODING_AGENT_DIR": str(agent), "PI_SESSION_DIR": str(sessions),"PRIME_AGENT_CODING_AGENT_DIR": str(agent),"PRIME_AGENT_SESSION_DIR": str(sessions)})+ env[TAG] = str(home.resolve())(home / "tmp").mkdir()goal_module = next((pathlib.Path(part) / "goal" / "__init__.py"for part in env.get("PYTHONPATH", "").split(os.pathsep)@@ -160,11 +162,20 @@ def run_case(binary, label, scenario, base_dir):}version = Noneif scenario == "control":- probe = subprocess.run([str(binary), "--version"], cwd=cwd, env=env,- text=True, capture_output=True, timeout=10, check=False)+ try:+ probe = subprocess.run([str(binary), "--version"], cwd=cwd, env=env,+ text=True, capture_output=True, timeout=10, check=False)+ except BaseException:+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)+ raiseversion = {"exit_code": probe.returncode, "stdout": probe.stdout.strip(),"stderr": probe.stderr.strip()}if probe.returncode != 0 or not probe.stdout.strip():+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)raise RuntimeError("--version failed: " + json.dumps(version))command = [str(binary), "--mode", "json", "--provider", "fixture", "--model","goal-fixture", "--no-session"]@@ -176,12 +187,39 @@ def run_case(binary, label, scenario, base_dir):stdout_path = home / "stdout.jsonl"stderr_path = home / "stderr.txt"started = time.monotonic()- with stdout_path.open("wb") as stdout, stderr_path.open("wb") as stderr:- process = subprocess.Popen(command, cwd=cwd, env=env, stdout=stdout, stderr=stderr,- start_new_session=True)- server.process = process- stopped = None- try:+ socket_path = home / 'd.sock'+ scope = OwnedProcesses(binary, home.resolve(), socket_path)+ daemon, client, process = None, None, None+ daemon_log = (home / 'daemon.log').open('wb')+ done = threading.Event()+ tracker_errors = []+ def discover():+ while not done.is_set():+ try:+ scope.discover()+ except Exception as error:+ tracker_errors.append(str(error))+ return+ done.wait(0.025)+ tracker = threading.Thread(target=discover, daemon=True)+ primary_error = None+ try:+ # TS JSON mode otherwise creates a detached daemon that outlives the CLI.+ # Supply the same daemon route with an explicitly owned supervisor/socket.+ if label == 'ts':+ daemon_command = [str(binary), '--mode', 'daemon', '--daemon-socket', str(socket_path)]+ daemon = subprocess.Popen(daemon_command, cwd=cwd, env=env, stdout=daemon_log,+ stderr=subprocess.STDOUT, start_new_session=True)+ scope.register(daemon, daemon_command)+ client = Client(socket_path, daemon)+ command += ['--daemon-socket', str(socket_path)]+ with stdout_path.open("wb") as stdout, stderr_path.open("wb") as stderr:+ process = subprocess.Popen(command, cwd=cwd, env=env, stdout=stdout, stderr=stderr,+ start_new_session=True)+ scope.register(process, command)+ server.process = process+ tracker.start()+ stopped = Nonewhile True:try:exit_code = process.wait(timeout=0.15)@@ -197,17 +235,37 @@ def run_case(binary, label, scenario, base_dir):elif count >= MAX_REQUESTS:stopped = "request_observation_limit"if stopped:- os.killpg(process.pid, signal.SIGTERM)+ scope.send(process.pid, signal.SIGTERM)try:exit_code = process.wait(timeout=2)except subprocess.TimeoutExpired:- os.killpg(process.pid, signal.SIGKILL)+ scope.send(process.pid, signal.SIGKILL)exit_code = process.wait(timeout=2)break- finally:- server.shutdown()- server.server_close()- thread.join(timeout=2)+ except BaseException as error:+ primary_error = error+ observation['primary_error'] = str(error)+ raise+ finally:+ done.set()+ if tracker.ident is not None:+ tracker.join(timeout=2)+ finish(scope, client, daemon, observation)+ observation['tracker_errors'] = tracker_errors+ observation['requests'] = server.requests+ for path, key, limit in ((stdout_path, 'stdout_tail', 3500), (stderr_path, 'stderr_tail', 2500)):+ if path.exists():+ observation[key] = path.read_text(errors='replace')[-limit:]+ daemon_log.close()+ observation['daemon_log_tail'] = (home / 'daemon.log').read_text(errors='replace')[-6000:]+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)+ if tracker_errors or tracker.is_alive():+ observation['cleanup_verified'] = False+ observation['cleanup_error'] = 'goal ownership tracker failed: ' + str(tracker_errors)+ if not observation['cleanup_verified'] and primary_error is None:+ raise AssertionError('goal fixture cleanup failed: ' + observation.get('cleanup_error', 'unknown'))raw = stdout_path.read_text(errors="replace")errors = stderr_path.read_text(errors="replace")@@ -245,7 +303,7 @@ def run_case(binary, label, scenario, base_dir):isinstance(block, dict) and block.get("type") == "text"and "Goal completed." in block.get("text", "") for block in content)- return {+ observation.update({"version_probe": version,"kernel_provenance": kernel_provenance if scenario == "control" else None,"exit_code": exit_code,@@ -267,7 +325,8 @@ def run_case(binary, label, scenario, base_dir):"cap_reason_seen": "Goal continuation cap reached: consecutive turns made no progress" in combined,"stderr_tail": errors[-2500:],"stdout_tail": raw[-3500:],- }+ })+ return observationdef main():@@ -295,13 +354,15 @@ def main():"binaries": {key: {"path": str(path), "sha256": sha256(path)}for key, path in paths.items()},"scenarios": {}, "differences": {}, "fixture_error": None}- with tempfile.TemporaryDirectory(prefix="goal-backoff-parity-") as temp:- base_dir = pathlib.Path(temp)+ temp = tempfile.TemporaryDirectory(prefix="goal-backoff-parity-")+ try:+ base_dir = pathlib.Path(temp.name)for scenario in ("control", "empty", "recover", "budget"):result["scenarios"][scenario] = {}for label, binary in paths.items():try:- result["scenarios"][scenario][label] = run_case(binary, label, scenario, base_dir)+ observation = result["scenarios"][scenario][label] = {}+ run_case(binary, label, scenario, base_dir, observation)except Exception as exc:result["fixture_error"] = "%s/%s: %s" % (scenario, label, exc)break@@ -321,14 +382,24 @@ def main():"model_completion_text_seen", "exit_code", "stopped")if ts[field] != rust[field]}+ finally:+ # Receipt persistence must survive cleanup failure; never suppress it or+ # retry deletion while a writer's lifetime has not been proved complete.+ try:+ temp.cleanup()+ except Exception as error:+ result['directory_cleanup_error'] = str(error)+ if result['fixture_error'] is None:+ result['fixture_error'] = 'directory cleanup: ' + str(error)all_runs = [run for versions in result["scenarios"].values() for run in versions.values()]result["observed_fields_equal"] = not any(result["differences"].values())result["validation_complete"] = (not result["fixture_error"] and len(all_runs) == 8- and all(run["request_count"] > 0 and run["stopped"] is None+ and all(run.get("request_count", 0) > 0 and run.get("stopped") is None+ and run.get("cleanup_verified") is Truefor run in all_runs))recovery = result["scenarios"].get("recover", {})result["recovery_confirmed"] = (len(recovery) == 2 and- all(run["confirmed_goal_complete"] for run in recovery.values()))+ all(run.get("confirmed_goal_complete", False) for run in recovery.values()))result["parity"] = (result["observed_fields_equal"] and result["validation_complete"]and result["recovery_confirmed"])result["requires_behavior_decision"] = not result["parity"]@@ -336,7 +407,7 @@ def main():print("goal parity receipt: %s" % args.receipt)for scenario, versions in result["scenarios"].items():print(scenario + ": " + ", ".join("%s requests=%s exit=%s stopped=%s" %- (label, run["request_count"], run["exit_code"], run["stopped"])+ (label, run.get("request_count"), run.get("exit_code"), run.get("stopped"))for label, run in versions.items()))if result["requires_behavior_decision"]:print("PARITY NOT CONFIRMED: inspect differences and incomplete observations in receipt")@@ -345,7 +416,7 @@ def main():if result["fixture_error"]:print(result["fixture_error"], file=sys.stderr)return 1- if any(run["request_count"] == 0 for versions in result["scenarios"].values()+ if any(run.get("request_count", 0) == 0 for versions in result["scenarios"].values()for run in versions.values()):print("a binary made no mock-provider request; inspect receipt", file=sys.stderr)return 1diff --git a/scripts/review_goal_fixture_lifecycle.py b/scripts/review_goal_fixture_lifecycle.pynew file mode 100644index 0000000000..b1716b592d--- /dev/null+++ b/scripts/review_goal_fixture_lifecycle.py@@ -0,0 +1,178 @@+"""Linux process ownership and cleanup for the offline goal CLI fixture."""+import json+import os+from pathlib import Path+import signal+import threading+import time++TAG = 'PA_GOAL_FIXTURE_ID'+++def process_identity(pid):+ stat = Path('/proc/%d/stat' % pid).read_text()+ fields = stat[stat.rfind(')') + 2:].split()+ return 'proc:' + fields[19], fields[0]+++def verify_worker(row, active, binary, socket_path):+ pid = row['pid']+ assert row.get('rootActiveSessionId') == active, 'wrong descriptor identity'+ assert row.get('supervisorSocketPath') == str(socket_path), 'wrong supervisor descriptor'+ command = Path('/proc/%d/cmdline' % pid).read_bytes().split(b'\0')+ assert command[0] == str(binary).encode(), 'worker argv0 is not fixture binary'+ env = dict(item.split(b'=', 1) for item in Path('/proc/%d/environ' % pid).read_bytes().split(b'\0') if b'=' in item)+ for key, value in {+ 'PRIME_AGENT_INTERNAL_DAEMON_WORKER': '1',+ 'PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID': active,+ 'PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET': str(socket_path),+ }.items():+ assert env.get(key.encode()) == value.encode(), 'wrong fixture worker env identity'+ worker_socket = str(row['socketPath']).encode()+ assert (worker_socket in command or env.get(b'PRIME_AGENT_INTERNAL_DAEMON_WORKER_SOCKET') == worker_socket), 'wrong worker socket identity'+ identity, state = process_identity(pid)+ assert row.get('processStartId') == identity and state != 'Z', 'wrong/reused worker PID'+ return pid, identity+++++class OwnedProcesses:+ def __init__(self, binary, root, socket_path):+ self.binary, self.root, self.socket_path = binary, root, socket_path+ self.direct = {}+ self.targets = {}+ self.errors = []++ def register(self, process, command):+ identity, state = process_identity(process.pid)+ assert state != 'Z', 'fixture process exited before identity capture'+ self.direct[process.pid] = (identity, [str(arg).encode() for arg in command])+ self.targets[process.pid] = identity++ def ownership(self, pid, identity):+ try:+ current, state = process_identity(pid)+ if current != identity or state == 'Z':+ return False+ env = dict(item.split(b'=', 1) for item in Path('/proc/%d/environ' % pid).read_bytes().split(b'\0') if b'=' in item)+ if env.get(TAG.encode()) != str(self.root).encode():+ return False+ command = Path('/proc/%d/cmdline' % pid).read_bytes().rstrip(b'\0').split(b'\0')+ if pid in self.direct:+ return self.direct[pid] == (identity, command)+ if command[0] == str(self.binary).encode():+ for path in (self.root / 'agent' / 'daemon-workers').rglob('*.json'):+ row = json.loads(path.read_text())+ if row.get('pid') == pid:+ return verify_worker(row, row['rootActiveSessionId'], self.binary, self.socket_path) == (pid, identity)+ return False+ # Kernels retain the owner PID supplied by the actual TS/Rust launcher.+ return ('python' in Path(command[0].decode()).name+ and env.get(b'PRIME_AGENT_KERNEL_OWNER_PID') in+ {str(owner).encode() for owner in self.targets})+ except (OSError, ValueError, KeyError, AssertionError, UnicodeError):+ return False++ def discover(self):+ # Capture verified workers before their kernels, including detached workers.+ for path in (self.root / 'agent' / 'daemon-workers').rglob('*.json'):+ try:+ row = json.loads(path.read_text())+ pid, identity = verify_worker(row, row['rootActiveSessionId'], self.binary, self.socket_path)+ if self.ownership(pid, identity):+ self.targets[pid] = identity+ except (OSError, ValueError, KeyError, AssertionError):+ pass # A partial/retired descriptor is not an ownership proof.+ for entry in Path('/proc').iterdir():+ if entry.name.isdigit():+ pid = int(entry.name)+ try:+ identity, _ = process_identity(pid)+ if self.ownership(pid, identity):+ self.targets[pid] = identity+ except OSError:+ pass++ def live(self):+ alive = []+ for pid, identity in list(self.targets.items()):+ try:+ current, state = process_identity(pid)+ if current == identity and state != 'Z':+ alive.append(pid)+ except FileNotFoundError:+ pass+ return alive++ def wait_gone(self, timeout):+ deadline = time.monotonic() + timeout+ while True:+ self.discover()+ alive = self.live()+ if not alive:+ return+ if time.monotonic() >= deadline:+ raise AssertionError('owned goal fixture processes remained: ' + str(alive))+ threading.Event().wait(0.025)++ def send(self, pid, signum):+ identity = self.targets[pid]+ try:+ fd = os.pidfd_open(pid)+ except ProcessLookupError:+ return False+ try:+ if not self.ownership(pid, identity):+ return False+ signal.pidfd_send_signal(fd, signum)+ return True+ except ProcessLookupError:+ return False+ finally:+ os.close(fd)+++def finish(scope, client, daemon, observation):+ """Fallback can reap leftovers but never converts failed shutdown into success."""+ observation['cleanup_verified'] = False+ try:+ scope.discover()+ if daemon is not None:+ assert client is not None, 'owned daemon cleanup client unavailable'+ client.call('shutdown', force=True)+ observation['shutdown_wire'] = client.wire+ client.close() # TS net.Server.close waits for raw fixture connections.+ daemon.wait(timeout=15)+ assert daemon.returncode == 0, 'owned goal daemon shutdown failed'+ scope.wait_gone(5)+ observation['cleanup_verified'] = True+ except Exception as error:+ observation['cleanup_error'] = str(error)+ observation['fallback_signals'] = []+ for signum, timeout in ((signal.SIGTERM, 3), (signal.SIGKILL, 2)):+ try:+ scope.discover()+ except Exception as discovery_error:+ scope.errors.append('fallback discovery failed: ' + str(discovery_error))+ for pid in scope.live():+ try:+ if scope.send(pid, signum):+ observation['fallback_signals'].append({'pid': pid, 'signal': signum.name})+ except OSError as signal_error:+ scope.errors.append(str(signal_error))+ try:+ scope.wait_gone(timeout)+ break+ except Exception as wait_error:+ scope.errors.append('fallback wait failed: ' + str(wait_error))+ observation['fallback_remaining'] = scope.live()+ observation['fallback_errors'] = scope.errors+ finally:+ if client is not None:+ try:+ client.close()+ except Exception as close_error:+ observation['cleanup_verified'] = False+ observation.setdefault('cleanup_error', str(close_error))+ observation['owned_process_identities'] = dict(scope.targets)diff --git a/scripts/review_launch_env_parity.py b/scripts/review_launch_env_parity.pynew file mode 100644index 0000000000..0ca674de52--- /dev/null+++ b/scripts/review_launch_env_parity.py@@ -0,0 +1,398 @@+#!/usr/bin/env python3+"""Actual daemon/kernel launch-env comparison; owned Linux CI processes only.++Exercises raw create wire (not TUI sender rendering), isolation, resident crash+recovery, owned recovery, promotion lifetime, and durable secret exclusion.+Requests/responses and actual provider tool results are retained. No ambient+credential is copied. Recovery kills only a descriptor- and cmdline-verified+worker belonging to this fixture, never a process found by name.+"""+import argparse+import http.server+import json+import os+from pathlib import Path+import signal+import subprocess+import sys+import tempfile+import threading+import time++from review_agent_bounce_parity import Client+from review_draft_disconnect_parity import digest, env_for, stop, TS_ARCHIVE_SHA256+from review_restore_notice_parity import texts++MARKER = 'LAUNCH_ENV_PARITY='+LIMIT = 35+CODE = """import os, json, subprocess, sys+keys = ('PA_ENV_MARKER', 'PA_ENV_BASE', 'PA_ENV_PRECEDENCE', 'PRIME_AGENT_INTERNAL_PARITY_CANARY')+result = {'env': {key: os.environ.get(key) for key in keys},+ 'child_marker': subprocess.check_output([sys.executable, '-c', "import os; print(os.environ.get('PA_ENV_MARKER', 'ABSENT'))"], text=True).strip()}+print('LAUNCH_ENV_PARITY=' + json.dumps(result))"""+++class Provider(http.server.ThreadingHTTPServer):+ daemon_threads = True++ def __init__(self):+ super().__init__(('127.0.0.1', 0), Handler)+ self.phase = None+ self.requests = {}+++class Handler(http.server.BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ 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'])))+ phase = self.server.phase+ requests = self.server.requests.setdefault(phase, [])+ requests.append(body)+ if len(requests) == 1:+ offered = {tool.get('function', {}).get('name') for tool in body.get('tools', [])}+ name = next((name for name in ('python_repl', 'ipython') if name in offered), None)+ if name is None:+ self.send_error(422, 'missing real REPL tool')+ return+ delta = {'tool_calls': [{'index': 0, 'id': 'launch_' + phase, 'type': 'function',+ 'function': {'name': name, 'arguments': json.dumps({'code': CODE})}}]}+ finish = 'tool_calls'+ else:+ delta, finish = {'content': 'Launch environment fixture complete.'}, 'stop'+ def chunk(delta, reason=None):+ return {'id': 'launch-env', 'object': 'chat.completion.chunk', 'created': 1,+ 'model': 'parity-1', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': reason}]}+ wire = ''.join('data: ' + json.dumps(row) + '\n\n' for row in (+ chunk({'role': 'assistant', **delta}), chunk({}, finish))) + 'data: [DONE]\n\n'+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream')+ self.send_header('Content-Length', str(len(wire.encode())))+ self.end_headers()+ self.wfile.write(wire.encode())+++def current_probe(requests, phase):+ assert len(requests) == 2, 'unexpected provider sequence'+ matches = [message for message in requests[-1]['messages'] if message.get('role') == 'tool'+ and message.get('tool_call_id') == 'launch_' + phase]+ assert len(matches) == 1, 'missing/duplicate current tool result'+ probes = [json.loads(line[len(MARKER):]) for text in texts(matches[0].get('content'))+ for line in text.splitlines() if line.startswith(MARKER)]+ assert len(probes) == 1, 'missing/duplicate current probe'+ return probes[0]+++def process_identity(pid):+ stat = Path('/proc/%d/stat' % pid).read_text()+ fields = stat[stat.rfind(')') + 2:].split()+ return 'proc:' + fields[19], fields[0]+++def worker_descriptor(agent, active, socket_path, deadline=None, previous=None):+ deadline = deadline or time.monotonic() + LIMIT+ while time.monotonic() < deadline:+ candidates = list((agent / 'daemon-workers').rglob('*.json'))+ for path in candidates:+ try:+ row = json.loads(path.read_text())+ pid = row.get('pid')+ if (row.get('rootActiveSessionId') == active+ and row.get('supervisorSocketPath') == str(socket_path)+ and isinstance(pid, int) and pid > 0 and pid != previous):+ return path, row+ except (OSError, ValueError):+ pass # Atomic/transitional descriptor writes are not readiness.+ threading.Event().wait(0.025)+ raise AssertionError('fixture worker descriptor never reached readiness')+++def verify_worker(row, active, binary, socket_path):+ pid = row['pid']+ assert row.get('rootActiveSessionId') == active, 'wrong descriptor identity'+ assert row.get('supervisorSocketPath') == str(socket_path), 'wrong supervisor descriptor'+ command = Path('/proc/%d/cmdline' % pid).read_bytes().split(b'\0')+ assert command[0] == str(binary).encode(), 'worker argv0 is not fixture binary'+ env = dict(item.split(b'=', 1) for item in Path('/proc/%d/environ' % pid).read_bytes().split(b'\0') if b'=' in item)+ for key, value in {+ 'PRIME_AGENT_INTERNAL_DAEMON_WORKER': '1',+ 'PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID': active,+ 'PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET': str(socket_path),+ }.items():+ assert env.get(key.encode()) == value.encode(), 'wrong fixture worker env identity'+ worker_socket = str(row['socketPath']).encode()+ assert (worker_socket in command or env.get(b'PRIME_AGENT_INTERNAL_DAEMON_WORKER_SOCKET') == worker_socket), 'wrong worker socket identity'+ identity, state = process_identity(pid)+ assert row.get('processStartId') == identity and state != 'Z', 'wrong/reused worker PID'+ return pid, identity+++def wait_gone(identities):+ deadline = time.monotonic() + LIMIT+ while time.monotonic() < deadline:+ alive = []+ for pid, identity in identities:+ try:+ current, state = process_identity(pid)+ if current == identity and state != 'Z':+ alive.append(pid)+ except FileNotFoundError:+ pass+ if not alive:+ return+ threading.Event().wait(0.025)+ raise AssertionError('owned fixture processes remained after shutdown: ' + str(alive))+++def restart(client, active, agent, binary, config, owned, observation, tracked, label, session_info):+ socket_path = agent.parent / 'd.sock'+ path, row = worker_descriptor(agent, active, socket_path)+ pid, identity = verify_worker(row, active, binary, socket_path)+ tracked.add((pid, identity))+ observation['killed_owned_worker_pid'] = pid+ os.kill(pid, signal.SIGKILL)+ wait_gone({(pid, identity)})+ if owned:+ # Observe the supervisor's death bookkeeping before the recovery action.+ deadline = time.monotonic() + LIMIT+ while time.monotonic() < deadline:+ try:+ changed = json.loads(path.read_text())+ if changed.get('pid') != pid or changed.get('lifecycle') != 'ready':+ break+ except (OSError, ValueError):+ pass+ threading.Event().wait(0.025)+ else:+ raise AssertionError('owner recovery never observed worker death')+ # Same owner context; refreshed attach launchEnv is deliberately out of scope.+ client.call('attach', activeSessionId=active, recoveryConfig=config)+ replacement_active = active+ if label == 'ts' and not owned:+ # Pinned TS recoverWorker (4236-4242) deliberately parks a resident+ # whose transient runtime/env were cleared at Ready. Rust instead+ # relaunches from its durable descriptor. Do not call those policies+ # equivalent: record the actual TS failed state, then explicitly reopen+ # the same file with fresh context and an empty client environment.+ deadline = time.monotonic() + LIMIT+ while time.monotonic() < deadline:+ try:+ failed = json.loads(path.read_text())+ if failed.get('lifecycle') == 'failed':+ assert failed.get('lastError') == 'Waiting for a client with fresh runtime context', failed.get('lastError')+ observation['parked_descriptor'] = failed+ break+ except (OSError, ValueError):+ pass+ threading.Event().wait(0.025)+ else:+ raise AssertionError('TS resident did not reach its fresh-context-required state')+ action = {'type': 'create', 'sessionPath': session_info['sessionFile'],+ 'config': config, 'lifecycle': 'resident', 'launchEnv': {}}+ observation['recovery_input'] = action+ created = client.call(action['type'], **{key: value for key, value in action.items() if key != 'type'})+ observation['recovery_create_response'] = created+ assert created['sessionId'] == session_info['sessionId'], 'TS fresh create changed durable session identity'+ assert created['sessionFile'] == session_info['sessionFile'], 'TS fresh create opened a different file'+ replacement_active = created.get('activeSessionId') or created.get('id')+ assert replacement_active, 'TS fresh create omitted active identity'+ observation['recovery_policy'] = 'TS parked after crash; explicit fresh-context create with empty launchEnv reopened the same durable session'+ elif not owned:+ observation['recovery_policy'] = 'Rust automatically relaunched from durable descriptor without retained client launchEnv'+ else:+ observation['recovery_policy'] = 'Owned recovery retained the original client launchEnv'+ new_path, new_row = worker_descriptor(agent, replacement_active, socket_path, previous=pid)+ if label != 'ts' or owned:+ assert new_path == path+ tracked.add(verify_worker(new_row, replacement_active, binary, socket_path))+ observation['replacement_worker_pid'] = new_row['pid']+ observation['replacement_active_session_id'] = replacement_active+ if not owned:+ client.call('attach', activeSessionId=replacement_active)+ state = client.call('get_state', activeSessionId=replacement_active)+ observation['replacement_state'] = state+ assert state['sessionId'] == session_info['sessionId'], 'recovery changed durable session identity'+ assert state['sessionFile'] == session_info['sessionFile'], 'recovery changed durable session file'+ return replacement_active+++def finish_daemon(client, process, kind, **payload):+ client.call(kind, **payload) # Successful acknowledgement is mandatory.+ client.close() # TS net.Server.close waits for every fixture client to end.+ process.wait(timeout=15)+ assert process.returncode == 0, 'supervisor did not shut down successfully'+++def comparable_probes(probes):+ # The ordinary client filters internal vars in both products. This raw-wire+ # injection additionally tests Rust's documented receive-side re-filter;+ # TS merges raw maps verbatim. Both actual values are asserted and retained.+ projected = json.loads(json.dumps(probes))+ for probe in projected.values():+ del probe['env']['PRIME_AGENT_INTERNAL_PARITY_CANARY']+ return projected+++def run_case(binary, label, root, observed):+ env = env_for(root, label)+ env.update(PA_ENV_BASE='daemon-base', PA_ENV_PRECEDENCE='daemon', RLM_DEPTH='3')+ library = Path(os.environ['PI_PACKAGE_DIR'])+ env['PYTHONPATH'] = os.pathsep.join(str(path) for path in sorted((library / 'skills').glob('*/src')))+ provider = Provider()+ thread = threading.Thread(target=provider.serve_forever, daemon=True)+ thread.start()+ models_path = root / 'agent/models.json'+ models = json.loads(models_path.read_text())+ models['providers']['parity-local']['baseUrl'] = 'http://127.0.0.1:%s/v1' % provider.server_port+ models_path.write_text(json.dumps(models))+ settings = root / 'agent/settings.json'+ settings.write_text(json.dumps({'prewarmPythonKernel': False, 'onboardingCompleted': True,+ 'telemetry': {'noticeShown': True}, 'defaultProvider': 'parity-local', 'defaultModel': 'parity-1'}))+ log = open(root / 'daemon.log', 'wb')+ process = subprocess.Popen([str(binary), '--mode', 'daemon', '--daemon-socket', str(root / 'd.sock')],+ cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)+ client = None+ probes = observed['probes'] = {}+ session_info = {}+ tracked = set()+ secret = 'fixture-launch-secret'+ prepared_transaction = False+ primary_error = None+ config = {'cwd': str(root), 'agentDir': str(root / 'agent'), 'provider': 'parity-local',+ 'model': 'parity-1', 'noExtensions': True, 'noContextFiles': True, 'telemetryDisabled': True}+ launch = {'PA_ENV_MARKER': secret, 'PA_ENV_PRECEDENCE': 'client', 'RLM_DEPTH': '9',+ 'PRIME_AGENT_INTERNAL_PARITY_CANARY': 'must-not-inherit'}+ def create(name, lifecycle, forwarded):+ row = client.call('create', name=name, lifecycle=lifecycle, config=config, **forwarded)+ active = row.get('activeSessionId') or row.get('id')+ assert active+ header = json.loads(Path(row['sessionFile']).read_text().splitlines()[0])+ assert header.get('rlmDepth', 0) == 0, header+ session_info[name] = {'sessionId': header['id'], 'sessionFile': row['sessionFile']}+ assert row['sessionId'] == header['id'], 'create response/file identity mismatch'+ client.call('attach', activeSessionId=active)+ _, descriptor = worker_descriptor(root / 'agent', active, root / 'd.sock')+ tracked.add(verify_worker(descriptor, active, binary, root / 'd.sock'))+ return active+ def probe(active, phase, expected_marker, expected_precedence):+ provider.phase = phase+ client.call('prompt_and_wait', activeSessionId=active, message='Probe ' + phase)+ result = current_probe(provider.requests[phase], phase)+ expected = {'env': {'PA_ENV_MARKER': expected_marker, 'PA_ENV_BASE': 'daemon-base',+ 'PA_ENV_PRECEDENCE': expected_precedence, 'PRIME_AGENT_INTERNAL_PARITY_CANARY':+ 'must-not-inherit' if label == 'ts' and expected_marker is not None else None},+ 'child_marker': expected_marker or 'ABSENT'}+ assert result == expected, (phase, result, expected)+ probes[phase] = result+ try:+ client = Client(root / 'd.sock', process)+ a = create('launch-a', 'resident', {'launchEnv': launch})+ b = create('launch-b', 'resident', {})+ probe(a, 'resident_initial', secret, 'client')+ probe(b, 'isolated_other', None, 'daemon')+ observed['resident_recovery'] = {}+ a = restart(client, a, root / 'agent', binary, config, False, observed['resident_recovery'], tracked, label, session_info['launch-a'])+ probe(a, 'resident_recovered', None, 'daemon')+ owner = create('launch-owned', 'client_owned', {'launchEnv': launch})+ probe(owner, 'owned_initial', secret, 'client')+ observed['owned_recovery'] = {}+ owner = restart(client, owner, root / 'agent', binary, config, True, observed['owned_recovery'], tracked, label, session_info['launch-owned'])+ probe(owner, 'owned_recovered', secret, 'client')+ client.call('promote_owned_session', activeSessionId=owner)+ observed['promoted_recovery'] = {}+ owner = restart(client, owner, root / 'agent', binary, config, False, observed['promoted_recovery'], tracked, label, session_info['launch-owned'])+ probe(owner, 'promoted_recovered', None, 'daemon')+ descriptors = list((root / 'agent/daemon-workers').rglob('*.json'))+ assert len(descriptors) >= 3, 'durable descriptor audit would be empty'+ for path in descriptors:+ assert secret not in path.read_text(), 'launch secret leaked into durable worker metadata'+ observed['durable_launch_secret_absent'] = True+ prepared = client.call('prepare_update_restart', updateId='launch-env-parity')+ prepared_transaction = True+ observed['prepare_update'] = prepared+ if label == 'rust':+ assert prepared.get('state') == 'prepared', 'update did not prepare'+ rosters = list((root / 'agent/update-restarts').glob('*/prepared/launch-env-parity/roster.json'))+ assert len(rosters) == 1, 'actual prepared Rust roster missing/ambiguous'+ roster = json.loads(rosters[0].read_text())+ assert len(roster['workers']) == 3, 'prepared roster omitted fixture workers'+ else:+ roster = prepared+ assert len(roster['sessions']) == 3, 'prepared manifest omitted fixture sessions'+ assert secret not in json.dumps(roster), 'launch secret leaked into actual update roster'+ observed['update_roster'] = roster+ except BaseException as error:+ primary_error = error+ observed['primary_error'] = str(error)+ raise+ finally:+ observed['requests'] = provider.requests+ cleanup_error = None+ try:+ if client:+ observed['wire'] = client.wire+ if process.poll() is None:+ if label == 'rust' and prepared_transaction:+ finish_daemon(client, process, 'commit_update_restart', updateId='launch-env-parity')+ else:+ finish_daemon(client, process, 'shutdown', force=True)+ assert process.returncode == 0, 'supervisor did not shut down successfully'+ wait_gone(tracked)+ observed['cleanup_verified'] = True+ else:+ raise AssertionError('fixture supervisor did not establish cleanup control')+ except Exception as error:+ cleanup_error = error+ observed['cleanup_error'] = str(error)+ finally:+ if client:+ client.close()+ stop(process)+ log.close()+ observed['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')[-6000:]+ provider.shutdown()+ provider.server_close()+ thread.join(timeout=2)+ if cleanup_error and primary_error is None:+ raise AssertionError('fixture cleanup failed: ' + str(cleanup_error)) from cleanup_error+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--receipt', type=Path, required=True)+ args = parser.parse_args()+ receipt = {'verified': False, 'runs': {}, 'scope': 'Raw daemon create, actual REPL/subprocess env, '+ 'env clearing/retention and durable launch-env secret exclusion. TS residents require explicit fresh-context reopen; Rust auto-relaunches. No recovery-policy equivalence claim.',+ 'not_verified': ['TUI/ACP sender env collection', 'refreshed attach launchEnv recovery',+ 'rlm.spawn and minimal depth-0 root forwarding', 'automatic resident/promotion recovery parity (actual policies differ)'],+ 'intentional_difference': 'Rust re-filters raw launchEnv internal-prefixed keys; TS trusts sender filtering and merges the injected canary. Exact canary values asserted per phase; raw results retained. Separately, TS parks crashed residents requiring fresh create context, whereas Rust relaunches automatically; exact parked states, explicit fresh-create inputs and durable identity proofs retained.',+ 'normalization': 'Generated session IDs, roots, worker PIDs and timestamps excluded only from cross-run comparison; raw wire retained.'}+ try:+ assert sys.platform == 'linux', 'requires hosted Linux /proc ownership checks'+ assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256, 'TS archive mismatch'+ receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256+ with tempfile.TemporaryDirectory(prefix='launch-env-parity-', dir='/tmp') as folder:+ for label in ('ts', 'rust'):+ binary = Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()+ run = receipt['runs'][label] = {'binary_sha256': digest(binary)}+ try:+ run_case(binary, label, Path(folder) / label, run)+ except Exception as error:+ run['error'] = str(error)+ assert all('error' not in run for run in receipt['runs'].values()), receipt['runs']+ assert comparable_probes(receipt['runs']['ts']['probes']) == comparable_probes(receipt['runs']['rust']['probes']), 'environment behavior differs'+ receipt['verified'] = True+ except Exception as error:+ receipt['error'] = str(error)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(receipt, indent=2) + '\n')+ print(json.dumps({'verified': receipt['verified'], 'receipt': str(args.receipt), 'error': receipt.get('error')}))+ return 0 if receipt['verified'] else 1+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/test_review_goal_backoff_parity.py b/scripts/test_review_goal_backoff_parity.pynew file mode 100644index 0000000000..2281a182f0--- /dev/null+++ b/scripts/test_review_goal_backoff_parity.py@@ -0,0 +1,113 @@+"""Mocked ownership/cleanup guards; no product binaries or kernels are started."""+import json+from pathlib import Path+import signal+import tempfile+import unittest+from unittest.mock import Mock, patch++import review_goal_backoff_parity as goal+import review_goal_fixture_lifecycle as lifecycle+++class CleanupTests(unittest.TestCase):+ def test_ack_then_close_then_exit_then_owned_absence(self):+ order = []+ scope, client, daemon = Mock(), Mock(), Mock(returncode=0)+ client.call.side_effect = lambda *_args, **_kwargs: order.append('ack')+ client.close.side_effect = lambda: order.append('close')+ daemon.wait.side_effect = lambda **_kwargs: order.append('exit')+ scope.wait_gone.side_effect = lambda *_args: order.append('absent')+ scope.targets = {}+ observation = {}+ lifecycle.finish(scope, client, daemon, observation)+ self.assertEqual(order[:4], ['ack', 'close', 'exit', 'absent'])+ self.assertTrue(observation['cleanup_verified'])+ scope.send.assert_not_called()++ def test_successful_fallback_keeps_shutdown_failure_red(self):+ scope, client, daemon = Mock(), Mock(), Mock()+ client.call.side_effect = TimeoutError('shutdown ack missing')+ scope.live.side_effect = [[12], []]+ scope.send.return_value = True+ scope.targets, scope.errors = {12: 'proc:4'}, []+ observation = {}+ lifecycle.finish(scope, client, daemon, observation)+ self.assertFalse(observation['cleanup_verified'])+ self.assertEqual(observation['cleanup_error'], 'shutdown ack missing')+ self.assertEqual(observation['fallback_signals'], [{'pid': 12, 'signal': 'SIGTERM'}])+ self.assertEqual(observation['fallback_remaining'], [])++ def test_reused_pid_is_never_signaled(self):+ scope = lifecycle.OwnedProcesses(Path('/fixture/bin'), Path('/fixture'), Path('/fixture/d.sock'))+ scope.targets[12] = 'proc:4'+ with patch.object(lifecycle.os, 'pidfd_open', return_value=9, create=True), \+ patch.object(lifecycle.os, 'close') as close, \+ patch.object(lifecycle.signal, 'pidfd_send_signal', create=True) as send, \+ patch.object(scope, 'ownership', return_value=False):+ self.assertFalse(scope.send(12, signal.SIGKILL))+ send.assert_not_called()+ close.assert_called_once_with(9)++ def test_pidfd_pins_signal_after_validation(self):+ scope = lifecycle.OwnedProcesses(Path('/fixture/bin'), Path('/fixture'), Path('/fixture/d.sock'))+ scope.targets[12] = 'proc:4'+ with patch.object(lifecycle.os, 'pidfd_open', return_value=9, create=True), \+ patch.object(lifecycle.os, 'close'), \+ patch.object(lifecycle.signal, 'pidfd_send_signal', create=True) as send, \+ patch.object(scope, 'ownership', return_value=True) as ownership:+ self.assertTrue(scope.send(12, signal.SIGTERM))+ ownership.assert_called_once_with(12, 'proc:4')+ send.assert_called_once_with(9, signal.SIGTERM)++ def test_foreign_fixture_tag_never_owned(self):+ scope = lifecycle.OwnedProcesses(Path('/fixture/bin'), Path('/fixture'), Path('/fixture/d.sock'))+ scope.direct[12] = ('proc:4', [b'/fixture/bin'])+ with patch.object(lifecycle, 'process_identity', return_value=('proc:4', 'S')), \+ patch.object(Path, 'read_bytes', return_value=b'PA_GOAL_FIXTURE_ID=/foreign\0'):+ self.assertFalse(scope.ownership(12, 'proc:4'))++ def test_same_tag_different_direct_argv_never_owned(self):+ scope = lifecycle.OwnedProcesses(Path('/fixture/bin'), Path('/fixture'), Path('/fixture/d.sock'))+ scope.direct[12] = ('proc:4', [b'/fixture/bin', b'--mode', b'daemon'])+ with patch.object(lifecycle, 'process_identity', return_value=('proc:4', 'S')), \+ patch.object(Path, 'read_bytes', side_effect=[b'PA_GOAL_FIXTURE_ID=/fixture\0', b'/fixture/bin\0different\0']):+ self.assertFalse(scope.ownership(12, 'proc:4'))++ def test_kernel_requires_verified_owner(self):+ scope = lifecycle.OwnedProcesses(Path('/fixture/bin'), Path('/fixture'), Path('/fixture/d.sock'))+ scope.targets = {12: 'proc:4'}+ for owner, expected in ((12, True), (99, False)):+ with patch.object(lifecycle, 'process_identity', return_value=('proc:8', 'S')), \+ patch.object(Path, 'read_bytes', side_effect=[+ ('PA_GOAL_FIXTURE_ID=/fixture\0PRIME_AGENT_KERNEL_OWNER_PID=%s\0' % owner).encode(), b'/usr/bin/python3\0kernel\0']):+ self.assertEqual(scope.ownership(20, 'proc:8'), expected)++ def test_receipt_survives_directory_cleanup_failure_and_primary_error(self):+ with tempfile.TemporaryDirectory() as temp:+ receipt = Path(temp) / 'receipt.json'+ fake_dir = Mock(name='temporary directory')+ fake_dir.name = temp+ fake_dir.cleanup.side_effect = OSError('Directory not empty')+ def run(_binary, _label, _scenario, _base_dir, observation):+ observation['primary_error'] = 'original probe failure'+ raise AssertionError('original probe failure')+ with patch.object(goal.sys, 'argv', ['fixture', '--receipt', str(receipt)]), \+ patch.object(goal.sys, 'platform', 'linux'), \+ patch.dict(goal.os.environ, {'PA_TS_BINARY': '/fake/ts', 'PA_RUST_BINARY': '/fake/rust', 'PA_TS_ARCHIVE': '/fake/archive'}), \+ patch.object(Path, 'is_file', return_value=True), \+ patch.object(goal.os, 'access', return_value=True), \+ patch.object(goal, 'sha256', return_value=goal.TS_ARCHIVE_SHA256), \+ patch.object(goal.tempfile, 'TemporaryDirectory', return_value=fake_dir), \+ patch.object(goal, 'run_case', side_effect=run):+ self.assertEqual(goal.main(), 1)+ result = json.loads(receipt.read_text())+ self.assertIn('original probe failure', result['fixture_error'])+ self.assertEqual(result['directory_cleanup_error'], 'Directory not empty')+ self.assertFalse(result['validation_complete'])+ self.assertFalse(result['parity'])+ fake_dir.cleanup.assert_called_once()+++if __name__ == '__main__':+ unittest.main()diff --git a/scripts/test_review_launch_env_parity.py b/scripts/test_review_launch_env_parity.pynew file mode 100644index 0000000000..1c29eb4061--- /dev/null+++ b/scripts/test_review_launch_env_parity.py@@ -0,0 +1,150 @@+#!/usr/bin/env python3+"""Reject stale result success and killing an unowned process in the verifier."""+import json+from pathlib import Path+import unittest+import tempfile+from unittest.mock import patch, MagicMock+from review_launch_env_parity import current_probe, restart, verify_worker, worker_descriptor, finish_daemon, comparable_probes, MARKER+++def requests(content=None):+ messages = [{'role': 'tool', 'tool_call_id': 'launch_old', 'content': MARKER + '{"old":true}'}]+ if content is not None:+ messages.append({'role': 'tool', 'tool_call_id': 'launch_new', 'content': content})+ return [{}, {'messages': messages}]+++class VerifierTests(unittest.TestCase):+ def test_only_current_result_counts(self):+ self.assertEqual(current_probe(requests(MARKER + '{"new":true}'), 'new'), {'new': True})++ def test_old_result_cannot_hide_failed_cell(self):+ with self.assertRaisesRegex(AssertionError, 'current probe'):+ current_probe(requests('Traceback: failed current cell'), 'new')++ def test_old_result_cannot_hide_missing_result(self):+ with self.assertRaisesRegex(AssertionError, 'current tool result'):+ current_probe(requests(), 'new')++ def test_duplicate_current_probe_is_failure(self):+ content = MARKER + '{}\n' + MARKER + '{}'+ with self.assertRaisesRegex(AssertionError, 'current probe'):+ current_probe(requests(content), 'new')++ def test_descriptor_with_wrong_identity_never_kills(self):+ with patch('review_launch_env_parity.worker_descriptor', return_value=(Path('/fixture'),+ {'pid': 123, 'rootActiveSessionId': 'someone-else'})), patch('os.kill') as kill:+ with self.assertRaisesRegex(AssertionError, 'descriptor identity'):+ restart(None, 'fixture', Path('/fixture'), Path('/fixture/binary'), {}, False, {}, set(), 'rust', {})+ kill.assert_not_called()++ def test_wrong_executable_never_kills(self):+ with patch('review_launch_env_parity.worker_descriptor', return_value=(Path('/fixture'),+ {'pid': 123, 'rootActiveSessionId': 'fixture', 'supervisorSocketPath': '/d.sock'})), \+ patch('pathlib.Path.read_bytes', return_value=b'/other/binary\0worker\0'), patch('os.kill') as kill:+ with self.assertRaisesRegex(AssertionError, 'fixture binary'):+ restart(None, 'fixture', Path('/fixture'), Path('/fixture/binary'), {}, False, {}, set(), 'rust', {})+ kill.assert_not_called()++ def test_ts_descriptor_filename_need_not_equal_active_id(self):+ with tempfile.TemporaryDirectory() as folder:+ agent = Path(folder)+ descriptors = agent / 'daemon-workers' / 'fixture'+ descriptors.mkdir(parents=True)+ row = {'pid': 123, 'rootActiveSessionId': 'active-id', 'supervisorSocketPath': '/fixture.sock'}+ path = descriptors / 'different-worker-id.json'+ path.write_text(json.dumps(row))+ self.assertEqual(worker_descriptor(agent, 'active-id', Path('/fixture.sock')), (path, row))++ def test_ts_and_rust_worker_socket_seams_are_both_checked(self):+ row = {'pid': 123, 'rootActiveSessionId': 'fixture', 'supervisorSocketPath': '/fixture/d.sock',+ 'socketPath': '/fixture/worker.sock', 'processStartId': 'proc:456'}+ env = b'PRIME_AGENT_INTERNAL_DAEMON_WORKER=1\0PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID=fixture\0PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET=/fixture/d.sock\0'+ for command, extra in [+ (b'/fixture/binary\0--mode\0daemon\0--daemon-socket\0/fixture/worker.sock\0', b''),+ (b'/fixture/binary\0worker\0', b'PRIME_AGENT_INTERNAL_DAEMON_WORKER_SOCKET=/fixture/worker.sock\0'),+ ]:+ with patch('pathlib.Path.read_bytes', side_effect=[command, env + extra]), \+ patch('review_launch_env_parity.process_identity', return_value=('proc:456', 'S')):+ self.assertEqual(verify_worker(row, 'fixture', Path('/fixture/binary'), Path('/fixture/d.sock')), (123, 'proc:456'))++ def test_reused_pid_is_rejected(self):+ row = {'pid': 123, 'rootActiveSessionId': 'fixture', 'supervisorSocketPath': '/fixture/d.sock',+ 'socketPath': '/fixture/worker.sock', 'processStartId': 'proc:old'}+ command = b'/fixture/binary\0--mode\0daemon\0/fixture/worker.sock\0'+ env = b'PRIME_AGENT_INTERNAL_DAEMON_WORKER=1\0PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID=fixture\0PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET=/fixture/d.sock\0'+ with patch('pathlib.Path.read_bytes', side_effect=[command, env]), \+ patch('review_launch_env_parity.process_identity', return_value=('proc:new', 'S')):+ with self.assertRaisesRegex(AssertionError, 'reused worker PID'):+ verify_worker(row, 'fixture', Path('/fixture/binary'), Path('/fixture/d.sock'))++ def test_shutdown_ack_then_close_then_process_exit(self):+ events = []+ client, process = MagicMock(), MagicMock(returncode=0)+ client.call.side_effect = lambda *a, **k: events.append('ack')+ client.close.side_effect = lambda: events.append('client_closed')+ process.wait.side_effect = lambda **k: events.append('process_exit')+ finish_daemon(client, process, 'shutdown', force=True)+ self.assertEqual(events, ['ack', 'client_closed', 'process_exit'])++ def test_refused_shutdown_cannot_be_cleanup_success(self):+ client, process = MagicMock(), MagicMock(returncode=0)+ client.call.side_effect = AssertionError('refused')+ with self.assertRaisesRegex(AssertionError, 'refused'):+ finish_daemon(client, process, 'shutdown', force=True)+ process.wait.assert_not_called()++ def test_known_filter_difference_does_not_hide_other_env_difference(self):+ ts = {'phase': {'env': {'PA_ENV_MARKER': 'same', 'PRIME_AGENT_INTERNAL_PARITY_CANARY': 'injected'}}}+ rust = {'phase': {'env': {'PA_ENV_MARKER': 'same', 'PRIME_AGENT_INTERNAL_PARITY_CANARY': None}}}+ self.assertEqual(comparable_probes(ts), comparable_probes(rust))+ rust['phase']['env']['PA_ENV_MARKER'] = 'wrong'+ self.assertNotEqual(comparable_probes(ts), comparable_probes(rust))+ self.assertEqual(ts['phase']['env']['PRIME_AGENT_INTERNAL_PARITY_CANARY'], 'injected')++ def test_ts_resident_reopens_exact_file_with_empty_fresh_context(self):+ with tempfile.TemporaryDirectory() as folder:+ root = Path(folder)+ path = root / 'descriptor.json'+ failed = {'pid': 123, 'rootActiveSessionId': 'old-active', 'lifecycle': 'failed',+ 'lastError': 'Waiting for a client with fresh runtime context'}+ path.write_text(json.dumps(failed))+ session = {'sessionId': 'durable-id', 'sessionFile': str(root / 'session.jsonl')}+ created = {**session, 'activeSessionId': 'new-active'}+ client = MagicMock()+ client.call.side_effect = lambda kind, **data: created if kind == 'create' else session+ observed = {}+ with patch('review_launch_env_parity.worker_descriptor', side_effect=[(path, failed), (root / 'new-descriptor.json', {'pid': 456})]), \+ patch('review_launch_env_parity.verify_worker', side_effect=[(123, 'proc:old'), (456, 'proc:new')]), \+ patch('review_launch_env_parity.wait_gone'), patch('os.kill'):+ active = restart(client, 'old-active', root / 'agent', root / 'binary', {'cwd': str(root)},+ False, observed, set(), 'ts', session)+ self.assertEqual(active, 'new-active')+ self.assertEqual(observed['parked_descriptor'], failed)+ create = [call for call in client.call.call_args_list if call.args == ('create',)]+ self.assertEqual(len(create), 1)+ self.assertEqual(create[0].kwargs['sessionPath'], session['sessionFile'])+ self.assertEqual(create[0].kwargs['launchEnv'], {})+ self.assertEqual(observed['replacement_state'], session)++ def test_ts_fresh_create_cannot_switch_durable_identity(self):+ with tempfile.TemporaryDirectory() as folder:+ root = Path(folder)+ path = root / 'descriptor.json'+ failed = {'pid': 123, 'rootActiveSessionId': 'old-active', 'lifecycle': 'failed',+ 'lastError': 'Waiting for a client with fresh runtime context'}+ path.write_text(json.dumps(failed))+ session = {'sessionId': 'durable-id', 'sessionFile': str(root / 'session.jsonl')}+ client = MagicMock()+ client.call.return_value = {**session, 'sessionId': 'wrong-id', 'activeSessionId': 'new-active'}+ with patch('review_launch_env_parity.worker_descriptor', return_value=(path, failed)), \+ patch('review_launch_env_parity.verify_worker', return_value=(123, 'proc:old')), \+ patch('review_launch_env_parity.wait_gone'), patch('os.kill'):+ with self.assertRaisesRegex(AssertionError, 'changed durable session identity'):+ restart(client, 'old-active', root / 'agent', root / 'binary', {}, False,+ {}, set(), 'ts', session)+++if __name__ == '__main__':+ unittest.main()