1use 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 cost_note: Option<String>,
46 #[serde(skip_serializing_if = "Option::is_none")]
47 hotspot: Option<crate::metrics::types::RankedFile>,
48 #[serde(skip_serializing_if = "Option::is_none")]
49 slowest_tool: Option<crate::metrics::types::RankedTool>,
50}
51
52pub(crate) fn summary_needs_cost_rollup_note(session_count: u64, total_cost_usd_e6: i64) -> bool {
54 session_count > 0 && total_cost_usd_e6 == 0
55}
56
57pub(crate) fn cost_rollup_zero_note_paragraph() -> &'static str {
58 "Cost rollup shows $0.00 because stored events have no cost_usd_e6 — common when Cursor agent-transcript lines omit usage/tokens. \
59If you expect non-zero spend, ingest Claude/Codex transcripts with usage, hooks with total_cost_usd, or Kaizen proxy Cost events; run `kaizen summary --refresh` after ingest changes. \
60See docs/usage.md#cost-shows-zero."
61}
62
63pub(crate) fn cost_rollup_zero_doctor_hint() -> &'static str {
64 "Cost rollup $0.00 with sessions but no cost_usd_e6 — often Cursor transcripts without usage; see docs/usage.md#cost-shows-zero"
65}
66
67struct ScanSpinner(Option<indicatif::ProgressBar>);
68
69impl ScanSpinner {
70 fn start(msg: &'static str) -> Self {
71 if !std::io::stdout().is_terminal() {
72 return Self(None);
73 }
74 let p = indicatif::ProgressBar::new_spinner();
75 p.set_message(msg.to_string());
76 p.enable_steady_tick(std::time::Duration::from_millis(120));
77 Self(Some(p))
78 }
79}
80
81impl Drop for ScanSpinner {
82 fn drop(&mut self) {
83 if let Some(p) = self.0.take() {
84 p.finish_and_clear();
85 }
86 }
87}
88
89fn now_ms_u64() -> u64 {
90 std::time::SystemTime::now()
91 .duration_since(std::time::UNIX_EPOCH)
92 .unwrap_or_default()
93 .as_millis() as u64
94}
95
96const AUTO_PRUNE_INTERVAL_MS: u64 = 86_400_000;
98
99pub(crate) fn maybe_auto_prune_after_scan(store: &Store, cfg: &config::Config) -> Result<()> {
100 if cfg.retention.hot_days == 0 {
101 return Ok(());
102 }
103 let now = now_ms_u64();
104 if let Some(last) = store.sync_state_get_u64(SYNC_STATE_LAST_AUTO_PRUNE_MS)?
105 && now.saturating_sub(last) < AUTO_PRUNE_INTERVAL_MS
106 {
107 return Ok(());
108 }
109 let cutoff = now.saturating_sub((cfg.retention.hot_days as u64).saturating_mul(86_400_000));
110 store.prune_sessions_started_before(cutoff as i64)?;
111 store.sync_state_set_u64(SYNC_STATE_LAST_AUTO_PRUNE_MS, now)?;
112 Ok(())
113}
114
115pub(crate) fn maybe_scan_all_agents(
117 ws: &Path,
118 cfg: &config::Config,
119 ws_str: &str,
120 store: &Store,
121 refresh: bool,
122) -> Result<()> {
123 let interval_ms = cfg.scan.min_rescan_seconds.saturating_mul(1000);
124 let now = now_ms_u64();
125 if !refresh
126 && interval_ms > 0
127 && let Some(last) = store.sync_state_get_u64(SYNC_STATE_LAST_AGENT_SCAN_MS)?
128 && now.saturating_sub(last) < interval_ms
129 {
130 return Ok(());
131 }
132 scan_all_agents(ws, cfg, ws_str, store)?;
133 store.sync_state_set_u64(SYNC_STATE_LAST_AGENT_SCAN_MS, now_ms_u64())?;
134 Ok(())
135}
136
137pub(crate) fn maybe_refresh_store(workspace: &Path, store: &Store, refresh: bool) -> Result<()> {
138 if !refresh {
139 return Ok(());
140 }
141 let cfg = config::load(workspace)?;
142 let ws_str = workspace.to_string_lossy().to_string();
143 maybe_scan_all_agents(workspace, &cfg, &ws_str, store, true)
144}
145
146fn combine_counts(rows: Vec<Vec<(String, u64)>>) -> Vec<(String, u64)> {
147 let mut counts = HashMap::new();
148 for set in rows {
149 for (key, value) in set {
150 *counts.entry(key).or_insert(0_u64) += value;
151 }
152 }
153 let mut out = counts.into_iter().collect::<Vec<_>>();
154 out.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
155 out
156}
157
158fn workspace_names(roots: &[PathBuf]) -> Vec<String> {
159 roots
160 .iter()
161 .map(|path| path.to_string_lossy().to_string())
162 .collect()
163}
164
165fn open_workspace_store(workspace: &Path) -> Result<Store> {
166 Store::open(&crate::core::workspace::db_path(workspace)?)
167}
168
169pub(crate) fn open_workspace_read_store(workspace: &Path, refresh: bool) -> Result<Store> {
170 let db_path = crate::core::workspace::db_path(workspace)?;
171 if refresh || !db_path.exists() {
172 Store::open(&db_path)
173 } else {
174 Store::open_query(&db_path)
175 }
176}
177
178pub fn sessions_list_text(
180 workspace: Option<&Path>,
181 json_out: bool,
182 refresh: bool,
183 all_workspaces: bool,
184 limit: Option<usize>,
185) -> Result<String> {
186 let roots = scope::resolve(workspace, all_workspaces)?;
187 let mut sessions = Vec::new();
188 if crate::daemon::enabled() && !refresh {
189 for workspace in &roots {
190 let ws_str = workspace.to_string_lossy().to_string();
191 let response =
192 crate::daemon::request_blocking(crate::ipc::DaemonRequest::ListSessions {
193 workspace: ws_str,
194 offset: 0,
195 limit: i64::MAX as usize,
196 filter: crate::store::SessionFilter::default(),
197 })?;
198 match response {
199 crate::ipc::DaemonResponse::Sessions(page) => sessions.extend(page.rows),
200 crate::ipc::DaemonResponse::Error { message, .. } => anyhow::bail!(message),
201 _ => anyhow::bail!("unexpected daemon sessions response"),
202 }
203 }
204 } else {
205 for workspace in &roots {
206 let store = open_workspace_read_store(workspace, refresh)?;
207 maybe_refresh_store(workspace, &store, refresh)?;
208 let ws_str = workspace.to_string_lossy().to_string();
209 sessions.extend(store.list_sessions(&ws_str)?);
210 }
211 }
212 sessions.sort_by(|a, b| {
213 b.started_at_ms
214 .cmp(&a.started_at_ms)
215 .then_with(|| a.id.cmp(&b.id))
216 });
217 let output_limit = limit.unwrap_or(100);
218 if output_limit > 0 {
219 let n = output_limit;
220 sessions.truncate(n);
221 }
222 let scope_label = scope::label(&roots);
223 let workspaces = if roots.len() > 1 {
224 workspace_names(&roots)
225 } else {
226 Vec::new()
227 };
228 if json_out {
229 return Ok(format!(
230 "{}\n",
231 serde_json::to_string_pretty(&SessionsListJson {
232 workspace: scope_label,
233 workspaces,
234 count: sessions.len(),
235 sessions,
236 })?
237 ));
238 }
239 use std::fmt::Write;
240 let mut out = String::new();
241 if roots.len() > 1 {
242 writeln!(&mut out, "Scope: {scope_label}").unwrap();
243 writeln!(&mut out).unwrap();
244 }
245 writeln!(
246 &mut out,
247 "{:<40} {:<10} {:<10} STARTED",
248 "ID", "AGENT", "STATUS"
249 )
250 .unwrap();
251 writeln!(&mut out, "{}", "-".repeat(80)).unwrap();
252 for s in &sessions {
253 writeln!(
254 &mut out,
255 "{:<40} {:<10} {:<10} {}",
256 s.id,
257 s.agent,
258 format!("{:?}", s.status),
259 fmt_ts(s.started_at_ms),
260 )
261 .unwrap();
262 }
263 if sessions.is_empty() {
264 writeln!(&mut out, "(no sessions)").unwrap();
265 sessions_empty_state_hints(&mut out);
266 }
267 Ok(out)
268}
269
270fn sessions_empty_state_hints(out: &mut String) {
271 use std::fmt::Write;
272 let _ = writeln!(out);
273 let _ = writeln!(out, "No sessions found for this workspace. Try:");
274 let _ = writeln!(out, " · `kaizen doctor` — verify config and hooks");
275 let _ = writeln!(out, " · a short agent session in this repo, then re-run");
276 let _ = writeln!(
277 out,
278 " · docs: https://github.com/marquesds/kaizen/blob/main/docs/config.md (sources)"
279 );
280}
281
282pub fn cmd_sessions_list(
284 workspace: Option<&Path>,
285 json_out: bool,
286 refresh: bool,
287 all_workspaces: bool,
288 limit: Option<usize>,
289) -> Result<()> {
290 print!(
291 "{}",
292 sessions_list_text(workspace, json_out, refresh, all_workspaces, limit)?
293 );
294 Ok(())
295}
296
297pub fn session_show_text(id: &str, workspace: Option<&Path>) -> Result<String> {
299 let ws = workspace_path(workspace)?;
300 let store = open_workspace_store(&ws)?;
301 use std::fmt::Write;
302 let mut out = String::new();
303 match store.get_session(id)? {
304 Some(s) => {
305 writeln!(&mut out, "id: {}", s.id).unwrap();
306 writeln!(&mut out, "agent: {}", s.agent).unwrap();
307 writeln!(
308 &mut out,
309 "model: {}",
310 s.model.as_deref().unwrap_or("-")
311 )
312 .unwrap();
313 writeln!(&mut out, "workspace: {}", s.workspace).unwrap();
314 writeln!(&mut out, "started_at: {}", fmt_ts(s.started_at_ms)).unwrap();
315 writeln!(
316 &mut out,
317 "ended_at: {}",
318 s.ended_at_ms.map(fmt_ts).unwrap_or_else(|| "-".to_string())
319 )
320 .unwrap();
321 writeln!(&mut out, "status: {:?}", s.status).unwrap();
322 writeln!(&mut out, "trace_path: {}", s.trace_path).unwrap();
323 if let Some(fp) = &s.prompt_fingerprint {
324 writeln!(&mut out, "prompt_fp: {fp}").unwrap();
325 if let Ok(Some(snap)) = store.get_prompt_snapshot(fp) {
326 for f in snap.files() {
327 writeln!(&mut out, " - {}", f.path).unwrap();
328 }
329 }
330 }
331 }
332 None => anyhow::bail!("session not found: {id} — try `kaizen sessions list`"),
333 }
334 let evals = store.list_evals_for_session(id).unwrap_or_default();
335 if !evals.is_empty() {
336 writeln!(&mut out, "evals:").unwrap();
337 for e in &evals {
338 writeln!(
339 &mut out,
340 " {} score={:.2} flagged={} {}",
341 e.rubric_id, e.score, e.flagged, e.rationale
342 )
343 .unwrap();
344 }
345 }
346 let fb = store
347 .feedback_for_sessions(&[id.to_string()])
348 .unwrap_or_default();
349 if let Some(r) = fb.get(id) {
350 let score = r
351 .score
352 .as_ref()
353 .map(|s| s.0.to_string())
354 .unwrap_or_else(|| "-".into());
355 let label = r
356 .label
357 .as_ref()
358 .map(|l| l.to_string())
359 .unwrap_or_else(|| "-".into());
360 writeln!(&mut out, "feedback: score={score} label={label}").unwrap();
361 if let Some(n) = &r.note {
362 writeln!(&mut out, " note: {n}").unwrap();
363 }
364 }
365 Ok(out)
366}
367
368pub fn cmd_session_show(id: &str, workspace: Option<&Path>) -> Result<()> {
370 print!("{}", session_show_text(id, workspace)?);
371 Ok(())
372}
373
374pub fn sessions_tree_text(id: &str, max_depth: u32, workspace: Option<&Path>) -> Result<String> {
375 let ws = workspace_path(workspace)?;
376 let store = open_workspace_store(&ws)?;
377 let nodes = store.session_span_tree(id)?;
378 if nodes.is_empty() {
379 if store.get_session(id)?.is_none() {
380 anyhow::bail!("session not found: {id}");
381 }
382 return Ok(format!("(no tool spans for session {id})\n"));
383 }
384 let total_cost: i64 = nodes.iter().map(|n| n.subtree_cost_usd_e6).sum();
385 let mut out = String::new();
386 for node in &nodes {
387 render_node(&mut out, node, 0, max_depth, total_cost);
388 }
389 Ok(out)
390}
391
392fn render_node(
393 out: &mut String,
394 node: &crate::store::span_tree::SpanNode,
395 depth: u32,
396 max_depth: u32,
397 session_total: i64,
398) {
399 use std::fmt::Write;
400 if depth > max_depth {
401 return;
402 }
403 let indent = "│ ".repeat(depth as usize);
404 let prefix = if depth == 0 { "┌─ " } else { "├─ " };
405 let cost_str = match node.span.subtree_cost_usd_e6 {
406 Some(c) => {
407 let pct = if session_total > 0 {
408 c * 100 / session_total
409 } else {
410 0
411 };
412 let flag = if pct > 40 { " ⚡" } else { "" };
413 format!(" ${:.4}{}", c as f64 / 1_000_000.0, flag)
414 }
415 None => String::new(),
416 };
417 writeln!(
418 out,
419 "{}{}{} [{}]{}",
420 indent, prefix, node.span.tool, node.span.status, cost_str
421 )
422 .unwrap();
423 for child in &node.children {
424 render_node(out, child, depth + 1, max_depth, session_total);
425 }
426}
427
428pub fn cmd_sessions_tree_text(
430 id: &str,
431 depth: u32,
432 json: bool,
433 workspace: Option<&Path>,
434) -> Result<String> {
435 if json {
436 let ws = workspace_path(workspace)?;
437 let store = open_workspace_read_store(&ws, false)?;
438 let nodes = store.session_span_tree(id)?;
439 Ok(serde_json::to_string_pretty(&nodes)?)
440 } else {
441 sessions_tree_text(id, depth, workspace)
442 }
443}
444
445pub fn cmd_sessions_tree(id: &str, depth: u32, json: bool, workspace: Option<&Path>) -> Result<()> {
447 print!("{}", cmd_sessions_tree_text(id, depth, json, workspace)?);
448 Ok(())
449}
450
451pub fn summary_text(
453 workspace: Option<&Path>,
454 json_out: bool,
455 refresh: bool,
456 all_workspaces: bool,
457 source: crate::core::data_source::DataSource,
458) -> Result<String> {
459 let roots = scope::resolve(workspace, all_workspaces)?;
460 let mut total_cost_usd_e6 = 0_i64;
461 let mut session_count = 0_u64;
462 let mut by_agent = Vec::new();
463 let mut by_model = Vec::new();
464 let mut top_tools = Vec::new();
465 let mut hottest = Vec::new();
466 let mut slowest = Vec::new();
467
468 for workspace in &roots {
469 let cfg = config::load(workspace)?;
470 let store = open_workspace_read_store(
471 workspace,
472 refresh || source != crate::core::data_source::DataSource::Local,
473 )?;
474 crate::shell::remote_pull::maybe_telemetry_pull(workspace, &store, &cfg, source, refresh)?;
475 maybe_refresh_store(workspace, &store, refresh)?;
476 let ws_str = workspace.to_string_lossy().to_string();
477 let read_store = open_workspace_read_store(workspace, false)?;
478 let query = crate::store::query::QueryStore::open(&crate::core::paths::project_data_dir(
479 workspace,
480 )?)?;
481 let mut stats = query.summary_stats(&read_store, &ws_str)?;
482 if source != crate::core::data_source::DataSource::Local
483 && let Ok(Some(agg)) =
484 crate::shell::remote_observe::try_remote_event_agg(&read_store, &cfg, workspace)
485 {
486 stats = crate::shell::remote_observe::merge_summary_stats(stats, &agg, source);
487 }
488 total_cost_usd_e6 += stats.total_cost_usd_e6;
489 session_count += stats.session_count;
490 by_agent.push(stats.by_agent);
491 by_model.push(stats.by_model);
492 top_tools.push(stats.top_tools);
493 if let Ok(metrics) = report::build_report(&read_store, &ws_str, 7) {
494 if let Some(file) = metrics.hottest_files.first().cloned() {
495 hottest.push(if roots.len() == 1 {
496 file
497 } else {
498 crate::metrics::types::RankedFile {
499 path: scope::decorate_path(workspace, &file.path),
500 ..file
501 }
502 });
503 }
504 if let Some(tool) = metrics.slowest_tools.first().cloned() {
505 slowest.push(tool);
506 }
507 }
508 }
509
510 let stats = crate::store::SummaryStats {
511 session_count,
512 total_cost_usd_e6,
513 by_agent: combine_counts(by_agent),
514 by_model: combine_counts(by_model),
515 top_tools: combine_counts(top_tools),
516 };
517 let cost_dollars = stats.total_cost_usd_e6 as f64 / 1_000_000.0;
518 let hotspot = hottest
519 .into_iter()
520 .max_by(|a, b| a.value.cmp(&b.value).then_with(|| b.path.cmp(&a.path)));
521 let slowest_tool = slowest.into_iter().max_by(|a, b| {
522 a.p95_ms
523 .unwrap_or(0)
524 .cmp(&b.p95_ms.unwrap_or(0))
525 .then_with(|| b.tool.cmp(&a.tool))
526 });
527 let scope_label = scope::label(&roots);
528 let workspaces = if roots.len() > 1 {
529 workspace_names(&roots)
530 } else {
531 Vec::new()
532 };
533 let cost_note = summary_needs_cost_rollup_note(stats.session_count, stats.total_cost_usd_e6)
534 .then_some(cost_rollup_zero_note_paragraph().to_string());
535 if json_out {
536 return Ok(format!(
537 "{}\n",
538 serde_json::to_string_pretty(&SummaryJsonOut {
539 workspace: scope_label,
540 workspaces,
541 cost_usd: cost_dollars,
542 stats,
543 cost_note,
544 hotspot,
545 slowest_tool,
546 })?
547 ));
548 }
549 use std::fmt::Write;
550 let mut out = String::new();
551 if roots.len() > 1 {
552 writeln!(&mut out, "Scope: {}", scope::label(&roots)).unwrap();
553 }
554 writeln!(
555 &mut out,
556 "Sessions: {} Cost: ${:.2}",
557 stats.session_count, cost_dollars
558 )
559 .unwrap();
560
561 if !stats.by_agent.is_empty() {
562 let parts: Vec<String> = stats
563 .by_agent
564 .iter()
565 .map(|(a, n)| format!("{a} {n}"))
566 .collect();
567 writeln!(&mut out, "By agent: {}", parts.join(" · ")).unwrap();
568 }
569 if !stats.by_model.is_empty() {
570 let parts: Vec<String> = stats
571 .by_model
572 .iter()
573 .map(|(m, n)| format!("{m} {n}"))
574 .collect();
575 writeln!(&mut out, "By model: {}", parts.join(" · ")).unwrap();
576 }
577 if !stats.top_tools.is_empty() {
578 let parts: Vec<String> = stats
579 .top_tools
580 .iter()
581 .take(5)
582 .map(|(t, n)| format!("{t} {n}"))
583 .collect();
584 writeln!(&mut out, "Top tools: {}", parts.join(" · ")).unwrap();
585 }
586 if let Some(file) = hotspot {
587 writeln!(&mut out, "Hotspot: {} ({})", file.path, file.value).unwrap();
588 }
589 if let Some(tool) = slowest_tool {
590 let p95 = tool
591 .p95_ms
592 .map(|v| format!("{v}ms"))
593 .unwrap_or_else(|| "-".into());
594 writeln!(&mut out, "Slowest: {} p95 {}", tool.tool, p95).unwrap();
595 }
596 if cost_note.is_some() {
597 writeln!(&mut out).unwrap();
598 writeln!(&mut out, "Note: {}", cost_rollup_zero_note_paragraph()).unwrap();
599 }
600 Ok(out)
601}
602
603pub fn cmd_summary(
605 workspace: Option<&Path>,
606 json_out: bool,
607 refresh: bool,
608 all_workspaces: bool,
609 source: crate::core::data_source::DataSource,
610) -> Result<()> {
611 print!(
612 "{}",
613 summary_text(workspace, json_out, refresh, all_workspaces, source,)?
614 );
615 Ok(())
616}
617
618pub(crate) fn scan_all_agents(
619 ws: &Path,
620 cfg: &config::Config,
621 ws_str: &str,
622 store: &Store,
623) -> Result<()> {
624 let _spin = ScanSpinner::start("Scanning agent sessions…");
625 let slug = workspace_slug(ws_str);
626 let sync_ctx = crate::sync::ingest_ctx(cfg, ws.to_path_buf());
627
628 for root in &cfg.scan.roots {
629 let expanded = expand_home(root);
630 let cursor_dir = PathBuf::from(&expanded)
631 .join(&slug)
632 .join("agent-transcripts");
633 scan_agent_dirs(
634 &cursor_dir,
635 store,
636 |p| {
637 scan_session_dir_all(p).map(|sessions| {
638 sessions
639 .into_iter()
640 .map(|(mut r, evs)| {
641 r.workspace = ws_str.to_string();
642 (r, evs)
643 })
644 .collect()
645 })
646 },
647 sync_ctx.as_ref(),
648 )?;
649 }
650
651 let home = std::env::var("HOME").unwrap_or_default();
652
653 let claude_dir = PathBuf::from(&home)
654 .join(".claude/projects")
655 .join(&slug)
656 .join("sessions");
657 scan_agent_dirs(
658 &claude_dir,
659 store,
660 |p| {
661 scan_claude_session_dir(p).map(|(mut r, evs)| {
662 r.workspace = ws_str.to_string();
663 vec![(r, evs)]
664 })
665 },
666 sync_ctx.as_ref(),
667 )?;
668
669 let codex_dir = PathBuf::from(&home).join(".codex/sessions").join(&slug);
670 scan_agent_dirs(
671 &codex_dir,
672 store,
673 |p| {
674 scan_codex_session_dir(p).map(|(mut r, evs)| {
675 r.workspace = ws_str.to_string();
676 vec![(r, evs)]
677 })
678 },
679 sync_ctx.as_ref(),
680 )?;
681
682 let tail = &cfg.sources.tail;
683 let home_pb = PathBuf::from(&home);
684 if tail.goose {
685 let sessions = scan_goose_workspace(&home_pb, ws)?;
686 persist_session_batch(store, sessions, sync_ctx.as_ref())?;
687 }
688 if tail.openclaw {
689 let sessions = scan_openclaw_workspace(ws)?;
690 persist_session_batch(store, sessions, sync_ctx.as_ref())?;
691 }
692 if tail.opencode {
693 let sessions = scan_opencode_workspace(ws)?;
694 persist_session_batch(store, sessions, sync_ctx.as_ref())?;
695 }
696 if tail.copilot_cli {
697 let sessions = scan_copilot_cli_workspace(ws)?;
698 persist_session_batch(store, sessions, sync_ctx.as_ref())?;
699 }
700 if tail.copilot_vscode {
701 let sessions = scan_copilot_vscode_workspace(ws)?;
702 persist_session_batch(store, sessions, sync_ctx.as_ref())?;
703 }
704
705 maybe_auto_prune_after_scan(store, cfg)?;
706 Ok(())
707}
708
709fn persist_session_batch(
710 store: &Store,
711 sessions: Vec<(SessionRecord, Vec<Event>)>,
712 sync_ctx: Option<&crate::sync::SyncIngestContext>,
713) -> Result<()> {
714 for (mut record, events) in sessions {
715 if record.start_commit.is_none() && !record.workspace.is_empty() {
716 let binding = crate::core::repo::binding_for_session(
717 Path::new(&record.workspace),
718 record.started_at_ms,
719 record.ended_at_ms,
720 );
721 record.start_commit = binding.start_commit;
722 record.end_commit = binding.end_commit;
723 record.branch = binding.branch;
724 record.dirty_start = binding.dirty_start;
725 record.dirty_end = binding.dirty_end;
726 record.repo_binding_source = binding.source;
727 }
728 store.upsert_session(&record)?;
729 let flush_ms = record.ended_at_ms.unwrap_or(record.started_at_ms);
730 for ev in events {
731 store.append_event_with_sync(&ev, sync_ctx)?;
732 }
733 if record.status == crate::core::event::SessionStatus::Done {
734 store.flush_projector_session(&record.id, flush_ms)?;
735 }
736 }
737 Ok(())
738}
739
740pub(crate) fn scan_agent_dirs<F>(
741 dir: &Path,
742 store: &Store,
743 scanner: F,
744 sync_ctx: Option<&crate::sync::SyncIngestContext>,
745) -> Result<()>
746where
747 F: Fn(&Path) -> Result<Vec<(SessionRecord, Vec<Event>)>>,
748{
749 if !dir.exists() {
750 return Ok(());
751 }
752 for entry in std::fs::read_dir(dir)?.filter_map(|e| e.ok()) {
753 if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
754 continue;
755 }
756 match scanner(&entry.path()) {
757 Ok(sessions) => {
758 for (mut record, events) in sessions {
759 if record.start_commit.is_none() && !record.workspace.is_empty() {
760 let binding = crate::core::repo::binding_for_session(
761 Path::new(&record.workspace),
762 record.started_at_ms,
763 record.ended_at_ms,
764 );
765 record.start_commit = binding.start_commit;
766 record.end_commit = binding.end_commit;
767 record.branch = binding.branch;
768 record.dirty_start = binding.dirty_start;
769 record.dirty_end = binding.dirty_end;
770 record.repo_binding_source = binding.source;
771 }
772 store.upsert_session(&record)?;
773 let flush_ms = record.ended_at_ms.unwrap_or(record.started_at_ms);
774 for ev in events {
775 store.append_event_with_sync(&ev, sync_ctx)?;
776 }
777 if record.status == crate::core::event::SessionStatus::Done {
778 store.flush_projector_session(&record.id, flush_ms)?;
779 }
780 }
781 }
782 Err(e) => tracing::warn!("scan {:?}: {e}", entry.path()),
783 }
784 }
785 Ok(())
786}
787
788pub(crate) fn workspace_path(workspace: Option<&Path>) -> Result<PathBuf> {
789 crate::core::workspace::resolve(workspace)
790}
791
792pub(crate) fn workspace_slug(ws: &str) -> String {
794 crate::core::paths::workspace_slug(std::path::Path::new(ws))
795}
796
797pub(crate) fn expand_home(path: &str) -> String {
798 if let (Some(rest), Ok(home)) = (path.strip_prefix("~/"), std::env::var("HOME")) {
799 return format!("{home}/{rest}");
800 }
801 path.to_string()
802}
803
804#[cfg(test)]
805mod cost_rollup_note_tests {
806 use super::*;
807
808 #[test]
809 fn needs_note_only_when_sessions_and_zero_cost() {
810 assert!(summary_needs_cost_rollup_note(1, 0));
811 assert!(!summary_needs_cost_rollup_note(0, 0));
812 assert!(!summary_needs_cost_rollup_note(1, 1));
813 }
814
815 #[test]
816 fn paragraph_names_gap_and_doc_anchor() {
817 let s = cost_rollup_zero_note_paragraph();
818 assert!(s.contains("cost_usd_e6"));
819 assert!(s.contains("usage"));
820 assert!(s.contains("docs/usage.md#cost-shows-zero"));
821 }
822}