A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix saved subagent family publication on session open
Sebastian Müllerfccecd04884d
diff --git a/.changes/fix-open-family-registration-race.md b/.changes/fix-open-family-registration-race.mdnew file mode 100644index 0000000000..009c4e5cef--- /dev/null+++ b/.changes/fix-open-family-registration-race.md@@ -0,0 +1 @@+- Reopening a saved session now publishes its passive subagents before the first Agents view snapshot, even when worker registration is delayed or the opening client disconnects.diff --git a/crates/pa-daemon/src/messaging.rs b/crates/pa-daemon/src/messaging.rsindex b92f019fe2..1e34c0e480 100644--- a/crates/pa-daemon/src/messaging.rs+++ b/crates/pa-daemon/src/messaging.rs@@ -13,7 +13,7 @@ use serde_json::{json, Map, Value};use crate::backpressure::RouteAdmission;use crate::protocol::{response_failure, response_success, DaemonResponse};use crate::registry::ResidentWorker;-use crate::supervisor::Supervisor;+use crate::supervisor::{RosterFamilySeedOwner, Supervisor};/// Worker round-trip budget for the sender-summary read and the delivery/// route (TS `WORKER_REQUEST_TIMEOUT_MS`).@@ -274,7 +274,11 @@ impl Supervisor {let launch = tokio::spawn({let supervisor = Arc::clone(self);let create = create;- async move { supervisor.launch_worker(&create, None).await }+ async move {+ supervisor+ .launch_worker(&create, None, RosterFamilySeedOwner::Registration)+ .await+ }});let launched = tokio::time::timeout(std::time::Duration::from_millis(crate::supervisor::ROUTE_TIMEOUT_MS),@@ -392,7 +396,11 @@ impl Supervisor {let launch = tokio::spawn({let supervisor = Arc::clone(self);let create = create;- async move { supervisor.launch_worker(&create, None).await }+ async move {+ supervisor+ .launch_worker(&create, None, RosterFamilySeedOwner::Registration)+ .await+ }});let launched = tokio::time::timeout(std::time::Duration::from_millis(crate::supervisor::ROUTE_TIMEOUT_MS),diff --git a/crates/pa-daemon/src/registry.rs b/crates/pa-daemon/src/registry.rsindex 667df288fe..173f0f2ff3 100644--- a/crates/pa-daemon/src/registry.rs+++ b/crates/pa-daemon/src/registry.rs@@ -95,6 +95,8 @@ pub(crate) struct ResidentWorker {pub(crate) worker_id: String,pub(crate) descriptor: Mutex<DaemonWorkerDescriptor>,pub(crate) descriptor_path: PathBuf,+ /// Fresh creates seed their family before replying; adopted workers seed on registration.+ pub(crate) roster_family_seed_owned_by_create: AtomicBool,/// The worker's command pump channel, bounded at/// [`crate::backpressure::WORKER_INFLIGHT_CAPACITY`]: admission precedes/// enqueue, so the queue and in-flight set share one bound.@@ -177,6 +179,7 @@ impl ResidentWorker {worker_id,descriptor: Mutex::new(descriptor),descriptor_path,+ roster_family_seed_owned_by_create: AtomicBool::new(false),cmd_tx: Mutex::new(None),inflight: Arc::new(tokio::sync::Semaphore::new(crate::backpressure::WORKER_INFLIGHT_CAPACITY,diff --git a/crates/pa-daemon/src/rlm_ledger.rs b/crates/pa-daemon/src/rlm_ledger.rsindex 0b81c1c49f..03ff133986 100644--- a/crates/pa-daemon/src/rlm_ledger.rs+++ b/crates/pa-daemon/src/rlm_ledger.rs@@ -229,6 +229,18 @@ fn fold_records(records: Vec<LedgerRecord>, keep: impl Fn(&str) -> bool) -> Repl_ => {}}}+ for (at, edge) in state.edges.iter().enumerate() {+ if edge.deleted.is_some() {+ continue;+ }+ if let Some(id) = Path::new(&edge.parent).file_stem() {+ state+ .children_by_parent_id+ .entry(id.to_string_lossy().into_owned())+ .or_default()+ .push(at);+ }+ }state}@@ -507,6 +519,86 @@ impl RlmSpawnLedger {Ok(usage)}+ /// Seed and replay the ledger ahead of its first reader; a failed+ /// replay is left to that reader, which reports it.+ pub(crate) fn warm(&self) {+ if self.seed_once().is_ok() {+ drop(self.replay_cached());+ }+ }++ /// The live family below `roots`, walked through the replay's parent+ /// index: the cost follows the families' size, not the ledger's. Each+ /// call re-resolves the endpoints it visits (restore, relocation,+ /// deletion, and symlink retargets append no ledger row). A node's+ /// children are the live edges recorded under its durable session id -+ /// that of its canonical path or of the path it was reached by - whose+ /// resolved parent is the node itself. Edges carry canonical endpoints,+ /// in walk order; each descendant appears once.+ ///+ /// # Errors+ ///+ /// Returns an error when the ledger replay fails (an oversized ledger)+ /// or a prior panic poisoned the artifact index lock.+ pub(crate) fn family_edges(+ &self,+ roots: impl IntoIterator<Item = PathBuf>,+ ) -> Result<Vec<RlmLedgerEdge>> {+ self.seed_once()?;+ let state = self.replay_cached()?;+ let mut resolver = LivePathResolver::new(+ self.agent_dir.clone(),+ self.canonical_sessions_dir.clone(),+ &state.artifact_index,+ );+ let mut visited = HashSet::new();+ let mut queue = Vec::new();+ for root in roots {+ let node = canonical_session_path(&root);+ if visited.insert(node.clone()) {+ queue.push((node, root));+ }+ }+ let mut edges = Vec::new();+ while let Some((node, reached_by)) = queue.pop() {+ let mut ids = vec![node.file_stem()];+ if reached_by.file_stem() != node.file_stem() {+ ids.push(reached_by.file_stem());+ }+ for id in ids.into_iter().flatten() {+ let Some(indices) = state+ .children_by_parent_id+ .get(id.to_string_lossy().as_ref())+ else {+ continue;+ };+ for &at in indices {+ let edge = &state.edges[at];+ let Some(parent) = resolver.resolve(&edge.parent)? else {+ continue;+ };+ if canonical_session_path(&parent) != node {+ continue;+ }+ let Some(child) = resolver.resolve(&edge.child)? else {+ continue;+ };+ let child = canonical_session_path(&child);+ if !visited.insert(child.clone()) {+ continue;+ }+ edges.push(RlmLedgerEdge {+ parent: node.to_string_lossy().into_owned(),+ child: child.to_string_lossy().into_owned(),+ ..edge.clone()+ });+ queue.push((child, PathBuf::from(&edge.child)));+ }+ }+ }+ Ok(edges)+ }+fn fold_deleted_descendant_usage(&self,edges: &[RlmLedgerEdge],diff --git a/crates/pa-daemon/src/rlm_ledger/replay.rs b/crates/pa-daemon/src/rlm_ledger/replay.rsindex 038dd9590b..7cc2409943 100644--- a/crates/pa-daemon/src/rlm_ledger/replay.rs+++ b/crates/pa-daemon/src/rlm_ledger/replay.rs@@ -158,6 +158,9 @@ pub(super) struct ReplayState {pub(super) index: HashMap<String, usize>,pub(super) artifact_index: OnceLock<Mutex<ArtifactIndex>>,pub(super) deleted_bucket: Mutex<Option<DeletedBucket>>,+ /// Live edges by the durable session id (file-name stem) of their+ /// recorded parent: the family walk's entry into the replay.+ pub(super) children_by_parent_id: HashMap<String, Vec<usize>>,}/// Ledger rows are immutable within a replay, but file moves and transcriptdiff --git a/crates/pa-daemon/src/rlm_ledger/tests.rs b/crates/pa-daemon/src/rlm_ledger/tests.rsindex 686711572e..13871b0caa 100644--- a/crates/pa-daemon/src/rlm_ledger/tests.rs+++ b/crates/pa-daemon/src/rlm_ledger/tests.rs@@ -1520,3 +1520,97 @@ fn artifact_misses_stay_cached_until_a_directory_changes() {assert_eq!(ledger.live_edges().unwrap(), expected);assert_eq!(replay::ARTIFACT_SCANS.with(std::cell::Cell::get), scans + 2);}++#[test]+fn family_edges_track_restore_and_relocation_without_a_ledger_append() {+ let dir = temp_dir("family-disk-change");+ let sessions = dir.join("sessions");+ fs::create_dir_all(&sessions).unwrap();+ let parent = sessions.join("parent.jsonl");+ let child = sessions.join("child.jsonl");+ fs::write(&parent, "{}").unwrap();+ let parent = canonical_session_path(&parent);+ fs::write(&child, "{}").unwrap();+ let ledger = ledger_for(&dir);+ ledger+ .append_spawn(&RlmSpawnInput {+ child_id: "sub".into(),+ parent: parent.to_string_lossy().into(),+ child: child.to_string_lossy().into(),+ depth: 1,+ name: "child".into(),+ })+ .unwrap();+ let family_children = || -> Vec<PathBuf> {+ ledger+ .family_edges([parent.clone()])+ .unwrap()+ .into_iter()+ .map(|edge| PathBuf::from(edge.child))+ .collect()+ };+ let archived = dir.join("sessions-archive").join("child.jsonl");+ fs::create_dir_all(archived.parent().unwrap()).unwrap();+ fs::rename(&child, &archived).unwrap();+ assert!(family_children().is_empty());+ fs::rename(&archived, &child).unwrap();+ assert_eq!(family_children(), vec![canonical_session_path(&child)]);+ let relocated = dir.join("session-artifacts/parent/sub/child.jsonl");+ fs::create_dir_all(relocated.parent().unwrap()).unwrap();+ fs::rename(&child, &relocated).unwrap();+ assert_eq!(family_children(), vec![canonical_session_path(&relocated)]);+ fs::remove_file(&relocated).unwrap();+ assert!(family_children().is_empty());+}++#[cfg(unix)]+#[test]+fn family_edges_recheck_symlink_targets_without_a_ledger_append() {+ use std::os::unix::fs::symlink;+ let dir = temp_dir("family-symlink");+ let parent = dir.join("parent.jsonl");+ let first = dir.join("first.jsonl");+ let second = dir.join("second.jsonl");+ let grandchild = dir.join("grandchild.jsonl");+ for file in [&parent, &first, &second, &grandchild] {+ fs::write(file, "{}").unwrap();+ }+ let ledger = ledger_for(&dir);+ for (child_id, parent, child) in [("sub", &parent, &first), ("grand", &first, &grandchild)] {+ ledger+ .append_spawn(&RlmSpawnInput {+ child_id: child_id.into(),+ parent: parent.to_string_lossy().into(),+ child: child.to_string_lossy().into(),+ depth: 1,+ name: child_id.into(),+ })+ .unwrap();+ }+ let family_children = || -> Vec<PathBuf> {+ ledger+ .family_edges([parent.clone()])+ .unwrap()+ .into_iter()+ .map(|edge| PathBuf::from(edge.child))+ .collect()+ };+ assert_eq!(+ family_children(),+ vec![+ canonical_session_path(&first),+ canonical_session_path(&grandchild)+ ]+ );+ fs::remove_file(&first).unwrap();+ symlink(&second, &first).unwrap();+ // The retargeted child resolves to its new file; its own children,+ // recorded under the old path's id, stay in the family.+ assert_eq!(+ family_children(),+ vec![+ canonical_session_path(&second),+ canonical_session_path(&grandchild)+ ]+ );+}diff --git a/crates/pa-daemon/src/stop_cleanup.rs b/crates/pa-daemon/src/stop_cleanup.rsindex 39bf46f4a4..eecef76fdf 100644--- a/crates/pa-daemon/src/stop_cleanup.rs+++ b/crates/pa-daemon/src/stop_cleanup.rs@@ -3,7 +3,7 @@//! Deliberate divergence from TS: the Rust port never wakes at all — a schedule fires//! only while its session is live; due jobs on not-running sessions report dormant.-use std::collections::{HashMap, HashSet};+use std::collections::HashSet;use std::path::{Path, PathBuf};use std::sync::Arc;@@ -24,33 +24,9 @@ struct TreeMember {session_file: PathBuf,}-/// The ledger's parent→child map: non-deleted edges keyed by canonical parent path.-fn children_by_parent(- agent_dir: &Path,- sessions_dir: &Path,-) -> HashMap<String, Vec<(String, PathBuf)>> {- let ledger = RlmSpawnLedger::new(agent_dir, sessions_dir, |_| {});- let mut map: HashMap<String, Vec<(String, PathBuf)>> = HashMap::new();- let Ok(edges) = ledger.edges(false) else {- return map;- };- for edge in edges {- let child = PathBuf::from(&edge.child);- let parent = canonical_session_path(Path::new(&edge.parent));- map.entry(parent.to_string_lossy().to_string())- .or_default()- .push((edge.child_id.clone(), child));- }- map-}-/// The stopped root's session tree: the root file plus every descendant the ledger/// reaches from it (the ledger is the only topology store).-fn session_tree(- agent_dir: &Path,- sessions_dir: &Path,- root_session_file: &Path,-) -> Vec<TreeMember> {+fn session_tree(ledger: &RlmSpawnLedger, root_session_file: &Path) -> Vec<TreeMember> {let mut members = Vec::new();let root = canonical_session_path(root_session_file);let root_id = read_session_info(&root).map_or_else(@@ -66,28 +42,20 @@ fn session_tree(}members.push(TreeMember {session_id: root_id,- session_file: root.clone(),+ session_file: root,});- let by_parent = children_by_parent(agent_dir, sessions_dir);- let mut queue = vec![root.to_string_lossy().to_string()];- let mut visited: HashSet<String> = queue.iter().cloned().collect();- while let Some(parent) = queue.pop() {- for (_child_id, child_file) in by_parent.get(&parent).cloned().unwrap_or_default() {- let child = canonical_session_path(&child_file);- let child_key = child.to_string_lossy().to_string();- if visited.contains(&child_key) {- continue;- }- visited.insert(child_key.clone());- let Some(info) = read_session_info(&child) else {- continue;- };- members.push(TreeMember {- session_id: info.id,- session_file: child.clone(),- });- queue.push(child_key);- }+ let Ok(family) = ledger.family_edges([root_session_file.to_path_buf()]) else {+ return members;+ };+ for edge in family {+ let child = PathBuf::from(edge.child);+ let Some(info) = read_session_info(&child) else {+ continue;+ };+ members.push(TreeMember {+ session_id: info.id,+ session_file: child,+ });}members}@@ -96,12 +64,17 @@ fn session_tree(/// A live worker covering any tree member owns its stores again, so the walk aborts on/// a coverage hit (`live_files`, collected before the walk).pub(crate) fn cancel_scheduled_jobs_for_tree(- agent_dir: &Path,- sessions_dir: &Path,+ ledger: &RlmSpawnLedger,root_session_file: &Path,live_files: &HashSet<String>,) -> Result<usize> {- let members = session_tree(agent_dir, sessions_dir, root_session_file);+ cancel_scheduled_jobs_for_members(&session_tree(ledger, root_session_file), live_files)+}++fn cancel_scheduled_jobs_for_members(+ members: &[TreeMember],+ live_files: &HashSet<String>,+) -> Result<usize> {if members.iter().any(|member| {live_files.contains(&canonical_session_path(&member.session_file)@@ -113,7 +86,7 @@ pub(crate) fn cancel_scheduled_jobs_for_tree(}let store = AgentCronJobStore::for_session_artifacts();let mut registered = false;- for member in &members {+ for member in members {let Some(dir) = session_artifact_dir(&member.session_file, &member.session_id) else {continue;};@@ -131,7 +104,7 @@ pub(crate) fn cancel_scheduled_jobs_for_tree(}let now = crate::util::now_ms();let mut cancelled = 0;- for member in &members {+ for member in members {cancelled += store.cancel_jobs_for_session(&CancelJobsFilter {@@ -169,28 +142,25 @@ pub(crate) fn ensure_archived_state(root_session_file: &Path) -> Result<()> {/// and the root file carries the `archived` state. `live_files` is collected/// after the stopped worker left the registry.pub(crate) fn finalize_archived_stop(- agent_dir: &Path,- sessions_dir: &Path,+ ledger: &RlmSpawnLedger,root_session_file: &Path,live_files: &HashSet<String>,) -> (usize, Option<anyhow::Error>) {- let cancelled =- cancel_scheduled_jobs_for_tree(agent_dir, sessions_dir, root_session_file, live_files);+ let members = session_tree(ledger, root_session_file);+ let cancelled = cancel_scheduled_jobs_for_members(&members, live_files);let (cancelled, cancel_error) = match cancelled {Ok(count) => (count, None),Err(error) => (0, Some(error)),};// A live worker covering the tree owns its stores again — including the session// file's state — so the belt skips covered trees like the cancel does.- let covered = session_tree(agent_dir, sessions_dir, root_session_file)- .iter()- .any(|member| {- live_files.contains(- &canonical_session_path(&member.session_file)- .to_string_lossy()- .to_string(),- )- });+ let covered = members.iter().any(|member| {+ live_files.contains(+ &canonical_session_path(&member.session_file)+ .to_string_lossy()+ .to_string(),+ )+ });if covered {return (cancelled, cancel_error);}@@ -347,22 +317,18 @@ impl Supervisor {if root_session_file.is_empty() {return true;}- let sessions_dir = match crate::paths::sessions_dir(&self.options.agent_dir) {- Ok(dir) => dir,+ let ledger = match self.rlm_spawn_ledger_for(None).await {+ Ok(ledger) => ledger,Err(error) => {self.log_line(&format!(- "stop finalize: could not resolve the sessions dir: {error:#}"+ "stop finalize: could not resolve the spawn ledger: {error:#}"));return false;}};let live = self.live_session_files().await;- let (cancelled, archive_error) = finalize_archived_stop(- &self.options.agent_dir,- &sessions_dir,- Path::new(&root_session_file),- &live,- );+ let (cancelled, archive_error) =+ finalize_archived_stop(&ledger, Path::new(&root_session_file), &live);if cancelled > 0 {self.log_line(&format!("stop finalize: cancelled {cancelled} scheduled job(s) of {root_session_file}"@@ -463,7 +429,7 @@ impl Supervisor {if root_session_file.is_empty() {return;}- let Ok(sessions_dir) = crate::paths::sessions_dir(&self.options.agent_dir) else {+ let Ok(ledger) = self.rlm_spawn_ledger_for(None).await else {return;};let mut live = self.live_session_files().await;@@ -472,12 +438,8 @@ impl Supervisor {.to_string_lossy().to_string(),);- let cancelled = cancel_scheduled_jobs_for_tree(- &self.options.agent_dir,- &sessions_dir,- Path::new(&root_session_file),- &live,- );+ let cancelled =+ cancel_scheduled_jobs_for_tree(&ledger, Path::new(&root_session_file), &live);let cancelled = match cancelled {Ok(count) => count,Err(error) => {@@ -568,7 +530,14 @@ mod tests {let (root_id, root_file) = write_session(&sessions_dir, Some("orchestrator"));let (child_id, child_file) = write_session(&sessions_dir, Some("lane"));- // The ledger edge parent -> child.+ let (moved_id, moved_at) = write_session(&sessions_dir, Some("moved"));+ let moved_dir = agent_dir+ .join("session-artifacts")+ .join(&root_id)+ .join("child-2");+ std::fs::create_dir_all(&moved_dir).unwrap();+ let moved_file = moved_dir.join(moved_at.file_name().unwrap());+ std::fs::rename(&moved_at, &moved_file).unwrap();let ledger = RlmSpawnLedger::new(&agent_dir, &sessions_dir, |_| {});ledger.append_spawn(&crate::rlm_ledger::RlmSpawnInput {@@ -579,15 +548,27 @@ mod tests {name: "lane".to_string(),}).unwrap();+ ledger+ .append_spawn(&crate::rlm_ledger::RlmSpawnInput {+ child_id: "child-2".to_string(),+ parent: root_file.to_string_lossy().to_string(),+ child: moved_at.to_string_lossy().to_string(),+ depth: 1,+ name: "moved".to_string(),+ })+ .unwrap();write_job(&root_file, &root_id, "job-root");write_job(&child_file, &child_id, "job-child");+ write_job(&moved_file, &moved_id, "job-moved");let live: HashSet<String> = HashSet::new();- let (cancelled, archive_error) =- finalize_archived_stop(&agent_dir, &sessions_dir, &root_file, &live);+ let (cancelled, archive_error) = finalize_archived_stop(&ledger, &root_file, &live);assert!(archive_error.is_none());- assert_eq!(cancelled, 2, "the root and child jobs both cancel");+ assert_eq!(+ cancelled, 3,+ "the root, the child, and the relocated child's jobs all cancel"+ );assert_eq!(read_job(&root_file, &root_id).status,pa_core::cron::JobStatus::Cancelled@@ -611,13 +592,14 @@ mod tests {let (root_id, root_file) = write_session(&sessions_dir, None);write_job(&root_file, &root_id, "job-root");+ let ledger = RlmSpawnLedger::new(&agent_dir, &sessions_dir, |_| {});let live: HashSet<String> = [canonical_session_path(&root_file).to_string_lossy().to_string()].into_iter().collect();- let (cancelled, _) = finalize_archived_stop(&agent_dir, &sessions_dir, &root_file, &live);+ let (cancelled, _) = finalize_archived_stop(&ledger, &root_file, &live);assert_eq!(cancelled, 0, "a covered tree keeps its schedules");assert_eq!(read_job(&root_file, &root_id).status,diff --git a/crates/pa-daemon/src/supervisor.rs b/crates/pa-daemon/src/supervisor.rsindex 3f211454e3..23213993b7 100644--- a/crates/pa-daemon/src/supervisor.rs+++ b/crates/pa-daemon/src/supervisor.rs@@ -57,6 +57,7 @@ pub(crate) use routing::{};// Called only by the supervision sibling module and in-file tests; lib-target unused.+pub(crate) use worker_lifecycle::RosterFamilySeedOwner;#[allow(unused_imports)]use worker_lifecycle::{probe_worker_socket, worker_connect_deadline};@@ -345,6 +346,16 @@ impl Supervisor {supervisor.note_catalog_refresh(count);});}+ // The first open's family walk reads the spawn ledger: replay it+ // while that open's worker launches, not on its reply path.+ {+ let supervisor = Arc::clone(&self);+ tokio::spawn(async move {+ if let Ok(ledger) = supervisor.rlm_spawn_ledger_for(None).await {+ drop(tokio::task::spawn_blocking(move || ledger.warm()).await);+ }+ });+ }socket::prepare_socket_path(&self.options.socket_path).await?;let listener = bind_transport(&self.options.socket_path).awaitdiff --git a/crates/pa-daemon/src/supervisor/adoption.rs b/crates/pa-daemon/src/supervisor/adoption.rsindex cfa8bfd8cf..e0f776b3f5 100644--- a/crates/pa-daemon/src/supervisor/adoption.rs+++ b/crates/pa-daemon/src/supervisor/adoption.rs@@ -557,22 +557,28 @@ impl Supervisor {record.epoch));drop(guard);- // Registration rebuilt the resident: refresh its roster entry from- // the live worker so the roster reflects the re-registered state.- self.refresh_roster_entry(&resident).await;// A worker that registers after the boot seed publishes its passive ledger family in// the background: TS reseeds on the worker's first roster snapshot, and this port's// workers push only their own summary, so the daemon walks the family here.- let family_root = {- let descriptor = resident.descriptor.lock().await;- descriptor- .session_file- .clone()- .or_else(|| descriptor.create_command.session_path.clone())- };- if let Some(root) = family_root {- self.spawn_roster_registration_seed(Path::new(&root));+ if record.epoch == 1+ && !resident+ .roster_family_seed_owned_by_create+ .load(Ordering::SeqCst)+ {+ let family_root = {+ let descriptor = resident.descriptor.lock().await;+ descriptor+ .session_file+ .clone()+ .or_else(|| descriptor.create_command.session_path.clone())+ };+ if let Some(root) = family_root {+ self.spawn_roster_registration_seed(Path::new(&root));+ }}+ // Registration rebuilt the resident: refresh its roster entry from+ // the live worker so the roster reflects the re-registered state.+ self.refresh_roster_entry(&resident).await;response_success(Some(command_id),type_name,diff --git a/crates/pa-daemon/src/supervisor/routing.rs b/crates/pa-daemon/src/supervisor/routing.rsindex b1302935e7..f95dab5e49 100644--- a/crates/pa-daemon/src/supervisor/routing.rs+++ b/crates/pa-daemon/src/supervisor/routing.rs@@ -4,7 +4,8 @@ use super::{anyhow, attach_client_capabilities, bail, client_command_payload, command_active_session_id,json, mpsc, oneshot, response_failure, response_line, response_success, streamed_attach_lines,wants_chunked, Arc, DaemonCommand, DaemonResponse, Duration, Outbound, ResidentWorker, Result,- RouteAdmission, SnapshotPurpose, Supervisor, Value, WorkerReply, WorkerRequest,+ RosterFamilySeedOwner, RouteAdmission, SnapshotPurpose, Supervisor, Value, WorkerReply,+ WorkerRequest,};use anyhow::Context as _;@@ -1003,7 +1004,11 @@ impl Supervisor {let launch = tokio::spawn({let supervisor = Arc::clone(self);let create = create;- async move { supervisor.launch_worker(&create, None).await }+ async move {+ supervisor+ .launch_worker(&create, None, RosterFamilySeedOwner::Registration)+ .await+ }});let launched =tokio::time::timeout(std::time::Duration::from_millis(ROUTE_TIMEOUT_MS), launch).await;@@ -1100,8 +1105,6 @@ impl Supervisor {};// The stopped child's teardown mirrors the resident delete's end state: the usage// capture, archived state, and artifact sweep land as a live child's kill leaves them.- let sessions_dir = crate::paths::sessions_dir(&self.options.agent_dir)- .with_context(|| "resolve the sessions dir for the delete finalize".to_string())?;// Live coverage captured AFTER the tombstone append: a wake that registered a resident// between the two must be visible here (the archive/sweep skips its tree).let live = self.live_session_files().await;@@ -1116,8 +1119,7 @@ impl Supervisor {return Ok(());}crate::stop_cleanup::finalize_archived_stop(- &self.options.agent_dir,- &sessions_dir,+ &ledger,std::path::Path::new(&session_file),&live,);diff --git a/crates/pa-daemon/src/supervisor/sessions.rs b/crates/pa-daemon/src/supervisor/sessions.rsindex d5dc4e8f88..d5db1a21da 100644--- a/crates/pa-daemon/src/supervisor/sessions.rs+++ b/crates/pa-daemon/src/supervisor/sessions.rs@@ -5,8 +5,8 @@ use super::{anyhow, bail, join_all, json, list_sessions, mpsc, name_unavailable_error, paths,reservation_key, response_failure, response_line, response_success, subscribers, Arc,DaemonCommand, DaemonResponse, DaemonSessionLifecycle, NameScope, Outbound, Path, PathBuf,- ResidentWorker, Result, RouteAdmission, Supervisor, Value, ROUTE_TIMEOUT_MS,- SUMMARY_TIMEOUT_MS,+ ResidentWorker, Result, RosterFamilySeedOwner, RouteAdmission, Supervisor, Value,+ ROUTE_TIMEOUT_MS, SUMMARY_TIMEOUT_MS,};use crate::session_scan::list_sessions_with;@@ -637,7 +637,9 @@ impl Supervisor {Some(DaemonSessionLifecycle::ClientOwned) => Some(client_id),_ => None,};- let (resident, create_summary) = self.launch_worker(command, owner_client_id).await?;+ let (resident, create_summary) = self+ .launch_worker(command, owner_client_id, RosterFamilySeedOwner::Create)+ .await?;// The single-flight stays held through the spawn admission below: an admission// failure tears the resident down, and a concurrent open that had just reused it// would hold a summary for a gone worker. The ledger is the only topology store.@@ -650,9 +652,7 @@ impl Supervisor {let _ = self.stop_worker(&resident).await;return Err(error);}- // The admission settled: the single-flight may release (a- // concurrent open's classification now finds a durable resident).- drop(opening_guard);+ // Keep concurrent opens behind the first family's edge-only seed.// Prefer a fresh get_state, but a degraded one falls back to the authoritative// create summary instead of failing the spawn.let summary = match self@@ -674,19 +674,22 @@ impl Supervisor {// write (its counter raises the resident's stale-delta watermark).self.write_roster_summary_for_resident(&resident, &summary).await;- // The new root's passive family renders immediately from the ledger edges, then- // one bounded background hydration fills each seeded row's display fields. The root- // is the CREATE response's session file (a mid-replay get_state must not skip it).if let Some(root) = summary.get("sessionFile").and_then(Value::as_str).or_else(|| create_summary.get("sessionFile").and_then(Value::as_str)){- let seeded = self.seed_roster_family_edges(Path::new(&root)).await;+ let seeded = self.seed_roster_family_edges(Path::new(root)).await;if !seeded.is_empty() {- self.spawn_seeded_hydration(seeded);+ drop(self.spawn_seeded_hydration(seeded));}+ let supervisor = Arc::clone(self);+ drop(tokio::spawn(async move {+ let refreshed = supervisor.refresh_deleted_descendant_usage().await;+ supervisor.push_roster_update(refreshed, Vec::new());+ }));}+ drop(opening_guard);Ok(summary)}diff --git a/crates/pa-daemon/src/supervisor/spawn_record_tests.rs b/crates/pa-daemon/src/supervisor/spawn_record_tests.rsindex 8dccf3fd57..366a5067e5 100644--- a/crates/pa-daemon/src/supervisor/spawn_record_tests.rs+++ b/crates/pa-daemon/src/supervisor/spawn_record_tests.rs@@ -294,7 +294,9 @@ async fn a_fresh_create_spawn_record_keeps_the_unsynced_shape() {};let _ = crate::descriptor::atomic_write_probe::take_under(&supervisor.descriptor_dir);- let outcome = supervisor.launch_worker(&create, None).await;+ let outcome = supervisor+ .launch_worker(&create, None, RosterFamilySeedOwner::Registration)+ .await;assert!(outcome.is_err(),"no live worker: the fresh launch fails at the probe"diff --git a/crates/pa-daemon/src/supervisor/tests.rs b/crates/pa-daemon/src/supervisor/tests.rsindex f3f5438aa8..e35a5eb684 100644--- a/crates/pa-daemon/src/supervisor/tests.rs+++ b/crates/pa-daemon/src/supervisor/tests.rs@@ -1161,7 +1161,7 @@ async fn a_create_while_shutting_down_is_refused() {rest: Map::default(),};let refused = supervisor- .launch_worker(&create, None)+ .launch_worker(&create, None, RosterFamilySeedOwner::Registration).await.err().expect("the shutting-down supervisor accepted a create");@@ -1427,7 +1427,7 @@ async fn first_signal_drains_a_settling_turn_and_rejects_new_work() {"the first signal must start the drain");let refused = supervisor- .launch_worker(&create, None)+ .launch_worker(&create, None, RosterFamilySeedOwner::Registration).await.err().expect("a create during the drain must be rejected");@@ -2545,3 +2545,48 @@ proptest! {})?;}}++#[tokio::test]+async fn a_restarted_supervisors_registration_seeds_the_roster_family() {+ let (dir, supervisor, root_file, child_file) =+ crate::supervisor_roster_seed::tests::roster_fixture().await;+ let agent_dir = dir.join("agent");+ crate::supervisor_roster_seed::tests::append_family_edge(+ &agent_dir,+ &agent_dir.join("sessions"),+ "sub-9",+ &root_file,+ &child_file,+ );+ crate::supervisor_roster_seed::tests::register_root_worker(&supervisor, "w-root", &root_file)+ .await;+ let command = DaemonCommand::WorkerRegister {+ id: None,+ active_session_id: "w-root".to_string(),+ session_id: None,+ socket_path: "/tmp/none.sock".to_string(),+ worker_instance_id: String::new(),+ token: "w-root-token".to_string(),+ pid: 4242,+ rest: Map::default(),+ };+ let registered = supervisor+ .handle_worker_register("r1", "worker_register", &command)+ .await;+ assert!(registered.success, "registration refused: {registered:?}");+ assert_eq!(+ registered.data.expect("registration response")["epoch"],+ 1,+ "the re-registration is the first under the restarted supervisor"+ );+ crate::supervisor_roster_seed::tests::drain_pending_seeds_for_tests(&supervisor).await;+ let row = crate::supervisor_roster_seed::tests::roster_row_for_child(&supervisor, "sub-9");+ assert_eq!(row.summary["rlmChildId"], "sub-9");+ assert_eq!(+ row.summary["parentSessionPath"],+ root_file.to_string_lossy().to_string()+ );+ assert_eq!(row.summary["runtimeKind"], "subagent");+ assert_eq!(row.worker_id, None, "the seeded row, never a worker's");+ let _ = std::fs::remove_dir_all(&dir);+}diff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rsindex 0a0ffce29e..1bd9831128 100644--- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs+++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs@@ -18,6 +18,12 @@ use super::{use crate::lease::is_process_alive;use crate::protocol::{response_failure, response_success, DaemonResponse};+/// Which admission path publishes a fresh worker's passive family.+pub(crate) enum RosterFamilySeedOwner {+ Create,+ Registration,+}+impl Supervisor {/// Complete a tombstoned stop for a worker encountered at adoption: adoption/// finishes the stop, never adopts the worker as healthy. The `archive_on_stop`@@ -101,6 +107,7 @@ impl Supervisor {self: &Arc<Self>,create: &DaemonCommand,owner_client_id: Option<String>,+ family_seed_owner: RosterFamilySeedOwner,) -> Result<(Arc<ResidentWorker>, Value)> {let DaemonCommand::Create {session_path,@@ -351,6 +358,11 @@ impl Supervisor {};let descriptor_path = self.descriptor_dir.join(format!("{worker_id}.json"));let resident = ResidentWorker::new(worker_id.clone(), descriptor, descriptor_path.clone());+ // Claim before registration can observe the newly inserted resident.+ resident.roster_family_seed_owned_by_create.store(+ matches!(family_seed_owner, RosterFamilySeedOwner::Create),+ Ordering::SeqCst,+ );// 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 mustdiff --git a/crates/pa-daemon/src/supervisor_roster.rs b/crates/pa-daemon/src/supervisor_roster.rsindex 96e4d47052..52be079a22 100644--- a/crates/pa-daemon/src/supervisor_roster.rs+++ b/crates/pa-daemon/src/supervisor_roster.rs@@ -2,7 +2,7 @@//! roster deltas, the stop-path passivation, and the `roster_update` pushes subscribers receive.use serde_json::Map;-use std::collections::{HashMap, HashSet};+use std::collections::HashSet;use std::path::{Path, PathBuf};use std::sync::Arc;@@ -15,7 +15,6 @@ use crate::lease::canonical_session_path;use crate::protocol::{response_failure, response_success, DaemonResponse};use crate::registry::ResidentWorker;use crate::supervisor::{ClientRouting, Supervisor, ROUTE_TIMEOUT_MS};-use crate::supervisor_roster_seed::family_descends_from;/// `worker_roster_delta`'s parsed frame. `sequence` feeds the stale-delta/// gate (the per-worker watermark drops a delayed older snapshot);@@ -271,13 +270,15 @@ impl Supervisor {// The stopping worker's family view — live edges and surviving// resident roots — decides each subagent row's fate; a ledger// failure degrades to an empty view.- let ledger_view = self.live_edges_and_parents().await;- let empty_view: (- Vec<crate::rlm_ledger::RlmLedgerEdge>,- HashMap<PathBuf, PathBuf>,- ) = (Vec::new(), HashMap::new());- let (_, parent_by_child) = ledger_view.as_ref().unwrap_or(&empty_view);let roots = self.roster_seed_roots().await;+ let ledger_view: Option<HashSet<PathBuf>> = self+ .rlm_spawn_ledger_for(None)+ .await+ .ok()+ .and_then(|ledger| ledger.family_edges(roots).ok())+ .map(|edges| edges.into_iter().map(|edge| edge.child.into()).collect());+ let empty_view = HashSet::new();+ let anchored_children = ledger_view.as_ref().unwrap_or(&empty_view);// The stop's own ledger event: an RLM delete tombstoned its child// before the stop began, and the shutdown route was the// transcript's flush barrier, so the fold beside the ledger view@@ -346,11 +347,7 @@ impl Supervisor {.get("sessionFile").and_then(Value::as_str).is_some_and(|file| {- parent_by_child- .get(&canonical_session_path(Path::new(file)))- .is_some_and(|parent| {- family_descends_from(parent_by_child, parent, &roots)- })+ anchored_children.contains(&canonical_session_path(Path::new(file)))});if !ephemeral && entry.queued_child != Some(true) && anchored {let passivated =@@ -364,7 +361,7 @@ impl Supervisor {// The seeded unowned rows outlived their departed root and// flashed as top-level rows: settle them with the same anchor// verdict as the owned rows, scoped to the snapshot.- if ledger_view.is_ok() {+ if ledger_view.is_some() {for entry in &unowned_at_start {if roster.get(&entry.agent_id)@@ -388,11 +385,7 @@ impl Supervisor {.get("sessionFile").and_then(Value::as_str).is_some_and(|file| {- parent_by_child- .get(&canonical_session_path(Path::new(file)))- .is_some_and(|parent| {- family_descends_from(parent_by_child, parent, &roots)- })+ anchored_children.contains(&canonical_session_path(Path::new(file)))});if !anchored {roster.delete(&entry.agent_id);diff --git a/crates/pa-daemon/src/supervisor_roster_seed.rs b/crates/pa-daemon/src/supervisor_roster_seed.rsindex 05057f8505..ef9fa19bed 100644--- a/crates/pa-daemon/src/supervisor_roster_seed.rs+++ b/crates/pa-daemon/src/supervisor_roster_seed.rs@@ -24,8 +24,13 @@ impl Supervisor {if roots.is_empty() {return;}- let (edges, parent_by_child) = match self.live_edges_and_parents().await {- Ok(view) => view,+ // The same ledger instance the family walk read, so its replay+ // cache carries deletions that land during this seed.+ let Ok(ledger) = self.rlm_spawn_ledger_for(None).await else {+ return;+ };+ let edges = match ledger.family_edges(roots) {+ Ok(edges) => edges,Err(error) => {self.log_line(&format!("Could not seed the agent roster from the spawn ledger: {error:#}"@@ -33,19 +38,18 @@ impl Supervisor {return;}};+ let parent_by_child: HashMap<PathBuf, PathBuf> = edges+ .iter()+ .map(|edge| (PathBuf::from(&edge.child), PathBuf::from(&edge.parent)))+ .collect();// Roots re-snapshot after the ledger awaits: a root that// stopped mid-read must not receive seeded rows.let roots = self.roster_seed_roots().await;- // The same ledger instance the edge snapshot read, so its- // replay cache carries deletions that land during this seed.- let Ok(ledger) = self.rlm_spawn_ledger_for(None).await else {- return;- };let mut changed = Vec::new();let mut retry = Vec::new();for edge in &edges {- let parent = canonical_session_path(Path::new(&edge.parent));- if !family_descends_from(&parent_by_child, &parent, &roots) {+ let parent = Path::new(&edge.parent);+ if !family_descends_from(&parent_by_child, parent, &roots) {continue;}let candidate = SeededRosterEntry::edge_only(edge);@@ -65,7 +69,7 @@ impl Supervisor {// revalidated: a stopped root or a tombstoned edge must// not receive rows.if !ledger.edge_is_live(&edge.child_id, &edge.child)- || !family_descends_from(&parent_by_child, &parent, &self.roster_seed_roots().await)+ || !family_descends_from(&parent_by_child, parent, &self.roster_seed_roots().await){continue;}@@ -140,25 +144,6 @@ impl Supervisor {}}- /// The default ledger's live edges and their canonical child->parent- /// map, shared by every seed and passivation walk.- pub(crate) async fn live_edges_and_parents(- self: &Arc<Self>,- ) -> anyhow::Result<(Vec<RlmLedgerEdge>, HashMap<PathBuf, PathBuf>)> {- let ledger = self.rlm_spawn_ledger_for(None).await?;- let edges = ledger.live_edges()?;- let parent_by_child = edges- .iter()- .map(|edge| {- (- canonical_session_path(Path::new(&edge.child)),- canonical_session_path(Path::new(&edge.parent)),- )- })- .collect();- Ok((edges, parent_by_child))- }-/// The deleted-descendant bucket (the spawn ledger's fold keyed by/// canonical parent session path) with the fold's ticket, computed/// off the async runtime: the fold reads the ledger, stats@@ -233,9 +218,11 @@ impl Supervisor {self: &Arc<Self>,root: &Path,) -> Vec<AgentRosterEntry> {- let roots: HashSet<PathBuf> = HashSet::from([canonical_session_path(root)]);- let (edges, parent_by_child) = match self.live_edges_and_parents().await {- Ok(view) => view,+ let Ok(ledger) = self.rlm_spawn_ledger_for(None).await else {+ return Vec::new();+ };+ let edges = match ledger.family_edges([root.to_path_buf()]) {+ Ok(edges) => edges,Err(error) => {self.log_line(&format!("Could not seed the agent roster from the spawn ledger: {error:#}"@@ -243,9 +230,6 @@ impl Supervisor {return Vec::new();}};- let Ok(ledger) = self.rlm_spawn_ledger_for(None).await else {- return Vec::new();- };// The root's residency is revalidated after the awaits: a dead// root must not receive ghost family rows (the walk holds no// further await).@@ -256,17 +240,11 @@ impl Supervisor {{return Vec::new();}- // The family walk outside the roster lock: neither the descent- // check nor the ledger read may block every roster operation.let candidates: Vec<&RlmLedgerEdge> = edges.iter()- .filter(|edge| {- let parent = canonical_session_path(Path::new(&edge.parent));- family_descends_from(&parent_by_child, &parent, &roots)- // The edge snapshot predates this pass: a child deleted in- // that window never seeds.- && ledger.edge_is_live(&edge.child_id, &edge.child)- })+ // The edge snapshot predates this pass: a child deleted in+ // that window never seeds.+ .filter(|edge| ledger.edge_is_live(&edge.child_id, &edge.child)).collect();let mut changed = Vec::new();let mut retry = Vec::new();@@ -1094,4 +1072,145 @@ pub(crate) mod tests {);let _ = std::fs::remove_dir_all(&dir);}++ #[tokio::test]+ async fn stopping_a_childless_root_leaves_the_bucket_and_other_rows_unchanged() {+ let (dir, supervisor, root_file, child_file) = roster_fixture().await;+ let agent_dir = dir.join("agent");+ let sessions_dir = agent_dir.join("sessions");+ register_root_worker(&supervisor, "w-root", &root_file).await;+ append_family_edge(+ &agent_dir,+ &sessions_dir,+ "sub-live",+ &root_file,+ &child_file,+ );+ let gone_child = agent_dir+ .join("session-artifacts")+ .join("root-1")+ .join("sub-gone")+ .join("sub-gone.jsonl");+ std::fs::create_dir_all(gone_child.parent().expect("gone child dir")).unwrap();+ write_display_file(&gone_child, "/the/gone/cwd");+ let ledger = crate::rlm_ledger::RlmSpawnLedger::new(&agent_dir, &sessions_dir, |_| {});+ ledger+ .append_spawn(&crate::rlm_ledger::RlmSpawnInput {+ child_id: "sub-gone".to_string(),+ parent: root_file.to_string_lossy().to_string(),+ child: gone_child.to_string_lossy().to_string(),+ depth: 1,+ name: "gone".to_string(),+ })+ .expect("append spawn");+ ledger+ .append_delete_with_usage(+ "sub-gone",+ &gone_child.to_string_lossy(),+ crate::rlm_ledger::RlmLedgerDeleteReason::User,+ &crate::session_usage::SessionUsageSummary {+ input_tokens: 11,+ output_tokens: 7,+ cost: 0.5,+ },+ )+ .expect("append delete");+ let mut events = supervisor.events.subscribe();+ let mut root_summary = live_child_summary(&root_file, &child_file);+ root_summary["runtimeKind"] = json!("top-level");+ root_summary["sessionId"] = json!("root-persisted");+ root_summary["id"] = json!("root-persisted");+ root_summary["sessionFile"] = json!(root_file.to_string_lossy());+ root_summary.as_object_mut().unwrap().remove("rlmChildId");+ root_summary+ .as_object_mut()+ .unwrap()+ .remove("parentSessionPath");+ supervisor.write_roster_summary(&root_summary, Some("w-root"));+ let _ = drain_roster_pushes(&mut events);+ let childless_file = sessions_dir.join("childless.jsonl");+ write_display_file(&childless_file, "/the/childless/cwd");+ register_root_worker(&supervisor, "w-childless", &childless_file).await;+ let mut childless_summary = live_child_summary(&root_file, &child_file);+ childless_summary["runtimeKind"] = json!("top-level");+ childless_summary["sessionId"] = json!("childless-persisted");+ childless_summary["id"] = json!("childless-persisted");+ childless_summary["sessionFile"] = json!(childless_file.to_string_lossy());+ childless_summary+ .as_object_mut()+ .unwrap()+ .remove("rlmChildId");+ childless_summary+ .as_object_mut()+ .unwrap()+ .remove("parentSessionPath");+ supervisor.write_roster_summary(&childless_summary, Some("w-childless"));+ let _ = drain_roster_pushes(&mut events);+ supervisor.spawn_roster_boot_seed();+ drain_pending_seeds_for_tests(&supervisor).await;+ let _ = drain_roster_pushes(&mut events);+ supervisor.refresh_deleted_descendant_usage().await;+ let _ = drain_roster_pushes(&mut events);++ let before = supervisor+ .handle_roster_subscribe("s1", "roster_subscribe")+ .await;+ let before_rows = before.data.expect("snapshot")["roster"]+ .as_array()+ .cloned()+ .unwrap_or_default();+ let family_root = before_rows+ .iter()+ .find(|entry| entry["summary"]["sessionId"] == json!("root-persisted"))+ .expect("family root row");+ assert_eq!(+ family_root["summary"]["deletedDescendantUsage"],+ json!({ "inputTokens": 11, "outputTokens": 7, "cost": 0.5 }),+ "the bucket attached to the family root before the stop"+ );+ let childless_id = roster_agent_id_for_summary(&childless_summary);+ let before_others: Vec<&Value> = before_rows+ .iter()+ .filter(|entry| entry["agentId"] != json!(childless_id))+ .collect();++ supervisor.registry.remove("w-childless").await;+ supervisor+ .passivate_roster_worker("w-childless", false)+ .await;++ let after = supervisor+ .handle_roster_subscribe("s2", "roster_subscribe")+ .await;+ let after_rows = after.data.expect("snapshot")["roster"]+ .as_array()+ .cloned()+ .unwrap_or_default();+ let stopped = after_rows+ .iter()+ .find(|entry| entry["agentId"] == json!(childless_id))+ .expect("the childless root's row settles in place");+ assert_eq!(stopped["status"], "inactive");+ assert_eq!(stopped["summary"]["isSessionActive"], false);+ let after_others: Vec<&Value> = after_rows+ .iter()+ .filter(|entry| entry["agentId"] != json!(childless_id))+ .collect();+ assert_eq!(+ before_others.len(),+ after_others.len(),+ "no row appeared or disappeared besides the stopped root"+ );+ for expected in &before_others {+ let found = after_others+ .iter()+ .find(|entry| entry["agentId"] == expected["agentId"])+ .unwrap_or_else(|| panic!("row vanished: {}", expected["agentId"]));+ assert_eq!(+ found, expected,+ "the stop of a childless root rewrote another row"+ );+ }+ let _ = std::fs::remove_dir_all(&dir);+ }}diff --git a/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rsindex 0c5edfb00f..c069e7cafc 100644--- a/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs+++ b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs@@ -24,7 +24,7 @@#![cfg(unix)]use std::io::{BufRead, BufReader, Write};-use std::os::unix::net::UnixStream;+use std::os::unix::net::{UnixListener, UnixStream};use std::path::{Path, PathBuf};use std::process::{Child, Command, Stdio};use std::time::{Duration, Instant};@@ -81,6 +81,146 @@ fn spawn_daemon(socket: &Path, agent_dir: &Path) -> Daemon {panic!("supervisor socket never appeared");}+fn drain_boot_seed(socket: &Path) {+ let deadline = Instant::now() + Duration::from_secs(10);+ loop {+ let (mut client, hello) = Client::connect(socket);+ if hello["updateResume"]["complete"] == true {+ // Restore completion follows adoption, which has already enqueued the boot seed.+ let subscribed =+ client.send_command("boot-seed", &json!({ "type": "roster_subscribe" }));+ assert_eq!(subscribed["success"], true, "{subscribed}");+ return;+ }+ assert!(Instant::now() < deadline, "boot adoption never settled");+ std::thread::yield_now();+ }+}++/// Gate registration requests while other worker-to-supervisor traffic keeps flowing.+struct RegistrationGate {+ socket: PathBuf,+ release: std::sync::Arc<(std::sync::Mutex<Option<bool>>, std::sync::Condvar)>,+ observed: std::sync::mpsc::Receiver<()>,+ registered: std::sync::mpsc::Receiver<()>,+ streams: std::sync::Arc<std::sync::Mutex<Vec<UnixStream>>>,+ stopped: std::sync::Arc<std::sync::atomic::AtomicBool>,+ thread: Option<std::thread::JoinHandle<()>>,+}++impl RegistrationGate {+ fn bind(socket: &Path, backend: &Path) -> Self {+ std::fs::rename(socket, backend).expect("move supervisor socket behind gate");+ let listener = UnixListener::bind(socket).expect("bind registration gate");+ let release = std::sync::Arc::new((std::sync::Mutex::new(None), std::sync::Condvar::new()));+ let (observed_tx, observed) = std::sync::mpsc::channel();+ let (registered_tx, registered) = std::sync::mpsc::channel();+ let streams = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let stopped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let owned_streams = std::sync::Arc::clone(&streams);+ let stop = std::sync::Arc::clone(&stopped);+ let gate = std::sync::Arc::clone(&release);+ let backend = backend.to_path_buf();+ let thread = std::thread::spawn(move || {+ let mut connections = Vec::new();+ for incoming in listener.incoming() {+ let mut worker = incoming.expect("accept worker link");+ if stop.load(std::sync::atomic::Ordering::SeqCst) {+ break;+ }+ let mut daemon = UnixStream::connect(&backend).expect("connect backend");+ {+ let mut streams = owned_streams.lock().unwrap();+ streams.push(worker.try_clone().unwrap());+ streams.push(daemon.try_clone().unwrap());+ }+ if stop.load(std::sync::atomic::Ordering::SeqCst) {+ break;+ }+ let gate = std::sync::Arc::clone(&gate);+ let observed = observed_tx.clone();+ let registered = registered_tx.clone();+ connections.push(std::thread::spawn(move || {+ let mut daemon_reader = BufReader::new(daemon.try_clone().unwrap());+ let mut worker_reader = BufReader::new(worker.try_clone().unwrap());+ let mut line = String::new();+ if daemon_reader.read_line(&mut line).unwrap_or(0) == 0+ || worker.write_all(line.as_bytes()).is_err()+ {+ return;+ }+ line.clear();+ if worker_reader.read_line(&mut line).unwrap_or(0) == 0 {+ return;+ }+ let request: Value = serde_json::from_str(&line).expect("worker envelope");+ let registration = request["command"]["type"] == "worker_register";+ if registration {+ let _ = observed.send(());+ let (state, changed) = &*gate;+ let released = changed+ .wait_while(state.lock().unwrap(), |state| state.is_none())+ .unwrap();+ if *released != Some(true) {+ return;+ }+ }+ if daemon.write_all(line.as_bytes()).is_err() {+ return;+ }+ let request_id = request["id"].clone();+ let upstream = std::thread::spawn(move || {+ let _ = std::io::copy(&mut worker_reader, &mut daemon);+ });+ loop {+ line.clear();+ if daemon_reader.read_line(&mut line).unwrap_or(0) == 0+ || worker.write_all(line.as_bytes()).is_err()+ {+ break;+ }+ let response: Value =+ serde_json::from_str(&line).expect("backend response");+ if registration && response["id"] == request_id {+ let _ = registered.send(());+ }+ }+ let _ = worker.shutdown(std::net::Shutdown::Both);+ let _ = upstream.join();+ }));+ }+ for connection in connections {+ let _ = connection.join();+ }+ });+ Self {+ socket: socket.to_path_buf(),+ release,+ observed,+ registered,+ streams,+ stopped,+ thread: Some(thread),+ }+ }+}++impl Drop for RegistrationGate {+ fn drop(&mut self) {+ self.stopped+ .store(true, std::sync::atomic::Ordering::SeqCst);+ *self.release.0.lock().unwrap() = Some(false);+ self.release.1.notify_all();+ let _ = UnixStream::connect(&self.socket);+ for stream in self.streams.lock().unwrap().iter() {+ let _ = stream.shutdown(std::net::Shutdown::Both);+ }+ if let Some(thread) = self.thread.take() {+ let _ = thread.join();+ }+ }+}+struct Client {reader: BufReader<UnixStream>,writer: UnixStream,@@ -479,3 +619,124 @@ async fn subscribe_after_spawn_then_shutdown_seeds_the_passive_child() {.expect("parent still resident");assert_eq!(parent_entry["summary"]["activeSessionId"], parent_active_id);}++#[test]+fn open_resume_publishes_the_family_in_the_first_subscribe_snapshot() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("daemon.sock");+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(&agent_dir).expect("agent dir");+ let (root_path, live) = write_synthetic_family(&agent_dir, 2);+ assert_eq!(live, 2, "two passive ledger children");+ let _daemon = spawn_daemon(&socket, &agent_dir);+ drain_boot_seed(&socket);+ let backend = dir.path().join("backend.sock");+ let registration = RegistrationGate::bind(&socket, &backend);+ let (mut client, hello) = Client::connect(&backend);+ assert_eq!(hello["type"], "daemon_hello");++ let root_session_path = root_path.to_string_lossy().to_string();+ let created = client.send_command(+ "c1",+ &json!({+ "type": "create",+ "sessionPath": root_session_path,+ "config": { "cwd": dir.path().to_string_lossy() },+ }),+ );+ assert_eq!(created["success"], true, "resume create failed: {created}");+ let root_active_id = created["data"]["activeSessionId"]+ .as_str()+ .expect("root active session id")+ .to_string();++ registration+ .observed+ .recv_timeout(Duration::from_secs(10))+ .expect("worker registration is held before daemon dispatch");+ let subscribed = client.send_command("r1", &json!({ "type": "roster_subscribe" }));+ assert_eq!(+ subscribed["success"], true,+ "subscribe failed: {subscribed}"+ );+ let snapshot = subscribed["data"]["roster"]+ .as_array()+ .cloned()+ .unwrap_or_default();+ for child_id in ["sub-0000", "sub-0001"] {+ let entry = snapshot+ .iter()+ .find(|entry| entry["summary"]["rlmChildId"] == json!(child_id))+ .unwrap_or_else(|| {+ panic!("child {child_id} missing from the FIRST snapshot: {snapshot:?}")+ });+ assert_eq!(entry["summary"]["runtimeKind"], "subagent");+ assert_eq!(+ entry["summary"]["parentSessionPath"],+ root_session_path.as_str(),+ "the family edge keys the seeded row to the root"+ );+ assert_eq!(+ entry["summary"]["sessionName"],+ child_id.replace("sub-", "worker-")+ );+ }+ let root_entry = snapshot+ .iter()+ .find(|entry| entry["summary"]["activeSessionId"] == json!(root_active_id.as_str()))+ .expect("the reopened root's own row in the same snapshot");+ assert_eq!(root_entry["status"], "idle");+ *registration.release.0.lock().unwrap() = Some(true);+ registration.release.1.notify_all();+ registration+ .registered+ .recv_timeout(Duration::from_secs(10))+ .expect("late registration completed");+ let repeated = client.send_command("r2", &json!({ "type": "roster_subscribe" }));+ let repeated_rows = repeated["data"]["roster"].as_array().unwrap();+ assert_eq!(+ repeated_rows.len(),+ snapshot.len(),+ "registration adds no duplicate rows"+ );+}++#[test]+fn a_disconnected_create_still_seeds_its_family_before_registration() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("daemon.sock");+ let backend = dir.path().join("backend.sock");+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(&agent_dir).expect("agent dir");+ let (root, _) = write_synthetic_family(&agent_dir, 1);+ let _daemon = spawn_daemon(&socket, &agent_dir);+ drain_boot_seed(&socket);+ let registration = RegistrationGate::bind(&socket, &backend);+ let (mut opener, _) = Client::connect(&backend);+ let create = json!({+ "type": "create",+ "sessionPath": root.to_string_lossy(),+ "config": { "cwd": dir.path().to_string_lossy() },+ });+ opener.send(&json!({+ "type": "command",+ "id": "disconnected-create",+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "command": create,+ }));+ drop(opener);+ registration+ .observed+ .recv_timeout(Duration::from_secs(10))+ .expect("detached create launched its worker; registration is held");+ let (mut observer, _) = Client::connect(&backend);+ // The same-file open joins the first create through its completed family seed.+ let reopened = observer.send_command("c2", &create);+ assert_eq!(reopened["success"], true, "{reopened}");+ let snapshot = observer.send_command("s2", &json!({ "type": "roster_subscribe" }));+ assert!(snapshot["data"]["roster"]+ .as_array()+ .unwrap()+ .iter()+ .any(|row| { row["summary"]["rlmChildId"] == "sub-0000" }));+}