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    let fb = store
296        .feedback_for_sessions(&[id.to_string()])
297        .unwrap_or_default();
298    if let Some(r) = fb.get(id) {
299        let score = r
300            .score
301            .as_ref()
302            .map(|s| s.0.to_string())
303            .unwrap_or_else(|| "-".into());
304        let label = r
305            .label
306            .as_ref()
307            .map(|l| l.to_string())
308            .unwrap_or_else(|| "-".into());
309        writeln!(&mut out, "feedback:     score={score} label={label}").unwrap();
310        if let Some(n) = &r.note {
311            writeln!(&mut out, "  note: {n}").unwrap();
312        }
313    }
314    Ok(out)
315}
316
317/// `kaizen sessions show <id>` — print full session fields.
318pub fn cmd_session_show(id: &str, workspace: Option<&Path>) -> Result<()> {
319    print!("{}", session_show_text(id, workspace)?);
320    Ok(())
321}
322
323pub fn sessions_tree_text(id: &str, max_depth: u32, workspace: Option<&Path>) -> Result<String> {
324    let ws = workspace_path(workspace)?;
325    let store = open_workspace_store(&ws)?;
326    let nodes = store.session_span_tree(id)?;
327    let total_cost: i64 = nodes.iter().map(|n| n.subtree_cost_usd_e6).sum();
328    let mut out = String::new();
329    for node in &nodes {
330        render_node(&mut out, node, 0, max_depth, total_cost);
331    }
332    Ok(out)
333}
334
335fn render_node(
336    out: &mut String,
337    node: &crate::store::span_tree::SpanNode,
338    depth: u32,
339    max_depth: u32,
340    session_total: i64,
341) {
342    use std::fmt::Write;
343    if depth > max_depth {
344        return;
345    }
346    let indent = "│  ".repeat(depth as usize);
347    let prefix = if depth == 0 { "┌─ " } else { "├─ " };
348    let cost_str = match node.span.subtree_cost_usd_e6 {
349        Some(c) => {
350            let pct = if session_total > 0 {
351                c * 100 / session_total
352            } else {
353                0
354            };
355            let flag = if pct > 40 { " ⚡" } else { "" };
356            format!(" ${:.4}{}", c as f64 / 1_000_000.0, flag)
357        }
358        None => String::new(),
359    };
360    writeln!(
361        out,
362        "{}{}{} [{}]{}",
363        indent, prefix, node.span.tool, node.span.status, cost_str
364    )
365    .unwrap();
366    for child in &node.children {
367        render_node(out, child, depth + 1, max_depth, session_total);
368    }
369}
370
371/// `kaizen sessions tree <id>` — produce text output (ASCII or JSON).
372pub fn cmd_sessions_tree_text(
373    id: &str,
374    depth: u32,
375    json: bool,
376    workspace: Option<&Path>,
377) -> Result<String> {
378    if json {
379        let ws = workspace_path(workspace)?;
380        let store = open_workspace_store(&ws)?;
381        let nodes = store.session_span_tree(id)?;
382        Ok(serde_json::to_string_pretty(&nodes)?)
383    } else {
384        sessions_tree_text(id, depth, workspace)
385    }
386}
387
388/// `kaizen sessions tree <id>` — print ASCII span tree.
389pub fn cmd_sessions_tree(id: &str, depth: u32, json: bool, workspace: Option<&Path>) -> Result<()> {
390    print!("{}", cmd_sessions_tree_text(id, depth, json, workspace)?);
391    Ok(())
392}
393
394/// `kaizen summary` — same output as CLI stdout.
395pub fn summary_text(
396    workspace: Option<&Path>,
397    json_out: bool,
398    refresh: bool,
399    all_workspaces: bool,
400    source: crate::core::data_source::DataSource,
401) -> Result<String> {
402    let roots = scope::resolve(workspace, all_workspaces)?;
403    let mut total_cost_usd_e6 = 0_i64;
404    let mut session_count = 0_u64;
405    let mut by_agent = Vec::new();
406    let mut by_model = Vec::new();
407    let mut top_tools = Vec::new();
408    let mut hottest = Vec::new();
409    let mut slowest = Vec::new();
410
411    for workspace in &roots {
412        let cfg = config::load(workspace)?;
413        let store = open_workspace_store(workspace)?;
414        crate::shell::remote_pull::maybe_telemetry_pull(workspace, &store, &cfg, source, refresh)?;
415        maybe_refresh_store(workspace, &store, refresh)?;
416        let ws_str = workspace.to_string_lossy().to_string();
417        let read_store = Store::open_read_only(&crate::core::workspace::db_path(workspace))?;
418        let mut stats = read_store.summary_stats(&ws_str)?;
419        if source != crate::core::data_source::DataSource::Local
420            && let Ok(Some(agg)) =
421                crate::shell::remote_observe::try_remote_event_agg(&read_store, &cfg, workspace)
422        {
423            stats = crate::shell::remote_observe::merge_summary_stats(stats, &agg, source);
424        }
425        total_cost_usd_e6 += stats.total_cost_usd_e6;
426        session_count += stats.session_count;
427        by_agent.push(stats.by_agent);
428        by_model.push(stats.by_model);
429        top_tools.push(stats.top_tools);
430        if let Ok(metrics) = report::build_report(&read_store, &ws_str, 7) {
431            if let Some(file) = metrics.hottest_files.first().cloned() {
432                hottest.push(if roots.len() == 1 {
433                    file
434                } else {
435                    crate::metrics::types::RankedFile {
436                        path: scope::decorate_path(workspace, &file.path),
437                        ..file
438                    }
439                });
440            }
441            if let Some(tool) = metrics.slowest_tools.first().cloned() {
442                slowest.push(tool);
443            }
444        }
445    }
446
447    let stats = crate::store::SummaryStats {
448        session_count,
449        total_cost_usd_e6,
450        by_agent: combine_counts(by_agent),
451        by_model: combine_counts(by_model),
452        top_tools: combine_counts(top_tools),
453    };
454    let cost_dollars = stats.total_cost_usd_e6 as f64 / 1_000_000.0;
455    let hotspot = hottest
456        .into_iter()
457        .max_by(|a, b| a.value.cmp(&b.value).then_with(|| b.path.cmp(&a.path)));
458    let slowest_tool = slowest.into_iter().max_by(|a, b| {
459        a.p95_ms
460            .unwrap_or(0)
461            .cmp(&b.p95_ms.unwrap_or(0))
462            .then_with(|| b.tool.cmp(&a.tool))
463    });
464    let scope_label = scope::label(&roots);
465    let workspaces = if roots.len() > 1 {
466        workspace_names(&roots)
467    } else {
468        Vec::new()
469    };
470    if json_out {
471        return Ok(format!(
472            "{}\n",
473            serde_json::to_string_pretty(&SummaryJsonOut {
474                workspace: scope_label,
475                workspaces,
476                cost_usd: cost_dollars,
477                stats,
478                hotspot,
479                slowest_tool,
480            })?
481        ));
482    }
483    use std::fmt::Write;
484    let mut out = String::new();
485    if roots.len() > 1 {
486        writeln!(&mut out, "Scope: {}", scope::label(&roots)).unwrap();
487    }
488    writeln!(
489        &mut out,
490        "Sessions: {}   Cost: ${:.2}",
491        stats.session_count, cost_dollars
492    )
493    .unwrap();
494
495    if !stats.by_agent.is_empty() {
496        let parts: Vec<String> = stats
497            .by_agent
498            .iter()
499            .map(|(a, n)| format!("{a} {n}"))
500            .collect();
501        writeln!(&mut out, "By agent:  {}", parts.join(" · ")).unwrap();
502    }
503    if !stats.by_model.is_empty() {
504        let parts: Vec<String> = stats
505            .by_model
506            .iter()
507            .map(|(m, n)| format!("{m} {n}"))
508            .collect();
509        writeln!(&mut out, "By model:  {}", parts.join(" · ")).unwrap();
510    }
511    if !stats.top_tools.is_empty() {
512        let parts: Vec<String> = stats
513            .top_tools
514            .iter()
515            .take(5)
516            .map(|(t, n)| format!("{t} {n}"))
517            .collect();
518        writeln!(&mut out, "Top tools: {}", parts.join(" · ")).unwrap();
519    }
520    if let Some(file) = hotspot {
521        writeln!(&mut out, "Hotspot:   {} ({})", file.path, file.value).unwrap();
522    }
523    if let Some(tool) = slowest_tool {
524        let p95 = tool
525            .p95_ms
526            .map(|v| format!("{v}ms"))
527            .unwrap_or_else(|| "-".into());
528        writeln!(&mut out, "Slowest:   {} p95 {}", tool.tool, p95).unwrap();
529    }
530    Ok(out)
531}
532
533/// `kaizen summary` — aggregate session + cost stats across all agents.
534pub fn cmd_summary(
535    workspace: Option<&Path>,
536    json_out: bool,
537    refresh: bool,
538    all_workspaces: bool,
539    source: crate::core::data_source::DataSource,
540) -> Result<()> {
541    print!(
542        "{}",
543        summary_text(workspace, json_out, refresh, all_workspaces, source,)?
544    );
545    Ok(())
546}
547
548pub(crate) fn scan_all_agents(
549    ws: &Path,
550    cfg: &config::Config,
551    ws_str: &str,
552    store: &Store,
553) -> Result<()> {
554    let _spin = ScanSpinner::start("Scanning agent sessions…");
555    let slug = workspace_slug(ws_str);
556    let sync_ctx = crate::sync::ingest_ctx(cfg, ws.to_path_buf());
557
558    for root in &cfg.scan.roots {
559        let expanded = expand_home(root);
560        let cursor_dir = PathBuf::from(&expanded)
561            .join(&slug)
562            .join("agent-transcripts");
563        scan_agent_dirs(
564            &cursor_dir,
565            store,
566            |p| {
567                scan_session_dir_all(p).map(|sessions| {
568                    sessions
569                        .into_iter()
570                        .map(|(mut r, evs)| {
571                            r.workspace = ws_str.to_string();
572                            (r, evs)
573                        })
574                        .collect()
575                })
576            },
577            sync_ctx.as_ref(),
578        )?;
579    }
580
581    let home = std::env::var("HOME").unwrap_or_default();
582
583    let claude_dir = PathBuf::from(&home)
584        .join(".claude/projects")
585        .join(&slug)
586        .join("sessions");
587    scan_agent_dirs(
588        &claude_dir,
589        store,
590        |p| {
591            scan_claude_session_dir(p).map(|(mut r, evs)| {
592                r.workspace = ws_str.to_string();
593                vec![(r, evs)]
594            })
595        },
596        sync_ctx.as_ref(),
597    )?;
598
599    let codex_dir = PathBuf::from(&home).join(".codex/sessions").join(&slug);
600    scan_agent_dirs(
601        &codex_dir,
602        store,
603        |p| {
604            scan_codex_session_dir(p).map(|(mut r, evs)| {
605                r.workspace = ws_str.to_string();
606                vec![(r, evs)]
607            })
608        },
609        sync_ctx.as_ref(),
610    )?;
611
612    let tail = &cfg.sources.tail;
613    let home_pb = PathBuf::from(&home);
614    if tail.goose {
615        let sessions = scan_goose_workspace(&home_pb, ws)?;
616        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
617    }
618    if tail.openclaw {
619        let sessions = scan_openclaw_workspace(ws)?;
620        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
621    }
622    if tail.opencode {
623        let sessions = scan_opencode_workspace(ws)?;
624        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
625    }
626    if tail.copilot_cli {
627        let sessions = scan_copilot_cli_workspace(ws)?;
628        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
629    }
630    if tail.copilot_vscode {
631        let sessions = scan_copilot_vscode_workspace(ws)?;
632        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
633    }
634
635    maybe_auto_prune_after_scan(store, cfg)?;
636    Ok(())
637}
638
639fn persist_session_batch(
640    store: &Store,
641    sessions: Vec<(SessionRecord, Vec<Event>)>,
642    sync_ctx: Option<&crate::sync::SyncIngestContext>,
643) -> Result<()> {
644    for (mut record, events) in sessions {
645        if record.start_commit.is_none() && !record.workspace.is_empty() {
646            let binding = crate::core::repo::binding_for_session(
647                Path::new(&record.workspace),
648                record.started_at_ms,
649                record.ended_at_ms,
650            );
651            record.start_commit = binding.start_commit;
652            record.end_commit = binding.end_commit;
653            record.branch = binding.branch;
654            record.dirty_start = binding.dirty_start;
655            record.dirty_end = binding.dirty_end;
656            record.repo_binding_source = binding.source;
657        }
658        store.upsert_session(&record)?;
659        let flush_ms = record.ended_at_ms.unwrap_or(record.started_at_ms);
660        for ev in events {
661            store.append_event_with_sync(&ev, sync_ctx)?;
662        }
663        if record.status == crate::core::event::SessionStatus::Done {
664            store.flush_projector_session(&record.id, flush_ms)?;
665        }
666    }
667    Ok(())
668}
669
670pub(crate) fn scan_agent_dirs<F>(
671    dir: &Path,
672    store: &Store,
673    scanner: F,
674    sync_ctx: Option<&crate::sync::SyncIngestContext>,
675) -> Result<()>
676where
677    F: Fn(&Path) -> Result<Vec<(SessionRecord, Vec<Event>)>>,
678{
679    if !dir.exists() {
680        return Ok(());
681    }
682    for entry in std::fs::read_dir(dir)?.filter_map(|e| e.ok()) {
683        if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
684            continue;
685        }
686        match scanner(&entry.path()) {
687            Ok(sessions) => {
688                for (mut record, events) in sessions {
689                    if record.start_commit.is_none() && !record.workspace.is_empty() {
690                        let binding = crate::core::repo::binding_for_session(
691                            Path::new(&record.workspace),
692                            record.started_at_ms,
693                            record.ended_at_ms,
694                        );
695                        record.start_commit = binding.start_commit;
696                        record.end_commit = binding.end_commit;
697                        record.branch = binding.branch;
698                        record.dirty_start = binding.dirty_start;
699                        record.dirty_end = binding.dirty_end;
700                        record.repo_binding_source = binding.source;
701                    }
702                    store.upsert_session(&record)?;
703                    let flush_ms = record.ended_at_ms.unwrap_or(record.started_at_ms);
704                    for ev in events {
705                        store.append_event_with_sync(&ev, sync_ctx)?;
706                    }
707                    if record.status == crate::core::event::SessionStatus::Done {
708                        store.flush_projector_session(&record.id, flush_ms)?;
709                    }
710                }
711            }
712            Err(e) => tracing::warn!("scan {:?}: {e}", entry.path()),
713        }
714    }
715    Ok(())
716}
717
718pub(crate) fn workspace_path(workspace: Option<&Path>) -> Result<PathBuf> {
719    crate::core::workspace::resolve(workspace)
720}
721
722/// Convert workspace path to cursor project slug.
723/// `/Users/lucas/Projects/kaizen` → `Users-lucas-Projects-kaizen`
724pub(crate) fn workspace_slug(ws: &str) -> String {
725    ws.trim_start_matches('/').replace('/', "-")
726}
727
728pub(crate) fn expand_home(path: &str) -> String {
729    if let (Some(rest), Ok(home)) = (path.strip_prefix("~/"), std::env::var("HOME")) {
730        return format!("{home}/{rest}");
731    }
732    path.to_string()
733}