leviath-cli 0.3.8

Command-line interface for Leviath agent framework
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
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
//! `lev setup` - the guided path from "just installed Leviath" to "ready to run
//! an agent".
//!
//! The previous version was nine `print!`/`read_line` prompts in a fixed order:
//! it asked every user for four API keys whether they had them or not, echoed
//! them in plaintext, touched about eight of `Config`'s twenty-odd fields, and
//! knew nothing about MCP servers or agent blueprints. It also ended by
//! claiming "All API keys look valid" on the strength of a `starts_with`
//! check. A fresh install came out the other side with a config file and no
//! agents.
//!
//! This is a ratatui wizard instead: pick the providers you actually use,
//! configure and verify each, set defaults and limits, install the bundled
//! blueprints, and import MCP servers already configured in other harnesses.
//!
//! ## Shape
//!
//! * [`state`] - what step we're on and what's been chosen. Pure data.
//! * [`input`] - key handling.
//! * [`render`] - drawing.
//! * [`plan`] - the decisions as plain data, and the only code that writes.
//! * [`catalog`] - which providers exist and how each is configured.
//! * [`import`] - MCP servers found in other tools.
//! * [`verify`] - proving a credential works.
//!
//! The terminal is a *front-end*, not the feature: everything it collects lands
//! in a [`plan::SetupPlan`], and `--non-interactive` builds the same struct
//! from flags. A future mobile or web host would be a third builder with
//! nothing downstream changing - which is why none of the platform-shaped parts
//! (scanning a home directory, taking over a TTY) are prescribed anywhere but
//! here.

pub mod catalog;
pub mod import;
pub mod input;
pub mod plan;
pub mod render;
pub mod state;
pub mod verify;

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

use clap::Args;
use ratatui::Terminal;
use tokio::sync::mpsc;

use crate::config::Config;
use crate::tui::{EventSource, TerminalSetup};
use crossterm::event::{Event, KeyEventKind};
use state::{VerifyReply, VerifyRequest, Wizard};
use verify::ProviderVerifier;

/// Arguments for `lev setup`.
#[derive(Args)]
pub struct SetupArgs {
    /// Run non-interactively using only flag values (useful for scripting)
    #[arg(long)]
    pub non_interactive: bool,

    /// Skip checking credentials against the provider APIs
    #[arg(long)]
    pub no_verify: bool,

    /// Anthropic API key
    #[arg(long)]
    pub anthropic_key: Option<String>,

    /// OpenAI API key
    #[arg(long)]
    pub openai_key: Option<String>,

    /// Google AI (Gemini) API key
    #[arg(long)]
    pub google_key: Option<String>,

    /// OpenRouter API key
    #[arg(long)]
    pub openrouter_key: Option<String>,

    /// Ollama base URL (default: http://localhost:11434)
    #[arg(long)]
    pub ollama_url: Option<String>,

    /// Default model override (e.g. claude-sonnet-4-6)
    #[arg(long)]
    pub default_model: Option<String>,

    /// Enable the Claude Code CLI transport (runs on your Claude subscription
    /// instead of an API key). Off unless set: the CLI adds its own context to
    /// every call, including your account email address.
    #[arg(long)]
    pub claude_code: Option<bool>,

    /// Reasoning effort for the Claude Code transport
    /// (low, medium, high, xhigh, max)
    #[arg(long)]
    pub claude_code_effort: Option<String>,

    /// Install the bundled agent blueprints without asking
    #[arg(long)]
    pub install_agents: bool,
}

/// Reads an environment variable. Injected so a test can hand the wizard a
/// fixed environment instead of the developer's real one.
pub type EnvLookup = Box<dyn Fn(&str) -> Option<String> + Send + Sync>;

/// Everything the wizard needs from the outside world, injected so tests point
/// it at tempdirs and a fake environment instead of the developer's real home.
pub struct SetupEnv {
    /// Where the config is read from and written back to.
    pub config_path: PathBuf,
    /// Where bundled blueprints are installed.
    pub agents_dir: PathBuf,
    /// Roots for the harness scan.
    pub roots: import::Roots,
    /// Reads an environment variable.
    pub env_lookup: EnvLookup,
    /// Opens a URL in a browser.
    pub opener: leviath_mcp::BrowserOpener,
}

// The real `SetupEnv` - the user's actual home, a real `std::env` lookup, and
// a real browser - is built in the binary, where those leaves belong. Nothing
// in the library reaches the real environment, so no test can either.

/// The non-interactive arm: apply flags to the config on disk and save.
///
/// Kept working byte-for-byte because it is the documented headless path and an
/// integration test spawns the real binary through it.
pub fn run_non_interactive(args: &SetupArgs, env: &SetupEnv) -> anyhow::Result<()> {
    let mut config = Config::load_from_path_public(&env.config_path).unwrap_or_default();
    apply_flags(&mut config, args);

    let agents = if args.install_agents {
        crate::bundled::plan_agent_actions(&env.agents_dir)
            .into_iter()
            // `preselect`, not `is_change`: the headless path must not overwrite
            // a blueprint the user edited, any more than the wizard does.
            .filter(|(_, action)| action.preselect())
            .map(|(agent, _)| agent)
            .collect()
    } else {
        Vec::new()
    };

    let applied = plan::apply(
        &plan::SetupPlan { config, agents },
        &env.config_path,
        &env.agents_dir,
    )?;
    report(&applied);
    Ok(())
}

/// Print what happened. Shared by both arms so the closing summary reads the
/// same however setup was driven.
fn report(applied: &plan::Applied) {
    println!("Config saved to {}", applied.config_path.display());
    if !applied.agents_installed.is_empty() {
        println!(
            "Installed {} agent(s): {}",
            applied.agents_installed.len(),
            applied.agents_installed.join(", ")
        );
    }
    for warning in &applied.warnings {
        println!("  Warning: {warning}");
    }
}

/// Copy the flag values onto a config.
fn apply_flags(config: &mut Config, args: &SetupArgs) {
    if let Some(ref k) = args.anthropic_key {
        config.providers.anthropic_api_key = Some(k.clone());
    }
    if let Some(ref k) = args.openai_key {
        config.providers.openai_api_key = Some(k.clone());
    }
    if let Some(ref k) = args.google_key {
        config.providers.google_api_key = Some(k.clone());
    }
    if let Some(ref k) = args.openrouter_key {
        config.openrouter_api_key = Some(k.clone());
    }
    if let Some(ref u) = args.ollama_url {
        config.ollama_base_url = Some(u.clone());
    }
    if let Some(ref m) = args.default_model {
        config.default_model = Some(m.clone());
    }
    if let Some(enabled) = args.claude_code {
        config.providers.claude_code_enabled = enabled;
    }
    if let Some(ref e) = args.claude_code_effort {
        config.providers.claude_code_effort = Some(e.clone());
    }
    retarget_default_provider(config);
}

/// The providers this config holds a credential for, best first.
///
/// Ollama sits last on purpose. It needs no key, so a config that merely
/// mentions it is not a statement of preference, and putting it first would
/// make it the default on a machine that never installed it.
fn configured_providers(config: &Config) -> Vec<&'static str> {
    [
        ("anthropic", config.providers.anthropic_api_key.is_some()),
        ("openai", config.providers.openai_api_key.is_some()),
        ("google", config.providers.google_api_key.is_some()),
        ("openrouter", config.openrouter_api_key.is_some()),
        ("claude-code", config.providers.claude_code_enabled),
        ("ollama", config.ollama_base_url.is_some()),
    ]
    .into_iter()
    .filter(|(_, configured)| *configured)
    .map(|(id, _)| id)
    .collect()
}

/// Point `default_provider` at a provider this config can actually reach.
///
/// It defaults to `anthropic` and nothing in non-interactive mode ever moved
/// it, so `lev setup --non-interactive --openrouter-key ...` produced a config
/// whose very next `lev doctor` said it "resolved to 'anthropic', which is not
/// configured". The install was fine; the default was pointing at a provider
/// the user had not asked for.
///
/// Only ever moves a default that is unreachable, so a deliberate choice
/// already in the file survives.
fn retarget_default_provider(config: &mut Config) {
    let configured = configured_providers(config);
    if configured.contains(&config.default_provider.as_str()) {
        return;
    }
    if let Some(first) = configured.first() {
        config.default_provider = (*first).to_string();
    }
}

/// Build a wizard against `env`.
///
/// The base config comes from reading the *file*, deliberately not from
/// `Config::load()`: `load` folds `$ANTHROPIC_API_KEY` and friends in, and the
/// old wizard re-serialized the whole struct - quietly writing into
/// `~/.leviath/config.toml` a key the user had chosen to keep in their
/// environment. Those are tracked separately and shown as such.
pub fn build_wizard(env: &SetupEnv) -> Wizard {
    let base = Config::load_from_path_public(&env.config_path).unwrap_or_default();
    let (candidates, errors) = state::candidates_from_scans(import::scan(&env.roots));
    Wizard::new(
        base,
        &env.env_lookup,
        candidates,
        errors,
        &env.agents_dir,
        env.opener.clone(),
    )
}

/// Answer verification requests until the wizard drops its sender.
///
/// Sequential rather than fanned out: the answers land on separate provider
/// cards a user reads one at a time, and firing six requests at once buys
/// nothing but a chance to trip a rate limiter with what is supposed to be a
/// harmless check.
pub async fn verification_loop<V: ProviderVerifier>(
    verifier: V,
    mut requests: mpsc::UnboundedReceiver<VerifyRequest>,
    replies: mpsc::UnboundedSender<VerifyReply>,
) {
    while let Some(request) = requests.recv().await {
        let outcome = verifier.verify(&request.creds).await;
        // A closed receiver means the wizard exited; nothing left to report to.
        if replies
            .send(VerifyReply {
                provider_id: request.provider_id,
                outcome,
            })
            .is_err()
        {
            return;
        }
    }
}

/// The wizard's draw/input loop.
///
/// Generic over the backend and event source so it runs against a
/// `TestBackend` and canned keys; the real crossterm bindings live in the
/// binary. Returns the plan to apply, or `None` if the user quit.
pub async fn run_wizard_loop<B: ratatui::backend::Backend>(
    wizard: &mut Wizard,
    terminal: &mut Terminal<B>,
    events: &mut impl EventSource,
    tick_rate: Duration,
) -> anyhow::Result<Option<plan::SetupPlan>> {
    loop {
        wizard.ticks += 1;
        wizard.drain_verifications();
        // The area is taken from the frame that was actually drawn, so a click
        // resolves against the layout the user was looking at rather than
        // against a size asked for separately afterwards.
        let mut area = ratatui::layout::Rect::default();
        terminal
            .draw(|frame| {
                area = frame.area();
                render::draw(frame, wizard);
            })
            // ratatui 0.30 made the backend error an associated type with no
            // Send/Sync guarantee, so convert by message rather than by `?`.
            .map_err(|e| anyhow::anyhow!("terminal draw failed: {e}"))?;

        match events.poll_event(tick_rate)? {
            Some(Event::Key(key))
                if key.kind == KeyEventKind::Press
                    && wizard.handle_key(key) == input::Action::Save =>
            {
                wizard.finished = true;
            }
            Some(Event::Mouse(mouse))
                if wizard.handle_mouse(mouse, area) == input::Action::Save =>
            {
                wizard.finished = true;
            }
            _ => {}
        }

        if wizard.finished {
            return Ok(Some(wizard.build_plan()));
        }
        if wizard.should_quit {
            return Ok(None);
        }
    }
}

/// Set up the terminal, run the loop, tear the terminal down, then apply.
///
/// The teardown happens before anything is printed: writing a summary while the
/// alternate screen is still up puts it somewhere the user will never see.
pub async fn execute_core<S: TerminalSetup, E: EventSource>(
    wizard: &mut Wizard,
    env: &SetupEnv,
    setup: &mut S,
    events: &mut E,
) -> anyhow::Result<()> {
    setup.enable()?;
    let mut terminal = setup.create_terminal()?;
    let result = run_wizard_loop(wizard, &mut terminal, events, Duration::from_millis(120)).await;
    setup.disable();

    match result? {
        Some(plan) => {
            let applied = plan::apply(&plan, &env.config_path, &env.agents_dir)?;
            report(&applied);
            print_next_steps(&applied);
        }
        None => println!("Setup cancelled. Nothing was written."),
    }
    Ok(())
}

/// What to do now that setup is done.
fn print_next_steps(applied: &plan::Applied) {
    println!();
    match applied.agents_installed.first() {
        Some(agent) => println!("Try it:  lev run {agent} --task \"...\""),
        None => println!("Install an agent with `lev setup`, then `lev run <agent>`."),
    }
}

/// `lev setup`: the flags path, or the wizard.
///
/// `is_terminal` is injected because the answer is a property of the real
/// process's stdout, and a wizard that starts on a pipe would take over a
/// terminal that isn't there.
pub async fn execute_with<S: TerminalSetup, E: EventSource>(
    args: &SetupArgs,
    env: &SetupEnv,
    setup: &mut S,
    events: &mut E,
    is_terminal: bool,
) -> anyhow::Result<()> {
    if args.non_interactive {
        return run_non_interactive(args, env);
    }
    if !is_terminal {
        anyhow::bail!(
            "lev setup needs a terminal. For scripted use:\n  \
             lev setup --non-interactive --anthropic-key sk-ant-... --install-agents"
        );
    }
    let mut wizard = build_wizard(env);
    execute_core(&mut wizard, env, setup, events).await
}

/// Resolve `~/.leviath/agents` for the real environment.
pub fn real_agents_dir(home: Option<&Path>) -> PathBuf {
    home.unwrap_or(Path::new(""))
        .join(".leviath")
        .join("agents")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bundled::BUNDLED_AGENTS;
    use crate::tui::{TestEventSource, TestSetup, key, key_with, test_terminal};
    use crossterm::event::{KeyCode, KeyModifiers};

    /// Args with everything off, so each test names only what it exercises.
    fn args() -> SetupArgs {
        SetupArgs {
            non_interactive: false,
            no_verify: false,
            anthropic_key: None,
            openai_key: None,
            google_key: None,
            openrouter_key: None,
            ollama_url: None,
            default_model: None,
            claude_code: None,
            claude_code_effort: None,
            install_agents: false,
        }
    }

    /// A `SetupEnv` rooted entirely in a tempdir, with a browser opener that
    /// records instead of launching and an environment that is simply empty.
    fn env_in(dir: &Path) -> SetupEnv {
        SetupEnv {
            config_path: dir.join("config.toml"),
            agents_dir: dir.join("agents"),
            roots: import::Roots {
                home: dir.join("home"),
                os_config: dir.join("os-config"),
                xdg_config: dir.join("home").join(".config"),
                cwd: dir.join("cwd"),
            },
            env_lookup: Box::new(|_| None),
            opener: std::sync::Arc::new(|_| true),
        }
    }

    // ─── default_provider retargeting ───────────────────────────────────────

    #[test]
    fn a_single_non_anthropic_key_becomes_the_default_provider() {
        // The bug this exists for: setup succeeded, then `lev doctor` said the
        // install resolved to a provider the user had never configured.
        let mut config = Config::default();
        assert_eq!(config.default_provider, "anthropic");
        apply_flags(
            &mut config,
            &SetupArgs {
                openrouter_key: Some("sk-or-test".to_string()),
                ..args()
            },
        );
        assert_eq!(config.default_provider, "openrouter");
    }

    #[test]
    fn a_reachable_default_provider_is_left_alone() {
        let mut config = Config::default();
        apply_flags(
            &mut config,
            &SetupArgs {
                anthropic_key: Some("sk-ant-test".to_string()),
                openrouter_key: Some("sk-or-test".to_string()),
                ..args()
            },
        );
        assert_eq!(config.default_provider, "anthropic");
    }

    #[test]
    fn a_deliberate_default_provider_survives() {
        let mut config = Config {
            default_provider: "google".to_string(),
            ..Config::default()
        };
        apply_flags(
            &mut config,
            &SetupArgs {
                google_key: Some("AIza-test".to_string()),
                openrouter_key: Some("sk-or-test".to_string()),
                ..args()
            },
        );
        assert_eq!(config.default_provider, "google");
    }

    #[test]
    fn configuring_nothing_leaves_the_default_provider_untouched() {
        // Nothing to retarget to, so moving it would only make it wrong
        // differently.
        let mut config = Config::default();
        apply_flags(&mut config, &args());
        assert_eq!(config.default_provider, "anthropic");
    }

    #[test]
    fn ollama_is_the_last_provider_considered() {
        // It needs no key, so it is the one most likely to be present by
        // accident. Anything the user actually holds a credential for wins.
        let mut config = Config::default();
        apply_flags(
            &mut config,
            &SetupArgs {
                ollama_url: Some("http://localhost:11434".to_string()),
                google_key: Some("AIza-test".to_string()),
                ..args()
            },
        );
        assert_eq!(config.default_provider, "google");

        let mut ollama_only = Config::default();
        apply_flags(
            &mut ollama_only,
            &SetupArgs {
                ollama_url: Some("http://localhost:11434".to_string()),
                ..args()
            },
        );
        assert_eq!(ollama_only.default_provider, "ollama");
    }

    #[test]
    fn the_claude_code_transport_counts_as_a_configured_provider() {
        let mut config = Config::default();
        apply_flags(
            &mut config,
            &SetupArgs {
                claude_code: Some(true),
                ..args()
            },
        );
        assert_eq!(config.default_provider, "claude-code");
    }

    // ─── the non-interactive path ───────────────────────────────────────────

    #[test]
    fn flags_are_written_to_the_config() {
        let dir = tempfile::tempdir().unwrap();
        let env = env_in(dir.path());
        let args = SetupArgs {
            non_interactive: true,
            anthropic_key: Some("sk-ant-x".to_string()),
            openai_key: Some("sk-oai".to_string()),
            google_key: Some("goog".to_string()),
            openrouter_key: Some("sk-or".to_string()),
            ollama_url: Some("http://box:11434".to_string()),
            default_model: Some("m".to_string()),
            claude_code: Some(true),
            claude_code_effort: Some("xhigh".to_string()),
            ..args()
        };

        run_non_interactive(&args, &env).unwrap();

        let written = Config::load_from_path_public(&env.config_path).unwrap();
        assert_eq!(
            written.providers.anthropic_api_key.as_deref(),
            Some("sk-ant-x")
        );
        assert_eq!(written.providers.openai_api_key.as_deref(), Some("sk-oai"));
        assert_eq!(written.providers.google_api_key.as_deref(), Some("goog"));
        assert_eq!(written.openrouter_api_key.as_deref(), Some("sk-or"));
        assert_eq!(written.ollama_base_url.as_deref(), Some("http://box:11434"));
        assert_eq!(written.default_model.as_deref(), Some("m"));
        assert!(written.providers.claude_code_enabled);
        assert_eq!(
            written.providers.claude_code_effort.as_deref(),
            Some("xhigh")
        );
    }

    #[test]
    fn the_non_interactive_path_installs_agents_only_when_asked() {
        let dir = tempfile::tempdir().unwrap();
        let env = env_in(dir.path());

        run_non_interactive(&args(), &env).unwrap();
        assert!(!env.agents_dir.exists(), "nothing was asked for");

        run_non_interactive(
            &SetupArgs {
                install_agents: true,
                ..args()
            },
            &env,
        )
        .unwrap();
        assert!(
            env.agents_dir.join(BUNDLED_AGENTS[0].name).exists(),
            "every bundled blueprint should land"
        );

        // Second time round there is nothing left to do.
        run_non_interactive(
            &SetupArgs {
                install_agents: true,
                ..args()
            },
            &env,
        )
        .unwrap();
        assert!(env.agents_dir.join(BUNDLED_AGENTS[0].name).exists());
    }

    #[test]
    fn the_non_interactive_path_keeps_settings_it_was_not_given() {
        let dir = tempfile::tempdir().unwrap();
        let env = env_in(dir.path());
        run_non_interactive(
            &SetupArgs {
                anthropic_key: Some("sk-ant-first".to_string()),
                ..args()
            },
            &env,
        )
        .unwrap();

        run_non_interactive(
            &SetupArgs {
                openai_key: Some("sk-oai".to_string()),
                ..args()
            },
            &env,
        )
        .unwrap();

        let written = Config::load_from_path_public(&env.config_path).unwrap();
        assert_eq!(
            written.providers.anthropic_api_key.as_deref(),
            Some("sk-ant-first")
        );
        assert_eq!(written.providers.openai_api_key.as_deref(), Some("sk-oai"));
    }

    #[test]
    fn a_config_that_cannot_be_written_is_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let blocked = dir.path().join("not-a-dir");
        std::fs::write(&blocked, "").unwrap();
        let mut env = env_in(dir.path());
        env.config_path = blocked.join("config.toml");

        assert!(run_non_interactive(&args(), &env).is_err());
    }

    // ─── building the wizard from the environment ───────────────────────────

    #[test]
    fn the_wizard_reads_the_config_file_and_scans_for_harnesses() {
        let dir = tempfile::tempdir().unwrap();
        let env = env_in(dir.path());
        std::fs::create_dir_all(&env.roots.home).unwrap();
        std::fs::write(
            env.roots.home.join(".claude.json"),
            r#"{"mcpServers":{"fs":{"command":"npx"}}}"#,
        )
        .unwrap();
        run_non_interactive(
            &SetupArgs {
                anthropic_key: Some("sk-ant-stored".to_string()),
                ..args()
            },
            &env,
        )
        .unwrap();

        let wizard = build_wizard(&env);

        assert_eq!(
            wizard.base.providers.anthropic_api_key.as_deref(),
            Some("sk-ant-stored")
        );
        assert_eq!(wizard.mcp.len(), 1);
        assert_eq!(wizard.mcp[0].candidate.config.name, "fs");
    }

    #[test]
    fn a_missing_config_file_starts_from_defaults() {
        let dir = tempfile::tempdir().unwrap();

        let wizard = build_wizard(&env_in(dir.path()));

        assert_eq!(
            wizard.base.default_provider,
            Config::default().default_provider
        );
    }

    // ─── the verification background loop ───────────────────────────────────

    #[tokio::test]
    async fn the_verification_loop_answers_every_request_then_stops() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = build_wizard(&env_in(dir.path()));
        let (requests, replies) = wizard.take_verify_ends().expect("first take");
        wizard.providers[0].selected = true;
        wizard.providers[0].value = "sk-ant".to_string();
        wizard.request_verification(0);

        let handle = tokio::spawn(verification_loop(verify::SkipVerifier, requests, replies));
        // Dropping the wizard's sender ends the loop.
        let sender = wizard.verify_tx.clone();
        drop(sender);

        // Give the loop a turn, then confirm the answer arrived.
        for _ in 0..50 {
            wizard.drain_verifications();
            if !wizard.providers[0].checking {
                break;
            }
            tokio::time::sleep(Duration::from_millis(2)).await;
        }
        assert!(!wizard.providers[0].checking);
        assert_eq!(wizard.providers[0].outcome, verify::Outcome::Skipped);

        drop(wizard);
        handle.await.expect("the loop exits cleanly");
    }

    #[tokio::test]
    async fn the_verification_loop_stops_when_nobody_is_listening() {
        // The wizard exited mid-check; there is nothing left to report to.
        let (request_tx, request_rx) = mpsc::unbounded_channel();
        let (reply_tx, reply_rx) = mpsc::unbounded_channel::<VerifyReply>();
        request_tx
            .send(VerifyRequest {
                provider_id: "anthropic".to_string(),
                creds: leviath_runtime::provider_creds::ProviderCreds {
                    name: "anthropic".to_string(),
                    api_key: Some("sk-ant".to_string()),
                    base_url: None,
                    model_capabilities: std::collections::HashMap::new(),
                    request_timeout_secs: Some(1),
                    rate_limit: None,
                    options: std::collections::HashMap::new(),
                },
            })
            .unwrap();
        drop(reply_rx);

        verification_loop(verify::SkipVerifier, request_rx, reply_tx).await;
    }

    // ─── the wizard loop ────────────────────────────────────────────────────

    #[tokio::test]
    async fn quitting_returns_no_plan() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = build_wizard(&env_in(dir.path()));
        let mut terminal = test_terminal();
        let mut events = TestEventSource::new(vec![key(KeyCode::Char('q'))]);

        let plan = run_wizard_loop(
            &mut wizard,
            &mut terminal,
            &mut events,
            Duration::from_millis(1),
        )
        .await
        .unwrap();

        assert!(plan.is_none());
    }

    #[tokio::test]
    async fn saving_returns_the_plan_the_wizard_describes() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = build_wizard(&env_in(dir.path()));
        let mut terminal = test_terminal();
        // A tick with no input, then save - covering the poll-timeout path.
        let mut events = TestEventSource::new_with_nones(vec![
            None,
            Some(key_with(KeyCode::Char('s'), KeyModifiers::CONTROL)),
        ]);

        let plan = run_wizard_loop(
            &mut wizard,
            &mut terminal,
            &mut events,
            Duration::from_millis(1),
        )
        .await
        .unwrap()
        .expect("a plan was produced");

        assert_eq!(plan.agents.len(), BUNDLED_AGENTS.len());
    }

    #[tokio::test]
    async fn non_press_and_non_key_events_are_ignored() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = build_wizard(&env_in(dir.path()));
        let mut terminal = test_terminal();
        let release = crossterm::event::Event::Key(crossterm::event::KeyEvent::new_with_kind(
            KeyCode::Char('q'),
            KeyModifiers::empty(),
            KeyEventKind::Release,
        ));
        let mut events = TestEventSource::new(vec![
            release,
            crossterm::event::Event::FocusGained,
            crossterm::event::Event::Resize(80, 24),
            key(KeyCode::Char('q')),
        ]);

        let plan = run_wizard_loop(
            &mut wizard,
            &mut terminal,
            &mut events,
            Duration::from_millis(1),
        )
        .await
        .unwrap();

        assert!(plan.is_none(), "only the real press quit");
    }

    /// A click reaches the wizard through the loop, against the size the
    /// terminal reports, and can finish the run the same way a key can.
    #[tokio::test]
    async fn a_click_is_routed_with_the_window_it_was_made_in() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = build_wizard(&env_in(dir.path()));
        wizard.enter(state::Step::Providers);
        let mut terminal = test_terminal();
        let size = terminal.size().expect("the test backend has a size");
        let area = ratatui::layout::Rect::new(0, 0, size.width, size.height);
        // The row the click has to land on is asked for, not assumed, so the
        // test does not encode a layout.
        let row = (0..area.height)
            .find(|y| render::row_at(area, &wizard, 4, *y) == Some(1))
            .expect("the second provider is on screen");

        let mut events = TestEventSource::new(vec![
            crossterm::event::Event::Mouse(crossterm::event::MouseEvent {
                kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
                column: 4,
                row,
                modifiers: KeyModifiers::empty(),
            }),
            key_with(KeyCode::Char('s'), KeyModifiers::CONTROL),
        ]);

        let plan = run_wizard_loop(
            &mut wizard,
            &mut terminal,
            &mut events,
            Duration::from_millis(1),
        )
        .await
        .unwrap()
        .expect("ctrl-s finished it");

        assert!(
            wizard.providers[1].selected,
            "the click selected what it landed on"
        );
        assert!(!plan.agents.is_empty());
    }

    /// The last button finishes the run, whether it is pressed or clicked.
    #[tokio::test]
    async fn clicking_apply_and_finish_ends_the_wizard() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = build_wizard(&env_in(dir.path()));
        wizard.enter(state::Step::Review);
        let mut terminal = test_terminal();
        let size = terminal.size().expect("the test backend has a size");
        let area = ratatui::layout::Rect::new(0, 0, size.width, size.height);
        let button = wizard.nav_rows() - 1;
        let row = (0..area.height)
            .find(|y| render::row_at(area, &wizard, 4, *y) == Some(button))
            .expect("the button is on screen");

        let mut events = TestEventSource::new(vec![crossterm::event::Event::Mouse(
            crossterm::event::MouseEvent {
                kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
                column: 4,
                row,
                modifiers: KeyModifiers::empty(),
            },
        )]);

        let plan = run_wizard_loop(
            &mut wizard,
            &mut terminal,
            &mut events,
            Duration::from_millis(1),
        )
        .await
        .unwrap();

        assert!(plan.is_some(), "the click applied the plan");
    }

    #[tokio::test]
    async fn a_draw_failure_propagates() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = build_wizard(&env_in(dir.path()));
        let mut terminal =
            ratatui::Terminal::new(crate::tui::TestBackendHarness::failing(80, 24)).unwrap();
        let mut events = TestEventSource::new(vec![]);

        let result = run_wizard_loop(
            &mut wizard,
            &mut terminal,
            &mut events,
            Duration::from_millis(1),
        )
        .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn an_event_source_failure_propagates() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = build_wizard(&env_in(dir.path()));
        let mut terminal = test_terminal();
        let mut events = TestEventSource::failing();

        let result = run_wizard_loop(
            &mut wizard,
            &mut terminal,
            &mut events,
            Duration::from_millis(1),
        )
        .await;

        assert!(result.is_err());
    }

    // ─── the composed command ───────────────────────────────────────────────

    #[tokio::test]
    async fn saving_writes_the_config_and_installs_the_agents() {
        let dir = tempfile::tempdir().unwrap();
        let env = env_in(dir.path());
        let mut wizard = build_wizard(&env);
        let mut setup = TestSetup::new();
        let mut events =
            TestEventSource::new(vec![key_with(KeyCode::Char('s'), KeyModifiers::CONTROL)]);

        execute_core(&mut wizard, &env, &mut setup, &mut events)
            .await
            .unwrap();

        assert!(env.config_path.exists());
        assert!(env.agents_dir.join(BUNDLED_AGENTS[0].name).exists());
    }

    #[tokio::test]
    async fn quitting_writes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let env = env_in(dir.path());
        let mut wizard = build_wizard(&env);
        let mut setup = TestSetup::new();
        let mut events = TestEventSource::new(vec![key(KeyCode::Char('q'))]);

        execute_core(&mut wizard, &env, &mut setup, &mut events)
            .await
            .unwrap();

        assert!(
            !env.config_path.exists(),
            "nothing should have been written"
        );
        assert!(!env.agents_dir.exists());
    }

    #[tokio::test]
    async fn a_terminal_that_will_not_start_is_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let env = env_in(dir.path());
        let mut wizard = build_wizard(&env);
        let mut events = TestEventSource::new(vec![]);

        let mut enable_fails = TestSetup {
            enable_should_fail: true,
            create_should_fail: false,
            draw_should_fail: false,
        };
        assert!(
            execute_core(&mut wizard, &env, &mut enable_fails, &mut events)
                .await
                .is_err()
        );

        let mut create_fails = TestSetup {
            enable_should_fail: false,
            create_should_fail: true,
            draw_should_fail: false,
        };
        assert!(
            execute_core(&mut wizard, &env, &mut create_fails, &mut events)
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn a_loop_failure_is_surfaced_after_the_terminal_is_restored() {
        let dir = tempfile::tempdir().unwrap();
        let env = env_in(dir.path());
        let mut wizard = build_wizard(&env);
        let mut setup = TestSetup::new();
        let mut events = TestEventSource::failing();

        let result = execute_core(&mut wizard, &env, &mut setup, &mut events).await;

        assert!(result.is_err());
        assert!(!env.config_path.exists());
    }

    #[tokio::test]
    async fn a_write_failure_after_the_wizard_is_surfaced() {
        // The terminal must already be restored, or the error would be printed
        // onto an alternate screen the user never sees again.
        let dir = tempfile::tempdir().unwrap();
        let mut env = env_in(dir.path());
        let blocked = dir.path().join("not-a-dir");
        std::fs::write(&blocked, "").unwrap();
        let mut wizard = build_wizard(&env);
        env.config_path = blocked.join("config.toml");
        let mut setup = TestSetup::new();
        let mut events =
            TestEventSource::new(vec![key_with(KeyCode::Char('s'), KeyModifiers::CONTROL)]);

        let result = execute_core(&mut wizard, &env, &mut setup, &mut events).await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn execute_with_routes_to_the_flags_path() {
        let dir = tempfile::tempdir().unwrap();
        let env = env_in(dir.path());
        let mut setup = TestSetup::new();
        let mut events = TestEventSource::new(vec![]);

        execute_with(
            &SetupArgs {
                non_interactive: true,
                anthropic_key: Some("sk-ant-x".to_string()),
                ..args()
            },
            &env,
            &mut setup,
            &mut events,
            false,
        )
        .await
        .unwrap();

        let written = Config::load_from_path_public(&env.config_path).unwrap();
        assert_eq!(
            written.providers.anthropic_api_key.as_deref(),
            Some("sk-ant-x")
        );
    }

    #[tokio::test]
    async fn without_a_terminal_the_wizard_refuses_and_says_what_to_run_instead() {
        // Starting ratatui on a pipe would take over a terminal that isn't
        // there.
        let dir = tempfile::tempdir().unwrap();
        let env = env_in(dir.path());
        let mut setup = TestSetup::new();
        let mut events = TestEventSource::new(vec![]);

        let error = execute_with(&args(), &env, &mut setup, &mut events, false)
            .await
            .expect_err("a pipe is not a terminal");

        let message = error.to_string();
        assert!(message.contains("needs a terminal"), "{message}");
        assert!(message.contains("--non-interactive"), "{message}");
        assert!(!env.config_path.exists());
    }

    #[tokio::test]
    async fn with_a_terminal_execute_with_runs_the_wizard() {
        let dir = tempfile::tempdir().unwrap();
        let env = env_in(dir.path());
        let mut setup = TestSetup::new();
        let mut events =
            TestEventSource::new(vec![key_with(KeyCode::Char('s'), KeyModifiers::CONTROL)]);

        execute_with(&args(), &env, &mut setup, &mut events, true)
            .await
            .unwrap();

        assert!(env.config_path.exists());
    }

    // ─── reporting ──────────────────────────────────────────────────────────

    #[test]
    fn the_summary_covers_agents_warnings_and_the_empty_case() {
        report(&plan::Applied {
            config_path: PathBuf::from("/tmp/config.toml"),
            agents_installed: vec!["coder".to_string()],
            warnings: vec!["could not install x".to_string()],
        });
        report(&plan::Applied {
            config_path: PathBuf::from("/tmp/config.toml"),
            agents_installed: Vec::new(),
            warnings: Vec::new(),
        });
    }

    #[test]
    fn the_next_step_names_an_installed_agent_when_there_is_one() {
        print_next_steps(&plan::Applied {
            config_path: PathBuf::from("/tmp/config.toml"),
            agents_installed: vec!["coder".to_string()],
            warnings: Vec::new(),
        });
        print_next_steps(&plan::Applied {
            config_path: PathBuf::from("/tmp/config.toml"),
            agents_installed: Vec::new(),
            warnings: Vec::new(),
        });
    }

    #[test]
    fn the_real_agents_directory_sits_under_the_leviath_home() {
        assert_eq!(
            real_agents_dir(Some(Path::new("/home/u"))),
            PathBuf::from("/home/u/.leviath/agents")
        );
        // No home directory resolvable: a relative path, not a panic.
        assert_eq!(real_agents_dir(None), PathBuf::from(".leviath/agents"));
    }
}