seshat-cli 0.5.1

CLI commands and TUI for Seshat
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
//! Implementation of the `seshat status` command.
//!
//! Scans the XDG repos directory for `.db` files, identifies root projects vs
//! submodules, reads `repo_metadata` from each DB for summary info, and
//! displays a tree view with aligned columns.

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

use owo_colors::OwoColorize;

use seshat_storage::{
    Database, RepoMetadataRepository, SqliteRepoMetadataRepository, SqliteSubmoduleRepository,
    SubmoduleRepository, SubmoduleRow,
};

use crate::db;
use crate::error::CliError;
use crate::format::color_enabled;

/// Summary info extracted from a project or submodule database.
struct ProjectSummary {
    /// Display name (project name or mount path for submodules).
    name: String,
    /// Number of indexed files.
    file_count: usize,
    /// Number of detected conventions.
    convention_count: usize,
    /// Database file size in bytes.
    db_size: u64,
    /// Database path on disk.
    db_path: PathBuf,
    /// Last scan timestamp from repo_metadata (ISO-8601 or epoch string).
    last_scan_time: Option<String>,
}

/// A root project with its optional submodules.
struct ProjectEntry {
    /// Root project summary.
    root: ProjectSummary,
    /// Submodule summaries (from the submodules table in root DB).
    submodules: Vec<SubmoduleSummary>,
}

/// A submodule entry — may have a valid DB or be orphaned/missing.
struct SubmoduleSummary {
    /// Mount path (relative_path from submodules table).
    mount_path: String,
    /// Summary from the submodule DB (None if DB is missing/broken).
    summary: Option<ProjectSummary>,
    /// Whether this submodule DB exists on disk.
    db_exists: bool,
}

/// Run the `seshat status` command.
///
/// Scans the XDG repos directory, identifies root projects and submodules,
/// and displays a tree with summary information.
pub fn run_status(verbose: bool) -> Result<(), CliError> {
    let color = color_enabled();
    let repos_dir = db::xdg_repos_dir()?;

    if !repos_dir.is_dir() {
        eprintln!("No Seshat databases found.");
        eprintln!();
        eprintln!("hint: run `seshat scan <path>` to index a project");
        return Ok(());
    }

    let entries = discover_projects(&repos_dir)?;

    if entries.is_empty() {
        eprintln!("No Seshat databases found.");
        eprintln!();
        eprintln!("hint: run `seshat scan <path>` to index a project");
        return Ok(());
    }

    print_status_tree(&entries, verbose, color);

    Ok(())
}

/// Discover all root projects and their submodules from the repos directory.
///
/// Root projects are `.db` files directly in the repos dir.
/// Submodules are tracked in each root DB's `submodules` table.
fn discover_projects(repos_dir: &Path) -> Result<Vec<ProjectEntry>, CliError> {
    let root_dbs = db::list_available_projects(repos_dir)?;
    let mut entries = Vec::new();

    for (db_path, project_name) in &root_dbs {
        let root_summary = match load_project_summary(db_path, project_name) {
            Some(s) => s,
            None => continue, // Skip DBs that can't be opened
        };

        // Load submodule rows from root DB and resolve each.
        let submodules = load_submodule_summaries(db_path, project_name);

        entries.push(ProjectEntry {
            root: root_summary,
            submodules,
        });
    }

    Ok(entries)
}

/// Load summary info from a database file.
///
/// `file_count` and `convention_count` are read from `repo_metadata` (written
/// by the scanner at the end of every scan) rather than from `files_ir` with
/// an `ir_schema_version` filter.  This avoids displaying `0 files` when a
/// database was scanned with an older IR schema version — the metadata values
/// reflect what was actually indexed at scan time regardless of schema version.
///
/// Falls back to a direct `COUNT(*)` query when `repo_metadata` does not yet
/// contain the keys (e.g., for very old databases created before the metadata
/// writes were introduced).
fn load_project_summary(db_path: &Path, name: &str) -> Option<ProjectSummary> {
    let db = Database::open(db_path).ok()?;

    let meta_repo = SqliteRepoMetadataRepository::new(db.connection().clone());

    // File count: prefer repo_metadata["file_count"] written by the scanner.
    //
    // We deliberately do NOT use get_file_hashes_by_branch() here, because
    // that query filters on the current IR_SCHEMA_VERSION and would return 0
    // for databases scanned with an older schema version — even when those
    // databases contain hundreds of files.  The repo_metadata value is written
    // at the end of every scan and is version-agnostic.
    let file_count = meta_repo
        .get("file_count")
        .ok()
        .flatten()
        .and_then(|v| v.parse::<usize>().ok())
        // Fallback for very old DBs that pre-date the metadata write.
        .unwrap_or_else(|| crate::db::count_files_any_schema(&db, "main"));

    // Convention count: prefer repo_metadata["convention_count"].
    let convention_count = meta_repo
        .get("convention_count")
        .ok()
        .flatten()
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or_else(|| crate::db::count_conventions(&db, "main"));

    let db_size = std::fs::metadata(db_path).map(|m| m.len()).unwrap_or(0);
    let last_scan_time = meta_repo.get("last_scan_time").ok().flatten();

    Some(ProjectSummary {
        name: name.to_string(),
        file_count,
        convention_count,
        db_size,
        db_path: db_path.to_path_buf(),
        last_scan_time,
    })
}

/// Load submodule summaries from a root project's database.
fn load_submodule_summaries(root_db_path: &Path, project_name: &str) -> Vec<SubmoduleSummary> {
    let db = match Database::open(root_db_path) {
        Ok(d) => d,
        Err(_) => return Vec::new(),
    };

    let sub_repo = SqliteSubmoduleRepository::new(db.connection().clone());
    let rows: Vec<SubmoduleRow> = match sub_repo.list() {
        Ok(r) => r,
        Err(_) => return Vec::new(),
    };

    rows.into_iter()
        .map(|row| {
            let sub_db_path = db::resolve_submodule_db_path(project_name, &row.relative_path).ok();

            let db_exists = sub_db_path.as_ref().is_some_and(|p| p.exists());

            let summary = if db_exists {
                sub_db_path
                    .as_ref()
                    .and_then(|p| load_project_summary(p, &row.relative_path))
            } else {
                None
            };

            SubmoduleSummary {
                mount_path: row.relative_path,
                summary,
                db_exists,
            }
        })
        .collect()
}

/// Format a last-scan timestamp for display.
///
/// If the value looks like a Unix epoch (all digits), format as a
/// human-readable date. Otherwise return as-is (likely already ISO-8601).
fn format_last_scan(value: &str) -> String {
    // Try parsing as Unix timestamp (seconds).
    if let Ok(epoch) = value.parse::<i64>() {
        let diff = chrono::Utc::now().timestamp() - epoch;
        if diff < 60 {
            // Covers negative diff (clock skew) and very recent scans.
            return "just now".to_string();
        } else if diff < 3600 {
            return format!("{}m ago", diff / 60);
        } else if diff < 86400 {
            return format!("{}h ago", diff / 3600);
        } else {
            return format!("{}d ago", diff / 86400);
        }
    }

    // Already a readable string (ISO-8601 or similar).
    value.to_string()
}

/// Print the status tree to stderr.
fn print_status_tree(entries: &[ProjectEntry], verbose: bool, color: bool) {
    let total_projects = entries.len();
    let total_submodules: usize = entries.iter().map(|e| e.submodules.len()).sum();

    // Header
    if color {
        eprintln!(
            "{}",
            format!("seshat status — {total_projects} project(s)").bold()
        );
    } else {
        eprintln!("seshat status — {total_projects} project(s)");
    }
    eprintln!();

    for (i, entry) in entries.iter().enumerate() {
        let is_last_project = i == entries.len() - 1;
        print_project_entry(entry, is_last_project, verbose, color);
    }

    // Footer summary
    eprintln!();
    let total_files: usize = entries.iter().map(|e| e.root.file_count).sum();
    let total_conventions: usize = entries.iter().map(|e| e.root.convention_count).sum();
    if color {
        eprintln!(
            "{}  {} files, {} conventions across {} project(s) and {} submodule(s)",
            "Total:".dimmed(),
            crate::format::format_number(total_files as u64),
            crate::format::format_number(total_conventions as u64),
            total_projects,
            total_submodules,
        );
    } else {
        eprintln!(
            "Total:  {} files, {} conventions across {} project(s) and {} submodule(s)",
            crate::format::format_number(total_files as u64),
            crate::format::format_number(total_conventions as u64),
            total_projects,
            total_submodules,
        );
    }
}

/// Print a single project entry (root + submodules).
fn print_project_entry(entry: &ProjectEntry, _is_last: bool, verbose: bool, color: bool) {
    let root = &entry.root;

    // Project name line
    let name_display = if color {
        root.name.bold().to_string()
    } else {
        root.name.clone()
    };

    eprintln!("  {name_display}");

    // Details line
    let files_str = crate::format::format_number(root.file_count as u64);
    let conventions_str = crate::format::format_number(root.convention_count as u64);
    let size_str = crate::format::format_human_size(root.db_size);

    let last_scan_str = root
        .last_scan_time
        .as_ref()
        .map(|t| format_last_scan(t))
        .unwrap_or_else(|| "never".to_string());

    if color {
        eprintln!(
            "    {} {files_str}  {} {conventions_str}  {} {size_str}  {} {last_scan_str}",
            "files:".dimmed(),
            "conventions:".dimmed(),
            "size:".dimmed(),
            "scanned:".dimmed(),
        );
    } else {
        eprintln!(
            "    files: {files_str}  conventions: {conventions_str}  size: {size_str}  scanned: {last_scan_str}",
        );
    }

    // Verbose: full DB path
    if verbose {
        if color {
            eprintln!("    {} {}", "db:".dimmed(), root.db_path.display());
        } else {
            eprintln!("    db: {}", root.db_path.display());
        }
    }

    // Submodules
    for (j, sub) in entry.submodules.iter().enumerate() {
        let is_last_sub = j == entry.submodules.len() - 1;
        let connector = if is_last_sub {
            "└── "
        } else {
            "├── "
        };

        if !sub.db_exists {
            // Orphaned / missing DB
            let warn = if color {
                format!(
                    "    {connector}{} {}",
                    sub.mount_path,
                    "(DB missing)".yellow()
                )
            } else {
                format!("    {connector}{} (DB missing)", sub.mount_path)
            };
            eprintln!("{warn}");
            continue;
        }

        match &sub.summary {
            Some(summary) => {
                let sub_files = crate::format::format_number(summary.file_count as u64);
                let sub_convs = crate::format::format_number(summary.convention_count as u64);
                let sub_size = crate::format::format_human_size(summary.db_size);

                let sub_scan = summary
                    .last_scan_time
                    .as_ref()
                    .map(|t| format_last_scan(t))
                    .unwrap_or_else(|| "never".to_string());

                // Indents for the details line and optional verbose line.
                // Chosen so the content aligns under the submodule name.
                let detail_indent = if is_last_sub {
                    "        "
                } else {
                    ""
                };

                // Line 1: name
                if color {
                    eprintln!("    {connector}{}", sub.mount_path.bold(),);
                } else {
                    eprintln!("    {connector}{}", sub.mount_path);
                }

                // Line 2: details — identical labels and layout as root project.
                if color {
                    eprintln!(
                        "{detail_indent}{} {sub_files}  {} {sub_convs}  {} {sub_size}  {} {sub_scan}",
                        "files:".dimmed(),
                        "conventions:".dimmed(),
                        "size:".dimmed(),
                        "scanned:".dimmed(),
                    );
                } else {
                    eprintln!(
                        "{detail_indent}files: {sub_files}  conventions: {sub_convs}  size: {sub_size}  scanned: {sub_scan}",
                    );
                }

                if verbose {
                    if color {
                        eprintln!(
                            "{detail_indent}{} {}",
                            "db:".dimmed(),
                            summary.db_path.display()
                        );
                    } else {
                        eprintln!("{detail_indent}db: {}", summary.db_path.display());
                    }
                }
            }
            None => {
                let warn = if color {
                    format!(
                        "    {connector}{} {}",
                        sub.mount_path,
                        "(could not read DB)".yellow()
                    )
                } else {
                    format!("    {connector}{} (could not read DB)", sub.mount_path)
                };
                eprintln!("{warn}");
            }
        }
    }

    eprintln!();
}

// ══════════════════════════════════════════════════════════════════════
// Tests
// ══════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn format_last_scan_epoch_just_now() {
        let now = chrono::Utc::now().timestamp();
        let result = format_last_scan(&now.to_string());
        assert_eq!(result, "just now");
    }

    #[test]
    fn format_last_scan_epoch_minutes_ago() {
        let five_min_ago = chrono::Utc::now().timestamp() - 300;
        let result = format_last_scan(&five_min_ago.to_string());
        assert_eq!(result, "5m ago");
    }

    #[test]
    fn format_last_scan_epoch_hours_ago() {
        let two_hours_ago = chrono::Utc::now().timestamp() - 7200;
        let result = format_last_scan(&two_hours_ago.to_string());
        assert_eq!(result, "2h ago");
    }

    #[test]
    fn format_last_scan_epoch_days_ago() {
        let three_days_ago = chrono::Utc::now().timestamp() - 259200;
        let result = format_last_scan(&three_days_ago.to_string());
        assert_eq!(result, "3d ago");
    }

    #[test]
    fn format_last_scan_iso_string_passthrough() {
        let result = format_last_scan("2026-04-03T22:00:00");
        assert_eq!(result, "2026-04-03T22:00:00");
    }

    #[test]
    fn discover_projects_empty_dir() {
        let tmp = tempfile::tempdir().expect("create temp dir");
        let repos = tmp.path().join("repos");
        fs::create_dir_all(&repos).expect("create repos dir");

        let entries = discover_projects(&repos).expect("should succeed");
        assert!(entries.is_empty());
    }

    #[test]
    fn discover_projects_with_root_db() {
        let tmp = tempfile::tempdir().expect("create temp dir");
        let repos = tmp.path().join("repos");
        fs::create_dir_all(&repos).expect("create repos dir");

        // Create a real DB file
        let db_path = repos.join("test-project.db");
        let db = Database::open(&db_path).expect("create db");

        // Write some repo_metadata
        let meta_repo = SqliteRepoMetadataRepository::new(db.connection().clone());
        meta_repo
            .set("last_scan_time", "1700000000")
            .expect("set metadata");
        drop(db);

        let entries = discover_projects(&repos).expect("should succeed");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].root.name, "test-project");
        assert_eq!(entries[0].root.file_count, 0);
        assert_eq!(entries[0].root.convention_count, 0);
        assert!(entries[0].root.db_size > 0);
        assert_eq!(
            entries[0].root.last_scan_time,
            Some("1700000000".to_string())
        );
    }

    #[test]
    fn discover_projects_with_submodule() {
        let tmp = tempfile::tempdir().expect("create temp dir");
        let repos = tmp.path().join("repos");
        fs::create_dir_all(&repos).expect("create repos dir");

        // Create root DB with a submodule entry
        let root_db_path = repos.join("my-project.db");
        let root_db = Database::open(&root_db_path).expect("create root db");

        let sub_repo = SqliteSubmoduleRepository::new(root_db.connection().clone());
        // Create submodule directory structure and DB
        let sub_dir = repos.join("my-project");
        fs::create_dir_all(&sub_dir).expect("create sub dir");
        let sub_db_path = sub_dir.join("vendor-lib.db");
        let sub_db = Database::open(&sub_db_path).expect("create sub db");
        drop(sub_db);

        // Insert submodule row pointing to the real DB path
        use seshat_storage::SubmoduleInput;
        sub_repo
            .insert(&SubmoduleInput {
                relative_path: "vendor-lib".to_string(),
                name: "lib".to_string(),
                db_path: sub_db_path.to_string_lossy().to_string(),
                commit_hash: Some("abc123".to_string()),
            })
            .expect("insert submodule");
        drop(root_db);

        // discover_projects uses resolve_submodule_db_path which uses XDG,
        // so this test verifies the row-loading path but the sub DB resolution
        // will differ. That's OK — the submodule will appear as "DB missing"
        // unless the XDG path happens to match.
        let entries = discover_projects(&repos).expect("should succeed");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].root.name, "my-project");
        // Submodule row was loaded (1 entry)
        assert_eq!(entries[0].submodules.len(), 1);
        assert_eq!(entries[0].submodules[0].mount_path, "vendor-lib");

        // Clean up: resolve_submodule_db_path creates dirs in the real XDG
        // data directory as a side effect.
        if let Ok(xdg_repos) = db::xdg_repos_dir() {
            let _ = fs::remove_dir_all(xdg_repos.join("my-project"));
        }
    }

    #[test]
    fn load_project_summary_returns_none_for_bad_path() {
        let result = load_project_summary(Path::new("/nonexistent/path.db"), "test");
        assert!(result.is_none());
    }

    #[test]
    fn load_project_summary_reads_metadata() {
        let tmp = tempfile::tempdir().expect("create temp dir");
        let db_path = tmp.path().join("test.db");
        let db = Database::open(&db_path).expect("create db");

        let meta_repo = SqliteRepoMetadataRepository::new(db.connection().clone());
        meta_repo.set("last_scan_time", "1700000000").expect("set");
        drop(db);

        let summary = load_project_summary(&db_path, "test").expect("should load");
        assert_eq!(summary.name, "test");
        assert_eq!(summary.last_scan_time, Some("1700000000".to_string()));
        assert!(summary.db_size > 0);
    }

    #[test]
    fn run_status_no_repos_dir() {
        // When XDG dir doesn't exist, run_status should succeed gracefully.
        // We can't easily mock XDG, but we can verify format_last_scan handles
        // edge cases which is the testable pure logic.
        let result = format_last_scan("not-a-number");
        assert_eq!(result, "not-a-number");
    }

    /// Regression test: file_count must be read from repo_metadata, not from
    /// get_file_hashes_by_branch (which filters on ir_schema_version and would
    /// return 0 for databases scanned with an older schema version).
    #[test]
    fn load_project_summary_reads_file_count_from_repo_metadata() {
        let tmp = tempfile::tempdir().expect("create temp dir");
        let db_path = tmp.path().join("test.db");
        let db = Database::open(&db_path).expect("create db");

        let meta_repo = SqliteRepoMetadataRepository::new(db.connection().clone());
        // Simulate what the scanner writes at the end of a scan.
        meta_repo.set("file_count", "370").expect("set file_count");
        meta_repo
            .set("convention_count", "552")
            .expect("set convention_count");
        meta_repo.set("last_scan_time", "1700000000").expect("set");
        // Note: we deliberately write NO rows to files_ir, simulating a DB
        // where all rows have an older ir_schema_version that would be filtered
        // out by get_file_hashes_by_branch.
        drop(db);

        let summary = load_project_summary(&db_path, "test").expect("should load");
        assert_eq!(
            summary.file_count, 370,
            "must read from repo_metadata, not files_ir"
        );
        assert_eq!(summary.convention_count, 552);
    }

    /// Regression test: when repo_metadata has no file_count (old DB), fall back
    /// to COUNT(*) without ir_schema_version filter.
    #[test]
    fn load_project_summary_falls_back_to_count_when_no_metadata() {
        use seshat_core::test_helpers::make_project_file;
        use seshat_storage::{FileIRRepository, SqliteFileIRRepository};

        let tmp = tempfile::tempdir().expect("create temp dir");
        let db_path = tmp.path().join("test.db");
        let db = Database::open(&db_path).expect("create db");
        let conn = db.connection().clone();

        // Insert a file without setting repo_metadata["file_count"].
        let branch = seshat_core::BranchId::from("main");
        let file = make_project_file(seshat_core::Language::Rust);
        SqliteFileIRRepository::new(conn)
            .upsert(&branch, &file, None)
            .expect("upsert");
        drop(db);

        let summary = load_project_summary(&db_path, "test").expect("should load");
        // Should fall back to COUNT(*) and find the 1 row we inserted.
        assert_eq!(
            summary.file_count, 1,
            "fallback COUNT(*) should find the file"
        );
    }
}