Skip to main content

orch/cli/stats/
mod.rs

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