A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
split state_getters.rs under 1000 lines (#3192)
kt2c6553ad2590
diff --git a/crates/pa-daemon/src/state_getters.rs b/crates/pa-daemon/src/state_getters.rsindex 32967493a9..31f575e1a1 100644--- a/crates/pa-daemon/src/state_getters.rs+++ b/crates/pa-daemon/src/state_getters.rs@@ -325,1333 +325,22 @@ impl Worker {)}}--/// The worker's model registry (auth storage + `models.json`, with the-/// on-disk private-authorization cache adopted so create-time resolution-/// sees the same availability the create path does).-pub(crate) fn worker_model_registry(agent_dir: &std::path::Path) -> ModelRegistry {- let auth = pa_core::auth::AuthStorage::create(agent_dir);- let mut registry = ModelRegistry::create(auth, agent_dir.join("models.json"));- registry.load_private_authorization_from_cache();- registry-}--/// The TS `Usage` wire shape (the TS `emptyUsage`).-pub(crate) fn empty_usage() -> Value {- json!({- "input": 0,- "output": 0,- "cacheRead": 0,- "cacheWrite": 0,- "totalTokens": 0,- "cost": {- "input": 0,- "output": 0,- "cacheRead": 0,- "cacheWrite": 0,- "total": 0,- },- })-}--/// TS `addAssistantUsage`: fold one usage block into a running total.-fn add_usage(total: &mut Value, usage: &Value) {- let add_field = |total: &mut Value, field: &str, usage: &Value| {- let current = total.get(field).and_then(Value::as_u64).unwrap_or(0);- let add = usage.get(field).and_then(Value::as_u64).unwrap_or(0);- total[field] = json!(current + add);- };- for field in ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] {- add_field(total, field, usage);- }- for field in ["input", "output", "cacheRead", "cacheWrite", "total"] {- let cost = total- .get_mut("cost")- .and_then(Value::as_object_mut)- .expect("usage totals always carry the cost block");- // The running total is a float after the first add (TS costs are- // floats); reading it as u64 dropped everything already banked.- let current = cost.get(field).and_then(Value::as_f64).unwrap_or(0.0);- let add = usage- .get("cost")- .and_then(|cost| cost.get(field))- .and_then(Value::as_f64)- .unwrap_or(0.0);- cost.insert(field.to_string(), json!(current + add));- }-}--/// TS `subtractAssistantUsage`: remove one usage block, clamping at zero.-fn subtract_usage(total: &mut Value, usage: &Value) {- let sub_field = |total: &mut Value, field: &str, usage: &Value| {- let current = total.get(field).and_then(Value::as_u64).unwrap_or(0);- let sub = usage.get(field).and_then(Value::as_u64).unwrap_or(0);- total[field] = json!(current.saturating_sub(sub));- };- for field in ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] {- sub_field(total, field, usage);- }- for field in ["input", "output", "cacheRead", "cacheWrite", "total"] {- let cost = total- .get_mut("cost")- .and_then(Value::as_object_mut)- .expect("usage totals always carry the cost block");- let current = cost.get(field).and_then(Value::as_f64).unwrap_or(0.0);- let sub = usage- .get("cost")- .and_then(|cost| cost.get(field))- .and_then(Value::as_f64)- .unwrap_or(0.0);- cost.insert(field.to_string(), json!((current - sub).max(0.0)));- }-}--/// TS `computeOwnAndTotalUsage`: the branch's cumulative assistant usage-/// (`totalUsage`, attributions included) minus the child usage-/// attributions targeting those assistants (`ownUsage`). Totals stay-/// cumulative across compactions: compaction shrinks the model-facing-/// context, not what the session spent.-pub(crate) fn compute_own_and_total_usage(- branch: &[&crate::session_store::SessionEntry],- all_entries: &[crate::session_store::SessionEntry],-) -> (Value, Value) {- let mut total = empty_usage();- let mut branch_assistant_ids = std::collections::HashSet::new();- for entry in branch {- if entry.type_ == "message" {- let Some(message) = entry.fields.get("message") else {- continue;- };- if message.get("role").and_then(Value::as_str) == Some("assistant") {- branch_assistant_ids.insert(entry.id.clone());- if let Some(usage) = message.get("usage") {- add_usage(&mut total, usage);- }- }- } else if matches!(entry.type_.as_str(), "compaction" | "branch_summary") {- if let Some(usage) = entry.fields.get("usage") {- add_usage(&mut total, usage);- }- }- }- let mut own = total.clone();- for entry in all_entries {- if entry.type_ != "child_usage_attributed" {- continue;- }- let Some(target_id) = entry.fields.get("targetId").and_then(Value::as_str) else {- continue;- };- if branch_assistant_ids.contains(target_id) {- if let Some(child_usage) = entry.fields.get("childUsage") {- subtract_usage(&mut own, child_usage);- }- }- }- (own, total)-}--/// The branch's own usage broken down by serving model (the operator's-/// cost question: a session that switches models mid-conversation — or-/// hosts subagents on other models — shows which model billed what).-///-/// Each assistant row folds into the bucket of the model on its message-/// envelope (the request-time serving model — cost blocks were computed-/// against that model's rates, so each bucket holds only spend billed at-/// those rates); `compaction` / `branch_summary` rows fold on the model-/// their entry records when the summary call named one (TS #2411 routes-/// branch summaries to a configured auxiliary model — the timeline names-/// the session's current model, not the routed one that billed) and-/// otherwise follow the branch's `model_change` timeline, seeded on a-/// windowed load with the retained-window boundary's model (the newest-/// `model_change` in the discarded prefix — the leaf's model would bill-/// the boundary's early summarizer rows on the wrong side of a post--/// boundary switch).-/// Child-usage attributions subtract from the target row's model bucket-/// exactly like [`compute_own_and_total_usage`] subtracts from-/// `ownUsage`, so the buckets sum to the node's own usage — and the sum-/// is verified against the caller's `own_usage` before the breakdown is-/// served. `None` when any usage-carrying row resolves to no model (a-/// foreign file without `model_change` rows or model-tagged assistants),-/// or when the buckets cannot reconcile: an attribution larger than its-/// target row's bucket clamps inside that bucket while the plain fold-/// subtracts the same amount from the combined pool, so the buckets-/// would overstate the node. A partial breakdown would not add up to the-/// displayed totals, so the caller omits the field and the display-/// degrades to the plain TS totals.-pub(crate) fn compute_own_usage_by_model(- branch: &[&crate::session_store::SessionEntry],- all_entries: &[crate::session_store::SessionEntry],- own_usage: &Value,- initial_model: Option<&(String, String)>,-) -> Option<Vec<Value>> {- // The buckets in first-seen order: JSON arrays keep the fold order,- // so the display renders the model the session started on first.- let mut order: Vec<(String, String)> = Vec::new();- let mut position: std::collections::HashMap<(String, String), usize> =- std::collections::HashMap::new();- let mut buckets: Vec<Value> = Vec::new();- // The branch's model timeline seeded with the retained-window- // boundary's model when the load kept only a window (a reopened- // compacted session's retained branch starts at the boundary — its- // early rows billed on the boundary's model, not the leaf's, and a- // full history keeps `None` so a foreign file still omits the- // breakdown) and the assistant id -> bucket map the attribution- // subtraction reads.- let mut current: Option<(String, String)> = initial_model.cloned();- let mut assistant_buckets: std::collections::HashMap<&str, usize> =- std::collections::HashMap::new();- let mut unresolved = false;- let mut bucket_for =- |key: Option<(String, String)>, buckets: &mut Vec<Value>| -> Option<usize> {- let key = key?;- let at = *position.entry(key.clone()).or_insert_with(|| {- order.push(key);- buckets.push(empty_usage());- buckets.len() - 1- });- Some(at)- };- for entry in branch {- let usage = match entry.type_.as_str() {- "model_change" => {- let provider = entry- .fields- .get("provider")- .and_then(Value::as_str)- .unwrap_or_default();- let model_id = entry- .fields- .get("modelId")- .and_then(Value::as_str)- .unwrap_or_default();- current = (!provider.is_empty() && !model_id.is_empty())- .then(|| (provider.to_string(), model_id.to_string()));- continue;- }- "message" => {- let Some(message) = entry.fields.get("message") else {- continue;- };- if message.get("role").and_then(Value::as_str) != Some("assistant") {- continue;- }- let usage = message.get("usage");- if usage.is_none() {- // An assistant row without usage bills nothing; the- // own-usage fold skips it the same way (an attribution- // targeting it subtracts from a zero base).- continue;- }- // The serving model on the envelope outranks the timeline- // (the row is the request's own record).- let provider = message- .get("provider")- .and_then(Value::as_str)- .unwrap_or_default();- let model_id = message- .get("model")- .and_then(Value::as_str)- .unwrap_or_default();- let key = (!provider.is_empty() && !model_id.is_empty())- .then(|| (provider.to_string(), model_id.to_string()))- .or(current.clone());- match bucket_for(key, &mut buckets) {- Some(at) => {- add_usage(&mut buckets[at], usage.expect("checked"));- assistant_buckets.insert(entry.id.as_str(), at);- }- None => unresolved = true,- }- continue;- }- "compaction" | "branch_summary" => entry.fields.get("usage"),- _ => continue,- };- if let Some(usage) = usage {- // A row that records the model its summary call served on- // (TS #2411's auxiliary routing — persisted on the entry)- // outranks the timeline: the branch timeline names the- // session's current model, not the routed one that billed.- let row_model = (|| {- let provider = entry.fields.get("provider")?.as_str()?;- let model_id = entry.fields.get("modelId")?.as_str()?;- (!provider.is_empty() && !model_id.is_empty())- .then(|| (provider.to_string(), model_id.to_string()))- })();- match bucket_for(row_model.or_else(|| current.clone()), &mut buckets) {- Some(at) => add_usage(&mut buckets[at], usage),- None => unresolved = true,- }- }- }- if unresolved {- return None;- }- for entry in all_entries {- if entry.type_ != "child_usage_attributed" {- continue;- }- let Some(target_id) = entry.fields.get("targetId").and_then(Value::as_str) else {- continue;- };- let (Some(at), Some(child_usage)) = (- assistant_buckets.get(target_id).copied(),- entry.fields.get("childUsage"),- ) else {- continue;- };- subtract_usage(&mut buckets[at], child_usage);- }- // Reconciliation: the buckets must sum to the node's own usage. The- // per-bucket attribution subtraction clamps inside the target row's- // bucket while the plain fold subtracts from the combined pool, so- // an attribution larger than its target row's spend (or one whose- // target row carries no usage) leaves the buckets overstating the- // node. Omit the breakdown then — the unresolved-model contract: a- // breakdown that cannot add up is worse than none. Token fields- // compare exactly; the cost fields allow the last-ulp drift of two- // differently ordered float sums.- let mut summed = empty_usage();- for bucket in &buckets {- add_usage(&mut summed, bucket);- }- for field in ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] {- if summed[field] != own_usage[field] {- return None;- }- }- for field in ["input", "output", "cacheRead", "cacheWrite", "total"] {- let summed_cost = summed["cost"][field].as_f64().unwrap_or_default();- let own_cost = own_usage["cost"][field].as_f64().unwrap_or_default();- if (summed_cost - own_cost).abs() > 1e-9 * (1.0 + summed_cost.max(own_cost)) {- return None;- }- }- Some(- order- .into_iter()- .zip(buckets)- .map(|((provider, model_id), own_usage)| {- json!({ "provider": provider, "id": model_id, "ownUsage": own_usage })- })- .collect(),- )-}-+// The usage math (the model registry resolution, the TS `Usage` wire shape,+// the add/subtract folds, and the own/total + by-model computations) moved to+// the child module at the same tree position (state_getters::usage); the+// re-exports keep the facade's paths stable (context_tree_cache.rs's+// empty_usage, rlm_child_model.rs's + setting_switches.rs's ++// worker/create.rs's worker_model_registry, context_tree_children.rs's+// compute_*). The private add_usage/subtract_usage folds ride with their+// callers.+mod usage;++pub(crate) use usage::{+ compute_own_and_total_usage, compute_own_usage_by_model, empty_usage, worker_model_registry,+};++// The getter battery moved to the child module at the same tree position+// (state_getters::state_getters_tests); the #[cfg(test)] decl rides at the+// facade tail.#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;- use std::sync::Arc;-- /// A created worker backed by an existing session file (the store's- /// path, so the artifact tree beside it resolves).- async fn created_worker_at(- root: &std::path::Path,- session_file: &std::path::Path,- ) -> Arc<Worker> {- std::fs::create_dir_all(root).unwrap();- let config = crate::worker::WorkerConfig {- socket_path: root.join("worker.sock"),- supervisor_socket_path: std::path::PathBuf::new(),- token: "token".to_string(),- worker_instance_id: String::new(),- active_session_id: "getter-session".to_string(),- agent_dir: root.join("agent"),- recovery_journal_path: root.join("recovery.jsonl"),- telemetry_disabled: None,- script: Some(json!({ "responses": ["ack"] })),- };- let worker = Arc::new(Worker::new(config, None));- let created = worker- .dispatch(- "create",- &json!({- "sessionPath": session_file.display().to_string(),- "cwd": "/tmp",- "name": "getters",- }),- )- .await;- assert!(created.success, "create failed: {created:?}");- worker- }-- async fn created_worker() -> Arc<Worker> {- let dir = std::env::temp_dir().join(format!("pa-worker-sg-{}", uuid::Uuid::new_v4()));- std::fs::create_dir_all(&dir).unwrap();- let config = crate::worker::WorkerConfig {- socket_path: dir.join("worker.sock"),- supervisor_socket_path: std::path::PathBuf::new(),- token: "token".to_string(),- worker_instance_id: String::new(),- active_session_id: "getter-session".to_string(),- agent_dir: dir.join("agent"),- recovery_journal_path: dir.join("recovery.jsonl"),- telemetry_disabled: None,- script: Some(json!({ "responses": ["ack"] })),- };- let worker = Arc::new(Worker::new(config, None));- let created = worker- .dispatch(- "create",- &json!({ "noSession": true, "cwd": "/tmp", "name": "getters" }),- )- .await;- assert!(created.success, "create failed: {created:?}");- worker- }-- /// `get_connection_state` answers the TS `AgentConnectionState` block- /// with the daemon overlay: `heartbeat` is present and null (no cron- /// store on this worker).- #[tokio::test]- async fn get_connection_state_matches_the_ts_shape() {- let worker = created_worker().await;- let response = worker- .dispatch(- "get_connection_state",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success, "failed: {response:?}");- let data = response.data.expect("connection state data");- assert_eq!(data["activeSessionId"], "getter-session");- assert_eq!(data["cwd"], "/tmp");- assert_eq!(data["heartbeat"], Value::Null);- for field in [- "thinkingLevel",- "serviceTier",- "availableThinkingLevels",- "isStreaming",- "isCompacting",- "isBashRunning",- "retryAttempt",- "steeringMode",- "followUpMode",- "sessionId",- "leafId",- "autoCompactionEnabled",- "messageCount",- "sessionActions",- "compactionCount",- "goal",- "scopedModels",- "activeToolNames",- ] {- assert!(data.get(field).is_some(), "missing {field}: {data}");- }- // A session that has not been created answers the TS- // initializing refusal.- let fresh = Arc::new(Worker::new(- {- let mut config = worker.config.clone();- config.active_session_id = "fresh-session".to_string();- config- },- None,- ));- let response = fresh- .dispatch(- "get_connection_state",- &json!({ "activeSessionId": "fresh-session" }),- )- .await;- assert!(!response.success);- assert_eq!(- response.error.as_deref(),- Some("Session is still initializing")- );- }-- /// `get_rlm_children`: the child roster plus the pre-walk event- /// sequence; a worker without children answers the empty roster.- #[tokio::test]- async fn get_rlm_children_carries_the_sequence() {- let worker = created_worker().await;- let response = worker- .dispatch(- "get_rlm_children",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success, "failed: {response:?}");- let data = response.data.expect("data");- assert_eq!(data["children"], json!([]));- let sequence = data["eventSequence"].as_u64().expect("event sequence");- // A subsequent read captures the same sequence until an event- // bumps it (TS freshness contract).- let again = worker- .dispatch(- "get_rlm_children",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert_eq!(again.data.expect("data")["eventSequence"], json!(sequence));- }-- /// `get_context_tree`: the root node with usage totals over the- /// persisted branch; child attributions move the split between- /// `ownUsage` and `totalUsage` (TS `computeOwnAndTotalUsage`).- #[tokio::test]- async fn get_context_tree_matches_the_ts_root_node() {- let worker = created_worker().await;- let response = worker- .dispatch(- "get_context_tree",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success, "failed: {response:?}");- let tree = response.data.expect("data");- assert_eq!(tree["id"], "root");- assert_eq!(tree["label"], "getters");- assert_eq!(tree["status"], "active");- assert_eq!(tree["children"], json!([]));- assert_eq!(tree["ownUsage"]["totalTokens"], json!(0));-- // One assistant turn seeds usage totals (the scripted usage block).- let _ = worker- .dispatch(- "prompt_and_wait",- &json!({ "activeSessionId": "getter-session", "message": "hi" }),- )- .await;- let response = worker- .dispatch(- "get_context_tree",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- let tree = response.data.expect("data");- assert_eq!(tree["ownUsage"]["input"], json!(120));- assert_eq!(tree["totalUsage"]["totalTokens"], json!(128));- assert_eq!(tree["totalUsage"]["cost"]["total"].as_f64(), Some(0.0));- }-- /// The captured-attribution fixture over the full daemon path (create- /// from a copy of the fixture file, so the repo fixture stays- /// read-only): the load-time fold makes the root's own/total split- /// TS-exact. `ownUsage` is the assistant's own row (input 2690, cost- /// $0 — `totalTokens` clamps to zero because the six attributions'- /// child `totalTokens` (54289) exceeds the aggregate's unchanged- /// 23032, TS `subtractAssistantUsage`'s clamp); `totalUsage` carries- /// the attributed child spend (input 52898, cost $0.0089957,- /// `totalTokens` stays 23032).- #[tokio::test]- async fn get_context_tree_folds_the_captured_attributions() {- let root = std::env::temp_dir().join(format!("pa-worker-af-{}", uuid::Uuid::new_v4()));- std::fs::create_dir_all(&root).unwrap();- let fixture = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .join("tests/fixtures/attribution-fold-captured.jsonl");- let session_file = root.join("captured.jsonl");- std::fs::copy(&fixture, &session_file).unwrap();- let worker = created_worker_at(&root, &session_file).await;- let response = worker- .dispatch(- "get_context_tree",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success, "failed: {response:?}");- let tree = response.data.expect("data");- assert_eq!(tree["ownUsage"]["input"], json!(2690));- assert_eq!(tree["ownUsage"]["output"], json!(2934));- assert_eq!(tree["ownUsage"]["cacheRead"], json!(17408));- assert_eq!(tree["ownUsage"]["totalTokens"], json!(0));- // The six sequential per-entry subtractions leave float-order noise- // in the last ulps (TS `subtractAssistantUsage` walks the same- // order), so own cost pins at ~0, not bit-exact zero.- assert!(- tree["ownUsage"]["cost"]["total"].as_f64().unwrap().abs() < 1e-12,- "own cost {} is not ~0",- tree["ownUsage"]["cost"]["total"]- );- assert_eq!(tree["totalUsage"]["input"], json!(52898));- assert_eq!(tree["totalUsage"]["output"], json!(5863));- assert_eq!(tree["totalUsage"]["cacheRead"], json!(18560));- assert_eq!(tree["totalUsage"]["totalTokens"], json!(23032));- assert_eq!(- tree["totalUsage"]["cost"]["total"].as_f64(),- Some(0.008_995_7)- );- // `get_session_stats` reports the same folded totals over the- // gap-bridged branch.- let stats = worker- .dispatch(- "get_session_stats",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(stats.success, "failed: {stats:?}");- let stats = stats.data.expect("data");- assert_eq!(stats["tokens"]["input"], json!(52898));- assert_eq!(stats["tokens"]["output"], json!(5863));- assert_eq!(stats["tokens"]["cacheRead"], json!(18560));- assert_eq!(stats["cost"].as_f64(), Some(0.008_995_7));- }-- /// The operator's cost question, proven over the real file path: a- /// session that switches models mid-conversation accumulates the- /// correct per-model costs INCLUDING the switch's cache-write burst.- /// The synthetic file's cost blocks are the provider-computed records- /// (`calculate_cost` against the catalog rates: gpt-5.6-sol $4/$20 per- /// M; claude-opus-4-6 $5/$25/M, cacheRead $0.5/M, cacheWrite $6.25/M- /// = the 1.25x write multiplier): the sol turn bills $0.44; the first- /// opus request re-caches the whole history — 104k cache-write tokens- /// at $6.25/M = $0.65 exactly — and bills $0.70; the next opus turn- /// hits the cache ($0.0775). The per-model buckets carry each model's- /// share with the fold's exact float sums, and the grand totals are- /// per-model-summed across the switch.- #[tokio::test]- async fn get_context_tree_breaks_own_usage_down_by_model() {- let root = std::env::temp_dir().join(format!("pa-worker-bm-{}", uuid::Uuid::new_v4()));- std::fs::create_dir_all(&root).unwrap();- let session_file = root.join("switched.jsonl");- let usage = |input: u64,- output: u64,- cache_read: u64,- cache_write: u64,- total: u64,- (ci, co, cr, cw, ct): (f64, f64, f64, f64, f64)| {- json!({- "input": input, "output": output, "cacheRead": cache_read,- "cacheWrite": cache_write, "totalTokens": total,- "cost": {"input": ci, "output": co, "cacheRead": cr,- "cacheWrite": cw, "total": ct},- })- };- let lines = [- json!({"type": "session", "version": 3, "id": "switched-0001", "timestamp": "2026-09-24T00:00:00.000Z", "cwd": "/tmp"}),- json!({"type": "model_change", "id": "m0", "parentId": null, "timestamp": "2026-09-24T00:00:00.100Z", "provider": "openai", "modelId": "gpt-5.6-sol"}),- json!({"type": "message", "id": "e1", "parentId": "m0", "timestamp": "2026-09-24T00:00:01.000Z", "message": {"role": "user", "content": "audit the costs"}}),- json!({"type": "message", "id": "e2", "parentId": "e1", "timestamp": "2026-09-24T00:00:02.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "on it"}], "provider": "openai", "model": "gpt-5.6-sol", "stopReason": "stop", "usage": usage(100_000, 2000, 0, 0, 1200, (0.4, 0.04, 0.0, 0.0, 0.44))}}),- json!({"type": "model_change", "id": "m1", "parentId": "e2", "timestamp": "2026-09-24T00:00:03.000Z", "provider": "anthropic", "modelId": "claude-opus-4-6"}),- json!({"type": "message", "id": "e3", "parentId": "m1", "timestamp": "2026-09-24T00:00:04.000Z", "message": {"role": "user", "content": "switch to opus"}}),- json!({"type": "message", "id": "e4", "parentId": "e3", "timestamp": "2026-09-24T00:00:05.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "done"}], "provider": "anthropic", "model": "claude-opus-4-6", "stopReason": "stop", "usage": usage(5000, 1000, 0, 104_000, 110_000, (0.025, 0.025, 0.0, 0.65, 0.7))}}),- json!({"type": "message", "id": "e5", "parentId": "e4", "timestamp": "2026-09-24T00:00:06.000Z", "message": {"role": "user", "content": "and now a cache hit"}}),- json!({"type": "message", "id": "e6", "parentId": "e5", "timestamp": "2026-09-24T00:00:07.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "cheap"}], "provider": "anthropic", "model": "claude-opus-4-6", "stopReason": "stop", "usage": usage(500, 800, 110_000, 0, 110_500, (0.0025, 0.02, 0.055, 0.0, 0.0775))}}),- ];- let content = lines- .iter()- .map(std::string::ToString::to_string)- .collect::<Vec<_>>()- .join("\n");- std::fs::write(&session_file, content).unwrap();- let worker = created_worker_at(&root, &session_file).await;- let response = worker- .dispatch(- "get_context_tree",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success, "failed: {response:?}");- let tree = response.data.expect("data");- // The grand totals sum every record's stored cost — the honest- // per-model-summed total across the switch.- assert_eq!(tree["ownUsage"]["input"], json!(105_500));- assert_eq!(tree["ownUsage"]["output"], json!(3800));- assert_eq!(tree["ownUsage"]["cacheRead"], json!(110_000));- assert_eq!(tree["ownUsage"]["cacheWrite"], json!(104_000));- assert_eq!(tree["ownUsage"]["totalTokens"], json!(221_700));- assert_eq!(- tree["ownUsage"]["cost"]["total"].as_f64(),- Some(0.4 + 0.04 + 0.7 + 0.0775)- );- // The per-model breakdown: first-seen order, each bucket holding- // exactly the records that model served.- let buckets = tree["ownUsageByModel"]- .as_array()- .expect("the by-model breakdown is present");- assert_eq!(buckets.len(), 2);- assert_eq!(buckets[0]["provider"], json!("openai"));- assert_eq!(buckets[0]["id"], json!("gpt-5.6-sol"));- assert_eq!(buckets[0]["ownUsage"]["input"], json!(100_000));- assert_eq!(buckets[0]["ownUsage"]["output"], json!(2000));- assert_eq!(buckets[0]["ownUsage"]["cacheWrite"], json!(0));- assert_eq!(- buckets[0]["ownUsage"]["cost"]["total"].as_f64(),- Some(0.4 + 0.04)- );- assert_eq!(buckets[1]["provider"], json!("anthropic"));- assert_eq!(buckets[1]["id"], json!("claude-opus-4-6"));- assert_eq!(buckets[1]["ownUsage"]["input"], json!(5500));- assert_eq!(buckets[1]["ownUsage"]["output"], json!(1800));- assert_eq!(buckets[1]["ownUsage"]["cacheRead"], json!(110_000));- assert_eq!(buckets[1]["ownUsage"]["cacheWrite"], json!(104_000));- // The switch's cache-write burst bills at the new model's write- // rate: 104k tokens x $6.25/M (1.25x the $5/M input rate) is- // exactly $0.65.- assert_eq!(- buckets[1]["ownUsage"]["cost"]["cacheWrite"].as_f64(),- Some(104_000.0 * 6.25 / 1_000_000.0)- );- assert_eq!(- buckets[1]["ownUsage"]["cost"]["total"].as_f64(),- Some(0.7 + 0.0775)- );- }-- /// The buckets reconcile or the breakdown is omitted: a child- /// attribution whose `totalTokens` exceed its target row's bucket- /// (the captured-fixture shape — the child's token deltas do not- /// ride the row's aggregate) clamps inside that bucket, while the- /// plain own-usage fold subtracts the same amount from the combined- /// pool where the other model's spend absorbs it. The buckets would- /// sum past `ownUsage`, so `ownUsageByModel` is omitted and the- /// display degrades to the plain totals instead of overstating the- /// node (the Macroscope attribution-clamp round).- #[tokio::test]- async fn get_context_tree_omits_the_breakdown_when_an_attribution_exceeds_its_bucket() {- let root = std::env::temp_dir().join(format!("pa-worker-bmx-{}", uuid::Uuid::new_v4()));- std::fs::create_dir_all(&root).unwrap();- let session_file = root.join("clamped.jsonl");- let usage = |input: u64, output: u64, total: u64| {- json!({- "input": input, "output": output, "cacheRead": 0, "cacheWrite": 0,- "totalTokens": total,- "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0},- })- };- let lines = [- json!({"type": "session", "version": 3, "id": "clamped-0001", "timestamp": "2026-09-25T00:00:00.000Z", "cwd": "/tmp"}),- json!({"type": "model_change", "id": "m0", "parentId": null, "timestamp": "2026-09-25T00:00:00.100Z", "provider": "openai", "modelId": "gpt-5.6-sol"}),- json!({"type": "message", "id": "e1", "parentId": "m0", "timestamp": "2026-09-25T00:00:01.000Z", "message": {"role": "user", "content": "audit the mix"}}),- json!({"type": "message", "id": "e2", "parentId": "e1", "timestamp": "2026-09-25T00:00:02.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "on it"}], "provider": "openai", "model": "gpt-5.6-sol", "stopReason": "stop", "usage": usage(1_000, 100, 1_100)}}),- json!({"type": "model_change", "id": "m1", "parentId": "e2", "timestamp": "2026-09-25T00:00:03.000Z", "provider": "anthropic", "modelId": "claude-opus-4-6"}),- json!({"type": "message", "id": "e3", "parentId": "m1", "timestamp": "2026-09-25T00:00:04.000Z", "message": {"role": "user", "content": "big opus turn"}}),- json!({"type": "message", "id": "e4", "parentId": "e3", "timestamp": "2026-09-25T00:00:05.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "done"}], "provider": "anthropic", "model": "claude-opus-4-6", "stopReason": "stop", "usage": usage(100_000, 2_000, 102_000)}}),- // The child's input/output ride the cumulative aggregate; the- // totalTokens do not (the row keeps its own 1_100).- json!({"type": "child_usage_attributed", "id": "a1", "parentId": "e4", "timestamp": "2026-09-25T00:00:06.000Z", "targetId": "e2",- "childUsage": usage(3_000, 300, 9_000),- "aggregateUsage": usage(4_000, 400, 1_100),- "origin": "spawn_task"}),- ];- let content = lines- .iter()- .map(std::string::ToString::to_string)- .collect::<Vec<_>>()- .join("\n");- std::fs::write(&session_file, content).unwrap();- let worker = created_worker_at(&root, &session_file).await;- let response = worker- .dispatch(- "get_context_tree",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success, "failed: {response:?}");- let tree = response.data.expect("data");- // The plain fold subtracts the 9_000 tokens from the combined- // pool: 1_100 + 102_000 - 9_000. The input and output fields- // reconcile exactly (the attribution rides the aggregate), so a- // mismatch here would mean the reconciliation itself drifted.- assert_eq!(tree["ownUsage"]["input"], json!(101_000));- assert_eq!(tree["ownUsage"]["output"], json!(2_100));- assert_eq!(tree["ownUsage"]["totalTokens"], json!(94_100));- // The sol bucket clamps at zero while the opus bucket keeps its- // 102_000: the buckets would sum to 102_000 and overstate the- // node's 94_100, so the breakdown is omitted.- assert!(- tree["ownUsageByModel"].is_null(),- "the clamped breakdown must not be served: {}",- tree["ownUsageByModel"]- );- }-- /// The control for the omission rule: an attribution that fits its- /// target row's bucket reconciles (the buckets sum to `ownUsage`- /// exactly) and the breakdown stays served.- #[tokio::test]- async fn get_context_tree_keeps_the_breakdown_when_an_attribution_fits_its_bucket() {- let root = std::env::temp_dir().join(format!("pa-worker-bmf-{}", uuid::Uuid::new_v4()));- std::fs::create_dir_all(&root).unwrap();- let session_file = root.join("fits.jsonl");- let usage = |input: u64, output: u64, total: u64| {- json!({- "input": input, "output": output, "cacheRead": 0, "cacheWrite": 0,- "totalTokens": total,- "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0},- })- };- let lines = [- json!({"type": "session", "version": 3, "id": "fits-0001", "timestamp": "2026-09-25T00:00:00.000Z", "cwd": "/tmp"}),- json!({"type": "model_change", "id": "m0", "parentId": null, "timestamp": "2026-09-25T00:00:00.100Z", "provider": "openai", "modelId": "gpt-5.6-sol"}),- json!({"type": "message", "id": "e1", "parentId": "m0", "timestamp": "2026-09-25T00:00:01.000Z", "message": {"role": "user", "content": "audit the mix"}}),- json!({"type": "message", "id": "e2", "parentId": "e1", "timestamp": "2026-09-25T00:00:02.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "on it"}], "provider": "openai", "model": "gpt-5.6-sol", "stopReason": "stop", "usage": usage(1_000, 100, 1_100)}}),- json!({"type": "model_change", "id": "m1", "parentId": "e2", "timestamp": "2026-09-25T00:00:03.000Z", "provider": "anthropic", "modelId": "claude-opus-4-6"}),- json!({"type": "message", "id": "e3", "parentId": "m1", "timestamp": "2026-09-25T00:00:04.000Z", "message": {"role": "user", "content": "big opus turn"}}),- json!({"type": "message", "id": "e4", "parentId": "e3", "timestamp": "2026-09-25T00:00:05.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "done"}], "provider": "anthropic", "model": "claude-opus-4-6", "stopReason": "stop", "usage": usage(100_000, 2_000, 102_000)}}),- json!({"type": "child_usage_attributed", "id": "a1", "parentId": "e4", "timestamp": "2026-09-25T00:00:06.000Z", "targetId": "e2",- "childUsage": usage(3_000, 300, 500),- "aggregateUsage": usage(4_000, 400, 1_100),- "origin": "spawn_task"}),- ];- let content = lines- .iter()- .map(std::string::ToString::to_string)- .collect::<Vec<_>>()- .join("\n");- std::fs::write(&session_file, content).unwrap();- let worker = created_worker_at(&root, &session_file).await;- let response = worker- .dispatch(- "get_context_tree",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success, "failed: {response:?}");- let tree = response.data.expect("data");- assert_eq!(tree["ownUsage"]["totalTokens"], json!(102_600));- let buckets = tree["ownUsageByModel"]- .as_array()- .expect("the fitting breakdown is served");- assert_eq!(buckets.len(), 2);- assert_eq!(buckets[0]["id"], json!("gpt-5.6-sol"));- assert_eq!(buckets[0]["ownUsage"]["input"], json!(1_000));- assert_eq!(buckets[0]["ownUsage"]["totalTokens"], json!(600));- assert_eq!(buckets[1]["id"], json!("claude-opus-4-6"));- assert_eq!(buckets[1]["ownUsage"]["totalTokens"], json!(102_000));- }-- /// `get_context_tree` surfaces the persisted child sessions under the- /// session's artifact tree (idle, settled, and restart-orphaned- /// subagents all appear, with their real usage and recursive- /// grandchildren — TS `loadContextTreeChildrenFromDisk`). The artifact- /// tree is keyed by the worker's agent dir and the durable session id,- /// exactly where `child_session_dir` writes; a session file outside- /// the agent dir must not change that.- #[tokio::test]- async fn get_context_tree_lists_persisted_children() {- let root = std::env::temp_dir().join(format!("pa-worker-ct-{}", uuid::Uuid::new_v4()));- let agent_dir = root.join("agent");- let sessions = agent_dir.join("sessions");- std::fs::create_dir_all(&sessions).unwrap();- let session_id = "01a0ct-1111-2222-3333-444444444444";- let session_file = sessions.join(format!("{session_id}.jsonl"));- let usage = json!({- "input": 30, "output": 6, "cacheRead": 0, "cacheWrite": 0,- "totalTokens": 36,- "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0 },- });- let content = [- json!({"type": "session", "version": 3, "id": session_id, "timestamp": "2026-09-22T00:00:00.000Z", "cwd": "/tmp"}),- json!({"type": "message", "id": "e1", "parentId": null, "timestamp": "2026-09-22T00:00:01.000Z", "message": {"role": "user", "content": "hi"}}),- json!({"type": "message", "id": "e2", "parentId": "e1", "timestamp": "2026-09-22T00:00:02.000Z", "message": {"role": "assistant", "content": [{ "type": "text", "text": "hello" }], "provider": "prime-inference", "model": "internal/glm-5.3-fast", "usage": usage}}),- ]- .iter()- .map(std::string::ToString::to_string)- .collect::<Vec<_>>()- .join("\n");- std::fs::write(&session_file, content).unwrap();- // The artifact tree lives under the worker's agent dir (the writer's- // addressing): one settled child with a grandchild in the child's own- // sibling tree.- let artifacts = agent_dir.join("session-artifacts");- let child_session = "01a0child-1111-2222-3333-4444444444";- let grandchild_session = "01a0grand-1111-2222-3333-4444444444";- let write_child = |stop: &str| {- [- json!({"type": "message", "id": "c1", "parentId": null, "timestamp": "2026-09-22T00:00:01.000Z", "message": {"role": "user", "content": "fix the login bug"}}),- json!({"type": "message", "id": "c2", "parentId": "c1", "timestamp": "2026-09-22T00:00:02.000Z", "message": {"role": "assistant", "content": [{ "type": "text", "text": "done" }], "provider": "prime-inference", "model": "internal/glm-5.3-fast", "stopReason": stop, "usage": {"input": 10, "output": 5, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 15, "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0}}}}),- ]- };- let write_session = |dir: &std::path::Path, session: &str, stop: &str| {- std::fs::create_dir_all(dir).unwrap();- let mut lines = vec![- json!({"type": "session", "version": 3, "id": session, "timestamp": "2026-09-22T00:00:00.000Z", "cwd": "/tmp"}),- ];- lines.extend(write_child(stop));- std::fs::write(- dir.join(format!("{session}.jsonl")),- lines- .iter()- .map(std::string::ToString::to_string)- .collect::<Vec<_>>()- .join("\n"),- )- .unwrap();- };- let child_dir = artifacts.join(session_id).join("sub-003f741a");- write_session(&child_dir, child_session, "stop");- let grandchild_dir = artifacts.join(child_session).join("sub-00aa00aa");- write_session(&grandchild_dir, grandchild_session, "stop");- // A second child the user deleted: the ledger tombstone must keep it- // out of the tree.- let deleted_dir = artifacts.join(session_id).join("sub-deadbeef");- let deleted_session = "01a0dead-1111-2222-3333-4444444444";- write_session(&deleted_dir, deleted_session, "stop");- let ledger = crate::rlm_ledger::RlmSpawnLedger::new(&agent_dir, &sessions, |_| {});- ledger- .append_spawn(&crate::rlm_ledger::RlmSpawnInput {- child_id: "sub-deadbeef".to_string(),- parent: session_file.display().to_string(),- child: deleted_dir.display().to_string(),- depth: 1,- name: "deleted-child".to_string(),- })- .unwrap();- ledger- .append_delete(- "sub-deadbeef",- &deleted_dir.display().to_string(),- crate::rlm_ledger::RlmLedgerDeleteReason::User,- )- .unwrap();-- let worker = created_worker_at(&root, &session_file).await;- // The children come from the background cache refresh (the create- // warm armed it): a cold read serves the root from memory- // instantly, and the persisted tree fills when the walk lands.- let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);- let children = loop {- let response = worker- .dispatch(- "get_context_tree",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success, "failed: {response:?}");- let tree = response.data.expect("data");- assert_eq!(- tree["ownUsage"]["input"],- json!(30),- "the root usage counts"- );- let children = tree["children"].as_array().cloned().unwrap_or_default();- if children.len() == 1 || std::time::Instant::now() > deadline {- break children;- }- tokio::time::sleep(std::time::Duration::from_millis(50)).await;- };- assert_eq!(- children.len(),- 1,- "the persisted child appears, the deleted one stays hidden: {children:?}"- );- let child = &children[0];- assert_eq!(child["id"], json!("sub-003f741a"));- assert_eq!(child["status"], json!("done"));- assert_eq!(child["label"], json!("fix the login bug"));- assert_eq!(child["ownUsage"]["totalTokens"], json!(15));- let grandchildren = child["children"].as_array().expect("grandchildren");- assert_eq!(grandchildren.len(), 1);- assert_eq!(grandchildren[0]["id"], json!("sub-00aa00aa"));- assert_eq!(grandchildren[0]["ownUsage"]["totalTokens"], json!(15));- let _ = std::fs::remove_dir_all(&root);- }-- /// The own/total split (TS `computeOwnAndTotalUsage`): attributions- /// subtract from own usage only, matched by target across every entry.- #[test]- fn own_usage_subtracts_child_attributions() {- let assistant = json!({- "type": "message", "id": "m1",- "message": {- "role": "assistant", "content": "text",- "usage": {- "input": 100, "output": 10, "cacheRead": 0, "cacheWrite": 0,- "totalTokens": 110,- "cost": { "input": 1, "output": 2, "cacheRead": 0, "cacheWrite": 0, "total": 3 },- },- },- });- let attribution = json!({- "type": "child_usage_attributed", "id": "a1",- "targetId": "m1",- "childUsage": {- "input": 40, "output": 5, "cacheRead": 0, "cacheWrite": 0,- "totalTokens": 45,- "cost": { "input": 0.5, "output": 1, "cacheRead": 0, "cacheWrite": 0, "total": 1.5 },- },- });- let entry = |value: &Value, id: &str| crate::session_store::SessionEntry {- type_: value["type"].as_str().expect("type").to_string(),- id: id.to_string(),- parent_id: None,- timestamp: "2024-01-01T00:00:00.000Z".to_string(),- fields: value- .as_object()- .expect("object")- .clone()- .into_iter()- .collect(),- };- let assistant_entry = entry(&assistant, "m1");- let attribution_entry = entry(&attribution, "a1");- let entries = vec![- assistant_entry.clone(),- attribution_entry.clone(),- attribution_entry.clone(),- ];- let branch_refs: Vec<&crate::session_store::SessionEntry> = entries.iter().collect();- let (own, total) = compute_own_and_total_usage(&branch_refs, &entries);- assert_eq!(total["input"], json!(100));- assert_eq!(total["totalTokens"], json!(110));- assert_eq!(own["input"], json!(20), "two attributions subtract twice");- // Subtraction clamps at zero instead of going negative (TS- // attribution-drift guard).- let entries_more = vec![- assistant_entry,- attribution_entry.clone(),- attribution_entry.clone(),- attribution_entry.clone(),- attribution_entry.clone(),- attribution_entry,- ];- let branch_refs_more: Vec<&crate::session_store::SessionEntry> =- entries_more.iter().collect();- let (own, _) = compute_own_and_total_usage(&branch_refs_more, &entries_more);- assert_eq!(own["input"], json!(0));- assert_eq!(own["cost"]["total"].as_f64(), Some(0.0));- }-- /// A `branch_summary` row served by an auxiliary model (TS #2411)- /// bills on the model its entry records, not the branch timeline's- /// current model: the routed call billed at the auxiliary model's- /// rates, so its spend belongs to that model's bucket while the- /// buckets still reconcile with the plain own-usage fold (the- /// Macroscope wrong-bucket round).- #[test]- fn branch_summary_usage_bills_on_the_row_recorded_auxiliary_model() {- let entry = |value: &Value, id: &str| crate::session_store::SessionEntry {- type_: value["type"].as_str().expect("type").to_string(),- id: id.to_string(),- parent_id: None,- timestamp: "2024-01-01T00:00:00.000Z".to_string(),- fields: value- .as_object()- .expect("object")- .clone()- .into_iter()- .collect(),- };- let usage = |input: u64, output: u64| {- json!({- "input": input, "output": output, "cacheRead": 0, "cacheWrite": 0,- "totalTokens": input + output,- "cost": {"input": 0.1, "output": 0.2, "cacheRead": 0, "cacheWrite": 0, "total": 0.3},- })- };- let entries = vec![- entry(- &json!({"type": "model_change", "provider": "openai", "modelId": "gpt-a"}),- "m0",- ),- entry(- &json!({- "type": "message",- "message": {"role": "assistant", "content": "on it", "provider": "openai", "model": "gpt-a", "usage": usage(100, 10)},- }),- "e1",- ),- entry(- &json!({- "type": "branch_summary",- "summary": "explored",- "usage": usage(50, 5),- "provider": "anthropic",- "modelId": "aux-opus-4",- }),- "b1",- ),- ];- let branch: Vec<&crate::session_store::SessionEntry> = entries.iter().collect();- let (own, _) = compute_own_and_total_usage(&branch, &entries);- let breakdown =- compute_own_usage_by_model(&branch, &entries, &own, None).expect("resolved");- assert_eq!(breakdown.len(), 2);- assert_eq!(breakdown[0]["provider"], json!("openai"));- assert_eq!(breakdown[0]["id"], json!("gpt-a"));- assert_eq!(breakdown[0]["ownUsage"]["totalTokens"], json!(110));- // The auxiliary summary lands on the routed model's bucket, not- // the timeline's current model.- assert_eq!(breakdown[1]["provider"], json!("anthropic"));- assert_eq!(breakdown[1]["id"], json!("aux-opus-4"));- assert_eq!(breakdown[1]["ownUsage"]["totalTokens"], json!(55));- }-- /// A windowed load (a reopened compacted session) seeds the timeline- /// with the retained-window boundary's model: retained usage rows- /// before the branch's first `model_change` still resolve a bucket and- /// the breakdown is served instead of omitted — the target case this- /// change exists for (the Bugbot windowed-omission round). The same- /// walk without a seed (a full-history foreign file without- /// `model_change` rows) keeps omitting the breakdown.- #[test]- fn window_seed_resolves_rows_before_the_first_model_change() {- let entry = |value: &Value, id: &str| crate::session_store::SessionEntry {- type_: value["type"].as_str().expect("type").to_string(),- id: id.to_string(),- parent_id: None,- timestamp: "2024-01-01T00:00:00.000Z".to_string(),- fields: value- .as_object()- .expect("object")- .clone()- .into_iter()- .collect(),- };- let usage = |input: u64, output: u64| {- json!({- "input": input, "output": output, "cacheRead": 0, "cacheWrite": 0,- "totalTokens": input + output,- "cost": {"input": 0.1, "output": 0.2, "cacheRead": 0, "cacheWrite": 0, "total": 0.3},- })- };- // The retained branch starts at the compaction boundary: the- // summarizer's usage row carries no model of its own (an- // unattributed row) and no `model_change` row precedes it on the walk.- let entries = vec![- entry(- &json!({"type": "branch_summary", "summary": "cut", "usage": usage(30, 3)}),- "b1",- ),- entry(- &json!({- "type": "message",- "message": {"role": "assistant", "content": "resumed", "provider": "openai", "model": "gpt-a", "usage": usage(100, 10)},- }),- "e1",- ),- ];- let branch: Vec<&crate::session_store::SessionEntry> = entries.iter().collect();- let (own, _) = compute_own_and_total_usage(&branch, &entries);- let seeded = compute_own_usage_by_model(- &branch,- &entries,- &own,- Some(&("openai".to_string(), "gpt-a".to_string())),- )- .expect("the seed resolves the boundary rows");- assert_eq!(seeded.len(), 1);- assert_eq!(seeded[0]["provider"], json!("openai"));- assert_eq!(seeded[0]["id"], json!("gpt-a"));- assert_eq!(seeded[0]["ownUsage"]["totalTokens"], json!(143));- // The unseeded walk keeps the foreign-file contract: a branch- // whose usage rows resolve to no model omits the breakdown.- assert_eq!(- compute_own_usage_by_model(&branch, &entries, &own, None),- None- );- }-- /// `get_commands` / `get_resource_snapshot` on the scripted engine:- /// the TS loader shapes over empty lists.- #[tokio::test]- async fn commands_and_resources_match_the_empty_loader_shape() {- let worker = created_worker().await;- let response = worker- .dispatch(- "get_commands",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success);- assert_eq!(response.data.expect("data"), json!({ "commands": [] }));- let response = worker- .dispatch(- "get_resource_snapshot",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success);- assert_eq!(- response.data.expect("data"),- crate::engine::empty_resource_snapshot()- );- }-- /// `get_session_context`: the resolved context at the leaf — messages,- /// effective thinking level, service tier, and model selector.- #[tokio::test]- async fn get_session_context_matches_the_ts_context_shape() {- let worker = created_worker().await;- let response = worker- .dispatch(- "get_session_context",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success, "failed: {response:?}");- let context = response.data.expect("data")["context"].clone();- assert!(context.get("messages").is_some());- assert!(context.get("thinkingLevel").is_some());- assert!(context.get("serviceTier").is_some());- assert!(context.get("model").is_some());-- // One turn lands its accepted user message on the resolved- // context. (The scripted harness's synthetic assistant row carries- // no stop reason, so it does not round-trip into the typed entry- // form the walk consumes; real engine rows do.)- let _ = worker- .dispatch(- "prompt_and_wait",- &json!({ "activeSessionId": "getter-session", "message": "hello" }),- )- .await;- let response = worker- .dispatch(- "get_session_context",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- let context = response.data.expect("data")["context"].clone();- let roles: Vec<String> = context["messages"]- .as_array()- .expect("messages array")- .iter()- .filter_map(|message| {- message- .get("role")- .and_then(Value::as_str)- .map(str::to_string)- })- .collect();- assert!(roles.iter().any(|role| role == "user"));- assert_eq!(context["messages"][0]["content"], json!("hello"));- }-- /// `get_system_prompt` / `get_tool_definition`: the scripted engine- /// has no prompt (empty string, the TS key present) and no tools (the- /// `toolDefinition` key omitted, like the TS `undefined` field).- #[tokio::test]- async fn system_prompt_and_tool_definition_match_the_ts_shapes() {- let worker = created_worker().await;- let response = worker- .dispatch(- "get_system_prompt",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success);- assert_eq!(response.data.expect("data"), json!({ "systemPrompt": "" }));-- let response = worker- .dispatch(- "get_tool_definition",- &json!({ "activeSessionId": "getter-session", "name": "ipython" }),- )- .await;- assert!(response.success);- assert_eq!(response.data.expect("data"), json!({}));-- let response = worker- .dispatch(- "get_tool_definition",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(!response.success);- assert_eq!(- response.error.as_deref(),- Some("get_tool_definition requires a name")- );- }-- /// `get_rlm_max_depth_status`: the TS source vocabulary (the b6 wave- /// replaced the provisional "settings" label; an unseeded scripted- /// session reports the shared default).- #[tokio::test]- async fn rlm_max_depth_status_matches_the_ts_shape() {- let worker = created_worker().await;- let response = worker- .dispatch(- "get_rlm_max_depth_status",- &json!({ "activeSessionId": "getter-session" }),- )- .await;- assert!(response.success);- assert_eq!(- response.data.expect("data"),- json!({ "maxDepth": crate::rlm_children::DEFAULT_RLM_MAX_DEPTH, "source": "default" })- );- }-- /// `get_model_catalog` / `get_available_models` against a fixture- /// registry (TS `refreshModelCatalog` / `refreshAvailableModels`).- #[tokio::test]- async fn model_catalog_and_available_models_match_the_ts_shapes() {- let dir = tempfile::tempdir().expect("tempdir");- std::fs::create_dir_all(dir.path().join("agent")).expect("agent dir");- std::fs::write(- dir.path().join("agent").join("models.json"),- json!({- "providers": {- "prime-inference": {- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:9/v1",- "apiKey": "sk-test",- "models": [- { "id": "mock-1", "name": "Mock 1", "api": "openai-completions",- "baseUrl": "http://127.0.0.1:9/v1", "contextWindow": 128_000,- "maxTokens": 4096 },- { "id": "mock-2", "name": "Mock 2", "api": "openai-completions",- "baseUrl": "http://127.0.0.1:9/v1", "contextWindow": 128_000,- "maxTokens": 4096 }- ]- }- }- })- .to_string(),- )- .expect("write models.json");- let config = crate::worker::WorkerConfig {- socket_path: dir.path().join("worker.sock"),- supervisor_socket_path: std::path::PathBuf::new(),- token: "token".to_string(),- worker_instance_id: String::new(),- active_session_id: "catalog-session".to_string(),- agent_dir: dir.path().join("agent"),- recovery_journal_path: dir.path().join("recovery.jsonl"),- telemetry_disabled: None,- script: Some(json!({ "responses": ["ack"] })),- };- let worker = Arc::new(Worker::new(config, None));- let created = worker- .dispatch("create", &json!({ "noSession": true, "cwd": "/tmp" }))- .await;- assert!(created.success, "create failed: {created:?}");-- let response = worker- .dispatch(- "get_model_catalog",- &json!({ "activeSessionId": "catalog-session" }),- )- .await;- assert!(response.success, "failed: {response:?}");- let catalog = response.data.expect("data");- assert_eq!(- catalog["models"]- .as_array()- .expect("models")- .iter()- .filter(|model| model["id"] == json!("mock-1"))- .count(),- 1- );- assert_eq!(catalog["configuredProviders"], json!(["prime-inference"]));-- let response = worker- .dispatch(- "get_available_models",- &json!({ "activeSessionId": "catalog-session" }),- )- .await;- assert!(response.success);- let available = response.data.expect("data");- let models = available["models"].as_array().expect("models");- // The registry also serves the built-in catalog when the box has- // configured auth for it; the fixture provider must be complete.- assert!(- models- .iter()- .filter(|model| model["provider"] == json!("prime-inference"))- .count()- >= 2- );- assert!(models.iter().any(|model| model["id"] == json!("mock-1")));- }-}+mod 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.rsnew file mode 100644index 0000000000..b8e2da65ab--- /dev/null+++ b/crates/pa-daemon/src/state_getters/state_getters_tests.rs@@ -0,0 +1,820 @@+//! The getter test battery (moved with its concern): the TS wire shapes of+//! every `get_*` handler - the connection state, the rlm children sequence,+//! the context tree folds, the session context, the model catalog, and the+//! empty-loader shapes - over the shared `created_worker` fixtures.++use super::*;+use serde_json::json;+use std::sync::Arc;++/// A created worker backed by an existing session file (the store's+/// path, so the artifact tree beside it resolves).+async fn created_worker_at(root: &std::path::Path, session_file: &std::path::Path) -> Arc<Worker> {+ std::fs::create_dir_all(root).unwrap();+ let config = crate::worker::WorkerConfig {+ socket_path: root.join("worker.sock"),+ supervisor_socket_path: std::path::PathBuf::new(),+ token: "token".to_string(),+ worker_instance_id: String::new(),+ active_session_id: "getter-session".to_string(),+ agent_dir: root.join("agent"),+ recovery_journal_path: root.join("recovery.jsonl"),+ telemetry_disabled: None,+ script: Some(json!({ "responses": ["ack"] })),+ };+ let worker = Arc::new(Worker::new(config, None));+ let created = worker+ .dispatch(+ "create",+ &json!({+ "sessionPath": session_file.display().to_string(),+ "cwd": "/tmp",+ "name": "getters",+ }),+ )+ .await;+ assert!(created.success, "create failed: {created:?}");+ worker+}++async fn created_worker() -> Arc<Worker> {+ let dir = std::env::temp_dir().join(format!("pa-worker-sg-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let config = crate::worker::WorkerConfig {+ socket_path: dir.join("worker.sock"),+ supervisor_socket_path: std::path::PathBuf::new(),+ token: "token".to_string(),+ worker_instance_id: String::new(),+ active_session_id: "getter-session".to_string(),+ agent_dir: dir.join("agent"),+ recovery_journal_path: dir.join("recovery.jsonl"),+ telemetry_disabled: None,+ script: Some(json!({ "responses": ["ack"] })),+ };+ let worker = Arc::new(Worker::new(config, None));+ let created = worker+ .dispatch(+ "create",+ &json!({ "noSession": true, "cwd": "/tmp", "name": "getters" }),+ )+ .await;+ assert!(created.success, "create failed: {created:?}");+ worker+}++/// `get_connection_state` answers the TS `AgentConnectionState` block+/// with the daemon overlay: `heartbeat` is present and null (no cron+/// store on this worker).+#[tokio::test]+async fn get_connection_state_matches_the_ts_shape() {+ let worker = created_worker().await;+ let response = worker+ .dispatch(+ "get_connection_state",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success, "failed: {response:?}");+ let data = response.data.expect("connection state data");+ assert_eq!(data["activeSessionId"], "getter-session");+ assert_eq!(data["cwd"], "/tmp");+ assert_eq!(data["heartbeat"], Value::Null);+ for field in [+ "thinkingLevel",+ "serviceTier",+ "availableThinkingLevels",+ "isStreaming",+ "isCompacting",+ "isBashRunning",+ "retryAttempt",+ "steeringMode",+ "followUpMode",+ "sessionId",+ "leafId",+ "autoCompactionEnabled",+ "messageCount",+ "sessionActions",+ "compactionCount",+ "goal",+ "scopedModels",+ "activeToolNames",+ ] {+ assert!(data.get(field).is_some(), "missing {field}: {data}");+ }+ // A session that has not been created answers the TS+ // initializing refusal.+ let fresh = Arc::new(Worker::new(+ {+ let mut config = worker.config.clone();+ config.active_session_id = "fresh-session".to_string();+ config+ },+ None,+ ));+ let response = fresh+ .dispatch(+ "get_connection_state",+ &json!({ "activeSessionId": "fresh-session" }),+ )+ .await;+ assert!(!response.success);+ assert_eq!(+ response.error.as_deref(),+ Some("Session is still initializing")+ );+}++/// `get_rlm_children`: the child roster plus the pre-walk event+/// sequence; a worker without children answers the empty roster.+#[tokio::test]+async fn get_rlm_children_carries_the_sequence() {+ let worker = created_worker().await;+ let response = worker+ .dispatch(+ "get_rlm_children",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success, "failed: {response:?}");+ let data = response.data.expect("data");+ assert_eq!(data["children"], json!([]));+ let sequence = data["eventSequence"].as_u64().expect("event sequence");+ // A subsequent read captures the same sequence until an event+ // bumps it (TS freshness contract).+ let again = worker+ .dispatch(+ "get_rlm_children",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert_eq!(again.data.expect("data")["eventSequence"], json!(sequence));+}++/// `get_context_tree`: the root node with usage totals over the+/// persisted branch; child attributions move the split between+/// `ownUsage` and `totalUsage` (TS `computeOwnAndTotalUsage`).+#[tokio::test]+async fn get_context_tree_matches_the_ts_root_node() {+ let worker = created_worker().await;+ let response = worker+ .dispatch(+ "get_context_tree",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success, "failed: {response:?}");+ let tree = response.data.expect("data");+ assert_eq!(tree["id"], "root");+ assert_eq!(tree["label"], "getters");+ assert_eq!(tree["status"], "active");+ assert_eq!(tree["children"], json!([]));+ assert_eq!(tree["ownUsage"]["totalTokens"], json!(0));++ // One assistant turn seeds usage totals (the scripted usage block).+ let _ = worker+ .dispatch(+ "prompt_and_wait",+ &json!({ "activeSessionId": "getter-session", "message": "hi" }),+ )+ .await;+ let response = worker+ .dispatch(+ "get_context_tree",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ let tree = response.data.expect("data");+ assert_eq!(tree["ownUsage"]["input"], json!(120));+ assert_eq!(tree["totalUsage"]["totalTokens"], json!(128));+ assert_eq!(tree["totalUsage"]["cost"]["total"].as_f64(), Some(0.0));+}++/// The captured-attribution fixture over the full daemon path (create+/// from a copy of the fixture file, so the repo fixture stays+/// read-only): the load-time fold makes the root's own/total split+/// TS-exact. `ownUsage` is the assistant's own row (input 2690, cost+/// $0 — `totalTokens` clamps to zero because the six attributions'+/// child `totalTokens` (54289) exceeds the aggregate's unchanged+/// 23032, TS `subtractAssistantUsage`'s clamp); `totalUsage` carries+/// the attributed child spend (input 52898, cost $0.0089957,+/// `totalTokens` stays 23032).+#[tokio::test]+async fn get_context_tree_folds_the_captured_attributions() {+ let root = std::env::temp_dir().join(format!("pa-worker-af-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&root).unwrap();+ let fixture = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("tests/fixtures/attribution-fold-captured.jsonl");+ let session_file = root.join("captured.jsonl");+ std::fs::copy(&fixture, &session_file).unwrap();+ let worker = created_worker_at(&root, &session_file).await;+ let response = worker+ .dispatch(+ "get_context_tree",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success, "failed: {response:?}");+ let tree = response.data.expect("data");+ assert_eq!(tree["ownUsage"]["input"], json!(2690));+ assert_eq!(tree["ownUsage"]["output"], json!(2934));+ assert_eq!(tree["ownUsage"]["cacheRead"], json!(17408));+ assert_eq!(tree["ownUsage"]["totalTokens"], json!(0));+ // The six sequential per-entry subtractions leave float-order noise+ // in the last ulps (TS `subtractAssistantUsage` walks the same+ // order), so own cost pins at ~0, not bit-exact zero.+ assert!(+ tree["ownUsage"]["cost"]["total"].as_f64().unwrap().abs() < 1e-12,+ "own cost {} is not ~0",+ tree["ownUsage"]["cost"]["total"]+ );+ assert_eq!(tree["totalUsage"]["input"], json!(52898));+ assert_eq!(tree["totalUsage"]["output"], json!(5863));+ assert_eq!(tree["totalUsage"]["cacheRead"], json!(18560));+ assert_eq!(tree["totalUsage"]["totalTokens"], json!(23032));+ assert_eq!(+ tree["totalUsage"]["cost"]["total"].as_f64(),+ Some(0.008_995_7)+ );+ // `get_session_stats` reports the same folded totals over the+ // gap-bridged branch.+ let stats = worker+ .dispatch(+ "get_session_stats",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(stats.success, "failed: {stats:?}");+ let stats = stats.data.expect("data");+ assert_eq!(stats["tokens"]["input"], json!(52898));+ assert_eq!(stats["tokens"]["output"], json!(5863));+ assert_eq!(stats["tokens"]["cacheRead"], json!(18560));+ assert_eq!(stats["cost"].as_f64(), Some(0.008_995_7));+}++/// The operator's cost question, proven over the real file path: a+/// session that switches models mid-conversation accumulates the+/// correct per-model costs INCLUDING the switch's cache-write burst.+/// The synthetic file's cost blocks are the provider-computed records+/// (`calculate_cost` against the catalog rates: gpt-5.6-sol $4/$20 per+/// M; claude-opus-4-6 $5/$25/M, cacheRead $0.5/M, cacheWrite $6.25/M+/// = the 1.25x write multiplier): the sol turn bills $0.44; the first+/// opus request re-caches the whole history — 104k cache-write tokens+/// at $6.25/M = $0.65 exactly — and bills $0.70; the next opus turn+/// hits the cache ($0.0775). The per-model buckets carry each model's+/// share with the fold's exact float sums, and the grand totals are+/// per-model-summed across the switch.+#[tokio::test]+async fn get_context_tree_breaks_own_usage_down_by_model() {+ let root = std::env::temp_dir().join(format!("pa-worker-bm-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&root).unwrap();+ let session_file = root.join("switched.jsonl");+ let usage = |input: u64,+ output: u64,+ cache_read: u64,+ cache_write: u64,+ total: u64,+ (ci, co, cr, cw, ct): (f64, f64, f64, f64, f64)| {+ json!({+ "input": input, "output": output, "cacheRead": cache_read,+ "cacheWrite": cache_write, "totalTokens": total,+ "cost": {"input": ci, "output": co, "cacheRead": cr,+ "cacheWrite": cw, "total": ct},+ })+ };+ let lines = [+ json!({"type": "session", "version": 3, "id": "switched-0001", "timestamp": "2026-09-24T00:00:00.000Z", "cwd": "/tmp"}),+ json!({"type": "model_change", "id": "m0", "parentId": null, "timestamp": "2026-09-24T00:00:00.100Z", "provider": "openai", "modelId": "gpt-5.6-sol"}),+ json!({"type": "message", "id": "e1", "parentId": "m0", "timestamp": "2026-09-24T00:00:01.000Z", "message": {"role": "user", "content": "audit the costs"}}),+ json!({"type": "message", "id": "e2", "parentId": "e1", "timestamp": "2026-09-24T00:00:02.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "on it"}], "provider": "openai", "model": "gpt-5.6-sol", "stopReason": "stop", "usage": usage(100_000, 2000, 0, 0, 1200, (0.4, 0.04, 0.0, 0.0, 0.44))}}),+ json!({"type": "model_change", "id": "m1", "parentId": "e2", "timestamp": "2026-09-24T00:00:03.000Z", "provider": "anthropic", "modelId": "claude-opus-4-6"}),+ json!({"type": "message", "id": "e3", "parentId": "m1", "timestamp": "2026-09-24T00:00:04.000Z", "message": {"role": "user", "content": "switch to opus"}}),+ json!({"type": "message", "id": "e4", "parentId": "e3", "timestamp": "2026-09-24T00:00:05.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "done"}], "provider": "anthropic", "model": "claude-opus-4-6", "stopReason": "stop", "usage": usage(5000, 1000, 0, 104_000, 110_000, (0.025, 0.025, 0.0, 0.65, 0.7))}}),+ json!({"type": "message", "id": "e5", "parentId": "e4", "timestamp": "2026-09-24T00:00:06.000Z", "message": {"role": "user", "content": "and now a cache hit"}}),+ json!({"type": "message", "id": "e6", "parentId": "e5", "timestamp": "2026-09-24T00:00:07.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "cheap"}], "provider": "anthropic", "model": "claude-opus-4-6", "stopReason": "stop", "usage": usage(500, 800, 110_000, 0, 110_500, (0.0025, 0.02, 0.055, 0.0, 0.0775))}}),+ ];+ let content = lines+ .iter()+ .map(std::string::ToString::to_string)+ .collect::<Vec<_>>()+ .join("\n");+ std::fs::write(&session_file, content).unwrap();+ let worker = created_worker_at(&root, &session_file).await;+ let response = worker+ .dispatch(+ "get_context_tree",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success, "failed: {response:?}");+ let tree = response.data.expect("data");+ // The grand totals sum every record's stored cost — the honest+ // per-model-summed total across the switch.+ assert_eq!(tree["ownUsage"]["input"], json!(105_500));+ assert_eq!(tree["ownUsage"]["output"], json!(3800));+ assert_eq!(tree["ownUsage"]["cacheRead"], json!(110_000));+ assert_eq!(tree["ownUsage"]["cacheWrite"], json!(104_000));+ assert_eq!(tree["ownUsage"]["totalTokens"], json!(221_700));+ assert_eq!(+ tree["ownUsage"]["cost"]["total"].as_f64(),+ Some(0.4 + 0.04 + 0.7 + 0.0775)+ );+ // The per-model breakdown: first-seen order, each bucket holding+ // exactly the records that model served.+ let buckets = tree["ownUsageByModel"]+ .as_array()+ .expect("the by-model breakdown is present");+ assert_eq!(buckets.len(), 2);+ assert_eq!(buckets[0]["provider"], json!("openai"));+ assert_eq!(buckets[0]["id"], json!("gpt-5.6-sol"));+ assert_eq!(buckets[0]["ownUsage"]["input"], json!(100_000));+ assert_eq!(buckets[0]["ownUsage"]["output"], json!(2000));+ assert_eq!(buckets[0]["ownUsage"]["cacheWrite"], json!(0));+ assert_eq!(+ buckets[0]["ownUsage"]["cost"]["total"].as_f64(),+ Some(0.4 + 0.04)+ );+ assert_eq!(buckets[1]["provider"], json!("anthropic"));+ assert_eq!(buckets[1]["id"], json!("claude-opus-4-6"));+ assert_eq!(buckets[1]["ownUsage"]["input"], json!(5500));+ assert_eq!(buckets[1]["ownUsage"]["output"], json!(1800));+ assert_eq!(buckets[1]["ownUsage"]["cacheRead"], json!(110_000));+ assert_eq!(buckets[1]["ownUsage"]["cacheWrite"], json!(104_000));+ // The switch's cache-write burst bills at the new model's write+ // rate: 104k tokens x $6.25/M (1.25x the $5/M input rate) is+ // exactly $0.65.+ assert_eq!(+ buckets[1]["ownUsage"]["cost"]["cacheWrite"].as_f64(),+ Some(104_000.0 * 6.25 / 1_000_000.0)+ );+ assert_eq!(+ buckets[1]["ownUsage"]["cost"]["total"].as_f64(),+ Some(0.7 + 0.0775)+ );+}++/// The buckets reconcile or the breakdown is omitted: a child+/// attribution whose `totalTokens` exceed its target row's bucket+/// (the captured-fixture shape — the child's token deltas do not+/// ride the row's aggregate) clamps inside that bucket, while the+/// plain own-usage fold subtracts the same amount from the combined+/// pool where the other model's spend absorbs it. The buckets would+/// sum past `ownUsage`, so `ownUsageByModel` is omitted and the+/// display degrades to the plain totals instead of overstating the+/// node (the Macroscope attribution-clamp round).+#[tokio::test]+async fn get_context_tree_omits_the_breakdown_when_an_attribution_exceeds_its_bucket() {+ let root = std::env::temp_dir().join(format!("pa-worker-bmx-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&root).unwrap();+ let session_file = root.join("clamped.jsonl");+ let usage = |input: u64, output: u64, total: u64| {+ json!({+ "input": input, "output": output, "cacheRead": 0, "cacheWrite": 0,+ "totalTokens": total,+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0},+ })+ };+ let lines = [+ json!({"type": "session", "version": 3, "id": "clamped-0001", "timestamp": "2026-09-25T00:00:00.000Z", "cwd": "/tmp"}),+ json!({"type": "model_change", "id": "m0", "parentId": null, "timestamp": "2026-09-25T00:00:00.100Z", "provider": "openai", "modelId": "gpt-5.6-sol"}),+ json!({"type": "message", "id": "e1", "parentId": "m0", "timestamp": "2026-09-25T00:00:01.000Z", "message": {"role": "user", "content": "audit the mix"}}),+ json!({"type": "message", "id": "e2", "parentId": "e1", "timestamp": "2026-09-25T00:00:02.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "on it"}], "provider": "openai", "model": "gpt-5.6-sol", "stopReason": "stop", "usage": usage(1_000, 100, 1_100)}}),+ json!({"type": "model_change", "id": "m1", "parentId": "e2", "timestamp": "2026-09-25T00:00:03.000Z", "provider": "anthropic", "modelId": "claude-opus-4-6"}),+ json!({"type": "message", "id": "e3", "parentId": "m1", "timestamp": "2026-09-25T00:00:04.000Z", "message": {"role": "user", "content": "big opus turn"}}),+ json!({"type": "message", "id": "e4", "parentId": "e3", "timestamp": "2026-09-25T00:00:05.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "done"}], "provider": "anthropic", "model": "claude-opus-4-6", "stopReason": "stop", "usage": usage(100_000, 2_000, 102_000)}}),+ // The child's input/output ride the cumulative aggregate; the+ // totalTokens do not (the row keeps its own 1_100).+ json!({"type": "child_usage_attributed", "id": "a1", "parentId": "e4", "timestamp": "2026-09-25T00:00:06.000Z", "targetId": "e2",+ "childUsage": usage(3_000, 300, 9_000),+ "aggregateUsage": usage(4_000, 400, 1_100),+ "origin": "spawn_task"}),+ ];+ let content = lines+ .iter()+ .map(std::string::ToString::to_string)+ .collect::<Vec<_>>()+ .join("\n");+ std::fs::write(&session_file, content).unwrap();+ let worker = created_worker_at(&root, &session_file).await;+ let response = worker+ .dispatch(+ "get_context_tree",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success, "failed: {response:?}");+ let tree = response.data.expect("data");+ // The plain fold subtracts the 9_000 tokens from the combined+ // pool: 1_100 + 102_000 - 9_000. The input and output fields+ // reconcile exactly (the attribution rides the aggregate), so a+ // mismatch here would mean the reconciliation itself drifted.+ assert_eq!(tree["ownUsage"]["input"], json!(101_000));+ assert_eq!(tree["ownUsage"]["output"], json!(2_100));+ assert_eq!(tree["ownUsage"]["totalTokens"], json!(94_100));+ // The sol bucket clamps at zero while the opus bucket keeps its+ // 102_000: the buckets would sum to 102_000 and overstate the+ // node's 94_100, so the breakdown is omitted.+ assert!(+ tree["ownUsageByModel"].is_null(),+ "the clamped breakdown must not be served: {}",+ tree["ownUsageByModel"]+ );+}++/// The control for the omission rule: an attribution that fits its+/// target row's bucket reconciles (the buckets sum to `ownUsage`+/// exactly) and the breakdown stays served.+#[tokio::test]+async fn get_context_tree_keeps_the_breakdown_when_an_attribution_fits_its_bucket() {+ let root = std::env::temp_dir().join(format!("pa-worker-bmf-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&root).unwrap();+ let session_file = root.join("fits.jsonl");+ let usage = |input: u64, output: u64, total: u64| {+ json!({+ "input": input, "output": output, "cacheRead": 0, "cacheWrite": 0,+ "totalTokens": total,+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0},+ })+ };+ let lines = [+ json!({"type": "session", "version": 3, "id": "fits-0001", "timestamp": "2026-09-25T00:00:00.000Z", "cwd": "/tmp"}),+ json!({"type": "model_change", "id": "m0", "parentId": null, "timestamp": "2026-09-25T00:00:00.100Z", "provider": "openai", "modelId": "gpt-5.6-sol"}),+ json!({"type": "message", "id": "e1", "parentId": "m0", "timestamp": "2026-09-25T00:00:01.000Z", "message": {"role": "user", "content": "audit the mix"}}),+ json!({"type": "message", "id": "e2", "parentId": "e1", "timestamp": "2026-09-25T00:00:02.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "on it"}], "provider": "openai", "model": "gpt-5.6-sol", "stopReason": "stop", "usage": usage(1_000, 100, 1_100)}}),+ json!({"type": "model_change", "id": "m1", "parentId": "e2", "timestamp": "2026-09-25T00:00:03.000Z", "provider": "anthropic", "modelId": "claude-opus-4-6"}),+ json!({"type": "message", "id": "e3", "parentId": "m1", "timestamp": "2026-09-25T00:00:04.000Z", "message": {"role": "user", "content": "big opus turn"}}),+ json!({"type": "message", "id": "e4", "parentId": "e3", "timestamp": "2026-09-25T00:00:05.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "done"}], "provider": "anthropic", "model": "claude-opus-4-6", "stopReason": "stop", "usage": usage(100_000, 2_000, 102_000)}}),+ json!({"type": "child_usage_attributed", "id": "a1", "parentId": "e4", "timestamp": "2026-09-25T00:00:06.000Z", "targetId": "e2",+ "childUsage": usage(3_000, 300, 500),+ "aggregateUsage": usage(4_000, 400, 1_100),+ "origin": "spawn_task"}),+ ];+ let content = lines+ .iter()+ .map(std::string::ToString::to_string)+ .collect::<Vec<_>>()+ .join("\n");+ std::fs::write(&session_file, content).unwrap();+ let worker = created_worker_at(&root, &session_file).await;+ let response = worker+ .dispatch(+ "get_context_tree",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success, "failed: {response:?}");+ let tree = response.data.expect("data");+ assert_eq!(tree["ownUsage"]["totalTokens"], json!(102_600));+ let buckets = tree["ownUsageByModel"]+ .as_array()+ .expect("the fitting breakdown is served");+ assert_eq!(buckets.len(), 2);+ assert_eq!(buckets[0]["id"], json!("gpt-5.6-sol"));+ assert_eq!(buckets[0]["ownUsage"]["input"], json!(1_000));+ assert_eq!(buckets[0]["ownUsage"]["totalTokens"], json!(600));+ assert_eq!(buckets[1]["id"], json!("claude-opus-4-6"));+ assert_eq!(buckets[1]["ownUsage"]["totalTokens"], json!(102_000));+}++/// `get_context_tree` surfaces the persisted child sessions under the+/// session's artifact tree (idle, settled, and restart-orphaned+/// subagents all appear, with their real usage and recursive+/// grandchildren — TS `loadContextTreeChildrenFromDisk`). The artifact+/// tree is keyed by the worker's agent dir and the durable session id,+/// exactly where `child_session_dir` writes; a session file outside+/// the agent dir must not change that.+#[tokio::test]+async fn get_context_tree_lists_persisted_children() {+ let root = std::env::temp_dir().join(format!("pa-worker-ct-{}", uuid::Uuid::new_v4()));+ let agent_dir = root.join("agent");+ let sessions = agent_dir.join("sessions");+ std::fs::create_dir_all(&sessions).unwrap();+ let session_id = "01a0ct-1111-2222-3333-444444444444";+ let session_file = sessions.join(format!("{session_id}.jsonl"));+ let usage = json!({+ "input": 30, "output": 6, "cacheRead": 0, "cacheWrite": 0,+ "totalTokens": 36,+ "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0 },+ });+ let content = [+ json!({"type": "session", "version": 3, "id": session_id, "timestamp": "2026-09-22T00:00:00.000Z", "cwd": "/tmp"}),+ json!({"type": "message", "id": "e1", "parentId": null, "timestamp": "2026-09-22T00:00:01.000Z", "message": {"role": "user", "content": "hi"}}),+ json!({"type": "message", "id": "e2", "parentId": "e1", "timestamp": "2026-09-22T00:00:02.000Z", "message": {"role": "assistant", "content": [{ "type": "text", "text": "hello" }], "provider": "prime-inference", "model": "internal/glm-5.3-fast", "usage": usage}}),+ ]+ .iter()+ .map(std::string::ToString::to_string)+ .collect::<Vec<_>>()+ .join("\n");+ std::fs::write(&session_file, content).unwrap();+ // The artifact tree lives under the worker's agent dir (the writer's+ // addressing): one settled child with a grandchild in the child's own+ // sibling tree.+ let artifacts = agent_dir.join("session-artifacts");+ let child_session = "01a0child-1111-2222-3333-4444444444";+ let grandchild_session = "01a0grand-1111-2222-3333-4444444444";+ let write_child = |stop: &str| {+ [+ json!({"type": "message", "id": "c1", "parentId": null, "timestamp": "2026-09-22T00:00:01.000Z", "message": {"role": "user", "content": "fix the login bug"}}),+ json!({"type": "message", "id": "c2", "parentId": "c1", "timestamp": "2026-09-22T00:00:02.000Z", "message": {"role": "assistant", "content": [{ "type": "text", "text": "done" }], "provider": "prime-inference", "model": "internal/glm-5.3-fast", "stopReason": stop, "usage": {"input": 10, "output": 5, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 15, "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0}}}}),+ ]+ };+ let write_session = |dir: &std::path::Path, session: &str, stop: &str| {+ std::fs::create_dir_all(dir).unwrap();+ let mut lines = vec![+ json!({"type": "session", "version": 3, "id": session, "timestamp": "2026-09-22T00:00:00.000Z", "cwd": "/tmp"}),+ ];+ lines.extend(write_child(stop));+ std::fs::write(+ dir.join(format!("{session}.jsonl")),+ lines+ .iter()+ .map(std::string::ToString::to_string)+ .collect::<Vec<_>>()+ .join("\n"),+ )+ .unwrap();+ };+ let child_dir = artifacts.join(session_id).join("sub-003f741a");+ write_session(&child_dir, child_session, "stop");+ let grandchild_dir = artifacts.join(child_session).join("sub-00aa00aa");+ write_session(&grandchild_dir, grandchild_session, "stop");+ // A second child the user deleted: the ledger tombstone must keep it+ // out of the tree.+ let deleted_dir = artifacts.join(session_id).join("sub-deadbeef");+ let deleted_session = "01a0dead-1111-2222-3333-4444444444";+ write_session(&deleted_dir, deleted_session, "stop");+ let ledger = crate::rlm_ledger::RlmSpawnLedger::new(&agent_dir, &sessions, |_| {});+ ledger+ .append_spawn(&crate::rlm_ledger::RlmSpawnInput {+ child_id: "sub-deadbeef".to_string(),+ parent: session_file.display().to_string(),+ child: deleted_dir.display().to_string(),+ depth: 1,+ name: "deleted-child".to_string(),+ })+ .unwrap();+ ledger+ .append_delete(+ "sub-deadbeef",+ &deleted_dir.display().to_string(),+ crate::rlm_ledger::RlmLedgerDeleteReason::User,+ )+ .unwrap();++ let worker = created_worker_at(&root, &session_file).await;+ // The children come from the background cache refresh (the create+ // warm armed it): a cold read serves the root from memory+ // instantly, and the persisted tree fills when the walk lands.+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);+ let children = loop {+ let response = worker+ .dispatch(+ "get_context_tree",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success, "failed: {response:?}");+ let tree = response.data.expect("data");+ assert_eq!(+ tree["ownUsage"]["input"],+ json!(30),+ "the root usage counts"+ );+ let children = tree["children"].as_array().cloned().unwrap_or_default();+ if children.len() == 1 || std::time::Instant::now() > deadline {+ break children;+ }+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;+ };+ assert_eq!(+ children.len(),+ 1,+ "the persisted child appears, the deleted one stays hidden: {children:?}"+ );+ let child = &children[0];+ assert_eq!(child["id"], json!("sub-003f741a"));+ assert_eq!(child["status"], json!("done"));+ assert_eq!(child["label"], json!("fix the login bug"));+ assert_eq!(child["ownUsage"]["totalTokens"], json!(15));+ let grandchildren = child["children"].as_array().expect("grandchildren");+ assert_eq!(grandchildren.len(), 1);+ assert_eq!(grandchildren[0]["id"], json!("sub-00aa00aa"));+ assert_eq!(grandchildren[0]["ownUsage"]["totalTokens"], json!(15));+ let _ = std::fs::remove_dir_all(&root);+}++/// `get_commands` / `get_resource_snapshot` on the scripted engine:+/// the TS loader shapes over empty lists.+#[tokio::test]+async fn commands_and_resources_match_the_empty_loader_shape() {+ let worker = created_worker().await;+ let response = worker+ .dispatch(+ "get_commands",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success);+ assert_eq!(response.data.expect("data"), json!({ "commands": [] }));+ let response = worker+ .dispatch(+ "get_resource_snapshot",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success);+ assert_eq!(+ response.data.expect("data"),+ crate::engine::empty_resource_snapshot()+ );+}++/// `get_session_context`: the resolved context at the leaf — messages,+/// effective thinking level, service tier, and model selector.+#[tokio::test]+async fn get_session_context_matches_the_ts_context_shape() {+ let worker = created_worker().await;+ let response = worker+ .dispatch(+ "get_session_context",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success, "failed: {response:?}");+ let context = response.data.expect("data")["context"].clone();+ assert!(context.get("messages").is_some());+ assert!(context.get("thinkingLevel").is_some());+ assert!(context.get("serviceTier").is_some());+ assert!(context.get("model").is_some());++ // One turn lands its accepted user message on the resolved+ // context. (The scripted harness's synthetic assistant row carries+ // no stop reason, so it does not round-trip into the typed entry+ // form the walk consumes; real engine rows do.)+ let _ = worker+ .dispatch(+ "prompt_and_wait",+ &json!({ "activeSessionId": "getter-session", "message": "hello" }),+ )+ .await;+ let response = worker+ .dispatch(+ "get_session_context",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ let context = response.data.expect("data")["context"].clone();+ let roles: Vec<String> = context["messages"]+ .as_array()+ .expect("messages array")+ .iter()+ .filter_map(|message| {+ message+ .get("role")+ .and_then(Value::as_str)+ .map(str::to_string)+ })+ .collect();+ assert!(roles.iter().any(|role| role == "user"));+ assert_eq!(context["messages"][0]["content"], json!("hello"));+}++/// `get_system_prompt` / `get_tool_definition`: the scripted engine+/// has no prompt (empty string, the TS key present) and no tools (the+/// `toolDefinition` key omitted, like the TS `undefined` field).+#[tokio::test]+async fn system_prompt_and_tool_definition_match_the_ts_shapes() {+ let worker = created_worker().await;+ let response = worker+ .dispatch(+ "get_system_prompt",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success);+ assert_eq!(response.data.expect("data"), json!({ "systemPrompt": "" }));++ let response = worker+ .dispatch(+ "get_tool_definition",+ &json!({ "activeSessionId": "getter-session", "name": "ipython" }),+ )+ .await;+ assert!(response.success);+ assert_eq!(response.data.expect("data"), json!({}));++ let response = worker+ .dispatch(+ "get_tool_definition",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(!response.success);+ assert_eq!(+ response.error.as_deref(),+ Some("get_tool_definition requires a name")+ );+}++/// `get_rlm_max_depth_status`: the TS source vocabulary (the b6 wave+/// replaced the provisional "settings" label; an unseeded scripted+/// session reports the shared default).+#[tokio::test]+async fn rlm_max_depth_status_matches_the_ts_shape() {+ let worker = created_worker().await;+ let response = worker+ .dispatch(+ "get_rlm_max_depth_status",+ &json!({ "activeSessionId": "getter-session" }),+ )+ .await;+ assert!(response.success);+ assert_eq!(+ response.data.expect("data"),+ json!({ "maxDepth": crate::rlm_children::DEFAULT_RLM_MAX_DEPTH, "source": "default" })+ );+}++/// `get_model_catalog` / `get_available_models` against a fixture+/// registry (TS `refreshModelCatalog` / `refreshAvailableModels`).+#[tokio::test]+async fn model_catalog_and_available_models_match_the_ts_shapes() {+ let dir = tempfile::tempdir().expect("tempdir");+ std::fs::create_dir_all(dir.path().join("agent")).expect("agent dir");+ std::fs::write(+ dir.path().join("agent").join("models.json"),+ json!({+ "providers": {+ "prime-inference": {+ "api": "openai-completions",+ "baseUrl": "http://127.0.0.1:9/v1",+ "apiKey": "sk-test",+ "models": [+ { "id": "mock-1", "name": "Mock 1", "api": "openai-completions",+ "baseUrl": "http://127.0.0.1:9/v1", "contextWindow": 128_000,+ "maxTokens": 4096 },+ { "id": "mock-2", "name": "Mock 2", "api": "openai-completions",+ "baseUrl": "http://127.0.0.1:9/v1", "contextWindow": 128_000,+ "maxTokens": 4096 }+ ]+ }+ }+ })+ .to_string(),+ )+ .expect("write models.json");+ let config = crate::worker::WorkerConfig {+ socket_path: dir.path().join("worker.sock"),+ supervisor_socket_path: std::path::PathBuf::new(),+ token: "token".to_string(),+ worker_instance_id: String::new(),+ active_session_id: "catalog-session".to_string(),+ agent_dir: dir.path().join("agent"),+ recovery_journal_path: dir.path().join("recovery.jsonl"),+ telemetry_disabled: None,+ script: Some(json!({ "responses": ["ack"] })),+ };+ let worker = Arc::new(Worker::new(config, None));+ let created = worker+ .dispatch("create", &json!({ "noSession": true, "cwd": "/tmp" }))+ .await;+ assert!(created.success, "create failed: {created:?}");++ let response = worker+ .dispatch(+ "get_model_catalog",+ &json!({ "activeSessionId": "catalog-session" }),+ )+ .await;+ assert!(response.success, "failed: {response:?}");+ let catalog = response.data.expect("data");+ assert_eq!(+ catalog["models"]+ .as_array()+ .expect("models")+ .iter()+ .filter(|model| model["id"] == json!("mock-1"))+ .count(),+ 1+ );+ assert_eq!(catalog["configuredProviders"], json!(["prime-inference"]));++ let response = worker+ .dispatch(+ "get_available_models",+ &json!({ "activeSessionId": "catalog-session" }),+ )+ .await;+ assert!(response.success);+ let available = response.data.expect("data");+ let models = available["models"].as_array().expect("models");+ // The registry also serves the built-in catalog when the box has+ // configured auth for it; the fixture provider must be complete.+ assert!(+ models+ .iter()+ .filter(|model| model["provider"] == json!("prime-inference"))+ .count()+ >= 2+ );+ assert!(models.iter().any(|model| model["id"] == json!("mock-1")));+}diff --git a/crates/pa-daemon/src/state_getters/usage.rs b/crates/pa-daemon/src/state_getters/usage.rsnew file mode 100644index 0000000000..4b95f854da--- /dev/null+++ b/crates/pa-daemon/src/state_getters/usage.rs@@ -0,0 +1,518 @@+//! The usage math (moved with its concern): the model registry resolution+//! the create path shares, the TS `Usage` wire shape (`empty_usage`), the+//! add/subtract folds, and the own/total + by-model attribution computations;+//! the unit battery rides inline.+use super::{json, ModelRegistry, Value};++/// The worker's model registry (auth storage + `models.json`, with the+/// on-disk private-authorization cache adopted so create-time resolution+/// sees the same availability the create path does).+pub(crate) fn worker_model_registry(agent_dir: &std::path::Path) -> ModelRegistry {+ let auth = pa_core::auth::AuthStorage::create(agent_dir);+ let mut registry = ModelRegistry::create(auth, agent_dir.join("models.json"));+ registry.load_private_authorization_from_cache();+ registry+}++/// The TS `Usage` wire shape (the TS `emptyUsage`).+pub(crate) fn empty_usage() -> Value {+ json!({+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0,+ "totalTokens": 0,+ "cost": {+ "input": 0,+ "output": 0,+ "cacheRead": 0,+ "cacheWrite": 0,+ "total": 0,+ },+ })+}++/// TS `addAssistantUsage`: fold one usage block into a running total.+fn add_usage(total: &mut Value, usage: &Value) {+ let add_field = |total: &mut Value, field: &str, usage: &Value| {+ let current = total.get(field).and_then(Value::as_u64).unwrap_or(0);+ let add = usage.get(field).and_then(Value::as_u64).unwrap_or(0);+ total[field] = json!(current + add);+ };+ for field in ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] {+ add_field(total, field, usage);+ }+ for field in ["input", "output", "cacheRead", "cacheWrite", "total"] {+ let cost = total+ .get_mut("cost")+ .and_then(Value::as_object_mut)+ .expect("usage totals always carry the cost block");+ // The running total is a float after the first add (TS costs are+ // floats); reading it as u64 dropped everything already banked.+ let current = cost.get(field).and_then(Value::as_f64).unwrap_or(0.0);+ let add = usage+ .get("cost")+ .and_then(|cost| cost.get(field))+ .and_then(Value::as_f64)+ .unwrap_or(0.0);+ cost.insert(field.to_string(), json!(current + add));+ }+}++/// TS `subtractAssistantUsage`: remove one usage block, clamping at zero.+fn subtract_usage(total: &mut Value, usage: &Value) {+ let sub_field = |total: &mut Value, field: &str, usage: &Value| {+ let current = total.get(field).and_then(Value::as_u64).unwrap_or(0);+ let sub = usage.get(field).and_then(Value::as_u64).unwrap_or(0);+ total[field] = json!(current.saturating_sub(sub));+ };+ for field in ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] {+ sub_field(total, field, usage);+ }+ for field in ["input", "output", "cacheRead", "cacheWrite", "total"] {+ let cost = total+ .get_mut("cost")+ .and_then(Value::as_object_mut)+ .expect("usage totals always carry the cost block");+ let current = cost.get(field).and_then(Value::as_f64).unwrap_or(0.0);+ let sub = usage+ .get("cost")+ .and_then(|cost| cost.get(field))+ .and_then(Value::as_f64)+ .unwrap_or(0.0);+ cost.insert(field.to_string(), json!((current - sub).max(0.0)));+ }+}++/// TS `computeOwnAndTotalUsage`: the branch's cumulative assistant usage+/// (`totalUsage`, attributions included) minus the child usage+/// attributions targeting those assistants (`ownUsage`). Totals stay+/// cumulative across compactions: compaction shrinks the model-facing+/// context, not what the session spent.+pub(crate) fn compute_own_and_total_usage(+ branch: &[&crate::session_store::SessionEntry],+ all_entries: &[crate::session_store::SessionEntry],+) -> (Value, Value) {+ let mut total = empty_usage();+ let mut branch_assistant_ids = std::collections::HashSet::new();+ for entry in branch {+ if entry.type_ == "message" {+ let Some(message) = entry.fields.get("message") else {+ continue;+ };+ if message.get("role").and_then(Value::as_str) == Some("assistant") {+ branch_assistant_ids.insert(entry.id.clone());+ if let Some(usage) = message.get("usage") {+ add_usage(&mut total, usage);+ }+ }+ } else if matches!(entry.type_.as_str(), "compaction" | "branch_summary") {+ if let Some(usage) = entry.fields.get("usage") {+ add_usage(&mut total, usage);+ }+ }+ }+ let mut own = total.clone();+ for entry in all_entries {+ if entry.type_ != "child_usage_attributed" {+ continue;+ }+ let Some(target_id) = entry.fields.get("targetId").and_then(Value::as_str) else {+ continue;+ };+ if branch_assistant_ids.contains(target_id) {+ if let Some(child_usage) = entry.fields.get("childUsage") {+ subtract_usage(&mut own, child_usage);+ }+ }+ }+ (own, total)+}++/// The branch's own usage broken down by serving model (the operator's+/// cost question: a session that switches models mid-conversation — or+/// hosts subagents on other models — shows which model billed what).+///+/// Each assistant row folds into the bucket of the model on its message+/// envelope (the request-time serving model — cost blocks were computed+/// against that model's rates, so each bucket holds only spend billed at+/// those rates); `compaction` / `branch_summary` rows fold on the model+/// their entry records when the summary call named one (TS #2411 routes+/// branch summaries to a configured auxiliary model — the timeline names+/// the session's current model, not the routed one that billed) and+/// otherwise follow the branch's `model_change` timeline, seeded on a+/// windowed load with the retained-window boundary's model (the newest+/// `model_change` in the discarded prefix — the leaf's model would bill+/// the boundary's early summarizer rows on the wrong side of a post-+/// boundary switch).+/// Child-usage attributions subtract from the target row's model bucket+/// exactly like [`compute_own_and_total_usage`] subtracts from+/// `ownUsage`, so the buckets sum to the node's own usage — and the sum+/// is verified against the caller's `own_usage` before the breakdown is+/// served. `None` when any usage-carrying row resolves to no model (a+/// foreign file without `model_change` rows or model-tagged assistants),+/// or when the buckets cannot reconcile: an attribution larger than its+/// target row's bucket clamps inside that bucket while the plain fold+/// subtracts the same amount from the combined pool, so the buckets+/// would overstate the node. A partial breakdown would not add up to the+/// displayed totals, so the caller omits the field and the display+/// degrades to the plain TS totals.+pub(crate) fn compute_own_usage_by_model(+ branch: &[&crate::session_store::SessionEntry],+ all_entries: &[crate::session_store::SessionEntry],+ own_usage: &Value,+ initial_model: Option<&(String, String)>,+) -> Option<Vec<Value>> {+ // The buckets in first-seen order: JSON arrays keep the fold order,+ // so the display renders the model the session started on first.+ let mut order: Vec<(String, String)> = Vec::new();+ let mut position: std::collections::HashMap<(String, String), usize> =+ std::collections::HashMap::new();+ let mut buckets: Vec<Value> = Vec::new();+ // The branch's model timeline seeded with the retained-window+ // boundary's model when the load kept only a window (a reopened+ // compacted session's retained branch starts at the boundary — its+ // early rows billed on the boundary's model, not the leaf's, and a+ // full history keeps `None` so a foreign file still omits the+ // breakdown) and the assistant id -> bucket map the attribution+ // subtraction reads.+ let mut current: Option<(String, String)> = initial_model.cloned();+ let mut assistant_buckets: std::collections::HashMap<&str, usize> =+ std::collections::HashMap::new();+ let mut unresolved = false;+ let mut bucket_for =+ |key: Option<(String, String)>, buckets: &mut Vec<Value>| -> Option<usize> {+ let key = key?;+ let at = *position.entry(key.clone()).or_insert_with(|| {+ order.push(key);+ buckets.push(empty_usage());+ buckets.len() - 1+ });+ Some(at)+ };+ for entry in branch {+ let usage = match entry.type_.as_str() {+ "model_change" => {+ let provider = entry+ .fields+ .get("provider")+ .and_then(Value::as_str)+ .unwrap_or_default();+ let model_id = entry+ .fields+ .get("modelId")+ .and_then(Value::as_str)+ .unwrap_or_default();+ current = (!provider.is_empty() && !model_id.is_empty())+ .then(|| (provider.to_string(), model_id.to_string()));+ continue;+ }+ "message" => {+ let Some(message) = entry.fields.get("message") else {+ continue;+ };+ if message.get("role").and_then(Value::as_str) != Some("assistant") {+ continue;+ }+ let usage = message.get("usage");+ if usage.is_none() {+ // An assistant row without usage bills nothing; the+ // own-usage fold skips it the same way (an attribution+ // targeting it subtracts from a zero base).+ continue;+ }+ // The serving model on the envelope outranks the timeline+ // (the row is the request's own record).+ let provider = message+ .get("provider")+ .and_then(Value::as_str)+ .unwrap_or_default();+ let model_id = message+ .get("model")+ .and_then(Value::as_str)+ .unwrap_or_default();+ let key = (!provider.is_empty() && !model_id.is_empty())+ .then(|| (provider.to_string(), model_id.to_string()))+ .or(current.clone());+ match bucket_for(key, &mut buckets) {+ Some(at) => {+ add_usage(&mut buckets[at], usage.expect("checked"));+ assistant_buckets.insert(entry.id.as_str(), at);+ }+ None => unresolved = true,+ }+ continue;+ }+ "compaction" | "branch_summary" => entry.fields.get("usage"),+ _ => continue,+ };+ if let Some(usage) = usage {+ // A row that records the model its summary call served on+ // (TS #2411's auxiliary routing — persisted on the entry)+ // outranks the timeline: the branch timeline names the+ // session's current model, not the routed one that billed.+ let row_model = (|| {+ let provider = entry.fields.get("provider")?.as_str()?;+ let model_id = entry.fields.get("modelId")?.as_str()?;+ (!provider.is_empty() && !model_id.is_empty())+ .then(|| (provider.to_string(), model_id.to_string()))+ })();+ match bucket_for(row_model.or_else(|| current.clone()), &mut buckets) {+ Some(at) => add_usage(&mut buckets[at], usage),+ None => unresolved = true,+ }+ }+ }+ if unresolved {+ return None;+ }+ for entry in all_entries {+ if entry.type_ != "child_usage_attributed" {+ continue;+ }+ let Some(target_id) = entry.fields.get("targetId").and_then(Value::as_str) else {+ continue;+ };+ let (Some(at), Some(child_usage)) = (+ assistant_buckets.get(target_id).copied(),+ entry.fields.get("childUsage"),+ ) else {+ continue;+ };+ subtract_usage(&mut buckets[at], child_usage);+ }+ // Reconciliation: the buckets must sum to the node's own usage. The+ // per-bucket attribution subtraction clamps inside the target row's+ // bucket while the plain fold subtracts from the combined pool, so+ // an attribution larger than its target row's spend (or one whose+ // target row carries no usage) leaves the buckets overstating the+ // node. Omit the breakdown then — the unresolved-model contract: a+ // breakdown that cannot add up is worse than none. Token fields+ // compare exactly; the cost fields allow the last-ulp drift of two+ // differently ordered float sums.+ let mut summed = empty_usage();+ for bucket in &buckets {+ add_usage(&mut summed, bucket);+ }+ for field in ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] {+ if summed[field] != own_usage[field] {+ return None;+ }+ }+ for field in ["input", "output", "cacheRead", "cacheWrite", "total"] {+ let summed_cost = summed["cost"][field].as_f64().unwrap_or_default();+ let own_cost = own_usage["cost"][field].as_f64().unwrap_or_default();+ if (summed_cost - own_cost).abs() > 1e-9 * (1.0 + summed_cost.max(own_cost)) {+ return None;+ }+ }+ Some(+ order+ .into_iter()+ .zip(buckets)+ .map(|((provider, model_id), own_usage)| {+ json!({ "provider": provider, "id": model_id, "ownUsage": own_usage })+ })+ .collect(),+ )+}++#[cfg(test)]+mod usage_tests {+ use super::*;++ /// The own/total split (TS `computeOwnAndTotalUsage`): attributions+ /// subtract from own usage only, matched by target across every entry.+ #[test]+ fn own_usage_subtracts_child_attributions() {+ let assistant = json!({+ "type": "message", "id": "m1",+ "message": {+ "role": "assistant", "content": "text",+ "usage": {+ "input": 100, "output": 10, "cacheRead": 0, "cacheWrite": 0,+ "totalTokens": 110,+ "cost": { "input": 1, "output": 2, "cacheRead": 0, "cacheWrite": 0, "total": 3 },+ },+ },+ });+ let attribution = json!({+ "type": "child_usage_attributed", "id": "a1",+ "targetId": "m1",+ "childUsage": {+ "input": 40, "output": 5, "cacheRead": 0, "cacheWrite": 0,+ "totalTokens": 45,+ "cost": { "input": 0.5, "output": 1, "cacheRead": 0, "cacheWrite": 0, "total": 1.5 },+ },+ });+ let entry = |value: &Value, id: &str| crate::session_store::SessionEntry {+ type_: value["type"].as_str().expect("type").to_string(),+ id: id.to_string(),+ parent_id: None,+ timestamp: "2024-01-01T00:00:00.000Z".to_string(),+ fields: value+ .as_object()+ .expect("object")+ .clone()+ .into_iter()+ .collect(),+ };+ let assistant_entry = entry(&assistant, "m1");+ let attribution_entry = entry(&attribution, "a1");+ let entries = vec![+ assistant_entry.clone(),+ attribution_entry.clone(),+ attribution_entry.clone(),+ ];+ let branch_refs: Vec<&crate::session_store::SessionEntry> = entries.iter().collect();+ let (own, total) = compute_own_and_total_usage(&branch_refs, &entries);+ assert_eq!(total["input"], json!(100));+ assert_eq!(total["totalTokens"], json!(110));+ assert_eq!(own["input"], json!(20), "two attributions subtract twice");+ // Subtraction clamps at zero instead of going negative (TS+ // attribution-drift guard).+ let entries_more = vec![+ assistant_entry,+ attribution_entry.clone(),+ attribution_entry.clone(),+ attribution_entry.clone(),+ attribution_entry.clone(),+ attribution_entry,+ ];+ let branch_refs_more: Vec<&crate::session_store::SessionEntry> =+ entries_more.iter().collect();+ let (own, _) = compute_own_and_total_usage(&branch_refs_more, &entries_more);+ assert_eq!(own["input"], json!(0));+ assert_eq!(own["cost"]["total"].as_f64(), Some(0.0));+ }++ /// A `branch_summary` row served by an auxiliary model (TS #2411)+ /// bills on the model its entry records, not the branch timeline's+ /// current model: the routed call billed at the auxiliary model's+ /// rates, so its spend belongs to that model's bucket while the+ /// buckets still reconcile with the plain own-usage fold (the+ /// Macroscope wrong-bucket round).+ #[test]+ fn branch_summary_usage_bills_on_the_row_recorded_auxiliary_model() {+ let entry = |value: &Value, id: &str| crate::session_store::SessionEntry {+ type_: value["type"].as_str().expect("type").to_string(),+ id: id.to_string(),+ parent_id: None,+ timestamp: "2024-01-01T00:00:00.000Z".to_string(),+ fields: value+ .as_object()+ .expect("object")+ .clone()+ .into_iter()+ .collect(),+ };+ let usage = |input: u64, output: u64| {+ json!({+ "input": input, "output": output, "cacheRead": 0, "cacheWrite": 0,+ "totalTokens": input + output,+ "cost": {"input": 0.1, "output": 0.2, "cacheRead": 0, "cacheWrite": 0, "total": 0.3},+ })+ };+ let entries = vec![+ entry(+ &json!({"type": "model_change", "provider": "openai", "modelId": "gpt-a"}),+ "m0",+ ),+ entry(+ &json!({+ "type": "message",+ "message": {"role": "assistant", "content": "on it", "provider": "openai", "model": "gpt-a", "usage": usage(100, 10)},+ }),+ "e1",+ ),+ entry(+ &json!({+ "type": "branch_summary",+ "summary": "explored",+ "usage": usage(50, 5),+ "provider": "anthropic",+ "modelId": "aux-opus-4",+ }),+ "b1",+ ),+ ];+ let branch: Vec<&crate::session_store::SessionEntry> = entries.iter().collect();+ let (own, _) = compute_own_and_total_usage(&branch, &entries);+ let breakdown =+ compute_own_usage_by_model(&branch, &entries, &own, None).expect("resolved");+ assert_eq!(breakdown.len(), 2);+ assert_eq!(breakdown[0]["provider"], json!("openai"));+ assert_eq!(breakdown[0]["id"], json!("gpt-a"));+ assert_eq!(breakdown[0]["ownUsage"]["totalTokens"], json!(110));+ // The auxiliary summary lands on the routed model's bucket, not+ // the timeline's current model.+ assert_eq!(breakdown[1]["provider"], json!("anthropic"));+ assert_eq!(breakdown[1]["id"], json!("aux-opus-4"));+ assert_eq!(breakdown[1]["ownUsage"]["totalTokens"], json!(55));+ }++ /// A windowed load (a reopened compacted session) seeds the timeline+ /// with the retained-window boundary's model: retained usage rows+ /// before the branch's first `model_change` still resolve a bucket and+ /// the breakdown is served instead of omitted — the target case this+ /// change exists for (the Bugbot windowed-omission round). The same+ /// walk without a seed (a full-history foreign file without+ /// `model_change` rows) keeps omitting the breakdown.+ #[test]+ fn window_seed_resolves_rows_before_the_first_model_change() {+ let entry = |value: &Value, id: &str| crate::session_store::SessionEntry {+ type_: value["type"].as_str().expect("type").to_string(),+ id: id.to_string(),+ parent_id: None,+ timestamp: "2024-01-01T00:00:00.000Z".to_string(),+ fields: value+ .as_object()+ .expect("object")+ .clone()+ .into_iter()+ .collect(),+ };+ let usage = |input: u64, output: u64| {+ json!({+ "input": input, "output": output, "cacheRead": 0, "cacheWrite": 0,+ "totalTokens": input + output,+ "cost": {"input": 0.1, "output": 0.2, "cacheRead": 0, "cacheWrite": 0, "total": 0.3},+ })+ };+ // The retained branch starts at the compaction boundary: the+ // summarizer's usage row carries no model of its own (an+ // unattributed row) and no `model_change` row precedes it on the walk.+ let entries = vec![+ entry(+ &json!({"type": "branch_summary", "summary": "cut", "usage": usage(30, 3)}),+ "b1",+ ),+ entry(+ &json!({+ "type": "message",+ "message": {"role": "assistant", "content": "resumed", "provider": "openai", "model": "gpt-a", "usage": usage(100, 10)},+ }),+ "e1",+ ),+ ];+ let branch: Vec<&crate::session_store::SessionEntry> = entries.iter().collect();+ let (own, _) = compute_own_and_total_usage(&branch, &entries);+ let seeded = compute_own_usage_by_model(+ &branch,+ &entries,+ &own,+ Some(&("openai".to_string(), "gpt-a".to_string())),+ )+ .expect("the seed resolves the boundary rows");+ assert_eq!(seeded.len(), 1);+ assert_eq!(seeded[0]["provider"], json!("openai"));+ assert_eq!(seeded[0]["id"], json!("gpt-a"));+ assert_eq!(seeded[0]["ownUsage"]["totalTokens"], json!(143));+ // The unseeded walk keeps the foreign-file contract: a branch+ // whose usage rows resolve to no model omits the breakdown.+ assert_eq!(+ compute_own_usage_by_model(&branch, &entries, &own, None),+ None+ );+ }+}