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
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
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
use super::*;

/// Wrap `stages_toml` in the smallest manifest that parses and validates.
fn manifest(stages_toml: &str) -> String {
    format!(
        r#"
[agent]
name = "lint-fixture"
version = "0.1.0"
description = "a fixture"

{stages_toml}

[context.regions]
system = {{ kind = "pinned", max_tokens = 1000 }}
conversation = {{ kind = "sliding_window", max_items = 50, max_tokens = 10000 }}
"#
    )
}

/// Lint a manifest whose text and blueprint come from the same source, which is
/// the only pairing production ever passes.
fn lint(content: &str, env: &LintEnv) -> Vec<LintFinding> {
    let bp = leviath_core::manifest::parse_manifest(content).expect("fixture parses");
    lint_manifest(content, &bp, env)
}

/// The codes reported, in order, so a test can assert on the whole outcome
/// rather than on one finding it went looking for.
fn codes(findings: &[LintFinding]) -> Vec<&'static str> {
    findings.iter().map(|f| f.code).collect()
}

/// Every finding carrying `code`.
fn with_code<'a>(findings: &'a [LintFinding], code: &str) -> Vec<&'a LintFinding> {
    findings.iter().filter(|f| f.code == code).collect()
}

/// A stage that declares everything the linter looks for, so a test can add a
/// single defect and see only that.
const CLEAN_STAGE: &str = r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
description = "Main"
max_iterations = 10
available_tools = ["read_file"]
"#;

fn known_tools(names: &[&str]) -> HashSet<String> {
    names.iter().map(|n| (*n).to_string()).collect()
}

// ─── Nothing to report ────────────────────────────────────────────────────────

#[test]
fn a_fully_declared_stage_reports_nothing() {
    let findings = lint(&manifest(CLEAN_STAGE), &LintEnv::default());
    assert!(findings.is_empty(), "{:?}", codes(&findings));
}

/// An empty [`LintEnv`] is "I don't know", and an unknown fact must never
/// become a finding: no tool catalog means no unknown-tool errors, no model
/// catalog means no unknown-model warnings.
#[test]
fn an_empty_env_skips_every_environment_dependent_check() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "madeup", model = "no-such-model" }] }
max_iterations = 10
available_tools = ["raed_file"]
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert!(findings.is_empty(), "{:?}", codes(&findings));
}

// ─── Declaration checks ───────────────────────────────────────────────────────

#[test]
fn a_stage_with_no_mode_is_warned_about() {
    let toml = manifest(
        r#"
[stages.main]
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["stage-missing-mode"]);
    assert_eq!(findings[0].stage.as_deref(), Some("main"));
    assert_eq!(findings[0].severity, LintSeverity::Warning);
    assert!(findings[0].message.contains("autonomous"), "{findings:?}");
}

/// The defect from the report: no model block, so the engine invents one and
/// the stage silently runs on the user's default provider.
#[test]
fn a_stage_with_no_model_block_is_warned_about() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
max_iterations = 10
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["stage-missing-model"]);
    assert!(
        findings[0].message.contains("default_provider"),
        "{findings:?}"
    );
    let fix = findings[0].fix.as_deref().expect("the fix names the block");
    assert!(fix.contains("[stages.main]"), "{fix}");
}

/// The old single-model spelling (`provider`/`model` at the top of the table)
/// still counts as declaring one.
#[test]
fn the_legacy_inline_model_spelling_counts_as_declared() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { provider = "anthropic", model = "claude-sonnet-5" }
max_iterations = 10
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert!(findings.is_empty(), "{:?}", codes(&findings));
}

#[test]
fn a_stage_with_no_max_iterations_is_warned_about() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["stage-missing-max-iterations"]);
    assert!(
        findings[0].message.contains("default_max_iterations"),
        "{findings:?}"
    );
}

/// A fan_out stage runs no inference of its own, so it has no iteration count
/// to cap and must not be nagged for one.
#[test]
fn a_fan_out_stage_needs_no_max_iterations() {
    let toml = manifest(
        r#"
[stages.split]
mode = "fan_out"
worker_stage = "work"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }

[stages.work]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
allow_as_worker = true
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert!(findings.is_empty(), "{:?}", codes(&findings));
}

/// An agent-level `[model]` block reads like it sets the agent's model. Nothing
/// looks at it.
#[test]
fn an_agent_level_model_block_is_warned_about() {
    let toml = format!(
        "{}\n[model]\nprovider = \"anthropic\"\nmodel = \"claude-opus-5\"\n",
        manifest(CLEAN_STAGE)
    );
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["agent-model-block-ignored"]);
    assert!(findings[0].stage.is_none(), "{findings:?}");
}

// ─── Declared: the fallbacks ──────────────────────────────────────────────────

/// Text the linter cannot re-read yields no declaration findings at all, rather
/// than a full set of false ones. Production never hits this (the caller only
/// lints a manifest that already parsed) so it is asserted directly.
#[test]
fn unreadable_text_reports_every_key_as_declared() {
    let declared = Declared::from_text("not valid toml [[[");
    assert!(!declared.agent_model_block);
    let keys = declared.stage("anything");
    assert!(keys.mode);
    assert!(keys.model);
}

/// Same for a stage the text has no entry for, which is how a blueprint built
/// in code rather than parsed would arrive.
#[test]
fn a_stage_absent_from_the_text_reports_as_declared() {
    let keys = Declared::from_text("[agent]\nname = \"x\"\n").stage("ghost");
    assert!(keys.mode);
    assert!(keys.model);
}

/// A manifest that parses to something other than a table (a bare TOML document
/// cannot, but the parse is fallible in principle) takes the same path.
#[test]
fn text_with_no_stages_table_has_no_stage_keys() {
    let declared = Declared::from_text("[agent]\nname = \"x\"\n");
    assert!(declared.stages.is_empty());
    assert!(!declared.opaque);
}

// ─── Tool checks ──────────────────────────────────────────────────────────────

#[test]
fn a_misspelled_tool_is_an_error() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["read_file", "raed_file"]
"#,
    );
    let env = LintEnv {
        known_tools: known_tools(&["read_file"]),
        ..LintEnv::default()
    };
    let findings = lint(&toml, &env);
    assert_eq!(codes(&findings), ["unknown-tool"]);
    assert!(findings[0].is_error());
    assert!(findings[0].message.contains("raed_file"), "{findings:?}");
}

/// `server__tool` names an MCP tool, which resolves only once that server is
/// installed. That is not a property of the manifest, so it is never flagged.
#[test]
fn an_mcp_tool_name_is_never_unknown() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["github__create_issue"]
"#,
    );
    let env = LintEnv {
        known_tools: known_tools(&["read_file"]),
        ..LintEnv::default()
    };
    assert!(lint(&toml, &env).is_empty());
}

#[test]
fn a_permission_for_an_ungranted_tool_is_an_error() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["read_file"]

[stages.main.tool_permissions]
write_file = "allow"
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["orphan-stage-permission"]);
    assert!(findings[0].is_error());
    assert!(findings[0].message.contains("write_file"), "{findings:?}");
}

#[test]
fn a_permission_for_a_granted_tool_is_fine() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["read_file"]

[stages.main.tool_permissions]
read_file = "allow"
"#,
    );
    assert!(lint(&toml, &LintEnv::default()).is_empty());
}

// ─── Blocking tools ───────────────────────────────────────────────────────────

#[test]
fn an_autonomous_stage_granting_an_ask_tool_is_warned_about() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["ask_user_text"]
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["blocking-tool-in-autonomous-stage"]);
    assert!(
        findings[0].message.contains("until a person answers"),
        "{findings:?}"
    );
}

/// Every name the runtime dispatches to a human is covered, not just the
/// `ask_user_*` family.
#[test]
fn every_blocking_interaction_tool_is_flagged() {
    for tool in BLOCKING_INTERACTION_TOOLS {
        let toml = manifest(&format!(
            r#"
[stages.main]
mode = "autonomous"
model = {{ models = [{{ provider = "anthropic", model = "claude-sonnet-5" }}] }}
max_iterations = 10
available_tools = ["{tool}"]
"#
        ));
        assert_eq!(
            codes(&lint(&toml, &LintEnv::default())),
            ["blocking-tool-in-autonomous-stage"],
            "{tool}"
        );
    }
}

#[test]
fn allow_blocking_tools_silences_the_warning() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["ask_user_text"]
allow_blocking_tools = true
"#,
    );
    assert!(lint(&toml, &LintEnv::default()).is_empty());
}

/// Naming the tool in `required_tools` says the same thing one tool at a time,
/// and says it about the runtime too: the stage keeps that tool when the run is
/// unattended. The lint has nothing left to point out.
#[test]
fn required_tools_silences_the_warning_for_that_tool() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["ask_user_text", "ask_user_confirm"]
required_tools = ["ask_user_text"]
"#,
    );
    // Only the tool that was *not* kept is still worth remarking on.
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["blocking-tool-in-autonomous-stage"]);
    assert!(
        findings[0].message.contains("ask_user_confirm"),
        "{:?}",
        findings[0].message
    );
}

/// An interactive stage is where a person is expected, so the same grant is
/// unremarkable there.
#[test]
fn an_interactive_stage_may_grant_ask_tools_freely() {
    let toml = manifest(
        r#"
[stages.main]
mode = "interactive"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["ask_user_text"]
"#,
    );
    assert!(lint(&toml, &LintEnv::default()).is_empty());
}

// ─── Shell policy ─────────────────────────────────────────────────────────────

/// The default for a shell grant is `ask`, and an `ask` nobody answers waits
/// rather than denying, so an unattended run hangs on the first command.
#[test]
fn a_shell_grant_with_no_policy_is_warned_about() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["bash"]
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["implicit-shell-policy"]);
    assert!(findings[0].message.contains("'bash'"), "{findings:?}");
}

/// `bash` and `shell` are the same tool, so both spellings are checked.
#[test]
fn the_canonical_shell_spelling_is_checked_too() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["shell"]
"#,
    );
    assert_eq!(
        codes(&lint(&toml, &LintEnv::default())),
        ["implicit-shell-policy"]
    );
}

#[test]
fn a_stage_level_shell_policy_settles_it() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["bash"]

[stages.main.tool_permissions]
bash = "allow"
"#,
    );
    assert!(lint(&toml, &LintEnv::default()).is_empty());
}

/// The bug this check exists for, found in a shipped blueprint: the stage
/// grants `shell` and the agent writes `bash = "ask"`. Policy is matched on the
/// name the model calls, so the entry is dead.
#[test]
fn a_permission_written_under_the_other_spelling_is_warned_about() {
    let toml = format!(
        "{}\n[tool_permissions]\nbash = \"ask\"\n",
        manifest(
            r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["shell"]
"#,
        )
    );
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["permission-name-mismatch"]);
    assert!(
        findings[0].message.contains("grants 'shell'"),
        "{findings:?}"
    );
    assert!(findings[0].message.contains("'bash'"), "{findings:?}");
}

/// And the reverse: granted as `bash`, written as `shell`.
#[test]
fn the_mismatch_is_caught_in_either_direction() {
    let toml = format!(
        "{}\n[tool_permissions]\nshell = \"allow\"\n",
        manifest(
            r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["bash"]
"#,
        )
    );
    assert_eq!(
        codes(&lint(&toml, &LintEnv::default())),
        ["permission-name-mismatch"]
    );
}

#[test]
fn alias_siblings_never_include_the_name_itself() {
    assert_eq!(alias_siblings("bash"), ["shell"]);
    assert_eq!(alias_siblings("shell"), ["bash"]);
    // A tool with no aliases has no siblings at all.
    assert!(alias_siblings("read_file").is_empty());
}

#[test]
fn an_agent_level_shell_policy_settles_it() {
    let toml = format!(
        "{}\n[tool_permissions]\nbash = \"deny\"\n",
        manifest(
            r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["bash"]
"#,
        )
    );
    assert!(lint(&toml, &LintEnv::default()).is_empty());
}

// ─── Models and providers ─────────────────────────────────────────────────────

#[test]
fn a_model_missing_from_a_known_catalog_is_warned_about() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-9" }] }
max_iterations = 10
"#,
    );
    let env = LintEnv {
        known_models: vec![("anthropic".to_string(), "claude-sonnet-5".to_string())],
        ..LintEnv::default()
    };
    let findings = lint(&toml, &env);
    assert_eq!(codes(&findings), ["unknown-model"]);
    assert!(
        findings[0].message.contains("anthropic/claude-sonnet-9"),
        "{findings:?}"
    );
}

/// Ollama serves whatever has been pulled and OpenRouter's catalog runs to
/// hundreds of entries, so a provider with no rows is not checked at all.
#[test]
fn a_provider_with_no_catalog_is_not_checked() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "ollama", model = "qwen3.5:9b" }] }
max_iterations = 10
"#,
    );
    let env = LintEnv {
        known_models: vec![("anthropic".to_string(), "claude-sonnet-5".to_string())],
        ..LintEnv::default()
    };
    assert!(lint(&toml, &env).is_empty());
}

#[test]
fn a_model_present_in_the_catalog_passes() {
    let env = LintEnv {
        known_models: vec![("anthropic".to_string(), "claude-sonnet-5".to_string())],
        ..LintEnv::default()
    };
    assert!(lint(&manifest(CLEAN_STAGE), &env).is_empty());
}

/// A stage with nothing reachable in its whole list is the shape the runtime
/// rejects at spawn, so it is worth saying up front.
#[test]
fn a_stage_with_no_reachable_provider_is_warned_about() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }, { provider = "openai", model = "gpt-5.5" }] }
max_iterations = 10
"#,
    );
    let env = LintEnv {
        available_providers: Some(known_tools(&["ollama"])),
        ..LintEnv::default()
    };
    let findings = lint(&toml, &env);
    assert_eq!(codes(&findings), ["no-reachable-provider"]);
    assert!(
        findings[0].message.contains("anthropic, openai"),
        "{findings:?}"
    );
}

/// The models list is an ordered set of fallbacks. A provider the install
/// cannot reach is unremarkable as long as something later in the list can, so
/// only a list that is reachable nowhere is reported.
#[test]
fn an_unreachable_provider_is_fine_when_a_later_one_answers() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }, { provider = "ollama", model = "qwen3.5:9b" }] }
max_iterations = 10
"#,
    );
    let env = LintEnv {
        available_providers: Some(known_tools(&["ollama"])),
        ..LintEnv::default()
    };
    assert!(lint(&toml, &env).is_empty());
}

#[test]
fn every_provider_reachable_reports_nothing() {
    let env = LintEnv {
        available_providers: Some(known_tools(&["anthropic"])),
        ..LintEnv::default()
    };
    assert!(lint(&manifest(CLEAN_STAGE), &env).is_empty());
}

/// A stage with no model entries at all has no list to check, so the
/// reachability question does not arise (the missing-model warning covers it).
#[test]
fn a_stage_with_an_empty_models_list_is_not_checked_for_reachability() {
    let mut bp =
        leviath_core::manifest::parse_manifest(&manifest(CLEAN_STAGE)).expect("the fixture parses");
    bp.stages[0].model.models.clear();
    let env = LintEnv {
        available_providers: Some(HashSet::new()),
        ..LintEnv::default()
    };
    let findings = lint_manifest(&manifest(CLEAN_STAGE), &bp, &env);
    assert!(findings.is_empty(), "{:?}", codes(&findings));
}

// ─── read_paths ───────────────────────────────────────────────────────────────

/// Declaring `[read_paths]` is legitimate, so it is a note rather than a
/// warning: it must survive `--deny-warnings` on an otherwise good blueprint.
#[test]
fn read_path_declarations_are_noted_not_warned() {
    let toml = format!(
        "{}\n[read_paths]\nallow = [\"~/.leviath/runs\"]\n",
        manifest(CLEAN_STAGE)
    );
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["read-paths-declared"]);
    assert_eq!(findings[0].severity, LintSeverity::Note);
    assert!(
        findings[0].message.contains("~/.leviath/runs"),
        "{findings:?}"
    );
}

#[test]
fn no_read_paths_means_no_note() {
    assert!(
        !codes(&lint(&manifest(CLEAN_STAGE), &LintEnv::default())).contains(&"read-paths-declared")
    );
}

// ─── read_paths grant status (issue #209) ────────────────────────────────────

/// A blueprint declaring `entries`, plus a `LintEnv` carrying the verdict a
/// config of `grants` would give. Absolute entries so they compile the same on
/// every OS.
fn read_paths_env(entries: &[&str], grants: &[&str]) -> (String, LintEnv) {
    let listed = entries
        .iter()
        .map(|e| format!("\"{e}\""))
        .collect::<Vec<_>>()
        .join(", ");
    let toml = format!(
        "{}\n[read_paths]\nallow = [{listed}]\n",
        manifest(CLEAN_STAGE)
    );
    let blueprint = leviath_core::manifest::parse_manifest(&toml).expect("the fixture parses");
    let mut config = crate::config::Config::default();
    config.security.read_paths = grants.iter().map(|s| s.to_string()).collect();
    let env = LintEnv::default().with_read_paths(&blueprint, &config, Path::new("/work"));
    (toml, env)
}

/// The reported bug: with nothing granting them, the declared entries are
/// named as inert and the stanza that would fix it is on the fix line.
#[test]
fn ungranted_read_paths_are_warned_about_with_the_stanza_to_add() {
    let (toml, env) = read_paths_env(&["/data/runs", "glob:/docs/**"], &[]);
    let findings = lint(&toml, &env);
    assert_eq!(
        codes(&findings),
        ["read-paths-not-granted", "read-paths-declared"]
    );
    assert!(findings[0].message.contains("/data/runs"), "{findings:?}");
    assert!(
        findings[0].message.contains("glob:/docs/**"),
        "{findings:?}"
    );
    let fix = findings[0].fix.as_deref().expect("a fix names the stanza");
    assert!(fix.contains("[agent_read_paths.lint-fixture]"), "{fix}");
}

/// A partial grant is the case the old spawn warning missed entirely: it only
/// fired when the grant list was empty.
#[test]
fn a_partial_grant_names_only_what_is_still_refused() {
    let (toml, env) = read_paths_env(&["/data/runs", "glob:/docs/**"], &["/data/runs"]);
    let findings = lint(&toml, &env);
    assert_eq!(
        codes(&findings),
        ["read-paths-not-granted", "read-paths-declared"]
    );
    assert!(!findings[0].message.contains("/data/runs,"), "{findings:?}");
    assert!(
        findings[0].message.contains("glob:/docs/**"),
        "{findings:?}"
    );
    assert!(
        findings[1].message.contains("2 declared, 1 granted"),
        "{findings:?}"
    );
}

/// Fully granted: the note says so, per entry, and nothing warns.
#[test]
fn granted_read_paths_are_a_note_only() {
    let (toml, env) = read_paths_env(&["/data/runs"], &["/data/runs"]);
    let findings = lint(&toml, &env);
    assert_eq!(codes(&findings), ["read-paths-declared"]);
    assert!(
        findings[0].message.contains("1 declared, 1 granted"),
        "{findings:?}"
    );
    assert!(
        findings[0]
            .fix
            .as_deref()
            .is_some_and(|f| f.contains("/data/runs: granted")),
        "{findings:?}"
    );
}

/// The blanket override grants everything, and says which switch did it.
#[test]
fn the_blanket_override_is_named_on_the_note() {
    let toml = format!(
        "{}\n[read_paths]\nallow = [\"/data/runs\"]\n",
        manifest(CLEAN_STAGE)
    );
    let blueprint = leviath_core::manifest::parse_manifest(&toml).expect("the fixture parses");
    let mut config = crate::config::Config::default();
    config.security.allow_blueprint_read_paths = true;
    let env = LintEnv::default().with_read_paths(&blueprint, &config, Path::new("/work"));
    let findings = lint(&toml, &env);
    assert_eq!(codes(&findings), ["read-paths-declared"]);
    assert!(
        findings[0]
            .fix
            .as_deref()
            .is_some_and(|f| f.contains("allow_blueprint_read_paths")),
        "{findings:?}"
    );
}

/// An entry no representative path can be built from is reported as unchecked
/// rather than as inert, and is not offered up for granting.
#[test]
fn an_uncheckable_entry_is_not_called_ungranted() {
    let (toml, env) = read_paths_env(&["glob:/docs/[ab]/**"], &["/data/runs"]);
    let findings = lint(&toml, &env);
    assert_eq!(codes(&findings), ["read-paths-declared"]);
    assert!(
        findings[0]
            .fix
            .as_deref()
            .is_some_and(|f| f.contains("cannot be checked")),
        "{findings:?}"
    );
}

/// A grant list of the user's own that will not compile is a hard spawn error;
/// `lev validate` is where it should surface first.
#[test]
fn a_malformed_config_grant_is_warned_about() {
    let (toml, env) = read_paths_env(&["/data/runs"], &["regex:relative/.*"]);
    let findings = lint(&toml, &env);
    assert_eq!(codes(&findings), ["read-paths-grant-invalid"]);
    assert!(findings[0].message.contains("config.toml"), "{findings:?}");
}

/// An entry amounting to "everything" gets its own warning on top of the note.
#[test]
fn a_broad_read_path_entry_gets_its_own_warning() {
    let toml = format!(
        "{}\n[read_paths]\nallow = [\"~\", \"~/.leviath/runs\"]\n",
        manifest(CLEAN_STAGE)
    );
    let findings = lint(&toml, &LintEnv::default());
    // Warning sorts ahead of Note.
    assert_eq!(codes(&findings), ["broad-read-path", "read-paths-declared"]);
    assert!(findings[0].message.contains("'~'"), "{findings:?}");
}

#[test]
fn the_broad_entry_heuristic_covers_each_shape() {
    for entry in [
        "~",
        "~/",
        "/",
        "glob:**",
        "glob:/**",
        "regex:/.*",
        "regex:/.+",
    ] {
        assert!(read_path_entry_is_broad(entry), "{entry}");
    }
    for entry in [
        "~/.leviath/runs",
        "glob:~/docs/**",
        "regex:/data/.*",
        "../shared",
        r"C:\data",
    ] {
        assert!(!read_path_entry_is_broad(entry), "{entry}");
    }
}

// ─── Command seeds ────────────────────────────────────────────────────────────

#[test]
fn command_seed_regions_are_named_in_one_note() {
    let toml = r#"
[agent]
name = "scanner"
version = "0.1.0"

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

[context.regions]
facts = { kind = "pinned", max_tokens = 1000, seed = { command = "git ls-files" } }
tests = { kind = "pinned", max_tokens = 1000, seed = { command = "ls tests" } }
plain = { kind = "pinned", max_tokens = 1000 }
conversation = { kind = "sliding_window", max_items = 50, max_tokens = 10000 }
"#;
    let findings = lint(toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["command-seed"]);
    let message = &findings[0].message;
    assert!(message.contains("2 region(s)"), "{message}");
    assert!(message.contains("facts: git ls-files"), "{message}");
    assert!(message.contains("tests: ls tests"), "{message}");
    // A region without a command seed is not named.
    assert!(!message.contains("plain"), "{message}");
    // The escape hatches are given, so the reader knows how to refuse.
    let fix = findings[0]
        .fix
        .as_deref()
        .expect("a seed note offers a fix");
    assert!(fix.contains("--no-seed-commands"), "{fix}");
    assert!(fix.contains("allow_seed_commands"), "{fix}");
}

#[test]
fn no_command_seeds_means_no_note() {
    assert!(!codes(&lint(&manifest(CLEAN_STAGE), &LintEnv::default())).contains(&"command-seed"));
}

// ─── Graph shape ──────────────────────────────────────────────────────────────

/// A graph-shaped blueprint with the entry reaching everything reports nothing,
/// including through a diamond where a shared target is queued twice.
#[test]
fn a_fully_reachable_graph_reports_nothing() {
    let toml = manifest(
        r#"
[stages.entry]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
entry = true
[stages.entry.transitions]
b = "true"
c = "true"

[stages.b]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
[stages.b.transitions]
d = "true"

[stages.c]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
[stages.c.transitions]
d = "true"

[stages.d]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert!(findings.is_empty(), "{:?}", codes(&findings));
}

/// A fan_out stage reaches its worker and merge stages through its own config
/// rather than a transition edge. Following only `transitions` reported both as
/// orphans in a correctly wired blueprint.
#[test]
fn fan_out_worker_and_merge_stages_are_reachable() {
    let toml = manifest(
        r#"
[stages.split]
mode = "fan_out"
worker_stage = "work"
merge_stage = "merge"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
entry = true
[stages.split.transitions]

[stages.work]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
allow_as_worker = true

[stages.merge]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert!(findings.is_empty(), "{:?}", codes(&findings));
}

#[test]
fn a_stage_the_entry_cannot_reach_is_warned_about() {
    let toml = manifest(
        r#"
[stages.a]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
entry = true
[stages.a.transitions]
b = "true"

[stages.b]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5

[stages.orphan]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
"#,
    );
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["unreachable-stage"]);
    assert_eq!(findings[0].stage.as_deref(), Some("orphan"));
}

#[test]
fn a_cycle_with_no_revisit_cap_is_warned_about() {
    let toml = manifest(
        r#"
[stages.a]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
entry = true
[stages.a.transitions]
b = "true"

[stages.b]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
[stages.b.transitions]
a = "true"
"#,
    );
    // Each stage is the "target" of the other's edge, and neither caps
    // revisits, so both ends of the loop are named.
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(
        codes(&findings),
        ["cycle-without-max-revisits", "cycle-without-max-revisits"]
    );
}

#[test]
fn a_cycle_with_max_revisits_is_fine() {
    let toml = manifest(
        r#"
[stages.a]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
max_revisits = 2
entry = true
[stages.a.transitions]
b = "true"

[stages.b]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
max_revisits = 3
[stages.b.transitions]
a = "true"
"#,
    );
    assert!(lint(&toml, &LintEnv::default()).is_empty());
}

/// A self-loop is not a two-stage cycle, and a terminal stage has an empty
/// transitions table rather than none. Both are shapes the walk has to step
/// over without complaining.
#[test]
fn self_loops_and_terminal_stages_are_not_cycles() {
    let toml = manifest(
        r#"
[stages.a]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
entry = true
[stages.a.transitions]
a = "true"
b = "true"

[stages.b]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
[stages.b.transitions]
"#,
    );
    assert!(lint(&toml, &LintEnv::default()).is_empty());
}

/// A blueprint with no transitions anywhere is linear: there is no graph to
/// walk, so the graph checks return before doing anything.
#[test]
fn a_linear_blueprint_has_no_graph_findings() {
    let toml = manifest(
        r#"
[stages.a]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5

[stages.b]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
"#,
    );
    assert!(lint(&toml, &LintEnv::default()).is_empty());
}

/// `Blueprint::validate` rejects an entry_stage or transition target that names
/// no real stage, so the graph walk only meets those through the struct's own
/// public fields. It has to step over them rather than panic.
#[test]
fn the_graph_walk_steps_over_names_that_are_not_stages() {
    use leviath_core::{Blueprint, ContextLayout, Stage, TransitionEdge};

    let model = leviath_core::blueprint::ModelConfig::new(
        "anthropic".to_string(),
        "claude-sonnet-5".to_string(),
    );

    // entry_stage points at a name with no Stage: the BFS pops "ghost" and
    // finds nothing to walk from.
    let mut only = Stage::new("a".to_string(), model.clone());
    only.transitions = Some(HashMap::new());
    only.max_iterations = Some(5);
    let mut bp = Blueprint::new(
        "t".to_string(),
        "t".to_string(),
        vec![only],
        ContextLayout::new(Vec::new(), 1000),
    );
    bp.entry_stage = Some("ghost".to_string());
    // "a" is now unreachable, which is the only thing worth saying.
    assert_eq!(
        codes(&lint_manifest("", &bp, &LintEnv::default())),
        ["unreachable-stage"]
    );

    // A transition target with no Stage: the cycle check finds nothing to ask
    // about the other end of the edge.
    let mut dangling = Stage::new("a".to_string(), model);
    dangling.max_iterations = Some(5);
    dangling.transitions = Some(HashMap::from([(
        "ghost".to_string(),
        TransitionEdge {
            target: "ghost".to_string(),
            condition: Default::default(),
            hint: None,
            transform: Default::default(),
            gate: None,
            stuck: None,
        },
    )]));
    let bp = Blueprint::new(
        "t".to_string(),
        "t".to_string(),
        vec![dangling],
        ContextLayout::new(Vec::new(), 1000),
    );
    assert!(lint_manifest("", &bp, &LintEnv::default()).is_empty());
}

// ─── Finding rendering ────────────────────────────────────────────────────────

#[test]
fn severity_labels_are_the_same_width() {
    assert_eq!(
        LintSeverity::Error.label().len(),
        LintSeverity::Warning.label().len()
    );
    assert_eq!(LintSeverity::Error.label().trim(), "ERR");
    assert_eq!(LintSeverity::Warning.label().trim(), "WARN");
}

#[test]
fn one_line_names_the_stage_when_there_is_one() {
    let stageless = LintFinding::new(LintSeverity::Warning, "c", "something".to_string());
    assert_eq!(stageless.one_line(), "something");
    assert_eq!(
        stageless.in_stage("main").one_line(),
        "stage 'main': something"
    );
}

#[test]
fn is_error_distinguishes_the_severities() {
    assert!(LintFinding::new(LintSeverity::Error, "c", String::new()).is_error());
    assert!(!LintFinding::new(LintSeverity::Warning, "c", String::new()).is_error());
}

// ─── Several defects at once ──────────────────────────────────────────────────

/// The reported blueprint, reconstructed: no mode, no model block, no iteration
/// cap, an unattended stage that can ask a human, a shell grant with no policy,
/// and a typo. Every finding lands, and only the typo is fatal.
#[test]
fn a_thoroughly_broken_stage_reports_each_defect_once() {
    let toml = manifest(
        r#"
[stages.scope]
available_tools = ["read_file", "bash", "ask_user_text", "raed_file"]
"#,
    );
    let env = LintEnv {
        known_tools: known_tools(&["read_file", "bash", "shell", "ask_user_text"]),
        ..LintEnv::default()
    };
    let findings = lint(&toml, &env);
    for code in [
        "stage-missing-mode",
        "stage-missing-model",
        "stage-missing-max-iterations",
        "unknown-tool",
        "blocking-tool-in-autonomous-stage",
        "implicit-shell-policy",
    ] {
        assert_eq!(with_code(&findings, code).len(), 1, "{code}: {findings:?}");
    }
    assert_eq!(findings.iter().filter(|f| f.is_error()).count(), 1);
    assert_eq!(findings.len(), 6, "{:?}", codes(&findings));
}