ralph-coder 0.2.1

An agentic code generation CLI powered by multiple LLM backends
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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
use clap::{Parser, Subcommand};
use colored::Colorize;
use ralph::checkpoint::Checkpoint;
use ralph::config::Config;
use ralph::errors::RalphError;
use ralph::loop_runner::LoopRunner;
use ralph::memory::MemoryStore;
use ralph::output::{ConfirmResult, OutputConfig, OutputFormat, Phase, Printer};
use ralph::providers::{
    deepseek::{DeepSeekProvider, ThinkingMode, DEFAULT_MODEL, PRO_MODEL},
    LlmProvider, Message,
};
use ralph::session::Session;
use rustyline::DefaultEditor;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

// ── CLI definition ────────────────────────────────────────────────────────────

#[derive(Parser, Debug)]
#[command(
    name = "ralph",
    version,
    about = "Ralph — an agentic code generation CLI",
    long_about = "Ralph is an AI-powered code generation agent that operates via an agentic loop.\nUses DeepSeek as the LLM backend (requires DEEPSEEK_API_KEY)."
)]
struct Cli {
    /// The task or prompt to execute
    prompt: Option<String>,

    /// Use the pro model (deepseek-v4-pro) instead of flash
    #[arg(long)]
    pro: bool,

    /// Override the model name
    #[arg(long, short = 'm')]
    model: Option<String>,

    /// Target workspace directory (default: current directory)
    #[arg(long, short = 'w', default_value = ".")]
    workspace: PathBuf,

    /// Limit the number of agentic loop iterations (default: unlimited)
    #[arg(long)]
    max_turns: Option<u32>,

    /// Show planned actions without executing them
    #[arg(long)]
    dry_run: bool,

    /// Skip confirmation prompts
    #[arg(long)]
    no_confirm: bool,

    /// Skip automatic workspace dependency installation (pip install -e ., npm install, etc.)
    #[arg(long)]
    no_setup: bool,

    /// Resume a session: --resume (last for workspace) or --resume <session-id>
    #[arg(long)]
    resume: Option<Option<String>>,

    /// Force a new session, ignoring any existing one
    #[arg(long)]
    new_session: bool,

    /// Create a named checkpoint at session start, before any changes
    #[arg(long)]
    checkpoint: Option<String>,

    /// Automatically checkpoint before every destructive operation
    #[arg(long)]
    auto_checkpoint: bool,

    /// Inject additional context from a file
    #[arg(long)]
    context: Option<PathBuf>,

    /// Activate LSP for a language (e.g. --lsp rust --lsp ts). May be repeated.
    #[arg(long)]
    lsp: Vec<String>,

    /// Output format: terminal (default) or json
    #[arg(long, default_value = "terminal")]
    output: String,

    /// Show full LLM interactions
    #[arg(long)]
    verbose: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Manage sessions
    Sessions {
        #[command(subcommand)]
        action: SessionAction,
    },
    /// Manage checkpoints
    Checkpoint {
        #[command(subcommand)]
        action: CheckpointAction,
    },
    /// Create a GitHub PR for the current branch (requires gh CLI)
    Pr {
        /// PR title
        #[arg(long, short = 't')]
        title: String,
        /// PR body / description
        #[arg(long, short = 'b', default_value = "")]
        body: String,
        /// Open as a draft PR
        #[arg(long)]
        draft: bool,
        /// Target base branch (default: repo default)
        #[arg(long)]
        base: Option<String>,
    },
    /// Show recent CI runs for the current branch (requires gh CLI)
    Ci {
        /// Branch name (default: current branch)
        #[arg(long)]
        branch: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
enum SessionAction {
    /// List all sessions
    List,
    /// Show details for a session
    Show { session_id: String },
    /// Delete sessions older than N days
    Clean {
        #[arg(long, default_value = "30")]
        older_than: u32,
    },
}

#[derive(Subcommand, Debug)]
enum CheckpointAction {
    /// List checkpoints for the current (or specified) session
    List {
        #[arg(long)]
        session: Option<String>,
    },
    /// Create a checkpoint in the current session
    Create {
        name: String,
        #[arg(long)]
        session: Option<String>,
    },
    /// Revert to a checkpoint
    Revert {
        name_or_number: String,
        #[arg(long)]
        session: Option<String>,
        /// Restore files only, without rolling back conversation history
        #[arg(long)]
        files_only: bool,
    },
    /// Show details for a checkpoint
    Show {
        name_or_number: String,
        #[arg(long)]
        session: Option<String>,
    },
}

// ── Entry point ───────────────────────────────────────────────────────────────

#[tokio::main]
async fn main() {
    if let Err(e) = run().await {
        eprintln!("{} {}", "[ralph]".red().bold(), e.to_string().red());
        std::process::exit(match &e {
            RalphError::GuardrailViolation(_) | RalphError::BlockedCommand(_) => 2,
            RalphError::MaxTurnsReached(_) => 3,
            _ => 1,
        });
    }
}

async fn run() -> Result<(), RalphError> {
    let cli = Cli::parse();

    let workspace = cli
        .workspace
        .canonicalize()
        .unwrap_or_else(|_| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));

    let mut config = Config::load(&workspace).unwrap_or_else(|e| {
        eprintln!("{} Config warning: {}", "[ralph]".yellow(), e);
        Config::default()
    });

    if cli.auto_checkpoint {
        config.checkpoints.auto_checkpoint_before_destructive = true;
    }

    let format = if cli.output == "json" {
        OutputFormat::Json
    } else {
        OutputFormat::Terminal
    };
    let printer = Arc::new(Printer::new(OutputConfig::new(format, cli.verbose)));

    // Subcommand dispatch — no provider needed
    if let Some(cmd) = cli.command {
        return handle_subcommand(cmd, &workspace, &config, &printer).await;
    }

    // ── Provider ──────────────────────────────────────────────────────────────
    let key = require_env("DEEPSEEK_API_KEY", "deepseek")?;
    let model = cli.model.clone().unwrap_or_else(|| {
        if cli.pro {
            PRO_MODEL.to_string()
        } else {
            DEFAULT_MODEL.to_string()
        }
    });
    // Normal provider uses thinking off; reasoning provider uses thinking on.
    let normal_provider: Arc<dyn LlmProvider> = Arc::new(DeepSeekProvider::new(
        key.clone(),
        Some(model.clone()),
        ThinkingMode::Off,
    ));
    let reasoning_provider: Arc<dyn LlmProvider> = Arc::new(DeepSeekProvider::new(
        key,
        Some(model.clone()),
        ThinkingMode::On {
            budget_tokens: 8000,
        },
    ));
    let provider = Arc::clone(&normal_provider);

    let provider_name = provider.name().to_string();

    printer.print(
        Phase::Ralph,
        &format!("Using {} / {}", provider_name.cyan(), model.cyan()),
    );

    // ── Session ───────────────────────────────────────────────────────────────
    let mut session = setup_session(&cli, &workspace, &provider_name, &model, &config, &printer)?;

    let printer = Arc::new(Printer::new(OutputConfig {
        format: if cli.output == "json" {
            OutputFormat::Json
        } else {
            OutputFormat::Terminal
        },
        verbose: cli.verbose,
        session_id: Some(session.meta.session_id.clone()),
    }));

    // Print LSP startup info
    if !cli.lsp.is_empty() {
        printer.print(
            Phase::Ralph,
            &format!("LSP enabled: {}", cli.lsp.join(", ")),
        );
    }

    // Shared diff-preview flag (off by default; toggled via /dp in interactive mode)
    let diff_preview = Arc::new(std::sync::atomic::AtomicBool::new(false));
    // Shared PR/CI flag (off by default; toggled via /pr in interactive mode)
    let pr_enabled = Arc::new(std::sync::atomic::AtomicBool::new(false));

    // Load project memory
    let memory = Arc::new(Mutex::new(MemoryStore::load(&workspace)));

    // Build workspace context for fresh sessions
    if session.messages.is_empty() {
        let search_on = ralph::tools::search_tools::search_available(
            &config.search.brave_api_key_env,
            &config.search.serp_api_key_env,
        );
        let ctx = ralph::context::WorkspaceContext::build(&workspace);
        let mem_ctx = memory.lock().unwrap().format_for_prompt();
        let test_cmd = config.testing.resolved_cmd(&workspace);

        // Pre-build the symbol index so the model knows it exists and can use
        // find_symbol immediately without exploring the codebase manually.
        let symbol_summary = {
            let idx = ralph::symbol_index::SymbolIndex::build(&workspace);
            let count = idx.symbol_count();
            if count > 0 {
                Some(format!(
                    "Symbol index: {:?} symbols indexed — use `find_symbol` to navigate by name instead of browsing files.",
                    count
                ))
            } else {
                None
            }
        };

        let system = ralph::prompts::system_prompt(
            &workspace.display().to_string(),
            search_on,
            mem_ctx.as_deref(),
            test_cmd.as_deref(),
            symbol_summary.as_deref(),
        );
        let combined = format!("{}\n\n---\n\n{}", system, ctx.to_context_string());
        session.messages.push(Message::system(combined));
    }

    // Initial checkpoint if requested
    if let Some(ref cp_name) = cli.checkpoint {
        Checkpoint::create(&session, cp_name, &config.checkpoints).await?;
    }

    // Ctrl+C handler
    ctrlc::set_handler(move || {
        eprintln!("\n{} Interrupted. Session state saved.", "[ralph]".yellow());
        std::process::exit(130);
    })
    .ok();

    match cli.prompt.clone() {
        Some(prompt) => {
            // ── Single-shot mode ──────────────────────────────────────────────
            let runner = LoopRunner::new(
                normal_provider,
                Some(reasoning_provider),
                config.clone(),
                workspace.clone(),
                Arc::clone(&printer),
                cli.max_turns, // None = unlimited; Some(n) if --max-turns given
                cli.dry_run,
                cli.no_confirm,
                cli.no_setup,
                Arc::clone(&memory),
                cli.lsp.clone(),
                Arc::clone(&diff_preview),
                Arc::clone(&pr_enabled),
            );
            let full_prompt = if let Some(ref ctx_path) = cli.context {
                let ctx =
                    std::fs::read_to_string(ctx_path).map_err(|e| RalphError::ToolFailed {
                        tool: "--context".to_string(),
                        message: e.to_string(),
                    })?;
                format!("## Additional Context\n\n{}\n\n## Task\n\n{}", ctx, prompt)
            } else {
                prompt
            };
            let dummy = Arc::new(AtomicBool::new(false));
            runner.run(&full_prompt, &mut session, dummy).await
        }
        None => {
            // ── Interactive mode: unlimited turns, Ctrl+C to cancel task ──────
            let runner = LoopRunner::new(
                normal_provider,
                Some(reasoning_provider),
                config.clone(),
                workspace.clone(),
                Arc::clone(&printer),
                None, // unlimited
                cli.dry_run,
                cli.no_confirm,
                cli.no_setup,
                Arc::clone(&memory),
                cli.lsp.clone(),
                Arc::clone(&diff_preview),
                Arc::clone(&pr_enabled),
            );
            interactive_mode(
                runner,
                session,
                cli.context.as_deref(),
                diff_preview,
                pr_enabled,
                Arc::clone(&printer),
                config.clone(),
            )
            .await
        }
    }
}

// ── Interactive mode ─────────────────────────────────────────────────────────

async fn interactive_mode(
    runner: LoopRunner,
    mut session: Session,
    context_path: Option<&std::path::Path>,
    diff_preview: Arc<std::sync::atomic::AtomicBool>,
    pr_enabled: Arc<std::sync::atomic::AtomicBool>,
    printer: Arc<Printer>,
    config: ralph::config::Config,
) -> Result<(), RalphError> {
    println!(
        "\n{} Interactive mode  {}  {}  {}\n",
        "Ralph".cyan().bold(),
        "Ctrl+C to cancel task".dimmed(),
        "·".dimmed(),
        "/h for help  ·  exit to quit".dimmed(),
    );
    println!(
        "  {} diff preview is off — type {} to enable\n",
        "tip:".dimmed(),
        "/dp on".cyan(),
    );

    let mut rl = DefaultEditor::new().map_err(|e| RalphError::ToolFailed {
        tool: "interactive".to_string(),
        message: e.to_string(),
    })?;

    // Load optional context file once
    let context_prefix: Option<String> = if let Some(path) = context_path {
        let ctx = std::fs::read_to_string(path).map_err(|e| RalphError::ToolFailed {
            tool: "--context".to_string(),
            message: e.to_string(),
        })?;
        Some(format!("## Additional Context\n\n{}\n\n## Task\n\n", ctx))
    } else {
        None
    };

    // Shared cancellation flag.  The ctrlc handler sets it; we reset it before
    // each new task.  A second Ctrl+C while the flag is already set exits Ralph.
    let task_cancelled = Arc::new(AtomicBool::new(false));
    let ctrlc_flag = Arc::clone(&task_cancelled);
    ctrlc::set_handler(move || {
        if ctrlc_flag.load(Ordering::SeqCst) {
            // Already cancelled once — user is insisting on exit
            eprintln!("\n{} Exiting.", "[ralph]".yellow());
            std::process::exit(130);
        }
        ctrlc_flag.store(true, Ordering::SeqCst);
        eprintln!(
            "\n{} Cancelling task… (Ctrl+C again to exit Ralph)",
            "[ralph]".yellow()
        );
    })
    .ok();

    loop {
        let readline = rl.readline(&format!("{} ", ">>".cyan().bold()));
        match readline {
            Ok(line) => {
                let input = line.trim().to_string();
                if input.is_empty() {
                    continue;
                }

                // ── Built-in commands ─────────────────────────────────────────
                if input == "exit" || input == "quit" {
                    println!("{} Goodbye.", "[ralph]".white().bold());
                    break;
                }
                if input == "/clear" {
                    session
                        .messages
                        .retain(|m| matches!(m.role, ralph::providers::Role::System));
                    session.flush().ok();
                    println!("{} Context cleared.", "[ralph]".white().bold());
                    println!();
                    continue;
                }
                if input == "/dp on"
                    || (input == "/dp" && !diff_preview.load(std::sync::atomic::Ordering::Relaxed))
                {
                    diff_preview.store(true, std::sync::atomic::Ordering::Relaxed);
                    println!(
                        "{} Diff preview {} — every write_file will show a diff before proceeding.",
                        "[ralph]".white().bold(),
                        "ON".green().bold()
                    );
                    println!();
                    continue;
                }
                if input == "/dp off"
                    || (input == "/dp" && diff_preview.load(std::sync::atomic::Ordering::Relaxed))
                {
                    diff_preview.store(false, std::sync::atomic::Ordering::Relaxed);
                    println!(
                        "{} Diff preview {}.",
                        "[ralph]".white().bold(),
                        "OFF".dimmed()
                    );
                    println!();
                    continue;
                }
                if input == "/cp" {
                    handle_cp_command(&mut session, &printer, &config);
                    continue;
                }
                if input == "/pr on"
                    || (input == "/pr" && !pr_enabled.load(std::sync::atomic::Ordering::Relaxed))
                {
                    pr_enabled.store(true, std::sync::atomic::Ordering::Relaxed);
                    println!("{} PR/CI tools {} — create_pr and get_ci_status are now available to Ralph.", "[ralph]".white().bold(), "ON".green().bold());
                    println!();
                    continue;
                }
                if input == "/pr off"
                    || (input == "/pr" && pr_enabled.load(std::sync::atomic::Ordering::Relaxed))
                {
                    pr_enabled.store(false, std::sync::atomic::Ordering::Relaxed);
                    println!(
                        "{} PR/CI tools {}.",
                        "[ralph]".white().bold(),
                        "OFF".dimmed()
                    );
                    println!();
                    continue;
                }
                if input == "/h" || input == "/help" {
                    print_help();
                    continue;
                }

                let _ = rl.add_history_entry(&input);

                let prompt = match &context_prefix {
                    Some(prefix) => format!("{}{}", prefix, input),
                    None => input,
                };

                // Reset cancellation flag before each new task
                task_cancelled.store(false, Ordering::SeqCst);

                match runner
                    .run(&prompt, &mut session, Arc::clone(&task_cancelled))
                    .await
                {
                    Ok(()) => {}
                    Err(RalphError::Interrupted) => {
                        println!(
                            "{} Task cancelled. Continuing chat.\n",
                            "[ralph]".yellow().bold()
                        );
                    }
                    Err(RalphError::MaxTurnsReached(_)) | Err(RalphError::ToolFailed { .. }) => {
                        // runner already printed the reason
                    }
                    Err(e) => {
                        eprintln!("{} {}", "[ralph]".red().bold(), e.to_string().red());
                    }
                }

                println!(); // blank line between tasks
            }
            Err(rustyline::error::ReadlineError::Eof) => {
                println!("\n{} Goodbye.", "[ralph]".white().bold());
                break;
            }
            Err(rustyline::error::ReadlineError::Interrupted) => {
                // Ctrl+C at the prompt (no task running) — exit
                println!("\n{} Goodbye.", "[ralph]".white().bold());
                break;
            }
            Err(e) => {
                eprintln!("{} Readline error: {}", "[ralph]".red(), e);
                break;
            }
        }
    }

    Ok(())
}

// ── Session setup ─────────────────────────────────────────────────────────────

fn setup_session(
    cli: &Cli,
    workspace: &PathBuf,
    provider_name: &str,
    model: &str,
    config: &Config,
    printer: &Printer,
) -> Result<Session, RalphError> {
    if let Some(Some(ref session_id)) = cli.resume {
        let session = Session::load(session_id, config)?;
        printer.print(
            Phase::Session,
            &format!(
                "Resumed session {} ({} turns)",
                session_id, session.meta.turn_count
            ),
        );
        return Ok(session);
    }

    if cli.new_session {
        return Session::create(workspace, provider_name, model, config);
    }

    if config.session.auto_resume {
        if let Some(existing) = Session::find_for_workspace(workspace, config) {
            let age_min = chrono::Utc::now()
                .signed_duration_since(existing.meta.last_active)
                .num_minutes();
            let age_str = if age_min < 60 {
                format!("{} min ago", age_min)
            } else {
                format!("{:.0} hr ago", age_min as f64 / 60.0)
            };
            println!(
                "{} Found previous session {} ({} turns, last active {}).",
                "[ralph]".white().bold(),
                existing.meta.session_id.cyan(),
                existing.meta.turn_count,
                age_str
            );
            let result = printer.confirm("Resume?", false, false);
            if result == ConfirmResult::Yes {
                printer.print(
                    Phase::Session,
                    &format!("Resumed ({} messages in context)", existing.messages.len()),
                );
                return Ok(existing);
            }
        }
    }

    // --resume with no ID: find latest
    if let Some(None) = cli.resume {
        if let Some(existing) = Session::find_for_workspace(workspace, config) {
            printer.print(
                Phase::Session,
                &format!(
                    "Resumed session {} ({} turns)",
                    existing.meta.session_id, existing.meta.turn_count
                ),
            );
            return Ok(existing);
        }
    }

    Session::create(workspace, provider_name, model, config)
}

// ── Subcommand handlers ───────────────────────────────────────────────────────

async fn handle_subcommand(
    cmd: Commands,
    workspace: &PathBuf,
    config: &Config,
    printer: &Arc<Printer>,
) -> Result<(), RalphError> {
    match cmd {
        Commands::Sessions { action } => handle_sessions(action, config),
        Commands::Checkpoint { action } => {
            handle_checkpoint(action, workspace, config, printer).await
        }
        Commands::Pr {
            title,
            body,
            draft,
            base,
        } => {
            if !ralph::tools::gh_tools::gh_available() {
                eprintln!("{} `gh` CLI not found or not authenticated. Install from https://cli.github.com and run `gh auth login`.", "[ralph]".red().bold());
                return Err(RalphError::ToolFailed {
                    tool: "ralph pr".to_string(),
                    message: "gh CLI unavailable".to_string(),
                });
            }
            match ralph::tools::gh_tools::create_pr(
                &title,
                &body,
                draft,
                base.as_deref(),
                workspace,
            )
            .await
            {
                Ok(url) => {
                    println!("{} PR created: {}", "[ralph]".white().bold(), url.cyan());
                    Ok(())
                }
                Err(e) => Err(e),
            }
        }
        Commands::Ci { branch } => {
            if !ralph::tools::gh_tools::gh_available() {
                eprintln!(
                    "{} `gh` CLI not found or not authenticated.",
                    "[ralph]".red().bold()
                );
                return Err(RalphError::ToolFailed {
                    tool: "ralph ci".to_string(),
                    message: "gh CLI unavailable".to_string(),
                });
            }
            match ralph::tools::gh_tools::get_ci_status(branch.as_deref(), workspace).await {
                Ok(output) => {
                    println!("{}", output);
                    Ok(())
                }
                Err(e) => Err(e),
            }
        }
    }
}

fn handle_sessions(action: SessionAction, config: &Config) -> Result<(), RalphError> {
    match action {
        SessionAction::List => {
            let sessions = Session::list_all(config);
            if sessions.is_empty() {
                println!("No sessions found.");
                return Ok(());
            }
            println!(
                "\n{:<24} {:<38} {:<12} {:<6} {}",
                "Session ID", "Workspace", "Provider", "Turns", "Status"
            );
            println!("{}", "-".repeat(95));
            for s in sessions {
                let ws = truncate(&s.workspace, 36);
                println!(
                    "{:<24} {:<38} {:<12} {:<6} {}",
                    s.session_id, ws, s.provider, s.turn_count, s.status
                );
            }
            println!();
        }
        SessionAction::Show { session_id } => {
            let session = Session::load(&session_id, config)?;
            let m = &session.meta;
            println!("\nSession: {}", m.session_id.cyan().bold());
            println!("  Workspace:   {}", m.workspace);
            println!("  Provider:    {} / {}", m.provider, m.model);
            println!(
                "  Created:     {}",
                m.created_at.format("%Y-%m-%d %H:%M:%S UTC")
            );
            println!(
                "  Last active: {}",
                m.last_active.format("%Y-%m-%d %H:%M:%S UTC")
            );
            println!("  Turns:       {}", m.turn_count);
            println!("  Status:      {}", m.status);
            println!("  Messages:    {}", session.messages.len());
            let cps = Checkpoint::list(&session);
            println!("  Checkpoints: {}", cps.len());
            println!();
        }
        SessionAction::Clean { older_than } => {
            Session::clean_old(config, older_than);
            println!("Cleaned sessions older than {} days.", older_than);
        }
    }
    Ok(())
}

async fn handle_checkpoint(
    action: CheckpointAction,
    workspace: &PathBuf,
    config: &Config,
    printer: &Printer,
) -> Result<(), RalphError> {
    match action {
        CheckpointAction::List { session } => {
            let sess = resolve_session(session, workspace, config)?;
            let cps = Checkpoint::list(&sess);
            if cps.is_empty() {
                println!("No checkpoints found.");
                return Ok(());
            }
            println!(
                "\nSession: {} (current)\n",
                sess.meta.session_id.cyan().bold()
            );
            println!("  {:<5} {:<30} {:<6} {}", "#", "Name", "Turn", "Timestamp");
            println!("  {}", "-".repeat(60));
            for (i, cp) in cps.iter().enumerate() {
                println!(
                    "  {:<5} {:<30} {:<6} {}",
                    i + 1,
                    cp.name,
                    cp.turn,
                    cp.created_at.format("%Y-%m-%d %H:%M:%S")
                );
            }
            println!();
        }
        CheckpointAction::Create { name, session } => {
            let sess = resolve_session(session, workspace, config)?;
            Checkpoint::create(&sess, &name, &config.checkpoints).await?;
        }
        CheckpointAction::Revert {
            name_or_number,
            session,
            files_only,
        } => {
            let mut sess = resolve_session(session, workspace, config)?;
            let cp = Checkpoint::find(&sess, &name_or_number)?;
            cp.revert_into(&mut sess, files_only, printer).await?;
        }
        CheckpointAction::Show {
            name_or_number,
            session,
        } => {
            let sess = resolve_session(session, workspace, config)?;
            let cp = Checkpoint::find(&sess, &name_or_number)?;
            let m = &cp.meta;
            println!("\nCheckpoint: {} ({})", m.name.cyan().bold(), m.id);
            println!("  Turn:     {}", m.turn);
            println!(
                "  Created:  {}",
                m.created_at.format("%Y-%m-%d %H:%M:%S UTC")
            );
            println!("  Files:    {}", m.modified_files.len());
            for f in &m.modified_files {
                println!("    - {}", f);
            }
            println!();
        }
    }
    Ok(())
}

fn resolve_session(
    session_id: Option<String>,
    workspace: &PathBuf,
    config: &Config,
) -> Result<Session, RalphError> {
    if let Some(id) = session_id {
        Session::load(&id, config)
    } else {
        Session::find_for_workspace(workspace, config).ok_or_else(|| {
            RalphError::SessionNotFound("no active session for this workspace".to_string())
        })
    }
}

// ── Interactive help ──────────────────────────────────────────────────────────

fn print_help() {
    println!();
    println!("  {} Interactive commands", "Ralph".cyan().bold());
    println!();
    println!(
        "  {:<16} {}",
        "/cp".cyan(),
        "Browse checkpoints and revert interactively"
    );
    println!("  {:<16} {}", "/dp".cyan(), "Toggle diff preview on/off");
    println!(
        "  {:<16} {}",
        "/dp on".cyan(),
        "Enable diff preview (show diff before every write)"
    );
    println!("  {:<16} {}", "/dp off".cyan(), "Disable diff preview");
    println!(
        "  {:<16} {}",
        "/pr".cyan(),
        "Toggle PR/CI tools on/off (requires gh CLI)"
    );
    println!(
        "  {:<16} {}",
        "/pr on".cyan(),
        "Enable create_pr and get_ci_status tools"
    );
    println!("  {:<16} {}", "/pr off".cyan(), "Disable PR/CI tools");
    println!(
        "  {:<16} {}",
        "/clear".cyan(),
        "Clear conversation context (keep system prompt)"
    );
    println!("  {:<16} {}", "/h, /help".cyan(), "Show this help");
    println!("  {:<16} {}", "exit, quit".cyan(), "Exit Ralph");
    println!();
}

fn handle_cp_command(session: &mut Session, printer: &Printer, config: &ralph::config::Config) {
    use colored::Colorize;
    use ralph::checkpoint::Checkpoint;
    use ralph::errors::RalphError;
    use std::io::Write;

    let checkpoints = Checkpoint::list(session);
    if checkpoints.is_empty() {
        println!(
            "  {} No checkpoints for this session.\n",
            "[ralph]".white().bold()
        );
        return;
    }

    println!(
        "\n  {} Checkpoints — session {}\n",
        "[ralph]".white().bold(),
        &session.meta.session_id[..8.min(session.meta.session_id.len())]
    );
    println!(
        "  {:<4} {:<30} {:<6} {:<6} {}",
        "#", "Name", "Turn", "Files", "When"
    );
    println!("  {}", "".repeat(58));

    for (i, cp) in checkpoints.iter().enumerate() {
        let git_tag = if cp.git_sha.is_some() { " *git" } else { "" };
        println!(
            "  {:<4} {:<30} {:<6} {:<6} {}{}",
            (i + 1).to_string().cyan(),
            cp.name,
            cp.turn,
            cp.modified_files.len(),
            age_string(cp.created_at).dimmed(),
            git_tag.dimmed(),
        );
    }
    println!(
        "  {} entries marked *git were also committed to the repo",
        "*".dimmed()
    );
    println!();
    print!("  Enter number to revert, or Enter to cancel: ");
    std::io::stdout().flush().ok();

    let mut input = String::new();
    if std::io::stdin().read_line(&mut input).is_err() {
        return;
    }
    let input = input.trim();

    if input.is_empty() {
        println!();
        return;
    }

    let num: usize = match input.parse::<usize>() {
        Ok(n) if n >= 1 && n <= checkpoints.len() => n,
        _ => {
            println!("  Invalid selection.\n");
            return;
        }
    };

    let cp_meta = &checkpoints[num - 1];
    println!(
        "\n  Checkpoint #{} \"{}\"  (turn {}, {} file(s))\n",
        num,
        cp_meta.name,
        cp_meta.turn,
        cp_meta.modified_files.len()
    );
    println!("  [f]  restore files only — conversation continues as-is");
    println!(
        "  [h]  restore files + roll back conversation to turn {}",
        cp_meta.turn
    );
    println!("  [c]  cancel");
    println!();
    print!("");
    std::io::stdout().flush().ok();

    let mut choice = String::new();
    if std::io::stdin().read_line(&mut choice).is_err() {
        return;
    }
    let choice = choice.trim().to_lowercase();

    if choice == "c" || choice.is_empty() {
        println!("  Cancelled.\n");
        return;
    }
    if choice != "f" && choice != "h" {
        println!("  Unknown option '{}'. Cancelled.\n", choice);
        return;
    }

    let files_only = choice == "f";
    match Checkpoint::find(session, &num.to_string()) {
        Ok(cp) => {
            let result = tokio::task::block_in_place(|| {
                tokio::runtime::Handle::current()
                    .block_on(cp.revert_into(session, files_only, printer))
            });
            match result {
                Ok(()) => {
                    let _ = session.flush();
                    println!();
                }
                Err(RalphError::UserAborted) => println!("  Revert cancelled.\n"),
                Err(e) => println!("  Revert failed: {}\n", e),
            }
        }
        Err(e) => println!("  Error loading checkpoint: {}\n", e),
    }

    // If full revert (files + history), also update the checkpoint list
    // using the new config so git-commit threshold is respected if needed.
}

fn age_string(ts: chrono::DateTime<chrono::Utc>) -> String {
    let mins = chrono::Utc::now().signed_duration_since(ts).num_minutes();
    if mins < 1 {
        "just now".to_string()
    } else if mins < 60 {
        format!("{}m ago", mins)
    } else {
        format!("{}h ago", mins / 60)
    }
}

// ── Helpers ────────────────────────────────────────────────────────────────────

fn require_env(env_var: &str, provider: &str) -> Result<String, RalphError> {
    std::env::var(env_var).map_err(|_| RalphError::MissingApiKey {
        env_var: env_var.to_string(),
        provider: provider.to_string(),
    })
}

fn truncate(s: &str, max: usize) -> String {
    if s.len() <= max {
        s.to_string()
    } else {
        format!("{}", &s[s.len() - (max - 1)..])
    }
}