weavr 1.0.0

Claude Code transcript exporter — beautiful, self-contained HTML and Markdown
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
//! CLI argument parsing and command dispatch.

use std::fs;
use std::path::{Path, PathBuf};

use askama::Template;
use clap::{Parser, Subcommand, ValueEnum};

use crate::cache::{Cache, CachedSessionMeta};
use crate::render::markdown_export::DetailLevel;
use crate::render::{IndexProjectData, ProjectSessionData};

/// weavr — Claude Code transcript exporter.
#[derive(Parser)]
#[command(name = "weavr", version)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Command>,

    /// Input JSONL file path (shorthand for `export <INPUT>`).
    #[arg(short, long)]
    pub input: Option<PathBuf>,

    /// Projects directory (default: ~/.claude/projects/).
    #[arg(long)]
    pub projects_dir: Option<PathBuf>,

    /// Export all projects (default when no INPUT_PATH is given).
    #[arg(long)]
    pub all_projects: bool,

    /// Skip per-session HTML files; only produce combined + index pages.
    #[arg(long)]
    pub no_individual_sessions: bool,

    /// Disable SQLite cache reads and writes.
    #[arg(long)]
    pub no_cache: bool,

    /// Clear the SQLite cache and rebuild from scratch.
    #[arg(long)]
    pub clear_cache: bool,

    /// Filter to a single session by ID or unique prefix.
    #[arg(long)]
    pub session_id: Option<String>,

    /// Wipe the output directory before writing.
    #[arg(long)]
    pub clear_output: bool,

    /// Output directory (default: ./weavr-out/).
    #[arg(long)]
    pub output_dir: Option<PathBuf>,

    /// Filter sessions starting on or after this date.
    /// Accepts: today, yesterday, last week, last month, YYYY-MM-DD.
    #[arg(long, global = true)]
    pub from_date: Option<String>,

    /// Filter sessions ending on or before this date.
    /// Accepts: today, yesterday, last week, last month, YYYY-MM-DD.
    #[arg(long, global = true)]
    pub to_date: Option<String>,

    /// Split long sessions across multiple HTML pages (messages per page).
    #[arg(long, global = true)]
    pub page_size: Option<usize>,

    /// Enable verbose debug logging via tracing.
    #[arg(long, global = true)]
    pub debug: bool,

    /// Interactive TUI mode (coming in a later release).
    #[arg(long, global = true)]
    pub tui: bool,
}

#[derive(Subcommand)]
pub enum Command {
    /// Emit a stub transcript HTML file for design verification.
    Stub {
        /// Output file path (default: weavr-stub.html in current dir).
        #[arg(short, long, default_value = "weavr-stub.html")]
        output: String,
    },

    /// Export a JSONL session file to HTML or Markdown.
    Export {
        /// Input JSONL file path.
        input: PathBuf,

        /// Output file path (default: <input_stem>.html or .md).
        #[arg(short, long)]
        output: Option<String>,

        /// Output format.
        #[arg(long, value_enum, default_value_t = Format::Html)]
        format: Format,

        /// Detail level for markdown output.
        #[arg(long, value_enum, default_value_t = DetailLevel::Full)]
        detail: DetailLevel,

        /// Compact mode: strip timestamps and horizontal rules (markdown only).
        #[arg(long, default_value_t = false)]
        compact: bool,

        /// Open the output file in the default browser.
        #[arg(long)]
        open_browser: bool,
    },

    /// Update weavr to the latest version from GitHub Releases.
    SelfUpdate,
}

/// Output format for the export command.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[clap(rename_all = "lowercase")]
pub enum Format {
    /// Self-contained HTML (default).
    Html,
    /// Markdown.
    #[clap(name = "md")]
    #[clap(alias = "markdown")]
    Markdown,
}

impl Cli {
    pub fn run(self) -> anyhow::Result<()> {
        // --tui exits early with code 2.
        if self.tui {
            eprintln!("Error: --tui is coming in a later release.");
            std::process::exit(2);
        }

        // --debug enables tracing.
        if self.debug {
            tracing_subscriber::fmt()
                .with_env_filter(
                    tracing_subscriber::EnvFilter::try_from_default_env()
                        .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("debug")),
                )
                .init();
        }

        // Passive update notice (non-blocking, throttled).
        crate::update::maybe_print_update_notice();

        match self.command {
            Some(Command::SelfUpdate) => crate::update::self_update().map(|msg| {
                println!("{msg}");
            }),
            Some(Command::Stub { output }) => run_stub(&output),
            Some(Command::Export {
                input,
                output,
                format,
                detail,
                compact,
                open_browser,
            }) => run_export(ExportConfig {
                input: &input,
                output: output.as_deref(),
                format,
                detail,
                compact,
                open_browser,
                from_date: self.from_date.as_deref(),
                to_date: self.to_date.as_deref(),
                page_size: self.page_size,
            }),
            None => {
                // If --input is provided, treat as single export.
                if let Some(ref input) = self.input {
                    run_export(ExportConfig {
                        input,
                        output: None,
                        format: Format::Html,
                        detail: DetailLevel::Full,
                        compact: false,
                        open_browser: false,
                        from_date: self.from_date.as_deref(),
                        to_date: self.to_date.as_deref(),
                        page_size: self.page_size,
                    })
                } else {
                    // Default: all-projects export.
                    run_all_projects(self)
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Single-session export
// ---------------------------------------------------------------------------

fn run_stub(output: &str) -> anyhow::Result<()> {
    let ctx = crate::render::html::stub_context();
    let html = ctx.render()?;
    std::fs::write(output, &html)?;
    println!("Wrote stub HTML to {output}");
    println!("  Size: {} bytes", html.len());
    let self_contained = !html.contains("http://") && !html.contains("https://");
    println!("  Self-contained: {}", if self_contained { "yes" } else { "NO" });
    Ok(())
}

struct ExportConfig<'a> {
    input: &'a Path,
    output: Option<&'a str>,
    format: Format,
    detail: DetailLevel,
    compact: bool,
    open_browser: bool,
    from_date: Option<&'a str>,
    to_date: Option<&'a str>,
    page_size: Option<usize>,
}

fn run_export(cfg: ExportConfig<'_>) -> anyhow::Result<()> {
    let result = crate::parser::parse_file(cfg.input)?;
    if !result.warnings.is_empty() {
        for w in &result.warnings {
            eprintln!("Warning: line {}: {}", w.line, w.message);
        }
    }

    let session = crate::session::build_session(&result.entries);
    if session.messages.is_empty() {
        anyhow::bail!("No messages found in input file");
    }

    let agg = crate::aggregate::aggregate(&session);

    // Date filter: skip if session doesn't match the date range.
    if !session_matches_date_range(&agg, cfg.from_date, cfg.to_date)? {
        anyhow::bail!(
            "Session does not match the requested date range (from={:?}, to={:?})",
            cfg.from_date,
            cfg.to_date
        );
    }

    match cfg.format {
        Format::Html => {
            let css = crate::assets::CSS.to_string();
            let base_stem = match cfg.output {
                Some(o) => {
                    if let Some(stem) = o.strip_suffix(".html") {
                        stem.to_string()
                    } else {
                        o.to_string()
                    }
                }
                None => {
                    cfg.input.file_stem().and_then(|s| s.to_str()).unwrap_or("session").to_string()
                }
            };

            if let Some(ps) = cfg.page_size {
                if let Some(pages) = crate::render::pagination::paginate(&session, ps) {
                    let total = pages.len();
                    for page in &pages {
                        let filename = crate::render::pagination::page_filename(&base_stem, page);
                        let ctx = crate::render::html::build_context_paginated(
                            &session,
                            &agg,
                            css.clone(),
                            page,
                            None,
                        );
                        let html = ctx.render()?;
                        std::fs::write(&filename, &html)?;
                        println!(
                            "Exported page {}/{} to {filename} ({} messages)",
                            page.number,
                            total,
                            page.message_range.len()
                        );
                    }
                    println!("  Format: HTML (paginated, {total} pages)");
                    println!("  Messages: {}", agg.message_count);
                    println!(
                        "  Tokens: {} in / {} out",
                        agg.total_input_tokens, agg.total_output_tokens
                    );
                    return Ok(());
                }
            }

            // Non-paginated path.
            let ctx = crate::render::html::build_context(&session, &agg, css, None);
            let html = ctx.render()?;

            let output_path = match cfg.output {
                Some(o) => o.to_string(),
                None => format!("{}.html", base_stem),
            };

            std::fs::write(&output_path, &html)?;
            println!("Exported to {output_path}");
            println!("  Format: HTML");
            println!("  Messages: {}", agg.message_count);
            println!("  Tokens: {} in / {} out", agg.total_input_tokens, agg.total_output_tokens);
            let self_contained = !html.contains("http://") && !html.contains("https://");
            println!("  Self-contained: {}", if self_contained { "yes" } else { "NO" });

            if cfg.open_browser {
                let _ = std::process::Command::new("open").arg(&output_path).spawn();
            }
        }

        Format::Markdown => {
            let md = crate::render::markdown_export::render_session(
                &session,
                &agg,
                cfg.detail,
                cfg.compact,
            );

            let output_path = match cfg.output {
                Some(o) => o.to_string(),
                None => {
                    let stem = cfg.input.file_stem().and_then(|s| s.to_str()).unwrap_or("session");
                    format!("{}.md", stem)
                }
            };

            std::fs::write(&output_path, &md)?;
            println!("Exported to {output_path}");
            println!("  Format: Markdown");
            println!("  Detail: {:?}", cfg.detail);
            println!("  Compact: {}", if cfg.compact { "yes" } else { "no" });
            println!("  Messages: {}", agg.message_count);
            println!("  Tokens: {} in / {} out", agg.total_input_tokens, agg.total_output_tokens);
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// All-projects pipeline
// ---------------------------------------------------------------------------

fn run_all_projects(cli: Cli) -> anyhow::Result<()> {
    let projects_dir = cli.projects_dir.unwrap_or_else(crate::project::default_projects_dir);

    if !projects_dir.is_dir() {
        anyhow::bail!(
            "Projects directory not found: {}. Use --projects-dir to specify a path.",
            projects_dir.display()
        );
    }

    let output_dir = cli.output_dir.unwrap_or_else(|| PathBuf::from("weavr-out"));

    if cli.clear_output && output_dir.exists() {
        fs::remove_dir_all(&output_dir)?;
    }
    fs::create_dir_all(&output_dir)?;

    // Cache.
    let cache_path = projects_dir.join("weavr-cache.db");
    if cli.clear_cache && cache_path.exists() {
        let _ = fs::remove_file(&cache_path);
    }

    let use_cache = !cli.no_cache;
    let cache: Option<Cache> = if use_cache { Cache::open(&cache_path).ok() } else { None };

    // Parse date filters once.
    let from_dt =
        if let Some(ref s) = cli.from_date { Some(crate::dates::parse_date(s)?) } else { None };
    let to_dt =
        if let Some(ref s) = cli.to_date { Some(crate::dates::parse_date(s)?) } else { None };

    // Discover projects.
    let mut projects = crate::project::discover_projects(&projects_dir);

    // Filter by --session-id if provided.
    if let Some(ref sid) = cli.session_id {
        projects = filter_by_session_id(projects, sid)?;
    }

    if projects.is_empty() {
        println!("No sessions found in {}", projects_dir.display());
        return Ok(());
    }

    let css = crate::assets::CSS.to_string();
    let mut all_project_data: Vec<IndexProjectData> = Vec::new();
    let mut global_messages: u32 = 0;
    let mut global_tokens: u64 = 0;
    let mut global_earliest: Option<String> = None;
    let mut global_latest: Option<String> = None;
    let mut total_exported: usize = 0;

    for project in &projects {
        let project_out = output_dir.join(&project.name);
        fs::create_dir_all(&project_out)?;

        let short_name = project_name_short(&project.name, &project.path);
        let display_name = project.display_name().to_string();

        let mut session_datas: Vec<ProjectSessionData> = Vec::new();
        let mut project_messages: u32 = 0;
        let mut project_tokens: u64 = 0;
        let mut project_last_activity: Option<String> = None;

        for sf in &project.sessions {
            // Check cache first.
            let file_meta = fs::metadata(&sf.path).ok();
            let file_mtime = file_meta
                .as_ref()
                .and_then(|m| m.modified().ok())
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .map(|d| d.as_secs())
                .unwrap_or(0);
            let file_size = file_meta.map(|m| m.len()).unwrap_or(0);

            let cached: Option<CachedSessionMeta> =
                cache.as_ref().and_then(|c| c.get(&sf.id, file_mtime));

            let (
                title,
                msg_count,
                input_tok,
                output_tok,
                cache_create,
                cache_read,
                first_ts,
                last_ts,
                first_user_prompt,
            ) = if let Some(ref cm) = cached {
                // Use cached metadata.
                (
                    cm.title.clone(),
                    cm.message_count,
                    cm.total_input_tokens,
                    cm.total_output_tokens,
                    cm.total_cache_creation_tokens,
                    cm.total_cache_read_tokens,
                    cm.first_timestamp.clone(),
                    cm.last_timestamp.clone(),
                    cm.first_user_prompt.clone(),
                )
            } else {
                // Parse and aggregate.
                let parse_result = match crate::parser::parse_file(&sf.path) {
                    Ok(r) => r,
                    Err(e) => {
                        eprintln!("Warning: skipping {}: {}", sf.id, e);
                        continue;
                    }
                };
                let session = crate::session::build_session(&parse_result.entries);
                let agg = crate::aggregate::aggregate(&session);

                let title = agg.summaries.first().cloned();
                let msg_count = agg.message_count as u32;
                let it = agg.total_input_tokens;
                let ot = agg.total_output_tokens;
                let cc = agg.total_cache_creation_tokens;
                let cr = agg.total_cache_read_tokens;
                let first = agg.first_timestamp.map(|t| t.to_rfc3339());
                let last = agg.last_timestamp.map(|t| t.to_rfc3339());
                let fup = crate::render::html::find_first_user_prompt(&session);

                // Store in cache.
                if let Some(ref c) = cache {
                    c.put(
                        &CachedSessionMeta {
                            session_id: sf.id.clone(),
                            project_name: project.name.clone(),
                            title: title.clone(),
                            first_timestamp: first.clone(),
                            last_timestamp: last.clone(),
                            message_count: msg_count,
                            total_input_tokens: it,
                            total_output_tokens: ot,
                            total_cache_creation_tokens: cc,
                            total_cache_read_tokens: cr,
                            first_user_prompt: fup.clone(),
                        },
                        file_mtime,
                        file_size,
                    );
                }

                (title, msg_count, it, ot, cc, cr, first, last, fup)
            };

            // Date filter.
            if !cached_timestamps_match_date_range(
                first_ts.as_deref(),
                last_ts.as_deref(),
                from_dt,
                to_dt,
            ) {
                continue;
            }

            let total_session_tokens = input_tok + output_tok + cache_create + cache_read;

            // Export per-session HTML if not skipped.
            if !cli.no_individual_sessions {
                // Only re-parse if we used cache metadata.
                let session_html_path = project_out.join(format!("{}.html", sf.id));
                if !session_html_path.exists() {
                    let parse_result = crate::parser::parse_file(&sf.path)?;
                    let session = crate::session::build_session(&parse_result.entries);
                    let agg = crate::aggregate::aggregate(&session);

                    if let Some(ps) = cli.page_size {
                        if let Some(pages) = crate::render::pagination::paginate(&session, ps) {
                            for page in &pages {
                                let filename =
                                    crate::render::pagination::page_filename(&sf.id, page);
                                let page_path = project_out.join(&filename);
                                let ctx = crate::render::html::build_context_paginated(
                                    &session,
                                    &agg,
                                    css.clone(),
                                    page,
                                    Some(&project.name),
                                );
                                let html = ctx.render()?;
                                fs::write(&page_path, &html)?;
                            }
                            total_exported += 1;
                        }
                    } else {
                        let ctx = crate::render::html::build_context(
                            &session,
                            &agg,
                            css.clone(),
                            Some(&project.name),
                        );
                        let html = ctx.render()?;
                        fs::write(&session_html_path, &html)?;
                        total_exported += 1;
                    }
                }
            }

            session_datas.push(ProjectSessionData {
                id: sf.id.clone(),
                title,
                message_count: msg_count,
                total_tokens: total_session_tokens,
                first_user_prompt,
                started_at: first_ts.clone(),
            });

            project_messages += msg_count;
            project_tokens += total_session_tokens;

            // Track per-project last activity.
            if let Some(ref ts) = last_ts {
                match project_last_activity.as_deref() {
                    None => project_last_activity = Some(ts.clone()),
                    Some(cur) if ts.as_str() > cur => project_last_activity = Some(ts.clone()),
                    _ => {}
                }
            }

            // Track global time range.
            if let Some(ref ts) = first_ts {
                if global_earliest.is_none()
                    || ts.as_str() < global_earliest.as_deref().unwrap_or("")
                {
                    global_earliest = Some(ts.clone());
                }
            }
            if let Some(ref ts) = last_ts {
                if global_latest.is_none() || ts.as_str() > global_latest.as_deref().unwrap_or("") {
                    global_latest = Some(ts.clone());
                }
            }
        }

        if session_datas.is_empty() {
            continue;
        }

        // Per-project combined page.
        let project_ctx = crate::render::project::build_context(
            css.clone(),
            project.name.clone(),
            display_name.clone(),
            session_datas,
        );
        let project_html = project_ctx.render()?;
        let combined_path = project_out.join("combined_transcripts.html");
        fs::write(&combined_path, &project_html)?;
        println!(
            "  {}/combined_transcripts.html ({} sessions)",
            project.name,
            projects.iter().find(|p| p.name == project.name).map(|p| p.sessions.len()).unwrap_or(0)
        );

        all_project_data.push(IndexProjectData {
            name: project.name.clone(),
            session_count: project.sessions.len().try_into().unwrap_or(u32::MAX),
            message_count: project_messages,
            total_tokens: project_tokens,
            short_name,
            display_name,
            last_activity: project_last_activity,
        });

        global_messages += project_messages;
        global_tokens += project_tokens;
    }

    // Master index.
    let index_ctx = crate::render::index::build_context(
        css,
        all_project_data,
        global_messages,
        global_tokens,
        global_earliest,
        global_latest,
    );
    let index_html = index_ctx.render()?;
    fs::write(output_dir.join("index.html"), &index_html)?;
    println!("  index.html");

    let mode = if cli.no_individual_sessions { "combined + index" } else { "full" };
    println!(
        "Done: {} sessions exported ({} mode) to {}",
        total_exported,
        mode,
        output_dir.display()
    );

    Ok(())
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Filter projects to only include the session matching `prefix`.
fn filter_by_session_id(
    projects: Vec<crate::project::Project>,
    prefix: &str,
) -> anyhow::Result<Vec<crate::project::Project>> {
    let mut matching: Vec<(&crate::project::Project, &crate::project::SessionFile)> = Vec::new();

    for p in &projects {
        for s in &p.sessions {
            if s.id.starts_with(prefix) {
                matching.push((p, s));
            }
        }
    }

    if matching.is_empty() {
        eprintln!("No session matches prefix \"{}\"", prefix);
        return Ok(Vec::new());
    }

    if matching.len() > 1 {
        eprintln!("Ambiguous prefix \"{}\" matches {} sessions:", prefix, matching.len());
        for (proj, sess) in &matching {
            eprintln!("  {}/{}", proj.name, sess.id);
        }
        anyhow::bail!("Ambiguous session-id prefix. Use a longer prefix to disambiguate.");
    }

    let (project, session) = matching.into_iter().next().unwrap();
    Ok(vec![crate::project::Project {
        name: project.name.clone(),
        path: project.path.clone(),
        sessions: vec![session.clone()],
    }])
}

/// Check whether a session (with known aggregate timestamps) matches the
/// requested date range.
fn session_matches_date_range(
    agg: &crate::aggregate::SessionAggregate,
    from_date: Option<&str>,
    to_date: Option<&str>,
) -> anyhow::Result<bool> {
    let from_dt = if let Some(s) = from_date { Some(crate::dates::parse_date(s)?) } else { None };
    let to_dt = if let Some(s) = to_date { Some(crate::dates::parse_date(s)?) } else { None };

    let first = agg.first_timestamp;
    let last = agg.last_timestamp;

    Ok(match (from_dt, to_dt, first, last) {
        // No filter → always match.
        (None, None, _, _) => true,
        // Only from-date: session must end on or after it.
        (Some(f), None, _, Some(l)) => l >= f,
        // Only to-date: session must start on or before it (end of that day).
        (None, Some(t), Some(f), _) => {
            let to_end = t.end_day();
            f <= to_end
        }
        // Both: session's range must overlap with [from, to_end].
        (Some(f), Some(t), Some(first_ts), Some(last_ts)) => {
            let to_end = t.end_day();
            last_ts >= f && first_ts <= to_end
        }
        // If we don't have timestamps, include the session (can't filter).
        _ => true,
    })
}

/// Check whether a cached session (with string timestamps) matches the
/// requested date range.
fn cached_timestamps_match_date_range(
    first_ts: Option<&str>,
    last_ts: Option<&str>,
    from_dt: Option<chrono::DateTime<chrono::Utc>>,
    to_dt: Option<chrono::DateTime<chrono::Utc>>,
) -> bool {
    match (from_dt, to_dt, first_ts, last_ts) {
        (None, None, _, _) => true,
        (Some(f), None, _, Some(l)) => {
            if let Ok(last_dt) = chrono::DateTime::parse_from_rfc3339(l) {
                last_dt >= f
            } else {
                true
            }
        }
        (None, Some(t), Some(f), _) => {
            if let Ok(first_dt) = chrono::DateTime::parse_from_rfc3339(f) {
                let to_end = t.end_day();
                first_dt <= to_end
            } else {
                true
            }
        }
        (Some(f), Some(t), Some(first_s), Some(last_s)) => {
            if let (Ok(first_dt), Ok(last_dt)) = (
                chrono::DateTime::parse_from_rfc3339(first_s),
                chrono::DateTime::parse_from_rfc3339(last_s),
            ) {
                let to_end = t.end_day();
                last_dt >= f && first_dt <= to_end
            } else {
                true
            }
        }
        _ => true,
    }
}

/// Extract a human-readable short name from a project path.
///
/// Uses the directory name (last non-empty path segment) as the short name,
/// which is what `discover_projects` already uses as `project.name`.
fn project_name_short(name: &str, _path: &Path) -> String {
    // `name` is already the final path segment from `discover_projects`.
    name.to_string()
}

/// Extension trait to get end-of-day for a DateTime<Utc>.
trait EndOfDay {
    fn end_day(self) -> chrono::DateTime<chrono::Utc>;
}

impl EndOfDay for chrono::DateTime<chrono::Utc> {
    fn end_day(self) -> chrono::DateTime<chrono::Utc> {
        self.date_naive().and_hms_opt(23, 59, 59).unwrap().and_local_timezone(chrono::Utc).unwrap()
    }
}