A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[factory] group factory run costs in /context and keep deleted agents' spend (#3799)
Sebastian Müllerec3feb6e3798
diff --git a/.changes/costs.md b/.changes/costs.mdnew file mode 100644index 0000000000..596e5403c4--- /dev/null+++ b/.changes/costs.md@@ -0,0 +1 @@+- `/context` groups each factory run's agents under one `factory <spec> <run>` row with the run's summed tokens and cost, and deleted subagents now stay in the totals as `deleted` rows, so the `/context` total cost matches the agents view's session total.diff --git a/crates/pa-cli/src/print_rlm.rs b/crates/pa-cli/src/print_rlm.rsindex bf9847cdd1..08cae24014 100644--- a/crates/pa-cli/src/print_rlm.rs+++ b/crates/pa-cli/src/print_rlm.rs@@ -1277,6 +1277,7 @@ mod tests {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,});std::future::poll_fn(|context| {assert!(spawn.as_mut().poll(context).is_pending());diff --git a/crates/pa-cli/tests/agents_view_flash_e2e.rs b/crates/pa-cli/tests/agents_view_flash_e2e.rsindex 5b8e0735ec..abc01b7ccf 100644--- a/crates/pa-cli/tests/agents_view_flash_e2e.rs+++ b/crates/pa-cli/tests/agents_view_flash_e2e.rs@@ -393,6 +393,7 @@ async fn the_first_agents_view_render_is_clean_behind_hundreds_of_dead_subagentschild: child_file.to_string_lossy().to_string(),depth: 1,name: format!("flash worker {index:03}"),+ factory: None,}).expect("append spawn edge");}diff --git a/crates/pa-cli/tests/dock_scope_exit_focus_e2e.rs b/crates/pa-cli/tests/dock_scope_exit_focus_e2e.rsindex 8defe20fa6..94c2061784 100644--- a/crates/pa-cli/tests/dock_scope_exit_focus_e2e.rs+++ b/crates/pa-cli/tests/dock_scope_exit_focus_e2e.rs@@ -277,6 +277,7 @@ async fn scope_exit_keeps_the_subagents_item(exit_key: &'static str) {child: child_path.to_string_lossy().to_string(),depth: 1,name: "scope exit worker".to_string(),+ factory: None,}).expect("append spawn edge");diff --git a/crates/pa-cli/tests/subagent_panel_nav_e2e.rs b/crates/pa-cli/tests/subagent_panel_nav_e2e.rsindex 7cbedc5f2b..67cfac6e1c 100644--- a/crates/pa-cli/tests/subagent_panel_nav_e2e.rs+++ b/crates/pa-cli/tests/subagent_panel_nav_e2e.rs@@ -280,6 +280,7 @@ async fn down_arrow_focuses_the_dock_and_enter_opens_the_scoped_agents_view() {child: child_path.to_string_lossy().to_string(),depth: 1,name: "panel nav worker".to_string(),+ factory: None,}).expect("append spawn edge");@@ -472,6 +473,7 @@ async fn the_title_bills_a_passive_subagents_spend() {child: child_path.to_string_lossy().to_string(),depth: 1,name: "title bill worker".to_string(),+ factory: None,}).expect("append spawn edge");@@ -561,6 +563,7 @@ async fn the_title_bills_a_deleted_subagents_spend() {child: child_path.to_string_lossy().to_string(),depth: 1,name: "title del worker".to_string(),+ factory: None,}).expect("append spawn edge");ledger@@ -573,6 +576,7 @@ async fn the_title_bills_a_deleted_subagents_spend() {output_tokens: 5,cost: 0.3,},+ None,).expect("append delete tombstone");diff --git a/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs b/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rsindex 116c402dd9..a5e8295a87 100644--- a/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs+++ b/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs@@ -226,6 +226,7 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}}diff --git a/crates/pa-core/src/session_engine/rlm_host.rs b/crates/pa-core/src/session_engine/rlm_host.rsindex 1ec6eb484c..0feedff1fb 100644--- a/crates/pa-core/src/session_engine/rlm_host.rs+++ b/crates/pa-core/src/session_engine/rlm_host.rs@@ -146,6 +146,19 @@ pub struct RlmSpawnRequest {/// The parent's in-flight turn request the spawn anchors to (TS/// `spawnedByRequestId`): `None` for a spawn outside an active run.pub spawned_by_request_id: Option<String>,+ /// The factory run that spawned the child; the daemon records it on+ /// the child's ledger spawn edge.+ pub factory: Option<RlmFactoryTag>,+}++/// The factory executor's run tag on a spawned child (`rlm.spawn`'s+/// private `factory` kwarg, wire shape `{runId, specId, stateId}`).+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RlmFactoryTag {+ pub run_id: String,+ pub spec_id: String,+ pub state_id: String,}/// Validated `rlm.create_session` request handed to the host.@@ -644,7 +657,11 @@ fn register_run(handlers: &mut HostRequestHandlers, bridge: &Arc<RlmHostBridge>)fn spawn_request_from_payload(prompt: &str, data: &Value) -> anyhow::Result<RlmSpawnRequest> {const OPERATION: &str = "rlm.spawn";let kwargs = kwargs_from_payload(data);- reject_unsupported_kwargs(&kwargs, OPERATION, &["name", "model", "thinking"])?;+ reject_unsupported_kwargs(+ &kwargs,+ OPERATION,+ &["name", "model", "thinking", "factory"],+ )?;let name = optional_string_kwarg(&kwargs, "name", OPERATION)?;let name = normalize_requested_rlm_subagent_session_name(name, OPERATION)?;if let Some(name) = &name {@@ -655,12 +672,21 @@ fn spawn_request_from_payload(prompt: &str, data: &Value) -> anyhow::Result<RlmSlet thinking = optional_string_kwarg(&kwargs, "thinking", OPERATION)?;let thinking =normalize_requested_rlm_subagent_thinking_level(thinking, OPERATION)?.map(String::from);+ let factory = match kwargs.get("factory") {+ None | Some(Value::Null) => None,+ Some(tag) => Some(serde_json::from_value(tag.clone()).map_err(|_| {+ anyhow::anyhow!(+ "{OPERATION} factory must be an object with string runId, specId, and stateId"+ )+ })?),+ };Ok(RlmSpawnRequest {prompt: prompt.to_string(),name,model,thinking,spawned_by_request_id: None,+ factory,})}@@ -1304,7 +1330,10 @@ mod tests {json!({"type": "rlm.run","prompt": "ship the lane",- "kwargs": { "name": "worker", "model": "p/m", "thinking": "High" }+ "kwargs": {+ "name": "worker", "model": "p/m", "thinking": "High",+ "factory": { "runId": "r1", "specId": "sw", "stateId": "build" },+ }}),).await@@ -1324,6 +1353,14 @@ mod tests {assert_eq!(requests[0].name.as_deref(), Some("worker"));assert_eq!(requests[0].model.as_deref(), Some("p/m"));assert_eq!(requests[0].thinking.as_deref(), Some("high"));+ assert_eq!(+ requests[0].factory,+ Some(RlmFactoryTag {+ run_id: "r1".to_string(),+ spec_id: "sw".to_string(),+ state_id: "build".to_string(),+ })+ );drop(requests);// Validation: prompt type, unsupported kwargs, name rules.diff --git a/crates/pa-daemon/src/context_tree_cache.rs b/crates/pa-daemon/src/context_tree_cache.rsindex 9414707fcd..6c0098c4a5 100644--- a/crates/pa-daemon/src/context_tree_cache.rs+++ b/crates/pa-daemon/src/context_tree_cache.rs@@ -30,6 +30,8 @@ pub(crate) struct CachedWalk {live_nodes: HashMap<String, Value>,/// Persisted child dirs' nodes, in the walk's mtime order.persisted: Vec<Value>,+ /// Exact roster identities whose files were tombstoned during this walk.+ excluded_snapshots: HashSet<String>,}/// The per-worker context-tree cache: the data swap under a std mutex@@ -108,7 +110,11 @@ impl ContextTreeCache {.and_then(Value::as_str).unwrap_or_default();live_ids.insert(id.to_string());- if invalidated.contains(id) {+ if invalidated.contains(id)+ || cached+ .as_ref()+ .is_some_and(|walk| walk.excluded_snapshots.contains(&snapshot_key(snapshot)))+ {// A deletion that outran the roster removal: the row must not come back.continue;}@@ -266,7 +272,7 @@ impl ContextTreeCache {}).await;match walk {- Ok(Ok((mut live_nodes, mut persisted))) => {+ Ok(Ok(mut walk)) => {let mut invalidated = cache.invalidated.lock()@@ -274,8 +280,8 @@ impl ContextTreeCache {// Deletions that landed while this walk ran must not be// republished by the stale snapshot. The set drains here.for child_id in invalidated.iter() {- live_nodes.remove(child_id);- persisted.retain(|node| {+ walk.live_nodes.remove(child_id);+ walk.persisted.retain(|node| {node.get("id").and_then(Value::as_str) != Some(child_id)});}@@ -284,12 +290,8 @@ impl ContextTreeCache {.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- *state = Some(CachedWalk {- computed_at: Instant::now(),- session_id: session_id.clone(),- live_nodes,- persisted,- });+ walk.computed_at = Instant::now();+ *state = Some(walk);}Ok(Err(error)) => {eprintln!("context tree walk failed: {error:#}");@@ -322,67 +324,66 @@ impl ContextTreeCache {}}-/// One full artifact-tree walk: the model registry, the ledger tombstones,-/// every live child's file-derived node, and every persisted child dir under-/// the session's artifact tree. Blocking pool only.+/// One full artifact-tree walk: the model registry, the ledger facts, every+/// live child's file-derived node, every persisted child dir under the+/// session's artifact tree, and the session's deleted rows. Blocking pool only.fn walk_children(agent_dir: &Path,session_id: &str,snapshots: &[Value],session_file: Option<&Path>,-) -> Result<(HashMap<String, Value>, Vec<Value>)> {+) -> Result<CachedWalk> {let registry = crate::state_getters::worker_model_registry(agent_dir);let artifacts_root = crate::context_tree_children::session_artifacts_dir(agent_dir);- // User-deleted subagents stay hidden at every depth: the tombstones key by the deleted- // child's parent session file, so this session's deletions resolve into the root skip- // set and each recursion level its own. Unreadable ledgers degrade to no filtering.+ // User-deleted subagents' transcripts stay hidden at every depth and bill+ // through their deleted rows: the ledger keys both by the deleted child's+ // parent session file, so this session's deletions resolve here and each+ // recursion level its own.+ let sessions_dir = agent_dir.join("sessions");+ let ledger = crate::context_tree_children::ContextLedger::read(+ &crate::rlm_ledger::RlmSpawnLedger::new(agent_dir, &sessions_dir, |_| {}),+ );let mut skip_ids: HashSet<String> = snapshots.iter().filter_map(|child| child.get("id").and_then(Value::as_str)).map(str::to_string).collect();- let mut tombstones = crate::context_tree_children::TombstonedChildren::new();- let sessions_dir = agent_dir.join("sessions");- let ledger = crate::rlm_ledger::RlmSpawnLedger::new(agent_dir, &sessions_dir, |_| {});- if let Ok(edges) = ledger.edges(true) {- for edge in edges {- if edge.deleted.is_some() {- tombstones- .entry(crate::lease::canonical_session_path(Path::new(- &edge.parent,- )))- .or_default()- .insert(edge.child_id.clone());- }- }- }if let Some(session_file) = session_file {- if let Some(deleted) = tombstones.get(&crate::lease::canonical_session_path(session_file)) {- skip_ids.extend(deleted.iter().cloned());- }+ skip_ids.extend(ledger.tombstoned_ids(session_file));}// Live children: the node carries the child's real usage and its// recursive grandchildren; the registry supplies the fresher identity.let mut live_nodes = HashMap::with_capacity(snapshots.len());+ let mut excluded_snapshots = HashSet::new();for child in snapshots {- let mut node = child+ let loaded = child.get("sessionDir").and_then(Value::as_str).and_then(|dir| {- crate::context_tree_children::load_context_tree_child(+ crate::context_tree_children::load_context_tree_child_with_path(&artifacts_root,Path::new(dir),®istry,- &tombstones,+ &ledger,)- })- .unwrap_or_else(|| {+ });+ if loaded+ .as_ref()+ .is_some_and(|(path, _)| ledger.is_tombstoned_file(path))+ {+ excluded_snapshots.insert(snapshot_key(child));+ continue;+ }+ let mut node = loaded.map_or_else(+ || {json!({"ownUsage": empty_usage(),"totalUsage": empty_usage(),"children": [],})- });+ },+ |(_, node)| node,+ );node["id"] = child.get("id").cloned().unwrap_or(Value::Null);node["label"] = child.get("label").cloned().unwrap_or(Value::Null);node["status"] = child.get("status").cloned().unwrap_or(Value::Null);@@ -393,14 +394,33 @@ fn walk_children(.to_string();live_nodes.insert(id, node);}- let persisted = crate::context_tree_children::load_context_tree_children(+ let mut persisted = crate::context_tree_children::load_context_tree_children(&artifacts_root,session_id,®istry,&skip_ids,- &tombstones,+ &ledger,);- Ok((live_nodes, persisted))+ if let Some(session_file) = session_file {+ persisted.extend(ledger.deleted_nodes(session_file));+ }+ Ok(CachedWalk {+ computed_at: Instant::now(),+ session_id: session_id.to_string(),+ live_nodes,+ persisted,+ excluded_snapshots,+ })+}++/// Identity only: status and elapsed duration can change on a stale roster row.+fn snapshot_key(snapshot: &Value) -> String {+ json!([+ snapshot.get("id"),+ snapshot.get("activeSessionId"),+ snapshot.get("sessionDir")+ ])+ .to_string()}#[cfg(test)]@@ -416,6 +436,7 @@ mod tests {let cache = Arc::new(ContextTreeCache::new());*cache.state.lock().unwrap() = Some(CachedWalk {computed_at: Instant::now(),+ excluded_snapshots: HashSet::new(),session_id: session_id.to_string(),live_nodes: live.iter()@@ -505,6 +526,7 @@ mod tests {// the child back at serve time.*cache.state.lock().unwrap() = Some(CachedWalk {computed_at: Instant::now(),+ excluded_snapshots: HashSet::new(),session_id: "session-a".to_string(),live_nodes: [("child-live".to_string(),@@ -557,6 +579,7 @@ mod tests {let cache = Arc::new(ContextTreeCache::new());*cache.state.lock().unwrap() = Some(CachedWalk {computed_at: Instant::now(),+ excluded_snapshots: HashSet::new(),session_id: "session-a".to_string(),live_nodes: HashMap::new(),persisted: vec![json!({@@ -583,6 +606,304 @@ mod tests {);}+ /// One session transcript: a user row and an assistant row billing `cost`.+ fn write_session(path: &Path, session_id: &str, cost: f64) {+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ let lines = [+ json!({+ "type": "session", "version": 3, "id": session_id,+ "timestamp": "2026-10-25T00:00:00.000Z", "cwd": "/tmp",+ }),+ json!({+ "type": "message", "id": "m1", "parentId": null,+ "timestamp": "2026-10-25T00:00:01.000Z",+ "message": {"role": "user", "content": "work"},+ }),+ json!({+ "type": "message", "id": "m2", "parentId": "m1",+ "timestamp": "2026-10-25T00:00:02.000Z",+ "message": {+ "role": "assistant",+ "content": [{ "type": "text", "text": "done" }],+ "provider": "anthropic", "model": "claude-opus-4-6",+ "stopReason": "stop",+ "usage": {+ "input": 10, "output": 5, "cacheRead": 0, "cacheWrite": 0,+ "totalTokens": 15,+ "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": cost },+ },+ },+ }),+ ];+ let content: Vec<String> = lines.iter().map(Value::to_string).collect();+ std::fs::write(path, content.join("\n") + "\n").unwrap();+ }++ /// A deleted factory child keeps billing: /context serves it as a+ /// `deleted` row tagged with its run (from the tombstoned ledger edge)+ /// and split by model (the delete's capture), and the /context grand+ /// total equals the agents-view session total (own row + live child+ /// rows + the ledger's deleted-descendant bucket).+ // Exact binary fractions: the two totals must be the same number.+ #[allow(clippy::float_cmp)]+ #[test]+ fn deleted_children_keep_their_spend_in_the_context_totals() {+ let agent_dir = std::env::temp_dir().join(format!("pa-ctx-del-{}", uuid::Uuid::new_v4()));+ let sessions_dir = agent_dir.join("sessions");+ let root_file = sessions_dir.join("01a0root-0000.jsonl");+ write_session(&root_file, "01a0root-0000", 0.5);+ let children_dir = agent_dir.join("session-artifacts/01a0root-0000");+ let live_file = children_dir.join("sub-live/01a0live-0000.jsonl");+ write_session(&live_file, "01a0live-0000", 0.25);+ let gone_file = children_dir.join("sub-gone/01a0gone-0000.jsonl");+ write_session(&gone_file, "01a0gone-0000", 0.125);+ let tag = crate::rlm_ledger::RlmFactoryTag {+ run_id: "0123456789ab".to_string(),+ spec_id: "sw".to_string(),+ state_id: "build".to_string(),+ };+ let ledger = crate::rlm_ledger::RlmSpawnLedger::new(&agent_dir, &sessions_dir, |_| {});+ for (child_id, file) in [("sub-live", &live_file), ("sub-gone", &gone_file)] {+ ledger+ .append_spawn(&crate::rlm_ledger::RlmSpawnInput {+ child_id: child_id.to_string(),+ parent: root_file.to_string_lossy().to_string(),+ child: file.to_string_lossy().to_string(),+ depth: 1,+ name: child_id.to_string(),+ factory: Some(tag.clone()),+ })+ .unwrap();+ }+ // Another session's untagged child that drew the same child id,+ // spawned later: tags key by child session file, so it neither+ // clears this run's tag nor inherits it.+ let twin = agent_dir.join("session-artifacts/01a0other-0000/sub-live/01a0twin-0000.jsonl");+ ledger+ .append_spawn(&crate::rlm_ledger::RlmSpawnInput {+ child_id: "sub-live".to_string(),+ parent: sessions_dir+ .join("01a0other-0000.jsonl")+ .to_string_lossy()+ .to_string(),+ child: twin.to_string_lossy().to_string(),+ depth: 1,+ name: "twin".to_string(),+ factory: None,+ })+ .unwrap();+ // The production delete: the tombstone, then the usage amendment.+ let gone = gone_file.to_string_lossy().to_string();+ ledger+ .append_delete(+ "sub-gone",+ &gone,+ crate::rlm_ledger::RlmLedgerDeleteReason::User,+ )+ .unwrap();+ crate::stop_cleanup::append_deleted_child_usage_amendments(&ledger, &gone, "sub-gone")+ .expect("a deleted child");++ let walk = walk_children(&agent_dir, "01a0root-0000", &[], Some(&root_file)).unwrap();+ let live_nodes = walk.live_nodes;+ let persisted = walk.persisted;+ assert!(live_nodes.is_empty());+ let cost = |node: &Value| node["ownUsage"]["cost"]["total"].as_f64().unwrap();+ let by_id = |id: &str| {+ persisted+ .iter()+ .find(|node| node["id"] == json!(id))+ .unwrap_or_else(|| panic!("{id} in {persisted:?}"))+ };+ assert_eq!(persisted.len(), 2, "{persisted:?}");+ assert_eq!(by_id("sub-live")["factory"], json!(tag));+ let deleted = persisted+ .iter()+ .find(|node| node["deleted"] == json!(true))+ .unwrap();+ assert_eq!(deleted["deleted"], json!(true));+ assert_eq!(+ deleted["factory"],+ json!(tag),+ "the run tag survives the tombstone"+ );+ assert_eq!(cost(deleted), 0.125);+ // The delete captured the per-model split, so the /context Cost+ // breakdown keeps the deleted spend under its model.+ assert_eq!(+ deleted["ownUsageByModel"],+ json!([{+ "provider": "anthropic",+ "id": "claude-opus-4-6",+ "ownUsage": {+ "input": 10, "output": 5, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 15,+ "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0.125 },+ },+ }])+ );++ let root = crate::session_store::SessionFile::open(&root_file).unwrap();+ let (root_own, _) = crate::state_getters::compute_own_and_total_usage(+ &root.branch_bridged(),+ root.entries(),+ );+ let context_total =+ root_own["cost"]["total"].as_f64().unwrap() + persisted.iter().map(cost).sum::<f64>();+ let row_cost = |file: &Path| {+ crate::session_store::read_session_info(file)+ .and_then(|info| info.usage)+ .map_or(0.0, |usage| usage.cost)+ };+ let root_key = crate::lease::canonical_session_path(&root_file)+ .to_string_lossy()+ .to_string();+ let bucket = ledger.deleted_descendant_usage_by_parent().unwrap();+ let agents_view_total =+ row_cost(&root_file) + row_cost(&live_file) + bucket[&root_key].cost;+ assert_eq!(context_total, 0.875);+ assert_eq!(context_total, agents_view_total);+ let _ = std::fs::remove_dir_all(&agent_dir);+ }++ /// Roster removal may lag the ledger tombstone even after invalidation+ /// has drained. A new walk must not bill the surviving snapshot again.+ #[test]+ fn a_tombstoned_roster_snapshot_never_reenters_the_context_walk() {+ let root = tempfile::tempdir().unwrap();+ let agent_dir = root.path();+ let parent = agent_dir.join("sessions/parent.jsonl");+ let child = agent_dir.join("session-artifacts/parent/sub-old/child.jsonl");+ write_session(&parent, "parent", 0.5);+ write_session(&child, "child", 0.125);+ let ledger =+ crate::rlm_ledger::RlmSpawnLedger::new(agent_dir, &agent_dir.join("sessions"), |_| {});+ ledger+ .append_spawn(&crate::rlm_ledger::RlmSpawnInput {+ child_id: "sub-old".into(),+ parent: parent.to_string_lossy().into(),+ child: child.to_string_lossy().into(),+ depth: 1,+ name: "old".into(),+ factory: None,+ })+ .unwrap();+ ledger+ .append_delete(+ "sub-old",+ &child.to_string_lossy(),+ crate::rlm_ledger::RlmLedgerDeleteReason::User,+ )+ .unwrap();+ crate::stop_cleanup::append_deleted_child_usage_amendments(+ &ledger,+ &child.to_string_lossy(),+ "sub-old",+ )+ .unwrap();+ let stale = json!({"id": "sub-old", "label": "old", "status": "completed",+ "sessionDir": child.parent().unwrap()});+ let walk = walk_children(+ agent_dir,+ "parent",+ std::slice::from_ref(&stale),+ Some(&parent),+ )+ .unwrap();+ let live = &walk.live_nodes;+ let deleted = &walk.persisted;+ assert!(+ live.is_empty(),+ "tombstone must hide stale roster row: {live:?}"+ );+ assert_eq!(deleted.len(), 1);+ assert_eq!(deleted[0]["totalUsage"]["cost"]["total"], json!(0.125));+ let expected = walk.persisted.clone();+ let cache = ContextTreeCache::new();+ *cache.state.lock().unwrap() = Some(walk);+ let mut changed_status = stale.clone();+ changed_status["status"] = json!("cancelled");+ changed_status["durationMs"] = json!(1234);+ assert_eq!(+ cache.serve_children(Some("parent"), &[changed_status]),+ expected,+ "cache overlay must not resurrect the usage-empty fallback either"+ );+ let mut reused = stale;+ reused["activeSessionId"] = json!("new-runtime");+ let served = cache.serve_children(Some("parent"), &[reused]);+ assert_eq!(+ served+ .iter()+ .map(|node| (node["id"].clone(), node["deleted"].clone()))+ .collect::<Vec<_>>(),+ vec![+ (json!("sub-old"), Value::Null),+ (expected[0]["id"].clone(), json!(true))+ ],+ "a new runtime reusing the child id remains visible"+ );+ }++ /// A child id may identify distinct historical files under the same+ /// parent. Each billable tombstone needs a distinct context node id.+ #[test]+ #[allow(clippy::float_cmp)] // Exact binary fractions: the billable total must match.+ fn deleted_context_nodes_distinguish_reused_child_ids() {+ let root = tempfile::tempdir().unwrap();+ let agent_dir = root.path();+ let parent = agent_dir.join("sessions/parent.jsonl");+ write_session(&parent, "parent", 0.5);+ let ledger =+ crate::rlm_ledger::RlmSpawnLedger::new(agent_dir, &agent_dir.join("sessions"), |_| {});+ for (id, cost) in [("first", 0.125), ("second", 0.25)] {+ let child = agent_dir.join(format!("session-artifacts/parent/{id}/{id}.jsonl"));+ write_session(&child, id, cost);+ ledger+ .append_spawn(&crate::rlm_ledger::RlmSpawnInput {+ child_id: "reused".into(),+ parent: parent.to_string_lossy().into(),+ child: child.to_string_lossy().into(),+ depth: 1,+ name: id.into(),+ factory: None,+ })+ .unwrap();+ ledger+ .append_delete(+ "reused",+ &child.to_string_lossy(),+ crate::rlm_ledger::RlmLedgerDeleteReason::User,+ )+ .unwrap();+ crate::stop_cleanup::append_deleted_child_usage_amendments(+ &ledger,+ &child.to_string_lossy(),+ "reused",+ )+ .unwrap();+ }+ let nodes = walk_children(agent_dir, "parent", &[], Some(&parent))+ .unwrap()+ .persisted;+ assert_eq!(nodes.len(), 2);+ let ids: HashSet<&str> = nodes+ .iter()+ .map(|node| node["id"].as_str().unwrap())+ .collect();+ assert_eq!(+ ids.len(),+ 2,+ "distinct tombstoned files share ids: {nodes:?}"+ );+ assert_eq!(+ nodes+ .iter()+ .map(|node| node["totalUsage"]["cost"]["total"].as_f64().unwrap())+ .sum::<f64>(),+ 0.375+ );+ }+#[test]fn cold_cache_serves_live_rows_with_the_usage_fallback() {let cache = ContextTreeCache::new();diff --git a/crates/pa-daemon/src/context_tree_children.rs b/crates/pa-daemon/src/context_tree_children.rsindex 68c7b02e23..7f85732e40 100644--- a/crates/pa-daemon/src/context_tree_children.rs+++ b/crates/pa-daemon/src/context_tree_children.rs@@ -1,7 +1,9 @@//! The persisted RLM child nodes of the /context tree: the live registry covers only children THIS//! worker spawned; every other child is read from its persisted session dir. Deliberate TS//! divergences: grandchildren live under the sibling tree (TS nests them inside `sub-<id>/`);-//! deleted subagents stay hidden via durable ledger tombstones at every level (TS: memory only).+//! a deleted subagent's transcript stays hidden via durable ledger tombstones at every level+//! (TS: memory only) and its spend rides a `deleted` row from the ledger's deleted-spend fold,+//! the same fold the agents view bills; every child carries its ledger edge's factory run tag.use std::collections::{HashMap, HashSet};use std::path::{Path, PathBuf};@@ -17,9 +19,172 @@ use crate::session_store::SessionFile;const LABEL_MAX_CHARS: usize = 80;const ELLIPSIS: &str = "...";-/// User-deleted child ids keyed by the deleted child's parent session-/// file path (the RLM ledger's durable tombstones, canonicalized).-pub type TombstonedChildren = HashMap<PathBuf, HashSet<String>>;+/// The RLM ledger facts the walk reads, keyed by the parent session file+/// (canonicalized): the tombstoned child ids whose transcripts stay hidden+/// and the billable deleted children (the agents view's deleted-spend+/// fold); plus each child's factory run tag, keyed by the child's own+/// session file (child ids are only unique under one parent).+#[derive(Debug, Default)]+pub struct ContextLedger {+ tombstoned: HashMap<PathBuf, HashSet<String>>,+ tombstoned_files: HashSet<PathBuf>,+ deleted: HashMap<PathBuf, Vec<crate::rlm_ledger::DeletedChildUsage>>,+ factory: HashMap<PathBuf, crate::rlm_ledger::RlmFactoryTag>,+}++impl ContextLedger {+ /// Read the facts from one ledger. An unreadable ledger degrades to no+ /// filtering and no deleted rows.+ pub fn read(ledger: &crate::rlm_ledger::RlmSpawnLedger) -> Self {+ let mut facts = Self::default();+ let (edges, deleted) = ledger.edges_with_deleted_children().unwrap_or_default();+ // A reused path with a live edge bills as live, like the ledger's+ // deleted-spend fold; an older tombstone must not hide its new owner.+ let live_files: HashSet<PathBuf> = edges+ .iter()+ .filter(|edge| edge.deleted.is_none())+ .map(|edge| crate::lease::canonical_session_path(Path::new(&edge.child)))+ .collect();+ // Replay order: the last edge at a child session file decides its tag.+ for edge in edges {+ let child = crate::lease::canonical_session_path(Path::new(&edge.child));+ match edge.factory.clone() {+ Some(tag) => facts.factory.insert(child, tag),+ None => facts.factory.remove(&child),+ };+ if edge.deleted.is_some() {+ let file = crate::lease::canonical_session_path(Path::new(&edge.child));+ if !live_files.contains(&file) {+ facts.tombstoned_files.insert(file);+ }+ facts+ .tombstoned+ .entry(crate::lease::canonical_session_path(Path::new(+ &edge.parent,+ )))+ .or_default()+ .insert(edge.child_id);+ }+ }+ for (parent, children) in deleted {+ facts.deleted.insert(PathBuf::from(parent), children);+ }+ facts+ }++ /// The tombstoned child ids of one parent session file.+ pub fn tombstoned_ids(&self, parent_file: &Path) -> HashSet<String> {+ self.tombstoned+ .get(&crate::lease::canonical_session_path(parent_file))+ .cloned()+ .unwrap_or_default()+ }++ /// Whether this exact session file was tombstoned; called on the blocking walk.+ pub(crate) fn is_tombstoned_file(&self, path: &Path) -> bool {+ self.tombstoned_files+ .contains(&crate::lease::canonical_session_path(path))+ }++ /// Set a child node's `factory` run tag from the ledger edge of its+ /// session file.+ fn tag(&self, node: &mut Value, session_file: &Path) {+ if let Some(tag) = self+ .factory+ .get(&crate::lease::canonical_session_path(session_file))+ {+ node["factory"] = json!(tag);+ }+ }++ /// One `deleted` row per billable deleted child of one parent session+ /// file, with its per-model split when the capture recorded one (the+ /// split's tokens equal the summary's; the billed cost stays the+ /// summary's). Without a split, the summary's `inputTokens` already+ /// include cache reads and writes.+ pub fn deleted_nodes(&self, parent_file: &Path) -> Vec<Value> {+ let Some(children) = self+ .deleted+ .get(&crate::lease::canonical_session_path(parent_file))+ else {+ return Vec::new();+ };+ children+ .iter()+ .map(|child| {+ let summary = &child.usage;+ let (input, cache_read, cache_write) = match &child.by_model {+ Some(models) => (+ models.iter().map(|model| model.input).sum(),+ models.iter().map(|model| model.cache_read).sum(),+ models.iter().map(|model| model.cache_write).sum(),+ ),+ None => (summary.input_tokens, 0, 0),+ };+ let usage = usage_value(+ input,+ summary.output_tokens,+ cache_read,+ cache_write,+ summary.cost,+ );+ // Its own id namespace: a live child reusing the id must+ // never collide with (or invalidate) the deleted spend.+ let mut node = json!({+ "id": format!("deleted:{}", child.child_file),+ "label": child.name,+ "status": "deleted",+ "deleted": true,+ "ownUsage": usage,+ "totalUsage": usage,+ "children": [],+ });+ if let Some(tag) = &child.factory {+ node["factory"] = json!(tag);+ }+ if let Some(models) = &child.by_model {+ let buckets: Vec<Value> = models+ .iter()+ .map(|model| {+ json!({+ "provider": model.provider,+ "id": model.id,+ "ownUsage": usage_value(+ model.input,+ model.output,+ model.cache_read,+ model.cache_write,+ model.cost,+ ),+ })+ })+ .collect();+ node["ownUsageByModel"] = json!(buckets);+ }+ node+ })+ .collect()+ }+}++/// The `Usage` wire shape for one token split and its billed total (the+/// ledger keeps no per-category cost).+fn usage_value(input: u64, output: u64, cache_read: u64, cache_write: u64, cost: f64) -> Value {+ json!({+ "input": input,+ "output": output,+ "cacheRead": cache_read,+ "cacheWrite": cache_write,+ "totalTokens": input + output + cache_read + cache_write,+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0,+ "total": cost,+ },+ })+}/// The artifact tree root every session's children live under/// (`child_session_dir` writes `<agent-dir>/session-artifacts/<id>/...`).@@ -37,8 +202,21 @@ pub fn load_context_tree_child(artifacts_root: &Path,child_dir: &Path,registry: &ModelRegistry,- tombstones: &TombstonedChildren,+ ledger: &ContextLedger,) -> Option<Value> {+ load_context_tree_child_with_path(artifacts_root, child_dir, registry, ledger)+ .filter(|(path, _)| !ledger.is_tombstoned_file(path))+ .map(|(_, node)| node)+}++/// The node and the exact file it read, so a stale live roster snapshot+/// can be fenced against durable tombstones without hiding a reused id.+pub(crate) fn load_context_tree_child_with_path(+ artifacts_root: &Path,+ child_dir: &Path,+ registry: &ModelRegistry,+ ledger: &ContextLedger,+) -> Option<(PathBuf, Value)> {// The newest VALID session file: artifact dirs carry sibling `.jsonl`// files that are not sessions, so candidates are tried newest-first.let store = newest_session_files(child_dir)@@ -84,20 +262,20 @@ pub fn load_context_tree_child(if let Some(by_model) = own_usage_by_model {node["ownUsageByModel"] = json!(by_model);}- // The child's own deleted subagents stay hidden one level down: the- // tombstones key by the deleted child's parent session file.- let deleted_ids = tombstones- .get(&crate::lease::canonical_session_path(&store.path))- .cloned()- .unwrap_or_default();- node["children"] = Value::Array(load_context_tree_children(+ ledger.tag(&mut node, &store.path);+ // The child's own deleted subagents stay hidden one level down and+ // bill through their deleted rows: the ledger keys by the deleted+ // child's parent session file.+ let mut children = load_context_tree_children(artifacts_root,store.session_id(),registry,- &deleted_ids,- tombstones,- ));- Some(node)+ &ledger.tombstoned_ids(&store.path),+ ledger,+ );+ children.extend(ledger.deleted_nodes(&store.path));+ node["children"] = Value::Array(children);+ Some((store.path, node))}/// Build the nodes for every persisted child dir of one session (TS@@ -108,7 +286,7 @@ pub fn load_context_tree_children(session_id: &str,registry: &ModelRegistry,skip_ids: &HashSet<String>,- tombstones: &TombstonedChildren,+ ledger: &ContextLedger,) -> Vec<Value> {child_session_dirs(&artifacts_root.join(session_id)).into_iter()@@ -119,7 +297,7 @@ pub fn load_context_tree_children(})}).filter_map(|child_dir| {- load_context_tree_child(artifacts_root, &child_dir, registry, tombstones)+ load_context_tree_child(artifacts_root, &child_dir, registry, ledger)}).collect()}@@ -326,7 +504,7 @@ mod tests {&artifacts,&child_dir,®istry(),- &TombstonedChildren::new(),+ &ContextLedger::default(),).expect("node builds");assert_eq!(node["id"], json!("sub-003f741a"));@@ -341,22 +519,14 @@ mod tests {// An errored child renders as errored; an aborted one as cancelled.let errored = write_child(&parent, "sub-errored", "01a0child-0001", "error");- let node = load_context_tree_child(- &artifacts,- &errored,- ®istry(),- &TombstonedChildren::new(),- )- .expect("node builds");+ let node =+ load_context_tree_child(&artifacts, &errored, ®istry(), &ContextLedger::default())+ .expect("node builds");assert_eq!(node["status"], json!("error"));let aborted = write_child(&parent, "sub-aborted", "01a0child-0002", "aborted");- let node = load_context_tree_child(- &artifacts,- &aborted,- ®istry(),- &TombstonedChildren::new(),- )- .expect("node builds");+ let node =+ load_context_tree_child(&artifacts, &aborted, ®istry(), &ContextLedger::default())+ .expect("node builds");assert_eq!(node["status"], json!("cancelled"));let _ = std::fs::remove_dir_all(&root);}@@ -431,7 +601,7 @@ mod tests {&artifacts,&child_dir,®istry(),- &TombstonedChildren::new(),+ &ContextLedger::default(),).expect("node builds");assert_eq!(@@ -491,7 +661,7 @@ mod tests {&artifacts,&modelless,®istry(),- &TombstonedChildren::new(),+ &ContextLedger::default(),).expect("node builds");assert!(node.get("ownUsageByModel").is_none());@@ -513,7 +683,7 @@ mod tests {"01a0parent-0000",®istry,&HashSet::default(),- &TombstonedChildren::new(),+ &ContextLedger::default(),);assert_eq!(nodes.len(), 2, "non-sub dirs and empty dirs drop out");@@ -523,7 +693,7 @@ mod tests {"01a0parent-0000",®istry,&skip,- &TombstonedChildren::new(),+ &ContextLedger::default(),);assert_eq!(nodes.len(), 1);assert_eq!(nodes[0]["id"], json!("sub-b"));@@ -553,7 +723,7 @@ mod tests {&artifacts,&child_dir,®istry(),- &TombstonedChildren::new(),+ &ContextLedger::default(),).expect("node builds");let grandchildren = node["children"].as_array().expect("children");@@ -585,14 +755,15 @@ mod tests {"01a0grand-0001","stop",);- let mut tombstones = TombstonedChildren::new();- tombstones+ let mut ledger = ContextLedger::default();+ ledger+ .tombstoned.entry(crate::lease::canonical_session_path(&child_dir.join("01a0child-0000.jsonl"),)).or_default().insert("sub-dead".to_string());- let node = load_context_tree_child(&artifacts, &child_dir, ®istry(), &tombstones)+ let node = load_context_tree_child(&artifacts, &child_dir, ®istry(), &ledger).expect("node builds");let grandchildren = node["children"].as_array().expect("children");assert_eq!(@@ -626,7 +797,7 @@ mod tests {&artifacts,&child_dir,®istry(),- &TombstonedChildren::new(),+ &ContextLedger::default(),).expect("node builds");assert_eq!(node["ownUsage"]["input"], json!(7));diff --git a/crates/pa-daemon/src/messaging.rs b/crates/pa-daemon/src/messaging.rsindex 1e34c0e480..a664160f89 100644--- a/crates/pa-daemon/src/messaging.rs+++ b/crates/pa-daemon/src/messaging.rs@@ -672,6 +672,8 @@ mod tests {name: "kid".to_string(),deleted: None,deleted_usage: None,+ deleted_usage_by_model: None,+ factory: None,};for selector in ["kid", "sub-kid1", "sess-kid"] {assert!(ledger_edge_matches(&edge, selector), "{selector}");diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rsindex 79c9f6cce6..75a347d556 100644--- a/crates/pa-daemon/src/rlm_children/host.rs+++ b/crates/pa-daemon/src/rlm_children/host.rs@@ -122,13 +122,17 @@ impl RlmSubagentHost for SupervisorChildSessions {let thinking = request.thinking.as_deref().or(identity.thinking.as_deref());let child_dir = this.child_session_dir(&child_id, &identity)?;let cwd = identity.cwd.clone().unwrap_or_else(|| "/".to_string());- let runtime_metadata = json!({+ let mut runtime_metadata = json!({"kind": "subagent","rlmChildId": child_id,"parentActiveSessionId": this.parent_active_session_id,"rlmDepth": identity.rlm_depth + 1,"createdAt": now_ms(),});+ // The admission's ledger spawn record reads the run tag back.+ if let Some(factory) = &request.factory {+ runtime_metadata["factory"] = json!(factory);+ }let created = this.create_child(&child_id,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.rsindex 24107cdb5b..1961849b6a 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@@ -161,6 +161,7 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}}diff --git a/crates/pa-daemon/src/rlm_children/watch_tests.rs b/crates/pa-daemon/src/rlm_children/watch_tests.rsindex a350b41bbd..84fa38dec0 100644--- a/crates/pa-daemon/src/rlm_children/watch_tests.rs+++ b/crates/pa-daemon/src/rlm_children/watch_tests.rs@@ -429,6 +429,7 @@ async fn spawn_child(sessions: &SupervisorChildSessions) -> RlmSpawnHandle {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}).await.expect("spawn must succeed against the fake supervisor")diff --git a/crates/pa-daemon/src/rlm_ledger.rs b/crates/pa-daemon/src/rlm_ledger.rsindex 03ff133986..5abcdaa71e 100644--- a/crates/pa-daemon/src/rlm_ledger.rs+++ b/crates/pa-daemon/src/rlm_ledger.rs@@ -28,6 +28,7 @@ use serde_json::{json, Value};use crate::lease::canonical_session_path;use crate::util::now_iso;+pub use pa_core::session_engine::rlm_host::RlmFactoryTag;mod replay;@@ -97,6 +98,13 @@ pub struct RlmLedgerEdge {/// The child's captured own usage at deletion, so a tombstoned child's/// spend stays billable; `None` on legacy tombstones and live edges.pub deleted_usage: Option<crate::session_usage::SessionUsageSummary>,+ /// The captured usage's per-model split (`None` on snapshots written+ /// before the split was captured, or when the transcript's models did+ /// not reconcile with the snapshot).+ pub deleted_usage_by_model: Option<Vec<crate::session_usage::ModelUsageSummary>>,+ /// The factory run that spawned the child (spawn records written+ /// before the tag existed read `None`); it survives the tombstone.+ pub factory: Option<RlmFactoryTag>,}/// Inputs for `append_spawn` (validated like a record the reader would refuse to read back).@@ -107,6 +115,69 @@ pub struct RlmSpawnInput {pub child: String,pub depth: u32,pub name: String,+ pub factory: Option<RlmFactoryTag>,+}++/// One billable tombstoned child (the deleted-spend fold's unit): its+/// edge identity and its spend with its tombstoned descendants folded in.+#[derive(Debug, Clone, PartialEq)]+pub struct DeletedChildUsage {+ pub child_id: String,+ /// Canonical file identity: child ids may be reused for another file.+ pub child_file: String,+ pub name: String,+ pub factory: Option<RlmFactoryTag>,+ pub usage: crate::session_usage::SessionUsageSummary,+ /// `usage` split by model; `None` when any folded path has no split+ /// (a snapshot captured before the split existed).+ pub by_model: Option<Vec<crate::session_usage::ModelUsageSummary>>,+}++/// The billable deleted children keyed by the parent's canonical session path.+pub type DeletedChildrenByParent = HashMap<String, Vec<DeletedChildUsage>>;++fn zero_usage() -> crate::session_usage::SessionUsageSummary {+ crate::session_usage::SessionUsageSummary {+ input_tokens: 0,+ output_tokens: 0,+ cost: 0.0,+ }+}++/// Saturating: the fold feeds billable rollups - a huge snapshot must not+/// panic or wrap to an underbill in release.+fn add_usage(+ mut left: crate::session_usage::SessionUsageSummary,+ right: &crate::session_usage::SessionUsageSummary,+) -> crate::session_usage::SessionUsageSummary {+ left.input_tokens = left.input_tokens.saturating_add(right.input_tokens);+ left.output_tokens = left.output_tokens.saturating_add(right.output_tokens);+ left.cost += right.cost;+ left+}++/// Merge two per-model splits; an unsplit side leaves the sum unsplit.+fn add_usage_by_model(+ left: Option<Vec<crate::session_usage::ModelUsageSummary>>,+ right: Option<&Vec<crate::session_usage::ModelUsageSummary>>,+) -> Option<Vec<crate::session_usage::ModelUsageSummary>> {+ let (mut left, right) = (left?, right?);+ for model in right {+ match left+ .iter_mut()+ .find(|existing| existing.provider == model.provider && existing.id == model.id)+ {+ Some(existing) => {+ existing.input = existing.input.saturating_add(model.input);+ existing.output = existing.output.saturating_add(model.output);+ existing.cache_read = existing.cache_read.saturating_add(model.cache_read);+ existing.cache_write = existing.cache_write.saturating_add(model.cache_write);+ existing.cost += model.cost;+ }+ None => left.push(model.clone()),+ }+ }+ Some(left)}/// The per-sessions-dir spawn ledger. Reads are guarded by a file stat snapshot; a missing ledger@@ -169,29 +240,25 @@ fn fold_records(records: Vec<LedgerRecord>, keep: impl Fn(&str) -> bool) -> Replchild,depth,name,+ factory,} if keep(&child_id) => {let key = edge_key(&child_id, &child);+ let edge = RlmLedgerEdge {+ child_id,+ parent,+ child,+ depth,+ name,+ deleted: None,+ deleted_usage: None,+ deleted_usage_by_model: None,+ factory,+ };if let Some(at) = state.index.get(&key).copied() {- state.edges[at] = RlmLedgerEdge {- child_id,- parent,- child,- depth,- name,- deleted: None,- deleted_usage: None,- };+ state.edges[at] = edge;} else {- state.index.insert(key.clone(), state.edges.len());- state.edges.push(RlmLedgerEdge {- child_id,- parent,- child,- depth,- name,- deleted: None,- deleted_usage: None,- });+ state.index.insert(key, state.edges.len());+ state.edges.push(edge);}}LedgerRecord::Rename {@@ -211,6 +278,7 @@ fn fold_records(records: Vec<LedgerRecord>, keep: impl Fn(&str) -> bool) -> Replchild,reason,usage,+ usage_by_model,} if keep(&child_id) => {let key = edge_key(&child_id, &child);let at = match state.index.get(&key).copied() {@@ -223,6 +291,7 @@ fn fold_records(records: Vec<LedgerRecord>, keep: impl Fn(&str) -> bool) -> Repl// block never clears it; a fresh capture replaces it.if let Some(usage) = usage {state.edges[at].deleted_usage = Some(usage);+ state.edges[at].deleted_usage_by_model = usage_by_model;}}}@@ -311,7 +380,7 @@ impl RlmSpawnLedger {);}}- self.append_record(&json!({+ let mut record = json!({"v": 1,"op": "spawn","at": now_iso(),@@ -320,7 +389,12 @@ impl RlmSpawnLedger {"child": child_path_text,"depth": input.depth,"name": input.name,- }))+ });+ // Optional: old readers skip the unknown field (no version bump).+ if let Some(factory) = &input.factory {+ record["factory"] = json!(factory);+ }+ self.append_record(&record)}/// Record a rename for a known child edge.@@ -399,6 +473,7 @@ impl RlmSpawnLedger {child: &str,reason: RlmLedgerDeleteReason,usage: &crate::session_usage::SessionUsageSummary,+ by_model: Option<&[crate::session_usage::ModelUsageSummary]>,) -> Result<()> {let child_path = canonical_session_path(Path::new(child));// The writer never records what the reader refuses: replay@@ -413,8 +488,12 @@ impl RlmSpawnLedger {if !usage.cost.is_finite() || usage.cost.is_sign_negative() {return self.append_delete(child_id, child, reason);}- let usage = serde_json::to_value(usage)+ let mut usage = serde_json::to_value(usage).with_context(|| "serialize the deleted child usage snapshot")?;+ // Optional: old readers skip the unknown field (no version bump).+ if let Some(by_model) = by_model {+ usage["byModel"] = json!(by_model);+ }self.append_record(&json!({"v": 1,"op": "delete",@@ -437,7 +516,7 @@ impl RlmSpawnLedger {child: &str,reason: RlmLedgerDeleteReason,) -> Result<Vec<RlmLedgerEdge>> {- self.tombstone_child_path_with_usage(child, reason, None)+ self.tombstone_child_path_with_usage(child, reason, None, None)}/// The saved-session delete's tombstone with the captured usage snapshot (the file dies right@@ -451,6 +530,7 @@ impl RlmSpawnLedger {child: &str,reason: RlmLedgerDeleteReason,usage: Option<&crate::session_usage::SessionUsageSummary>,+ by_model: Option<&[crate::session_usage::ModelUsageSummary]>,) -> Result<Vec<RlmLedgerEdge>> {let target = canonical_session_path(Path::new(child));let state = self.replay_cached()?;@@ -463,7 +543,13 @@ impl RlmSpawnLedger {for edge in &matching {match usage {Some(usage) => {- self.append_delete_with_usage(&edge.child_id, &edge.child, reason, usage)?;+ self.append_delete_with_usage(+ &edge.child_id,+ &edge.child,+ reason,+ usage,+ by_model,+ )?;}None => self.append_delete(&edge.child_id, &edge.child, reason)?,}@@ -473,21 +559,9 @@ impl RlmSpawnLedger {/// Recursive spend of tombstoned descendants keyed by the parent's/// canonical session path (TS `deletedDescendantUsageByParent`, the- /// agents-view cost rollup's bucket): a deleted subagent keeps no row- /// anywhere, so nothing re-adds its spend once the tombstone drops its- /// row - this folds the captured spend back per family so cost rollups- /// bill it to the parent that spent it. Live paths never contribute- /// (their own rows carry their spend); a tombstoned path that still- /// has a catalog row bills through that row instead (see the skip- /// below); the first tombstoned edge claims a path (a raced ledger- /// must not bill one child to two parents); the fold is an iterative- /// post-order walk (a pathological chain must not overflow the- /// stack) that reads each tombstoned child's captured own usage- /// first and falls back to the transcript's own-usage fold (the- /// resumable `read_session_info` scan) for legacy tombstones that- /// predate the capture - a path with neither a snapshot nor a- /// readable transcript is the documented historical gap (no- /// fabricated backfill: zero).+ /// agents-view cost rollup's bucket): the sum of the parent's+ /// [`Self::deleted_children_of`] entries, so every surface that+ /// bills deleted subagents reads one fold.////// # Errors///@@ -498,6 +572,58 @@ impl RlmSpawnLedger {) -> Result<HashMap<String, crate::session_usage::SessionUsageSummary>> {self.seed_once()?;let state = self.replay_cached()?;+ Ok(self+ .deleted_children_of(&state)?+ .into_iter()+ .map(|(parent, children)| {+ let total = children+ .iter()+ .fold(zero_usage(), |total, child| add_usage(total, &child.usage));+ (parent, total)+ })+ .collect())+ }++ /// Every edge (tombstones included) and the billable deleted children+ /// ([`Self::deleted_children_of`]) from ONE replay snapshot, so a delete+ /// appended mid-read cannot both keep a transcript row and add its+ /// deleted row.+ ///+ /// # Errors+ ///+ /// Returns an error when the ledger replay fails (an oversized+ /// ledger) or a prior panic poisoned the deleted-usage cache.+ pub fn edges_with_deleted_children(+ &self,+ ) -> Result<(Vec<RlmLedgerEdge>, DeletedChildrenByParent)> {+ self.seed_once()?;+ let state = self.replay_cached()?;+ Ok((state.edges.clone(), self.deleted_children_of(&state)?))+ }++ /// The billable tombstoned children keyed by the parent's canonical+ /// session path, each with its folded spend: a deleted subagent keeps+ /// no row anywhere, so nothing re-adds its spend once the tombstone+ /// drops its row - this folds the captured spend back per family so+ /// cost surfaces bill it to the parent that spent it. Live paths never+ /// contribute (their own rows carry their spend); a tombstoned path+ /// that still has a catalog row bills through that row instead (see+ /// the skip in the fold); the first tombstoned edge claims a path (a+ /// raced ledger must not bill one child to two parents); a child's+ /// entry folds its tombstoned descendants in (an iterative post-order+ /// walk: a pathological chain must not overflow the stack), reading+ /// each tombstoned child's captured own usage first and falling back+ /// to the transcript's own-usage fold (the resumable+ /// `read_session_info` scan) for legacy tombstones that predate the+ /// capture - a path with neither a snapshot nor a readable transcript+ /// is the documented historical gap (no fabricated backfill: zero,+ /// and a zero entry is dropped).+ ///+ /// # Errors+ ///+ /// Returns an error when a deleted child's file cannot be stat'ed or a+ /// prior panic poisoned the deleted-usage cache.+ fn deleted_children_of(&self, state: &ReplayState) -> Result<DeletedChildrenByParent> {let inputs = state.edges.iter()@@ -509,14 +635,14 @@ impl RlmSpawnLedger {.lock().map_err(|_| anyhow::anyhow!("deleted bucket lock poisoned"))?;if let Some(bucket) = cached.as_ref().filter(|bucket| bucket.inputs == inputs) {- return Ok(bucket.usage.clone());+ return Ok(bucket.children.clone());}- let usage = self.fold_deleted_descendant_usage(&state.edges);+ let children = self.fold_deleted_children(&state.edges);*cached = Some(DeletedBucket {inputs,- usage: usage.clone(),+ children: children.clone(),});- Ok(usage)+ Ok(children)}/// Seed and replay the ledger ahead of its first reader; a failed@@ -599,11 +725,8 @@ impl RlmSpawnLedger {Ok(edges)}- fn fold_deleted_descendant_usage(- &self,- edges: &[RlmLedgerEdge],- ) -> HashMap<String, crate::session_usage::SessionUsageSummary> {- use crate::session_usage::SessionUsageSummary;+ fn fold_deleted_children(&self, edges: &[RlmLedgerEdge]) -> DeletedChildrenByParent {+ use crate::session_usage::{ModelUsageSummary, SessionUsageSummary};let canonical = |path: &str| {canonical_session_path(Path::new(path)).to_string_lossy()@@ -618,13 +741,13 @@ impl RlmSpawnLedger {// First writer wins per path: the earliest tombstoned edge claims// the child (and its snapshot) for its parent.let mut children_by_parent: HashMap<String, Vec<String>> = HashMap::new();- let mut snapshot_by_path: HashMap<String, Option<SessionUsageSummary>> = HashMap::new();+ let mut edge_by_path: HashMap<String, &RlmLedgerEdge> = HashMap::new();for edge in edges {if edge.deleted.is_none() {continue;}let child = canonical(&edge.child);- if live_paths.contains(&child) || snapshot_by_path.contains_key(&child) {+ if live_paths.contains(&child) || edge_by_path.contains_key(&child) {continue;}// A tombstoned path that still has a catalog row bills@@ -643,35 +766,36 @@ impl RlmSpawnLedger {continue;}let parent = canonical(&edge.parent);- snapshot_by_path.insert(child.clone(), edge.deleted_usage.clone());+ edge_by_path.insert(child.clone(), edge);children_by_parent.entry(parent).or_default().push(child);}- let zero = || SessionUsageSummary {- input_tokens: 0,- output_tokens: 0,- cost: 0.0,- };- let add = |mut left: SessionUsageSummary, right: SessionUsageSummary| {- // Saturating: the bucket feeds billable rollups — a huge- // snapshot must not panic or wrap to an underbill in release.- left.input_tokens = left.input_tokens.saturating_add(right.input_tokens);- left.output_tokens = left.output_tokens.saturating_add(right.output_tokens);- left.cost += right.cost;- left- };- let tombstone_usage = |path: &str| -> SessionUsageSummary {- match snapshot_by_path.get(path).cloned().flatten() {- Some(snapshot) => snapshot,- // The legacy fallback is the same own-usage fold, read- // through the resumable scan: a repeat bucket fold on a- // surviving legacy transcript is one stat per child.- None => crate::session_store::read_session_info(Path::new(path))- .and_then(|info| info.usage)- .unwrap_or_else(zero),- }- };+ // A path's own spend and its per-model split.+ let tombstone_usage =+ |path: &str| -> (SessionUsageSummary, Option<Vec<ModelUsageSummary>>) {+ let edge = edge_by_path.get(path);+ match edge.and_then(|edge| edge.deleted_usage.clone()) {+ Some(snapshot) => (+ snapshot,+ edge.and_then(|edge| edge.deleted_usage_by_model.clone()),+ ),+ // The legacy fallback is the same own-usage fold, read+ // through the resumable scan: a repeat bucket fold on a+ // surviving legacy transcript is one stat per child. It has+ // no split (a per-model read would reparse the transcript on+ // every fold); the historical gap bills zero, which needs none.+ None => match crate::session_store::read_session_info(Path::new(path))+ .and_then(|info| info.usage)+ {+ Some(usage) => (usage, None),+ None => (zero_usage(), Some(Vec::new())),+ },+ }+ };// Iterative post-order fold with per-path memoization.- let mut contribution: HashMap<String, SessionUsageSummary> = HashMap::new();+ let mut contribution: HashMap<+ String,+ (SessionUsageSummary, Option<Vec<ModelUsageSummary>>),+ > = HashMap::new();let mut on_stack: HashSet<String> = HashSet::new();for children in children_by_parent.values() {for root in children {@@ -707,33 +831,46 @@ impl RlmSpawnLedger {}stack.pop();on_stack.remove(¤t);- let mut total = tombstone_usage(¤t);+ let (mut total, mut by_model) = tombstone_usage(¤t);for descendant in children_by_parent.get(¤t).map(Vec::as_slice).unwrap_or_default(){- if let Some(folded) = contribution.get(descendant) {- total = add(total, folded.clone());+ if let Some((folded, folded_by_model)) = contribution.get(descendant) {+ total = add_usage(total, folded);+ by_model = add_usage_by_model(by_model, folded_by_model.as_ref());}}- contribution.insert(current, total);+ contribution.insert(current, (total, by_model));}}}- let mut usage_by_parent: HashMap<String, SessionUsageSummary> = HashMap::new();+ let mut deleted_by_parent: DeletedChildrenByParent = HashMap::new();for (parent, children) in &children_by_parent {- let mut total = zero();- for child in children {- if let Some(folded) = contribution.get(child) {- total = add(total, folded.clone());- }- }- if total.input_tokens > 0 || total.output_tokens > 0 || total.cost > 0.0 {- usage_by_parent.insert(parent.clone(), total);+ let billed: Vec<DeletedChildUsage> = children+ .iter()+ .filter_map(|child| {+ let (usage, by_model) = contribution.get(child)?.clone();+ if usage.input_tokens == 0 && usage.output_tokens == 0 && usage.cost <= 0.0 {+ return None;+ }+ let edge = edge_by_path.get(child)?;+ Some(DeletedChildUsage {+ child_id: edge.child_id.clone(),+ child_file: child.clone(),+ name: edge.name.clone(),+ factory: edge.factory.clone(),+ usage,+ by_model,+ })+ })+ .collect();+ if !billed.is_empty() {+ deleted_by_parent.insert(parent.clone(), billed);}}- usage_by_parent+ deleted_by_parent}/// Replay edges without liveness reconciliation. Deleted edges arediff --git a/crates/pa-daemon/src/rlm_ledger/replay.rs b/crates/pa-daemon/src/rlm_ledger/replay.rsindex 7cc2409943..bf82ce6602 100644--- a/crates/pa-daemon/src/rlm_ledger/replay.rs+++ b/crates/pa-daemon/src/rlm_ledger/replay.rs@@ -18,6 +18,7 @@ pub(super) enum LedgerRecord {child: String,depth: u32,name: String,+ factory: Option<super::RlmFactoryTag>,},Rename {child_id: String,@@ -29,6 +30,7 @@ pub(super) enum LedgerRecord {child: String,reason: RlmLedgerDeleteReason,usage: Option<crate::session_usage::SessionUsageSummary>,+ usage_by_model: Option<Vec<crate::session_usage::ModelUsageSummary>>,},}@@ -103,12 +105,18 @@ pub(super) fn parse_ledger_line(line: &str, index: usize) -> Result<Option<Ledgeif depth < 1 || depth > u64::from(u32::MAX) {bail!("malformed RLM ledger line {line_no}: invalid spawn record");}+ // The optional run tag: a malformed one reads as untagged, so+ // the edge itself survives.+ let factory = record+ .get("factory")+ .and_then(|factory| serde_json::from_value(factory.clone()).ok());Ok(Some(LedgerRecord::Spawn {child_id,parent,child,depth: depth as u32,name,+ factory,}))}"rename" => {@@ -140,11 +148,18 @@ pub(super) fn parse_ledger_line(line: &str, index: usize) -> Result<Option<LedgeNone => None,Some(usage) => Some(parse_deleted_usage(usage, line_no)?),};+ // The snapshot's optional per-model split: a malformed one reads+ // as unsplit, so the billed snapshot itself survives.+ let usage_by_model = record+ .get("usage")+ .and_then(|usage| usage.get("byModel"))+ .and_then(|by_model| serde_json::from_value(by_model.clone()).ok());Ok(Some(LedgerRecord::Delete {child_id,child,reason,usage,+ usage_by_model,}))}_ => Ok(None),@@ -168,7 +183,7 @@ pub(super) struct ReplayState {#[derive(Debug)]pub(super) struct DeletedBucket {pub(super) inputs: Vec<Option<FileIdentity>>,- pub(super) usage: HashMap<String, crate::session_usage::SessionUsageSummary>,+ pub(super) children: super::DeletedChildrenByParent,}pub(super) fn edge_key(child_id: &str, child: &str) -> String {diff --git a/crates/pa-daemon/src/rlm_ledger/tests.rs b/crates/pa-daemon/src/rlm_ledger/tests.rsindex 13871b0caa..8b3f865165 100644--- a/crates/pa-daemon/src/rlm_ledger/tests.rs+++ b/crates/pa-daemon/src/rlm_ledger/tests.rs@@ -90,6 +90,7 @@ fn spawn_rename_delete_replay_in_order() {child: child.to_string_lossy().into(),depth: 1,name: "worker".into(),+ factory: None,}).unwrap();ledger@@ -131,6 +132,7 @@ fn edge_is_live_reflects_tombstones_and_files() {child: child_path.clone(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();assert!(ledger.edge_is_live("sub-1", &child_path));@@ -155,6 +157,7 @@ fn edge_is_live_reflects_tombstones_and_files() {child: other_path,depth: 1,name: "w2".into(),+ factory: None,}).unwrap();ledger@@ -195,6 +198,7 @@ fn edge_is_live_revalidates_paths_without_a_ledger_append() {child: path.to_string_lossy().into_owned(),depth: 1,name: "child".into(),+ factory: None,}).unwrap();}@@ -258,6 +262,7 @@ fn a_respawned_child_id_on_a_new_path_is_live_and_the_old_one_is_not() {child: child.to_string_lossy().into_owned(),depth: 1,name: name.into(),+ factory: None,}).unwrap();};@@ -288,6 +293,7 @@ fn dead_child_or_parent_drops_from_live_edges() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();assert_eq!(ledger.live_edges().unwrap().len(), 1);@@ -325,6 +331,7 @@ fn moved_edge_paths_resolve_through_the_session_id() {child: recorded_child.into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();@@ -380,6 +387,7 @@ fn the_artifact_index_updates_after_a_new_partition() {child: child.into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();};@@ -439,6 +447,7 @@ fn live_edges_of_parent_bounds_the_liveness_work() {child: "/gone-root/sess-a.jsonl".into(),depth: 1,name: "a".into(),+ factory: None,}).unwrap();ledger@@ -448,6 +457,7 @@ fn live_edges_of_parent_bounds_the_liveness_work() {child: resident_child.to_string_lossy().into(),depth: 1,name: "b".into(),+ factory: None,}).unwrap();let deleted_child = sessions_dir.join("sess-d.jsonl");@@ -459,6 +469,7 @@ fn live_edges_of_parent_bounds_the_liveness_work() {child: deleted_child.to_string_lossy().into(),depth: 1,name: "d".into(),+ factory: None,}).unwrap();ledger@@ -476,6 +487,7 @@ fn live_edges_of_parent_bounds_the_liveness_work() {child: format!("/gone-root/sess-f{n}-child.jsonl"),depth: 1,name: format!("f{n}"),+ factory: None,}).unwrap();}@@ -536,6 +548,7 @@ fn a_parent_left_in_the_archive_dir_is_a_dead_endpoint_walked_once() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();let scans = replay::ARTIFACT_SCANS.with(std::cell::Cell::get);@@ -567,6 +580,7 @@ fn live_edges_of_parent_follows_a_moved_parent() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();let edges = ledger.live_edges_of_parent(&live_parent).unwrap();@@ -594,6 +608,7 @@ fn live_edges_of_parent_follows_a_moved_parent() {child: sessions_dir.join("sess-c2.jsonl").to_string_lossy().into(),depth: 1,name: "w2".into(),+ factory: None,}).unwrap();let edges = ledger.live_edges_of_parent(&elsewhere).unwrap();@@ -618,6 +633,7 @@ fn duplicate_child_path_and_bad_spawn_inputs_fail_but_bad_lines_skip() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();let duplicate = ledger.append_spawn(&RlmSpawnInput {@@ -626,6 +642,7 @@ fn duplicate_child_path_and_bad_spawn_inputs_fail_but_bad_lines_skip() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,});assert!(duplicate.is_err());let depth_zero = ledger.append_spawn(&RlmSpawnInput {@@ -634,6 +651,7 @@ fn duplicate_child_path_and_bad_spawn_inputs_fail_but_bad_lines_skip() {child: child.to_string_lossy().into(),depth: 0,name: "w".into(),+ factory: None,});assert!(depth_zero.is_err());// A torn tail or bad line costs that record only; later appends still land.@@ -648,6 +666,7 @@ fn duplicate_child_path_and_bad_spawn_inputs_fail_but_bad_lines_skip() {child: dir.join("c4.jsonl").to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();let edges = ledger.edges(false).unwrap();@@ -824,6 +843,7 @@ fn delete_amendment_carries_the_usage_snapshot() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();ledger@@ -845,6 +865,7 @@ fn delete_amendment_carries_the_usage_snapshot() {&child.to_string_lossy(),RlmLedgerDeleteReason::User,&usage_summary(0.40),+ None,).unwrap();let edges = ledger.edges(true).unwrap();@@ -869,6 +890,7 @@ fn delete_amendment_carries_the_usage_snapshot() {&child.to_string_lossy(),RlmLedgerDeleteReason::User,&usage_summary(0.45),+ None,).unwrap();assert_eq!(@@ -894,6 +916,7 @@ fn append_delete_with_usage_sanitizes_a_rejectable_cost() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();for bad_cost in [-0.40, -0.0, f64::NAN, f64::INFINITY] {@@ -903,6 +926,7 @@ fn append_delete_with_usage_sanitizes_a_rejectable_cost() {&child.to_string_lossy(),RlmLedgerDeleteReason::User,&usage_summary(bad_cost),+ None,).unwrap();let edges = ledger.edges(true).expect("the ledger must stay readable");@@ -917,6 +941,7 @@ fn append_delete_with_usage_sanitizes_a_rejectable_cost() {&child.to_string_lossy(),RlmLedgerDeleteReason::User,&usage_summary(0.40),+ None,).unwrap();assert_eq!(@@ -941,6 +966,7 @@ fn tombstone_child_path_with_usage_snapshots_every_edge() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();ledger@@ -956,6 +982,7 @@ fn tombstone_child_path_with_usage_snapshots_every_edge() {&child.to_string_lossy(),RlmLedgerDeleteReason::User,Some(&usage_summary(0.30)),+ None,).unwrap();assert_eq!(edges.len(), 2);@@ -996,6 +1023,7 @@ fn bucket_folds_own_snapshots_post_order_without_double_counting() {child: child.to_string_lossy().into(),depth,name: "w".into(),+ factory: None,}).unwrap();};@@ -1012,6 +1040,7 @@ fn bucket_folds_own_snapshots_post_order_without_double_counting() {&child_1.to_string_lossy(),RlmLedgerDeleteReason::User,&usage_summary(0.40),+ None,).unwrap();ledger@@ -1020,6 +1049,7 @@ fn bucket_folds_own_snapshots_post_order_without_double_counting() {&grandchild_1.to_string_lossy(),RlmLedgerDeleteReason::User,&usage_summary(0.10),+ None,).unwrap();// The tombstoned children's transcripts are gone (a transcript@@ -1089,6 +1119,7 @@ fn bucket_legacy_tombstones_fall_back_then_gap_to_zero() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();ledger@@ -1190,6 +1221,7 @@ fn bucket_bills_tombstoned_children_without_catalog_rows() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();};@@ -1202,6 +1234,7 @@ fn bucket_bills_tombstoned_children_without_catalog_rows() {&snapshot_child.to_string_lossy(),RlmLedgerDeleteReason::User,&usage_summary(0.30),+ None,).unwrap();ledger@@ -1322,6 +1355,7 @@ fn bucket_skips_recreated_live_paths() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();ledger@@ -1330,6 +1364,7 @@ fn bucket_skips_recreated_live_paths() {&child.to_string_lossy(),RlmLedgerDeleteReason::User,&usage_summary(0.20),+ None,).unwrap();ledger@@ -1339,6 +1374,7 @@ fn bucket_skips_recreated_live_paths() {child: child.to_string_lossy().into(),depth: 1,name: "w2".into(),+ factory: None,}).unwrap();let bucket = ledger.deleted_descendant_usage_by_parent().unwrap();@@ -1368,6 +1404,7 @@ fn the_bucket_updates_after_an_append_on_the_same_ledger() {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();ledger@@ -1376,6 +1413,7 @@ fn the_bucket_updates_after_an_append_on_the_same_ledger() {&child.to_string_lossy(),RlmLedgerDeleteReason::User,&usage_summary(cost),+ None,).unwrap();fs::remove_file(child).unwrap();@@ -1420,6 +1458,7 @@ fn a_restored_tombstoned_child_stops_billing_the_parent_without_an_append() {child: child.to_string_lossy().into(),depth: 1,name: "child".into(),+ factory: None,}).unwrap();ledger@@ -1428,6 +1467,7 @@ fn a_restored_tombstoned_child_stops_billing_the_parent_without_an_append() {&child.to_string_lossy(),RlmLedgerDeleteReason::User,&usage_summary(0.25),+ None,).unwrap();let archive = dir.join("sessions-archive");@@ -1466,6 +1506,7 @@ fn the_artifact_index_rechecks_deleted_and_relocated_transcripts_without_an_appechild: "/gone/child.jsonl".into(),depth: 1,name: "child".into(),+ factory: None,}).unwrap();let initial = ledger.live_edges().unwrap();@@ -1499,6 +1540,7 @@ fn artifact_misses_stay_cached_until_a_directory_changes() {child: "/gone/child.jsonl".into(),depth: 1,name: "child".into(),+ factory: None,}).unwrap();let scans = replay::ARTIFACT_SCANS.with(std::cell::Cell::get);@@ -1515,6 +1557,8 @@ fn artifact_misses_stay_cached_until_a_directory_changes() {name: "child".into(),deleted: None,deleted_usage: None,+ deleted_usage_by_model: None,+ factory: None,}];assert_eq!(ledger.live_edges().unwrap(), expected);assert_eq!(ledger.live_edges().unwrap(), expected);@@ -1539,6 +1583,7 @@ fn family_edges_track_restore_and_relocation_without_a_ledger_append() {child: child.to_string_lossy().into(),depth: 1,name: "child".into(),+ factory: None,}).unwrap();let family_children = || -> Vec<PathBuf> {@@ -1584,6 +1629,7 @@ fn family_edges_recheck_symlink_targets_without_a_ledger_append() {child: child.to_string_lossy().into(),depth: 1,name: child_id.into(),+ factory: None,}).unwrap();}diff --git a/crates/pa-daemon/src/rlm_roster.rs b/crates/pa-daemon/src/rlm_roster.rsindex 720ef64602..c944c049ca 100644--- a/crates/pa-daemon/src/rlm_roster.rs+++ b/crates/pa-daemon/src/rlm_roster.rs@@ -264,6 +264,8 @@ mod tests {name: "worker-a".to_string(),deleted: None,deleted_usage: None,+ deleted_usage_by_model: None,+ factory: None,},info,metadata: RlmChildMetadata::default(),@@ -285,6 +287,8 @@ mod tests {name: "worker-b".to_string(),deleted: None,deleted_usage: None,+ deleted_usage_by_model: None,+ factory: None,},info: plain_info,metadata: RlmChildMetadata::default(),@@ -319,6 +323,8 @@ mod tests {name: "worker-c".to_string(),deleted: None,deleted_usage: None,+ deleted_usage_by_model: None,+ factory: None,},info,metadata: RlmChildMetadata::default(),@@ -365,6 +371,7 @@ mod tests {child: child.to_string_lossy().into(),depth: 1,name: "w1".into(),+ factory: None,}).unwrap();ledger@@ -374,6 +381,7 @@ mod tests {child: grandchild.to_string_lossy().into(),depth: 2,name: "w2".into(),+ factory: None,}).unwrap();ledger@@ -383,6 +391,7 @@ mod tests {child: dead.to_string_lossy().into(),depth: 1,name: "gone".into(),+ factory: None,}).unwrap();// A deleted child tombstones out of the walk.@@ -456,6 +465,7 @@ mod tests {child: child.to_string_lossy().into(),depth: 1,name: "worker".into(),+ factory: None,}).unwrap();let walked = walk_passive_rlm_children(diff --git a/crates/pa-daemon/src/saved_session_commands.rs b/crates/pa-daemon/src/saved_session_commands.rsindex eee1ad4495..445d549489 100644--- a/crates/pa-daemon/src/saved_session_commands.rs+++ b/crates/pa-daemon/src/saved_session_commands.rs@@ -170,6 +170,8 @@ pub(crate) enum SavedDeleteCapture {TopLevel,Child {usage: Option<crate::session_usage::SessionUsageSummary>,+ /// `usage` split by model (`None` when it does not reconcile).+ by_model: Option<Vec<crate::session_usage::ModelUsageSummary>>,/// The canonical session key captured while the file still existed:/// a symlink delete unlinks the LINK, so the tombstone uses the pre-unlink key.canonical_path: String,@@ -206,8 +208,12 @@ pub(crate) fn capture_saved_session_delete(} else {None};+ let by_model = usage.as_ref().and_then(|usage| {+ crate::state_getters::own_usage_by_model_of(Path::new(session_path), usage)+ });SavedDeleteCapture::Child {usage,+ by_model,canonical_path,}}@@ -221,6 +227,7 @@ pub(crate) fn tombstone_saved_session_delete_captured() -> usize {let SavedDeleteCapture::Child {usage,+ by_model,canonical_path,} = captureelse {@@ -231,6 +238,7 @@ pub(crate) fn tombstone_saved_session_delete_captured(canonical_path,crate::rlm_ledger::RlmLedgerDeleteReason::User,usage.as_ref(),+ by_model.as_deref(),) {// The returned edges are the pre-append replay state: every// matching edge received the snapshot when one was captured.@@ -1015,6 +1023,7 @@ mod tombstone_usage_tests {child: child.to_string_lossy().to_string(),depth: 1,name: "lane".to_string(),+ factory: None,}).unwrap();let captured = tombstone_saved_session_delete(@@ -1086,6 +1095,7 @@ mod tombstone_usage_tests {child: child.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();// The delete goes through a final-component symlink: the capture@@ -1132,6 +1142,7 @@ mod tombstone_usage_tests {child: fifo.to_string_lossy().into(),depth: 1,name: "w".into(),+ factory: None,}).unwrap();let capture = capture_saved_session_delete(&fifo.to_string_lossy(), None);@@ -1139,6 +1150,7 @@ mod tombstone_usage_tests {SavedDeleteCapture::Child {usage,canonical_path,+ ..} => {assert!(usage.is_none(),diff --git a/crates/pa-daemon/src/session_usage.rs b/crates/pa-daemon/src/session_usage.rsindex 32bbff1a77..9a562b0a7a 100644--- a/crates/pa-daemon/src/session_usage.rs+++ b/crates/pa-daemon/src/session_usage.rs@@ -28,6 +28,20 @@ pub struct SessionUsageSummary {impl Eq for SessionUsageSummary {}+/// One model's share of a session's own usage, with the cache split the+/// summary folds away (the deleted-child capture's per-model snapshot).+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ModelUsageSummary {+ pub provider: String,+ pub id: String,+ pub input: u64,+ pub output: u64,+ pub cache_read: u64,+ pub cache_write: u64,+ pub cost: f64,+}+/// `None` (absent wire field) when the session recorded no billable work at all.#[must_use]pub fn session_usage_summary_from(usage: &Usage) -> Option<SessionUsageSummary> {diff --git a/crates/pa-daemon/src/state_getters.rs b/crates/pa-daemon/src/state_getters.rsindex fd85938251..183c5cb9be 100644--- a/crates/pa-daemon/src/state_getters.rs+++ b/crates/pa-daemon/src/state_getters.rs@@ -57,7 +57,8 @@ impl Worker {/// `get_context_tree`: the root is the session itself (usage totals over/// the persisted branch, ghost-parent gaps bridged); the children are the/// live RLM roster plus every persisted child dir (tombstoned ids stay- /// hidden). The disk walk runs in the background cache refresh: this path+ /// hidden; their spend rides `deleted` rows from the ledger's+ /// deleted-spend fold). The disk walk runs in the background cache refresh: this path/// serves the cached walk with fresh live identity overlaid (usage lags;/// a child's status never lags).pub(crate) async fn handle_get_context_tree(&self) -> DaemonResponse {@@ -285,7 +286,8 @@ impl Worker {mod usage;pub(crate) use usage::{- compute_own_and_total_usage, compute_own_usage_by_model, empty_usage, worker_model_registry,+ compute_own_and_total_usage, compute_own_usage_by_model, empty_usage, own_usage_by_model_of,+ worker_model_registry,};// The getter battery lives in state_getters::state_getters_tests.diff --git a/crates/pa-daemon/src/state_getters/state_getters_tests.rs b/crates/pa-daemon/src/state_getters/state_getters_tests.rsindex 57f8c2cfba..6ef1512ff3 100644--- a/crates/pa-daemon/src/state_getters/state_getters_tests.rs+++ b/crates/pa-daemon/src/state_getters/state_getters_tests.rs@@ -507,6 +507,7 @@ async fn get_context_tree_lists_persisted_children() {child: deleted_dir.display().to_string(),depth: 1,name: "deleted-child".to_string(),+ factory: None,}).unwrap();ledgerdiff --git a/crates/pa-daemon/src/state_getters/usage.rs b/crates/pa-daemon/src/state_getters/usage.rsindex ddd008521e..583ddef956 100644--- a/crates/pa-daemon/src/state_getters/usage.rs+++ b/crates/pa-daemon/src/state_getters/usage.rs@@ -286,6 +286,53 @@ pub(crate) fn compute_own_usage_by_model()}+/// A transcript's own usage split by model: the same branch fold `/context`+/// renders for a live child, kept only when it reconciles with `summary`+/// (the whole-file snapshot a delete bills), so a deleted child's buckets+/// always add up to its billed spend. `None` when the file is unreadable,+/// a usage row resolves to no model, or the two folds disagree (a+/// branched transcript).+pub(crate) fn own_usage_by_model_of(+ path: &std::path::Path,+ summary: &crate::session_usage::SessionUsageSummary,+) -> Option<Vec<crate::session_usage::ModelUsageSummary>> {+ let store = crate::session_store::SessionFile::open(path).ok()?;+ let branch = store.branch_bridged();+ let (own_usage, _) = compute_own_and_total_usage(&branch, store.entries());+ let buckets = compute_own_usage_by_model(+ &branch,+ store.entries(),+ &own_usage,+ store.window_boundary_model().as_ref(),+ )?;+ let tokens = |usage: &Value, field: &str| usage[field].as_u64().unwrap_or_default();+ let by_model: Vec<crate::session_usage::ModelUsageSummary> = buckets+ .iter()+ .map(|bucket| {+ let usage = &bucket["ownUsage"];+ crate::session_usage::ModelUsageSummary {+ provider: bucket["provider"].as_str().unwrap_or_default().to_string(),+ id: bucket["id"].as_str().unwrap_or_default().to_string(),+ input: tokens(usage, "input"),+ output: tokens(usage, "output"),+ cache_read: tokens(usage, "cacheRead"),+ cache_write: tokens(usage, "cacheWrite"),+ cost: usage["cost"]["total"].as_f64().unwrap_or_default(),+ }+ })+ .collect();+ let input: u64 = by_model+ .iter()+ .map(|model| model.input + model.cache_read + model.cache_write)+ .sum();+ let output: u64 = by_model.iter().map(|model| model.output).sum();+ let cost: f64 = by_model.iter().map(|model| model.cost).sum();+ let reconciles = input == summary.input_tokens+ && output == summary.output_tokens+ && (cost - summary.cost).abs() <= 1e-9 * (1.0 + cost.max(summary.cost));+ reconciles.then_some(by_model)+}+#[cfg(test)]mod usage_tests {use super::*;diff --git a/crates/pa-daemon/src/stop_cleanup.rs b/crates/pa-daemon/src/stop_cleanup.rsindex eecef76fdf..041d254e0b 100644--- a/crates/pa-daemon/src/stop_cleanup.rs+++ b/crates/pa-daemon/src/stop_cleanup.rs@@ -200,6 +200,9 @@ pub(crate) fn append_deleted_child_usage_amendments(}let summary = crate::session_usage::read_session_usage(&path).and_then(|totals| crate::session_usage::session_usage_summary_from(&totals.own));+ let by_model = summary+ .as_ref()+ .and_then(|summary| crate::state_getters::own_usage_by_model_of(&path, summary));let mut captured = 0usize;for edge in &tombstoned {let Some(reason) = edge.deleted else {@@ -211,7 +214,13 @@ pub(crate) fn append_deleted_child_usage_amendments(continue;};if ledger- .append_delete_with_usage(&edge.child_id, &edge.child, reason, summary)+ .append_delete_with_usage(+ &edge.child_id,+ &edge.child,+ reason,+ summary,+ by_model.as_deref(),+ ).is_err(){continue;@@ -546,6 +555,7 @@ mod tests {child: child_file.to_string_lossy().to_string(),depth: 1,name: "lane".to_string(),+ factory: None,}).unwrap();ledger@@ -555,6 +565,7 @@ mod tests {child: moved_at.to_string_lossy().to_string(),depth: 1,name: "moved".to_string(),+ factory: None,}).unwrap();@@ -623,6 +634,7 @@ mod tests {child: child_file.to_string_lossy().to_string(),depth: 1,name: "lane".to_string(),+ factory: None,}).unwrap();// The tombstone lands before the kill (the revival window); the@@ -710,6 +722,7 @@ mod tests {child: child_file.to_string_lossy().to_string(),depth: 1,name: "lane".to_string(),+ factory: None,}).unwrap();ledger@@ -785,6 +798,7 @@ mod tests {child: child_file.to_string_lossy().to_string(),depth: 1,name: "lane".to_string(),+ factory: None,}).unwrap();// Still live: no capture (kill-failure retryability — the child@@ -817,6 +831,7 @@ mod tests {child: child_file.to_string_lossy().to_string(),depth: 1,name: "lane".to_string(),+ factory: None,}).unwrap();ledgerdiff --git a/crates/pa-daemon/src/supervisor/adoption.rs b/crates/pa-daemon/src/supervisor/adoption.rsindex e0f776b3f5..aff1f447c4 100644--- a/crates/pa-daemon/src/supervisor/adoption.rs+++ b/crates/pa-daemon/src/supervisor/adoption.rs@@ -778,6 +778,9 @@ impl Supervisor {child: child.to_string(),depth,name: session_name.clone(),+ factory: metadata+ .get("factory")+ .and_then(|factory| serde_json::from_value(factory.clone()).ok()),}).inspect_err(|error| {self.log_line(&format!("failed to append RLM ledger spawn: {error:#}"));diff --git a/crates/pa-daemon/src/supervisor/dead_child_delete_tests.rs b/crates/pa-daemon/src/supervisor/dead_child_delete_tests.rsindex c009542928..4ef2cf3a9b 100644--- a/crates/pa-daemon/src/supervisor/dead_child_delete_tests.rs+++ b/crates/pa-daemon/src/supervisor/dead_child_delete_tests.rs@@ -43,6 +43,7 @@ async fn fixture() -> Fixture {child: child_file.clone(),depth: 1,name: "dead-worker".to_string(),+ factory: None,}).expect("the spawn edge appends");Fixture {diff --git a/crates/pa-daemon/src/supervisor/tests.rs b/crates/pa-daemon/src/supervisor/tests.rsindex e35a5eb684..cd500ed44a 100644--- a/crates/pa-daemon/src/supervisor/tests.rs+++ b/crates/pa-daemon/src/supervisor/tests.rs@@ -1071,6 +1071,7 @@ async fn adoption_settles_then_seeds_the_roster_once() {child: child_file.to_string_lossy().to_string(),depth: 1,name: "lane".to_string(),+ factory: None,}).unwrap();let descriptor = pa_types::daemon::DaemonWorkerDescriptor {@@ -1977,6 +1978,7 @@ async fn a_ledger_delete_of_a_stopped_child_tombstones_without_a_worker() {child: child_file.to_string_lossy().into_owned(),depth: 1,name: "parked-worker".to_string(),+ factory: None,}).expect("the spawn edge appends");assert_eq!(ledger.live_edges().expect("edges").len(), 1);@@ -2140,6 +2142,7 @@ async fn the_stopped_childs_delete_removes_its_row_and_bills_the_parent() {child: child_transcript.to_string_lossy().into_owned(),depth: 1,name: "parked-worker".to_string(),+ factory: None,}).expect("the spawn edge appends");let mut events = supervisor.events.subscribe();@@ -2251,6 +2254,7 @@ async fn a_ledger_delete_never_tombstones_an_unrelated_edge_sharing_the_child_idchild: child.clone(),depth: 1,name: stem.to_string(),+ factory: None,}).expect("the spawn edge appends");}@@ -2320,6 +2324,7 @@ async fn a_ledger_child_wake_joins_an_already_hosting_resident() {child: session_file.to_string_lossy().into_owned(),depth: 1,name: "kid-1".to_string(),+ factory: None,}).expect("the spawn edge appends");// The concurrent revival's resident already hosting the child's file.diff --git a/crates/pa-daemon/src/supervisor_roster_seed.rs b/crates/pa-daemon/src/supervisor_roster_seed.rsindex ef9fa19bed..7f3acdb33e 100644--- a/crates/pa-daemon/src/supervisor_roster_seed.rs+++ b/crates/pa-daemon/src/supervisor_roster_seed.rs@@ -476,6 +476,8 @@ pub(crate) mod tests {name: name.to_string(),deleted: None,deleted_usage: None,+ deleted_usage_by_model: None,+ factory: None,}}@@ -647,6 +649,7 @@ pub(crate) mod tests {child: child.to_string_lossy().to_string(),depth: 1,name: "lane".to_string(),+ factory: None,}).expect("append spawn");}@@ -951,6 +954,8 @@ pub(crate) mod tests {name: "w9".to_string(),deleted: None,deleted_usage: None,+ deleted_usage_by_model: None,+ factory: None,},);roster.write_seeded(candidate.summary, candidate.seeded_cwd)@@ -1101,6 +1106,7 @@ pub(crate) mod tests {child: gone_child.to_string_lossy().to_string(),depth: 1,name: "gone".to_string(),+ factory: None,}).expect("append spawn");ledger@@ -1113,6 +1119,7 @@ pub(crate) mod tests {output_tokens: 7,cost: 0.5,},+ /*by_model*/ None,).expect("append delete");let mut events = supervisor.events.subscribe();diff --git a/crates/pa-daemon/src/update_roster.rs b/crates/pa-daemon/src/update_roster.rsindex 7aac6aa033..5e1f50fb76 100644--- a/crates/pa-daemon/src/update_roster.rs+++ b/crates/pa-daemon/src/update_roster.rs@@ -493,6 +493,7 @@ mod tests {child_id: "child-c1".into(),depth: 1,name: "api-reviewer".into(),+ factory: None,}).unwrap();(ledger, sessions_dir)diff --git a/crates/pa-daemon/tests/agent_family_e2e.rs b/crates/pa-daemon/tests/agent_family_e2e.rsindex ee82cd0fd1..28196cc60f 100644--- a/crates/pa-daemon/tests/agent_family_e2e.rs+++ b/crates/pa-daemon/tests/agent_family_e2e.rs@@ -424,6 +424,7 @@ async fn parent_child_agent_message_round_trip_end_to_end() {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}).await.expect("spawn the child");@@ -753,6 +754,7 @@ async fn family_edges_never_cross_families_end_to_end() {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}).await.expect("spawn the child");@@ -893,6 +895,7 @@ async fn family_edges_never_cross_families_end_to_end() {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}).await.expect("spawn the grandchild");@@ -1211,6 +1214,7 @@ async fn parent_renames_a_child_end_to_end() {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}).await.expect("spawn the child");diff --git a/crates/pa-daemon/tests/agents_view_roster_e2e.rs b/crates/pa-daemon/tests/agents_view_roster_e2e.rsindex db1feca132..0e10c0d089 100644--- a/crates/pa-daemon/tests/agents_view_roster_e2e.rs+++ b/crates/pa-daemon/tests/agents_view_roster_e2e.rs@@ -425,6 +425,7 @@ async fn rlm_children_key_the_roster_by_parent_path_and_child_id() {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}).await.expect("spawn child");diff --git a/crates/pa-daemon/tests/idle_passivation_e2e.rs b/crates/pa-daemon/tests/idle_passivation_e2e.rsindex b5f890afa3..9f2c90353c 100644--- a/crates/pa-daemon/tests/idle_passivation_e2e.rs+++ b/crates/pa-daemon/tests/idle_passivation_e2e.rs@@ -295,6 +295,7 @@ async fn a_settled_child_passivates_stays_listable_and_revives_by_agent_message(model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}).await.expect("spawn the child");@@ -612,6 +613,7 @@ async fn a_parent_rename_after_a_revival_and_second_passivation_reaches_the_chilmodel: None,thinking: None,spawned_by_request_id: None,+ factory: None,}).await.expect("spawn the child");diff --git a/crates/pa-daemon/tests/launch_env_e2e.rs b/crates/pa-daemon/tests/launch_env_e2e.rsindex f1f0b13471..39c56e5481 100644--- a/crates/pa-daemon/tests/launch_env_e2e.rs+++ b/crates/pa-daemon/tests/launch_env_e2e.rs@@ -546,6 +546,7 @@ async fn an_rlm_spawn_child_inherits_the_parent_worker_env() {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}).await.expect("spawn");diff --git a/crates/pa-daemon/tests/rlm_children_e2e.rs b/crates/pa-daemon/tests/rlm_children_e2e.rsindex 614f34b8b6..56cd134a30 100644--- a/crates/pa-daemon/tests/rlm_children_e2e.rs+++ b/crates/pa-daemon/tests/rlm_children_e2e.rs@@ -233,6 +233,7 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}}diff --git a/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rsindex c069e7cafc..b70a0d5347 100644--- a/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs+++ b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs@@ -499,6 +499,7 @@ async fn subscribe_after_spawn_then_shutdown_seeds_the_passive_child() {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}).await.expect("spawn child");diff --git a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rsindex b51f200ce0..785c45e2b0 100644--- a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs+++ b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs@@ -232,6 +232,7 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {model: None,thinking: None,spawned_by_request_id: None,+ factory: None,}}diff --git a/crates/pa-perf/src/corpus/artifacts.rs b/crates/pa-perf/src/corpus/artifacts.rsindex c1c4417fa6..c68ffefc4e 100644--- a/crates/pa-perf/src/corpus/artifacts.rs+++ b/crates/pa-perf/src/corpus/artifacts.rs@@ -217,6 +217,7 @@ pub(crate) fn spawn_child(child: child_file.display().to_string(),depth,name: WORKER_NAMES[rng.below(WORKER_NAMES.len() as u64) as usize].to_string(),+ factory: None,})?;written.push(child_file.clone());if depth < tree.max_depth {diff --git a/crates/pa-tui/src/info_commands/context_tree.rs b/crates/pa-tui/src/info_commands/context_tree.rsindex 96ee67a692..4061f55987 100644--- a/crates/pa-tui/src/info_commands/context_tree.rs+++ b/crates/pa-tui/src/info_commands/context_tree.rs@@ -1,3 +1,4 @@+use std::collections::HashMap;use std::fmt::Write as _;use serde_json::Value;@@ -112,6 +113,10 @@ struct ContextNode {own_usage: UsageTotals,own_usage_by_model: Vec<ModelUsage>,context_usage: Option<ContextUsageSnapshot>,+ /// The factory run that spawned this agent: `(run_id, spec_id)`.+ factory_run: Option<(String, String)>,+ /// A deleted subagent's billing row (the daemon keeps its spend).+ deleted: bool,children: Vec<ContextNode>,}@@ -171,6 +176,12 @@ fn parse_context_node(value: &Value) -> ContextNode {}).unwrap_or_default(),context_usage,+ factory_run: value.get("factory").and_then(|factory| {+ let run_id = factory.get("runId").and_then(Value::as_str)?;+ let spec_id = factory.get("specId").and_then(Value::as_str)?;+ Some((run_id.to_string(), spec_id.to_string()))+ }),+ deleted: value.get("deleted").and_then(Value::as_bool) == Some(true),children: value.get("children").and_then(Value::as_array)@@ -179,39 +190,231 @@ fn parse_context_node(value: &Value) -> ContextNode {}}-/// One flattened tree row: the node and its drawing prefix.+/// A synthetic group row: a factory run's agents, or one parent's deleted+/// agents. Its usage sums the real agent rows under it; the grand totals+/// never read it.+#[derive(Debug, Clone, PartialEq)]+struct GroupRow {+ label: String,+ status: String,+ usage: UsageTotals,+ agents: usize,+ /// The collapse folded its agent rows into it.+ folded: bool,+}++/// What one rendered row shows.+enum RowKind<'a> {+ Agent(&'a ContextNode),+ Group(GroupRow),+}++/// One flattened tree row: an agent or group row and its drawing prefix.struct TreeRow<'a> {- node: &'a ContextNode,+ kind: RowKind<'a>,prefix: String,}-fn flatten_tree(root: &ContextNode) -> Vec<TreeRow<'_>> {- let mut rows = vec![TreeRow {- node: root,- prefix: String::new(),- }];- walk_tree(&root.children, "", &mut rows);- rows+impl TreeRow<'_> {+ fn label(&self) -> String {+ match &self.kind {+ RowKind::Agent(node) => node.label.clone(),+ RowKind::Group(group) if group.folded => format!(+ "{} ({} {})",+ group.label,+ group.agents,+ if group.agents == 1 { "agent" } else { "agents" }+ ),+ RowKind::Group(group) => group.label.clone(),+ }+ }++ fn status(&self) -> &str {+ match &self.kind {+ RowKind::Agent(node) => &node.status,+ RowKind::Group(group) => &group.status,+ }+ }++ fn usage(&self) -> &UsageTotals {+ match &self.kind {+ RowKind::Agent(node) => &node.own_usage,+ RowKind::Group(group) => &group.usage,+ }+ }++ fn node(&self) -> Option<&ContextNode> {+ match &self.kind {+ RowKind::Agent(node) => Some(node),+ RowKind::Group(_) => None,+ }+ }}-fn walk_tree<'a>(children: &'a [ContextNode], ancestors: &str, rows: &mut Vec<TreeRow<'a>>) {- for (index, child) in children.iter().enumerate() {- let is_last = index + 1 == children.len();- let branch = if is_last {- "\u{2514}\u{2500} "- } else {- "\u{251c}\u{2500} "- };- rows.push(TreeRow {- node: child,- prefix: format!("{ancestors}{branch}"),- });- let ancestors = if is_last {- format!("{ancestors} ")- } else {- format!("{ancestors}\u{2502} ")- };- walk_tree(&child.children, &ancestors, rows);+/// One collapse unit: an agent row alone, or a group row followed by every+/// row under it (a run ranks and hides as one).+struct RowUnit<'a> {+ rows: Vec<TreeRow<'a>>,+ usage: UsageTotals,+ agents: usize,+}++/// How a child joins a group row: its factory run first, else its deletion.+#[derive(PartialEq)]+enum GroupKey<'a> {+ Run { run_id: &'a str, spec_id: &'a str },+ Deleted,+}++fn group_key(node: &ContextNode) -> Option<GroupKey<'_>> {+ match &node.factory_run {+ Some((run_id, spec_id)) => Some(GroupKey::Run { run_id, spec_id }),+ None if node.deleted => Some(GroupKey::Deleted),+ None => None,+ }+}++/// One tree level's display items: ungrouped agents in tree order, and each+/// group at its first member's position.+enum TreeItem<'a> {+ Agent(&'a ContextNode),+ Group(GroupKey<'a>, Vec<&'a ContextNode>),+}++fn flatten_tree<'a>(root: &'a ContextNode, run_states: &HashMap<&str, &str>) -> Vec<RowUnit<'a>> {+ let mut units = vec![agent_unit(root, String::new())];+ walk_tree(&root.children, "", run_states, &mut units);+ units+}++fn agent_unit(node: &ContextNode, prefix: String) -> RowUnit<'_> {+ RowUnit {+ rows: vec![TreeRow {+ kind: RowKind::Agent(node),+ prefix,+ }],+ usage: node.own_usage,+ agents: 1,+ }+}++/// The branch glyph for one child and the prefix its own children continue.+fn branch(ancestors: &str, is_last: bool) -> (String, String) {+ if is_last {+ (+ format!("{ancestors}\u{2514}\u{2500} "),+ format!("{ancestors} "),+ )+ } else {+ (+ format!("{ancestors}\u{251c}\u{2500} "),+ format!("{ancestors}\u{2502} "),+ )+ }+}++fn walk_tree<'a>(+ children: &'a [ContextNode],+ ancestors: &str,+ run_states: &HashMap<&str, &str>,+ units: &mut Vec<RowUnit<'a>>,+) {+ let mut items: Vec<TreeItem<'a>> = Vec::new();+ for child in children {+ match group_key(child) {+ None => items.push(TreeItem::Agent(child)),+ Some(key) => {+ let group = items.iter_mut().find_map(|item| match item {+ TreeItem::Group(existing, members) if *existing == key => Some(members),+ _ => None,+ });+ match group {+ Some(members) => members.push(child),+ None => items.push(TreeItem::Group(key, vec![child])),+ }+ }+ }+ }+ let count = items.len();+ for (index, item) in items.into_iter().enumerate() {+ let (prefix, next) = branch(ancestors, index + 1 == count);+ match item {+ TreeItem::Agent(node) => {+ units.push(agent_unit(node, prefix));+ walk_tree(&node.children, &next, run_states, units);+ }+ TreeItem::Group(key, members) => {+ let mut inner = Vec::new();+ for (member_index, member) in members.iter().enumerate() {+ let (member_prefix, member_next) =+ branch(&next, member_index + 1 == members.len());+ inner.push(agent_unit(member, member_prefix));+ walk_tree(&member.children, &member_next, run_states, &mut inner);+ }+ let mut usage = UsageTotals::default();+ let mut agents = 0;+ for row in inner.iter().flat_map(|unit| &unit.rows) {+ if let RowKind::Agent(node) = &row.kind {+ usage.add_fold(&node.own_usage);+ agents += 1;+ }+ }+ let (label, status) = match key {+ GroupKey::Run { run_id, spec_id } => {+ let run6: String = run_id.chars().take(6).collect();+ let status = run_states.get(run_id).map_or_else(+ || derived_run_status(&members),+ |state| run_state_status(state),+ );+ (format!("factory {spec_id} {run6}"), status)+ }+ GroupKey::Deleted => ("deleted agents".to_string(), "deleted"),+ };+ let mut rows = vec![TreeRow {+ kind: RowKind::Group(GroupRow {+ label,+ status: status.to_string(),+ usage,+ agents,+ folded: false,+ }),+ prefix,+ }];+ rows.extend(inner.into_iter().flat_map(|unit| unit.rows));+ units.push(RowUnit {+ rows,+ usage,+ agents,+ });+ }+ }+ }+}++/// A polled factory run state in the status-icon vocabulary.+fn run_state_status(state: &str) -> &str {+ match state {+ "stopping" => "running",+ "failed" => "error",+ "stopped" => "cancelled",+ other => other,+ }+}++/// A run missing from the polled factory graph: running while any agent+/// runs, errored when any errored, else done.+fn derived_run_status(members: &[&ContextNode]) -> &'static str {+ let any = |statuses: &[&str]| {+ members+ .iter()+ .any(|member| statuses.contains(&member.status.as_str()))+ };+ if any(&["running", "active"]) {+ "running"+ } else if any(&["error"]) {+ "error"+ } else {+ "done"}}@@ -322,10 +525,17 @@ fn sum_own_usage(node: &ContextNode, total: &mut UsageTotals) {/// The whole tree's own usage summed per model (the `/context` Cost/// section's breakdown), so a mid-conversation model switch shows each-/// model's share. `None` when a node with billable own usage carries no-/// per-model fold (a foreign file): a partial breakdown would not add up.+/// model's share. A deleted row captured before deletes recorded a split+/// folds into the unknown-model bucket (empty provider and id), so the+/// lines still add up.fn sum_own_usage_by_model(node: &ContextNode, total: &mut Vec<ModelUsage>) {- for bucket in &node.own_usage_by_model {+ let unsplit_deleted =+ (node.deleted && node.own_usage_by_model.is_empty()).then(|| ModelUsage {+ provider: String::new(),+ id: String::new(),+ totals: node.own_usage,+ });+ for bucket in node.own_usage_by_model.iter().chain(&unsplit_deleted) {if let Some(existing) = total.iter_mut().find(|existing| existing.provider == bucket.provider && existing.id == bucket.id)@@ -341,12 +551,15 @@ fn sum_own_usage_by_model(node: &ContextNode, total: &mut Vec<ModelUsage>) {}/// The tree's per-model buckets when they account for every billed row.+/// `None` when a billed live row carries no per-model fold (a foreign+/// file): a partial breakdown would not add up.fn tree_own_usage_by_model(root: &ContextNode) -> Option<Vec<ModelUsage>> {fn billed(node: &ContextNode) -> bool {node.own_usage.spent_tokens() > 0 || node.own_usage.cost_total > 0.0}fn covers(node: &ContextNode) -> bool {- (!billed(node) || !node.own_usage_by_model.is_empty()) && node.children.iter().all(covers)+ (!billed(node) || node.deleted || !node.own_usage_by_model.is_empty())+ && node.children.iter().all(covers)}if !covers(root) {return None;@@ -381,50 +594,77 @@ pub enum ContextTreeScope {/// The `/context` rows (TS `formatContextTree`): the agent tree with own/// token/cost columns and per-agent context utilization, then the grand/// totals. `width` is the TS render width: `clamp(columns - 2, 60, 120)`.-pub fn context_tree_rows(tree: &Value, width: usize, scope: ContextTreeScope) -> Vec<ClientLine> {+/// Children sharing a factory run render under one run row (its state from+/// `factory_runs` when the poll has it), and one parent's deleted agents+/// under one `deleted agents` row; group rows sum their agents and never+/// count toward the grand totals.+pub fn context_tree_rows(+ tree: &Value,+ width: usize,+ scope: ContextTreeScope,+ factory_runs: &[crate::factory_view::FactoryRunSnapshot],+) -> Vec<ClientLine> {let root = parse_context_node(tree);- let mut rows = flatten_tree(&root);+ let run_states: HashMap<&str, &str> = factory_runs+ .iter()+ .filter_map(|run| Some((run.run_id.as_str(), run.state.as_deref()?)))+ .collect();+ let mut units = flatten_tree(&root, &run_states);// The collapse: a tree over the row budget keeps its highest-usage- // rows (spend decides which agents matter) and folds the rest into- // the summary row. Ties keep tree order (stable sort).+ // units (spend decides which agents matter; a group ranks by its sum)+ // and folds the rest into the summary row. A group whose rows do not+ // fit keeps its group row alone. Ties keep tree order (stable sort).let mut summary: Option<HiddenAgents> = None;- if scope == ContextTreeScope::Collapsed && rows.len() > CONTEXT_ROW_BUDGET {- rows.sort_by(|left, right| {+ let row_count: usize = units.iter().map(|unit| unit.rows.len()).sum();+ // Over the budget something always folds or hides: the hint follows.+ let collapsed = scope == ContextTreeScope::Collapsed && row_count > CONTEXT_ROW_BUDGET;+ let rows: Vec<TreeRow<'_>> = if collapsed {+ units.sort_by(|left, right| {right- .node- .own_usage+ .usage.spent_tokens()- .cmp(&left.node.own_usage.spent_tokens())- .then_with(|| {- right- .node- .own_usage- .cost_total- .total_cmp(&left.node.own_usage.cost_total)- })+ .cmp(&left.usage.spent_tokens())+ .then_with(|| right.usage.cost_total.total_cmp(&left.usage.cost_total))});- let hidden_count = rows.len() - CONTEXT_ROW_BUDGET;+ let mut shown = Vec::new();+ let mut hidden_count = 0;let mut hidden_total = UsageTotals::default();- for row in &rows[CONTEXT_ROW_BUDGET..] {- hidden_total.add_fold(&row.node.own_usage);+ for mut unit in units {+ let free_rows = CONTEXT_ROW_BUDGET - shown.len();+ if unit.rows.len() <= free_rows {+ shown.extend(unit.rows);+ } else if free_rows > 0 && unit.rows.len() > 1 {+ unit.rows.truncate(1);+ if let RowKind::Group(group) = &mut unit.rows[0].kind {+ group.folded = true;+ }+ shown.extend(unit.rows);+ } else {+ hidden_count += unit.agents;+ hidden_total.add_fold(&unit.usage);+ }}- let noun = if hidden_count == 1 { "agent" } else { "agents" };- summary = Some(HiddenAgents {- label: format!("{hidden_count} more {noun}"),- tokens: crate::chrome::format_token_count(hidden_total.spent_tokens()),- cost: format_cost(hidden_total.cost_total),- });- rows.truncate(CONTEXT_ROW_BUDGET);- }+ if hidden_count > 0 {+ let noun = if hidden_count == 1 { "agent" } else { "agents" };+ summary = Some(HiddenAgents {+ label: format!("{hidden_count} more {noun}"),+ tokens: crate::chrome::format_token_count(hidden_total.spent_tokens()),+ cost: format_cost(hidden_total.cost_total),+ });+ }+ shown+ } else {+ units.into_iter().flat_map(|unit| unit.rows).collect()+ };let token_cells: Vec<String> = rows.iter()- .map(|row| crate::chrome::format_token_count(row.node.own_usage.spent_tokens()))+ .map(|row| crate::chrome::format_token_count(row.usage().spent_tokens())).collect();let cost_cells: Vec<String> = rows.iter()- .map(|row| format_cost(row.node.own_usage.cost_total))+ .map(|row| format_cost(row.usage().cost_total)).collect();let token_width = token_cells.iter()@@ -446,12 +686,16 @@ pub fn context_tree_rows(tree: &Value, width: usize, scope: ContextTreeScope) ->// when at least one node has a model.let model_cells: Vec<String> = rows.iter()- .map(|row| match &row.node.model {- Some((_, id)) => id.rsplit('/').next().unwrap_or(id).to_string(),- None => "-".to_string(),- })+ .map(+ |row| match row.node().and_then(|node| node.model.as_ref()) {+ Some((_, id)) => id.rsplit('/').next().unwrap_or(id).to_string(),+ None => "-".to_string(),+ },+ ).collect();- let show_models = rows.iter().any(|row| row.node.model.is_some());+ let show_models = rows+ .iter()+ .any(|row| row.node().is_some_and(|node| node.model.is_some()));let model_width = if show_models {model_cells.iter()@@ -464,7 +708,7 @@ pub fn context_tree_rows(tree: &Value, width: usize, scope: ContextTreeScope) ->};let max_label = rows.iter()- .map(|row| row.prefix.chars().count() + 2 + str_width(&row.node.label))+ .map(|row| row.prefix.chars().count() + 2 + str_width(&row.label())).chain(summary.iter().map(|hidden| 2 + str_width(&hidden.label))).max().unwrap_or_default();@@ -502,8 +746,8 @@ pub fn context_tree_rows(tree: &Value, width: usize, scope: ContextTreeScope) ->.saturating_sub(row.prefix.chars().count()).saturating_sub(2).max(1);- let label = truncate_plain(&row.node.label, label_space);- let (icon, icon_color) = status_icon(&row.node.status);+ let label = truncate_plain(&row.label(), label_space);+ let (icon, icon_color) = status_icon(row.status());// TS padEndAnsi/padStartAnsi pad with plain spaces OUTSIDE the// color codes, so the padding renders with the default foreground.let mut spans = vec![@@ -528,14 +772,14 @@ pub fn context_tree_rows(tree: &Value, width: usize, scope: ContextTreeScope) ->spans.push(dim(&cost_cells[index]));spans.push(raw_span(" "));spans.extend(context_column(- row.node.context_usage.as_ref(),- row.node.id == "root",+ row.node().and_then(|node| node.context_usage.as_ref()),+ row.node().is_some_and(|node| node.id == "root"),));lines.push(spans);}if let Some(hidden) = &summary {- // The summary row and the expand affordance.+ // The summary row.let label_space = label_width.saturating_sub(2).max(1);let label = truncate_plain(&hidden.label, label_space);let mut spans = vec![dim("..."), dim(format!(" {label}"))];@@ -557,6 +801,8 @@ pub fn context_tree_rows(tree: &Value, width: usize, scope: ContextTreeScope) ->spans.push(raw_span(" "));spans.push(dim("-"));lines.push(spans);+ }+ if collapsed {lines.push(vec![dim("Use /context all to show every agent.")]);}@@ -608,8 +854,9 @@ pub fn context_tree_rows(tree: &Value, width: usize, scope: ContextTreeScope) ->raw_span(format!(" ${}", js_to_fixed(totals.cost_total, 4))),]);// The per-model breakdown (the model mix decides the cost): the whole- // tree's buckets, most expensive model first. Rendered only when the tree- // used more than one model — a single-model tree already names its model.+ // tree's buckets, most expensive model first (the unknown-model bucket of+ // unsplit deleted spend sorts the same way). Rendered only when there is+ // more than one line — a single-model tree already names its model.let by_model = tree_own_usage_by_model(&root);if let Some(mut by_model) = by_model.filter(|by_model| by_model.len() > 1) {by_model.sort_by(|a, b| {@@ -620,8 +867,13 @@ pub fn context_tree_rows(tree: &Value, width: usize, scope: ContextTreeScope) ->.then_with(|| a.id.cmp(&b.id))});for bucket in &by_model {+ let label = if bucket.provider.is_empty() {+ "unknown model (deleted agents)".to_string()+ } else {+ format!("{}/{}", bucket.provider, bucket.id)+ };lines.push(vec![- dim(format!("{}/{}:", bucket.provider, bucket.id)),+ dim(format!("{label}:")),raw_span(format!(" ${}", js_to_fixed(bucket.totals.cost_total, 4))),]);}diff --git a/crates/pa-tui/src/info_commands/tests.rs b/crates/pa-tui/src/info_commands/tests.rsindex d0ab5c3b0c..91e28e79a7 100644--- a/crates/pa-tui/src/info_commands/tests.rs+++ b/crates/pa-tui/src/info_commands/tests.rs@@ -161,7 +161,7 @@ fn context_tree_root_only_matches_ts() {}"#,);assert_eq!(- plain(&context_tree_rows(&tree, 120, ContextTreeScope::Collapsed)),+ plain(&context_tree_rows(&tree, 120, ContextTreeScope::Collapsed, &[])),vec!["Context","",@@ -239,7 +239,7 @@ fn context_tree_full_shape_matches_ts() {}"#,);assert_eq!(- plain(&context_tree_rows(&tree, 100, ContextTreeScope::Collapsed)),+ plain(&context_tree_rows(&tree, 100, ContextTreeScope::Collapsed, &[])),vec!["Context","",@@ -311,7 +311,7 @@ fn context_tree_shows_per_model_costs_across_a_switch() {}"#,);assert_eq!(- plain(&context_tree_rows(&tree, 120, ContextTreeScope::Collapsed)),+ plain(&context_tree_rows(&tree, 120, ContextTreeScope::Collapsed, &[])),vec!["Context","",@@ -353,7 +353,7 @@ fn context_bar_color_follows_the_percent() {"children": []}"#,);- let rows = context_tree_rows(&tree, 120, ContextTreeScope::Collapsed);+ let rows = context_tree_rows(&tree, 120, ContextTreeScope::Collapsed, &[]);let bar = rows[3].iter().find(|span| span.text.contains("\u{2593}"))@@ -434,7 +434,7 @@ fn context_tree_ten_rows_render_the_full_shape() {}"#,);assert_eq!(- plain(&context_tree_rows(&tree, 120, ContextTreeScope::Collapsed)),+ plain(&context_tree_rows(&tree, 120, ContextTreeScope::Collapsed, &[])),vec!["Context","",@@ -562,7 +562,7 @@ fn context_tree_collapses_over_the_budget_to_top_usage_rows() {}"#,);assert_eq!(- plain(&context_tree_rows(&tree, 120, ContextTreeScope::Collapsed)),+ plain(&context_tree_rows(&tree, 120, ContextTreeScope::Collapsed, &[])),vec!["Context","",@@ -689,7 +689,7 @@ fn context_tree_all_renders_every_row() {}"#,);assert_eq!(- plain(&context_tree_rows(&tree, 120, ContextTreeScope::EveryAgent)),+ plain(&context_tree_rows(&tree, 120, ContextTreeScope::EveryAgent, &[])),vec!["Context","",@@ -806,7 +806,12 @@ fn context_tree_collapse_can_fold_the_root_into_the_summary() {}"#,);assert_eq!(- plain(&context_tree_rows(&tree, 120, ContextTreeScope::Collapsed)),+ plain(&context_tree_rows(+ &tree,+ 120,+ ContextTreeScope::Collapsed,+ &[]+ )),vec!["Context","",@@ -837,6 +842,182 @@ fn context_tree_collapse_can_fold_the_root_into_the_summary() {);}+/// Children sharing a factory run render under one run row (summed, its+/// status from the polled graph or derived from its agents), a parent's+/// deleted agents under one `deleted agents` row, and the grand totals stay+/// those of the ungrouped tree (group rows are never summed again).+#[test]+fn context_tree_groups_factory_runs_and_deleted_agents() {+ let usage = |input: u64, cost: f64| {+ serde_json::json!({"input": input, "output": 0, "cacheRead": 0, "cacheWrite": 0,+ "cost": {"total": cost}})+ };+ let run = serde_json::json!({"runId": "abcdef123456", "specId": "sw", "stateId": "build"});+ let child = |id: &str, status: &str, input: u64, cost: f64| {+ serde_json::json!({"id": id, "label": id, "status": status,+ "ownUsage": usage(input, cost), "totalUsage": usage(input, cost),+ "children": []})+ };+ let mut f1 = child("f1", "done", 3000, 0.03);+ f1["factory"] = run.clone();+ let mut f2 = child("f2", "running", 4000, 0.04);+ f2["factory"] = run.clone();+ let mut d1 = child("d1", "deleted", 1000, 0.01);+ d1["factory"] = run;+ d1["deleted"] = serde_json::json!(true);+ let mut d2 = child("d2", "deleted", 500, 0.006);+ d2["deleted"] = serde_json::json!(true);+ let mut tree = child("root", "active", 1000, 0.1);+ tree["label"] = serde_json::json!("main agent");+ tree["children"] = serde_json::json!([child("worker-a", "done", 2000, 0.02), f1, f2, d1, d2]);+ let normalized = |rows: Vec<ClientLine>| -> Vec<String> {+ plain(&rows)+ .iter()+ .map(|row| row.split_whitespace().collect::<Vec<_>>().join(" "))+ .collect()+ };+ let grouped = normalized(context_tree_rows(+ &tree,+ 120,+ ContextTreeScope::Collapsed,+ &[],+ ));+ assert_eq!(+ grouped[3..11],+ [+ "\u{25cf} main agent 1.0k $0.10 -",+ "\u{251c}\u{2500} \u{2713} worker-a 2.0k $0.02 -",+ "\u{251c}\u{2500} \u{25c6} factory sw abcdef 8.0k $0.08 -",+ "\u{2502} \u{251c}\u{2500} \u{2713} f1 3.0k $0.03 -",+ "\u{2502} \u{251c}\u{2500} \u{25c6} f2 4.0k $0.04 -",+ "\u{2502} \u{2514}\u{2500} \u{25c7} d1 1.0k $0.01 -",+ "\u{2514}\u{2500} \u{25c7} deleted agents 500 $0.01 -",+ "\u{2514}\u{2500} \u{25c7} d2 500 $0.01 -",+ ],+ "{grouped:#?}"+ );+ // The polled graph's run state wins over the derived one.+ let runs = crate::factory_view::parse_factory_runs(&serde_json::json!({"runs": [+ {"run_id": "abcdef123456", "spec_id": "sw", "state": "failed", "machine": {}}+ ]}));+ let polled = normalized(context_tree_rows(+ &tree,+ 120,+ ContextTreeScope::Collapsed,+ &runs,+ ));+ assert_eq!(+ polled[5],+ "\u{251c}\u{2500} \u{2717} factory sw abcdef 8.0k $0.08 -"+ );++ // The grand totals equal the ungrouped tree's: the real agents only.+ let totals = |rows: &[String]| {+ let start = rows+ .iter()+ .position(|row| row.starts_with("Total:"))+ .unwrap();+ rows[start..].to_vec()+ };+ let mut ungrouped = tree.clone();+ for child in ungrouped["children"].as_array_mut().unwrap() {+ child.as_object_mut().unwrap().remove("factory");+ child.as_object_mut().unwrap().remove("deleted");+ }+ let flat = normalized(context_tree_rows(+ &ungrouped,+ 120,+ ContextTreeScope::Collapsed,+ &[],+ ));+ assert_eq!(totals(&grouped), totals(&flat));+ assert_eq!(+ totals(&grouped)[0],+ "Total: 12k tokens \u{b7} $0.21 across 6 agents"+ );++ // Over the row budget the run ranks and folds as ONE unit.+ let children = tree["children"].as_array_mut().unwrap();+ for index in 0..9 {+ children.push(child(&format!("w{index}"), "done", 100, 0.001));+ }+ let collapsed = normalized(context_tree_rows(+ &tree,+ 120,+ ContextTreeScope::Collapsed,+ &[],+ ));+ let factory_row = collapsed+ .iter()+ .position(|row| row.contains("factory sw abcdef 8.0k"))+ .expect("the run row stays visible");+ assert!(+ collapsed[factory_row + 1].contains("f1 3.0k"),+ "{collapsed:#?}"+ );+ assert!(+ collapsed[factory_row + 3].contains("d1 1.0k"),+ "{collapsed:#?}"+ );+ assert!(+ collapsed.contains(&"... 7 more agents 700 $0.01 -".to_string()),+ "{collapsed:#?}"+ );++ // A run that only folds (nothing hidden) still offers the expand hint.+ let mut folded_tree = child("root", "active", 1000, 0.1);+ folded_tree["children"] = (0..10)+ .map(|index| {+ let mut member = child(&format!("m{index}"), "done", 100, 0.001);+ member["factory"] = serde_json::json!({"runId": "fedcba987654", "specId": "sw"});+ member+ })+ .collect();+ let folded = normalized(context_tree_rows(+ &folded_tree,+ 120,+ ContextTreeScope::Collapsed,+ &[],+ ));+ assert!(+ folded.contains(+ &"\u{2514}\u{2500} \u{2713} factory sw fedcba (10 agents) 1.0k $0.01 -".to_string()+ ),+ "{folded:#?}"+ );+ assert!(+ folded.contains(&"Use /context all to show every agent.".to_string()),+ "{folded:#?}"+ );++ // A deleted row without a per-model split (deleted before the capture+ // existed) keeps the breakdown: its spend is one unknown-model line.+ let mut split_tree = child("root", "active", 1000, 0.1);+ split_tree["ownUsageByModel"] = serde_json::json!([+ {"provider": "anthropic", "id": "claude-opus-4-6", "ownUsage": usage(1000, 0.1)}+ ]);+ let mut legacy = child("old", "deleted", 500, 0.05);+ legacy["deleted"] = serde_json::json!(true);+ split_tree["children"] = serde_json::json!([legacy]);+ let split = normalized(context_tree_rows(+ &split_tree,+ 120,+ ContextTreeScope::Collapsed,+ &[],+ ));+ let cost_section = &split[split.iter().position(|row| row == "Cost").unwrap()..];+ assert_eq!(+ cost_section[..4],+ [+ "Cost",+ "Total: $0.1500",+ "anthropic/claude-opus-4-6: $0.1000",+ "unknown model (deleted agents): $0.0500",+ ],+ "{split:#?}"+ );+}+#[test]fn client_text_renders_spacer_then_margined_rows() {let theme = crate::theme::Theme::builtin("prime", crate::theme::ColorMode::TrueColor);diff --git a/crates/pa-tui/src/session_ui/commands.rs b/crates/pa-tui/src/session_ui/commands.rsindex 9371c1c4e0..b9752773f2 100644--- a/crates/pa-tui/src/session_ui/commands.rs+++ b/crates/pa-tui/src/session_ui/commands.rs@@ -653,11 +653,16 @@ impl SessionUi {Ok(tree) => {// TS render width: clamp(columns - 2, 60, 120).let width = terminal_columns().saturating_sub(2).clamp(60, 120);+ let factory_runs =+ crate::factory_view::parse_factory_runs(&self.factory_graph);self.open_info_panel(view,None,InfoContent::Rows(info_commands::context_tree_rows(- &tree, width, scope,+ &tree,+ width,+ scope,+ &factory_runs,)),);self.track_menu_opened("context", "command");diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex 82f1da339b..2239f8d2f2 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -190,6 +190,19 @@ async def spawn(``thinking`` sets the child reasoning level (e.g. 'off', 'low', 'medium', 'high');defaults to the parent level; levels invalid for the resolved model fail the spawn."""+ return await _spawn(prompt, name=name, model=model, thinking=thinking)+++async def _spawn(+ prompt: str,+ *,+ name: str,+ model: str | None = None,+ thinking: str | None = None,+ factory: dict[str, str] | None = None,+) -> RLMSpawnHandle:+ """``spawn`` plus the factory executor's run tag (``{runId, specId,+ stateId}``), which the host records on the child's ledger spawn edge."""if not isinstance(prompt, str):raise TypeError(f"prompt must be str, got {type(prompt).__name__}")kwargs: dict[str, Any] = {"name": name}@@ -197,6 +210,8 @@ async def spawn(kwargs["model"] = modelif thinking is not None:kwargs["thinking"] = thinking+ if factory is not None:+ kwargs["factory"] = factory# Wire type stays "rlm.run" so kernels and hosts of different versions stay compatible.payload = await host_request("rlm.run", {"prompt": prompt, "kwargs": kwargs})return _spawn_handle_from_payload(payload)diff --git a/prime-agent-runtime/src/rlm/factory.py b/prime-agent-runtime/src/rlm/factory.pyindex 85e41c404d..e98ecfc16a 100644--- a/prime-agent-runtime/src/rlm/factory.py+++ b/prime-agent-runtime/src/rlm/factory.py@@ -2804,13 +2804,17 @@ class FactoryExecutor:``stop()`` is retracted (deleted and cancelled) instead ofregistered running."""- from . import spawn+ from . import _spawninstance.attempt += 1child_name = _spawn_label(state.name, run.run_id, state.state_id, instance.index, instance.attempt)try:- handle = await spawn(- instance.prompt, name=child_name, model=state.model, thinking=state.thinking+ handle = await _spawn(+ instance.prompt,+ name=child_name,+ model=state.model,+ thinking=state.thinking,+ factory={"runId": run.run_id, "specId": run.spec_id, "stateId": state.state_id},)except RuntimeError as exc:last_error = str(exc)diff --git a/prime-agent-runtime/test/test_factory.py b/prime-agent-runtime/test/test_factory.pyindex 9a565ac75d..8ecf584e82 100644--- a/prime-agent-runtime/test/test_factory.py+++ b/prime-agent-runtime/test/test_factory.py@@ -3345,6 +3345,11 @@ class FactoryExecutorTest(_ExecutorTestCase):self.assertEqual(spawn[0]["prompt"], "Template by title.")self.assertEqual(spawn[0]["kwargs"]["model"], "pi/test-model")self.assertEqual(spawn[0]["kwargs"]["thinking"], "low")+ # The run tag the host records on the child's ledger spawn edge.+ self.assertEqual(+ spawn[0]["kwargs"]["factory"],+ {"runId": result["run_id"], "specId": "sw", "stateId": node_id},+ )@async_testasync def test_inline_subagent_name_labels_the_spawned_child(self) -> None: