1use crate::core::config;
5use crate::core::data_source::DataSource;
6use crate::metrics::{index, report};
7use crate::shell::cli::{maybe_refresh_store, open_workspace_read_store, workspace_path};
8use crate::shell::remote_pull::maybe_telemetry_pull;
9use crate::shell::scope;
10use crate::store::Store;
11use crate::sync::{ingest_ctx, smart};
12use anyhow::Result;
13use std::path::Path;
14
15pub fn metrics_text(
17 workspace: Option<&Path>,
18 days: u32,
19 json_out: bool,
20 force: bool,
21 all_workspaces: bool,
22 refresh: bool,
23 source: DataSource,
24) -> Result<String> {
25 let roots = scope::resolve(workspace, all_workspaces)?;
26 let mut reports = Vec::new();
27 for workspace in &roots {
28 let cfg = config::load(workspace)?;
29 let store = open_workspace_read_store(workspace, refresh || source != DataSource::Local)?;
30 maybe_telemetry_pull(workspace, &store, &cfg, source, refresh)?;
31 maybe_refresh_store(workspace, &store, refresh)?;
32 if force {
33 let snapshot = index::ensure_indexed(&store, workspace, true)?;
34 maybe_enqueue_snapshot(&store, &cfg, workspace, &snapshot)?;
35 }
36 let ws_str = workspace.to_string_lossy().to_string();
37 if let Ok(mut report) = report::build_report(&store, &ws_str, days) {
38 if source != DataSource::Local
39 && let Ok(Some(agg)) =
40 crate::shell::remote_observe::try_remote_event_agg(&store, &cfg, workspace)
41 {
42 report =
43 crate::shell::remote_observe::apply_remote_to_metrics(report, &agg, source);
44 }
45 reports.push(if roots.len() == 1 {
46 report
47 } else {
48 decorate_metrics(workspace, report)
49 });
50 }
51 }
52 let metrics = merge_metrics(reports);
53 if json_out {
54 return Ok(serde_json::to_string_pretty(&metrics)?);
55 }
56 Ok(format_human(&metrics))
57}
58
59pub fn cmd_metrics(
60 workspace: Option<&Path>,
61 days: u32,
62 json_out: bool,
63 force: bool,
64 all_workspaces: bool,
65 refresh: bool,
66 source: DataSource,
67) -> Result<()> {
68 print!(
69 "{}",
70 metrics_text(
71 workspace,
72 days,
73 json_out,
74 force,
75 all_workspaces,
76 refresh,
77 source
78 )?
79 );
80 Ok(())
81}
82
83pub fn metrics_index_text(workspace: Option<&Path>, force: bool) -> Result<String> {
85 let ws = workspace_path(workspace)?;
86 let cfg = config::load(&ws)?;
87 let db_path = crate::core::workspace::db_path(&ws)?;
88 let store = Store::open(&db_path)?;
89 let snapshot = index::ensure_indexed(&store, &ws, force)?;
90 maybe_enqueue_snapshot(&store, &cfg, &ws, &snapshot)?;
91 use std::fmt::Write;
92 let mut s = String::new();
93 writeln!(&mut s, "snapshot: {}", snapshot.id).unwrap();
94 writeln!(&mut s, "graph: {}", snapshot.graph_path).unwrap();
95 Ok(s)
96}
97
98pub fn cmd_metrics_index(workspace: Option<&Path>, force: bool) -> Result<()> {
99 print!("{}", metrics_index_text(workspace, force)?);
100 Ok(())
101}
102
103pub fn metrics_quality_text(workspace: Option<&Path>, days: u32, json: bool) -> Result<String> {
104 let ws = workspace_path(workspace)?;
105 let store = open_workspace_read_store(&ws, false)?;
106 let end = now_ms();
107 let start = end.saturating_sub(days as u64 * 86_400_000);
108 let ws_str = ws.to_string_lossy().to_string();
109 let report = crate::metrics::quality::build_quality_report(&store, &ws_str, start, end)?;
110 if json {
111 return Ok(format!("{}\n", serde_json::to_string_pretty(&report)?));
112 }
113 Ok(format_quality(&report))
114}
115
116pub fn cmd_metrics_quality(workspace: Option<&Path>, days: u32, json: bool) -> Result<()> {
117 print!("{}", metrics_quality_text(workspace, days, json)?);
118 Ok(())
119}
120
121fn format_quality(report: &crate::metrics::quality::CaptureQualityReport) -> String {
122 format!(
123 "Capture quality\n events: {}\n proxy_events: {}\n trace_spans: {}\n token_coverage: {}%\n latency_coverage: {}%\n context_coverage: {}%\n proxy_correlation: {}%\n orphan_spans: {}\n",
124 report.events_total,
125 report.proxy_events,
126 report.trace_spans_total,
127 report.token_coverage_pct,
128 report.latency_coverage_pct,
129 report.context_coverage_pct,
130 report.proxy_correlation_pct,
131 report.orphan_span_count,
132 )
133}
134
135fn now_ms() -> u64 {
136 std::time::SystemTime::now()
137 .duration_since(std::time::UNIX_EPOCH)
138 .map(|d| d.as_millis() as u64)
139 .unwrap_or(0)
140}
141
142fn decorate_metrics(
143 workspace: &Path,
144 mut metrics: crate::metrics::types::MetricsReport,
145) -> crate::metrics::types::MetricsReport {
146 for row in &mut metrics.hottest_files {
147 row.path = scope::decorate_path(workspace, &row.path);
148 }
149 for row in &mut metrics.most_changed_files {
150 row.path = scope::decorate_path(workspace, &row.path);
151 }
152 for row in &mut metrics.most_complex_files {
153 row.path = scope::decorate_path(workspace, &row.path);
154 }
155 for row in &mut metrics.highest_risk_files {
156 row.path = scope::decorate_path(workspace, &row.path);
157 }
158 for row in &mut metrics.agent_pain_hotspots {
159 row.path = scope::decorate_path(workspace, &row.path);
160 }
161 metrics
162}
163
164fn merge_metrics(
165 rows: Vec<crate::metrics::types::MetricsReport>,
166) -> crate::metrics::types::MetricsReport {
167 let mut out = crate::metrics::types::MetricsReport {
168 snapshot: None,
169 hottest_files: Vec::new(),
170 most_changed_files: Vec::new(),
171 most_complex_files: Vec::new(),
172 highest_risk_files: Vec::new(),
173 slowest_tools: Vec::new(),
174 highest_token_tools: Vec::new(),
175 highest_reasoning_tools: Vec::new(),
176 agent_pain_hotspots: Vec::new(),
177 };
178 for row in rows {
179 out.hottest_files.extend(row.hottest_files);
180 out.most_changed_files.extend(row.most_changed_files);
181 out.most_complex_files.extend(row.most_complex_files);
182 out.highest_risk_files.extend(row.highest_risk_files);
183 out.agent_pain_hotspots.extend(row.agent_pain_hotspots);
184 merge_tool_rows(&mut out.slowest_tools, row.slowest_tools);
185 merge_tool_rows(&mut out.highest_token_tools, row.highest_token_tools);
186 merge_tool_rows(
187 &mut out.highest_reasoning_tools,
188 row.highest_reasoning_tools,
189 );
190 }
191 trim_file_rows(&mut out.hottest_files);
192 trim_file_rows(&mut out.most_changed_files);
193 trim_file_rows(&mut out.most_complex_files);
194 trim_file_rows(&mut out.highest_risk_files);
195 trim_file_rows(&mut out.agent_pain_hotspots);
196 trim_tool_rows(&mut out.slowest_tools, |row| row.p95_ms.unwrap_or(0));
197 trim_tool_rows(&mut out.highest_token_tools, |row| row.total_tokens);
198 trim_tool_rows(&mut out.highest_reasoning_tools, |row| {
199 row.total_reasoning_tokens
200 });
201 out
202}
203
204fn merge_tool_rows(
205 target: &mut Vec<crate::metrics::types::RankedTool>,
206 rows: Vec<crate::metrics::types::RankedTool>,
207) {
208 for row in rows {
209 if let Some(existing) = target.iter_mut().find(|item| item.tool == row.tool) {
210 existing.calls += row.calls;
211 existing.total_tokens += row.total_tokens;
212 existing.total_reasoning_tokens += row.total_reasoning_tokens;
213 existing.p50_ms = existing.p50_ms.max(row.p50_ms);
214 existing.p95_ms = existing.p95_ms.max(row.p95_ms);
215 continue;
216 }
217 target.push(row);
218 }
219}
220
221fn trim_file_rows(rows: &mut Vec<crate::metrics::types::RankedFile>) {
222 rows.sort_by(|a, b| b.value.cmp(&a.value).then_with(|| a.path.cmp(&b.path)));
223 rows.truncate(10);
224}
225
226fn trim_tool_rows<F>(rows: &mut Vec<crate::metrics::types::RankedTool>, rank: F)
227where
228 F: Fn(&crate::metrics::types::RankedTool) -> u64,
229{
230 rows.sort_by(|a, b| rank(b).cmp(&rank(a)).then_with(|| a.tool.cmp(&b.tool)));
231 rows.truncate(10);
232}
233
234fn maybe_enqueue_snapshot(
235 store: &Store,
236 cfg: &crate::core::config::Config,
237 ws: &std::path::Path,
238 snapshot: &crate::metrics::types::RepoSnapshotRecord,
239) -> Result<()> {
240 let Some(ctx) = ingest_ctx(cfg, ws.to_path_buf()) else {
241 return Ok(());
242 };
243 let facts = store.file_facts_for_snapshot(&snapshot.id)?;
244 let edges = store.repo_edges_for_snapshot(&snapshot.id)?;
245 smart::enqueue_repo_snapshot(store, snapshot, &facts, &edges, &ctx)?;
246 smart::enqueue_workspace_fact_snapshot(store, ws, &ctx)
247}
248
249pub fn print_human(metrics: &crate::metrics::types::MetricsReport) {
250 print!("{}", format_human(metrics));
251}
252
253fn format_files(title: &str, rows: &[crate::metrics::types::RankedFile]) -> String {
254 use std::fmt::Write;
255 let mut s = String::new();
256 writeln!(&mut s, "{title}").unwrap();
257 if rows.is_empty() {
258 writeln!(&mut s, " (none)").unwrap();
259 writeln!(&mut s).unwrap();
260 return s;
261 }
262 for row in rows.iter().take(5) {
263 writeln!(&mut s, " {:>8} {}", row.value, row.path).unwrap();
264 }
265 writeln!(&mut s).unwrap();
266 s
267}
268
269fn format_tools(title: &str, rows: &[crate::metrics::types::RankedTool]) -> String {
270 use std::fmt::Write;
271 let mut s = String::new();
272 writeln!(&mut s, "{title}").unwrap();
273 if rows.is_empty() {
274 writeln!(&mut s, " (none)").unwrap();
275 writeln!(&mut s).unwrap();
276 return s;
277 }
278 for row in rows.iter().take(5) {
279 let p95 = row
280 .p95_ms
281 .map(|v| format!("{v}ms"))
282 .unwrap_or_else(|| "-".into());
283 writeln!(
284 &mut s,
285 " {:<14} calls={} p95={} tok={} rtok={}",
286 row.tool, row.calls, p95, row.total_tokens, row.total_reasoning_tokens
287 )
288 .unwrap();
289 }
290 writeln!(&mut s).unwrap();
291 s
292}
293
294fn format_human(metrics: &crate::metrics::types::MetricsReport) -> String {
295 let mut out = String::new();
296 out.push_str(&format_files("Hottest files", &metrics.hottest_files));
297 out.push_str(&format_files("Most changed", &metrics.most_changed_files));
298 out.push_str(&format_files("Most complex", &metrics.most_complex_files));
299 out.push_str(&format_files("Highest risk", &metrics.highest_risk_files));
300 out.push_str(&format_tools("Slowest tools", &metrics.slowest_tools));
301 out.push_str(&format_tools(
302 "Highest token tools",
303 &metrics.highest_token_tools,
304 ));
305 out.push_str(&format_tools(
306 "Highest reasoning tools",
307 &metrics.highest_reasoning_tools,
308 ));
309 out.push_str(&format_files(
310 "Agent pain hotspots",
311 &metrics.agent_pain_hotspots,
312 ));
313 use std::fmt::Write;
314 let _ = writeln!(&mut out);
315 let _ = writeln!(&mut out, "Takeaway");
316 if let Some(f) = metrics.hottest_files.first() {
317 let _ = writeln!(
318 &mut out,
319 " · Review {} first (heat {}); pair with `kaizen insights` for session context",
320 f.path, f.value
321 );
322 }
323 if let Some(t) = metrics.slowest_tools.first() {
324 let p95 = t
325 .p95_ms
326 .map(|v| format!("{v}ms"))
327 .unwrap_or_else(|| "n/a".into());
328 let _ = writeln!(
329 &mut out,
330 " · Latency focus: {} p95 {} — tune or cache this tool path if it recurs",
331 t.tool, p95
332 );
333 }
334 if let Some(t) = metrics.highest_token_tools.first() {
335 let _ = writeln!(
336 &mut out,
337 " · Token sink: {} ({} total tok) — compare week over week with `kaizen metrics --days 30`",
338 t.tool, t.total_tokens
339 );
340 }
341 let _ = writeln!(
342 &mut out,
343 " · Next: `kaizen retro --days 7` for team-level bets"
344 );
345 out
346}