Skip to main content

kaizen/shell/
cli.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2//! CLI command implementations.
3
4use crate::collect::tail::claude::scan_claude_session_dir;
5use crate::collect::tail::codex::scan_codex_session_dir;
6use crate::collect::tail::copilot_cli::scan_copilot_cli_workspace;
7use crate::collect::tail::copilot_vscode::scan_copilot_vscode_workspace;
8use crate::collect::tail::cursor::scan_session_dir_all;
9use crate::collect::tail::goose::scan_goose_workspace;
10use crate::collect::tail::openclaw::scan_openclaw_workspace;
11use crate::collect::tail::opencode::scan_opencode_workspace;
12use crate::core::config;
13use crate::core::event::{Event, SessionRecord};
14use crate::metrics::report;
15use crate::shell::fmt::fmt_ts;
16use crate::shell::scope;
17use crate::store::{SYNC_STATE_LAST_AGENT_SCAN_MS, SYNC_STATE_LAST_AUTO_PRUNE_MS, Store};
18use anyhow::Result;
19use serde::Serialize;
20use std::collections::HashMap;
21use std::io::IsTerminal;
22use std::path::{Path, PathBuf};
23
24pub use crate::shell::init::cmd_init;
25pub use crate::shell::insights::cmd_insights;
26
27#[derive(Serialize)]
28struct SessionsListJson {
29    workspace: String,
30    #[serde(skip_serializing_if = "Vec::is_empty")]
31    workspaces: Vec<String>,
32    count: usize,
33    sessions: Vec<SessionRecord>,
34}
35
36#[derive(Serialize)]
37struct SummaryJsonOut {
38    workspace: String,
39    #[serde(skip_serializing_if = "Vec::is_empty")]
40    workspaces: Vec<String>,
41    #[serde(flatten)]
42    stats: crate::store::SummaryStats,
43    cost_usd: f64,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    hotspot: Option<crate::metrics::types::RankedFile>,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    slowest_tool: Option<crate::metrics::types::RankedTool>,
48}
49
50struct ScanSpinner(Option<indicatif::ProgressBar>);
51
52impl ScanSpinner {
53    fn start(msg: &'static str) -> Self {
54        if !std::io::stdout().is_terminal() {
55            return Self(None);
56        }
57        let p = indicatif::ProgressBar::new_spinner();
58        p.set_message(msg.to_string());
59        p.enable_steady_tick(std::time::Duration::from_millis(120));
60        Self(Some(p))
61    }
62}
63
64impl Drop for ScanSpinner {
65    fn drop(&mut self) {
66        if let Some(p) = self.0.take() {
67            p.finish_and_clear();
68        }
69    }
70}
71
72fn now_ms_u64() -> u64 {
73    std::time::SystemTime::now()
74        .duration_since(std::time::UNIX_EPOCH)
75        .unwrap_or_default()
76        .as_millis() as u64
77}
78
79/// Minimum interval between automatic local DB prunes after a successful rescan (24h).
80const AUTO_PRUNE_INTERVAL_MS: u64 = 86_400_000;
81
82pub(crate) fn maybe_auto_prune_after_scan(store: &Store, cfg: &config::Config) -> Result<()> {
83    if cfg.retention.hot_days == 0 {
84        return Ok(());
85    }
86    let now = now_ms_u64();
87    if let Some(last) = store.sync_state_get_u64(SYNC_STATE_LAST_AUTO_PRUNE_MS)?
88        && now.saturating_sub(last) < AUTO_PRUNE_INTERVAL_MS
89    {
90        return Ok(());
91    }
92    let cutoff = now.saturating_sub((cfg.retention.hot_days as u64).saturating_mul(86_400_000));
93    store.prune_sessions_started_before(cutoff as i64)?;
94    store.sync_state_set_u64(SYNC_STATE_LAST_AUTO_PRUNE_MS, now)?;
95    Ok(())
96}
97
98/// Full transcript rescan unless throttled by `[scan].min_rescan_seconds` or `refresh` is true.
99pub(crate) fn maybe_scan_all_agents(
100    ws: &Path,
101    cfg: &config::Config,
102    ws_str: &str,
103    store: &Store,
104    refresh: bool,
105) -> Result<()> {
106    let interval_ms = cfg.scan.min_rescan_seconds.saturating_mul(1000);
107    let now = now_ms_u64();
108    if !refresh
109        && interval_ms > 0
110        && let Some(last) = store.sync_state_get_u64(SYNC_STATE_LAST_AGENT_SCAN_MS)?
111        && now.saturating_sub(last) < interval_ms
112    {
113        return Ok(());
114    }
115    scan_all_agents(ws, cfg, ws_str, store)?;
116    store.sync_state_set_u64(SYNC_STATE_LAST_AGENT_SCAN_MS, now_ms_u64())?;
117    Ok(())
118}
119
120pub(crate) fn maybe_refresh_store(workspace: &Path, store: &Store, refresh: bool) -> Result<()> {
121    if !refresh {
122        return Ok(());
123    }
124    let cfg = config::load(workspace)?;
125    let ws_str = workspace.to_string_lossy().to_string();
126    maybe_scan_all_agents(workspace, &cfg, &ws_str, store, true)
127}
128
129fn combine_counts(rows: Vec<Vec<(String, u64)>>) -> Vec<(String, u64)> {
130    let mut counts = HashMap::new();
131    for set in rows {
132        for (key, value) in set {
133            *counts.entry(key).or_insert(0_u64) += value;
134        }
135    }
136    let mut out = counts.into_iter().collect::<Vec<_>>();
137    out.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
138    out
139}
140
141fn workspace_names(roots: &[PathBuf]) -> Vec<String> {
142    roots
143        .iter()
144        .map(|path| path.to_string_lossy().to_string())
145        .collect()
146}
147
148fn open_workspace_store(workspace: &Path) -> Result<Store> {
149    Store::open(&crate::core::workspace::db_path(workspace))
150}
151
152/// `kaizen sessions list` — same output as CLI stdout.
153pub fn sessions_list_text(
154    workspace: Option<&Path>,
155    json_out: bool,
156    refresh: bool,
157    all_workspaces: bool,
158) -> Result<String> {
159    let roots = scope::resolve(workspace, all_workspaces)?;
160    let mut sessions = Vec::new();
161    for workspace in &roots {
162        let store = open_workspace_store(workspace)?;
163        maybe_refresh_store(workspace, &store, refresh)?;
164        let ws_str = workspace.to_string_lossy().to_string();
165        sessions.extend(store.list_sessions(&ws_str)?);
166    }
167    sessions.sort_by(|a, b| {
168        b.started_at_ms
169            .cmp(&a.started_at_ms)
170            .then_with(|| a.id.cmp(&b.id))
171    });
172    let scope_label = scope::label(&roots);
173    let workspaces = if roots.len() > 1 {
174        workspace_names(&roots)
175    } else {
176        Vec::new()
177    };
178    if json_out {
179        return Ok(format!(
180            "{}\n",
181            serde_json::to_string_pretty(&SessionsListJson {
182                workspace: scope_label,
183                workspaces,
184                count: sessions.len(),
185                sessions,
186            })?
187        ));
188    }
189    use std::fmt::Write;
190    let mut out = String::new();
191    if roots.len() > 1 {
192        writeln!(&mut out, "Scope: {scope_label}").unwrap();
193        writeln!(&mut out).unwrap();
194    }
195    writeln!(
196        &mut out,
197        "{:<40} {:<10} {:<10} STARTED",
198        "ID", "AGENT", "STATUS"
199    )
200    .unwrap();
201    writeln!(&mut out, "{}", "-".repeat(80)).unwrap();
202    for s in &sessions {
203        writeln!(
204            &mut out,
205            "{:<40} {:<10} {:<10} {}",
206            s.id,
207            s.agent,
208            format!("{:?}", s.status),
209            fmt_ts(s.started_at_ms),
210        )
211        .unwrap();
212    }
213    if sessions.is_empty() {
214        writeln!(&mut out, "(no sessions)").unwrap();
215        sessions_empty_state_hints(&mut out);
216    }
217    Ok(out)
218}
219
220fn sessions_empty_state_hints(out: &mut String) {
221    use std::fmt::Write;
222    let _ = writeln!(out);
223    let _ = writeln!(out, "No sessions found for this workspace. Try:");
224    let _ = writeln!(out, "  · `kaizen doctor` — verify config and hooks");
225    let _ = writeln!(out, "  · a short agent session in this repo, then re-run");
226    let _ = writeln!(
227        out,
228        "  · docs: https://github.com/marquesds/kaizen/blob/main/docs/config.md (sources)"
229    );
230}
231
232/// `kaizen sessions list` — scan all agent transcripts, upsert sessions, print table.
233pub fn cmd_sessions_list(
234    workspace: Option<&Path>,
235    json_out: bool,
236    refresh: bool,
237    all_workspaces: bool,
238) -> Result<()> {
239    print!(
240        "{}",
241        sessions_list_text(workspace, json_out, refresh, all_workspaces)?
242    );
243    Ok(())
244}
245
246/// `kaizen sessions show` — same output as CLI stdout.
247pub fn session_show_text(id: &str, workspace: Option<&Path>) -> Result<String> {
248    let ws = workspace_path(workspace)?;
249    let store = open_workspace_store(&ws)?;
250    use std::fmt::Write;
251    let mut out = String::new();
252    match store.get_session(id)? {
253        Some(s) => {
254            writeln!(&mut out, "id:           {}", s.id).unwrap();
255            writeln!(&mut out, "agent:        {}", s.agent).unwrap();
256            writeln!(
257                &mut out,
258                "model:        {}",
259                s.model.as_deref().unwrap_or("-")
260            )
261            .unwrap();
262            writeln!(&mut out, "workspace:    {}", s.workspace).unwrap();
263            writeln!(&mut out, "started_at:   {}", fmt_ts(s.started_at_ms)).unwrap();
264            writeln!(
265                &mut out,
266                "ended_at:     {}",
267                s.ended_at_ms.map(fmt_ts).unwrap_or_else(|| "-".to_string())
268            )
269            .unwrap();
270            writeln!(&mut out, "status:       {:?}", s.status).unwrap();
271            writeln!(&mut out, "trace_path:   {}", s.trace_path).unwrap();
272            if let Some(fp) = &s.prompt_fingerprint {
273                writeln!(&mut out, "prompt_fp:    {fp}").unwrap();
274                if let Ok(Some(snap)) = store.get_prompt_snapshot(fp) {
275                    for f in snap.files() {
276                        writeln!(&mut out, "  - {}", f.path).unwrap();
277                    }
278                }
279            }
280        }
281        None => anyhow::bail!("session not found: {id} — try `kaizen sessions list`"),
282    }
283    let evals = store.list_evals_for_session(id).unwrap_or_default();
284    if !evals.is_empty() {
285        writeln!(&mut out, "evals:").unwrap();
286        for e in &evals {
287            writeln!(
288                &mut out,
289                "  {} score={:.2} flagged={} {}",
290                e.rubric_id, e.score, e.flagged, e.rationale
291            )
292            .unwrap();
293        }
294    }
295    Ok(out)
296}
297
298/// `kaizen sessions show <id>` — print full session fields.
299pub fn cmd_session_show(id: &str, workspace: Option<&Path>) -> Result<()> {
300    print!("{}", session_show_text(id, workspace)?);
301    Ok(())
302}
303
304/// `kaizen summary` — same output as CLI stdout.
305pub fn summary_text(
306    workspace: Option<&Path>,
307    json_out: bool,
308    refresh: bool,
309    all_workspaces: bool,
310    source: crate::core::data_source::DataSource,
311) -> Result<String> {
312    let roots = scope::resolve(workspace, all_workspaces)?;
313    let mut total_cost_usd_e6 = 0_i64;
314    let mut session_count = 0_u64;
315    let mut by_agent = Vec::new();
316    let mut by_model = Vec::new();
317    let mut top_tools = Vec::new();
318    let mut hottest = Vec::new();
319    let mut slowest = Vec::new();
320
321    for workspace in &roots {
322        let cfg = config::load(workspace)?;
323        let store = open_workspace_store(workspace)?;
324        crate::shell::remote_pull::maybe_telemetry_pull(workspace, &store, &cfg, source, refresh)?;
325        maybe_refresh_store(workspace, &store, refresh)?;
326        let ws_str = workspace.to_string_lossy().to_string();
327        let mut stats = store.summary_stats(&ws_str)?;
328        if source != crate::core::data_source::DataSource::Local
329            && let Ok(Some(agg)) =
330                crate::shell::remote_observe::try_remote_event_agg(&store, &cfg, workspace)
331        {
332            stats = crate::shell::remote_observe::merge_summary_stats(stats, &agg, source);
333        }
334        total_cost_usd_e6 += stats.total_cost_usd_e6;
335        session_count += stats.session_count;
336        by_agent.push(stats.by_agent);
337        by_model.push(stats.by_model);
338        top_tools.push(stats.top_tools);
339        if let Ok(metrics) = report::build_report(&store, &ws_str, 7) {
340            if let Some(file) = metrics.hottest_files.first().cloned() {
341                hottest.push(if roots.len() == 1 {
342                    file
343                } else {
344                    crate::metrics::types::RankedFile {
345                        path: scope::decorate_path(workspace, &file.path),
346                        ..file
347                    }
348                });
349            }
350            if let Some(tool) = metrics.slowest_tools.first().cloned() {
351                slowest.push(tool);
352            }
353        }
354    }
355
356    let stats = crate::store::SummaryStats {
357        session_count,
358        total_cost_usd_e6,
359        by_agent: combine_counts(by_agent),
360        by_model: combine_counts(by_model),
361        top_tools: combine_counts(top_tools),
362    };
363    let cost_dollars = stats.total_cost_usd_e6 as f64 / 1_000_000.0;
364    let hotspot = hottest
365        .into_iter()
366        .max_by(|a, b| a.value.cmp(&b.value).then_with(|| b.path.cmp(&a.path)));
367    let slowest_tool = slowest.into_iter().max_by(|a, b| {
368        a.p95_ms
369            .unwrap_or(0)
370            .cmp(&b.p95_ms.unwrap_or(0))
371            .then_with(|| b.tool.cmp(&a.tool))
372    });
373    let scope_label = scope::label(&roots);
374    let workspaces = if roots.len() > 1 {
375        workspace_names(&roots)
376    } else {
377        Vec::new()
378    };
379    if json_out {
380        return Ok(format!(
381            "{}\n",
382            serde_json::to_string_pretty(&SummaryJsonOut {
383                workspace: scope_label,
384                workspaces,
385                cost_usd: cost_dollars,
386                stats,
387                hotspot,
388                slowest_tool,
389            })?
390        ));
391    }
392    use std::fmt::Write;
393    let mut out = String::new();
394    if roots.len() > 1 {
395        writeln!(&mut out, "Scope: {}", scope::label(&roots)).unwrap();
396    }
397    writeln!(
398        &mut out,
399        "Sessions: {}   Cost: ${:.2}",
400        stats.session_count, cost_dollars
401    )
402    .unwrap();
403
404    if !stats.by_agent.is_empty() {
405        let parts: Vec<String> = stats
406            .by_agent
407            .iter()
408            .map(|(a, n)| format!("{a} {n}"))
409            .collect();
410        writeln!(&mut out, "By agent:  {}", parts.join(" · ")).unwrap();
411    }
412    if !stats.by_model.is_empty() {
413        let parts: Vec<String> = stats
414            .by_model
415            .iter()
416            .map(|(m, n)| format!("{m} {n}"))
417            .collect();
418        writeln!(&mut out, "By model:  {}", parts.join(" · ")).unwrap();
419    }
420    if !stats.top_tools.is_empty() {
421        let parts: Vec<String> = stats
422            .top_tools
423            .iter()
424            .take(5)
425            .map(|(t, n)| format!("{t} {n}"))
426            .collect();
427        writeln!(&mut out, "Top tools: {}", parts.join(" · ")).unwrap();
428    }
429    if let Some(file) = hotspot {
430        writeln!(&mut out, "Hotspot:   {} ({})", file.path, file.value).unwrap();
431    }
432    if let Some(tool) = slowest_tool {
433        let p95 = tool
434            .p95_ms
435            .map(|v| format!("{v}ms"))
436            .unwrap_or_else(|| "-".into());
437        writeln!(&mut out, "Slowest:   {} p95 {}", tool.tool, p95).unwrap();
438    }
439    Ok(out)
440}
441
442/// `kaizen summary` — aggregate session + cost stats across all agents.
443pub fn cmd_summary(
444    workspace: Option<&Path>,
445    json_out: bool,
446    refresh: bool,
447    all_workspaces: bool,
448    source: crate::core::data_source::DataSource,
449) -> Result<()> {
450    print!(
451        "{}",
452        summary_text(workspace, json_out, refresh, all_workspaces, source,)?
453    );
454    Ok(())
455}
456
457pub(crate) fn scan_all_agents(
458    ws: &Path,
459    cfg: &config::Config,
460    ws_str: &str,
461    store: &Store,
462) -> Result<()> {
463    let _spin = ScanSpinner::start("Scanning agent sessions…");
464    let slug = workspace_slug(ws_str);
465    let sync_ctx = crate::sync::ingest_ctx(cfg, ws.to_path_buf());
466
467    for root in &cfg.scan.roots {
468        let expanded = expand_home(root);
469        let cursor_dir = PathBuf::from(&expanded)
470            .join(&slug)
471            .join("agent-transcripts");
472        scan_agent_dirs(
473            &cursor_dir,
474            store,
475            |p| {
476                scan_session_dir_all(p).map(|sessions| {
477                    sessions
478                        .into_iter()
479                        .map(|(mut r, evs)| {
480                            r.workspace = ws_str.to_string();
481                            (r, evs)
482                        })
483                        .collect()
484                })
485            },
486            sync_ctx.as_ref(),
487        )?;
488    }
489
490    let home = std::env::var("HOME").unwrap_or_default();
491
492    let claude_dir = PathBuf::from(&home)
493        .join(".claude/projects")
494        .join(&slug)
495        .join("sessions");
496    scan_agent_dirs(
497        &claude_dir,
498        store,
499        |p| {
500            scan_claude_session_dir(p).map(|(mut r, evs)| {
501                r.workspace = ws_str.to_string();
502                vec![(r, evs)]
503            })
504        },
505        sync_ctx.as_ref(),
506    )?;
507
508    let codex_dir = PathBuf::from(&home).join(".codex/sessions").join(&slug);
509    scan_agent_dirs(
510        &codex_dir,
511        store,
512        |p| {
513            scan_codex_session_dir(p).map(|(mut r, evs)| {
514                r.workspace = ws_str.to_string();
515                vec![(r, evs)]
516            })
517        },
518        sync_ctx.as_ref(),
519    )?;
520
521    let tail = &cfg.sources.tail;
522    let home_pb = PathBuf::from(&home);
523    if tail.goose {
524        let sessions = scan_goose_workspace(&home_pb, ws)?;
525        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
526    }
527    if tail.openclaw {
528        let sessions = scan_openclaw_workspace(ws)?;
529        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
530    }
531    if tail.opencode {
532        let sessions = scan_opencode_workspace(ws)?;
533        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
534    }
535    if tail.copilot_cli {
536        let sessions = scan_copilot_cli_workspace(ws)?;
537        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
538    }
539    if tail.copilot_vscode {
540        let sessions = scan_copilot_vscode_workspace(ws)?;
541        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
542    }
543
544    maybe_auto_prune_after_scan(store, cfg)?;
545    Ok(())
546}
547
548fn persist_session_batch(
549    store: &Store,
550    sessions: Vec<(SessionRecord, Vec<Event>)>,
551    sync_ctx: Option<&crate::sync::SyncIngestContext>,
552) -> Result<()> {
553    for (mut record, events) in sessions {
554        if record.start_commit.is_none() && !record.workspace.is_empty() {
555            let binding = crate::core::repo::binding_for_session(
556                Path::new(&record.workspace),
557                record.started_at_ms,
558                record.ended_at_ms,
559            );
560            record.start_commit = binding.start_commit;
561            record.end_commit = binding.end_commit;
562            record.branch = binding.branch;
563            record.dirty_start = binding.dirty_start;
564            record.dirty_end = binding.dirty_end;
565            record.repo_binding_source = binding.source;
566        }
567        store.upsert_session(&record)?;
568        for ev in events {
569            store.append_event_with_sync(&ev, sync_ctx)?;
570        }
571    }
572    Ok(())
573}
574
575pub(crate) fn scan_agent_dirs<F>(
576    dir: &Path,
577    store: &Store,
578    scanner: F,
579    sync_ctx: Option<&crate::sync::SyncIngestContext>,
580) -> Result<()>
581where
582    F: Fn(&Path) -> Result<Vec<(SessionRecord, Vec<Event>)>>,
583{
584    if !dir.exists() {
585        return Ok(());
586    }
587    for entry in std::fs::read_dir(dir)?.filter_map(|e| e.ok()) {
588        if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
589            continue;
590        }
591        match scanner(&entry.path()) {
592            Ok(sessions) => {
593                for (mut record, events) in sessions {
594                    if record.start_commit.is_none() && !record.workspace.is_empty() {
595                        let binding = crate::core::repo::binding_for_session(
596                            Path::new(&record.workspace),
597                            record.started_at_ms,
598                            record.ended_at_ms,
599                        );
600                        record.start_commit = binding.start_commit;
601                        record.end_commit = binding.end_commit;
602                        record.branch = binding.branch;
603                        record.dirty_start = binding.dirty_start;
604                        record.dirty_end = binding.dirty_end;
605                        record.repo_binding_source = binding.source;
606                    }
607                    store.upsert_session(&record)?;
608                    for ev in events {
609                        store.append_event_with_sync(&ev, sync_ctx)?;
610                    }
611                }
612            }
613            Err(e) => tracing::warn!("scan {:?}: {e}", entry.path()),
614        }
615    }
616    Ok(())
617}
618
619pub(crate) fn workspace_path(workspace: Option<&Path>) -> Result<PathBuf> {
620    crate::core::workspace::resolve(workspace)
621}
622
623/// Convert workspace path to cursor project slug.
624/// `/Users/lucas/Projects/kaizen` → `Users-lucas-Projects-kaizen`
625pub(crate) fn workspace_slug(ws: &str) -> String {
626    ws.trim_start_matches('/').replace('/', "-")
627}
628
629pub(crate) fn expand_home(path: &str) -> String {
630    if let (Some(rest), Ok(home)) = (path.strip_prefix("~/"), std::env::var("HOME")) {
631        return format!("{home}/{rest}");
632    }
633    path.to_string()
634}