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 mut stats = store.summary_stats(&ws_str)?;
418        if source != crate::core::data_source::DataSource::Local
419            && let Ok(Some(agg)) =
420                crate::shell::remote_observe::try_remote_event_agg(&store, &cfg, workspace)
421        {
422            stats = crate::shell::remote_observe::merge_summary_stats(stats, &agg, source);
423        }
424        total_cost_usd_e6 += stats.total_cost_usd_e6;
425        session_count += stats.session_count;
426        by_agent.push(stats.by_agent);
427        by_model.push(stats.by_model);
428        top_tools.push(stats.top_tools);
429        if let Ok(metrics) = report::build_report(&store, &ws_str, 7) {
430            if let Some(file) = metrics.hottest_files.first().cloned() {
431                hottest.push(if roots.len() == 1 {
432                    file
433                } else {
434                    crate::metrics::types::RankedFile {
435                        path: scope::decorate_path(workspace, &file.path),
436                        ..file
437                    }
438                });
439            }
440            if let Some(tool) = metrics.slowest_tools.first().cloned() {
441                slowest.push(tool);
442            }
443        }
444    }
445
446    let stats = crate::store::SummaryStats {
447        session_count,
448        total_cost_usd_e6,
449        by_agent: combine_counts(by_agent),
450        by_model: combine_counts(by_model),
451        top_tools: combine_counts(top_tools),
452    };
453    let cost_dollars = stats.total_cost_usd_e6 as f64 / 1_000_000.0;
454    let hotspot = hottest
455        .into_iter()
456        .max_by(|a, b| a.value.cmp(&b.value).then_with(|| b.path.cmp(&a.path)));
457    let slowest_tool = slowest.into_iter().max_by(|a, b| {
458        a.p95_ms
459            .unwrap_or(0)
460            .cmp(&b.p95_ms.unwrap_or(0))
461            .then_with(|| b.tool.cmp(&a.tool))
462    });
463    let scope_label = scope::label(&roots);
464    let workspaces = if roots.len() > 1 {
465        workspace_names(&roots)
466    } else {
467        Vec::new()
468    };
469    if json_out {
470        return Ok(format!(
471            "{}\n",
472            serde_json::to_string_pretty(&SummaryJsonOut {
473                workspace: scope_label,
474                workspaces,
475                cost_usd: cost_dollars,
476                stats,
477                hotspot,
478                slowest_tool,
479            })?
480        ));
481    }
482    use std::fmt::Write;
483    let mut out = String::new();
484    if roots.len() > 1 {
485        writeln!(&mut out, "Scope: {}", scope::label(&roots)).unwrap();
486    }
487    writeln!(
488        &mut out,
489        "Sessions: {}   Cost: ${:.2}",
490        stats.session_count, cost_dollars
491    )
492    .unwrap();
493
494    if !stats.by_agent.is_empty() {
495        let parts: Vec<String> = stats
496            .by_agent
497            .iter()
498            .map(|(a, n)| format!("{a} {n}"))
499            .collect();
500        writeln!(&mut out, "By agent:  {}", parts.join(" · ")).unwrap();
501    }
502    if !stats.by_model.is_empty() {
503        let parts: Vec<String> = stats
504            .by_model
505            .iter()
506            .map(|(m, n)| format!("{m} {n}"))
507            .collect();
508        writeln!(&mut out, "By model:  {}", parts.join(" · ")).unwrap();
509    }
510    if !stats.top_tools.is_empty() {
511        let parts: Vec<String> = stats
512            .top_tools
513            .iter()
514            .take(5)
515            .map(|(t, n)| format!("{t} {n}"))
516            .collect();
517        writeln!(&mut out, "Top tools: {}", parts.join(" · ")).unwrap();
518    }
519    if let Some(file) = hotspot {
520        writeln!(&mut out, "Hotspot:   {} ({})", file.path, file.value).unwrap();
521    }
522    if let Some(tool) = slowest_tool {
523        let p95 = tool
524            .p95_ms
525            .map(|v| format!("{v}ms"))
526            .unwrap_or_else(|| "-".into());
527        writeln!(&mut out, "Slowest:   {} p95 {}", tool.tool, p95).unwrap();
528    }
529    Ok(out)
530}
531
532/// `kaizen summary` — aggregate session + cost stats across all agents.
533pub fn cmd_summary(
534    workspace: Option<&Path>,
535    json_out: bool,
536    refresh: bool,
537    all_workspaces: bool,
538    source: crate::core::data_source::DataSource,
539) -> Result<()> {
540    print!(
541        "{}",
542        summary_text(workspace, json_out, refresh, all_workspaces, source,)?
543    );
544    Ok(())
545}
546
547pub(crate) fn scan_all_agents(
548    ws: &Path,
549    cfg: &config::Config,
550    ws_str: &str,
551    store: &Store,
552) -> Result<()> {
553    let _spin = ScanSpinner::start("Scanning agent sessions…");
554    let slug = workspace_slug(ws_str);
555    let sync_ctx = crate::sync::ingest_ctx(cfg, ws.to_path_buf());
556
557    for root in &cfg.scan.roots {
558        let expanded = expand_home(root);
559        let cursor_dir = PathBuf::from(&expanded)
560            .join(&slug)
561            .join("agent-transcripts");
562        scan_agent_dirs(
563            &cursor_dir,
564            store,
565            |p| {
566                scan_session_dir_all(p).map(|sessions| {
567                    sessions
568                        .into_iter()
569                        .map(|(mut r, evs)| {
570                            r.workspace = ws_str.to_string();
571                            (r, evs)
572                        })
573                        .collect()
574                })
575            },
576            sync_ctx.as_ref(),
577        )?;
578    }
579
580    let home = std::env::var("HOME").unwrap_or_default();
581
582    let claude_dir = PathBuf::from(&home)
583        .join(".claude/projects")
584        .join(&slug)
585        .join("sessions");
586    scan_agent_dirs(
587        &claude_dir,
588        store,
589        |p| {
590            scan_claude_session_dir(p).map(|(mut r, evs)| {
591                r.workspace = ws_str.to_string();
592                vec![(r, evs)]
593            })
594        },
595        sync_ctx.as_ref(),
596    )?;
597
598    let codex_dir = PathBuf::from(&home).join(".codex/sessions").join(&slug);
599    scan_agent_dirs(
600        &codex_dir,
601        store,
602        |p| {
603            scan_codex_session_dir(p).map(|(mut r, evs)| {
604                r.workspace = ws_str.to_string();
605                vec![(r, evs)]
606            })
607        },
608        sync_ctx.as_ref(),
609    )?;
610
611    let tail = &cfg.sources.tail;
612    let home_pb = PathBuf::from(&home);
613    if tail.goose {
614        let sessions = scan_goose_workspace(&home_pb, ws)?;
615        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
616    }
617    if tail.openclaw {
618        let sessions = scan_openclaw_workspace(ws)?;
619        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
620    }
621    if tail.opencode {
622        let sessions = scan_opencode_workspace(ws)?;
623        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
624    }
625    if tail.copilot_cli {
626        let sessions = scan_copilot_cli_workspace(ws)?;
627        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
628    }
629    if tail.copilot_vscode {
630        let sessions = scan_copilot_vscode_workspace(ws)?;
631        persist_session_batch(store, sessions, sync_ctx.as_ref())?;
632    }
633
634    maybe_auto_prune_after_scan(store, cfg)?;
635    Ok(())
636}
637
638fn persist_session_batch(
639    store: &Store,
640    sessions: Vec<(SessionRecord, Vec<Event>)>,
641    sync_ctx: Option<&crate::sync::SyncIngestContext>,
642) -> Result<()> {
643    for (mut record, events) in sessions {
644        if record.start_commit.is_none() && !record.workspace.is_empty() {
645            let binding = crate::core::repo::binding_for_session(
646                Path::new(&record.workspace),
647                record.started_at_ms,
648                record.ended_at_ms,
649            );
650            record.start_commit = binding.start_commit;
651            record.end_commit = binding.end_commit;
652            record.branch = binding.branch;
653            record.dirty_start = binding.dirty_start;
654            record.dirty_end = binding.dirty_end;
655            record.repo_binding_source = binding.source;
656        }
657        store.upsert_session(&record)?;
658        for ev in events {
659            store.append_event_with_sync(&ev, sync_ctx)?;
660        }
661    }
662    Ok(())
663}
664
665pub(crate) fn scan_agent_dirs<F>(
666    dir: &Path,
667    store: &Store,
668    scanner: F,
669    sync_ctx: Option<&crate::sync::SyncIngestContext>,
670) -> Result<()>
671where
672    F: Fn(&Path) -> Result<Vec<(SessionRecord, Vec<Event>)>>,
673{
674    if !dir.exists() {
675        return Ok(());
676    }
677    for entry in std::fs::read_dir(dir)?.filter_map(|e| e.ok()) {
678        if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
679            continue;
680        }
681        match scanner(&entry.path()) {
682            Ok(sessions) => {
683                for (mut record, events) in sessions {
684                    if record.start_commit.is_none() && !record.workspace.is_empty() {
685                        let binding = crate::core::repo::binding_for_session(
686                            Path::new(&record.workspace),
687                            record.started_at_ms,
688                            record.ended_at_ms,
689                        );
690                        record.start_commit = binding.start_commit;
691                        record.end_commit = binding.end_commit;
692                        record.branch = binding.branch;
693                        record.dirty_start = binding.dirty_start;
694                        record.dirty_end = binding.dirty_end;
695                        record.repo_binding_source = binding.source;
696                    }
697                    store.upsert_session(&record)?;
698                    for ev in events {
699                        store.append_event_with_sync(&ev, sync_ctx)?;
700                    }
701                }
702            }
703            Err(e) => tracing::warn!("scan {:?}: {e}", entry.path()),
704        }
705    }
706    Ok(())
707}
708
709pub(crate) fn workspace_path(workspace: Option<&Path>) -> Result<PathBuf> {
710    crate::core::workspace::resolve(workspace)
711}
712
713/// Convert workspace path to cursor project slug.
714/// `/Users/lucas/Projects/kaizen` → `Users-lucas-Projects-kaizen`
715pub(crate) fn workspace_slug(ws: &str) -> String {
716    ws.trim_start_matches('/').replace('/', "-")
717}
718
719pub(crate) fn expand_home(path: &str) -> String {
720    if let (Some(rest), Ok(home)) = (path.strip_prefix("~/"), std::env::var("HOME")) {
721        return format!("{home}/{rest}");
722    }
723    path.to_string()
724}