Skip to content

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

Rust

fix(daemon): subagent roster and agent_observe fidelity (#3576)

Sebastian Müller2d4951b531fe
diff --git a/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs b/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs
index 211a196e27..116c402dd9 100644
--- a/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs
+++ b/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs
@@ -203,6 +203,7 @@ fn children_host(
agent_dir.to_path_buf(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
sessions.set_identity(ParentIdentity {
rlm_depth: depth,
diff --git a/crates/pa-core/src/session_engine/agent_messaging.rs b/crates/pa-core/src/session_engine/agent_messaging.rs
index e1eb003c7c..2fed2c73f0 100644
--- a/crates/pa-core/src/session_engine/agent_messaging.rs
+++ b/crates/pa-core/src/session_engine/agent_messaging.rs
@@ -532,7 +532,8 @@ mod observe;
pub use observe::{
create_agent_observe_message_preview, normalize_observe_limit, normalize_observe_max_chars,
register_agent_observe_host_handlers, AgentFamilyStatus, AgentObserveActivity,
- AgentObserveController, AgentObserveMessagePreview, AgentObserveSummary,
+ AgentObserveController, AgentObserveListResult, AgentObserveMessagePreview,
+ AgentObserveRecentMessagesResult, AgentObserveSummary,
};
#[cfg(test)]
diff --git a/crates/pa-core/src/session_engine/agent_messaging/observe.rs b/crates/pa-core/src/session_engine/agent_messaging/observe.rs
index eec8030867..edaa09375e 100644
--- a/crates/pa-core/src/session_engine/agent_messaging/observe.rs
+++ b/crates/pa-core/src/session_engine/agent_messaging/observe.rs
@@ -62,6 +62,9 @@ pub struct AgentObserveSummary {
pub session_name: Option<String>,
pub relationship: Option<AgentFamilyRelationship>,
pub runtime_kind: Option<String>,
+ /// The session's working directory (TS marks the field absent for
+ /// roster rows that carry none).
+ pub cwd: Option<String>,
pub status: AgentFamilyStatus,
/// The live activity of a resident session; `None` for family members
/// with no live session in this daemon (TS marks the field absent).
@@ -70,8 +73,19 @@ pub struct AgentObserveSummary {
pub is_streaming: bool,
pub is_compacting: bool,
pub attached_clients: usize,
+ /// The session's persisted message count.
+ pub message_count: Option<u64>,
pub queued_count: usize,
pub is_session_active: bool,
+ /// The parent's live active session id (subagent summaries).
+ pub parent_active_session_id: Option<String>,
+ /// The parent's persisted session id (subagent summaries).
+ pub parent_session_id: Option<String>,
+ /// This subagent's child id under its parent.
+ pub rlm_child_id: Option<String>,
+ /// The session's first user message, preview-capped (an inactive
+ /// child's identity signal; TS `firstMessage`).
+ pub first_message: Option<String>,
}
impl AgentObserveSummary {
@@ -93,10 +107,51 @@ impl AgentObserveSummary {
if let Some(activity) = self.activity {
row["activity"] = json!(activity.as_str());
}
+ // The TS summary spreads these facts in only when the row
+ // carries them.
+ if let Some(cwd) = &self.cwd {
+ row["cwd"] = json!(cwd);
+ }
+ if let Some(message_count) = self.message_count {
+ row["messageCount"] = json!(message_count);
+ }
+ if let Some(parent_active_session_id) = &self.parent_active_session_id {
+ row["parentActiveSessionId"] = json!(parent_active_session_id);
+ }
+ if let Some(parent_session_id) = &self.parent_session_id {
+ row["parentSessionId"] = json!(parent_session_id);
+ }
+ if let Some(rlm_child_id) = &self.rlm_child_id {
+ row["rlmChildId"] = json!(rlm_child_id);
+ }
+ if let Some(first_message) = &self.first_message {
+ row["firstMessage"] = json!(first_message);
+ }
row
}
}
+/// TS `AgentObserveListResult`: the caller's own summary plus the family
+/// roster, which excludes the caller.
+#[derive(Debug, Clone)]
+pub struct AgentObserveListResult {
+ pub current: AgentObserveSummary,
+ pub agents: Vec<AgentObserveSummary>,
+}
+
+/// TS `AgentObserveRecentMessagesResult`: the target's summary plus the
+/// bounded preview window and the clamped bounds.
+#[derive(Debug, Clone)]
+pub struct AgentObserveRecentMessagesResult {
+ pub agent: AgentObserveSummary,
+ pub messages: Vec<AgentObserveMessagePreview>,
+ pub limit: usize,
+ pub max_chars: usize,
+ /// Whether older messages exist beyond the returned window
+ /// (TS `truncated: startIndex > 0`).
+ pub truncated: bool,
+}
+
/// One bounded message preview.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct AgentObserveMessagePreview {
@@ -111,7 +166,7 @@ pub struct AgentObserveMessagePreview {
/// The controller the daemon supplies for `agent_observe.*` requests.
pub trait AgentObserveController: Send + Sync {
- fn list_agents(&self) -> impl Future<Output = anyhow::Result<Vec<AgentObserveSummary>>> + Send;
+ fn list_agents(&self) -> impl Future<Output = anyhow::Result<AgentObserveListResult>> + Send;
fn get_agent(
&self,
target: &str,
@@ -121,7 +176,7 @@ pub trait AgentObserveController: Send + Sync {
target: &str,
limit: usize,
max_chars: usize,
- ) -> impl Future<Output = anyhow::Result<Vec<AgentObserveMessagePreview>>> + Send;
+ ) -> impl Future<Output = anyhow::Result<AgentObserveRecentMessagesResult>> + Send;
}
/// Clamp an observe limit (default 8, range 1..=50).
@@ -295,9 +350,10 @@ pub fn register_agent_observe_host_handlers<C: AgentObserveController + 'static>
move |_payload| {
let controller = controller.clone();
Box::pin(async move {
- let agents = controller.list_agents().await?;
+ let list = controller.list_agents().await?;
Ok(json!({
- "agents": agents.iter().map(AgentObserveSummary::to_value).collect::<Vec<_>>(),
+ "current": list.current.to_value(),
+ "agents": list.agents.iter().map(AgentObserveSummary::to_value).collect::<Vec<_>>(),
}))
})
}
@@ -340,7 +396,7 @@ pub fn register_agent_observe_host_handlers<C: AgentObserveController + 'static>
.or_else(|| payload.data.get("maxChars")),
"agent_observe.recent max_chars",
)?;
- let messages = controller
+ let recent = controller
.recent_messages(
target,
normalize_observe_limit(limit)?,
@@ -348,7 +404,11 @@ pub fn register_agent_observe_host_handlers<C: AgentObserveController + 'static>
)
.await?;
Ok(json!({
- "messages": messages.iter().map(preview_value).collect::<Vec<_>>(),
+ "agent": recent.agent.to_value(),
+ "messages": recent.messages.iter().map(preview_value).collect::<Vec<_>>(),
+ "limit": recent.limit,
+ "maxChars": recent.max_chars,
+ "truncated": recent.truncated,
}))
})
}),
diff --git a/crates/pa-core/src/session_engine/agent_messaging/tests.rs b/crates/pa-core/src/session_engine/agent_messaging/tests.rs
index 211aba4dcf..10886f152a 100644
--- a/crates/pa-core/src/session_engine/agent_messaging/tests.rs
+++ b/crates/pa-core/src/session_engine/agent_messaging/tests.rs
@@ -12,14 +12,20 @@ fn observe_rows_carry_the_typed_status_and_activity() {
session_name: Some("worker".to_string()),
relationship: Some(AgentFamilyRelationship::Child),
runtime_kind: Some("subagent".to_string()),
+ cwd: None,
status: AgentFamilyStatus::Running,
activity: Some(AgentObserveActivity::Tool),
is_current: false,
is_streaming: true,
is_compacting: false,
attached_clients: 1,
+ message_count: None,
queued_count: 0,
is_session_active: true,
+ parent_active_session_id: None,
+ parent_session_id: None,
+ rlm_child_id: None,
+ first_message: None,
};
let value = row.to_value();
assert_eq!(value["status"], "running");
@@ -439,3 +445,148 @@ async fn broadcast_without_family_is_empty_and_failures_settle() {
assert_eq!(receipts[0]["target"], "sib-1");
assert_eq!(receipts[0]["error"], "peer unreachable");
}
+
+/// The static roster the observe handler tests read: the caller's own
+/// row plus one child.
+struct StaticObserveController;
+
+fn observe_row(active_session_id: &str, is_current: bool) -> AgentObserveSummary {
+ AgentObserveSummary {
+ active_session_id: Some(active_session_id.to_string()),
+ session_id: format!("sess-{active_session_id}"),
+ session_name: Some(active_session_id.to_string()),
+ relationship: (!is_current).then_some(AgentFamilyRelationship::Child),
+ runtime_kind: Some("subagent".to_string()),
+ cwd: None,
+ status: AgentFamilyStatus::Running,
+ activity: Some(AgentObserveActivity::Model),
+ is_current,
+ is_streaming: true,
+ is_compacting: false,
+ attached_clients: 0,
+ message_count: None,
+ queued_count: 1,
+ is_session_active: true,
+ parent_active_session_id: None,
+ parent_session_id: None,
+ rlm_child_id: None,
+ first_message: None,
+ }
+}
+
+/// The child row with the supervisor facts TS `AgentObserveAgentSummary`
+/// carries.
+fn child_row() -> AgentObserveSummary {
+ AgentObserveSummary {
+ cwd: Some("/agent/kid".to_string()),
+ message_count: Some(42),
+ parent_active_session_id: Some("me-1".to_string()),
+ parent_session_id: Some("sess-me-1".to_string()),
+ rlm_child_id: Some("sub-kid-1".to_string()),
+ first_message: Some("the task prompt".to_string()),
+ ..observe_row("kid-1", false)
+ }
+}
+
+fn observe_preview(index: usize) -> AgentObserveMessagePreview {
+ AgentObserveMessagePreview {
+ index,
+ role: "user".to_string(),
+ timestamp: Some(index as u64),
+ text: "hello".to_string(),
+ truncated: false,
+ tool_calls: Vec::new(),
+ custom_type: None,
+ }
+}
+
+impl AgentObserveController for StaticObserveController {
+ fn list_agents(&self) -> impl Future<Output = anyhow::Result<AgentObserveListResult>> + Send {
+ std::future::ready(Ok(AgentObserveListResult {
+ current: observe_row("me-1", true),
+ agents: vec![child_row()],
+ }))
+ }
+
+ fn get_agent(
+ &self,
+ target: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<AgentObserveSummary>>> + Send {
+ std::future::ready(Ok((target == "kid-1").then(child_row)))
+ }
+
+ fn recent_messages(
+ &self,
+ _target: &str,
+ limit: usize,
+ max_chars: usize,
+ ) -> impl Future<Output = anyhow::Result<AgentObserveRecentMessagesResult>> + Send {
+ std::future::ready(Ok(AgentObserveRecentMessagesResult {
+ agent: child_row(),
+ messages: (0..3).map(observe_preview).collect(),
+ limit,
+ max_chars,
+ truncated: true,
+ }))
+ }
+}
+
+/// TS `AgentObserveListResult`: the caller's own row rides `current`,
+/// the family roster excludes it, and each row carries the supervisor
+/// facts the roster already holds.
+#[tokio::test]
+async fn observe_list_returns_current_and_family_without_self() {
+ let mut handlers = HostRequestHandlers::default();
+ register_agent_observe_host_handlers(
+ std::sync::Arc::new(StaticObserveController),
+ &mut handlers,
+ );
+ let list = handlers.get("agent_observe.list").unwrap().clone();
+ let response = send_request(&list, json!({})).unwrap();
+ let agents = response
+ .get("agents")
+ .and_then(Value::as_array)
+ .expect("family rows");
+ assert_eq!(agents.len(), 1, "{agents:?}");
+ assert!(
+ agents.iter().all(|row| row["isCurrent"] != true),
+ "the family roster excludes the caller: {agents:?}"
+ );
+ let row = &agents[0];
+ assert_eq!(row["activeSessionId"], "kid-1");
+ assert_eq!(row["relationship"], "child");
+ assert_eq!(row["cwd"], "/agent/kid");
+ assert_eq!(row["messageCount"], 42);
+ assert_eq!(row["parentActiveSessionId"], "me-1");
+ assert_eq!(row["parentSessionId"], "sess-me-1");
+ assert_eq!(row["rlmChildId"], "sub-kid-1");
+ assert_eq!(row["firstMessage"], "the task prompt");
+ let current = response
+ .get("current")
+ .expect("the caller's own row rides the response");
+ assert_eq!(current["activeSessionId"], "me-1");
+ assert_eq!(current["isCurrent"], true);
+ assert_eq!(current["relationship"], Value::Null);
+}
+
+/// TS `AgentObserveRecentMessagesResult`: the preview window rides with
+/// the target summary and the clamped bounds.
+#[tokio::test]
+async fn observe_recent_returns_the_ts_envelope() {
+ let mut handlers = HostRequestHandlers::default();
+ register_agent_observe_host_handlers(
+ std::sync::Arc::new(StaticObserveController),
+ &mut handlers,
+ );
+ let recent = handlers.get("agent_observe.recent").unwrap().clone();
+ let response = send_request(
+ &recent,
+ json!({ "target": "kid-1", "limit": 2, "max_chars": 90 }),
+ )
+ .unwrap();
+ assert_eq!(response["agent"]["activeSessionId"], "kid-1");
+ assert_eq!(response["limit"], 2);
+ assert_eq!(response["maxChars"], 90);
+ assert_eq!(response["truncated"], true);
+ assert_eq!(response["messages"].as_array().map(Vec::len), Some(3));
+}
diff --git a/crates/pa-core/src/session_engine/messages.rs b/crates/pa-core/src/session_engine/messages.rs
index 0a4da4695e..78b647c052 100644
--- a/crates/pa-core/src/session_engine/messages.rs
+++ b/crates/pa-core/src/session_engine/messages.rs
@@ -26,6 +26,10 @@ pub const REFINEMENT_NOTICE_CUSTOM_TYPE: &str = "refinement_notice";
/// DIVERGENCE, operator ruling 2026-09-23): a user-facing disclosure, never
/// model context — `convert_to_llm` drops it.
pub const PROVIDER_RETRY_OUTCOME_CUSTOM_TYPE: &str = "provider_retry_outcome";
+/// TS `MCP_CONNECTION_OUTCOME_CUSTOM_TYPE`: the durable row an MCP
+/// connect/disconnect leaves in the transcript (produced by the TS-era
+/// daemon; the row is bookkeeping, never model context).
+pub const MCP_CONNECTION_OUTCOME_CUSTOM_TYPE: &str = "mcp_connection_outcome";
pub const HEARTBEAT_PROMPT_CUSTOM_TYPE: &str = "heartbeat_prompt";
/// The durable row a detached kernel bash completion admits as the
/// woken turn's injected prompt.
@@ -323,6 +327,7 @@ pub fn convert_to_llm(messages: &[AgentMessage]) -> Vec<AgentMessage> {
SESSION_SLASH_COMMAND_CUSTOM_TYPE
| SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE
| COMPACTION_OUTCOME_CUSTOM_TYPE
+ | MCP_CONNECTION_OUTCOME_CUSTOM_TYPE
| REFINEMENT_OUTCOME_CUSTOM_TYPE
| PROVIDER_RETRY_OUTCOME_CUSTOM_TYPE
| crate::prompts::model_prompts::MODEL_PROMPT_ERROR_CUSTOM_TYPE
@@ -476,6 +481,25 @@ mod tests {
assert!(convert_to_llm(&[AgentMessage::Custom(message)]).is_empty());
}
+ /// TS `MCP_CONNECTION_OUTCOME_CUSTOM_TYPE`: the durable MCP
+ /// login/disconnect line is bookkeeping, never model context.
+ #[test]
+ fn mcp_connection_outcome_row_is_never_context() {
+ // The literal is the on-disk value a TS-era session file carries.
+ let message = pa_types::session::CustomMessage {
+ custom_type: "mcp_connection_outcome".to_string(),
+ content: UserContent::Text("Connected acme (12 tools verified).".to_string()),
+ display: true,
+ details: None,
+ timestamp: 0,
+ rest: serde_json::Map::default(),
+ };
+ assert!(
+ convert_to_llm(&[AgentMessage::Custom(message)]).is_empty(),
+ "the MCP connection outcome row must drop out of model context"
+ );
+ }
+
#[test]
fn bash_output_fences_and_status() {
let rendered = bash_output_to_text(
diff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rs
index fc2be0556b..f5e56150ba 100644
--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs
+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs
@@ -56,6 +56,7 @@ impl AgentSessionEngine {
config.agent_dir.clone(),
link_config.active_session_id.clone(),
std::sync::Arc::clone(&model_refusal_telemetry),
+ link_config.worker_token.clone(),
))
});
let autonomous_driver = std::sync::RwLock::new(std::sync::Arc::new(
diff --git a/crates/pa-daemon/src/agent_messaging.rs b/crates/pa-daemon/src/agent_messaging.rs
index 435747b02a..30c15c7a46 100644
--- a/crates/pa-daemon/src/agent_messaging.rs
+++ b/crates/pa-daemon/src/agent_messaging.rs
@@ -10,7 +10,8 @@ use serde_json::{json, Value};
use pa_core::session_engine::agent_messaging::{
AgentFamilyMember, AgentFamilyRelationship, AgentFamilyStatus, AgentMessageController,
AgentMessageDeliveryStatus, AgentMessageReceipt, AgentMessageSendInput, AgentObserveActivity,
- AgentObserveController, AgentObserveMessagePreview, AgentObserveSummary,
+ AgentObserveController, AgentObserveListResult, AgentObserveMessagePreview,
+ AgentObserveRecentMessagesResult, AgentObserveSummary, AGENT_OBSERVE_PREVIEW_MAX_CHARS,
};
use crate::supervisor_link::SupervisorLink;
diff --git a/crates/pa-daemon/src/agent_messaging/controller_tests.rs b/crates/pa-daemon/src/agent_messaging/controller_tests.rs
index 3bb88a848b..d3795f7d48 100644
--- a/crates/pa-daemon/src/agent_messaging/controller_tests.rs
+++ b/crates/pa-daemon/src/agent_messaging/controller_tests.rs
@@ -6,7 +6,7 @@ use super::*;
use crate::protocol::{response_failure, response_success};
use crate::rlm_children::RlmChildIdentity;
use crate::supervisor_link::SupervisorLink;
-use pa_core::session_engine::agent_messaging::AgentMessageController;
+use pa_core::session_engine::agent_messaging::{AgentMessageController, AgentObserveController};
use pa_types::platform::transport::bind_transport;
use serde_json::{json, Value};
use std::sync::Arc;
@@ -52,6 +52,34 @@ async fn spawn_fake_supervisor(
"list_agent_peers",
Some(json!({ "peers": roster["sessions"] })),
),
+ // The observe controller's roster walk.
+ "list" => response_success(
+ Some(&id),
+ "list",
+ Some(json!({ "sessions": roster["sessions"] })),
+ ),
+ // Target-specific transcripts let resolver regressions prove
+ // which worker was read; older fixtures retain their five-row tail.
+ "get_messages" => {
+ let active = command["activeSessionId"].as_str().unwrap_or_default();
+ let messages = roster["messagesByActiveSessionId"]
+ .get(active)
+ .cloned()
+ .unwrap_or_else(|| {
+ json!([
+ { "role": "user", "content": "m0", "timestamp": 10 },
+ { "role": "user", "content": "m1", "timestamp": 11 },
+ { "role": "user", "content": "m2", "timestamp": 12 },
+ { "role": "user", "content": "m3", "timestamp": 13 },
+ { "role": "user", "content": "m4", "timestamp": 14 },
+ ])
+ });
+ response_success(
+ Some(&id),
+ "get_messages",
+ Some(json!({ "messages": messages })),
+ )
+ }
"get_worker_peer_transport" => match ticket_response.clone() {
Some(ticket) => {
response_success(Some(&id), &command_type, Some(ticket))
@@ -120,12 +148,24 @@ fn controller_with_children(
std::path::PathBuf::from("/agent"),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
let mut controller = controller(socket, own_summary);
controller.children = Some(Arc::new(children));
controller
}
+/// The observe controller over the same scripted supervisor: roster
+/// reads and transcript reads share one link.
+fn observe_controller(socket: std::path::PathBuf) -> LinkAgentObserveController {
+ LinkAgentObserveController::new(
+ Arc::new(SupervisorLink::new(socket)),
+ "aaa111".to_string(),
+ Arc::new(std::sync::Mutex::new(own_summary())),
+ None,
+ )
+}
+
/// Seed the children registry with one admitted child (the same state
/// `rlm.spawn` leaves behind, without the supervisor round trip).
async fn admit_child(controller: &LinkAgentMessageController, child: RlmChildIdentity) {
@@ -935,3 +975,270 @@ async fn family_resolves_a_moved_parent_by_the_session_file_alias() {
assert_eq!(family[0].relationship, AgentFamilyRelationship::Parent);
assert_eq!(family[0].id, "rrr777");
}
+
+/// TS `AgentObserveListResult`: the daemon roster walk splits the
+/// caller's own row into `current` and keeps the family in `agents`.
+#[tokio::test]
+async fn list_agents_returns_current_and_family_without_self() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let socket = dir.path().join("sup.sock");
+ spawn_fake_supervisor(
+ socket.clone(),
+ json!({ "sessions": [
+ { "activeSessionId": "aaa111", "sessionId": "sess-a", "sessionName": "alpha",
+ "cwd": "/w", "messageCount": 7 },
+ { "activeSessionId": "bbb222", "sessionId": "sess-b", "sessionName": "beta" },
+ { "activeSessionId": "ddd444", "sessionId": "sess-d", "sessionName": "kid",
+ "runtimeKind": "subagent",
+ "parentActiveSessionId": "aaa111", "parentSessionId": "sess-a",
+ "rlmChildId": "sub-kid1" },
+ ]}),
+ None,
+ )
+ .await;
+ let observer = observe_controller(socket);
+ let list = observer.list_agents().await.unwrap();
+ assert_eq!(list.current.active_session_id.as_deref(), Some("aaa111"));
+ assert!(list.current.is_current);
+ assert_eq!(
+ list.agents.len(),
+ 2,
+ "the family roster excludes the caller: {:?}",
+ list.agents
+ );
+ assert!(list.agents.iter().all(|summary| !summary.is_current));
+ assert!(
+ list.agents
+ .iter()
+ .any(|summary| summary.active_session_id.as_deref() == Some("bbb222")),
+ "the sibling stays in the roster"
+ );
+ let child = list
+ .agents
+ .iter()
+ .find(|summary| summary.active_session_id.as_deref() == Some("ddd444"))
+ .expect("the child stays in the roster");
+ assert_eq!(child.relationship, Some(AgentFamilyRelationship::Child));
+}
+
+/// TS `AgentObserveRecentMessagesResult`: the transcript read resolves
+/// the family target first (the family gate), then reports the bounded
+/// window with its clamped bounds.
+#[tokio::test]
+async fn recent_messages_resolves_by_name_and_reports_the_envelope() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let socket = dir.path().join("sup.sock");
+ spawn_fake_supervisor(
+ socket.clone(),
+ json!({ "sessions": [
+ { "activeSessionId": "aaa111", "sessionId": "sess-a", "sessionName": "alpha" },
+ { "activeSessionId": "ddd444", "sessionId": "sess-d", "sessionName": "kid",
+ "runtimeKind": "subagent",
+ "parentActiveSessionId": "aaa111", "parentSessionId": "sess-a" },
+ ]}),
+ None,
+ )
+ .await;
+ let observer = observe_controller(socket);
+ let recent = observer.recent_messages("kid", 2, 90).await.unwrap();
+ assert_eq!(recent.agent.active_session_id.as_deref(), Some("ddd444"));
+ assert_eq!(recent.limit, 2);
+ assert_eq!(recent.max_chars, 90);
+ assert!(
+ recent.truncated,
+ "five scripted rows minus two leave older ones"
+ );
+ assert_eq!(recent.messages.len(), 2);
+ assert_eq!(recent.messages[0].index, 3);
+ assert_eq!(recent.messages[0].text, "m3");
+ // A target outside the nuclear family never reaches the transcript read.
+ let error = observer.recent_messages("ghost", 2, 90).await.unwrap_err();
+ assert_eq!(error.to_string(), "agent ghost is not reachable");
+}
+
+#[tokio::test]
+async fn recent_messages_reads_a_degraded_live_sibling_but_not_a_foreign_stub() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let socket = dir.path().join("sup.sock");
+ spawn_fake_supervisor(
+ socket.clone(),
+ json!({ "sessions": [
+ { "activeSessionId": "aaa111", "sessionId": "sess-a",
+ "parentActiveSessionId": "parent", "parentSessionId": "sess-parent" },
+ { "id": "sibling", "sessionId": "", "lifecycle": "recovering",
+ "parentActiveSessionId": "parent", "parentSessionId": "sess-parent" },
+ { "id": "foreign", "sessionId": "", "lifecycle": "recovering" },
+ ], "messagesByActiveSessionId": {
+ "sibling": [{ "role": "user", "content": "sibling transcript" }],
+ "foreign": [{ "role": "user", "content": "foreign transcript" }],
+ }}),
+ None,
+ )
+ .await;
+ let observer = LinkAgentObserveController::new(
+ Arc::new(SupervisorLink::new(socket)),
+ "aaa111".to_string(),
+ Arc::new(std::sync::Mutex::new(Some(json!({
+ "activeSessionId": "aaa111", "sessionId": "sess-a",
+ "parentActiveSessionId": "parent", "parentSessionId": "sess-parent",
+ })))),
+ None,
+ );
+ let recent = observer.recent_messages("sibling", 8, 800).await.unwrap();
+ assert_eq!(
+ recent.agent.relationship,
+ Some(AgentFamilyRelationship::Sibling)
+ );
+ assert_eq!(recent.messages.len(), 1);
+ assert_eq!(recent.messages[0].text, "sibling transcript");
+ assert_eq!(
+ observer
+ .recent_messages("foreign", 8, 800)
+ .await
+ .unwrap_err()
+ .to_string(),
+ "agent foreign is not reachable",
+ );
+}
+
+/// The supervisor roster row's own facts ride the observation summary,
+/// with `firstMessage` capped at the TS preview width.
+#[test]
+fn summaries_carry_the_supervisor_row_facts() {
+ let identity = FamilyIdentity {
+ active_session_id: "ppp000".to_string(),
+ session_id: Some("sess-p".to_string()),
+ session_file: Some("/agent/sessions/sess-p.jsonl".to_string()),
+ ..Default::default()
+ };
+ let sessions = vec![
+ json!({
+ "activeSessionId": "ppp000", "sessionId": "sess-p",
+ "runtimeKind": "top-level", "activity": "idle",
+ "cwd": "/w/agent", "messageCount": 12,
+ }),
+ json!({
+ "activeSessionId": "kid111", "sessionId": "sess-kid",
+ "sessionName": "kid", "runtimeKind": "subagent", "activity": "working",
+ "cwd": "/w/agent/kid", "messageCount": 3,
+ "parentActiveSessionId": "ppp000", "parentSessionId": "sess-p",
+ "rlmChildId": "sub-kid1", "firstMessage": "x".repeat(300),
+ }),
+ ];
+ let summaries = summaries_from_roster(sessions, &identity, &[]);
+ let child = summaries
+ .iter()
+ .find(|summary| summary.session_id == "sess-kid")
+ .expect("the child row");
+ assert_eq!(child.cwd.as_deref(), Some("/w/agent/kid"));
+ assert_eq!(child.message_count, Some(3));
+ assert_eq!(child.parent_active_session_id.as_deref(), Some("ppp000"));
+ assert_eq!(child.parent_session_id.as_deref(), Some("sess-p"));
+ assert_eq!(child.rlm_child_id.as_deref(), Some("sub-kid1"));
+ assert_eq!(
+ child.first_message.as_ref().map(String::len),
+ Some(240),
+ "firstMessage caps at the TS preview width"
+ );
+ let current = summaries
+ .iter()
+ .find(|summary| summary.is_current)
+ .expect("the caller's own row");
+ assert_eq!(current.cwd.as_deref(), Some("/w/agent"));
+ assert_eq!(current.message_count, Some(12));
+}
+
+/// Normalized active-id and durable-id suffixes still resolve through the
+/// nuclear family to the correct worker transcript (the pre-PR registry contract).
+#[tokio::test]
+async fn observe_recent_suffixes_read_the_selected_family_transcript() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let socket = dir.path().join("sup.sock");
+ spawn_fake_supervisor(socket.clone(), json!({
+ "sessions": [
+ { "activeSessionId": "aaa111", "sessionId": "sess-a" },
+ { "activeSessionId": "abcddd444", "sessionId": "deadbeef-112233",
+ "runtimeKind": "subagent", "parentActiveSessionId": "aaa111", "parentSessionId": "sess-a" },
+ ],
+ "messagesByActiveSessionId": {
+ "aaa111": [{ "role": "user", "content": "wrong parent transcript", "timestamp": 1 }],
+ "abcddd444": [{ "role": "user", "content": "selected child transcript", "timestamp": 2 }],
+ },
+ }), None).await;
+ let observer = observe_controller(socket);
+ for selector in ["DD-D444", "11-2233"] {
+ let recent = observer.recent_messages(selector, 1, 80).await.unwrap();
+ assert_eq!(recent.agent.active_session_id.as_deref(), Some("abcddd444"));
+ assert_eq!(recent.messages[0].text, "selected child transcript");
+ }
+}
+
+/// Names may repeat across parent/child scopes. An ambiguous family name
+/// never authorizes whichever transcript happened to arrive first in the roster.
+#[tokio::test]
+async fn observe_recent_rejects_duplicate_family_names() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let socket = dir.path().join("sup.sock");
+ spawn_fake_supervisor(socket.clone(), json!({ "sessions": [
+ { "activeSessionId": "aaa111", "sessionId": "sess-a", "sessionName": "reviewer" },
+ { "activeSessionId": "ddd444", "sessionId": "sess-d", "sessionName": "reviewer",
+ "runtimeKind": "subagent", "parentActiveSessionId": "aaa111", "parentSessionId": "sess-a" },
+ ]}), None).await;
+ let error = observe_controller(socket)
+ .recent_messages("reviewer", 1, 80)
+ .await
+ .unwrap_err();
+ assert!(
+ error.to_string().contains("Ambiguous active session"),
+ "{error}"
+ );
+}
+
+/// The exact active id outranks a different family member named after it,
+/// matching the registry's direct lookup before its suffix/name search.
+#[tokio::test]
+async fn observe_recent_exact_active_id_outranks_a_name_collision() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let socket = dir.path().join("sup.sock");
+ spawn_fake_supervisor(socket.clone(), json!({
+ "sessions": [
+ { "activeSessionId": "aaa111", "sessionId": "sess-a" },
+ { "activeSessionId": "fff555", "sessionId": "sess-f", "sessionName": "ddd444",
+ "runtimeKind": "subagent", "parentActiveSessionId": "aaa111", "parentSessionId": "sess-a" },
+ { "activeSessionId": "ddd444", "sessionId": "sess-d",
+ "runtimeKind": "subagent", "parentActiveSessionId": "aaa111", "parentSessionId": "sess-a" },
+ ],
+ "messagesByActiveSessionId": {
+ "fff555": [{ "role": "user", "content": "wrong name collision", "timestamp": 1 }],
+ "ddd444": [{ "role": "user", "content": "exact active transcript", "timestamp": 2 }],
+ },
+ }), None).await;
+ let recent = observe_controller(socket)
+ .recent_messages("ddd444", 1, 80)
+ .await
+ .unwrap();
+ assert_eq!(recent.messages[0].text, "exact active transcript");
+}
+
+/// Suffix resolution must stay inside the nuclear family; a known foreign
+/// worker with a matching suffix never becomes readable.
+#[tokio::test]
+async fn observe_recent_suffix_does_not_read_a_foreign_transcript() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let socket = dir.path().join("sup.sock");
+ spawn_fake_supervisor(socket.clone(), json!({
+ "sessions": [
+ { "activeSessionId": "aaa111", "sessionId": "sess-a" },
+ { "activeSessionId": "fffddd444", "sessionId": "foreign-id", "sessionName": "foreign",
+ "runtimeKind": "subagent", "parentActiveSessionId": "zzz999", "parentSessionId": "foreign-parent" },
+ ],
+ "messagesByActiveSessionId": {
+ "fffddd444": [{ "role": "user", "content": "foreign private transcript", "timestamp": 1 }],
+ },
+ }), None).await;
+ let error = observe_controller(socket)
+ .recent_messages("ddd444", 1, 80)
+ .await
+ .unwrap_err();
+ assert_eq!(error.to_string(), "agent ddd444 is not reachable");
+}
diff --git a/crates/pa-daemon/src/agent_messaging/observe.rs b/crates/pa-daemon/src/agent_messaging/observe.rs
index 0fcb542fb1..33132ac6fe 100644
--- a/crates/pa-daemon/src/agent_messaging/observe.rs
+++ b/crates/pa-daemon/src/agent_messaging/observe.rs
@@ -2,9 +2,10 @@
//! summaries from the supervisor, the nuclear-family roster derivation, and
//! the preview text helpers.
use super::{
- json, row_is_child, row_is_parent, row_is_sibling, AgentFamilyRelationship, AgentFamilyStatus,
- AgentObserveActivity, AgentObserveController, AgentObserveMessagePreview, AgentObserveSummary,
- Arc, FamilyIdentity, SupervisorLink, Value,
+ json, row_is_child, row_is_parent, row_is_sibling, row_str, AgentFamilyRelationship,
+ AgentFamilyStatus, AgentObserveActivity, AgentObserveController, AgentObserveListResult,
+ AgentObserveMessagePreview, AgentObserveRecentMessagesResult, AgentObserveSummary, Arc,
+ FamilyIdentity, SupervisorLink, Value, AGENT_OBSERVE_PREVIEW_MAX_CHARS,
};
/// `agent_observe.*` controller for daemon workers: message previews and
@@ -76,25 +77,106 @@ impl LinkAgentObserveController {
None => Vec::new(),
}
}
-}
-impl AgentObserveController for LinkAgentObserveController {
- async fn list_agents(&self) -> anyhow::Result<Vec<AgentObserveSummary>> {
+ /// The nuclear-family summaries every observe handler reads: one
+ /// roster walk plus the registry join.
+ async fn family_summaries(&self) -> anyhow::Result<Vec<AgentObserveSummary>> {
let (sessions, identity) = self.roster_and_identity().await?;
let child_ids = self.registry_child_active_ids().await;
Ok(summaries_from_roster(sessions, &identity, &child_ids))
}
- async fn get_agent(&self, target: &str) -> anyhow::Result<Option<AgentObserveSummary>> {
- let (sessions, identity) = self.roster_and_identity().await?;
- let child_ids = self.registry_child_active_ids().await;
- Ok(summaries_from_roster(sessions, &identity, &child_ids)
+ /// The caller's own summary from its pushed state alone, no roster
+ /// read: the row `list_agents` serves when the walk missed this
+ /// session's live row.
+ fn current_summary(&self) -> Option<AgentObserveSummary> {
+ let own = self
+ .own_summary
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()?;
+ let identity = FamilyIdentity::from_summary(Some(&own), &self.active_session_id);
+ summaries_from_roster(vec![own], &identity, &[])
.into_iter()
- .find(|summary| {
- summary.active_session_id.as_deref() == Some(target)
- || summary.session_id == target
- || summary.session_name.as_deref() == Some(target)
- }))
+ .next()
+ }
+}
+
+/// Resolve within the nuclear family using the registry's normalized id-suffix
+/// and exact-name contract. Exact active ids retain direct-lookup precedence.
+fn find_target(
+ mut summaries: Vec<AgentObserveSummary>,
+ target: &str,
+) -> anyhow::Result<Option<AgentObserveSummary>> {
+ if let Some(at) = summaries
+ .iter()
+ .position(|summary| summary.active_session_id.as_deref() == Some(target))
+ {
+ return Ok(Some(summaries.remove(at)));
+ }
+ let mut matches: Vec<_> = summaries
+ .into_iter()
+ .filter(|summary| {
+ summary
+ .active_session_id
+ .as_deref()
+ .is_some_and(|id| crate::registry::selector_matches(id, target))
+ || crate::registry::selector_matches(&summary.session_id, target)
+ || summary.session_name.as_deref() == Some(target)
+ })
+ .collect();
+ if matches.len() > 1 {
+ let rendered = matches
+ .iter()
+ .map(|summary| {
+ let id = summary
+ .active_session_id
+ .as_deref()
+ .unwrap_or(&summary.session_id);
+ summary
+ .session_name
+ .as_deref()
+ .filter(|name| !name.is_empty())
+ .map_or_else(|| id.to_string(), |name| format!("{id} ({name})"))
+ })
+ .collect::<Vec<_>>()
+ .join(", ");
+ anyhow::bail!("Ambiguous active session \"{target}\": matches {rendered}");
+ }
+ Ok(matches.pop())
+}
+
+impl AgentObserveController for LinkAgentObserveController {
+ async fn list_agents(&self) -> anyhow::Result<AgentObserveListResult> {
+ let mut summaries = self.family_summaries().await?;
+ // TS `requireCurrentState`: the caller's own row always rides the
+ // list response. The roster walk can miss it when the caller's own
+ // worker `get_state` degraded to the offline stub, so fall back to
+ // the pushed own summary before erroring.
+ let own_row = || {
+ self.current_summary().ok_or_else(|| {
+ anyhow::anyhow!("Agent observe state is not ready for this session yet")
+ })
+ };
+ let current = match summaries.iter().position(|summary| summary.is_current) {
+ // A degraded own row is the offline stub (empty sessionId, no
+ // activeSessionId): never serve it as `current` — drop it and
+ // serve the pushed own summary instead.
+ Some(at) if !summaries[at].session_id.is_empty() => summaries.remove(at),
+ Some(at) => {
+ summaries.remove(at);
+ own_row()?
+ }
+ None => own_row()?,
+ };
+ Ok(AgentObserveListResult {
+ current,
+ agents: summaries,
+ })
+ }
+
+ async fn get_agent(&self, target: &str) -> anyhow::Result<Option<AgentObserveSummary>> {
+ find_target(self.family_summaries().await?, target)
}
async fn recent_messages(
@@ -102,13 +184,29 @@ impl AgentObserveController for LinkAgentObserveController {
target: &str,
limit: usize,
max_chars: usize,
- ) -> anyhow::Result<Vec<AgentObserveMessagePreview>> {
+ ) -> anyhow::Result<AgentObserveRecentMessagesResult> {
+ let agent = find_target(self.family_summaries().await?, target)?
+ .ok_or_else(|| anyhow::anyhow!("agent {target} is not reachable"))?;
+ // A family member with no live session (a passivated child) has no
+ // worker to read; TS hydrates it first, the roster walk errors. A
+ // live member whose `get_state` degraded shows the offline stub
+ // (empty sessionId, no activeSessionId — classified Inactive): its
+ // row still carries the session id, so read the transcript through
+ // it instead of refusing a session that is live, just slow.
+ let degraded_stub = agent.session_id.is_empty();
+ let Some(live_session_id) = agent
+ .active_session_id
+ .as_deref()
+ .filter(|_| degraded_stub || agent.status != AgentFamilyStatus::Inactive)
+ else {
+ anyhow::bail!("agent {target} has no live session");
+ };
let data = self
.link
.request_success(
json!({
"type": "get_messages",
- "activeSessionId": target,
+ "activeSessionId": live_session_id,
}),
std::time::Duration::from_secs(30),
)
@@ -140,7 +238,13 @@ impl AgentObserveController for LinkAgentObserveController {
.map(str::to_string),
});
}
- Ok(previews)
+ Ok(AgentObserveRecentMessagesResult {
+ agent,
+ messages: previews,
+ limit,
+ max_chars,
+ truncated: start > 0,
+ })
}
}
@@ -256,14 +360,25 @@ pub(super) fn summaries_from_roster(
.map(str::to_string),
relationship,
runtime_kind: Some(runtime_kind),
+ cwd: row_str(&session, "cwd").map(str::to_string),
status,
activity: has_live_session.then_some(activity),
is_current,
is_streaming,
is_compacting,
attached_clients,
+ message_count: session.get("messageCount").and_then(Value::as_u64),
queued_count: queued,
is_session_active,
+ // TS `AgentObserveAgentSummary`: the parent edges and the
+ // child id ride the row when the roster carries them; the
+ // preview cap bounds an inactive child's first message.
+ parent_active_session_id: row_str(&session, "parentActiveSessionId")
+ .map(str::to_string),
+ parent_session_id: row_str(&session, "parentSessionId").map(str::to_string),
+ rlm_child_id: row_str(&session, "rlmChildId").map(str::to_string),
+ first_message: row_str(&session, "firstMessage")
+ .map(|text| truncate_chars(text, AGENT_OBSERVE_PREVIEW_MAX_CHARS)),
})
})
.collect()
diff --git a/crates/pa-daemon/src/rlm_children.rs b/crates/pa-daemon/src/rlm_children.rs
index ba28bd4797..ba35bc9533 100644
--- a/crates/pa-daemon/src/rlm_children.rs
+++ b/crates/pa-daemon/src/rlm_children.rs
@@ -130,6 +130,23 @@ pub(crate) fn durable_child_selector(session_id: Option<&str>, rlm_child_id: &st
session_id.unwrap_or(rlm_child_id).to_string()
}
+/// Peer rows can contain pushed snapshots or older supervisor pulls.
+/// At equal embedded counters retain a direct observation conservatively;
+/// a greater counter refreshes either source normally.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+enum ChildObservationSource {
+ Roster,
+ Direct,
+}
+
+#[derive(Debug)]
+struct ChildObservation {
+ request_order: u64,
+ worker_instance_id: Option<String>,
+ sequence: Option<u64>,
+ source: ChildObservationSource,
+}
+
/// One tracked child session.
#[derive(Debug)]
struct ChildRecord {
@@ -157,6 +174,18 @@ struct ChildRecord {
/// A child agent message arrived since its task was admitted; the
/// no-reply terminal notice is withheld once set.
replied_since_task: bool,
+ /// The latest progress note the parent observed on the child's live
+ /// summary (the supervisor roster join, a refresh's `get_state`); a
+ /// settled row keeps it — the child clears its own note at its run
+ /// boundaries, so only what a read saw survives one.
+ progress_note: Option<String>,
+ /// The child's tool-call count as last observed live; `None` until a
+ /// read saw one (the wire omits a zero count, TS parity).
+ tool_use_count: Option<u64>,
+ /// Freshness of the last live summary, shared by roster and direct reads.
+ live_observation: Option<ChildObservation>,
+ /// Direct reads establish process generations in capture order.
+ direct_observation: Arc<Mutex<()>>,
/// The terminal notice was claimed: exactly one of the settle watcher,
/// the delete path, or a late natural settle delivers it.
notice_delivered: bool,
@@ -338,6 +367,11 @@ struct SupervisorChildSessionsInner {
link: Arc<SupervisorLink>,
agent_dir: PathBuf,
parent_active_session_id: String,
+ /// The worker's supervisor token: the roster read that joins the
+ /// children's live summaries authenticates with it.
+ worker_token: String,
+ /// Request-start order for independent roster and child-state connections.
+ observation_requests: std::sync::atomic::AtomicU64,
/// The parent session's live name (the worker's summary, the TS
/// `sessionName` of every spawn row's `from` endpoint): `None` until
/// the worker publishes a summary, and refreshed by every rename.
@@ -398,18 +432,25 @@ impl Clone for SupervisorChildSessions {
}
impl SupervisorChildSessions {
- /// Children registry bound to one parent session worker.
+ /// Children registry bound to one parent session worker. The worker's
+ /// supervisor token is known at construction (the daemon hands the same
+ /// config to the message controllers) and rides the registry from the
+ /// start: a roster read that joins the children's live summaries
+ /// authenticates with it.
pub fn new(
link: Arc<SupervisorLink>,
agent_dir: PathBuf,
parent_active_session_id: String,
model_refusal_telemetry: std::sync::Arc<crate::model_allowlist::ModelRefusalTelemetry>,
+ worker_token: String,
) -> Self {
Self {
inner: Arc::new(SupervisorChildSessionsInner {
link,
agent_dir,
parent_active_session_id,
+ worker_token,
+ observation_requests: std::sync::atomic::AtomicU64::new(0),
parent_session_name: std::sync::Mutex::new(None),
identity: std::sync::Mutex::new(ParentIdentity::with_default_depth()),
children: Mutex::new(Vec::new()),
@@ -693,6 +734,10 @@ impl SupervisorChildSessions {
answer_text: None,
answer_captured: false,
replied_since_task: false,
+ progress_note: None,
+ tool_use_count: None,
+ live_observation: None,
+ direct_observation: Arc::new(Mutex::new(())),
notice_delivered: false,
prompt_admitted: true,
error: None,
@@ -767,11 +812,11 @@ impl SupervisorChildSessions {
kind: "executing",
tool_name: None,
}),
- tool_use_count: None,
+ tool_use_count: record.tool_use_count,
duration_ms: Some(now_ms().saturating_sub(record.started_at_ms)),
answer_preview: record.answer_preview.clone(),
- replied_since_task: None,
- progress_note: None,
+ replied_since_task: Some(record.replied_since_task),
+ progress_note: record.progress_note.clone(),
label: (!record.label.is_empty()).then(|| record.label.clone()),
last_activity_at: Some(record.started_at_ms),
activity_stale_ms: None,
@@ -789,8 +834,8 @@ impl SupervisorChildSessions {
answer_text: record.answer_text.clone(),
error: record.error.clone(),
duration_ms: Some(now_ms().saturating_sub(record.started_at_ms)),
- tool_use_count: None,
- replied_since_task: None,
+ tool_use_count: record.tool_use_count,
+ replied_since_task: Some(record.replied_since_task),
}
}
@@ -853,6 +898,105 @@ impl SupervisorChildSessionsInner {
});
}
+ /// The supervisor's pushed worker roster (`list_agent_peers`): one
+ /// in-memory read per roster call, no child-worker round trip. `None`
+ /// when no child is live (settled rows keep their cached values), or
+ /// when the supervisor is unreachable: the rows keep the last observed
+ /// values instead of failing the read.
+ pub(super) async fn child_roster_rows(
+ &self,
+ records: &[Arc<Mutex<ChildRecord>>],
+ ) -> Option<Vec<Value>> {
+ let running = async {
+ for record in records {
+ if record.lock().await.settled_status.is_none() {
+ return true;
+ }
+ }
+ false
+ }
+ .await;
+ if !running {
+ return None;
+ }
+ let data = self
+ .link
+ .request_success(
+ json!({ "type": "list_agent_peers", "workerToken": self.worker_token }),
+ Duration::from_secs(5),
+ )
+ .await
+ .ok()?;
+ Some(
+ data.get("peers")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default(),
+ )
+ }
+
+ /// Merge both read paths by the worker's captured counter, not response
+ /// arrival. Request order breaks ties within one process generation.
+ pub(super) async fn observe_live_state(
+ &self,
+ record: &Arc<Mutex<ChildRecord>>,
+ summary: &Value,
+ request_order: u64,
+ source: ChildObservationSource,
+ ) {
+ let observation = ChildObservation {
+ request_order,
+ worker_instance_id: summary
+ .get("workerInstanceId")
+ .and_then(Value::as_str)
+ .filter(|instance| !instance.is_empty())
+ .map(str::to_string),
+ sequence: summary.get("rosterDeltaSequence").and_then(Value::as_u64),
+ source,
+ };
+ let direct_observation = {
+ let record = record.lock().await;
+ Arc::clone(&record.direct_observation)
+ };
+ // A roster read must not initialize a generation while an older
+ // direct request is in flight, and must never wait behind that request.
+ let _roster_guard = match source {
+ ChildObservationSource::Roster => match direct_observation.try_lock() {
+ Ok(guard) => Some(guard),
+ Err(_) => return,
+ },
+ ChildObservationSource::Direct => None,
+ };
+ let mut record = record.lock().await;
+ if let Some(previous) = &record.live_observation {
+ let fresh = if observation.worker_instance_id == previous.worker_instance_id {
+ match (observation.sequence, previous.sequence) {
+ (Some(sequence), Some(previous_sequence)) => {
+ (sequence, source, request_order)
+ > (previous_sequence, previous.source, previous.request_order)
+ }
+ _ => request_order > previous.request_order,
+ }
+ } else {
+ // Only serialized direct reads establish a replacement.
+ source == ChildObservationSource::Direct
+ };
+ if !fresh {
+ return;
+ }
+ if observation.worker_instance_id != previous.worker_instance_id {
+ record.progress_note = None;
+ record.tool_use_count = None;
+ }
+ }
+ if let Some(note) = summary.get("progressNote").and_then(Value::as_str) {
+ record.progress_note = Some(note.to_string());
+ }
+ // An omitted count is zero, including after a session replacement.
+ record.tool_use_count = summary.get("toolUseCount").and_then(Value::as_u64);
+ record.live_observation = Some(observation);
+ }
+
pub(crate) async fn emit_child_update(&self, record: &Arc<Mutex<ChildRecord>>) {
let sink = self
.child_update_sink
diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rs
index 0be796751b..cbaef9a905 100644
--- a/crates/pa-daemon/src/rlm_children/host.rs
+++ b/crates/pa-daemon/src/rlm_children/host.rs
@@ -5,11 +5,12 @@
use super::{
assert_thinking_supported, bail, create_default_rlm_subagent_session_name, json, now_ms,
resolve_child_model, rlm_child_label, rlm_depth_limit_error, spawn_name_unavailable_error, Arc,
- ChildCloseReason, ChildRecord, Context, DaemonCommand, Duration, Instant, Mutex, Path, PathBuf,
- Result, RlmChildResult, RlmCreateSessionHandle, RlmCreateSessionRequest,
- RlmDeleteSubagentResult, RlmHostFuture, RlmSpawnHandle, RlmSpawnRequest, RlmSubagentEntry,
- RlmSubagentHost, SpawnNameReservationGuard, SupervisorChildSessions,
- SupervisorChildSessionsInner, Value, KILL_TIMEOUT_MS, RENAME_TIMEOUT_MS,
+ ChildCloseReason, ChildObservationSource, ChildRecord, Context, DaemonCommand, Duration,
+ Instant, Mutex, Path, PathBuf, Result, RlmChildResult, RlmCreateSessionHandle,
+ RlmCreateSessionRequest, RlmDeleteSubagentResult, RlmHostFuture, RlmSpawnHandle,
+ RlmSpawnRequest, RlmSubagentEntry, RlmSubagentHost, SpawnNameReservationGuard,
+ SupervisorChildSessions, SupervisorChildSessionsInner, Value, KILL_TIMEOUT_MS,
+ RENAME_TIMEOUT_MS,
};
/// Resolve the child model with the daemon `allowedModels` allowlist enforced, refusing loudly with
@@ -164,6 +165,10 @@ impl RlmSubagentHost for SupervisorChildSessions {
answer_text: None,
answer_captured: false,
replied_since_task: false,
+ progress_note: None,
+ tool_use_count: None,
+ live_observation: None,
+ direct_observation: Arc::new(Mutex::new(())),
notice_delivered: false,
prompt_admitted: false,
error: None,
@@ -372,10 +377,49 @@ impl RlmSubagentHost for SupervisorChildSessions {
let this = Arc::clone(&self.inner);
Box::pin(async move {
let records = this.children.lock().await.clone();
+ // The children's live note and tool count join from the
+ // supervisor's pushed roster: one in-memory read, never a busy
+ // child worker round trip. A failed read keeps the last values
+ // each record observed; the settle watcher owns worker refreshes.
+ let request_order = this
+ .observation_requests
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ if let Some(peers) = this.child_roster_rows(&records).await {
+ for record in &records {
+ let (rlm_child_id, active_session_id) = {
+ let record = record.lock().await;
+ (
+ record.rlm_child_id.clone(),
+ record.active_session_id.clone(),
+ )
+ };
+ let live = peers
+ .iter()
+ .find(|row| {
+ row.get("rlmChildId").and_then(Value::as_str)
+ == Some(rlm_child_id.as_str())
+ })
+ .or_else(|| {
+ peers.iter().find(|row| {
+ row.get("activeSessionId").and_then(Value::as_str)
+ == Some(active_session_id.as_str())
+ })
+ });
+ if let Some(live) = live {
+ this.observe_live_state(
+ record,
+ live,
+ request_order,
+ ChildObservationSource::Roster,
+ )
+ .await;
+ }
+ }
+ }
let mut entries = Vec::with_capacity(records.len());
for record in &records {
- // The settle watcher owns worker refreshes. A roster read is a
- // snapshot and must not queue behind a long supervisor request.
+ // A roster read is a snapshot: the rows serve the records'
+ // last observed state without another round trip.
let record = record.lock().await;
entries.push(SupervisorChildSessions::entry(&record));
}
diff --git a/crates/pa-daemon/src/rlm_children/lifecycle.rs b/crates/pa-daemon/src/rlm_children/lifecycle.rs
index 7315365ea0..662ba82933 100644
--- a/crates/pa-daemon/src/rlm_children/lifecycle.rs
+++ b/crates/pa-daemon/src/rlm_children/lifecycle.rs
@@ -3,13 +3,13 @@
//! spawn-admission outbox types (`CreatedSessionIds`, `CreatedChild`).
use super::{
anyhow, cap_text, compact_rlm_text, create_rlm_child_failure_message,
- create_rlm_child_terminal_notice, json, now_ms, Arc, ChildCloseReason, ChildRecord, Context,
- CustomMessage, DaemonCommand, DaemonSessionLifecycle, Duration, Map, Mutex, ParentIdentity,
- Path, PromptInput, Result, RlmChildTerminalNotice, SupervisorChildSessionsInner, Value,
- ANSWER_TEXT_MAX_CHARS, CREATE_TIMEOUT_MS, IDLE_WAIT_GRACE_MS, KILL_TIMEOUT_MS,
- NOTICE_DELIVERY_TIMEOUT_MS, PROMPT_TIMEOUT_MS, RUNTIME_METADATA_PROMPT_MAX, STATE_TIMEOUT_MS,
- WATCH_MAX_UNREACHABLE_POLLS, WATCH_POLL_INTERVAL_MS, WATCH_SETTLE_GRACE_MS,
- WATCH_WAIT_SLICE_MS,
+ create_rlm_child_terminal_notice, json, now_ms, Arc, ChildCloseReason, ChildObservationSource,
+ ChildRecord, Context, CustomMessage, DaemonCommand, DaemonSessionLifecycle, Duration, Map,
+ Mutex, ParentIdentity, Path, PromptInput, Result, RlmChildTerminalNotice,
+ SupervisorChildSessionsInner, Value, ANSWER_TEXT_MAX_CHARS, CREATE_TIMEOUT_MS,
+ IDLE_WAIT_GRACE_MS, KILL_TIMEOUT_MS, NOTICE_DELIVERY_TIMEOUT_MS, PROMPT_TIMEOUT_MS,
+ RUNTIME_METADATA_PROMPT_MAX, STATE_TIMEOUT_MS, WATCH_MAX_UNREACHABLE_POLLS,
+ WATCH_POLL_INTERVAL_MS, WATCH_SETTLE_GRACE_MS, WATCH_WAIT_SLICE_MS,
};
/// Parsed ids of one created child session.
@@ -344,26 +344,24 @@ impl SupervisorChildSessionsInner {
Ok(())
}
- /// Whether the child worker still has work in flight (streaming,
- /// queued, or its own children still running - so a child stays
- /// running while any descendant does). `Err` means the child cannot be
- /// reached right now.
- pub(super) async fn child_busy(&self, active_session_id: &str) -> Result<bool> {
+ /// The child's live session summary (`get_state`): the busy verdict,
+ /// the note, and the tool count read one round trip.
+ pub(super) async fn child_state(&self, active_session_id: &str) -> Result<Value> {
let command = DaemonCommand::GetState {
id: None,
active_session_id: active_session_id.to_string(),
rest: Map::default(),
};
- let state = self.command(&command, STATE_TIMEOUT_MS).await?;
- let flag = |name: &str| state.get(name).and_then(Value::as_bool).unwrap_or(false);
- Ok(flag("isStreaming")
- || flag("hasRunningSubagents")
- || state
- .get("sessionActions")
- .and_then(|actions| actions.get("queuedCount"))
- .and_then(Value::as_u64)
- .unwrap_or(0)
- > 0)
+ self.command(&command, STATE_TIMEOUT_MS).await
+ }
+
+ /// Whether the child worker still has work in flight (streaming,
+ /// queued, or its own children still running - so a child stays
+ /// running while any descendant does). `Err` means the child cannot be
+ /// reached right now.
+ pub(super) async fn child_busy(&self, active_session_id: &str) -> Result<bool> {
+ let state = self.child_state(active_session_id).await?;
+ Ok(child_busy_flags(&state))
}
/// One `GetLastAssistantText` round trip: the raw text the roster
@@ -408,7 +406,8 @@ impl SupervisorChildSessionsInner {
}
/// Refresh one record against its worker: settle a child whose worker ran out of work and
- /// capture its answer once; an unreachable child keeps its last known state.
+ /// capture its answer once; an unreachable child keeps its last known state. The same
+ /// round trip observes the child's live note and tool count onto the record.
pub(super) async fn refresh_record(&self, record: &Arc<Mutex<ChildRecord>>) {
{
let record = record.lock().await;
@@ -416,9 +415,32 @@ impl SupervisorChildSessionsInner {
return;
}
}
- let active_session_id = record.lock().await.active_session_id.clone();
- let busy = self.child_busy(&active_session_id).await;
- if !matches!(busy, Ok(false)) {
+ let (active_session_id, direct_observation) = {
+ let record = record.lock().await;
+ (
+ record.active_session_id.clone(),
+ Arc::clone(&record.direct_observation),
+ )
+ };
+ let state = {
+ let _direct = direct_observation.lock().await;
+ let request_order = self
+ .observation_requests
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ let state = self.child_state(&active_session_id).await;
+ if let Ok(state) = &state {
+ self.observe_live_state(
+ record,
+ state,
+ request_order,
+ ChildObservationSource::Direct,
+ )
+ .await;
+ }
+ state
+ };
+ let idle = matches!(&state, Ok(state) if !child_busy_flags(state));
+ if !idle {
return;
}
// Capture the answer before taking the record lock (the capture is
@@ -840,6 +862,20 @@ pub(super) fn last_assistant_text_from_file(session_file: &str) -> Option<String
None
}
+/// The busy flags of one child `get_state` summary (streaming, its own
+/// descendants, or queued work in flight).
+fn child_busy_flags(state: &Value) -> bool {
+ let flag = |name: &str| state.get(name).and_then(Value::as_bool).unwrap_or(false);
+ flag("isStreaming")
+ || flag("hasRunningSubagents")
+ || state
+ .get("sessionActions")
+ .and_then(|actions| actions.get("queuedCount"))
+ .and_then(Value::as_u64)
+ .unwrap_or(0)
+ > 0
+}
+
#[cfg(test)]
mod exit_capture_tests {
use super::*;
diff --git a/crates/pa-daemon/src/rlm_children/registry.rs b/crates/pa-daemon/src/rlm_children/registry.rs
index 00945ed9e7..f95161a9cb 100644
--- a/crates/pa-daemon/src/rlm_children/registry.rs
+++ b/crates/pa-daemon/src/rlm_children/registry.rs
@@ -520,6 +520,10 @@ fn ledger_child_records(
answer_text: None,
answer_captured: false,
replied_since_task: false,
+ progress_note: None,
+ tool_use_count: None,
+ live_observation: None,
+ direct_observation: Arc::new(Mutex::new(())),
notice_delivered: true,
prompt_admitted: true,
error: None,
diff --git a/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rs b/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rs
index 4b2a538b00..24107cdb5b 100644
--- a/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rs
+++ b/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rs
@@ -144,6 +144,7 @@ async fn sessions_with_gated_supervisor(
std::env::temp_dir(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
sessions.set_identity(ParentIdentity {
model: Some("mock/mock-1".to_string()),
diff --git a/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs b/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs
index a98985b8b1..82bd6c2a0d 100644
--- a/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs
+++ b/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs
@@ -57,6 +57,10 @@ fn record_with_file(child_id: &str, session_file: &Path) -> Arc<Mutex<ChildRecor
answer_text: None,
answer_captured: false,
replied_since_task: false,
+ progress_note: None,
+ tool_use_count: None,
+ live_observation: None,
+ direct_observation: Arc::new(Mutex::new(())),
notice_delivered: false,
prompt_admitted: true,
error: None,
@@ -88,6 +92,7 @@ fn registry(agent_dir: &Path) -> SupervisorChildSessions {
agent_dir.to_path_buf(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
)
}
@@ -596,6 +601,7 @@ async fn retirement_registry(
dir.to_path_buf(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
(registry, kills, commands, task)
}
diff --git a/crates/pa-daemon/src/rlm_children/watch_tests.rs b/crates/pa-daemon/src/rlm_children/watch_tests.rs
index 3b1295e091..188f5fdddc 100644
--- a/crates/pa-daemon/src/rlm_children/watch_tests.rs
+++ b/crates/pa-daemon/src/rlm_children/watch_tests.rs
@@ -41,15 +41,28 @@ enum FakeChild {
/// deliveries). `idle_delay_ms` paces `wait_for_idle` so a test can act
/// while the child is still "running". `child` scripts the child link
/// (`FakeChild`).
+/// The fake supervisor's scripted answers: the kill and child behaviors
+/// plus the pushed worker roster `list_agent_peers` serves.
+struct FakeSupervisorScript {
+ kill: FakeKill,
+ child: FakeChild,
+ child_subagents: Arc<FakeChildSubagents>,
+ peers: Arc<std::sync::Mutex<Vec<Value>>>,
+}
+
async fn spawn_fake_supervisor(
socket: std::path::PathBuf,
follow_up_tx: mpsc::UnboundedSender<Value>,
idle_delay_ms: u64,
kill_tx: mpsc::UnboundedSender<Value>,
- kill_behavior: FakeKill,
- child: FakeChild,
- child_subagents: Arc<FakeChildSubagents>,
+ script: FakeSupervisorScript,
) {
+ let FakeSupervisorScript {
+ kill: kill_behavior,
+ child,
+ child_subagents,
+ peers,
+ } = script;
let kill_behavior = std::sync::Arc::new(kill_behavior);
// Per-fake child session file: a fixed path would let a leftover file
// from another test (or run) carry the prompt text, flip the
@@ -83,6 +96,7 @@ async fn spawn_fake_supervisor(
let state_reads = Arc::clone(&state_reads);
let child_session_file = std::sync::Arc::clone(&child_session_file);
let child_subagents = Arc::clone(&child_subagents);
+ let peers = Arc::clone(&peers);
tokio::spawn(async move {
let (reader, mut writer) = stream.split();
let mut reader = BufReader::new(reader);
@@ -167,12 +181,32 @@ async fn spawn_fake_supervisor(
"get_state" => response_success(
Some(&id),
command_type,
- Some(json!({
- "isStreaming": false,
- "hasRunningSubagents": child_subagents.running.load(Ordering::SeqCst),
- "sessionActions": { "queuedCount": 0 },
+ Some(child_subagents.live_state.lock().unwrap().clone().unwrap_or_else(|| {
+ json!({
+ "isStreaming": false,
+ "hasRunningSubagents": child_subagents.running.load(Ordering::SeqCst),
+ "sessionActions": { "queuedCount": 0 },
+ "progressNote": "halfway through the task",
+ "toolUseCount": 3,
+ })
})),
),
+ "list_agent_peers" => {
+ let snapshot = peers.lock().unwrap().clone();
+ if let Some(gate) = child_subagents
+ .peer_gate
+ .as_ref()
+ .filter(|gate| gate.armed.swap(false, Ordering::SeqCst))
+ {
+ gate.copied.notify_one();
+ gate.release.notified().await;
+ }
+ response_success(
+ Some(&id),
+ command_type,
+ Some(json!({ "peers": snapshot })),
+ )
+ }
"get_last_assistant_text" => {
// The settle capture: with the knob set, the
// worker leaves right after its final answer.
@@ -261,6 +295,15 @@ struct FakeChildSubagents {
running: AtomicBool,
quiescent_waits: std::sync::atomic::AtomicUsize,
answer_reads: AtomicU32,
+ live_state: std::sync::Mutex<Option<Value>>,
+ peer_gate: Option<Arc<FakePeerGate>>,
+}
+
+#[derive(Default)]
+struct FakePeerGate {
+ armed: AtomicBool,
+ copied: tokio::sync::Notify,
+ release: tokio::sync::Notify,
}
/// [`sessions_with_fake_supervisor`] whose child reports its own running
@@ -282,9 +325,12 @@ async fn sessions_with_fake_child_subagents(
follow_up_tx,
idle_delay_ms,
kill_tx,
- kill_behavior,
- child,
- child_subagents,
+ FakeSupervisorScript {
+ kill: kill_behavior,
+ child,
+ child_subagents,
+ peers: Arc::new(std::sync::Mutex::new(Vec::new())),
+ },
)
.await;
let link = Arc::new(crate::supervisor_link::SupervisorLink::new(socket));
@@ -296,6 +342,7 @@ async fn sessions_with_fake_child_subagents(
std::env::temp_dir(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
// A live parent carries its resolved model on the identity; the
// spawn path resolves the child's model from it.
@@ -320,6 +367,50 @@ async fn spawn_child(sessions: &SupervisorChildSessions) -> RlmSpawnHandle {
.expect("spawn must succeed against the fake supervisor")
}
+/// [`sessions_with_fake_supervisor`] whose fake answers `list_agent_peers`
+/// from `peers`: the supervisor's pushed worker roster that the live roster
+/// read joins each child row onto.
+async fn sessions_with_roster_peers(
+ peers: Arc<std::sync::Mutex<Vec<Value>>>,
+ idle_delay_ms: u64,
+) -> (SupervisorChildSessions, mpsc::UnboundedReceiver<Value>) {
+ let socket = std::env::temp_dir().join(format!(
+ "pa-rlm-peers-{}.sock",
+ uuid::Uuid::new_v4().simple()
+ ));
+ let (kill_tx, kill_rx) = mpsc::unbounded_channel();
+ spawn_fake_supervisor(
+ socket.clone(),
+ mpsc::unbounded_channel().0,
+ idle_delay_ms,
+ kill_tx,
+ FakeSupervisorScript {
+ kill: FakeKill::Success,
+ child: FakeChild::Healthy,
+ child_subagents: Arc::new(FakeChildSubagents::default()),
+ peers,
+ },
+ )
+ .await;
+ let link = Arc::new(crate::supervisor_link::SupervisorLink::new(socket));
+ let sessions = SupervisorChildSessions::new(
+ link,
+ std::env::temp_dir(),
+ "parent-live".to_string(),
+ std::sync::Arc::new(crate::model_allowlist::ModelRefusalTelemetry::new(
+ std::env::temp_dir(),
+ /*telemetry_disabled*/ true,
+ )),
+ String::new(),
+ );
+ sessions.set_identity(ParentIdentity {
+ model: Some("mock/mock-1".to_string()),
+ cwd: Some(std::env::temp_dir().to_string_lossy().to_string()),
+ ..ParentIdentity::with_default_depth()
+ });
+ (sessions, kill_rx)
+}
+
#[tokio::test]
async fn roster_snapshot_does_not_wait_for_a_slow_child_worker() {
let (follow_up_tx, _follow_up_rx) = mpsc::unbounded_channel();
@@ -334,14 +425,277 @@ async fn roster_snapshot_does_not_wait_for_a_slow_child_worker() {
session_name: "slow-child".to_string(),
})
.await;
- let roster = tokio::time::timeout(Duration::from_millis(10), sessions.list_subagents())
+ let roster = tokio::time::timeout(Duration::from_millis(250), sessions.list_subagents())
.await
- .expect("roster must not make a supervisor round trip")
+ .expect("the roster read never waits on the slow child worker")
.expect("roster snapshot");
assert_eq!(roster.len(), 1);
assert_eq!(roster[0].status, "running");
}
+/// #4 A1/A2: a running child's row carries its latest accepted note and its
+/// tool-call count within one roster read — the supervisor's pushed worker
+/// roster joined onto the registry row (the watcher's 60s slice is too
+/// coarse to be the source; TS bumps the child's counter per
+/// `tool_execution_start` and omits a zero count).
+#[tokio::test]
+async fn a_running_childs_roster_row_carries_its_live_note_and_tool_count() {
+ let peers = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let (sessions, _kill_rx) = sessions_with_roster_peers(peers.clone(), 5_000).await;
+ let handle = spawn_child(&sessions).await;
+ *peers.lock().unwrap() = vec![json!({
+ "activeSessionId": "child-live",
+ "rlmChildId": handle.rlm_child_id.clone(),
+ "progressNote": "halfway through the task",
+ "toolUseCount": 3,
+ })];
+ let roster = sessions.list_subagents().await.expect("child roster");
+ assert_eq!(roster[0].status, "running");
+ assert_eq!(
+ roster[0].progress_note.as_deref(),
+ Some("halfway through the task"),
+ "the row joins the pushed roster's live note: {roster:?}"
+ );
+ assert_eq!(
+ roster[0].tool_use_count,
+ Some(3),
+ "the row joins the pushed roster's live count: {roster:?}"
+ );
+}
+
+/// #4: `collect` rows carry the same count: the refresh's `get_state`
+/// round trip (already in flight for the busy verdict) observes the child's
+/// live summary onto the record.
+#[tokio::test]
+async fn a_collect_row_counts_the_childs_tool_calls() {
+ let peers = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let (sessions, _kill_rx) = sessions_with_roster_peers(peers, 5_000).await;
+ sessions
+ .push_test_child(RlmChildIdentity {
+ rlm_child_id: "sub-collect".to_string(),
+ active_session_id: "child-live".to_string(),
+ session_id: Some("child-file".to_string()),
+ session_name: "counted-child".to_string(),
+ })
+ .await;
+ let results = sessions.collect(Vec::new(), 0).await.expect("collect");
+ assert_eq!(results[0].status, "done");
+ assert_eq!(
+ results[0].tool_use_count,
+ Some(3),
+ "the collect row reads the observed count: {results:?}"
+ );
+}
+
+/// An old list reply must not undo a newer direct child observation, even
+/// when that direct read settled the child before the list reply arrived.
+#[tokio::test]
+async fn a_delayed_roster_reply_keeps_the_newer_settled_observation() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let socket = dir.path().join("sup.sock");
+ let gate = Arc::new(FakePeerGate::default());
+ gate.armed.store(true, Ordering::SeqCst);
+ let state = Arc::new(FakeChildSubagents {
+ peer_gate: Some(Arc::clone(&gate)),
+ ..FakeChildSubagents::default()
+ });
+ let peers = Arc::new(std::sync::Mutex::new(vec![json!({
+ "activeSessionId": "child-live",
+ "workerInstanceId": "instance-1",
+ "rosterDeltaSequence": 3,
+ "progressNote": "older note",
+ "toolUseCount": 3,
+ })]));
+ *state.live_state.lock().unwrap() = Some(json!({
+ "workerInstanceId": "instance-1",
+ "rosterDeltaSequence": 4,
+ "isStreaming": false,
+ "progressNote": "newer note",
+ "toolUseCount": 4,
+ }));
+ spawn_fake_supervisor(
+ socket.clone(),
+ mpsc::unbounded_channel().0,
+ 0,
+ mpsc::unbounded_channel().0,
+ FakeSupervisorScript {
+ kill: FakeKill::Success,
+ child: FakeChild::Healthy,
+ child_subagents: state,
+ peers: Arc::clone(&peers),
+ },
+ )
+ .await;
+ let sessions = SupervisorChildSessions::new(
+ Arc::new(crate::supervisor_link::SupervisorLink::new(socket)),
+ dir.path().to_path_buf(),
+ "parent-live".to_string(),
+ Arc::new(crate::model_allowlist::ModelRefusalTelemetry::new(
+ dir.path().to_path_buf(),
+ /*telemetry_disabled*/ true,
+ )),
+ String::new(),
+ );
+ sessions
+ .push_test_child(RlmChildIdentity {
+ rlm_child_id: "child-id".to_string(),
+ active_session_id: "child-live".to_string(),
+ session_id: Some("child-file".to_string()),
+ session_name: "worker".to_string(),
+ })
+ .await;
+ let listing = {
+ let sessions = sessions.clone();
+ tokio::spawn(async move { sessions.list_subagents().await.unwrap() })
+ };
+ gate.copied.notified().await;
+ let collected = sessions.collect(Vec::new(), 0).await.unwrap();
+ assert_eq!(collected[0].tool_use_count, Some(4));
+ gate.release.notify_one();
+ let roster = listing.await.unwrap();
+ assert_eq!(
+ (roster[0].tool_use_count, roster[0].progress_note.as_deref()),
+ (Some(4), Some("newer note")),
+ );
+ // Completed rows do not read peers again: the accepted observation
+ // must survive even when no further direct refresh is requested.
+ let roster = sessions.list_subagents().await.unwrap();
+ assert_eq!(roster[0].tool_use_count, Some(4));
+}
+
+/// A later roster request may still read older pushed state. Sequence
+/// wins over request order; a replacement worker may legitimately reset.
+#[tokio::test]
+async fn child_observations_order_worker_sequences_and_allow_recovery_resets() {
+ let peers = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let (sessions, _kill_rx) = sessions_with_roster_peers(peers, 0).await;
+ sessions
+ .push_test_child(RlmChildIdentity {
+ rlm_child_id: "child-id".to_string(),
+ active_session_id: "child-live".to_string(),
+ session_id: Some("child-file".to_string()),
+ session_name: "worker".to_string(),
+ })
+ .await;
+ let record = sessions.inner.children.lock().await[0].clone();
+ let direct_observation = Arc::clone(&record.lock().await.direct_observation);
+ let direct = direct_observation.lock().await;
+ sessions
+ .inner
+ .observe_live_state(
+ &record,
+ &json!({
+ "workerInstanceId": "initial-roster",
+ "rosterDeltaSequence": 99,
+ "toolUseCount": 99,
+ }),
+ 0,
+ ChildObservationSource::Roster,
+ )
+ .await;
+ assert!(record.lock().await.live_observation.is_none());
+ drop(direct);
+ for (request_order, instance, sequence, count, note, source, expected) in [
+ (
+ 1,
+ "i1",
+ 4,
+ 4,
+ "new",
+ ChildObservationSource::Direct,
+ (Some(4), Some("new")),
+ ),
+ (
+ 2,
+ "i1",
+ 3,
+ 3,
+ "old",
+ ChildObservationSource::Roster,
+ (Some(4), Some("new")),
+ ),
+ (
+ 3,
+ "i1",
+ 4,
+ 5,
+ "pushed",
+ ChildObservationSource::Roster,
+ (Some(4), Some("new")),
+ ),
+ (
+ 4,
+ "i1",
+ 4,
+ 4,
+ "equal",
+ ChildObservationSource::Direct,
+ (Some(4), Some("equal")),
+ ),
+ (
+ 5,
+ "i1",
+ 5,
+ 6,
+ "advanced",
+ ChildObservationSource::Roster,
+ (Some(6), Some("advanced")),
+ ),
+ (
+ 6,
+ "i2",
+ 0,
+ 1,
+ "recovered",
+ ChildObservationSource::Direct,
+ (Some(1), Some("recovered")),
+ ),
+ (
+ 8,
+ "i1",
+ 99,
+ 99,
+ "retired",
+ ChildObservationSource::Roster,
+ (Some(1), Some("recovered")),
+ ),
+ ] {
+ sessions
+ .inner
+ .observe_live_state(
+ &record,
+ &json!({
+ "workerInstanceId": instance,
+ "rosterDeltaSequence": sequence,
+ "toolUseCount": count,
+ "progressNote": note,
+ }),
+ request_order,
+ source,
+ )
+ .await;
+ let record = record.lock().await;
+ assert_eq!(
+ (record.tool_use_count, record.progress_note.as_deref()),
+ expected,
+ );
+ }
+ sessions
+ .inner
+ .observe_live_state(
+ &record,
+ &json!({ "workerInstanceId": "i3", "rosterDeltaSequence": 0 }),
+ 7,
+ ChildObservationSource::Direct,
+ )
+ .await;
+ let record = record.lock().await;
+ assert_eq!(
+ (record.tool_use_count, &record.progress_note),
+ (None, &None)
+ );
+}
+
#[tokio::test]
async fn a_settled_child_without_a_reply_delivers_the_terminal_notice() {
let (follow_up_tx, mut follow_up_rx) = mpsc::unbounded_channel();
@@ -1252,6 +1606,10 @@ fn an_already_settled_child_never_re_scores_as_an_unreachable_error() {
answer_text: None,
answer_captured: false,
replied_since_task: false,
+ progress_note: None,
+ tool_use_count: None,
+ live_observation: None,
+ direct_observation: Arc::new(Mutex::new(())),
notice_delivered: false,
prompt_admitted: true,
error: None,
@@ -1320,6 +1678,10 @@ async fn the_unreachable_give_up_skips_the_exit_capture_when_a_capture_stands()
answer_text: Some("the captured say".to_string()),
answer_captured: true,
replied_since_task: false,
+ progress_note: None,
+ tool_use_count: None,
+ live_observation: None,
+ direct_observation: Arc::new(Mutex::new(())),
notice_delivered: false,
prompt_admitted: true,
error: None,
diff --git a/crates/pa-daemon/src/saved_session_commands.rs b/crates/pa-daemon/src/saved_session_commands.rs
index 83e2c549cc..eee1ad4495 100644
--- a/crates/pa-daemon/src/saved_session_commands.rs
+++ b/crates/pa-daemon/src/saved_session_commands.rs
@@ -729,9 +729,12 @@ impl Supervisor {
{
continue;
}
- let root_active_session_id = {
+ let (root_active_session_id, worker_instance_id) = {
let descriptor = resident.descriptor.lock().await;
- descriptor.root_active_session_id.clone()
+ (
+ descriptor.root_active_session_id.clone(),
+ descriptor.worker_instance_id.clone(),
+ )
};
if root_active_session_id.is_empty() {
continue;
@@ -746,6 +749,15 @@ impl Supervisor {
.map(|entry| entry.summary.clone())
};
if let Some(summary) = summary {
+ // A replacement may not have pushed yet. Never serve the old
+ // process's snapshot as the new resident's live state.
+ if summary
+ .get("workerInstanceId")
+ .and_then(Value::as_str)
+ .is_some_and(|instance| Some(instance) != worker_instance_id.as_deref())
+ {
+ continue;
+ }
peers.push(agent_peer_summary(&summary));
}
}
@@ -793,6 +805,12 @@ fn agent_peer_summary(summary: &Value) -> Value {
"parentActiveSessionId",
"parentSessionId",
"parentSessionPath",
+ // The child's live note and tool count ride the peer rows: the
+ // parent registry's roster read joins them onto its subagent rows.
+ "progressNote",
+ "toolUseCount",
+ "workerInstanceId",
+ "rosterDeltaSequence",
] {
if let Some(value) = summary.get(key).filter(|value| !value.is_null()) {
peer[key] = value.clone();
diff --git a/crates/pa-daemon/src/session_stats.rs b/crates/pa-daemon/src/session_stats.rs
index eede40589c..0b0f2254ce 100644
--- a/crates/pa-daemon/src/session_stats.rs
+++ b/crates/pa-daemon/src/session_stats.rs
@@ -158,7 +158,7 @@ pub(crate) fn store_context_usage(
}
/// `toolCall` content blocks on one assistant message.
-fn tool_call_count(message: &Value) -> u64 {
+pub(crate) fn tool_call_count(message: &Value) -> u64 {
message
.get("content")
.and_then(Value::as_array)
diff --git a/crates/pa-daemon/src/session_store/view.rs b/crates/pa-daemon/src/session_store/view.rs
index 2fcb7f33a9..9b22105bca 100644
--- a/crates/pa-daemon/src/session_store/view.rs
+++ b/crates/pa-daemon/src/session_store/view.rs
@@ -494,6 +494,28 @@ impl SessionFile {
}
}
+ /// The session's persisted tool calls on the ACTIVE BRANCH (gap-bridged,
+ /// the same chain the usage accounting walks): `toolCall` blocks on
+ /// assistant messages, the window's folded prefix included (the
+ /// summary's `toolUseCount` seed; TS counts a child's assistant tool
+ /// calls over the active chain).
+ #[must_use]
+ pub fn tool_call_count(&self) -> u64 {
+ let older = self
+ .window
+ .as_ref()
+ .map_or(0, |window| window.older_path_stats.tool_calls);
+ older
+ + self
+ .branch_bridged()
+ .iter()
+ .filter(|entry| entry.type_ == "message")
+ .filter_map(|entry| entry.fields.get("message"))
+ .filter(|message| message_role(message) == Some("assistant"))
+ .map(crate::session_stats::tool_call_count)
+ .sum::<u64>()
+ }
+
pub fn first_message(&self) -> Option<String> {
if let Some(window) = &self.window {
return window.first_message.clone();
diff --git a/crates/pa-daemon/src/session_store_window_tests.rs b/crates/pa-daemon/src/session_store_window_tests.rs
index 8e09a98a8c..c20dca44a8 100644
--- a/crates/pa-daemon/src/session_store_window_tests.rs
+++ b/crates/pa-daemon/src/session_store_window_tests.rs
@@ -279,6 +279,61 @@ fn usage_of(input: u64, output: u64, cache_read: u64, total: f64) -> Value {
})
}
+/// The tool-call seed walk counts on both sides of the window cut: the
+/// folded prefix rides `older_path_stats`, the retained rows the store
+/// entries, and a windowed open seeds the same count a full open does.
+#[test]
+fn windowed_tool_call_count_matches_the_full_open_across_the_cut() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("tools.jsonl");
+ let mut full = SessionFile::create("/tmp", None, 0);
+ full.set_path(path.clone());
+ let old = full.append_message(&json!({
+ "role":"assistant", "provider":"p", "model":"m",
+ "content":[{"type":"text","text":"old"},
+ {"type":"toolCall","id":"call-1","name":"bash","arguments":{}}],
+ "stopReason":"toolUse", "timestamp":0
+ }));
+ let mut boundary = String::new();
+ for i in 1..220 {
+ let id = full.append_message(&json!({
+ "role":"user", "content": format!("message {i}"), "timestamp": i,
+ }));
+ if i == 210 {
+ boundary = id;
+ }
+ }
+ // The compaction boundary is what folds the windowed open's prefix.
+ full.append_entry(
+ "compaction",
+ json!({"summary":"summary","firstKeptEntryId":boundary,"tokensBefore":10000}),
+ );
+ let kept = full.append_message(&json!({
+ "role":"assistant", "provider":"p", "model":"m",
+ "content":[{"type":"toolCall","id":"call-2","name":"edit","arguments":{}},
+ {"type":"toolCall","id":"call-3","name":"edit","arguments":{}}],
+ "stopReason":"toolUse", "timestamp":221
+ }));
+ full.rewrite().unwrap();
+
+ let windowed = SessionFile::open_windowed(&path).unwrap();
+ assert!(
+ windowed.window.is_some(),
+ "the fixture must serve a windowed open"
+ );
+ // The fixture really spans the cut: the pre-cut row folded away, the
+ // kept row retained.
+ assert!(windowed.entry(&old).is_none());
+ assert!(windowed.entry(&kept).is_some());
+ let full = SessionFile::open(&path).unwrap();
+ assert_eq!(full.tool_call_count(), 3);
+ assert_eq!(
+ windowed.tool_call_count(),
+ full.tool_call_count(),
+ "the windowed open seeds the same count as the full open"
+ );
+}
+
/// One shared walk backs both the materialized fold and the scalar scan:
/// across every window shape the scan must reproduce exactly the scalars the
/// old full-clone fold computed.
diff --git a/crates/pa-daemon/src/supervisor/sessions.rs b/crates/pa-daemon/src/supervisor/sessions.rs
index 5f6ff00dc7..bf9512d390 100644
--- a/crates/pa-daemon/src/supervisor/sessions.rs
+++ b/crates/pa-daemon/src/supervisor/sessions.rs
@@ -547,12 +547,42 @@ impl Supervisor {
RouteAdmission::SupervisorInternal,
)
.await;
- match response {
- Ok(response) if response.success => response
- .data
- .unwrap_or_else(|| offline_summary(&resident.worker_id)),
- _ => offline_summary(&resident.worker_id),
+ if let Some(summary) = response
+ .ok()
+ .filter(|response| response.success)
+ .and_then(|response| response.data)
+ {
+ return summary;
+ }
+ let root_active_session_id = resident
+ .descriptor
+ .lock()
+ .await
+ .root_active_session_id
+ .clone();
+ let roster = self
+ .roster
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let mut summary = offline_summary(&resident.worker_id);
+ // A failed live pull loses activity, not the supervisor's trusted family
+ // binding. Never borrow identity from a row now owned by another worker.
+ if let Some(entry) = roster
+ .by_active_session_id(&root_active_session_id)
+ .filter(|entry| entry.worker_id.as_deref() == Some(resident.worker_id.as_str()))
+ {
+ for key in [
+ "parentActiveSessionId",
+ "parentSessionId",
+ "parentSessionPath",
+ "sessionName",
+ ] {
+ if let Some(value) = entry.summary.get(key) {
+ summary[key] = value.clone();
+ }
+ }
}
+ summary
}
async fn worker_summaries(self: &Arc<Self>, residents: &[Arc<ResidentWorker>]) -> Vec<Value> {
@@ -967,6 +997,42 @@ mod tests {
);
}
+ #[tokio::test(start_paused = true)]
+ async fn a_degraded_summary_keeps_only_its_own_workers_family_binding() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let supervisor = Arc::new(supervisor(dir.path()));
+ let resident = resident("sibling", None);
+ resident.descriptor.lock().await.root_active_session_id = "sibling".to_string();
+ let _requests = wedged_worker(&resident).await;
+ let binding = json!({
+ "activeSessionId": "sibling", "sessionId": "session-sibling",
+ "sessionName": "sibling-name", "parentActiveSessionId": "parent",
+ "parentSessionId": "session-parent", "parentSessionPath": "/parent.jsonl",
+ });
+ supervisor
+ .roster
+ .lock()
+ .unwrap()
+ .write_summary(binding.clone(), Some("sibling"), None);
+ let summary = supervisor.worker_summary(&resident).await;
+ let mut expected = offline_summary("sibling");
+ expected["sessionName"] = binding["sessionName"].clone();
+ expected["parentActiveSessionId"] = binding["parentActiveSessionId"].clone();
+ expected["parentSessionId"] = binding["parentSessionId"].clone();
+ expected["parentSessionPath"] = binding["parentSessionPath"].clone();
+ assert_eq!(summary, expected);
+
+ supervisor
+ .roster
+ .lock()
+ .unwrap()
+ .write_summary(binding, Some("replacement"), None);
+ assert_eq!(
+ supervisor.worker_summary(&resident).await,
+ offline_summary("sibling")
+ );
+ }
+
#[tokio::test(start_paused = true)]
async fn a_named_create_name_check_does_not_wait_out_the_client_deadline_behind_a_wedged_resident(
) {
diff --git a/crates/pa-daemon/src/types.rs b/crates/pa-daemon/src/types.rs
index 88108d600c..e5a0a64cf6 100644
--- a/crates/pa-daemon/src/types.rs
+++ b/crates/pa-daemon/src/types.rs
@@ -100,6 +100,11 @@ pub struct SessionSummary {
/// boundaries so an idle row never carries one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub progress_note: Option<String>,
+ /// The session's tool calls so far (TS `toolUseCount`, omitted when
+ /// zero): bumped per `tool_execution_start`, re-seeded from the session
+ /// file when a worker opens it so a revived child never resets it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tool_use_count: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent_session_path: Option<String>,
/// The parent's live active-session id (subagent summaries).
diff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rs
index b2410db25b..0254de2181 100644
--- a/crates/pa-daemon/src/worker.rs
+++ b/crates/pa-daemon/src/worker.rs
@@ -321,6 +321,7 @@ impl Worker {
active_action: None,
running_tool_calls: std::collections::HashSet::new(),
running_admission_ids: std::collections::HashSet::new(),
+ tool_use_count: 0,
};
let active_session_id = config.active_session_id.clone();
let script = config.script.clone();
diff --git a/crates/pa-daemon/src/worker/create.rs b/crates/pa-daemon/src/worker/create.rs
index 01e8616320..c232d6e830 100644
--- a/crates/pa-daemon/src/worker/create.rs
+++ b/crates/pa-daemon/src/worker/create.rs
@@ -519,6 +519,9 @@ impl Worker {
core.cwd = cwd;
core.steering = steering;
core.follow_up = follow_up;
+ // A resumed session's tool counter re-seeds from its file: a
+ // revived worker keeps the count its roster rows carried.
+ core.tool_use_count = store.tool_call_count();
core.store = Some(store);
if let Some(disclosure) = &interrupted_compaction {
if let Some(store) = core.store.as_mut() {
diff --git a/crates/pa-daemon/src/worker/session_core.rs b/crates/pa-daemon/src/worker/session_core.rs
index ae8e014344..2147bfae20 100644
--- a/crates/pa-daemon/src/worker/session_core.rs
+++ b/crates/pa-daemon/src/worker/session_core.rs
@@ -32,6 +32,11 @@ pub(crate) struct SessionCore {
/// The turn's tool calls in flight, keyed by tool-call id: the
/// roster summary derives `isRunningTools` from its size.
pub(crate) running_tool_calls: std::collections::HashSet<String>,
+ /// The session's tool executions so far (the summary's `toolUseCount`):
+ /// bumped per `tool_execution_start` under the same core lock the frames
+ /// sequence under, and seeded from the session file when a worker opens
+ /// it, so a revived session never resets the count.
+ pub(crate) tool_use_count: u64,
/// Admission ids belonging to the current in-flight turn. The queue
/// handoff and owned cancellation both inspect this under the core lock.
pub(crate) running_admission_ids: std::collections::HashSet<String>,
@@ -124,6 +129,7 @@ impl SessionCore {
compacting: false,
running_tool_calls: std::collections::HashSet::new(),
running_admission_ids: std::collections::HashSet::new(),
+ tool_use_count: 0,
auto_compaction_enabled: true,
last_action_snapshot: Some(SessionActionSnapshot::default()),
rlm_depth: 0,
diff --git a/crates/pa-daemon/src/worker/summary.rs b/crates/pa-daemon/src/worker/summary.rs
index d690f22df6..54a0a4ed44 100644
--- a/crates/pa-daemon/src/worker/summary.rs
+++ b/crates/pa-daemon/src/worker/summary.rs
@@ -341,6 +341,7 @@ pub(crate) async fn push_roster_delta(context: &RosterPushContext) {
.roster_delta_sequence
.load(std::sync::atomic::Ordering::SeqCst),
);
+ summary.worker_instance_id = Some(context.worker_instance_id.clone());
let summary = serde_json::to_value(&summary).unwrap_or(serde_json::Value::Null);
let sequence_value = context
.roster_delta_sequence
@@ -580,6 +581,7 @@ pub(crate) fn session_summary(core: &SessionCore, inputs: SummaryInputs) -> Sess
modified,
first_message: store.and_then(crate::session_store::SessionFile::first_message),
progress_note: inputs.progress_note,
+ tool_use_count: (core.tool_use_count > 0).then_some(core.tool_use_count),
parent_session_path: store.and_then(|store| store.header.parent_session.clone()),
parent_active_session_id: core.parent_active_session_id.clone(),
parent_session_id: core.parent_session_id.clone(),
diff --git a/crates/pa-daemon/src/worker/tests/summary_tests.rs b/crates/pa-daemon/src/worker/tests/summary_tests.rs
index ace3ae1bf6..687172c00e 100644
--- a/crates/pa-daemon/src/worker/tests/summary_tests.rs
+++ b/crates/pa-daemon/src/worker/tests/summary_tests.rs
@@ -258,6 +258,69 @@ fn pathless_summary_usage_folds_the_in_memory_entries() {
);
}
+/// #4: a resumed session's summary counts the tool calls its file already
+/// holds, so a revived child's `toolUseCount` never resets (TS counts a
+/// run-less child's assistant tool calls).
+#[tokio::test]
+async fn a_resumed_sessions_summary_counts_its_persisted_tool_calls() {
+ let dir = std::env::temp_dir().join(format!("pa-worker-tools-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("tool-count.jsonl");
+ let header = json!({
+ "type": "session", "version": 3, "id": "tool-count",
+ "timestamp": "2026-01-01T00:00:00.000Z", "cwd": "/tmp",
+ });
+ let user = json!({
+ "type": "message", "id": "u1", "parentId": null,
+ "timestamp": "2026-01-01T00:00:00.000Z",
+ "message": { "role": "user", "content": "run it" },
+ });
+ let tools = json!({
+ "type": "message", "id": "a1", "parentId": "u1",
+ "timestamp": "2026-01-01T00:00:01.000Z",
+ "message": {
+ "role": "assistant",
+ "content": [
+ { "type": "toolCall", "toolCallId": "t1", "name": "bash", "arguments": {} },
+ { "type": "toolCall", "toolCallId": "t2", "name": "edit", "arguments": {} },
+ ],
+ "provider": "p", "model": "m", "stopReason": "toolUse",
+ },
+ });
+ std::fs::write(&path, format!("{header}\n{user}\n{tools}\n")).unwrap();
+ let config = WorkerConfig {
+ socket_path: dir.join("worker.sock"),
+ supervisor_socket_path: std::path::PathBuf::new(),
+ token: "token".to_string(),
+ worker_instance_id: String::new(),
+ active_session_id: "tool-count".to_string(),
+ agent_dir: dir.join("agent"),
+ recovery_journal_path: dir.join("recovery.jsonl"),
+ telemetry_disabled: None,
+ script: Some(json!({ "responses": [] })),
+ };
+ let worker = Worker::new(config, None);
+ let resumed = worker
+ .dispatch(
+ "create",
+ &json!({
+ "cwd": "/tmp",
+ "sessionPath": path,
+ "name": "resumed",
+ }),
+ )
+ .await;
+ assert!(resumed.success, "resume failed: {resumed:?}");
+ let state = worker.dispatch("get_state", &json!({})).await;
+ assert!(state.success, "get_state failed: {state:?}");
+ assert_eq!(
+ state.data.unwrap_or(Value::Null)["toolUseCount"],
+ json!(2),
+ "the resumed summary counts the persisted tool calls"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
#[test]
fn display_ids_are_twelve_hex() {
let id = crate::util::new_display_id();
diff --git a/crates/pa-daemon/src/worker/turn.rs b/crates/pa-daemon/src/worker/turn.rs
index 7bd64c5621..2abb59bfd3 100644
--- a/crates/pa-daemon/src/worker/turn.rs
+++ b/crates/pa-daemon/src/worker/turn.rs
@@ -604,9 +604,12 @@ impl TurnRunner {
}
// The in-flight tool-call set, updated under the same core lock
// the frames sequence under: the roster feed never reads a
- // half-applied transition.
+ // half-applied transition. The session's tool counter bumps
+ // with the same set, so the summary a roster push composes
+ // from this event already carries it.
EngineEvent::ToolExecutionStart { tool_call_id, .. } => {
core.running_tool_calls.insert(tool_call_id.clone());
+ core.tool_use_count += 1;
}
EngineEvent::ToolExecutionEnd { tool_call_id, .. } => {
core.running_tool_calls.remove(tool_call_id);
diff --git a/crates/pa-daemon/src/worker/turn_stream_tests.rs b/crates/pa-daemon/src/worker/turn_stream_tests.rs
index 7226baac79..572fca1dd8 100644
--- a/crates/pa-daemon/src/worker/turn_stream_tests.rs
+++ b/crates/pa-daemon/src/worker/turn_stream_tests.rs
@@ -53,6 +53,7 @@ fn burst_runner(engine: Arc<dyn SessionEngine>) -> TurnRunner {
active_action: None,
running_tool_calls: std::collections::HashSet::new(),
running_admission_ids: std::collections::HashSet::new(),
+ tool_use_count: 0,
}));
TurnRunner {
core,
@@ -122,6 +123,7 @@ fn positions_of(events: &[Value], frame_type: &str) -> Vec<usize> {
// The abort gate's arm semantics, pinned on the wire: `run_turn` driven
// directly (the pickup's delivery-scoped clear never ran), so the final-emit
// race is deterministic.
+#[derive(Default)]
struct GateProbeEngine {
frames: Vec<EngineEvent>,
boundaries: Mutex<Vec<Option<String>>>,
@@ -265,6 +267,75 @@ async fn done_aborted_arms_the_fallback_silence() {
);
}
+/// #4: the turn's tool executions count onto the session's `toolUseCount`
+/// (TS bumps the child's counter per `tool_execution_start`), the value the
+/// worker's roster deltas carry.
+#[tokio::test]
+async fn a_turns_tool_executions_count_onto_the_summary() {
+ let engine: Arc<dyn SessionEngine> = Arc::new(GateProbeEngine {
+ frames: vec![
+ EngineEvent::ToolExecutionStart {
+ tool_call_id: "t1".to_string(),
+ tool_name: "bash".to_string(),
+ args: Value::Null,
+ },
+ EngineEvent::ToolExecutionEnd {
+ tool_call_id: "t1".to_string(),
+ result: Value::Null,
+ is_error: false,
+ },
+ EngineEvent::ToolExecutionStart {
+ tool_call_id: "t2".to_string(),
+ tool_name: "edit".to_string(),
+ args: Value::Null,
+ },
+ EngineEvent::Done(Ok(())),
+ ],
+ ..GateProbeEngine::default()
+ });
+ let runner = burst_runner(Arc::clone(&engine));
+ runner
+ .run_turn(
+ engine,
+ vec![QueuedItem {
+ priority: QueuePriority::Human,
+ preview: None,
+ message: "tools".to_string(),
+ custom_message: None,
+ agent_message: None,
+ queue_key: None,
+ admission_id: None,
+ images: Vec::new(),
+ done: None,
+ queue_visible: true,
+ policy: TurnPolicy::Queued,
+ forced_batch: false,
+ }],
+ )
+ .await;
+ let summary = {
+ let core = runner.core.lock().unwrap();
+ session_summary(
+ &core,
+ SummaryInputs {
+ thinking_level: "default".to_string(),
+ model: None,
+ model_fallback_message: None,
+ bash_running: false,
+ quota_parked: false,
+ subagents_running: false,
+ progress_note: None,
+ },
+ )
+ };
+ let summary = serde_json::to_value(&summary).unwrap();
+ assert_eq!(
+ summary["toolUseCount"],
+ json!(2),
+ "the summary: {summary:?}"
+ );
+}
+
/// A settle frame that would forward on a plain flag sighting drops when
/// `suppress_aborted_row` is set.
#[tokio::test]
diff --git a/crates/pa-daemon/tests/agent_family_e2e.rs b/crates/pa-daemon/tests/agent_family_e2e.rs
index d562c9941b..1e88ffc25c 100644
--- a/crates/pa-daemon/tests/agent_family_e2e.rs
+++ b/crates/pa-daemon/tests/agent_family_e2e.rs
@@ -404,6 +404,7 @@ async fn parent_child_agent_message_round_trip_end_to_end() {
agent_dir.clone(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
children.set_identity(ParentIdentity {
rlm_depth: 0,
@@ -732,6 +733,7 @@ async fn family_edges_never_cross_families_end_to_end() {
agent_dir.clone(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
children.set_identity(ParentIdentity {
rlm_depth: 0,
@@ -871,6 +873,7 @@ async fn family_edges_never_cross_families_end_to_end() {
agent_dir.clone(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
kid_children.set_identity(ParentIdentity {
rlm_depth: 1,
@@ -972,22 +975,28 @@ async fn family_edges_never_cross_families_end_to_end() {
if let Ok(error) = std::fs::read_to_string(receipts_dir.join("kid-observe.error")) {
panic!("kid kernel cell failed: {error}");
}
- let kid_roster = read_recorded(&receipts_dir, "kid-observe.json");
- let kid_roster = kid_roster
+ let kid_payload = read_recorded(&receipts_dir, "kid-observe.json");
+ let kid_current = kid_payload
+ .get("current")
+ .expect("kid-a's own row rides current");
+ assert_eq!(kid_current["activeSessionId"], kid_a_active.as_str());
+ assert!(kid_current["isCurrent"] == true, "{kid_current:?}");
+ assert_eq!(kid_current["relationship"], Value::Null, "{kid_current:?}");
+ let kid_roster = kid_payload
.get("agents")
.and_then(Value::as_array)
.expect("the observe roster is a list of summaries");
assert_eq!(
kid_roster.len(),
- 3,
- "kid-a's observe roster is its nuclear family: {kid_roster:?}"
+ 2,
+ "kid-a's family roster excludes itself: {kid_roster:?}"
+ );
+ assert!(
+ !kid_roster
+ .iter()
+ .any(|summary| summary["activeSessionId"] == kid_a_active.as_str()),
+ "kid-a's own row never rides the family roster: {kid_roster:?}"
);
- let kid_self = kid_roster
- .iter()
- .find(|summary| summary["activeSessionId"] == kid_a_active.as_str())
- .expect("kid-a's own row");
- assert!(kid_self["isCurrent"] == true, "{kid_self:?}");
- assert_eq!(kid_self["relationship"], Value::Null, "{kid_self:?}");
let kid_parent_row = kid_roster
.iter()
.find(|summary| summary["sessionId"] == parent_a_session.as_str())
@@ -1016,14 +1025,20 @@ async fn family_edges_never_cross_families_end_to_end() {
panic!("parent kernel cell failed: {error}");
}
let roster = read_recorded(&receipts_dir, "parent-observe.json");
+ let current = roster
+ .get("current")
+ .expect("the parent's own row rides current");
+ assert_eq!(current["sessionId"], parent_a_session.as_str());
+ assert_eq!(current["isCurrent"], true, "{current:?}");
+ assert_eq!(current["relationship"], Value::Null, "{current:?}");
let roster = roster
.get("agents")
.and_then(Value::as_array)
.expect("the observe roster is a list of summaries");
assert_eq!(
roster.len(),
- 3,
- "the observe roster is the nuclear family: {roster:?}"
+ 2,
+ "the family roster excludes the caller: {roster:?}"
);
let by_id = |id: &str| {
roster
@@ -1035,9 +1050,6 @@ async fn family_edges_never_cross_families_end_to_end() {
.unwrap_or_else(|| panic!("row {id} missing: {roster:?}"))
.clone()
};
- let self_row = by_id(parent_a_session);
- assert_eq!(self_row["isCurrent"], true, "{self_row:?}");
- assert_eq!(self_row["relationship"], Value::Null, "{self_row:?}");
let sibling_row = by_id(sibling_root_active);
assert_eq!(sibling_row["relationship"], "sibling", "{sibling_row:?}");
let child_row = by_id(kid_a_active);
@@ -1179,6 +1191,7 @@ async fn parent_renames_a_child_end_to_end() {
agent_dir.clone(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
children.set_identity(ParentIdentity {
rlm_depth: 0,
diff --git a/crates/pa-daemon/tests/agents_view_roster_e2e.rs b/crates/pa-daemon/tests/agents_view_roster_e2e.rs
index ebaed340c7..db1feca132 100644
--- a/crates/pa-daemon/tests/agents_view_roster_e2e.rs
+++ b/crates/pa-daemon/tests/agents_view_roster_e2e.rs
@@ -405,6 +405,7 @@ async fn rlm_children_key_the_roster_by_parent_path_and_child_id() {
agent_dir.clone(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
children.set_identity(ParentIdentity {
rlm_depth: 0,
diff --git a/crates/pa-daemon/tests/idle_passivation_e2e.rs b/crates/pa-daemon/tests/idle_passivation_e2e.rs
index 50eb723fe1..b5f890afa3 100644
--- a/crates/pa-daemon/tests/idle_passivation_e2e.rs
+++ b/crates/pa-daemon/tests/idle_passivation_e2e.rs
@@ -276,6 +276,7 @@ async fn a_settled_child_passivates_stays_listable_and_revives_by_agent_message(
agent_dir.clone(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
children.set_identity(ParentIdentity {
rlm_depth: 0,
@@ -592,6 +593,7 @@ async fn a_parent_rename_after_a_revival_and_second_passivation_reaches_the_chil
agent_dir.clone(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
children.set_identity(ParentIdentity {
rlm_depth: 0,
diff --git a/crates/pa-daemon/tests/launch_env_e2e.rs b/crates/pa-daemon/tests/launch_env_e2e.rs
index d7535d223a..f1f0b13471 100644
--- a/crates/pa-daemon/tests/launch_env_e2e.rs
+++ b/crates/pa-daemon/tests/launch_env_e2e.rs
@@ -525,6 +525,9 @@ async fn an_rlm_spawn_child_inherits_the_parent_worker_env() {
agent_dir.clone(),
/*telemetry_disabled*/ true,
)),
+ // This process stands in for the parent and has no worker token;
+ // this fixture reads the child's env, not authenticated roster joins.
+ String::new(),
);
children.set_identity(ParentIdentity {
rlm_depth: 0,
diff --git a/crates/pa-daemon/tests/rlm_children_e2e.rs b/crates/pa-daemon/tests/rlm_children_e2e.rs
index 639263e20d..614f34b8b6 100644
--- a/crates/pa-daemon/tests/rlm_children_e2e.rs
+++ b/crates/pa-daemon/tests/rlm_children_e2e.rs
@@ -197,6 +197,7 @@ fn children(socket: &Path, agent_dir: &Path, script: &Path, depth: u32) -> Super
agent_dir.to_path_buf(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
sessions.set_identity(ParentIdentity {
rlm_depth: depth,
diff --git a/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs
index 4bf9869e80..0c5edfb00f 100644
--- a/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs
+++ b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs
@@ -340,6 +340,7 @@ async fn subscribe_after_spawn_then_shutdown_seeds_the_passive_child() {
agent_dir.clone(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
children.set_identity(ParentIdentity {
rlm_depth: 0,
diff --git a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs
index 8a7c95afb7..b51f200ce0 100644
--- a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs
+++ b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs
@@ -209,6 +209,7 @@ fn children(socket: &Path, agent_dir: &Path, script: &Path) -> SupervisorChildSe
agent_dir.to_path_buf(),
/*telemetry_disabled*/ true,
)),
+ String::new(),
);
sessions.set_identity(ParentIdentity {
rlm_depth: 0,
diff --git a/scripts/review_observe_selectors_parity.py b/scripts/review_observe_selectors_parity.py
new file mode 100644
index 0000000000..fd9b74e155
--- /dev/null
+++ b/scripts/review_observe_selectors_parity.py
@@ -0,0 +1,519 @@
+#!/usr/bin/env python3
+"""Actual resident agent_observe selector comparison, pinned TS vs Rust.
+
+Only identity/transcript selection, ambiguity and family rejection are compared.
+Full summary/preview objects and differing rejection messages remain in receipt;
+passive hydration, transient progress events and preview fidelity are excluded.
+"""
+import argparse
+import http.server
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+
+from review_agent_bounce_parity import Client
+from review_draft_disconnect_parity import digest, TS_ARCHIVE_SHA256
+from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish, verify_worker
+from review_restore_notice_parity import texts
+
+MARKER = 'OBSERVE_SELECTORS_PARITY='
+LIMIT = 35
+MAIN_CHILD_TASKS = {'observe-child-a': 'OBSERVE_TASK_A', 'observe-child-b': 'OBSERVE_TASK_B'}
+FOREIGN_CHILD_TASKS = {'observe-foreign-child': 'OBSERVE_TASK_FOREIGN'}
+ALL_TASKS = set(MAIN_CHILD_TASKS.values()) | set(FOREIGN_CHILD_TASKS.values())
+
+
+class ObserveClient(Client):
+ def call(self, kind, timeout_seconds=LIMIT, **payload):
+ self.counter += 1
+ ident = str(self.counter)
+ envelope = {'type': 'command', 'id': ident,
+ 'protocol': {'name': 'prime-agent.daemon', 'version': 7},
+ 'command': {'type': kind, **payload}}
+ self.sent.append(envelope)
+ deadline = time.monotonic() + timeout_seconds
+ previous_timeout = self.sock.gettimeout()
+ try:
+ self.sock.settimeout(timeout_seconds)
+ self.sock.sendall((json.dumps(envelope) + '\n').encode())
+ while time.monotonic() < deadline:
+ self.sock.settimeout(max(0.001, deadline - time.monotonic()))
+ line = self.reader.readline()
+ assert line, 'daemon closed connection'
+ response = json.loads(line)
+ self.wire.append(response)
+ if response.get('type') == 'response' and response.get('id') == ident:
+ assert response.get('success'), response
+ return response.get('data')
+ raise TimeoutError('command never answered: ' + kind)
+ finally:
+ self.sock.settimeout(previous_timeout)
+
+ def __init__(self, path, process):
+ super().__init__(path, process)
+ self.sent = []
+
+
+def cell(selectors):
+ return """import json, agent_observe
+selectors = """ + repr(selectors) + """
+result = {'roster': await agent_observe.list_agents(), 'selectors': {}}
+for label, target in selectors.items():
+ row = result['selectors'][label] = {}
+ for operation in ('get', 'recent'):
+ try:
+ value = (await agent_observe.get_agent(target) if operation == 'get'
+ else await agent_observe.recent_messages(target, limit=8, max_chars=800))
+ row[operation] = {'value': value}
+ except Exception as error:
+ row[operation] = {'error': str(error)}
+print('OBSERVE_SELECTORS_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, self.code = None, None
+ self.requests = {}
+ self.child_requests = {}
+ self.children_arrived = threading.Condition()
+ self.release_children = threading.Event()
+ self.child_reply_timeout = False
+
+
+def child_task(body):
+ users = [message for message in body.get('messages', []) if message.get('role') == 'user']
+ text = '\n'.join(texts(users[-1].get('content'))).strip() if users else ''
+ tasks = {f'[task from parent]\n\n{task}': task for task in ALL_TASKS}
+ return tasks.get(text)
+
+
+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'])))
+ task = child_task(body)
+ if task:
+ with self.server.children_arrived:
+ self.server.child_requests.setdefault(task, []).append(body)
+ self.server.children_arrived.notify_all()
+ # Keep the actual spawned child live; no settle/passive hydration is exercised.
+ if not self.server.release_children.wait(300):
+ self.server.child_reply_timeout = True
+ phase, requests = task, self.server.child_requests[task]
+ code = None
+ else:
+ phase = self.server.phase
+ requests = self.server.requests.setdefault(phase, [])
+ requests.append(body)
+ code = self.server.code
+ if code is not None and 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, 'no actual REPL tool offered')
+ return
+ delta = {'tool_calls': [{'index': 0, 'id': 'observe_' + phase, 'type': 'function',
+ 'function': {'name': name, 'arguments': json.dumps({'code': code})}}]}
+ reason = 'tool_calls'
+ else:
+ delta, reason = {'content': 'TRANSCRIPT_' + phase.upper()}, 'stop'
+ def chunk(delta, reason=None):
+ return {'id': 'observe-selectors', 'object': 'chat.completion.chunk', 'created': 1,
+ 'model': 'observe-fixture', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': reason}]}
+ wire = ''.join('data: ' + json.dumps(row) + '\n\n' for row in (
+ chunk({'role': 'assistant', **delta}), chunk({}, reason))) + '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()
+ try:
+ self.wfile.write(wire.encode())
+ except (BrokenPipeError, ConnectionResetError):
+ pass # Actual shutdown interrupts the held child's connection.
+
+
+def current_probe(requests, phase):
+ assert len(requests) == 2, 'unexpected actual provider sequence'
+ ident = 'observe_' + phase
+ calls = [call for message in requests[-1]['messages'] if message.get('role') == 'assistant'
+ for call in message.get('tool_calls', []) if call.get('id') == ident]
+ assert len(calls) == 1, 'missing/duplicate current observe tool call'
+ matches = [message for message in requests[-1]['messages'] if message.get('role') == 'tool'
+ and message.get('tool_call_id') == ident]
+ assert len(matches) == 1, 'missing/duplicate current observe 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 observe marker'
+ return probes[0]
+
+
+def suffix(identifier, all_ids):
+ normalize = lambda value: value.replace('-', '').lower()
+ identifier = normalize(identifier)
+ for size in range(8, len(identifier) + 1):
+ candidate = identifier[-size:]
+ if sum(value.endswith(candidate) for value in {normalize(value) for value in all_ids}) == 1:
+ # Exercise both case and hyphen normalization, not just a substring.
+ return candidate[:4].upper() + '-' + candidate[4:].upper()
+ raise AssertionError('fixture did not generate a unique ID suffix')
+
+
+READ_CHILDREN = """import json, dataclasses
+print('OBSERVE_SELECTORS_PARITY=' + json.dumps({'children': [dataclasses.asdict(row) for row in await rlm.list_subagents()]}, default=str))
+"""
+
+
+def ready_children(snapshot, expected_child_ids, expected_tasks=MAIN_CHILD_TASKS):
+ children = snapshot['children']
+ assert len(children) == len(expected_tasks), 'unexpected spawned-child roster size'
+ rows = {row['session_name']: row for row in children}
+ assert set(rows) == set(expected_tasks), 'unexpected/duplicate child names'
+ for name, task in expected_tasks.items():
+ row = rows[name]
+ assert row['rlm_child_id'] == expected_child_ids[name], 'spawned child identity changed'
+ assert row['status'] == 'running', 'spawned child settled before identity proof'
+ assert row.get('label') == task, 'spawned child task/name mismatch'
+ complete = True
+ for key in ('active_session_id', 'session_id'):
+ ids = [row[key] for row in children]
+ published = [value for value in ids if value is not None]
+ assert all(isinstance(value, str) and value for value in published), 'invalid published live child ID'
+ assert len(set(published)) == len(published), 'duplicate published live child IDs'
+ complete = complete and len(published) == len(expected_tasks)
+ # Only explicit None is a transient admission/publication state. Validate
+ # every present ID first, even if another field has not been published.
+ return rows if complete else None
+
+
+def await_child_identities(first, read_snapshot, observation, clock=time.monotonic, budget=LIMIT, expected_tasks=MAIN_CHILD_TASKS):
+ expected = {row['session_name']: row['rlm_child_id'] for row in first['children']}
+ assert all(isinstance(value, str) and value for value in expected.values()), 'invalid spawned child handles'
+ assert len(set(expected.values())) == len(expected_tasks), 'duplicate spawned child handles'
+ deadline = clock() + budget
+ observation['identity_polls'] = []
+ rows = ready_children(first, expected, expected_tasks)
+ while rows is None:
+ remaining = deadline - clock()
+ assert remaining > 0, 'spawned children did not publish live IDs before deadline'
+ # Each poll executes the actual RLM host read in another REPL tool call.
+ # The request itself yields to publication; no fixed sleep grants readiness.
+ snapshot = read_snapshot(len(observation['identity_polls']) + 1, remaining)
+ observation['identity_polls'].append(snapshot)
+ assert clock() < deadline, 'spawned child identity observation exceeded deadline'
+ rows = ready_children(snapshot, expected, expected_tasks)
+ return rows
+
+
+def validate_foreign_agent(agent, foreign, other_parent, parent):
+ assert other_parent['active'] != parent['active'] and other_parent['durable'] != parent['durable'], 'foreign parent aliases main parent'
+ assert agent['activeSessionId'] == foreign['active'] and agent['sessionId'] == foreign['durable'], agent
+ assert agent['runtimeKind'] == 'subagent', agent
+ assert agent['parentSessionId'] == other_parent['durable'], agent
+ assert agent['parentActiveSessionId'] == other_parent['active'], agent
+
+
+def validate_roster(roster, parent, other_parent, a, b, foreign):
+ family = [roster['current']] + roster['agents']
+ family_ids = {row.get('activeSessionId') for row in family}
+ assert family_ids == {parent['active'], other_parent['active'], a['active'], b['active']}, roster
+ assert foreign['active'] not in family_ids, roster
+ expected = {other_parent['active']: 'sibling', a['active']: 'child', b['active']: 'child'}
+ for active, relationship in expected.items():
+ assert any(row.get('activeSessionId') == active and row.get('relationship') == relationship
+ for row in roster['agents']), roster
+
+
+def selected(row, expected, marker):
+ for operation in ('get', 'recent'):
+ value = row[operation]['value']
+ assert value['agent']['activeSessionId'] == expected['active'], value
+ assert value['agent']['sessionId'] == expected['durable'], value
+ messages = row['recent']['value']['messages']
+ task_texts = [message.get('text') for message in messages
+ if message.get('role') == 'custom' and message.get('customType') == 'agent_message']
+ assert task_texts == ['[task from parent]\n\n' + marker], messages
+ assert not any('OBSERVE_TASK_B' in message.get('text', '') for message in messages), messages
+ assert not any('OBSERVE_TASK_FOREIGN' in message.get('text', '') for message in messages), messages
+ return {'selection': 'child-a', 'transcript_marker': marker}
+
+
+def rejected(row, kind, label):
+ errors = [row[operation].get('error', '') for operation in ('get', 'recent')]
+ assert all(errors), row # A successful foreign/ambiguous read is never accepted.
+ if kind == 'ambiguous':
+ assert all('Ambiguous active session' in error for error in errors), errors
+ else:
+ expected = ('Unknown active session:' if label == 'ts'
+ else 'is not reachable')
+ assert all(expected in error for error in errors), errors
+ return {'rejection': kind}
+
+
+def run_case(binary, label, root, observation):
+ for directory in ('home', 'tmp', 'work', 'agent', 'sessions'):
+ (root / directory).mkdir(parents=True)
+ root = root.resolve()
+ env = {key: os.environ[key] for key in ('PATH', 'LANG', 'LC_ALL', 'TZ',
+ 'PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON') if key in os.environ}
+ library = Path(os.environ['PI_PACKAGE_DIR'])
+ if label == 'ts':
+ env['PI_PACKAGE_DIR'] = str(library)
+ env['PYTHONPATH'] = os.pathsep.join(str(path) for path in sorted((library / 'skills').glob('*/src')))
+ env.update(HOME=str(root / 'home'), TMPDIR=str(root / 'tmp'), DO_NOT_TRACK='1', PI_OFFLINE='1',
+ PI_CODING_AGENT_DIR=str(root / 'agent'), PRIME_AGENT_CODING_AGENT_DIR=str(root / 'agent'),
+ PI_SESSION_DIR=str(root / 'sessions'), PRIME_AGENT_SESSION_DIR=str(root / 'sessions'),
+ XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(root / 'cache'), XDG_DATA_HOME=str(root / 'data'))
+ env[TAG] = str(root)
+ provider = Provider()
+ thread = threading.Thread(target=provider.serve_forever, daemon=True)
+ thread.start()
+ (root / 'agent/models.json').write_text(json.dumps({'providers': {'fixture': {
+ 'api': 'openai-completions', 'apiKey': 'synthetic-only',
+ 'baseUrl': 'http://127.0.0.1:%s/v1' % provider.server_port,
+ 'models': [{'id': 'observe-fixture', 'name': 'Observe Fixture', 'reasoning': False,
+ 'contextWindow': 128000, 'maxTokens': 4096}]}}}))
+ (root / 'agent/settings.json').write_text(json.dumps({'prewarmPythonKernel': False,
+ 'defaultProvider': 'fixture', 'defaultModel': 'observe-fixture'}))
+ socket_path = root / 'd.sock'
+ scope = OwnedProcesses(binary, root, socket_path)
+ log = (root / 'daemon.log').open('wb')
+ command = [str(binary), '--mode', 'daemon', '--daemon-socket', str(socket_path)]
+ process = subprocess.Popen(command, cwd=root / 'work', env=env, stdout=log,
+ stderr=subprocess.STDOUT, start_new_session=True)
+ client, primary = None, None
+ 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)
+ try:
+ scope.register(process, command)
+ client = ObserveClient(socket_path, process)
+ tracker.start()
+ config = {'cwd': str(root / 'work'), 'agentDir': str(root / 'agent'),
+ 'sessionDir': str(root / 'sessions'), 'provider': 'fixture', 'model': 'observe-fixture',
+ 'noExtensions': True, 'noContextFiles': True, 'telemetryDisabled': True}
+ created = observation['created'] = {}
+ def create(name):
+ options = {'config': dict(config), 'name': name, 'lifecycle': 'resident'}
+ value = client.call('create', **options)
+ row = {'active': value.get('activeSessionId') or value.get('id'),
+ 'durable': value['sessionId'], 'file': value['sessionFile'], 'raw': value}
+ assert row['active'], 'create omitted actual active identity'
+ created[name] = row
+ deadline = time.monotonic() + LIMIT
+ while True:
+ scope.discover()
+ matches = []
+ for path in (root / 'agent/daemon-workers').rglob('*.json'):
+ try:
+ descriptor = json.loads(path.read_text())
+ if descriptor.get('rootActiveSessionId') == row['active']:
+ pid, identity = verify_worker(descriptor, row['active'], binary, socket_path)
+ assert scope.ownership(pid, identity), 'worker lacked fixture ownership'
+ matches.append((pid, identity))
+ except (OSError, ValueError):
+ pass # Atomic/transitional descriptor reads are not readiness.
+ if matches:
+ assert len(matches) == 1, 'duplicate descriptor identity'
+ observation.setdefault('worker_identities', {})[name] = matches[0]
+ break
+ assert time.monotonic() < deadline, 'actual worker descriptor never ready'
+ threading.Event().wait(0.025)
+ return row
+ parent = create('observe-parent')
+ other_parent = create('observe-other-parent')
+ # Parentless roots are siblings in both products. An actual child of
+ # that sibling is outside this root's nuclear family (nephew/niece).
+ provider.phase = 'foreign_spawn_setup'
+ provider.code = """import json, dataclasses
+await rlm.spawn('OBSERVE_TASK_FOREIGN', name='observe-foreign-child', model='fixture/observe-fixture')
+print('OBSERVE_SELECTORS_PARITY=' + json.dumps({'children': [dataclasses.asdict(row) for row in await rlm.list_subagents()]}, default=str))
+"""
+ client.call('prompt_and_wait', timeout_seconds=90, activeSessionId=other_parent['active'],
+ message='Spawn an actual child in the other parent family.')
+ foreign_setup = current_probe(provider.requests['foreign_spawn_setup'], 'foreign_spawn_setup')
+ foreign_observation = observation['foreign_setup'] = {'spawn_setup': foreign_setup}
+ with provider.children_arrived:
+ assert provider.children_arrived.wait_for(lambda: 'OBSERVE_TASK_FOREIGN' in provider.child_requests,
+ timeout=LIMIT), 'foreign child never reached its actual model request'
+ def read_foreign_identity(number, remaining):
+ phase = 'foreign_identity_poll_%d' % number
+ provider.phase, provider.code = phase, READ_CHILDREN
+ client.call('prompt_and_wait', timeout_seconds=remaining, activeSessionId=other_parent['active'],
+ message='Read actual foreign child identity readiness.')
+ return current_probe(provider.requests[phase], phase)
+ foreign_rows = await_child_identities(foreign_setup, read_foreign_identity, foreign_observation,
+ expected_tasks=FOREIGN_CHILD_TASKS)
+ foreign_row = foreign_rows['observe-foreign-child']
+ foreign = {'active': foreign_row['active_session_id'], 'durable': foreign_row['session_id'], 'raw': foreign_row}
+ created['observe-foreign-child'] = foreign
+ provider.phase = 'foreign_topology'
+ provider.code = """import json, agent_observe
+print('OBSERVE_SELECTORS_PARITY=' + json.dumps(await agent_observe.get_agent('observe-foreign-child')))
+"""
+ client.call('prompt_and_wait', timeout_seconds=90, activeSessionId=other_parent['active'],
+ message='Observe the actual foreign child parent edges.')
+ foreign_agent = current_probe(provider.requests['foreign_topology'], 'foreign_topology')['agent']
+ observation['foreign_agent'] = foreign_agent
+ validate_foreign_agent(foreign_agent, foreign, other_parent, parent)
+ provider.phase = 'spawn_setup'
+ provider.code = """import json, dataclasses
+await rlm.spawn('OBSERVE_TASK_A', name='observe-child-a', model='fixture/observe-fixture')
+await rlm.spawn('OBSERVE_TASK_B', name='observe-child-b', model='fixture/observe-fixture')
+print('OBSERVE_SELECTORS_PARITY=' + json.dumps({'children': [dataclasses.asdict(row) for row in await rlm.list_subagents()]}, default=str))
+"""
+ client.call('prompt_and_wait', timeout_seconds=90, activeSessionId=parent['active'], message='Run actual resident selector spawn setup.')
+ setup = current_probe(provider.requests['spawn_setup'], 'spawn_setup')
+ observation['spawn_setup'] = setup
+ with provider.children_arrived:
+ assert provider.children_arrived.wait_for(lambda: set(provider.child_requests) == ALL_TASKS,
+ timeout=LIMIT), 'spawned children never reached their actual model requests'
+ def read_identity_snapshot(number, remaining):
+ phase = 'identity_poll_%d' % number
+ provider.phase, provider.code = phase, READ_CHILDREN
+ client.call('prompt_and_wait', timeout_seconds=remaining, activeSessionId=parent['active'],
+ message='Read actual spawned child identity readiness.')
+ return current_probe(provider.requests[phase], phase)
+ rows = await_child_identities(setup, read_identity_snapshot, observation)
+ def child(name):
+ row = rows[name]
+ value = {'active': row['active_session_id'], 'durable': row['session_id'], 'raw': row}
+ assert value['active'] and value['durable'], 'live spawn omitted actual IDs'
+ created[name] = value
+ return value
+ a, b = child('observe-child-a'), child('observe-child-b')
+ ids = [row[key] for row in created.values() for key in ('active', 'durable')]
+ probes = observation['probes'] = {}
+ contract = observation['contract'] = {}
+ def probe(phase, selectors):
+ provider.phase, provider.code = phase, cell(selectors)
+ client.call('prompt_and_wait', timeout_seconds=90, activeSessionId=parent['active'],
+ message='Run the resident observe selectors fixture: ' + phase)
+ value = current_probe(provider.requests[phase], phase)
+ probes[phase] = value
+ validate_roster(value['roster'], parent, other_parent, a, b, foreign)
+ return value['selectors']
+ basic = probe('baseline', {'exact': a['active'], 'active_suffix': suffix(a['active'], ids),
+ 'durable_suffix': suffix(a['durable'], ids), 'name': 'observe-child-a',
+ 'foreign_suffix': suffix(foreign['active'], ids)})
+ for name in ('exact', 'active_suffix', 'durable_suffix', 'name'):
+ contract[name] = selected(basic[name], a, 'OBSERVE_TASK_A')
+ contract['foreign_suffix'] = rejected(basic['foreign_suffix'], 'foreign-family', label)
+ client.call('rename', activeSessionId=b['active'], name=a['active'])
+ collision = probe('collision', {'exact_id_over_name': a['active']})
+ contract['exact_id_over_name'] = selected(collision['exact_id_over_name'], a, 'OBSERVE_TASK_A')
+ client.call('rename', activeSessionId=b['active'], name='observe-child-b')
+ # Same-depth siblings cannot share a name in TS. Parent and child belong
+ # to distinct name namespaces, but both are reachable from the parent.
+ client.call('rename', activeSessionId=parent['active'], name='observe-child-a')
+ ambiguous = probe('ambiguity', {'duplicate_name': 'observe-child-a'})
+ contract['duplicate_name'] = rejected(ambiguous['duplicate_name'], 'ambiguous', label)
+ # Selection is proven only for resident rows; no hydration or full summary equality.
+ assert len(observation['worker_identities']) == 2, 'missing owned root-worker proof'
+ assert set(provider.child_requests) == ALL_TASKS, 'missing live spawned-child proof'
+ assert all(len(requests) == 1 for requests in provider.child_requests.values()), 'child retried/finished during selection'
+ assert not provider.child_reply_timeout, 'held child completed before selector proof'
+ observation['summary_field_presence'] = {
+ phase: {name: {operation: sorted(row[operation]['value']['agent'])
+ for operation in ('get', 'recent') if 'value' in row[operation]}
+ for name, row in value['selectors'].items()}
+ for phase, value in probes.items()}
+
+ except BaseException as error:
+ primary = error
+ observation['primary_error'] = str(error)
+ raise
+ finally:
+ done.set()
+ if tracker.ident is not None:
+ tracker.join(timeout=2)
+ # Shutdown must interrupt the held child turns before provider teardown.
+ finish(scope, client, process, observation)
+ provider.release_children.set()
+ observation['requests'] = provider.requests
+ observation['held_child_requests'] = provider.child_requests
+ observation['child_reply_timeout'] = provider.child_reply_timeout
+ observation['sent_wire'] = client.sent if client else []
+ observation['received_wire'] = client.wire if client else []
+ observation['tracker_errors'] = tracker_errors
+ if tracker_errors or tracker.is_alive():
+ observation['cleanup_verified'] = False
+ observation['cleanup_error'] = 'ownership tracker failed: ' + str(tracker_errors)
+ log.close()
+ observation['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')
+ provider.shutdown()
+ provider.server_close()
+ thread.join(timeout=2)
+ if not observation['cleanup_verified'] and primary is None:
+ raise AssertionError('owned observe fixture cleanup failed: ' + observation.get('cleanup_error', 'unknown'))
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--receipt', type=Path, required=True)
+ args = parser.parse_args()
+ receipt = {'verified': False, 'runs': {}, 'scope': 'Resident agent_observe.get/recent/list: exact active ID, '
+ 'normalized active/durable ID suffix, exact name, exact ID/name precedence, ambiguous name, foreign family rejection.',
+ 'not_verified': ['Passive child hydration', 'Transient progress-note event retention',
+ 'latestMessage/full summary field parity', 'Tool/image/bash preview fidelity', 'TUI/ACP presentation', 'RLM spawn/settle policy equivalence (real spawn is fixture setup only)'],
+ 'normalization': 'Dynamic IDs verified exactly inside each run, then compared by selected fixture identity. '
+ 'Foreign denial text differs (TS worker-local unknown selector vs Rust family-filtered unreachable); raw errors are retained. '
+ 'All summary/preview objects remain raw and are not claimed equal.',
+ 'ownership': 'pa-daemon internal family resolver; existing pa-core host bridge and Python skill unchanged; no new pub API/dependencies.'}
+ try:
+ assert sys.platform == 'linux', 'requires hosted Linux binaries'
+ assert digest(os.environ['PA_TS_ARCHIVE']) == TS_ARCHIVE_SHA256, 'TS archive SHA mismatch'
+ receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256
+ temp = tempfile.TemporaryDirectory(prefix='observe-selectors-')
+ try:
+ for label in ('ts', 'rust'):
+ binary = Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()
+ observation = receipt['runs'][label] = {'binary': str(binary), 'binary_sha256': digest(binary)}
+ run_case(binary, label, Path(temp.name) / label, observation)
+ assert receipt['runs']['ts']['contract'] == receipt['runs']['rust']['contract'], 'selector contract differs'
+ receipt['summary_field_presence'] = {label: run['summary_field_presence']
+ for label, run in receipt['runs'].items()}
+ receipt['verified'] = True
+ finally:
+ primary_pending = sys.exc_info()[0] is not None
+ try:
+ temp.cleanup()
+ except Exception as cleanup_error:
+ receipt['directory_cleanup_error'] = str(cleanup_error)
+ receipt['verified'] = False
+ if not primary_pending:
+ raise # Preserve an earlier probe error instead of replacing it.
+
+ except Exception as error:
+ receipt['error'] = str(error)
+ receipt['verified'] = False
+ finally:
+ args.receipt.parent.mkdir(parents=True, exist_ok=True)
+ args.receipt.write_text(json.dumps(receipt, indent=2) + '\n')
+ print('resident observe selectors verified:', receipt['verified'])
+ return 0 if receipt['verified'] else 1
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/test_review_observe_selectors_parity.py b/scripts/test_review_observe_selectors_parity.py
new file mode 100644
index 0000000000..970183ff69
--- /dev/null
+++ b/scripts/test_review_observe_selectors_parity.py
@@ -0,0 +1,206 @@
+"""Guard exact changed-surface receipts without running product binaries."""
+import ast
+import json
+import unittest
+
+import review_observe_selectors_parity as fixture
+
+
+class SelectorReceiptTests(unittest.TestCase):
+ def test_normalized_suffix_is_unique_and_preserves_case_hyphen_probe(self):
+ value = fixture.suffix('abcd-00112233', ['abcd-00112233', 'different-99992233'])
+ self.assertEqual(value, '0011-2233')
+ self.assertEqual(fixture.suffix('abcd-00112233', ['abcd-00112233', 'abcd-00112233']), value)
+
+ def test_colliding_suffix_extends_before_selection(self):
+ value = fixture.suffix('abc000112233', ['abc000112233', 'def000112233'])
+ normalized = value.replace('-', '').lower()
+ self.assertTrue('abc000112233'.endswith(normalized))
+ self.assertFalse('def000112233'.endswith(normalized))
+
+ def test_current_probe_rejects_stale_or_duplicate_tool_results(self):
+ message = {'role': 'tool', 'tool_call_id': 'observe_current',
+ 'content': fixture.MARKER + json.dumps({'actual': True})}
+ call = {'role': 'assistant', 'tool_calls': [{'id': 'observe_current'}]}
+ requests = [{}, {'messages': [call, message]}]
+ self.assertEqual(fixture.current_probe(requests, 'current'), {'actual': True})
+ for messages in ([call, {**message, 'tool_call_id': 'observe_previous'}], [call, message, message]):
+ with self.assertRaises(AssertionError):
+ fixture.current_probe([{}, {'messages': messages}], 'current')
+
+ def test_current_probe_needs_actual_current_assistant_call(self):
+ with self.assertRaises(AssertionError):
+ fixture.current_probe([{}, {'messages': [{'role': 'tool', 'tool_call_id': 'observe_current',
+ 'content': fixture.MARKER + '{}'}]}], 'current')
+
+ def test_correct_transcript_and_both_actual_ids_required(self):
+ agent = {'activeSessionId': 'actual-a', 'sessionId': 'durable-a'}
+ row = {'get': {'value': {'agent': agent}}, 'recent': {'value': {
+ 'agent': agent, 'messages': [{'role': 'custom', 'customType': 'agent_message', 'text': '[task from parent]\n\nOBSERVE_TASK_A'}]}}}
+ expected = {'active': 'actual-a', 'durable': 'durable-a'}
+ self.assertEqual(fixture.selected(row, expected, 'OBSERVE_TASK_A'), {
+ 'selection': 'child-a', 'transcript_marker': 'OBSERVE_TASK_A'})
+ row['recent']['value']['messages'].append({'role': 'custom', 'customType': 'agent_message', 'text': '[task from parent]\n\nOBSERVE_TASK_B'})
+ with self.assertRaises(AssertionError):
+ fixture.selected(row, expected, 'OBSERVE_TASK_A')
+ row['recent']['value']['messages'] = [{'role': 'custom', 'customType': 'agent_message', 'text': '[task from parent]\n\nOBSERVE_TASK_B'}]
+ with self.assertRaises(AssertionError):
+ fixture.selected(row, expected, 'OBSERVE_TASK_A')
+ row['get']['value']['agent'] = {'activeSessionId': 'actual-a', 'sessionId': 'wrong-durable'}
+ with self.assertRaises(AssertionError):
+ fixture.selected(row, expected, 'OBSERVE_TASK_A')
+
+ def test_foreign_error_and_ambiguity_cannot_be_success_or_other_error(self):
+ for label, error in (('ts', 'Unknown active session: FFF-123'),
+ ('rust', 'agent suffix is not reachable')):
+ row = {'get': {'error': error}, 'recent': {'error': error}}
+ self.assertEqual(fixture.rejected(row, 'foreign-family', label), {'rejection': 'foreign-family'})
+ row['get'] = {'value': {'agent': {'activeSessionId': 'foreign'}}}
+ with self.assertRaises(AssertionError):
+ fixture.rejected(row, 'foreign-family', label)
+ row = {'get': {'error': 'No live session'}, 'recent': {'error': 'No live session'}}
+ with self.assertRaises(AssertionError):
+ fixture.rejected(row, 'ambiguous', 'rust')
+ row = {operation: {'error': 'Ambiguous active session: matches a,b'} for operation in ('get', 'recent')}
+ self.assertEqual(fixture.rejected(row, 'ambiguous', 'ts'), {'rejection': 'ambiguous'})
+
+ def test_child_hold_matches_current_task_not_root_digest_or_history(self):
+ self.assertEqual(fixture.child_task({'messages': [{'role': 'user', 'content': '[task from parent]\n\nOBSERVE_TASK_A'}]}), 'OBSERVE_TASK_A')
+ self.assertIsNone(fixture.child_task({'messages': [
+ {'role': 'user', 'content': 'digest includes OBSERVE_TASK_A'},
+ {'role': 'user', 'content': 'Run parent selector baseline.'}]}))
+ self.assertIsNone(fixture.child_task({'messages': [{'role': 'assistant', 'content': 'OBSERVE_TASK_A'}]}))
+
+ def children(self, ready=True):
+ return {'children': [
+ {'session_name': name, 'rlm_child_id': child_id, 'status': 'running', 'label': task,
+ 'active_session_id': active, 'session_id': durable}
+ for name, child_id, task, active, durable in (
+ ('observe-child-a', 'child-a', 'OBSERVE_TASK_A', 'active-a', 'durable-a'),
+ ('observe-child-b', 'child-b', 'OBSERVE_TASK_B', 'active-b' if ready else None, 'durable-b' if ready else None))]}
+
+ def test_actual_identity_poll_keeps_first_and_every_ready_snapshot(self):
+ first, ready = self.children(False), self.children()
+ polls, observation = [], {'spawn_setup': first}
+ def read(number, remaining):
+ polls.append((number, remaining))
+ return ready
+ times = iter([100, 101, 102])
+ rows = fixture.await_child_identities(first, read, observation, clock=lambda: next(times), budget=5)
+ self.assertEqual(rows['observe-child-b']['active_session_id'], 'active-b')
+ self.assertEqual(polls, [(1, 4)])
+ self.assertIs(observation['spawn_setup'], first)
+ self.assertEqual(observation['identity_polls'], [ready])
+
+ def test_already_ready_children_need_no_additional_model_turn(self):
+ def forbidden(*_args):
+ self.fail('readiness was already observed')
+ observation = {}
+ rows = fixture.await_child_identities(self.children(), forbidden, observation, clock=lambda: 100)
+ self.assertEqual(len(rows), 2)
+ self.assertEqual(observation['identity_polls'], [])
+
+ def test_identity_wait_deadline_is_strict_and_never_sleeps_or_retries(self):
+ times = iter([100, 106])
+ def forbidden(*_args):
+ self.fail('deadline expired before another model turn')
+ with self.assertRaisesRegex(AssertionError, 'before deadline'):
+ fixture.await_child_identities(self.children(False), forbidden, {}, clock=lambda: next(times), budget=5)
+ times = iter([100, 101, 106])
+ observation = {}
+ with self.assertRaisesRegex(AssertionError, 'exceeded deadline'):
+ fixture.await_child_identities(self.children(False), lambda *_args: self.children(),
+ observation, clock=lambda: next(times), budget=5)
+ self.assertEqual(observation['identity_polls'], [self.children()])
+
+ def test_identity_ready_rejects_duplicate_ids_changed_handle_or_wrong_task(self):
+ expected = {'observe-child-a': 'child-a', 'observe-child-b': 'child-b'}
+ for key, bad in (('active_session_id', 'active-a'), ('session_id', 'durable-a'),
+ ('rlm_child_id', 'other-child'), ('label', 'OBSERVE_TASK_A'), ('status', 'completed')):
+ snapshot = self.children()
+ snapshot['children'][1][key] = bad
+ with self.assertRaises(AssertionError, msg=key):
+ fixture.ready_children(snapshot, expected)
+
+ def test_partial_publication_rejects_malformed_ids_before_any_poll(self):
+ for key in ('active_session_id', 'session_id'):
+ for value in (123, '', False, []):
+ snapshot = self.children(False)
+ snapshot['children'][0][key] = value
+ def forbidden(*_args):
+ self.fail('malformed publication must fail before a readiness poll')
+ with self.assertRaisesRegex(AssertionError, 'invalid published'):
+ fixture.await_child_identities(snapshot, forbidden, {}, clock=lambda: 100)
+
+ def test_partial_publication_rejects_duplicates_before_any_poll(self):
+ for duplicate_key, missing_key in (('active_session_id', 'session_id'), ('session_id', 'active_session_id')):
+ snapshot = self.children()
+ snapshot['children'][1][duplicate_key] = snapshot['children'][0][duplicate_key]
+ snapshot['children'][1][missing_key] = None
+ def forbidden(*_args):
+ self.fail('duplicate publication must fail before a readiness poll')
+ with self.assertRaisesRegex(AssertionError, 'duplicate published'):
+ fixture.await_child_identities(snapshot, forbidden, {}, clock=lambda: 100)
+
+ def test_foreign_topology_requires_real_other_parent_edges_not_a_sibling_root(self):
+ parent = {'active': 'main-a', 'durable': 'main-s'}
+ other = {'active': 'other-a', 'durable': 'other-s'}
+ foreign = {'active': 'foreign-a', 'durable': 'foreign-s'}
+ agent = {'activeSessionId': 'foreign-a', 'sessionId': 'foreign-s', 'runtimeKind': 'subagent',
+ 'parentActiveSessionId': 'other-a', 'parentSessionId': 'other-s'}
+ fixture.validate_foreign_agent(agent, foreign, other, parent)
+ for key, value in (('runtimeKind', 'top-level'), ('parentActiveSessionId', 'main-a'), ('parentSessionId', 'main-s')):
+ with self.assertRaises(AssertionError):
+ fixture.validate_foreign_agent({**agent, key: value}, foreign, other, parent)
+ with self.assertRaises(AssertionError):
+ fixture.validate_foreign_agent(agent, foreign, parent, parent)
+
+ def test_roster_retains_valid_root_sibling_but_rejects_its_child(self):
+ parent, other, a, b, foreign = [{'active': name} for name in ('parent', 'other', 'a', 'b', 'foreign')]
+ roster = {'current': {'activeSessionId': 'parent'}, 'agents': [
+ {'activeSessionId': 'other', 'relationship': 'sibling'},
+ {'activeSessionId': 'a', 'relationship': 'child'}, {'activeSessionId': 'b', 'relationship': 'child'}]}
+ fixture.validate_roster(roster, parent, other, a, b, foreign)
+ for extra in ({'activeSessionId': 'foreign', 'relationship': 'child'}, {'activeSessionId': 'foreign', 'relationship': 'sibling'}):
+ with self.assertRaises(AssertionError):
+ fixture.validate_roster({**roster, 'agents': roster['agents'] + [extra]}, parent, other, a, b, foreign)
+ with self.assertRaises(AssertionError):
+ fixture.validate_roster({**roster, 'agents': roster['agents'][1:]}, parent, other, a, b, foreign)
+
+ def test_captured_custom_kickoff_shape_and_mixed_foreign_preview_guard(self):
+ agent = {'activeSessionId': 'actual-a', 'sessionId': 'durable-a'}
+ messages = [{'role': 'custom', 'customType': 'harness_digest', 'text': '[harness-digest]'},
+ {'role': 'custom', 'customType': 'agent_message', 'text': '[task from parent]\n\nOBSERVE_TASK_A'}]
+ row = {'get': {'value': {'agent': agent}}, 'recent': {'value': {'agent': agent, 'messages': messages}}}
+ expected = {'active': 'actual-a', 'durable': 'durable-a'}
+ fixture.selected(row, expected, 'OBSERVE_TASK_A')
+ messages.append({'role': 'custom', 'customType': 'agent_message', 'text': '[task from parent]\n\nOBSERVE_TASK_FOREIGN'})
+ with self.assertRaises(AssertionError):
+ fixture.selected(row, expected, 'OBSERVE_TASK_A')
+ messages[:] = [{'role': 'user', 'text': '[task from parent]\n\nOBSERVE_TASK_A'}]
+ with self.assertRaises(AssertionError):
+ fixture.selected(row, expected, 'OBSERVE_TASK_A')
+
+ def test_single_foreign_child_uses_same_strict_identity_readiness_guards(self):
+ snapshot = {'children': [{'session_name': 'observe-foreign-child', 'rlm_child_id': 'foreign-child',
+ 'label': 'OBSERVE_TASK_FOREIGN', 'status': 'running', 'active_session_id': 'foreign-a', 'session_id': 'foreign-s'}]}
+ rows = fixture.await_child_identities(snapshot, lambda *_args: self.fail('already ready'), {},
+ expected_tasks=fixture.FOREIGN_CHILD_TASKS, clock=lambda: 100)
+ self.assertEqual(rows['observe-foreign-child']['active_session_id'], 'foreign-a')
+ snapshot['children'][0]['active_session_id'] = 123
+ snapshot['children'][0]['session_id'] = None
+ with self.assertRaises(AssertionError):
+ fixture.await_child_identities(snapshot, lambda *_args: self.fail('malformed publication'), {},
+ expected_tasks=fixture.FOREIGN_CHILD_TASKS, clock=lambda: 100)
+
+ def test_identical_cell_uses_actual_skill_functions(self):
+ code = fixture.cell({'exact': 'actual-a', 'foreign_suffix': 'FFF-123'})
+ tree = ast.parse(code)
+ calls = {node.func.attr for node in ast.walk(tree) if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)}
+ self.assertTrue({'list_agents', 'get_agent', 'recent_messages'} <= calls)
+ self.assertIn("'foreign_suffix': 'FFF-123'", code)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/skills/agent-observe/SKILL.md b/skills/agent-observe/SKILL.md
index 9bc4b5016e..28ccac0dba 100644
--- a/skills/agent-observe/SKILL.md
+++ b/skills/agent-observe/SKILL.md
@@ -7,9 +7,10 @@ description: Read-only roster and observation of an agent's parent, siblings, an
Observe the current agent's nuclear family through the local daemon: parent,
siblings, direct children, and self. `list_agents` is the one family roster and
-covers every member `agent_message.send` can reach. `get_agent` and
-`recent_messages` hydrate an inactive child before reading it. They cannot read
-a root sibling that has no live session in this worker.
+covers every member `agent_message.send` can reach. `get_agent` also returns an
+inactive child's roster row. `recent_messages` reads live sessions only; it
+does not rehydrate an inactive member. They cannot read a root sibling that has
+no live session in this worker.
This skill is read-only: it can list family sessions, inspect one session, and fetch
bounded recent message previews. It cannot prompt, steer, clear, kill, rename, or
otherwise mutate another session.
@@ -28,22 +29,31 @@ if child is not None:
## API
-- `await agent_observe.list_agents()` returns `current` and `agents`, the full
- nuclear family: parent, siblings, and direct children, active or not. Each
- agent carries `sessionId`, optional `sessionName`, `relationship`
- (`parent`/`sibling`/`child`), `status`, `isSessionActive`, and the counts and
- message previews known for it: `latestMessage` for a live session,
- `firstMessage` for an inactive child. A member with no live session has
- no `activeSessionId` and no live detail; address it with `agent_message.send`
- using its `relationship` plus its `sessionName`, or its `sessionId` when the
- member has no name. For direct children,
+- `await agent_observe.list_agents()` returns `current` (the calling agent's
+ own row) and `agents` (the family: parent, siblings, and direct children,
+ active or not; the caller is excluded from `agents`). Each row carries
+ `sessionId`, optional `sessionName`, `relationship`
+ (`parent`/`sibling`/`child`), `status` (`running`/`idle` for live sessions,
+ `inactive` without one), the live `activity` (`tool`/`model`/`compacting`/
+ `busy`/`user`/`idle`), `isSessionActive`, the counts known
+ for it (`messageCount`, `queuedCount`, `attachedClients`), `cwd` when the
+ roster row carries it, the parent edges (`parentActiveSessionId`,
+ `parentSessionId`) and `rlmChildId` for subagents, and `firstMessage`
+ (capped at 240 chars) for an inactive child. A member with no live session
+ has no `activeSessionId` and no live detail; address it with
+ `agent_message.send` using its `relationship` plus its `sessionName`, or its
+ `sessionId` when the member has no name. For direct children,
`await rlm.list_subagents()` also exposes parent-owned lifecycle handles.
- `await agent_observe.get_agent(target)` returns `agent`, where `agent`
- contains one live agent summary. `target` is resolved like other live-session
- selectors: active id, session id/name, or unambiguous suffix.
+ contains one agent summary (the same shape as the roster rows, including a
+ passive child's row). `target` is resolved like other live-session
+ selectors: active id, session id or name, or an unambiguous id suffix.
- `await agent_observe.recent_messages(target, limit=8, max_chars=800)`
- returns up to `limit` recent bounded message previews for the target session.
- `limit` must be 1-50, and `max_chars` must be 80-2000.
+ returns `agent` (the target's summary), `messages` (up to `limit` recent
+ bounded previews), the clamped `limit` and `maxChars`, and `truncated`
+ (true when older messages exist beyond the returned window). `limit` must be
+ 1-50, and `max_chars` must be 80-2000. The target must be a live family
+ member: a member with no live session errors instead of hydrating.
## Safety
diff --git a/skills/agent-observe/src/agent_observe/__init__.py b/skills/agent-observe/src/agent_observe/__init__.py
index 39e2d6360c..5b4d2737d9 100644
--- a/skills/agent-observe/src/agent_observe/__init__.py
+++ b/skills/agent-observe/src/agent_observe/__init__.py
@@ -18,7 +18,7 @@ async def list_agents() -> dict[str, Any]:
async def get_agent(target: str) -> dict[str, Any]:
- """Read one live session summary by active id, session id/name, or suffix."""
+ """Read one family member's summary by active id, session id/name, or id suffix."""
if not isinstance(target, str):
raise TypeError(f"target must be str, got {type(target).__name__}")
return await host_request("agent_observe.get", {"target": target})
@@ -32,7 +32,7 @@ async def recent_messages(
"""Read bounded recent message previews from an active session.
Args:
- target: Active session id, session id/name, or unambiguous suffix.
+ target: Active session id, session id/name, or unambiguous id suffix.
limit: Number of recent messages to return. Host validates 1-50.
max_chars: Per-message preview size. Host validates 80-2000.
"""