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
//! Blueprint discovery, CRUD, and validation endpoints.

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

use axum::extract::Path as AxumPath;
use axum::extract::Query;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::Json;

use super::types::*;
use leviath_core::manifest::parse_manifest;

/// Resolve the installed agents directory.
///
/// Goes through the shared home resolver so `LEVIATH_HOME` applies here too.
/// Calling `dirs::home_dir()` directly would have these handlers read and
/// write a *different* directory from the one `lev add` installs into
/// whenever that override is set.
pub(super) fn agents_dir() -> PathBuf {
    leviath_core::paths::agents_dir().unwrap_or_default()
}

/// Resolve `<agents_dir>/<name>`, refusing a name that is not a single safe path
/// component.
///
/// `Path::join` neither normalizes `..` nor resists an absolute path, so an
/// unvalidated `name` from a REST body or URL segment reached anywhere on the
/// filesystem: `POST /api/blueprints` with `name = "../../../../tmp/x"` created
/// a directory and wrote attacker-controlled TOML into it, and
/// `DELETE /api/blueprints/{name}` recursively deleted whatever it landed on.
fn blueprint_dir(name: &str) -> Result<PathBuf, (StatusCode, Json<ErrorResponse>)> {
    if !leviath_core::is_safe_path_component(name) {
        return Err((
            StatusCode::BAD_REQUEST,
            Json(ErrorResponse {
                error: format!(
                    "Invalid blueprint name '{name}': names may contain only letters, \
                     digits, '.', '_' and '-'"
                ),
            }),
        ));
    }
    Ok(agents_dir().join(name))
}

/// Collapse a raw discovery scan into the canonical catalog: one blueprint per
/// name, in a stable order.
///
/// Split out of [`discover_blueprints`] because it is the part with the rules,
/// and it can be tested over a hand-built `Vec` instead of a directory tree.
///
/// **Dedup by name, first wins.** `get_blueprint` and `spawn_agent` both resolve
/// a blueprint with `.find(|b| b.name == name)` over this list, so a name
/// reachable from two roots (the installed agents dir and a `config.agent_paths`
/// entry, say) made *which agent actually ran* depend on `read_dir` order, which
/// is a filesystem detail that can differ between two calls on one machine. The
/// dedup happens in scan order, before the sort, so the winner is the one the
/// existing `.find()` already meant to pick - the installed catalog first - and
/// this only makes that choice deterministic rather than changing it.
///
/// **Then sort by name**, which needs no tie-break precisely because the dedup
/// above ran first: after it, no two entries share a name, so name alone is a
/// total order. A list that is merely "whatever the filesystem said" cannot be
/// paginated - a cursor over an unstable order skips and repeats entries.
fn canonicalize(found: Vec<BlueprintInfo>) -> Vec<BlueprintInfo> {
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut kept: Vec<BlueprintInfo> = Vec::with_capacity(found.len());
    for info in found {
        if seen.insert(info.name.clone()) {
            kept.push(info);
        } else {
            tracing::debug!(
                name = %info.name,
                shadowed = %info.path,
                "duplicate blueprint name; keeping the earlier one"
            );
        }
    }
    kept.sort_by(|a, b| a.name.cmp(&b.name));
    kept
}

/// Scan for blueprints from installed agents dir and configured agent_paths.
///
/// The result is deduplicated by name and name-sorted - see [`canonicalize`].
/// Every consumer goes through here (`list_blueprints`, `get_blueprint`,
/// `spawn_agent`), so they all share one answer to "which blueprint is `x`".
pub(super) fn discover_blueprints(config: &crate::config::Config) -> Vec<BlueprintInfo> {
    let mut results = Vec::new();
    let agents = agents_dir();

    let mut dirs_to_scan: Vec<PathBuf> = vec![agents];
    dirs_to_scan.extend(config.agent_paths.iter().cloned());

    for dir in dirs_to_scan {
        if !dir.exists() {
            continue;
        }
        // Check dir itself
        let manifest = dir.join("agent.leviath");
        if manifest.exists() {
            results.extend(read_blueprint_info(&manifest, &dir));
        }
        // Check subdirs. Sorted, because `canonicalize` resolves a duplicate
        // name by taking the first one scanned - and two subdirectories of the
        // *same* root can declare the same name, so without this the winner
        // would still come down to `read_dir` order.
        let mut subdirs: Vec<PathBuf> = std::fs::read_dir(&dir)
            .into_iter()
            .flatten()
            .flatten()
            .map(|entry| entry.path())
            .filter(|p| p.is_dir())
            .collect();
        subdirs.sort();
        for p in subdirs {
            let m = p.join("agent.leviath");
            if m.exists() {
                results.extend(read_blueprint_info(&m, &p));
            }
        }
    }

    canonicalize(results)
}

pub(super) fn read_blueprint_info(manifest_path: &Path, dir: &Path) -> Option<BlueprintInfo> {
    let content = std::fs::read_to_string(manifest_path).ok()?;
    let bp = parse_manifest(&content).ok()?;
    Some(BlueprintInfo {
        name: bp.name,
        version: bp.version,
        description: bp.description,
        path: dir.to_string_lossy().to_string(),
        stages: bp.stages.iter().map(|s| s.name.clone()).collect(),
    })
}

/// Default page size. Comfortably more blueprints than anyone installs, so the
/// common case is one request.
const DEFAULT_LIMIT: usize = 50;
/// Largest page served.
const MAX_LIMIT: usize = 200;

/// `GET /api/blueprints`: the installed agent catalog, paginated and filterable.
///
/// **Breaking change**, taken deliberately in the same release as the rest of
/// this work: the response is now the envelope every paginated route here
/// returns, rather than a bare array. Announced through the `capabilities` list
/// on `GET /api/config` so a client can tell before it asks.
///
/// Worth being plain about the tradeoff: **pagination buys nothing here.**
/// `discover_blueprints` scans every configured directory and TOML-parses every
/// manifest on every request regardless of page size, so a page of ten costs
/// what the whole list costs. The saving is wire bytes on a handful of small
/// objects. The envelope is worth taking for one consistent shape across the
/// API, and `q` is the part with real value - but the catalog is bounded by
/// what a person installs, and this is not what makes it scale.
pub(super) async fn list_blueprints(
    State(state): State<AppState>,
    Query(query): Query<BlueprintsQuery>,
) -> Result<Json<Page<BlueprintInfo>>, (StatusCode, Json<ErrorResponse>)> {
    let descending = match query.order.as_deref() {
        None | Some("asc") => false,
        Some("desc") => true,
        Some(other) => {
            return Err(err(
                StatusCode::BAD_REQUEST,
                format!("Unknown order '{other}': expected asc or desc"),
            ));
        }
    };
    let sort_name = match query.sort.as_deref() {
        None | Some("name") => "name",
        Some("version") => "version",
        Some(other) => {
            return Err(err(
                StatusCode::BAD_REQUEST,
                format!("Unknown sort '{other}': expected name or version"),
            ));
        }
    };
    let limit = match query.limit {
        None => DEFAULT_LIMIT,
        Some(0) => {
            return Err(err(
                StatusCode::BAD_REQUEST,
                "`limit` must be at least 1; omit it for the default".to_string(),
            ));
        }
        Some(n) => n.min(MAX_LIMIT),
    };

    let digest = super::cursor::filter_digest(&[query.q.as_deref().unwrap_or("")]);
    let order_name = if descending { "desc" } else { "asc" };
    let cursor = match query.cursor.as_deref() {
        None => None,
        Some(raw) => Some(
            super::cursor::decode(raw, sort_name, order_name, &digest)
                .map_err(|e| err(StatusCode::BAD_REQUEST, e.message()))?,
        ),
    };

    let mut found = discover_blueprints(&state.config);

    // `q` shares the search primitive but not the framework: three in-memory
    // string fields do not need sources, phases or highlights.
    if let Some(needle) = query.q.as_deref().filter(|s| !s.is_empty()) {
        found.retain(|bp| {
            super::search::find_ignore_ascii_case(&bp.name, needle).is_some()
                || super::search::find_ignore_ascii_case(&bp.description, needle).is_some()
                || bp
                    .stages
                    .iter()
                    .any(|stage| super::search::find_ignore_ascii_case(stage, needle).is_some())
        });
    }

    // `discover_blueprints` already sorts by (name, path); re-sort only when
    // something other than that default was asked for.
    // Sorting by version needs the name to break ties; sorting by name needs
    // nothing, because `canonicalize` already made names unique.
    let key = |bp: &BlueprintInfo| match sort_name {
        "version" => (bp.version.clone(), bp.name.clone()),
        _ => (bp.name.clone(), String::new()),
    };
    found.sort_by(|a, b| {
        if descending {
            key(b).cmp(&key(a))
        } else {
            key(a).cmp(&key(b))
        }
    });

    let total = found.len();
    let mut remaining: Vec<BlueprintInfo> = match cursor {
        None => found,
        Some(ref cursor) => found
            .into_iter()
            .filter(|bp| {
                cursor.precedes(
                    &super::cursor::CursorKey::Text(key(bp).0),
                    &key(bp).1,
                    descending,
                )
            })
            .collect(),
    };

    let has_more = remaining.len() > limit;
    remaining.truncate(limit);
    let next_cursor = has_more.then(|| remaining.last()).flatten().map(|last| {
        let (primary, tiebreak) = key(last);
        super::cursor::encode(
            sort_name,
            order_name,
            &digest,
            super::cursor::CursorKey::Text(primary),
            &tiebreak,
        )
    });

    Ok(Json(Page::new(
        remaining,
        next_cursor,
        Some(total),
        now_secs(),
    )))
}

fn now_secs() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

pub(super) async fn get_blueprint(
    State(state): State<AppState>,
    AxumPath(name): AxumPath<String>,
) -> Result<Json<BlueprintInfo>, StatusCode> {
    let blueprints = discover_blueprints(&state.config);
    blueprints
        .into_iter()
        .find(|b| b.name == name)
        .map(Json)
        .ok_or(StatusCode::NOT_FOUND)
}

pub(super) async fn create_blueprint(
    Json(body): Json<CreateBlueprintReq>,
) -> Result<Json<BlueprintInfo>, (StatusCode, Json<ErrorResponse>)> {
    // Validate manifest first, keeping the parsed Blueprint so the response
    // can be built from it directly below instead of re-reading the file we
    // just wrote (re-reading would make the re-read's error arm a TOCTOU-only,
    // untestable dead branch).
    let bp = parse_manifest(&body.manifest).map_err(|e| {
        (
            StatusCode::BAD_REQUEST,
            Json(ErrorResponse {
                error: format!("Invalid manifest: {}", e),
            }),
        )
    })?;

    let dir = blueprint_dir(&body.name)?;
    std::fs::create_dir_all(&dir).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse {
                error: format!("Failed to create directory: {}", e),
            }),
        )
    })?;

    let manifest_path = dir.join("agent.leviath");
    std::fs::write(&manifest_path, &body.manifest).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse {
                error: format!("Failed to write manifest: {}", e),
            }),
        )
    })?;

    Ok(Json(BlueprintInfo {
        name: bp.name,
        version: bp.version,
        description: bp.description,
        path: dir.to_string_lossy().to_string(),
        stages: bp.stages.iter().map(|s| s.name.clone()).collect(),
    }))
}

pub(super) async fn update_blueprint(
    AxumPath(name): AxumPath<String>,
    Json(body): Json<UpdateBlueprintReq>,
) -> Result<Json<BlueprintInfo>, (StatusCode, Json<ErrorResponse>)> {
    let bp = parse_manifest(&body.manifest).map_err(|e| {
        (
            StatusCode::BAD_REQUEST,
            Json(ErrorResponse {
                error: format!("Invalid manifest: {}", e),
            }),
        )
    })?;

    let dir = blueprint_dir(&name)?;
    let manifest_path = dir.join("agent.leviath");
    if !manifest_path.exists() {
        return Err((
            StatusCode::NOT_FOUND,
            Json(ErrorResponse {
                error: format!("Blueprint '{}' not found", name),
            }),
        ));
    }

    std::fs::write(&manifest_path, &body.manifest).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse {
                error: format!("Failed to write manifest: {}", e),
            }),
        )
    })?;

    Ok(Json(BlueprintInfo {
        name: bp.name,
        version: bp.version,
        description: bp.description,
        path: dir.to_string_lossy().to_string(),
        stages: bp.stages.iter().map(|s| s.name.clone()).collect(),
    }))
}

pub(super) async fn delete_blueprint(
    AxumPath(name): AxumPath<String>,
) -> Result<StatusCode, (StatusCode, Json<ErrorResponse>)> {
    let dir = blueprint_dir(&name)?;
    if !dir.exists() {
        return Err((
            StatusCode::NOT_FOUND,
            Json(ErrorResponse {
                error: format!("Blueprint '{}' not found", name),
            }),
        ));
    }

    std::fs::remove_dir_all(&dir).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse {
                error: format!("Failed to delete blueprint: {}", e),
            }),
        )
    })?;

    Ok(StatusCode::NO_CONTENT)
}

pub(super) async fn validate_blueprint(
    Json(body): Json<ValidateBlueprintReq>,
) -> Json<ValidateResponse> {
    Json(validate_manifest_text(&body.manifest))
}

/// Parse, validate and lint a manifest posted as text.
///
/// A lint error is a real defect (a tool name that resolves to nothing, a
/// permission for a tool the stage never granted), so it makes the response
/// invalid alongside the structural errors. Warnings and notes are reported
/// separately and do not.
///
/// The manifest arrives as text with no directory behind it, so the lint runs
/// against the built-in tool set only: an agent's own `tools/*.rhai` cannot be
/// resolved from a POST body, and an env that claimed otherwise would report
/// every one of them as unknown.
fn validate_manifest_text(manifest: &str) -> ValidateResponse {
    let bp = match parse_manifest(manifest) {
        Ok(bp) => bp,
        Err(e) => return ValidateResponse::invalid(vec![e.to_string()]),
    };
    if let Err(e) = bp.validate() {
        return ValidateResponse::invalid(vec![e.to_string()]);
    }

    let env = crate::lint::LintEnv::offline(std::path::Path::new("."));
    let findings = crate::lint::lint_manifest(manifest, &bp, &env);
    let (errors, warnings): (Vec<_>, Vec<_>) = findings
        .iter()
        .partition(|f| f.severity == crate::lint::LintSeverity::Error);
    let render = |f: &&crate::lint::LintFinding| format!("{} [{}]", f.one_line(), f.code);

    ValidateResponse {
        valid: errors.is_empty(),
        errors: (!errors.is_empty()).then(|| errors.iter().map(render).collect()),
        warnings: (!warnings.is_empty()).then(|| warnings.iter().map(render).collect()),
    }
}

#[cfg(test)]
mod listing_tests {
    use super::*;
    use axum::Router;
    use axum::body::Body;
    use axum::http::Request;
    use axum::routing::get;
    use std::sync::Arc;
    use tokio::sync::broadcast;
    use tower::ServiceExt;

    use crate::config::Config;

    fn manifest(name: &str, description: &str) -> String {
        format!(
            r#"
[agent]
name = "{name}"
version = "1.0.0"
description = "{description}"

[stages.zzstage-work]
system_prompt = "do it"
"#
        )
    }

    /// A catalog directory holding the named blueprints, each name prefixed so
    /// it cannot be confused with an installed one.
    fn catalog(entries: &[(&str, &str)]) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        for (name, description) in entries {
            let name = format!("{FIXTURE_PREFIX}{name}");
            let sub = dir.path().join(&name);
            std::fs::create_dir_all(&sub).unwrap();
            std::fs::write(sub.join("agent.leviath"), manifest(&name, description)).unwrap();
        }
        dir
    }

    /// A fixture's full name.
    fn fx(name: &str) -> String {
        format!("{FIXTURE_PREFIX}{name}")
    }

    /// Fixture names all start with this, so assertions can pick them out of a
    /// catalog that also contains whatever the developer running the tests has
    /// installed.
    ///
    /// `discover_blueprints` always scans the installed agents dir on top of
    /// `agent_paths`, and redirecting `LEVIATH_HOME` to hide it would mutate
    /// process-global env and break every concurrently-running test that
    /// resolves an agents path. So these assert invariants over the discovered
    /// catalog instead of pinning its exact contents - which is the house rule
    /// for agent tests anyway.
    const FIXTURE_PREFIX: &str = "zzfixture-";

    async fn page(dir: &tempfile::TempDir, extra: &str) -> (StatusCode, serde_json::Value) {
        let (tx, _) = broadcast::channel(64);
        let state = AppState {
            config: Arc::new(Config {
                agent_paths: vec![dir.path().to_path_buf()],
                ..Default::default()
            }),
            event_tx: tx,
            control: crate::commands::serve::testutil::no_daemon_client(),
            mcp: crate::commands::serve::mcp::McpAdmin::default(),
            limits: Arc::new(crate::commands::serve::types::ServeLimits::default()),
        };
        let app = Router::new()
            .route("/api/blueprints", get(list_blueprints))
            .with_state(state);
        let req = Request::builder()
            .uri(format!("/api/blueprints{extra}"))
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        let status = resp.status();
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        (
            status,
            serde_json::from_slice(&body).unwrap_or(serde_json::Value::Null),
        )
    }

    /// Just this test's fixtures, in the order the page returned them.
    fn fixture_names(page: &serde_json::Value) -> Vec<String> {
        names(page)
            .into_iter()
            .filter(|n| n.starts_with(FIXTURE_PREFIX))
            .collect()
    }

    fn names(page: &serde_json::Value) -> Vec<String> {
        page["items"]
            .as_array()
            .unwrap()
            .iter()
            .map(|b| b["name"].as_str().unwrap().to_string())
            .collect()
    }

    #[tokio::test]
    async fn the_catalog_pages_through_every_blueprint_exactly_once() {
        let dir = catalog(&[
            ("alpha", "first"),
            ("bravo", "second"),
            ("charlie", "third"),
            ("delta", "fourth"),
        ]);

        let mut seen: Vec<String> = Vec::new();
        let mut cursor: Option<String> = None;
        for _ in 0..10 {
            let extra = match cursor {
                None => "?limit=2".to_string(),
                Some(ref c) => format!("?limit=2&cursor={c}"),
            };
            let (status, body) = page(&dir, &extra).await;
            assert_eq!(status, StatusCode::OK);
            seen.extend(names(&body));
            match body["next_cursor"].as_str() {
                Some(c) => cursor = Some(c.to_string()),
                None => break,
            }
        }
        // Every fixture, once, in order - regardless of what else the catalog
        // holds, and regardless of which page each landed on.
        let got: Vec<String> = seen
            .iter()
            .filter(|n| n.starts_with(FIXTURE_PREFIX))
            .cloned()
            .collect();
        assert_eq!(
            got,
            vec![fx("alpha"), fx("bravo"), fx("charlie"), fx("delta")]
        );
        let mut unique = seen.clone();
        unique.sort();
        unique.dedup();
        assert_eq!(unique.len(), seen.len(), "a blueprint was returned twice");
    }

    /// The part of this change with real value: the catalog is small, so
    /// filtering is what a person actually wants from it.
    #[tokio::test]
    async fn q_matches_name_description_and_stage_names() {
        let dir = catalog(&[
            ("researcher", "digs through papers"),
            ("coder", "writes zzrust"),
        ]);

        // The prefix makes the needle unique to this test's fixtures.
        let (_, by_name) = page(&dir, "?q=ZZFIXTURE-RESEARCH").await;
        assert_eq!(names(&by_name), vec![fx("researcher")]);

        let (_, by_description) = page(&dir, "?q=writes+zzrust").await;
        assert_eq!(names(&by_description), vec![fx("coder")]);

        // Both fixtures declare a stage named after the prefix.
        let (_, by_stage) = page(&dir, "?q=zzstage").await;
        assert_eq!(fixture_names(&by_stage).len(), 2);

        let (_, nothing) = page(&dir, "?q=nothing-like-this-at-all").await;
        assert!(names(&nothing).is_empty());
        assert_eq!(nothing["total"], 0);
    }

    /// Versions collide freely, so this is the sort where the name tie-break
    /// actually does work.
    #[tokio::test]
    async fn the_catalog_can_be_sorted_by_version() {
        let dir = catalog(&[("alpha", "a"), ("bravo", "b")]);
        let (status, body) = page(&dir, "?sort=version&limit=200").await;
        assert_eq!(status, StatusCode::OK);
        // Both fixtures declare 1.0.0, so the shared version leaves the name
        // to order them.
        assert_eq!(fixture_names(&body), vec![fx("alpha"), fx("bravo")]);
    }

    #[tokio::test]
    async fn the_catalog_can_be_ordered_backwards() {
        let dir = catalog(&[("alpha", "a"), ("bravo", "b")]);
        let (_, body) = page(&dir, "?order=desc&limit=200").await;
        assert_eq!(fixture_names(&body), vec![fx("bravo"), fx("alpha")]);
    }

    #[tokio::test]
    async fn a_bad_sort_order_or_limit_is_refused() {
        let dir = catalog(&[("alpha", "a")]);
        for extra in [
            "?sort=whenever",
            "?order=sideways",
            "?limit=0",
            "?cursor=zz",
        ] {
            let (status, _) = page(&dir, extra).await;
            assert_eq!(
                status,
                StatusCode::BAD_REQUEST,
                "expected {extra} to be rejected"
            );
        }
    }

    /// A cursor names a position in one filtered list; changing the filter
    /// under it cannot produce a meaningful continuation.
    #[tokio::test]
    async fn a_cursor_is_bound_to_the_query_that_minted_it() {
        let dir = catalog(&[("alpha", "a"), ("bravo", "b"), ("charlie", "c")]);
        let (_, first) = page(&dir, "?limit=1").await;
        let cursor = first["next_cursor"].as_str().unwrap().to_string();

        let (ok, _) = page(&dir, &format!("?limit=1&cursor={cursor}")).await;
        assert_eq!(ok, StatusCode::OK);

        let (changed, _) = page(&dir, &format!("?limit=1&q=alpha&cursor={cursor}")).await;
        assert_eq!(changed, StatusCode::BAD_REQUEST);
    }
}

#[cfg(test)]
mod canonicalize_tests {
    use super::*;

    fn info(name: &str, path: &str) -> BlueprintInfo {
        BlueprintInfo {
            name: name.to_string(),
            version: "1".to_string(),
            description: String::new(),
            path: path.to_string(),
            stages: vec![],
        }
    }

    /// The scan order decides the winner, so the *earlier* root keeps the name
    /// even though its path sorts later. Getting this backwards would silently
    /// change which agent a spawn runs.
    #[test]
    fn duplicate_names_keep_the_first_scanned_not_the_first_sorted() {
        let out = canonicalize(vec![
            info("coder", "/zzz/installed"),
            info("coder", "/aaa/custom"),
        ]);
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].path, "/zzz/installed");
    }

    #[test]
    fn output_is_name_sorted_with_path_as_the_tie_break() {
        let out = canonicalize(vec![
            info("zebra", "/b"),
            info("alpha", "/z"),
            info("alpha2", "/a"),
        ]);
        let names: Vec<&str> = out.iter().map(|b| b.name.as_str()).collect();
        assert_eq!(names, vec!["alpha", "alpha2", "zebra"]);
    }

    /// Distinct names from the same root all survive - the dedup keys on name,
    /// not on the directory a blueprint was found in.
    #[test]
    fn distinct_names_are_all_kept() {
        let out = canonicalize(vec![info("a", "/1"), info("b", "/2"), info("c", "/3")]);
        assert_eq!(out.len(), 3);
    }

    #[test]
    fn an_empty_scan_canonicalizes_to_an_empty_catalog() {
        assert!(canonicalize(vec![]).is_empty());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::write_test_agent;
    use axum::Router;
    use axum::body::Body;
    use axum::http::Request;
    use axum::routing::{get, post};
    use std::sync::Arc;
    use tokio::sync::broadcast;
    use tower::ServiceExt;

    use crate::config::Config;

    fn test_state_with_path(path: PathBuf) -> AppState {
        let (tx, _) = broadcast::channel(64);
        AppState {
            config: Arc::new(Config {
                agent_paths: vec![path],
                ..Default::default()
            }),
            event_tx: tx,
            control: crate::commands::serve::testutil::no_daemon_client(),
            mcp: crate::commands::serve::mcp::McpAdmin::default(),
            limits: Default::default(),
        }
    }

    fn test_manifest() -> &'static str {
        r#"
[agent]
name = "test-bp"
version = "1.0.0"
description = "A test blueprint"

[stages.plan]
system_prompt = "Plan the work"
"#
    }

    // ─── list_blueprints ──────────────────────────────────────────────────────

    #[tokio::test]
    async fn list_blueprints_empty_path_returns_ok() {
        let dir = tempfile::tempdir().unwrap();
        let state = test_state_with_path(dir.path().to_path_buf());
        let app = Router::new()
            .route("/api/blueprints", get(list_blueprints))
            .with_state(state);
        let req = Request::builder()
            .uri("/api/blueprints")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        // The envelope, not a bare array - the breaking change this release
        // takes deliberately.
        let page: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert!(page["items"].is_array());
        assert!(page["total"].is_number());
        assert!(page["next_cursor"].is_null());
    }

    #[tokio::test]
    async fn list_blueprints_with_agent_returns_it() {
        let dir = tempfile::tempdir().unwrap();
        let agent_dir = dir.path().join("my-agent");
        std::fs::create_dir_all(&agent_dir).unwrap();
        std::fs::write(agent_dir.join("agent.leviath"), test_manifest()).unwrap();

        let state = test_state_with_path(dir.path().to_path_buf());
        let app = Router::new()
            .route("/api/blueprints", get(list_blueprints))
            .with_state(state);
        let req = Request::builder()
            .uri("/api/blueprints")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let page: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let blueprints = page["items"].as_array().unwrap().clone();
        assert_test_bp_listed(&blueprints);
    }

    fn assert_test_bp_listed(blueprints: &[serde_json::Value]) {
        assert!(
            blueprints
                .iter()
                .any(|b| b["name"].as_str() == Some("test-bp")),
            "test-bp should be listed"
        );
    }

    #[test]
    #[should_panic(expected = "test-bp should be listed")]
    fn assert_test_bp_listed_panics_when_missing() {
        assert_test_bp_listed(&[]);
    }

    // ─── get_blueprint ────────────────────────────────────────────────────────

    #[tokio::test]
    async fn get_blueprint_existing_returns_ok() {
        let dir = tempfile::tempdir().unwrap();
        let agent_dir = dir.path().join("test-bp");
        std::fs::create_dir_all(&agent_dir).unwrap();
        std::fs::write(agent_dir.join("agent.leviath"), test_manifest()).unwrap();

        let state = test_state_with_path(dir.path().to_path_buf());
        let app = Router::new()
            .route("/api/blueprints/{name}", get(get_blueprint))
            .with_state(state);
        let req = Request::builder()
            .uri("/api/blueprints/test-bp")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let bp: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(bp["name"].as_str().unwrap(), "test-bp");
        assert_eq!(bp["version"].as_str().unwrap(), "1.0.0");
    }

    #[tokio::test]
    async fn get_blueprint_not_found_returns_404() {
        let dir = tempfile::tempdir().unwrap();
        let state = test_state_with_path(dir.path().to_path_buf());
        let app = Router::new()
            .route("/api/blueprints/{name}", get(get_blueprint))
            .with_state(state);
        let req = Request::builder()
            .uri("/api/blueprints/does-not-exist-xyz")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
    }

    /// Unique blueprint name so tests operating against the real
    /// `~/.leviath/agents` dir (create/update/delete have no path DI seam)
    /// don't collide with each other or with a developer's real agents.
    fn unique_bp_name(prefix: &str) -> String {
        use std::time::{SystemTime, UNIX_EPOCH};
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .subsec_nanos();
        format!("test-bp-{}-{}-{}", prefix, std::process::id(), nanos)
    }

    // ─── create_blueprint ─────────────────────────────────────────────────────

    #[tokio::test]
    async fn create_blueprint_valid_manifest_returns_ok() {
        let name = unique_bp_name("create");
        let manifest = format!(
            r#"
[agent]
name = "{name}"
version = "1.0.0"
description = "Created via API"

[stages.plan]
system_prompt = "Plan the work"
"#
        );

        let app = Router::new().route("/api/blueprints", post(create_blueprint));
        let body = serde_json::json!({ "name": name, "manifest": manifest });
        let req = Request::builder()
            .method("POST")
            .uri("/api/blueprints")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_string(&body).unwrap()))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let info: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(info["name"].as_str().unwrap(), name);
        assert_eq!(info["stages"].as_array().unwrap().len(), 1);

        let _ = std::fs::remove_dir_all(agents_dir().join(&name));
    }

    /// `POST /api/blueprints` with a traversing name created a directory and
    /// wrote attacker-controlled TOML wherever it pointed. `Path::join` neither
    /// normalizes `..` nor resists an absolute path, so the name had to be
    /// validated rather than trusted.
    #[tokio::test]
    async fn create_blueprint_rejects_traversing_names() {
        let manifest = r#"
[agent]
name = "x"
version = "1.0.0"
description = "d"

[stages.plan]
system_prompt = "p"
"#;
        for name in [
            "../../../../tmp/leviath-traversal-probe",
            "/tmp/leviath-traversal-probe",
            "..",
            "a/b",
        ] {
            let app = Router::new().route("/api/blueprints", post(create_blueprint));
            let body = serde_json::json!({ "name": name, "manifest": manifest });
            let req = Request::builder()
                .method("POST")
                .uri("/api/blueprints")
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_string(&body).unwrap()))
                .unwrap();
            let resp = app.oneshot(req).await.unwrap();
            assert_eq!(
                resp.status(),
                axum::http::StatusCode::BAD_REQUEST,
                "name {name:?} should be refused"
            );
        }
        assert!(
            !std::path::Path::new("/tmp/leviath-traversal-probe").exists(),
            "nothing may be created outside the agents directory"
        );
    }

    /// `DELETE /api/blueprints/{name}` reached `fs::remove_dir_all` on the same
    /// unvalidated join - arbitrary recursive deletion for any token holder.
    /// A percent-encoded `..%2f` decodes *after* segment matching, so the
    /// decoded form is what has to be rejected.
    #[tokio::test]
    async fn delete_blueprint_rejects_traversing_names() {
        let victim = std::env::temp_dir().join("leviath-delete-probe");
        std::fs::create_dir_all(&victim).unwrap();

        let app = Router::new().route(
            "/api/blueprints/{name}",
            axum::routing::delete(delete_blueprint),
        );
        let req = Request::builder()
            .method("DELETE")
            .uri("/api/blueprints/..%2f..%2f..%2f..%2ftmp%2fleviath-delete-probe")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::BAD_REQUEST);
        assert!(victim.exists(), "the directory must not have been deleted");
        let _ = std::fs::remove_dir_all(&victim);
    }

    #[tokio::test]
    async fn create_blueprint_dir_creation_failure_returns_500() {
        // Force `create_dir_all` to fail deterministically by pre-creating a
        // regular *file* at the target path - a directory can't be created
        // where a non-directory entry already exists. This is cross-platform:
        // both Unix (ENOTDIR/EEXIST) and Windows (ERROR_ALREADY_EXISTS) refuse
        // to create a directory at a path that's already occupied by a file.
        let name = unique_bp_name("create-fail");
        let dir = agents_dir().join(&name);
        std::fs::create_dir_all(agents_dir()).unwrap();
        std::fs::write(&dir, b"blocking file").unwrap();

        let app = Router::new().route("/api/blueprints", post(create_blueprint));
        let manifest = format!(
            "\n[agent]\nname = \"{name}\"\nversion = \"1.0.0\"\ndescription = \"d\"\n\n[stages.plan]\nsystem_prompt = \"p\"\n"
        );
        let body = serde_json::json!({ "name": name, "manifest": manifest });
        let req = Request::builder()
            .method("POST")
            .uri("/api/blueprints")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_string(&body).unwrap()))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::INTERNAL_SERVER_ERROR);

        let _ = std::fs::remove_file(&dir);
    }

    #[tokio::test]
    async fn create_blueprint_invalid_manifest_returns_400() {
        let app = Router::new().route("/api/blueprints", post(create_blueprint));
        let body = serde_json::json!({
            "name": "bad-agent",
            "manifest": "not valid toml [[[{"
        });
        let req = Request::builder()
            .method("POST")
            .uri("/api/blueprints")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_string(&body).unwrap()))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn create_blueprint_manifest_write_failure_returns_500() {
        // Distinct from `create_blueprint_dir_creation_failure_returns_500`:
        // here `create_dir_all` succeeds (the blueprint dir doesn't already
        // exist as a blocking file), but the manifest *file* write fails --
        // forced by pre-creating a directory at the exact path
        // `<dir>/agent.leviath`, so `std::fs::write` hits EISDIR.
        let name = unique_bp_name("create-manifest-write-fail");
        let dir = agents_dir().join(&name);
        std::fs::create_dir_all(dir.join("agent.leviath")).unwrap();

        let app = Router::new().route("/api/blueprints", post(create_blueprint));
        let manifest = format!(
            "\n[agent]\nname = \"{name}\"\nversion = \"1.0.0\"\ndescription = \"d\"\n\n[stages.plan]\nsystem_prompt = \"p\"\n"
        );
        let body = serde_json::json!({ "name": name, "manifest": manifest });
        let req = Request::builder()
            .method("POST")
            .uri("/api/blueprints")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_string(&body).unwrap()))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::INTERNAL_SERVER_ERROR);

        let _ = std::fs::remove_dir_all(&dir);
    }

    // ─── update_blueprint ─────────────────────────────────────────────────────

    #[tokio::test]
    async fn update_blueprint_write_failure_returns_500() {
        use axum::routing::put;

        // Force `std::fs::write` to fail deterministically: the manifest
        // file exists (so the not-found check passes) but is read-only, so
        // overwriting it fails. `set_readonly` is cross-platform (Unix
        // clears/sets the owner-write bit; Windows toggles the FILE_ATTRIBUTE
        // _READONLY flag), and both platforms' `std::fs::write` honor it.
        let name = unique_bp_name("update-fail");
        let dir = agents_dir().join(&name);
        std::fs::create_dir_all(&dir).unwrap();
        let manifest_path = dir.join("agent.leviath");
        std::fs::write(&manifest_path, test_manifest()).unwrap();
        let original = std::fs::metadata(&manifest_path).unwrap().permissions();
        let mut perms = original.clone();
        perms.set_readonly(true);
        std::fs::set_permissions(&manifest_path, perms).unwrap();

        let app = Router::new().route("/api/blueprints/{name}", put(update_blueprint));
        let body = serde_json::json!({ "manifest": test_manifest() });
        let req = Request::builder()
            .method("PUT")
            .uri(format!("/api/blueprints/{}", name))
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_string(&body).unwrap()))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::INTERNAL_SERVER_ERROR);

        // Put the original permissions back so the directory can be removed on
        // Windows, where a read-only file cannot be deleted. Restoring what was
        // there beats `set_readonly(false)`, which on Unix sets *every* write
        // bit and would hand back a mode the file never had.
        let _ = std::fs::set_permissions(&manifest_path, original);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn update_blueprint_existing_returns_ok() {
        use axum::routing::put;

        let name = unique_bp_name("update");
        let dir = agents_dir().join(&name);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("agent.leviath"),
            format!(
                r#"
[agent]
name = "{name}"
version = "1.0.0"
description = "Original"

[stages.plan]
system_prompt = "Plan"
"#
            ),
        )
        .unwrap();

        let app = Router::new().route("/api/blueprints/{name}", put(update_blueprint));
        let updated_manifest = format!(
            r#"
[agent]
name = "{name}"
version = "2.0.0"
description = "Updated"

[stages.plan]
system_prompt = "Plan"

[stages.implement]
system_prompt = "Implement"
"#
        );
        let body = serde_json::json!({ "manifest": updated_manifest });
        let req = Request::builder()
            .method("PUT")
            .uri(format!("/api/blueprints/{}", name))
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_string(&body).unwrap()))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let info: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(info["version"].as_str().unwrap(), "2.0.0");
        assert_eq!(info["stages"].as_array().unwrap().len(), 2);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn update_blueprint_invalid_manifest_returns_400() {
        use axum::routing::put;

        let app = Router::new().route("/api/blueprints/{name}", put(update_blueprint));
        let body = serde_json::json!({
            "manifest": "not valid toml {{{"
        });
        let req = Request::builder()
            .method("PUT")
            .uri("/api/blueprints/my-agent")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_string(&body).unwrap()))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::BAD_REQUEST);
    }

    /// `PUT` runs the same unvalidated join as `POST` and `DELETE` did, and it
    /// ends in `fs::write` of caller-supplied TOML. A valid manifest with a
    /// traversing *name* must be refused before the path is built, not after.
    #[tokio::test]
    async fn update_blueprint_rejects_traversing_names() {
        use axum::routing::put;

        let manifest = r#"
[agent]
name = "x"
version = "1.0.0"
description = "d"

[stages.plan]
system_prompt = "p"
"#;
        for name in ["..", "%2e%2e", "."] {
            let app = Router::new().route("/api/blueprints/{name}", put(update_blueprint));
            let body = serde_json::json!({ "manifest": manifest });
            let req = Request::builder()
                .method("PUT")
                .uri(format!("/api/blueprints/{name}"))
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_string(&body).unwrap()))
                .unwrap();
            let resp = app.oneshot(req).await.unwrap();
            assert_eq!(
                resp.status(),
                axum::http::StatusCode::BAD_REQUEST,
                "name {name:?} should be refused"
            );
        }
    }

    #[tokio::test]
    async fn update_blueprint_not_found_returns_404() {
        use axum::routing::put;

        let app = Router::new().route("/api/blueprints/{name}", put(update_blueprint));
        let body = serde_json::json!({
            "manifest": r#"
[agent]
name = "no-such-agent"
version = "1.0.0"
description = "Missing"

[stages.run]
system_prompt = "Run"
"#
        });
        let req = Request::builder()
            .method("PUT")
            .uri("/api/blueprints/no-such-agent-xyz-99999")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_string(&body).unwrap()))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
    }

    // ─── delete_blueprint ─────────────────────────────────────────────────────

    #[cfg(unix)]
    #[tokio::test]
    async fn delete_blueprint_removal_failure_returns_500() {
        use axum::routing::delete;
        use std::os::unix::fs::PermissionsExt;

        // Force `remove_dir_all` to fail deterministically: the blueprint
        // dir exists (so the not-found check passes) but is made read-only
        // and non-executable, so unlinking its contents fails with EACCES.
        let name = unique_bp_name("delete-fail");
        let dir = agents_dir().join(&name);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("agent.leviath"), test_manifest()).unwrap();
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap();

        let app = Router::new().route("/api/blueprints/{name}", delete(delete_blueprint));
        let req = Request::builder()
            .method("DELETE")
            .uri(format!("/api/blueprints/{}", name))
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::INTERNAL_SERVER_ERROR);

        // Restore perms so cleanup (and any subsequent test) can remove it.
        let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Windows twin of `delete_blueprint_removal_failure_returns_500`.
    ///
    /// On Unix, directory *write* permission (not the file's own
    /// permission) governs whether an entry can be unlinked from a
    /// directory, so making the directory `0o555` is what forces
    /// `remove_dir_all` to fail there. Windows has no equivalent
    /// "directory write permission" concept via `std::fs::Permissions`, and
    /// marking a file inside the directory read-only does NOT make
    /// `remove_dir_all` fail on Windows: it clears the read-only attribute
    /// before deleting, the same way it silently succeeds through other
    /// removable-but-`readonly` obstacles. A real sharing violation does
    /// still block deletion, though: holding an exclusive (no-share) file
    /// handle open on a file inside the directory for the duration of the
    /// request - the same technique
    /// `session.rs`'s `resolve_task_unreadable_file_returns_error` Windows
    /// twin uses - reliably makes `remove_dir_all` fail there.
    #[cfg(windows)]
    #[tokio::test]
    async fn delete_blueprint_removal_failure_returns_500_windows() {
        use axum::routing::delete;
        use std::fs::OpenOptions;
        use std::os::windows::fs::OpenOptionsExt;

        let name = unique_bp_name("delete-fail-win");
        let dir = agents_dir().join(&name);
        std::fs::create_dir_all(&dir).unwrap();
        let manifest_path = dir.join("agent.leviath");

        // Create the manifest THROUGH an exclusive (no-share) handle and hold
        // it open for the duration of the delete attempt below, so
        // `remove_dir_all` hits a sharing violation trying to unlink
        // `manifest_path`. Writing the file first and reopening it exclusively
        // was a CI flake: Windows Defender / the indexer briefly opens a
        // just-written file, and then it is OUR exclusive open that gets the
        // sharing violation. Creating it exclusively from the start leaves no
        // closed-file window for a scanner to grab.
        let mut locked = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .share_mode(0)
            .open(&manifest_path)
            .unwrap();
        std::io::Write::write_all(&mut locked, test_manifest().as_bytes()).unwrap();
        let _locked = locked;

        let app = Router::new().route("/api/blueprints/{name}", delete(delete_blueprint));
        let req = Request::builder()
            .method("DELETE")
            .uri(format!("/api/blueprints/{}", name))
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::INTERNAL_SERVER_ERROR);

        drop(_locked);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn delete_blueprint_existing_returns_no_content() {
        use axum::routing::delete;

        let name = unique_bp_name("delete");
        let dir = agents_dir().join(&name);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("agent.leviath"), test_manifest()).unwrap();
        assert!(dir.exists());

        let app = Router::new().route("/api/blueprints/{name}", delete(delete_blueprint));
        let req = Request::builder()
            .method("DELETE")
            .uri(format!("/api/blueprints/{}", name))
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::NO_CONTENT);
        assert_dir_removed(&dir);
    }

    fn assert_dir_removed(dir: &std::path::Path) {
        assert!(!dir.exists(), "directory should be removed");
    }

    #[test]
    #[should_panic(expected = "directory should be removed")]
    fn assert_dir_removed_panics_when_still_present() {
        assert_dir_removed(std::path::Path::new("."));
    }

    #[tokio::test]
    async fn delete_blueprint_not_found_returns_404() {
        use axum::routing::delete;

        let app = Router::new().route("/api/blueprints/{name}", delete(delete_blueprint));
        let req = Request::builder()
            .method("DELETE")
            .uri("/api/blueprints/nonexistent-xyz")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
    }

    // ─── validate_blueprint ───────────────────────────────────────────────────

    #[tokio::test]
    async fn validate_blueprint_valid_manifest_returns_ok_valid_true() {
        let app = Router::new().route("/api/blueprints/validate", post(validate_blueprint));
        let body = serde_json::json!({"manifest": test_manifest()});
        let req = Request::builder()
            .method("POST")
            .uri("/api/blueprints/validate")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_string(&body).unwrap()))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let result: ValidateResponse = serde_json::from_slice(&bytes).unwrap();
        assert!(result.valid);
        assert!(result.errors.is_none());
    }

    /// A blueprint the lint objects to but `Blueprint::validate` does not.
    /// `valid` follows the lint errors, and the warnings ride alongside without
    /// affecting it.
    #[tokio::test]
    async fn validate_blueprint_reports_lint_errors_and_warnings_separately() {
        // `raed_file` is an error (it resolves to nothing); the missing
        // `max_iterations` and the unattended `ask_user_text` are warnings.
        let manifest = r#"
[agent]
name = "linty"
version = "0.1.0"

[stages.main]
mode = "autonomous"
model = { models = [{ provider = "anthropic", model = "claude-sonnet-5" }] }
available_tools = ["read_file", "raed_file", "ask_user_text"]

[context.regions]
system = { kind = "pinned", max_tokens = 1000 }
"#;
        let result = validate_manifest_text(manifest);
        assert!(!result.valid);
        let errors = result.errors.expect("the typo is an error");
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("unknown-tool"), "{errors:?}");
        let warnings = result.warnings.expect("the defaults are warnings");
        assert!(
            warnings
                .iter()
                .any(|w| w.contains("stage-missing-max-iterations")),
            "{warnings:?}"
        );
        assert!(
            warnings
                .iter()
                .any(|w| w.contains("blocking-tool-in-autonomous-stage")),
            "{warnings:?}"
        );
    }

    /// Warnings alone leave the blueprint valid.
    #[tokio::test]
    async fn validate_blueprint_with_only_warnings_stays_valid() {
        let manifest = r#"
[agent]
name = "warny"
version = "0.1.0"

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

[context.regions]
system = { kind = "pinned", max_tokens = 1000 }
"#;
        let result = validate_manifest_text(manifest);
        assert!(result.valid);
        assert!(result.errors.is_none());
        assert_eq!(result.warnings.expect("no max_iterations").len(), 1);
    }

    #[tokio::test]
    async fn validate_blueprint_invalid_manifest_returns_ok_valid_false() {
        let app = Router::new().route("/api/blueprints/validate", post(validate_blueprint));
        let body = serde_json::json!({"manifest": "not toml at all [[[{"});
        let req = Request::builder()
            .method("POST")
            .uri("/api/blueprints/validate")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_string(&body).unwrap()))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let result: ValidateResponse = serde_json::from_slice(&bytes).unwrap();
        assert!(!result.valid);
        assert!(result.errors.is_some());
    }

    #[tokio::test]
    async fn validate_blueprint_parses_but_fails_structural_validation_returns_ok_valid_false() {
        // Distinct from the manifest above: this one parses fine as TOML/a
        // Blueprint (Ok(bp) from parse_manifest), but bp.validate()
        // itself rejects it - an entry_stage that doesn't match any defined
        // stage. Exercises the `Ok(bp) => match bp.validate() { Err(e) => .. }`
        // arm, which `validate_blueprint_invalid_manifest_returns_ok_valid_false`
        // (a parse failure) never reaches.
        let app = Router::new().route("/api/blueprints/validate", post(validate_blueprint));
        let manifest = r#"
[agent]
name = "bad-entry-stage"
version = "1.0.0"
description = "Entry stage doesn't exist"
entry_stage = "does-not-exist"

[stages.plan]
system_prompt = "Plan"
"#;
        let body = serde_json::json!({"manifest": manifest});
        let req = Request::builder()
            .method("POST")
            .uri("/api/blueprints/validate")
            .header("content-type", "application/json")
            .body(Body::from(serde_json::to_string(&body).unwrap()))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let result: ValidateResponse = serde_json::from_slice(&bytes).unwrap();
        assert!(!result.valid);
        assert!(
            result
                .errors
                .unwrap()
                .iter()
                .any(|e| e.contains("entry_stage"))
        );
    }

    #[test]
    fn agents_dir_is_under_home() {
        let dir = agents_dir();
        let path_str = dir.to_string_lossy();
        assert!(path_str.contains(".leviath"));
        assert!(path_str.ends_with("agents"));
    }

    #[test]
    fn read_blueprint_info_from_valid_manifest() {
        let dir = tempfile::tempdir().unwrap();
        let manifest_path = dir.path().join("agent.leviath");
        let content = r#"
[agent]
name = "test-bp"
version = "1.0.0"
description = "A test blueprint"

[stages.plan]
system_prompt = "Plan the work"
"#;
        std::fs::write(&manifest_path, content).unwrap();

        let info = read_blueprint_info(&manifest_path, dir.path()).unwrap();
        assert_eq!(info.name, "test-bp");
        assert_eq!(info.version, "1.0.0");
        assert_eq!(info.description, "A test blueprint");
        assert_eq!(info.stages, vec!["plan"]);
        assert_eq!(info.path, dir.path().to_string_lossy());
    }

    #[test]
    fn read_blueprint_info_nonexistent_file_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        let manifest_path = dir.path().join("nonexistent.leviath");
        let result = read_blueprint_info(&manifest_path, dir.path());
        assert!(result.is_none());
    }

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

    #[test]
    fn read_blueprint_info_multiple_stages() {
        let dir = tempfile::tempdir().unwrap();
        let manifest_path = dir.path().join("agent.leviath");
        let content = r#"
[agent]
name = "multi-stage"
version = "0.2.0"
description = "Multi-stage"

[stages.plan]
system_prompt = "Plan"

[stages.implement]
system_prompt = "Implement"

[stages.review]
system_prompt = "Review"
"#;
        std::fs::write(&manifest_path, content).unwrap();

        let info = read_blueprint_info(&manifest_path, dir.path()).unwrap();
        assert_eq!(info.name, "multi-stage");
        assert_eq!(info.stages.len(), 3);
    }

    #[test]
    fn discover_blueprints_with_custom_path() {
        let dir = tempfile::tempdir().unwrap();
        let agent_dir = dir.path().join("my-agent");
        std::fs::create_dir_all(&agent_dir).unwrap();

        let content = r#"
[agent]
name = "discovered"
version = "1.0.0"
description = "Should be discovered"

[stages.work]
system_prompt = "Do work"
"#;
        write_test_agent(agent_dir, content);

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

        let blueprints = discover_blueprints(&config);
        let found = blueprints.iter().find(|b| b.name == "discovered");
        assert_discovered_in_custom_path(found.is_some());
    }

    fn assert_discovered_in_custom_path(found: bool) {
        assert!(found, "should discover agent in custom path");
    }

    #[test]
    #[should_panic(expected = "should discover agent in custom path")]
    fn assert_discovered_in_custom_path_panics_when_not_found() {
        assert_discovered_in_custom_path(false);
    }

    #[test]
    fn discover_blueprints_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        let config = crate::config::Config {
            agent_paths: vec![dir.path().to_path_buf()],
            ..Default::default()
        };
        // Should not panic even with empty dirs
        let blueprints = discover_blueprints(&config);
        // May include blueprints from ~/.leviath/agents, but no crash
        let _ = blueprints;
    }

    #[test]
    fn discover_blueprints_nonexistent_path_is_skipped() {
        let config = crate::config::Config {
            agent_paths: vec![PathBuf::from("/nonexistent/path/unlikely_to_exist_12345")],
            ..Default::default()
        };
        // Should not panic
        let _ = discover_blueprints(&config);
    }

    #[test]
    fn discover_blueprints_direct_manifest_in_dir() {
        let dir = tempfile::tempdir().unwrap();
        let content = r#"
[agent]
name = "direct"
version = "0.1.0"
description = "Directly in scan dir"

[stages.run]
system_prompt = "Run"
"#;
        write_test_agent(dir.path(), content);

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

        let blueprints = discover_blueprints(&config);
        let found = blueprints.iter().find(|b| b.name == "direct");
        assert_discovered_directly_in_scan_dir(found.is_some());
    }

    fn assert_discovered_directly_in_scan_dir(found: bool) {
        assert!(found, "should discover agent.leviath directly in scan dir");
    }

    #[test]
    #[should_panic(expected = "should discover agent.leviath directly in scan dir")]
    fn assert_discovered_directly_in_scan_dir_panics_when_not_found() {
        assert_discovered_directly_in_scan_dir(false);
    }
}