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
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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
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:?}");
}

// ─── dead-end-possible ────────────────────────────────────────────────────────

/// A graph whose only way on is a stage with a spendable revisit budget.
fn strandable(extra_edge: &str) -> String {
    format!(
        r#"
[agent]
name = "strandable"
version = "0.1.0"
description = "a fixture"

[stages.work]
mode = "autonomous"
model = {{ models = [{{ provider = "anthropic", model = "claude-sonnet-5" }}] }}
description = "Work"
max_iterations = 10
available_tools = ["read_file"]
[stages.work.transitions.review]
transform = "direct"
{extra_edge}

[stages.review]
mode = "autonomous"
model = {{ models = [{{ provider = "anthropic", model = "claude-sonnet-5" }}] }}
description = "Review"
max_iterations = 10
max_revisits = 2
available_tools = ["read_file"]

[stages.answer]
mode = "output"
model = {{ models = [{{ provider = "anthropic", model = "claude-sonnet-5" }}] }}
description = "Answer"
max_iterations = 10

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

#[test]
fn a_strandable_stage_is_warned_about() {
    let findings = lint(&strandable(""), &LintEnv::default());
    assert!(
        codes(&findings).contains(&"dead-end-possible"),
        "{:?}",
        codes(&findings)
    );
}

/// The remedy the message names has to be one that silences it, or an author
/// who follows the advice literally is left reaching for the other one - which
/// is a route the model can take on every visit.
#[test]
fn a_dead_end_edge_satisfies_the_check() {
    let toml = strandable(
        "\n[stages.work.transitions.answer]\ncondition = \"dead_end\"\ntransform = \"direct\"\n",
    );
    let findings = lint(&toml, &LintEnv::default());
    assert!(
        !codes(&findings).contains(&"dead-end-possible"),
        "the recommended fix should silence it: {:?}",
        codes(&findings)
    );
}

/// An `error` edge is the other escape the runtime consults on this path.
#[test]
fn an_error_edge_also_satisfies_the_check() {
    let toml = strandable(
        "\n[stages.work.transitions.answer]\ncondition = \"error\"\ntransform = \"direct\"\n",
    );
    assert!(!codes(&lint(&toml, &LintEnv::default())).contains(&"dead-end-possible"));
}

/// `max_iterations` does **not**, and the message no longer suggests it. It
/// fires when a stage burns its iteration budget, which is a different event:
/// on the stranding path `resolve_transition` never consults it, so counting it
/// would silence the warning without preventing the strand.
#[test]
fn a_max_iterations_edge_does_not_satisfy_the_check() {
    let toml = strandable(
        "\n[stages.work.transitions.answer]\ncondition = \"max_iterations\"\ntransform = \"direct\"\n",
    );
    let findings = lint(&toml, &LintEnv::default());
    assert!(
        codes(&findings).contains(&"dead-end-possible"),
        "{:?}",
        codes(&findings)
    );
    let fix = with_code(&findings, "dead-end-possible")[0]
        .fix
        .clone()
        .expect("the finding carries a fix");
    assert!(fix.contains("dead_end"), "{fix}");
    assert!(
        !fix.contains("max_iterations"),
        "it should no longer recommend an inert remedy: {fix}"
    );
}

/// An escape to a stage that can itself run out is no escape, so it does not
/// silence the warning.
#[test]
fn a_dead_end_edge_to_an_exhaustible_stage_does_not_count() {
    let toml = r#"
[agent]
name = "strandable"
version = "0.1.0"
description = "a fixture"

[stages.work]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
description = "Work"
max_iterations = 10
available_tools = ["read_file"]
[stages.work.transitions.review]
transform = "direct"
[stages.work.transitions.fallback]
condition = "dead_end"
transform = "direct"

[stages.review]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
description = "Review"
max_iterations = 10
max_revisits = 2
available_tools = ["read_file"]

# The escape's own target can run out too, so following it only defers the
# strand rather than resolving it.
[stages.fallback]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
description = "Fallback"
max_iterations = 10
max_revisits = 1
available_tools = ["read_file"]

[context.regions]
system = { kind = "pinned", max_tokens = 1000 }
conversation = { kind = "sliding_window", max_items = 50, max_tokens = 10000 }
"#;
    assert!(codes(&lint(toml, &LintEnv::default())).contains(&"dead-end-possible"));
}

// ─── Seeds the parser threw away ──────────────────────────────────────────────

/// A seed table with no key the parser recognizes leaves the region empty.
///
/// This is what a one-character typo looks like, and it is what a "coder-shaped"
/// fixture in this repo shipped with for months: `caller_input` instead of
/// `caller`, silently seeding nothing.
#[test]
fn a_seed_table_with_no_recognized_key_is_warned_about() {
    let toml = format!(
        "{}\n[context.regions.notes]\nkind = \"pinned\"\nmax_tokens = 100\n\
         seed = {{ caller_input = \"task\" }}\n",
        manifest(CLEAN_STAGE)
    );
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(codes(&findings), ["region-seed-not-understood"]);
    assert!(findings[0].message.contains("notes"), "{findings:?}");
}

/// A seed that is neither a string nor a table goes the same way.
#[test]
fn a_seed_of_the_wrong_type_is_warned_about() {
    let toml = format!(
        "{}\n[context.regions.notes]\nkind = \"pinned\"\nmax_tokens = 100\nseed = 42\n",
        manifest(CLEAN_STAGE)
    );
    assert_eq!(
        codes(&lint(&toml, &LintEnv::default())),
        ["region-seed-not-understood"]
    );
}

/// Every recognized form stays silent, so the check cannot become noise.
#[test]
fn the_recognized_seed_forms_are_not_warned_about() {
    for seed in [
        r#""task""#,
        r#""input""#,
        r#"{ caller = "extra" }"#,
        r#"{ literal = "x" }"#,
        r#"{ files = ["a.txt"] }"#,
        r#"{ glob = "*.rs" }"#,
        r#"{ rhai = "\"x\"" }"#,
        r#"{ command = "git ls-files" }"#,
    ] {
        let toml = format!(
            "{}\n[context.regions.notes]\nkind = \"pinned\"\nmax_tokens = 100\nseed = {seed}\n",
            manifest(CLEAN_STAGE)
        );
        let codes = codes(&lint(&toml, &LintEnv::default()));
        assert!(
            !codes.contains(&"region-seed-not-understood"),
            "seed {seed} was reported as unreadable: {codes:?}"
        );
    }
}

/// A region with no `seed` key at all is not a dropped seed.
#[test]
fn a_region_declaring_no_seed_is_not_warned_about() {
    let findings = lint(&manifest(CLEAN_STAGE), &LintEnv::default());
    assert!(
        !codes(&findings).contains(&"region-seed-not-understood"),
        "{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 warned about. The kept one is
    // noted instead, because keeping it is what makes it hold under `--yolo`.
    let findings = lint(&toml, &LintEnv::default());
    assert_eq!(
        codes(&findings),
        ["blocking-tool-in-autonomous-stage", "holds-under-yolo"]
    );
    assert!(
        findings[0].message.contains("ask_user_confirm"),
        "{:?}",
        findings[0].message
    );
    assert!(
        findings[1].message.contains("ask_user_text"),
        "{:?}",
        findings[1].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());
}

/// A permission written under either spelling reaches the tool, so neither is
/// a mismatch to warn about. It used to be: only the name the model calls was
/// looked up, so `bash = "ask"` against a stage granting `shell` was dead, and
/// this check told the author so. Policy resolution now accepts both, and a
/// warning here would send them to fix something that works.
#[test]
fn either_spelling_of_a_permission_settles_the_shell() {
    for (granted, written) in [("shell", "bash"), ("bash", "shell")] {
        let toml = format!(
            "{}\n[tool_permissions]\n{written} = \"ask\"\n",
            manifest(&format!(
                r#"
[stages.main]
mode = "autonomous"
model = {{ models = [{{ provider = "anthropic", model = "claude-sonnet-5" }}] }}
max_iterations = 10
available_tools = ["{granted}"]
"#
            ))
        );
        let found = codes(&lint(&toml, &LintEnv::default()));
        assert!(found.is_empty(), "{granted}/{written}: {found:?}");
    }
}

#[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));
}

// ─── held checkpoints ─────────────────────────────────────────────────────────

/// A checkpoint that holds under `--yolo` is the blueprint working as written,
/// so it is a note. It is worth saying because `--yolo` reads as "run without
/// me", and a run that stops anyway looks like a hang.
#[test]
fn a_checkpoint_that_holds_under_yolo_is_noted() {
    let toml = manifest(
        r#"
[stages.plan]
mode = "interactive_points"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["read_file", "ask_user_text"]
required_tools = ["ask_user_text"]

[[stages.plan.interaction_points]]
name = "plan_approval"
prompt = "Review the plan"
style = "confirm"
unattended = "ask"
"#,
    );
    let all = lint(&toml, &LintEnv::default());
    let findings = with_code(&all, "holds-under-yolo");
    assert_eq!(findings.len(), 2, "the point and the kept tool");
    assert!(findings.iter().all(|f| f.severity == LintSeverity::Note));
    assert!(
        findings.iter().any(|f| f.message.contains("plan_approval")),
        "{findings:?}"
    );
    assert!(
        findings.iter().any(|f| f.message.contains("ask_user_text")),
        "{findings:?}"
    );
    assert!(findings.iter().all(|f| f.stage.as_deref() == Some("plan")));
}

/// A blueprint with nothing held says nothing, so the note does not become
/// background noise on every validate.
#[test]
fn a_blueprint_that_holds_nothing_is_not_noted() {
    let found = codes(&lint(&manifest(CLEAN_STAGE), &LintEnv::default()));
    assert!(!found.contains(&"holds-under-yolo"), "{found:?}");
}

/// A stage granting `bash` and keeping `shell` is one decision, not two - the
/// runtime canonicalises both sides, so the lint has to as well.
#[test]
fn the_blocking_tool_check_canonicalises_required_tools() {
    let toml = manifest(
        r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 10
available_tools = ["ask_user_text", "bash"]
required_tools = ["ask_user_text", "bash"]
"#,
    );
    let found = codes(&lint(&toml, &LintEnv::default()));
    assert!(
        !found.contains(&"blocking-tool-in-autonomous-stage"),
        "{found:?}"
    );
}

// ─── safe_commands ────────────────────────────────────────────────────────────

fn with_safe_commands(body: &str) -> String {
    format!("{}\n[safe_commands]\n{body}\n", manifest(CLEAN_STAGE))
}

/// Declaring `[safe_commands]` is legitimate, so it is a note - but an author
/// who does not know that declaring is not granting ships a block that does
/// nothing on every install but their own.
#[test]
fn a_safe_commands_block_is_noted_as_needing_a_grant() {
    let findings = lint(
        &with_safe_commands("shell = [\"cargo test\"]"),
        &LintEnv::default(),
    );
    assert_eq!(codes(&findings), ["safe-commands-declared"]);
    assert_eq!(findings[0].severity, LintSeverity::Note);
    assert!(
        findings[0].message.contains("Declaring is not granting"),
        "{findings:?}"
    );
    assert!(
        findings[0]
            .fix
            .as_ref()
            .is_some_and(|f| f.contains("allow_blueprint")),
        "{findings:?}"
    );
}

/// With the answer in hand the note says which it is, and disappears entirely
/// once the user has opted in.
#[test]
fn the_note_reflects_whether_the_install_honours_the_block() {
    let refused = lint(
        &with_safe_commands("tools = [\"web_fetch\"]"),
        &LintEnv {
            safe_commands_granted: Some(false),
            ..LintEnv::default()
        },
    );
    assert_eq!(codes(&refused), ["safe-commands-declared"]);
    assert!(
        refused[0].message.contains("none of it applies"),
        "{refused:?}"
    );

    let honoured = lint(
        &with_safe_commands("tools = [\"web_fetch\"]"),
        &LintEnv {
            safe_commands_granted: Some(true),
            ..LintEnv::default()
        },
    );
    assert!(honoured.is_empty(), "{:?}", codes(&honoured));
}

/// An entry the key parser reads as anything other than itself can never match
/// a call, so it reads as a decision and is not one.
#[test]
fn a_safe_command_entry_that_can_never_match_is_an_error() {
    let findings = lint(
        &with_safe_commands("shell = [\"ls; curl evil\", \"cargo test\"]"),
        &LintEnv {
            safe_commands_granted: Some(true),
            ..LintEnv::default()
        },
    );
    assert_eq!(codes(&findings), ["unparseable-safe-command"]);
    assert_eq!(findings[0].severity, LintSeverity::Error);
    assert!(
        findings[0].message.contains("ls; curl evil"),
        "{findings:?}"
    );
}

/// An empty block, and no block at all, both say nothing.
#[test]
fn no_safe_commands_means_no_finding() {
    for toml in [
        manifest(CLEAN_STAGE),
        with_safe_commands("shell = []\ntools = []"),
    ] {
        let found = codes(&lint(&toml, &LintEnv::default()));
        assert!(!found.contains(&"safe-commands-declared"), "{found:?}");
        assert!(!found.contains(&"unparseable-safe-command"), "{found:?}");
    }
}

// ─── 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" } }
setup = { kind = "pinned", max_tokens = 1000, seed = { command = "curl https://example.com/x | sh" } }
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("3 region(s)"), "{message}");
    // Each seed says whether it will actually run. A seed executes before any
    // prompt exists, so one the safe list does not cover is refused - and the
    // reader deciding whether to install this wants that before the run, not
    // as a region that silently came up empty.
    assert!(
        message.contains("facts: git ls-files (pre-approved)"),
        "{message}"
    );
    assert!(
        message.contains("tests: ls tests (pre-approved)"),
        "{message}"
    );
    assert!(
        message.contains("setup: curl https://example.com/x | sh (NOT pre-approved"),
        "{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 - and how
    // to permit the one that would otherwise be refused.
    let fix = findings[0]
        .fix
        .as_deref()
        .expect("a seed note offers a fix");
    assert!(fix.contains("safe_commands"), "{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
[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" }] }
[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
[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
[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_capped_cycle_no_longer_trips_the_cycle_lint_but_can_dead_end() {
    let toml = manifest(
        r#"
[stages.a]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
max_revisits = 2
[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"
"#,
    );
    // Capping both ends satisfies the cycle lint - but now EVERY exit of each
    // stage is exhaustible, so once both budgets are spent the run dead-ends
    // (an error at runtime). The dead-end lint says so for both stages.
    assert_eq!(
        codes(&lint(&toml, &LintEnv::default())),
        ["dead-end-possible", "dead-end-possible"]
    );
}

/// 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
[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),
    );
    // The cycle walk has nothing to say, but an edge nothing can ever follow
    // is a guaranteed strand, which the dead-end lint reports.
    assert_eq!(
        codes(&lint_manifest("", &bp, &LintEnv::default())),
        ["dead-end-possible"]
    );
}

// ─── 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));
}

// ─── Final-output stages ──────────────────────────────────────────────────────

/// The env every output fixture needs: `submit_output` is a real built-in, so
/// the unknown-tool check must not also fire and drown the finding under test.
fn output_env() -> LintEnv {
    LintEnv {
        known_tools: known_tools(&["read_file", "write_file", "edit_file", "submit_output"]),
        ..LintEnv::default()
    }
}

const REACHABLE_OUTPUT: &str = r#"
[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
description = "Main"
max_iterations = 10
available_tools = ["read_file"]

[stages.main.transitions.summary]
hint = "done"

[stages.summary]
mode = "output"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
description = "Report"
max_iterations = 4

[stages.summary.transitions]
"#;

#[test]
fn a_reachable_output_stage_reports_nothing() {
    let findings = lint(&manifest(REACHABLE_OUTPUT), &output_env());
    assert!(findings.is_empty(), "{:?}", codes(&findings));
}

/// An output stage nothing routes to means the run can never produce one - and
/// the blueprint still validates, because the graph is otherwise well-formed.
#[test]
fn an_output_stage_no_edge_reaches_is_an_error() {
    let toml = REACHABLE_OUTPUT.replace("[stages.main.transitions.summary]\nhint = \"done\"\n", "");
    let findings = lint(&manifest(&toml), &output_env());
    let unreachable = with_code(&findings, "output-unreachable");
    assert_eq!(unreachable.len(), 1, "{:?}", codes(&findings));
    assert_eq!(unreachable[0].severity, LintSeverity::Error);
}

/// The quiet one. `allow_complete` offers the model a DONE it may pick instead
/// of routing onward - and it is appended even to a custom transition_prompt,
/// so a stage can offer an exit its own prompt never mentions.
#[test]
fn an_upstream_allow_complete_that_could_skip_the_output_stage_is_flagged() {
    let toml = REACHABLE_OUTPUT.replace(
        "available_tools = [\"read_file\"]\n",
        "available_tools = [\"read_file\"]\nallow_complete = true\n",
    );
    let findings = lint(&manifest(&toml), &output_env());
    let skipped = with_code(&findings, "allow-complete-skips-output");
    assert_eq!(skipped.len(), 1, "{:?}", codes(&findings));
    assert_eq!(skipped[0].stage.as_deref(), Some("main"));
}

/// The output stage's own `allow_complete` (set for it by the mode) is the
/// point, not a defect.
#[test]
fn the_output_stages_own_allow_complete_is_not_flagged() {
    let findings = lint(&manifest(REACHABLE_OUTPUT), &output_env());
    assert!(with_code(&findings, "allow-complete-skips-output").is_empty());
}

/// A blueprint with no output stage at all is not nagged: plenty of agents
/// legitimately produce files and nothing else.
#[test]
fn a_blueprint_with_no_output_stage_is_left_alone() {
    let toml = CLEAN_STAGE.replace(
        "available_tools = [\"read_file\"]\n",
        "available_tools = [\"read_file\"]\nallow_complete = true\n",
    );
    let findings = lint(&manifest(&toml), &LintEnv::default());
    assert!(with_code(&findings, "allow-complete-skips-output").is_empty());
    assert!(with_code(&findings, "output-unreachable").is_empty());
}

/// An output stage that can also write files invites the model to keep working
/// where it was meant to report.
#[test]
fn an_output_stage_that_can_modify_files_is_flagged() {
    let toml = REACHABLE_OUTPUT.replace(
        "description = \"Report\"",
        "description = \"Report\"\navailable_tools = [\"write_file\"]",
    );
    let findings = lint(&manifest(&toml), &output_env());
    let modifies = with_code(&findings, "output-stage-can-modify");
    assert_eq!(modifies.len(), 1, "{:?}", codes(&findings));
    assert_eq!(modifies[0].stage.as_deref(), Some("summary"));
}

/// A declared shape nobody is obliged to produce is a wish, not a contract.
#[test]
fn a_declared_shape_without_require_output_is_flagged() {
    let toml = CLEAN_STAGE.to_string() + "\n[stages.main.output]\nformat = \"a2ui\"\n";
    let findings = lint(&manifest(&toml), &output_env());
    let unrequired = with_code(&findings, "output-shape-not-required");
    assert_eq!(unrequired.len(), 1, "{:?}", codes(&findings));
}

/// The same shape on a stage that must submit is exactly right.
#[test]
fn a_declared_shape_on_a_requiring_stage_reports_nothing() {
    let toml = REACHABLE_OUTPUT.to_string()
        + "\n[stages.summary.output]\nformat = \"a2ui\"\ninstructions = \"one card per finding\"\n";
    let findings = lint(&manifest(&toml), &output_env());
    assert!(findings.is_empty(), "{:?}", codes(&findings));
}

/// `require_output` by hand, without the tool. The manifest parser's hard error
/// normally catches this first; the check exists so `lev validate` still says
/// something useful if a blueprint reaches it another way.
#[test]
fn requiring_an_output_without_the_submit_tool_is_an_error() {
    let mut stage = leviath_core::Stage::new(
        "summary".to_string(),
        leviath_core::blueprint::ModelConfig::new("anthropic".to_string(), "m".to_string()),
    );
    stage.available_tools = vec!["read_file".to_string()];
    stage.require_output = true;
    let findings = lint_output_stage(&stage);
    let missing = with_code(&findings, "output-missing-submit-tool");
    assert_eq!(missing.len(), 1, "{:?}", codes(&findings));
    assert_eq!(missing[0].severity, LintSeverity::Error);
}

// ─── compact-summarizes-deliverable (#369) ───────────────────────────────────

/// The reported shape: a `required` region and a bare `compact` edge, which
/// together mean the stage's own deliverable is paraphrased on the way out.
#[test]
fn a_bare_compact_over_a_required_region_is_warned_about() {
    let toml = manifest(
        r#"
[stages.verify]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
[stages.verify.transitions.answer]
transform = "compact"

[stages.answer]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
"#,
    )
    .replace(
        "conversation = { kind = \"sliding_window\", max_items = 50, max_tokens = 10000 }",
        "conversation = { kind = \"sliding_window\", max_items = 50, max_tokens = 10000 }\n\
         results = { kind = \"sliding_window\", max_items = 20, max_tokens = 8000, required = true }",
    );
    let findings = lint(&toml, &LintEnv::default());
    let found = with_code(&findings, "compact-summarizes-deliverable");
    assert_eq!(found.len(), 1, "{:?}", codes(&findings));
    assert!(found[0].message.contains("results"), "{}", found[0].message);
}

/// Silenced by the flag that fixes it, or the warning would be advice nobody
/// can act on.
#[test]
fn a_region_declared_not_summarizable_is_not_warned_about() {
    let toml = manifest(
        r#"
[stages.verify]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
[stages.verify.transitions.answer]
transform = "compact"

[stages.answer]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
"#,
    )
    .replace(
        "conversation = { kind = \"sliding_window\", max_items = 50, max_tokens = 10000 }",
        "conversation = { kind = \"sliding_window\", max_items = 50, max_tokens = 10000 }\n\
         results = { kind = \"sliding_window\", max_items = 20, max_tokens = 8000, required = true, summarizable = false }",
    );
    let findings = lint(&toml, &LintEnv::default());
    assert!(
        with_code(&findings, "compact-summarizes-deliverable").is_empty(),
        "{:?}",
        codes(&findings)
    );
}

/// A pinned region is never handed to the summarizer in the first place, so
/// warning about one would be noise.
#[test]
fn a_pinned_required_region_is_not_warned_about() {
    let toml = manifest(
        r#"
[stages.verify]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
[stages.verify.transitions.answer]
transform = "compact"

[stages.answer]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
"#,
    )
    .replace(
        "system = { kind = \"pinned\", max_tokens = 1000 }",
        "system = { kind = \"pinned\", max_tokens = 1000, required = true }",
    );
    let findings = lint(&toml, &LintEnv::default());
    assert!(
        with_code(&findings, "compact-summarizes-deliverable").is_empty(),
        "{:?}",
        codes(&findings)
    );
}

/// No compact edge, nothing to say - so the check is about the pairing rather
/// than about declaring a required region at all.
#[test]
fn a_required_region_with_no_compact_edge_is_not_warned_about() {
    let toml = manifest(
        r#"
[stages.verify]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
[stages.verify.transitions.answer]
transform = "direct"

[stages.answer]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
max_iterations = 5
"#,
    )
    .replace(
        "conversation = { kind = \"sliding_window\", max_items = 50, max_tokens = 10000 }",
        "conversation = { kind = \"sliding_window\", max_items = 50, max_tokens = 10000 }\n\
         results = { kind = \"sliding_window\", max_items = 20, max_tokens = 8000, required = true }",
    );
    let findings = lint(&toml, &LintEnv::default());
    assert!(
        with_code(&findings, "compact-summarizes-deliverable").is_empty(),
        "{:?}",
        codes(&findings)
    );
}