Skip to main content

orch/cli/
stats.rs

1use std::fs;
2use std::path::PathBuf;
3
4use crate::cli;
5use crate::cli::cost::format_cost;
6use crate::config;
7use crate::store::CostSummary;
8use crate::store::MetricsSummary;
9
10/// Show task metrics and statistics, per-project by default.
11///
12/// `since_hours` controls the time window (default 24; pass 168 for 7 days, etc.).
13pub async fn stats(all: bool, since_hours: u32) -> anyhow::Result<()> {
14    let store = cli::init_store().await?;
15    let window_label = cli::hours_to_label(since_hours);
16
17    if all {
18        let summary = store.get_metrics_summary(since_hours).await?;
19        let cost = store.get_cost_summary().await.ok();
20        println!();
21        print_summary_table("All Projects", &window_label, &summary, cost.as_ref());
22    } else {
23        let repos = get_configured_repos();
24        if repos.is_empty() {
25            // Fallback to global stats if no projects configured
26            let summary = store.get_metrics_summary(since_hours).await?;
27            let cost = store.get_cost_summary().await.ok();
28            println!();
29            print_summary_table("All Projects", &window_label, &summary, cost.as_ref());
30        } else {
31            println!();
32            for repo in &repos {
33                let summary = store.get_metrics_summary_by_repo(repo, since_hours).await?;
34                let cost = store.get_cost_summary_by_repo(repo, since_hours).await.ok();
35                print_summary_table(repo, &window_label, &summary, cost.as_ref());
36            }
37        }
38    }
39
40    Ok(())
41}
42
43fn print_summary_table(
44    title: &str,
45    window_label: &str,
46    summary: &MetricsSummary,
47    cost: Option<&CostSummary>,
48) {
49    println!("── {title} ──────────────────────────────────");
50
51    let total = summary.tasks_completed_24h + summary.tasks_failed_24h;
52    #[expect(
53        clippy::cast_precision_loss,
54        reason = "a display percentage of task counts far below 2^52"
55    )]
56    let success_rate = if total > 0 {
57        summary.tasks_completed_24h as f64 / total as f64 * 100.0
58    } else {
59        0.0
60    };
61
62    println!(
63        "  Tasks ({}):  {} completed, {} failed",
64        window_label, summary.tasks_completed_24h, summary.tasks_failed_24h
65    );
66    println!("  Success rate: {success_rate:.1}%");
67
68    // Duration by complexity
69    let mut durations = Vec::new();
70    if let Some(d) = summary.avg_duration_simple {
71        durations.push(format!("simple {:.1}m", d / 60.0));
72    }
73    if let Some(d) = summary.avg_duration_medium {
74        durations.push(format!("medium {:.1}m", d / 60.0));
75    }
76    if let Some(d) = summary.avg_duration_complex {
77        durations.push(format!("complex {:.1}m", d / 60.0));
78    }
79    if !durations.is_empty() {
80        println!("  Avg duration: {}", durations.join(" | "));
81    }
82
83    // Agent stats
84    if !summary.agent_stats.is_empty() {
85        let agents: Vec<String> = summary
86            .agent_stats
87            .iter()
88            .map(|a| format!("{}: {} ({:.0}%)", a.agent, a.total_runs, a.success_rate))
89            .collect();
90        println!("  Agents:       {}", agents.join(" | "));
91    }
92
93    // Cost: show total across all recorded periods
94    if let Some(c) = cost {
95        if let Some(period) = c.periods.iter().find(|p| p.label == window_label) {
96            println!(
97                "  Cost ({}): {}",
98                window_label,
99                format_cost(period.total_cost_usd)
100            );
101        } else if let Some(period_24h) = c.periods.iter().find(|p| p.label == "24h") {
102            println!("  Cost (24h):   {}", format_cost(period_24h.total_cost_usd));
103        }
104    }
105
106    if summary.rate_limits_24h > 0 {
107        println!("  Rate limits:  {}", summary.rate_limits_24h);
108    }
109
110    println!();
111}
112
113/// Get all configured project repos from global config + .orch.yml files.
114fn get_configured_repos() -> Vec<String> {
115    let mut repos = Vec::new();
116
117    // Try current project
118    if let Ok(repo) = config::get_current_repo()
119        && !repo.is_empty()
120    {
121        repos.push(repo);
122    }
123
124    // Try projects from global config
125    if let Ok(paths) = config::get_project_paths() {
126        for path_str in &paths {
127            let candidate = PathBuf::from(path_str).join(".orch.yml");
128            if candidate.exists()
129                && let Ok(content) = fs::read_to_string(&candidate)
130                && let Ok(val) = serde_norway::from_str::<serde_norway::Value>(&content)
131                && let Some(repo) = val
132                    .get("gh")
133                    .and_then(|g| g.get("repo"))
134                    .and_then(|r| r.as_str())
135                && !repos.contains(&repo.to_string())
136            {
137                repos.push(repo.to_string());
138            }
139        }
140    }
141
142    repos
143}