leviath-cli 0.1.2

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
//! `lev list` - List available agents and blueprints

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

use super::resolve_cwd;
use crate::config::Config;
use leviath_core::manifest::parse_manifest;

#[derive(Args)]
pub struct ListArgs {
    /// Filter by type (agents, blueprints, all)
    #[arg(short, long, default_value = "all")]
    pub filter: String,
}

/// Info parsed from an agent manifest for display.
struct AgentInfo {
    name: String,
    version: String,
    description: String,
    /// The agent's `[read_paths]` grant status under the active config, when it
    /// declares any. Shown because a declaration nothing grants is inert, and
    /// the listing is where someone looks before running an agent they just
    /// installed or copied over from another machine.
    read_paths: Option<String>,
}

fn read_agent_info(manifest_path: &Path, config: &Config, cwd: &Path) -> Option<AgentInfo> {
    let content = fs::read_to_string(manifest_path).ok()?;
    let blueprint = parse_manifest(&content).ok()?;
    let read_paths = read_path_summary(&blueprint, config, cwd);
    Some(AgentInfo {
        name: blueprint.name,
        version: blueprint.version,
        description: blueprint.description,
        read_paths,
    })
}

/// The one-line `[read_paths]` verdict for an agent, or `None` when it declares
/// none. A config whose own grant list is broken says so here rather than
/// staying silent; `lev validate` and the spawn error carry the detail.
fn read_path_summary(
    blueprint: &leviath_core::Blueprint,
    config: &Config,
    cwd: &Path,
) -> Option<String> {
    match crate::read_path_report::build(blueprint, config, cwd)? {
        Ok(report) if report.has_ungranted() => Some(format!(
            "read_paths: {} - `lev validate` shows which",
            report.summary()
        )),
        Ok(report) => Some(format!("read_paths: {}", report.summary())),
        Err(e) => Some(format!("read_paths: {e}")),
    }
}

fn scan_directory_for_agents(dir: &Path, config: &Config, cwd: &Path) -> Vec<(PathBuf, AgentInfo)> {
    let mut agents = Vec::new();
    if !dir.exists() {
        return agents;
    }

    // Check if this directory itself has an agent.leviath
    let direct_manifest = dir.join("agent.leviath");
    if direct_manifest.exists()
        && let Some(info) = read_agent_info(&direct_manifest, config, cwd)
    {
        agents.push((dir.to_path_buf(), info));
    }

    // Check subdirectories
    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                let manifest_path = path.join("agent.leviath");
                if manifest_path.exists()
                    && let Some(info) = read_agent_info(&manifest_path, config, cwd)
                {
                    agents.push((path, info));
                }
            }
        }
    }

    agents
}

/// One agent's listing: the name line every section shares, plus the
/// `[read_paths]` line when there is one.
fn print_agent(info: &AgentInfo) {
    let desc = if info.description.is_empty() {
        String::new()
    } else {
        format!(" - {}", info.description)
    };
    println!("  {} (v{}){}", info.name, info.version, desc);
    if let Some(read_paths) = &info.read_paths {
        println!("      {read_paths}");
    }
}

pub async fn execute(_args: ListArgs) -> anyhow::Result<()> {
    // Propagate, don't default: a config that exists but doesn't parse would
    // silently list from the default `agent_paths`, hiding the user's own
    // agent directories with no hint why (a missing file loads as defaults).
    let config = Config::load()?;
    let agents_dir = get_agents_dir()?;
    let cwd = resolve_cwd().unwrap_or_default();
    let exe_dir = std::env::current_exe()
        .ok()
        .and_then(|p| p.parent().map(|p| p.to_path_buf()));

    print_agent_listing(&agents_dir, &cwd, exe_dir.as_deref(), &config)
}

/// Core `lev list` logic, parameterized by every real-environment source it
/// reads from so it can be tested against tempdirs instead of the real
/// home directory / CWD / executable location / config.
fn print_agent_listing(
    agents_dir: &Path,
    cwd: &Path,
    exe_dir: Option<&Path>,
    config: &Config,
) -> anyhow::Result<()> {
    // Tracks whether the user has any agent they can actually *run*. The
    // bundled catalog deliberately does not count: it is always non-empty, and
    // treating it as "you have agents" would suppress the get-started guidance
    // for exactly the person who needs it - someone with a fresh install and
    // nothing installed yet.
    let mut found_runnable = false;

    // 1. Installed agents (~/.leviath/agents/)
    let installed = scan_directory_for_agents(agents_dir, config, cwd);
    if !installed.is_empty() {
        found_runnable = true;
        println!("Installed agents (~/.leviath/agents/):");
        for (_path, info) in &installed {
            print_agent(info);
        }
        println!();
    }

    // 2. Local (current directory)
    let local_manifest = cwd.join("agent.leviath");
    if local_manifest.exists()
        && let Some(info) = read_agent_info(&local_manifest, config, cwd)
    {
        found_runnable = true;
        println!("Local (current directory):");
        print_agent(&info);
        println!();
    }

    // 3. Config's agent_paths directories
    let mut config_agents = Vec::new();
    for agent_path in &config.agent_paths {
        let found = scan_directory_for_agents(agent_path, config, cwd);
        config_agents.extend(found);
    }
    if !config_agents.is_empty() {
        found_runnable = true;
        println!("From configured paths:");
        for (_path, info) in &config_agents {
            print_agent(info);
        }
        println!();
    }

    // 4. Bundled agents - the blueprints embedded in this binary.
    //
    // Reports the embedded catalog, which is what `lev setup` installs from.
    // Scanning only `<exe_dir>/agents` would leave this section blank outside a
    // git checkout - a directory no real install has. The on-disk scan stays as
    // a second source so a checkout or a packaging layout that *does* ship an
    // `agents/` dir next to the binary still shows up.
    let mut builtin_names: Vec<String> = crate::bundled::BUNDLED_AGENTS
        .iter()
        .map(|a| format!("{} (v{})", a.name, a.version))
        .collect();
    if let Some(exe_dir) = exe_dir {
        for (_path, info) in scan_directory_for_agents(&exe_dir.join("agents"), config, cwd) {
            let entry = format!("{} (v{})", info.name, info.version);
            if !builtin_names.contains(&entry) {
                builtin_names.push(entry);
            }
        }
    }
    // No emptiness guard: the embedded catalog is always populated (a build
    // that found no blueprints fails `bundled`'s own invariant test), so an
    // `if !builtin_names.is_empty()` here would be a branch that can never be
    // false - unreachable code dressed up as a handled case.
    println!("Bundled agents (install with `lev setup`):");
    println!("  {}", builtin_names.join(", "));
    println!();

    if !found_runnable {
        println!("No agents installed yet.");
        println!();
        println!("To install the bundled agents:");
        println!("  lev setup");
        println!();
        println!("To create your own:");
        println!("  lev create my-agent");
    }

    Ok(())
}

/// Core `get_agents_dir` logic, parameterized by the home directory so the
/// "could not determine home directory" error path can be unit tested
/// without depending on the real environment.
fn get_agents_dir_or_error(dir: Option<PathBuf>) -> anyhow::Result<PathBuf> {
    dir.ok_or(anyhow::anyhow!("Could not determine home directory"))
}

/// Resolve `~/.leviath/agents`, the directory `lev list` scans for installed
/// agents.
///
/// A thin wrapper over [`get_agents_dir_or_error`] supplying the real
/// resolved directory. The `#[cfg(test)]` guard below only lets tests force the
/// "no home directory" error arm of `execute()` deterministically - the real
/// the shared resolver can't be made to return `None` in any environment a
/// test may safely create (on macOS `dirs::home_dir()` falls back to a
/// passwd-database lookup independent of `$HOME`). It does NOT hide the real
/// body from coverage: with the toggle off, `get_agents_dir_or_error(
/// leviath_core::paths::agents_dir())` runs (and is measured) in every ordinary test, and
/// only computes a `PathBuf` (no filesystem writes). The `None` arm of
/// `get_agents_dir_or_error` is covered directly by
/// `get_agents_dir_or_error_none_returns_error`.
fn get_agents_dir() -> anyhow::Result<PathBuf> {
    #[cfg(test)]
    if FORCE_AGENTS_DIR_ERROR.with(|f| f.get()) {
        anyhow::bail!("Could not determine home directory");
    }
    get_agents_dir_or_error(leviath_core::paths::agents_dir())
}

#[cfg(test)]
thread_local! {
    /// Test-only toggle letting `execute_returns_err_when_agents_dir_unresolvable`
    /// force `get_agents_dir`'s `Err` arm deterministically.
    static FORCE_AGENTS_DIR_ERROR: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

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

    fn write_manifest(dir: &Path, name: &str) {
        write_manifest_with_description(dir, name, "Test agent");
    }

    /// The scanners under a config that grants nothing, which is what every
    /// test predating `[read_paths]` reporting assumed. Tests that care about
    /// grants call the real functions with a config of their own.
    fn read_agent_info(manifest_path: &Path) -> Option<AgentInfo> {
        super::read_agent_info(manifest_path, &Config::default(), Path::new("/work"))
    }

    fn scan_directory_for_agents(dir: &Path) -> Vec<(PathBuf, AgentInfo)> {
        super::scan_directory_for_agents(dir, &Config::default(), Path::new("/work"))
    }

    fn write_manifest_with_description(dir: &Path, name: &str, description: &str) {
        let content = format!(
            r#"[agent]
name = "{}"
version = "1.0.0"
description = "{}"

[stages.main]
mode = "autonomous"
model = {{ provider = "anthropic", model = "claude-sonnet-4-6" }}
description = "Main"
max_iterations = 5

[context.regions]
system = {{ kind = "pinned", max_tokens = 1000 }}
"#,
            name, description
        );
        write_test_agent(dir, content);
    }

    /// An agent that asks to read outside its workdir, for the grant-status
    /// line. Written as an absolute entry so it compiles the same on every OS.
    fn write_read_paths_manifest(dir: &Path, name: &str) {
        let content = format!(
            r#"[agent]
name = "{name}"
version = "1.0.0"
description = "Test agent"

[stages.main]
mode = "autonomous"
model = {{ provider = "anthropic", model = "claude-sonnet-4-6" }}
description = "Main"
max_iterations = 5

[context.regions]
system = {{ kind = "pinned", max_tokens = 1000 }}

[read_paths]
allow = ["/data/runs"]
"#
        );
        write_test_agent(dir, content);
    }

    fn info_with_config(dir: &Path, config: &Config) -> AgentInfo {
        super::read_agent_info(&dir.join("agent.leviath"), config, Path::new("/work"))
            .expect("manifest parses")
    }

    /// The reported bug, in the listing: an agent whose declarations nothing
    /// grants must say so, and point at where the detail is.
    #[test]
    fn an_ungranted_read_paths_declaration_is_listed_as_such() {
        let dir = tempfile::tempdir().unwrap();
        write_read_paths_manifest(dir.path(), "cto");
        let summary = info_with_config(dir.path(), &Config::default())
            .read_paths
            .expect("declares read paths");
        assert!(summary.contains("1 declared, 0 granted"), "{summary}");
        assert!(summary.contains("lev validate"), "{summary}");
    }

    #[test]
    fn a_granted_read_paths_declaration_needs_no_pointer() {
        let dir = tempfile::tempdir().unwrap();
        write_read_paths_manifest(dir.path(), "cto");
        let mut config = Config::default();
        config.security.read_paths = vec!["/data/runs".to_string()];
        let summary = info_with_config(dir.path(), &config)
            .read_paths
            .expect("declares read paths");
        assert_eq!(summary, "read_paths: 1 declared, 1 granted");
    }

    /// A grant list that cannot compile is a hard spawn error later; saying so
    /// here beats printing a count derived from nothing.
    #[test]
    fn a_broken_grant_list_is_reported_on_the_agent() {
        let dir = tempfile::tempdir().unwrap();
        write_read_paths_manifest(dir.path(), "cto");
        let mut config = Config::default();
        config.security.read_paths = vec!["regex:relative/.*".to_string()];
        let summary = info_with_config(dir.path(), &config)
            .read_paths
            .expect("declares read paths");
        assert!(summary.contains("config.toml"), "{summary}");
    }

    #[test]
    fn an_agent_declaring_no_read_paths_gets_no_line() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(dir.path(), "plain");
        assert!(
            info_with_config(dir.path(), &Config::default())
                .read_paths
                .is_none()
        );
    }

    #[test]
    fn read_agent_info_valid_manifest() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(dir.path(), "my-agent");
        let info = read_agent_info(&dir.path().join("agent.leviath")).unwrap();
        assert_eq!(info.name, "my-agent");
        assert_eq!(info.version, "1.0.0");
        assert_eq!(info.description, "Test agent");
    }

    #[test]
    fn read_agent_info_missing_file_returns_none() {
        let result = read_agent_info(Path::new("/nonexistent/agent.leviath"));
        assert!(result.is_none());
    }

    #[test]
    fn read_agent_info_invalid_toml_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("agent.leviath"), "not valid toml {{{{").unwrap();
        let result = read_agent_info(&dir.path().join("agent.leviath"));
        assert!(result.is_none());
    }

    #[test]
    fn scan_directory_nonexistent_returns_empty() {
        let agents = scan_directory_for_agents(Path::new("/nonexistent/path"));
        assert!(agents.is_empty());
    }

    #[test]
    fn scan_directory_path_is_a_file_returns_empty() {
        // `dir.exists()` is true for a plain file too, so this reaches
        // `fs::read_dir(dir)` - which fails with "not a directory",
        // exercising the `if let Ok(entries) = ...` construct's implicit
        // (no-`else`) false arm that no other test hits.
        let tmp = tempfile::tempdir().unwrap();
        let file_path = tmp.path().join("not-a-directory.txt");
        fs::write(&file_path, "hello").unwrap();
        let agents = scan_directory_for_agents(&file_path);
        assert!(agents.is_empty());
    }

    #[test]
    fn scan_directory_direct_manifest_invalid_is_skipped() {
        // The direct-manifest branch (as opposed to the subdirectory-scan
        // branch, covered separately by `scan_directory_subdir_with_invalid_manifest`)
        // has its own `if let Some(info) = read_agent_info(...)` - this
        // exercises that branch's `None` arm when the manifest at the
        // directory's own root is present but unparseable.
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("agent.leviath"), "not valid toml {{{{").unwrap();
        let agents = scan_directory_for_agents(dir.path());
        assert!(agents.is_empty());
    }

    #[test]
    fn scan_directory_with_direct_manifest() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(dir.path(), "direct-agent");
        let agents = scan_directory_for_agents(dir.path());
        assert_eq!(agents.len(), 1);
        assert_eq!(agents[0].1.name, "direct-agent");
    }

    #[test]
    fn scan_directory_with_subdirectories() {
        let dir = tempfile::tempdir().unwrap();
        let sub1 = dir.path().join("agent-a");
        let sub2 = dir.path().join("agent-b");
        fs::create_dir_all(&sub1).unwrap();
        fs::create_dir_all(&sub2).unwrap();
        write_manifest(&sub1, "agent-a");
        write_manifest(&sub2, "agent-b");

        let agents = scan_directory_for_agents(dir.path());
        assert_eq!(agents.len(), 2);
        let names: Vec<&str> = agents.iter().map(|a| a.1.name.as_str()).collect();
        assert!(names.contains(&"agent-a"));
        assert!(names.contains(&"agent-b"));
    }

    #[test]
    fn scan_directory_ignores_subdirs_without_manifest() {
        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("no-manifest");
        fs::create_dir_all(&sub).unwrap();
        fs::write(sub.join("readme.txt"), "not a manifest").unwrap();

        let agents = scan_directory_for_agents(dir.path());
        assert!(agents.is_empty());
    }

    #[test]
    fn list_args_default_filter() {
        let args = ListArgs {
            filter: "all".to_string(),
        };
        assert_eq!(args.filter, "all");
    }

    // ─── read_agent_info: description and version ───────────────────────

    #[test]
    fn read_agent_info_extracts_description() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(dir.path(), "my-agent");
        let info = read_agent_info(&dir.path().join("agent.leviath")).unwrap();
        assert_eq!(info.description, "Test agent");
        assert_eq!(info.version, "1.0.0");
    }

    // ─── scan_directory: nested but not deep ────────────────────────────

    #[test]
    fn scan_directory_with_both_direct_and_subdirs() {
        let dir = tempfile::tempdir().unwrap();
        // Direct manifest
        write_manifest(dir.path(), "root-agent");
        // Subdirectory with manifest
        let sub = dir.path().join("child");
        fs::create_dir_all(&sub).unwrap();
        write_manifest(&sub, "child-agent");

        let agents = scan_directory_for_agents(dir.path());
        assert_eq!(agents.len(), 2);
        let names: Vec<&str> = agents.iter().map(|a| a.1.name.as_str()).collect();
        assert!(names.contains(&"root-agent"));
        assert!(names.contains(&"child-agent"));
    }

    // ─── scan_directory: empty directory ────────────────────────────────

    #[test]
    fn scan_directory_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        let agents = scan_directory_for_agents(dir.path());
        assert!(agents.is_empty());
    }

    // ─── scan_directory: subdirectory with invalid manifest ─────────────

    #[test]
    fn scan_directory_subdir_with_invalid_manifest() {
        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("bad-agent");
        fs::create_dir_all(&sub).unwrap();
        fs::write(sub.join("agent.leviath"), "invalid toml {{{{").unwrap();

        let agents = scan_directory_for_agents(dir.path());
        assert!(agents.is_empty());
    }

    // ─── get_agents_dir ────────────────────────────────────────────────

    #[test]
    fn get_agents_dir_returns_path_with_agents() {
        let dir = get_agents_dir().unwrap();
        assert!(dir.to_str().unwrap().contains(".leviath"));
        assert!(dir.to_str().unwrap().ends_with("agents"));
    }

    #[test]
    fn get_agents_dir_or_error_some_returns_path() {
        let dir = PathBuf::from("/home/testuser/.leviath/agents");
        assert_eq!(get_agents_dir_or_error(Some(dir.clone())).unwrap(), dir);
    }

    #[test]
    fn get_agents_dir_or_error_none_returns_error() {
        let err = get_agents_dir_or_error(None).unwrap_err();
        assert!(
            err.to_string()
                .contains("Could not determine home directory")
        );
    }

    // ─── read_agent_info: minimal manifest ──────────────────────────────

    #[test]
    fn read_agent_info_minimal_manifest() {
        let dir = tempfile::tempdir().unwrap();
        let content = r#"[agent]
name = "minimal"
version = "0.0.1"
description = ""

[stages.main]
mode = "autonomous"
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
description = "Main"
max_iterations = 5

[context.regions]
system = { kind = "pinned", max_tokens = 1000 }
"#;
        write_test_agent(dir.path(), content);
        let info = read_agent_info(&dir.path().join("agent.leviath")).unwrap();
        assert_eq!(info.name, "minimal");
        assert_eq!(info.description, "");
    }

    // ─── execute() smoke test (real environment) ────────────────────────

    #[tokio::test]
    async fn execute_runs_without_error() {
        // Isolated: this reaches `Config::load()`, which reads process-wide
        // environment. Unisolated it races every `temp_env` test in the binary.
        crate::config::with_isolated_config_path_async("list-runs-ok", |_fake_dir| async move {
            // Touches the real environment (home dir / CWD / exe location /
            // config) but must always succeed regardless of what it finds.
            let args = ListArgs {
                filter: "all".to_string(),
            };
            let result = execute(args).await;
            assert!(result.is_ok());
        })
        .await;
    }

    #[tokio::test]
    async fn execute_returns_err_when_agents_dir_unresolvable() {
        // Isolated: this reaches `Config::load()`, which reads process-wide
        // environment. Unisolated it races every `temp_env` test in the binary.
        crate::config::with_isolated_config_path_async("list-dir-err", |_fake_dir| async move {
            // Drives `execute`'s `get_agents_dir()?` error-propagation branch
            // for real via the test-only `FORCE_AGENTS_DIR_ERROR` toggle on
            // `get_agents_dir`'s twin (see its doc comment for why the real
            // implementation's failure can't be forced directly).
            FORCE_AGENTS_DIR_ERROR.with(|f| f.set(true));
            let args = ListArgs {
                filter: "all".to_string(),
            };
            let result = execute(args).await;
            FORCE_AGENTS_DIR_ERROR.with(|f| f.set(false));

            let err = result.unwrap_err();
            assert!(
                err.to_string()
                    .contains("Could not determine home directory")
            );
        })
        .await;
    }

    // `execute`'s `std::env::current_dir().unwrap_or_default()` can only take
    // its `Err` arm in a real (if rare) TOCTOU scenario: the process's CWD is
    // removed out from under it. That's genuinely reproducible on Unix (not a
    // fake): create a directory, `chdir` into it, then delete it --
    // `current_dir()` then reliably returns an error. On Windows this same
    // sequence isn't reproducible: NTFS/Win32 refuse to remove a directory
    // that's a live process's current working directory (a sharing
    // violation), so `remove_dir_all` itself fails there instead of
    // succeeding - confirmed via real Windows CI. Unix-only.
    #[cfg(unix)]
    #[tokio::test]
    async fn execute_falls_back_to_default_cwd_when_current_dir_is_gone() {
        // Isolated: this reaches `Config::load()`, which reads process-wide
        // environment. Unisolated it races every `temp_env` test in the binary.
        crate::config::with_isolated_config_path_async("list-cwd-gone", |_fake_dir| async move {
            // `isolate_cwd_for_test` serializes against every other CWD-mutating
            // test in the crate and restores CWD automatically on drop, so it's
            // safe to hold across the `.await` below.
            let _guard = crate::config::isolate_cwd_for_test();
            let dir = std::env::temp_dir().join("lev-test-list-cwd-gone");
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).unwrap();
            std::env::set_current_dir(&dir).unwrap();
            std::fs::remove_dir_all(&dir).unwrap();

            let args = ListArgs {
                filter: "all".to_string(),
            };
            let result = execute(args).await;

            assert!(result.is_ok());
        })
        .await;
    }

    /// Cross-platform companion to the Unix-only real-filesystem test above:
    /// forces [`resolve_cwd`]'s `Err` arm deterministically via
    /// [`super::super::force_cwd_error`] so `execute`'s `unwrap_or_default()` fallback is
    /// also exercised on Windows, where the real filesystem race isn't
    /// reproducible.
    #[tokio::test]
    async fn execute_falls_back_to_default_cwd_via_forced_error() {
        // Isolated: this reaches `Config::load()`, which reads process-wide
        // environment. Unisolated it races every `temp_env` test in the binary.
        crate::config::with_isolated_config_path_async("list-cwd-forced", |_fake_dir| async move {
            crate::commands::force_cwd_error(true);
            let args = ListArgs {
                filter: "all".to_string(),
            };
            let result = execute(args).await;
            crate::commands::force_cwd_error(false);

            assert!(result.is_ok());
        })
        .await;
    }

    /// A config that exists but doesn't parse must fail the command, not
    /// silently list from the default `agent_paths` (regression: this used to
    /// be `unwrap_or_default()`, which hid the user's agent directories with
    /// no hint why).
    #[tokio::test]
    async fn execute_fails_loudly_on_a_broken_config() {
        crate::config::with_isolated_config_path_async(
            "list-broken-config",
            |fake_dir| async move {
                std::fs::write(fake_dir.join("config.toml"), "not = valid = toml").unwrap();
                let args = ListArgs {
                    filter: "all".to_string(),
                };
                let err = execute(args).await.expect_err("broken config must error");
                assert!(err.to_string().contains("parse"), "{err}");
            },
        )
        .await;
    }

    // ─── print_agent_listing (fully injectable) ─────────────────────────

    #[test]
    fn print_agent_listing_nothing_installed() {
        // The bundled catalog is always non-empty, so it must not count as
        // "you have agents" - otherwise the get-started guidance would be
        // suppressed for exactly the fresh install that needs it.
        let agents_dir = tempfile::tempdir().unwrap();
        let cwd = tempfile::tempdir().unwrap();
        let config = Config::default();

        let result = print_agent_listing(agents_dir.path(), cwd.path(), None, &config);
        assert!(result.is_ok());
    }

    #[test]
    fn print_agent_listing_finds_installed_agent() {
        let agents_dir = tempfile::tempdir().unwrap();
        let sub = agents_dir.path().join("installed-agent");
        fs::create_dir_all(&sub).unwrap();
        write_manifest(&sub, "installed-agent");

        let cwd = tempfile::tempdir().unwrap();
        let config = Config::default();

        let result = print_agent_listing(agents_dir.path(), cwd.path(), None, &config);
        assert!(result.is_ok());
    }

    #[test]
    fn print_agent_listing_finds_local_manifest() {
        let agents_dir = tempfile::tempdir().unwrap();
        let cwd = tempfile::tempdir().unwrap();
        write_manifest(cwd.path(), "local-agent");
        let config = Config::default();

        let result = print_agent_listing(agents_dir.path(), cwd.path(), None, &config);
        assert!(result.is_ok());
    }

    #[test]
    fn print_agent_listing_local_manifest_invalid_is_skipped() {
        // The local-manifest section has its own `if let Some(info) = ...`
        // construct with no `else`; this exercises its false arm (an
        // existing but unparseable `agent.leviath` in the cwd), which
        // `print_agent_listing_finds_local_manifest` (valid manifest) never
        // reaches.
        let agents_dir = tempfile::tempdir().unwrap();
        let cwd = tempfile::tempdir().unwrap();
        fs::write(cwd.path().join("agent.leviath"), "not valid toml {{{{").unwrap();
        let config = Config::default();

        let result = print_agent_listing(agents_dir.path(), cwd.path(), None, &config);
        assert!(result.is_ok());
    }

    #[test]
    fn print_agent_listing_finds_configured_path_agent() {
        let agents_dir = tempfile::tempdir().unwrap();
        let cwd = tempfile::tempdir().unwrap();
        let configured = tempfile::tempdir().unwrap();
        let sub = configured.path().join("configured-agent");
        fs::create_dir_all(&sub).unwrap();
        write_manifest(&sub, "configured-agent");

        let config = Config {
            agent_paths: vec![configured.path().to_path_buf()],
            ..Config::default()
        };

        let result = print_agent_listing(agents_dir.path(), cwd.path(), None, &config);
        assert!(result.is_ok());
    }

    #[test]
    fn print_agent_listing_finds_builtin_agents() {
        // An `agents/` directory beside the executable contributes a blueprint
        // the embedded catalog doesn't have, so it is appended to the list.
        let agents_dir = tempfile::tempdir().unwrap();
        let cwd = tempfile::tempdir().unwrap();
        let exe_dir = tempfile::tempdir().unwrap();
        let builtin_dir = exe_dir.path().join("agents");
        let sub = builtin_dir.join("builtin-agent");
        fs::create_dir_all(&sub).unwrap();
        write_manifest(&sub, "builtin-agent");
        let config = Config::default();

        let result =
            print_agent_listing(agents_dir.path(), cwd.path(), Some(exe_dir.path()), &config);
        assert!(result.is_ok());
    }

    /// The listing prints the `[read_paths]` line for an agent that has one,
    /// which is the second line `print_agent` can emit.
    #[test]
    fn print_agent_listing_carries_the_read_paths_line() {
        let agents_dir = tempfile::tempdir().unwrap();
        let agent = agents_dir.path().join("cto");
        fs::create_dir_all(&agent).unwrap();
        write_read_paths_manifest(&agent, "cto");
        let cwd = tempfile::tempdir().unwrap();

        let result = print_agent_listing(agents_dir.path(), cwd.path(), None, &Config::default());

        assert!(result.is_ok());
        // The line itself is asserted where it is built, without capturing
        // stdout; this is the path that reaches the printer with one to print.
        assert!(
            info_with_config(&agent, &Config::default())
                .read_paths
                .is_some()
        );
    }

    #[test]
    fn print_agent_listing_does_not_list_a_bundled_agent_twice() {
        // Running from a git checkout puts the *same* blueprints both in the
        // embedded catalog and in `<exe_dir>/agents`. Listing each one twice
        // would be pure noise, so the on-disk scan only appends what the
        // catalog doesn't already carry.
        let bundled = &crate::bundled::BUNDLED_AGENTS[0];
        let agents_dir = tempfile::tempdir().unwrap();
        let cwd = tempfile::tempdir().unwrap();
        let exe_dir = tempfile::tempdir().unwrap();
        let sub = exe_dir.path().join("agents").join(bundled.name);
        fs::create_dir_all(&sub).unwrap();
        crate::bundled::install_bundled(bundled, &exe_dir.path().join("agents")).unwrap();
        let config = Config::default();

        let result =
            print_agent_listing(agents_dir.path(), cwd.path(), Some(exe_dir.path()), &config);

        assert!(result.is_ok());
        // The same name+version pair the catalog already holds resolves to one
        // entry, not two.
        let entry = format!("{} (v{})", bundled.name, bundled.version);
        let names: Vec<String> = crate::bundled::BUNDLED_AGENTS
            .iter()
            .map(|a| format!("{} (v{})", a.name, a.version))
            .collect();
        assert_eq!(names.iter().filter(|n| **n == entry).count(), 1);
    }

    #[test]
    fn print_agent_listing_all_sources_populated() {
        let agents_dir = tempfile::tempdir().unwrap();
        fs::create_dir_all(agents_dir.path().join("installed")).unwrap();
        write_manifest(&agents_dir.path().join("installed"), "installed");

        let cwd = tempfile::tempdir().unwrap();
        write_manifest(cwd.path(), "local");

        let configured = tempfile::tempdir().unwrap();
        fs::create_dir_all(configured.path().join("configured")).unwrap();
        write_manifest(&configured.path().join("configured"), "configured");

        let exe_dir = tempfile::tempdir().unwrap();
        let builtin_sub = exe_dir.path().join("agents").join("builtin");
        fs::create_dir_all(&builtin_sub).unwrap();
        write_manifest(&builtin_sub, "builtin");

        let config = Config {
            agent_paths: vec![configured.path().to_path_buf()],
            ..Config::default()
        };

        let result =
            print_agent_listing(agents_dir.path(), cwd.path(), Some(exe_dir.path()), &config);
        assert!(result.is_ok());
    }

    #[test]
    fn print_agent_listing_empty_descriptions_across_all_sources() {
        // Every section (installed / local / configured-path) has its own
        // "empty description -> no dash suffix" branch; the tests above only
        // ever exercise the non-empty path for all three, since
        // `write_manifest` hardcodes a non-empty description.
        let agents_dir = tempfile::tempdir().unwrap();
        fs::create_dir_all(agents_dir.path().join("installed")).unwrap();
        write_manifest_with_description(&agents_dir.path().join("installed"), "installed", "");

        let cwd = tempfile::tempdir().unwrap();
        write_manifest_with_description(cwd.path(), "local", "");

        let configured = tempfile::tempdir().unwrap();
        fs::create_dir_all(configured.path().join("configured")).unwrap();
        write_manifest_with_description(&configured.path().join("configured"), "configured", "");

        let config = Config {
            agent_paths: vec![configured.path().to_path_buf()],
            ..Config::default()
        };

        let result = print_agent_listing(agents_dir.path(), cwd.path(), None, &config);
        assert!(result.is_ok());
    }

    // ─── scan_directory: agent with empty description ────────────────────

    #[test]
    fn scan_directory_agent_with_empty_description() {
        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("my-agent");
        fs::create_dir_all(&sub).unwrap();
        let content = r#"[agent]
name = "my-agent"
version = "2.0.0"
description = ""

[stages.main]
mode = "autonomous"
model = { provider = "anthropic", model = "claude-sonnet-4-6" }
description = "Main"
max_iterations = 5

[context.regions]
system = { kind = "pinned", max_tokens = 1000 }
"#;
        write_test_agent(sub, content);

        let agents = scan_directory_for_agents(dir.path());
        assert_eq!(agents.len(), 1);
        assert_eq!(agents[0].1.description, "");
    }

    // ─── scan_directory: multiple subdirs with mixed manifests ──────────

    #[test]
    fn scan_directory_mixed_valid_and_invalid() {
        let dir = tempfile::tempdir().unwrap();
        let good = dir.path().join("good");
        let bad = dir.path().join("bad");
        let empty = dir.path().join("empty");
        fs::create_dir_all(&good).unwrap();
        fs::create_dir_all(&bad).unwrap();
        fs::create_dir_all(&empty).unwrap();

        write_manifest(&good, "good-agent");
        fs::write(bad.join("agent.leviath"), "bad {{ toml").unwrap();

        let agents = scan_directory_for_agents(dir.path());
        assert_eq!(agents.len(), 1);
        assert_eq!(agents[0].1.name, "good-agent");
    }
}