lore-cli 0.1.13

Capture AI coding sessions and link them to git commits
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
use anyhow::Result;
use clap::{CommandFactory, Parser, Subcommand};
use std::io::{self, IsTerminal, Write};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

// Reset SIGPIPE to default behavior on Unix systems.
// This prevents panics when piping output to commands like `head` that close
// the pipe early. Without this, writing to a closed pipe causes EPIPE errors
// which manifest as panics in libraries that don't handle them gracefully.
#[cfg(unix)]
fn reset_sigpipe() {
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
}

#[cfg(not(unix))]
fn reset_sigpipe() {
    // No-op on non-Unix systems
}

mod capture;
mod cli;
mod cloud;
mod config;
mod daemon;
mod git;
mod mcp;
mod storage;
mod summarize;

use cli::commands;
use config::Config;

// ANSI escape codes for terminal colors
const YELLOW: &str = "\x1b[33m";
const GREEN: &str = "\x1b[32m";
const RED: &str = "\x1b[31m";
const BOLD: &str = "\x1b[1m";
const RESET: &str = "\x1b[0m";

/// Timeout duration for the init prompt in seconds.
const PROMPT_TIMEOUT_SECS: u64 = 30;

/// The main CLI command line interface.
#[derive(Parser)]
#[command(name = "lore")]
#[command(version)]
#[command(about = "Reasoning history for code - capture the story behind your commits")]
#[command(
    long_about = "Lore captures AI coding sessions and links them to git commits,\n\
    preserving the reasoning behind code changes.\n\n\
    Git captures code history (what changed). Lore captures reasoning\n\
    history (how and why it changed through human-AI collaboration)."
)]
#[command(after_help = "EXAMPLES:\n    \
    lore import              Import sessions from Claude Code\n    \
    lore sessions            List recent sessions\n    \
    lore show abc123         View session details\n    \
    lore show --commit HEAD  View sessions linked to HEAD\n    \
    lore link abc123         Link session to HEAD\n    \
    lore search \"auth\"       Search sessions for text\n    \
    lore insights            Show AI development insights\n    \
    lore daemon start        Start background watcher\n\n\
    For more information about a command, run 'lore <command> --help'.")]
pub struct Cli {
    #[command(subcommand)]
    command: Commands,

    /// Enable verbose output for debugging
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Skip the first-run setup prompt (useful for scripting)
    #[arg(long, global = true)]
    no_init: bool,
}

/// Available CLI subcommands.
#[derive(Subcommand)]
enum Commands {
    /// Initialize Lore with guided setup
    #[command(
        long_about = "Runs a guided setup wizard that detects installed AI coding tools\n\
        and creates an initial configuration file. Use this when first\n\
        installing Lore or to reconfigure your setup."
    )]
    Init(commands::init::Args),

    /// Show Lore status, database stats, and recent sessions
    #[command(
        long_about = "Displays an overview of the Lore database including session counts,\n\
        watcher availability, daemon status, links to the current commit,\n\
        and a list of recent sessions."
    )]
    Status(commands::status::Args),

    /// Show the active session for the current directory
    #[command(
        long_about = "Reports the active session ID for the current working directory.\n\
        Queries the daemon if running, otherwise checks the database for\n\
        the most recent session."
    )]
    Current(commands::current::Args),

    /// Show recent sessions for quick orientation
    #[command(
        long_about = "Provides a summary of recent sessions for the current repository.\n\
        Shows session ID, tool, start time, message count, and linked commits.\n\
        Use --last for detailed info about the most recent session only."
    )]
    Context(commands::context::Args),

    /// List and filter imported sessions
    #[command(
        long_about = "Displays a table of imported sessions with their IDs, timestamps,\n\
        message counts, branches, and directories. Sessions can be filtered\n\
        by repository path."
    )]
    Sessions(commands::sessions::Args),

    /// Show session details or sessions linked to a commit
    #[command(
        long_about = "Displays the full conversation history for a session, or lists\n\
        all sessions linked to a specific commit when using --commit.\n\
        \n\
        Supports multiple output formats:\n\
        - text: colored terminal output (default)\n\
        - json: machine-readable structured output\n\
        - markdown: formatted for documentation"
    )]
    Show(commands::show::Args),

    /// Link sessions to git commits
    #[command(
        long_about = "Creates associations between AI coding sessions and git commits.\n\
        Links can be created manually by specifying session IDs, or\n\
        automatically using --auto to find sessions by time proximity\n\
        and file overlap."
    )]
    Link(commands::link::Args),

    /// Remove session-to-commit links
    #[command(
        long_about = "Removes links between sessions and commits. Can remove a specific\n\
        link using --commit, or remove all links for a session."
    )]
    Unlink(commands::unlink::Args),

    /// Add a bookmark or note to the current session
    #[command(
        long_about = "Adds an annotation (bookmark or note) to the current active session\n\
        or a specified session. Annotations help mark important moments\n\
        in a session for later reference."
    )]
    Annotate(commands::annotate::Args),

    /// Add or remove tags from a session
    #[command(
        long_about = "Tags sessions for organization and filtering. Each session can\n\
        have multiple tags. Use --remove to remove a tag. Tags are shown\n\
        in 'lore show' output and can be filtered with 'lore sessions --tag'."
    )]
    Tag(commands::tag::Args),

    /// Add or view a session summary
    #[command(
        long_about = "Manages session summaries that provide concise descriptions of\n\
        what happened in a session. Summaries help with quickly understanding\n\
        session context when continuing work or reviewing history."
    )]
    Summarize(commands::summarize::Args),

    /// Permanently delete a session and its data
    #[command(
        long_about = "Permanently removes a session and all its associated data\n\
        (messages and links) from the database. This operation cannot\n\
        be undone."
    )]
    Delete(commands::delete::Args),

    /// Show which AI session led to a specific line of code
    #[command(
        long_about = "Uses git blame to find the commit that introduced a specific\n\
        line of code, then looks up any sessions linked to that commit.\n\
        Displays the session info and relevant message excerpts."
    )]
    Blame(commands::blame::Args),

    /// Export a session in various formats
    #[command(
        long_about = "Exports session data as markdown or JSON. Supports redaction\n\
        of sensitive information like API keys, tokens, passwords,\n\
        and email addresses. Use --redact for built-in patterns or\n\
        --redact-pattern for custom regex patterns."
    )]
    Export(commands::export::Args),

    /// Search session content using full-text search
    #[command(
        long_about = "Searches message content using SQLite FTS5 full-text search.\n\
        Supports filtering by repository, date range, and message role.\n\
        The search index is built automatically on first use."
    )]
    Search(commands::search::Args),

    /// View and manage configuration settings
    #[command(
        long_about = "Provides subcommands to show, get, and set configuration values.\n\
        Configuration is stored in ~/.lore/config.yaml."
    )]
    Config(commands::config::Args),

    /// Import sessions from AI coding tools
    #[command(
        long_about = "Discovers and imports session files from AI coding tools into\n\
        the Lore database. Tracks imported files to avoid duplicates.\n\n\
        Supported tools:\n  \
        - Aider (markdown chat history files)\n  \
        - Claude Code (JSONL files in ~/.claude/projects/)\n  \
        - Cline (VS Code extension storage)\n  \
        - Codex CLI (JSONL files in ~/.codex/sessions/)\n  \
        - Continue.dev (JSON files in ~/.continue/sessions/)\n  \
        - Gemini CLI (JSON files in ~/.gemini/tmp/)"
    )]
    Import(commands::import::Args),

    /// Show AI development insights and analytics
    #[command(
        long_about = "Surfaces analytics about AI-assisted development patterns\n\
        including commit coverage, tool usage breakdown, activity patterns,\n\
        and most-touched files. Use --since to scope to a time period."
    )]
    Insights(commands::insights::Args),

    /// Manage git hooks for automatic session linking
    #[command(
        long_about = "Installs, uninstalls, or checks the status of git hooks that\n\
        integrate Lore with your git workflow. The post-commit hook\n\
        automatically links sessions to commits."
    )]
    Hooks(commands::hooks::Args),

    /// Manage the background daemon for automatic session capture
    #[command(
        long_about = "Controls the background daemon that watches for new AI coding\n\
        sessions and automatically imports them into the database."
    )]
    Daemon(commands::daemon::Args),

    /// Manage the database (vacuum, prune, stats)
    #[command(
        long_about = "Database management commands for maintenance and statistics.\n\
        Includes vacuum (reclaim space), prune (delete old sessions),\n\
        and stats (show database statistics)."
    )]
    Db(commands::db::Args),

    /// Authenticate with the Lore cloud service
    #[command(
        long_about = "Opens a browser to authenticate with the Lore cloud service.\n\
        After authentication, your API key is stored securely in the\n\
        OS keychain (or a fallback file if keychain is unavailable)."
    )]
    Login(commands::login::Args),

    /// Log out from the Lore cloud service
    #[command(
        long_about = "Removes stored credentials and encryption keys from the keychain\n\
        and any fallback files."
    )]
    Logout(commands::logout::Args),

    /// Sync sessions with Lore cloud
    #[command(
        long_about = "Cloud sync commands for backing up sessions and syncing across\n\
        machines. Session content is encrypted end-to-end using a\n\
        passphrase that only you know."
    )]
    Cloud(commands::cloud::Args),

    /// Diagnose Lore installation and configuration issues
    #[command(
        long_about = "Performs comprehensive health checks on the Lore installation.\n\
        Checks configuration, database, daemon status, watchers, and MCP server.\n\
        Returns exit code 0 for OK, 1 for warnings, 2 for errors."
    )]
    Doctor(commands::doctor::Args),

    /// Run the MCP server for AI tool integration
    #[command(
        long_about = "Runs the MCP (Model Context Protocol) server on stdio.\n\
        This allows AI coding tools like Claude Code to query Lore\n\
        session data directly."
    )]
    Mcp(commands::mcp::Args),

    /// Generate shell completions
    #[command(
        long_about = "Generates shell completion scripts for various shells.\n\
        Output to stdout for redirection to the appropriate file."
    )]
    Completions(commands::completions::Args),
}

/// Checks if Lore is configured (config file exists).
fn is_configured() -> bool {
    Config::config_path()
        .map(|path| path.exists())
        .unwrap_or(false)
}

/// Checks if the given command should skip the first-run prompt.
///
/// Commands that should skip:
/// - `init` (the setup command itself)
/// - `config` (should work without init for debugging)
/// - `completions` (should work without init for shell setup)
/// - `doctor` (diagnostic command should work without init)
/// - `mcp` (MCP server should work without init for tool integration)
/// - `login` (should work to set up cloud before init)
/// - `logout` (should work to clean up cloud state)
fn should_skip_first_run_prompt(command: &Commands) -> bool {
    matches!(
        command,
        Commands::Init(_)
            | Commands::Config(_)
            | Commands::Completions(_)
            | Commands::Doctor(_)
            | Commands::Mcp(_)
            | Commands::Login(_)
            | Commands::Logout(_)
    )
}

/// Checks if this is a daemon foreground run.
///
/// The daemon sets up its own file-based logging, so we skip the default
/// console logging initialization to allow the daemon's logging to succeed.
fn is_daemon_foreground(command: &Commands) -> bool {
    matches!(
        command,
        Commands::Daemon(commands::daemon::Args {
            command: commands::daemon::DaemonSubcommand::Start { foreground: true }
        })
    )
}

/// Checks if stdin is connected to a terminal (interactive mode).
fn is_interactive() -> bool {
    io::stdin().is_terminal()
}

/// Checks if stdout is connected to a terminal (for color output).
fn stdout_is_tty() -> bool {
    io::stdout().is_terminal()
}

/// Result of the init prompt, including timeout case.
#[derive(Debug, PartialEq)]
enum PromptResult {
    /// User chose to run init
    Yes,
    /// User declined init
    No,
    /// Prompt timed out with no response
    Timeout,
}

/// Prompts the user to run the init wizard with colored output and timeout.
///
/// Returns the user's choice or timeout after 30 seconds.
/// Uses ANSI colors if stdout is a TTY.
fn prompt_for_init() -> Result<PromptResult> {
    let use_color = stdout_is_tty();

    // Build the prompt with optional colors
    if use_color {
        print!(
            "{BOLD}{YELLOW}Lore isn't configured yet. Run setup?{RESET} [{GREEN}Y{RESET}/{RED}n{RESET}] "
        );
    } else {
        print!("Lore isn't configured yet. Run setup? [Y/n] ");
    }
    io::stdout().flush()?;

    // Use a channel to receive input with timeout
    let (tx, rx) = mpsc::channel();

    // Spawn a thread to read input
    thread::spawn(move || {
        let mut input = String::new();
        if io::stdin().read_line(&mut input).is_ok() {
            let _ = tx.send(input);
        }
    });

    // Wait for input with timeout
    match rx.recv_timeout(Duration::from_secs(PROMPT_TIMEOUT_SECS)) {
        Ok(input) => {
            let input = input.trim().to_lowercase();
            // Empty input or "y" or "yes" means yes (default)
            if input.is_empty() || input == "y" || input == "yes" {
                Ok(PromptResult::Yes)
            } else {
                Ok(PromptResult::No)
            }
        }
        Err(mpsc::RecvTimeoutError::Timeout) => {
            println!();
            Ok(PromptResult::Timeout)
        }
        Err(mpsc::RecvTimeoutError::Disconnected) => {
            // Sender dropped without sending, treat as no
            println!();
            Ok(PromptResult::No)
        }
    }
}

/// Creates a minimal config so the first-run prompt is not shown again.
fn create_minimal_config() -> Result<()> {
    let config = Config::default();
    config.save()
}

/// Returns a user-friendly name for the command being executed.
fn command_name(command: &Commands) -> &'static str {
    match command {
        Commands::Init(_) => "init",
        Commands::Status(_) => "status",
        Commands::Current(_) => "current",
        Commands::Context(_) => "context",
        Commands::Sessions(_) => "sessions",
        Commands::Show(_) => "show",
        Commands::Link(_) => "link",
        Commands::Unlink(_) => "unlink",
        Commands::Annotate(_) => "annotate",
        Commands::Tag(_) => "tag",
        Commands::Summarize(_) => "summarize",
        Commands::Delete(_) => "delete",
        Commands::Blame(_) => "blame",
        Commands::Export(_) => "export",
        Commands::Search(_) => "search",
        Commands::Config(_) => "config",
        Commands::Import(_) => "import",
        Commands::Insights(_) => "insights",
        Commands::Hooks(_) => "hooks",
        Commands::Daemon(_) => "daemon",
        Commands::Db(_) => "db",
        Commands::Login(_) => "login",
        Commands::Logout(_) => "logout",
        Commands::Cloud(_) => "cloud",
        Commands::Doctor(_) => "doctor",
        Commands::Mcp(_) => "mcp",
        Commands::Completions(_) => "completions",
    }
}

fn main() -> Result<()> {
    // Handle SIGPIPE to prevent panics when piping to commands like `head`
    reset_sigpipe();

    let cli = Cli::parse();

    // Initialize logging (skip for daemon foreground mode - it sets up file logging)
    if !is_daemon_foreground(&cli.command) {
        let filter = if cli.verbose {
            "lore=debug"
        } else {
            "lore=info"
        };

        tracing_subscriber::registry()
            .with(
                tracing_subscriber::EnvFilter::try_from_default_env()
                    .unwrap_or_else(|_| filter.into()),
            )
            .with(tracing_subscriber::fmt::layer().without_time())
            .init();
    }

    // First-run detection: prompt to run init if not configured
    // Skip if --no-init flag is set (useful for scripting)
    if !cli.no_init
        && !is_configured()
        && !should_skip_first_run_prompt(&cli.command)
        && is_interactive()
    {
        match prompt_for_init()? {
            PromptResult::Yes => {
                // Run the init wizard with force=true since user explicitly chose setup
                commands::init::run(commands::init::Args { force: true })?;
                println!();
                println!(
                    "Setup complete! Running 'lore {}'...",
                    command_name(&cli.command)
                );
                println!();
            }
            PromptResult::No => {
                // User declined; create minimal config so we don't ask again
                println!("Okay, run 'lore init' anytime to configure.");
                println!();
                create_minimal_config()?;
            }
            PromptResult::Timeout => {
                // Timed out; create minimal config so we don't hang again
                println!("No response, continuing without setup...");
                println!();
                create_minimal_config()?;
            }
        }
    }

    match cli.command {
        Commands::Init(args) => commands::init::run(args),
        Commands::Status(args) => commands::status::run(args),
        Commands::Current(args) => commands::current::run(args),
        Commands::Context(args) => commands::context::run(args),
        Commands::Sessions(args) => commands::sessions::run(args),
        Commands::Show(args) => commands::show::run(args),
        Commands::Link(args) => commands::link::run(args),
        Commands::Unlink(args) => commands::unlink::run(args),
        Commands::Annotate(args) => commands::annotate::run(args),
        Commands::Tag(args) => commands::tag::run(args),
        Commands::Summarize(args) => commands::summarize::run(args),
        Commands::Delete(args) => commands::delete::run(args),
        Commands::Blame(args) => commands::blame::run(args),
        Commands::Export(args) => commands::export::run(args),
        Commands::Search(args) => commands::search::run(args),
        Commands::Config(args) => commands::config::run(args),
        Commands::Import(args) => commands::import::run(args),
        Commands::Insights(args) => commands::insights::run(args),
        Commands::Hooks(args) => commands::hooks::run(args),
        Commands::Daemon(args) => commands::daemon::run(args),
        Commands::Db(args) => commands::db::run(args),
        Commands::Login(args) => commands::login::run(args),
        Commands::Logout(args) => commands::logout::run(args),
        Commands::Cloud(args) => commands::cloud::run(args),
        Commands::Doctor(args) => commands::doctor::run(args),
        Commands::Mcp(args) => commands::mcp::run(args),
        Commands::Completions(args) => {
            let mut cmd = Cli::command();
            commands::completions::run(args, &mut cmd)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::OutputFormat;

    #[test]
    fn test_should_skip_first_run_prompt_init() {
        let command = Commands::Init(commands::init::Args { force: false });
        assert!(should_skip_first_run_prompt(&command));
    }

    #[test]
    fn test_should_skip_first_run_prompt_init_force() {
        let command = Commands::Init(commands::init::Args { force: true });
        assert!(should_skip_first_run_prompt(&command));
    }

    #[test]
    fn test_should_skip_first_run_prompt_config() {
        let command = Commands::Config(commands::config::Args {
            command: None,
            format: OutputFormat::Text,
        });
        assert!(should_skip_first_run_prompt(&command));
    }

    #[test]
    fn test_should_not_skip_first_run_prompt_status() {
        let command = Commands::Status(commands::status::Args {
            format: OutputFormat::Text,
        });
        assert!(!should_skip_first_run_prompt(&command));
    }

    #[test]
    fn test_should_not_skip_first_run_prompt_sessions() {
        let command = Commands::Sessions(commands::sessions::Args {
            repo: None,
            tag: None,
            limit: 20,
            format: OutputFormat::Text,
        });
        assert!(!should_skip_first_run_prompt(&command));
    }

    #[test]
    fn test_should_not_skip_first_run_prompt_import() {
        let command = Commands::Import(commands::import::Args {
            force: false,
            dry_run: false,
        });
        assert!(!should_skip_first_run_prompt(&command));
    }

    #[test]
    fn test_cli_no_init_flag_parses() {
        use clap::Parser;
        // Test that --no-init flag is recognized and parsed correctly
        let cli = Cli::try_parse_from(["lore", "--no-init", "status"]);
        assert!(cli.is_ok());
        let cli = cli.unwrap();
        assert!(cli.no_init);
    }

    #[test]
    fn test_cli_no_init_flag_default_false() {
        use clap::Parser;
        // Test that --no-init defaults to false when not provided
        let cli = Cli::try_parse_from(["lore", "status"]);
        assert!(cli.is_ok());
        let cli = cli.unwrap();
        assert!(!cli.no_init);
    }

    #[test]
    fn test_cli_no_init_flag_with_verbose() {
        use clap::Parser;
        // Test that --no-init and --verbose can be combined
        let cli = Cli::try_parse_from(["lore", "--no-init", "--verbose", "sessions"]);
        assert!(cli.is_ok());
        let cli = cli.unwrap();
        assert!(cli.no_init);
        assert!(cli.verbose);
    }

    #[test]
    fn test_command_name_status() {
        let command = Commands::Status(commands::status::Args {
            format: OutputFormat::Text,
        });
        assert_eq!(command_name(&command), "status");
    }

    #[test]
    fn test_command_name_sessions() {
        let command = Commands::Sessions(commands::sessions::Args {
            repo: None,
            tag: None,
            limit: 20,
            format: OutputFormat::Text,
        });
        assert_eq!(command_name(&command), "sessions");
    }

    #[test]
    fn test_command_name_import() {
        let command = Commands::Import(commands::import::Args {
            force: false,
            dry_run: false,
        });
        assert_eq!(command_name(&command), "import");
    }

    #[test]
    fn test_command_name_init() {
        let command = Commands::Init(commands::init::Args { force: false });
        assert_eq!(command_name(&command), "init");
    }

    #[test]
    fn test_prompt_result_equality() {
        // Test that PromptResult enum variants are distinguishable
        assert_eq!(PromptResult::Yes, PromptResult::Yes);
        assert_eq!(PromptResult::No, PromptResult::No);
        assert_eq!(PromptResult::Timeout, PromptResult::Timeout);
        assert_ne!(PromptResult::Yes, PromptResult::No);
        assert_ne!(PromptResult::Yes, PromptResult::Timeout);
        assert_ne!(PromptResult::No, PromptResult::Timeout);
    }

    #[test]
    fn test_completions_bash() {
        use clap_complete::{generate, Shell};
        let mut cmd = Cli::command();
        let mut buf = Vec::new();
        generate(Shell::Bash, &mut cmd, "lore", &mut buf);
        let output = String::from_utf8(buf).expect("valid utf8");
        assert!(
            output.contains("_lore"),
            "Should contain bash completion function"
        );
    }

    #[test]
    fn test_completions_zsh() {
        use clap_complete::{generate, Shell};
        let mut cmd = Cli::command();
        let mut buf = Vec::new();
        generate(Shell::Zsh, &mut cmd, "lore", &mut buf);
        let output = String::from_utf8(buf).expect("valid utf8");
        assert!(
            output.contains("#compdef lore"),
            "Should contain zsh compdef"
        );
    }

    #[test]
    fn test_completions_fish() {
        use clap_complete::{generate, Shell};
        let mut cmd = Cli::command();
        let mut buf = Vec::new();
        generate(Shell::Fish, &mut cmd, "lore", &mut buf);
        let output = String::from_utf8(buf).expect("valid utf8");
        assert!(
            output.contains("complete -c lore"),
            "Should contain fish completion"
        );
    }

    #[test]
    fn test_completions_powershell() {
        use clap_complete::{generate, Shell};
        let mut cmd = Cli::command();
        let mut buf = Vec::new();
        generate(Shell::PowerShell, &mut cmd, "lore", &mut buf);
        let output = String::from_utf8(buf).expect("valid utf8");
        assert!(
            output.contains("Register-ArgumentCompleter"),
            "Should contain powershell completer"
        );
    }

    #[test]
    fn test_completions_elvish() {
        use clap_complete::{generate, Shell};
        let mut cmd = Cli::command();
        let mut buf = Vec::new();
        generate(Shell::Elvish, &mut cmd, "lore", &mut buf);
        let output = String::from_utf8(buf).expect("valid utf8");
        assert!(
            output.contains("set edit:completion"),
            "Should contain elvish completion"
        );
    }
}