patina-ai 0.23.0

Context orchestration for AI development - captures and evolves patterns over time
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
use super::*;
use std::io::Write;

fn write_temp_manifest(content: &str) -> tempfile::NamedTempFile {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(content.as_bytes()).unwrap();
    f.flush().unwrap();
    f
}

// =====================================================================
// PluginManifest::from_path
// =====================================================================

#[test]
fn manifest_valid_minimal() {
    let f = write_temp_manifest(
        r#"
[plugin]
name = "test-plugin"
world = "mother-child"

[capabilities]
host_log = true

[provides]
child = "test"
"#,
    );
    let m = PluginManifest::from_path(f.path()).unwrap();
    assert_eq!(m.name, "test-plugin");
    assert_eq!(m.world, PluginWorld::MotherChild);
    assert_eq!(m.version, "0.0.0"); // default
    assert_eq!(m.capabilities, vec!["host_log"]);
    assert_eq!(m.provides.child.as_deref(), Some("test"));
}

#[test]
fn manifest_valid_full() {
    let f = write_temp_manifest(
        r#"
[plugin]
name = "full-plugin"
version = "1.2.3"
description = "A full manifest"
world = "mother-child"
patina_min = "0.17.0"

[capabilities]
host_log = true
filesystem = false

[provides]
child = "full"
commands = ["cmd1", "cmd2"]
"#,
    );
    let m = PluginManifest::from_path(f.path()).unwrap();
    assert_eq!(m.name, "full-plugin");
    assert_eq!(m.version, "1.2.3");
    assert_eq!(m.description, "A full manifest");
    assert_eq!(m.patina_min, "0.17.0");
    // filesystem = false should NOT be in capabilities
    assert_eq!(m.capabilities, vec!["host_log"]);
    assert_eq!(m.provides.commands, vec!["cmd1", "cmd2"]);
}

#[test]
fn manifest_missing_plugin_section() {
    let f = write_temp_manifest("[other]\nfoo = 1\n");
    let err = PluginManifest::from_path(f.path()).unwrap_err();
    assert!(
        err.to_string().contains("missing [plugin] section"),
        "got: {}",
        err
    );
}

#[test]
fn manifest_missing_name() {
    let f = write_temp_manifest("[plugin]\nworld = \"mother-child\"\n");
    let err = PluginManifest::from_path(f.path()).unwrap_err();
    assert!(
        err.to_string().contains("missing plugin.name"),
        "got: {}",
        err
    );
}

#[test]
fn manifest_missing_world() {
    let f = write_temp_manifest("[plugin]\nname = \"test\"\n");
    let err = PluginManifest::from_path(f.path()).unwrap_err();
    assert!(
        err.to_string().contains("missing plugin.world"),
        "got: {}",
        err
    );
}

#[test]
fn manifest_parses_toy_commands() {
    let f = write_temp_manifest(
        r#"
[plugin]
name = "test-plugin"
world = "mother-child"

[capabilities]
host_log = true

[capabilities.toys]
commands = ["git", "patina"]

[provides]
child = "test"
"#,
    );
    let m = PluginManifest::from_path(f.path()).unwrap();
    assert_eq!(m.allowed_toy_commands, vec!["git", "patina"]);
}

#[test]
fn manifest_no_toy_commands_defaults_empty() {
    let f = write_temp_manifest(
        r#"
[plugin]
name = "test-plugin"
world = "mother-child"

[capabilities]
host_log = true

[provides]
child = "test"
"#,
    );
    let m = PluginManifest::from_path(f.path()).unwrap();
    assert!(m.allowed_toy_commands.is_empty());
}

#[test]
fn manifest_invalid_toml() {
    let f = write_temp_manifest("this is not valid toml {{{}}}");
    assert!(PluginManifest::from_path(f.path()).is_err());
}

// =====================================================================
// check_capabilities
// =====================================================================

#[test]
fn capabilities_all_granted() {
    let m = PluginManifest {
        name: "test".into(),
        version: "0.1.0".into(),
        description: String::new(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: None,
            commands: vec![],
            ..Default::default()
        },
    };
    assert!(PluginEngine::check_capabilities(&m).is_ok());
}

#[test]
fn capabilities_empty() {
    let m = PluginManifest {
        name: "test".into(),
        version: "0.1.0".into(),
        description: String::new(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec![],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: None,
            commands: vec![],
            ..Default::default()
        },
    };
    assert!(PluginEngine::check_capabilities(&m).is_ok());
}

#[test]
fn capabilities_denied() {
    let m = PluginManifest {
        name: "test".into(),
        version: "0.1.0".into(),
        description: String::new(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into(), "filesystem".into(), "network".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: None,
            commands: vec![],
            ..Default::default()
        },
    };
    let err = PluginEngine::check_capabilities(&m).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("filesystem"), "got: {}", msg);
    assert!(msg.contains("network"), "got: {}", msg);
    assert!(
        !msg.contains("host_log"),
        "host_log should be granted: {}",
        msg
    );
}

// =====================================================================
// Query param sanitization — scope-reserved keys
// =====================================================================

#[test]
fn sanitize_strips_all_repos_for_current_project() {
    let params = r#"{"query":"test","all_repos":true,"limit":5}"#;
    let result = host_support::sanitize_query_params(params, &QueryScope::CurrentProject);
    let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
    assert!(
        parsed.get("all_repos").is_none(),
        "all_repos should be stripped, got: {}",
        result
    );
    // Non-reserved keys preserved
    assert_eq!(parsed.get("query").unwrap(), "test");
    assert_eq!(parsed.get("limit").unwrap(), 5);
}

#[test]
fn sanitize_strips_repo_for_current_project() {
    let params = r#"{"query":"test","repo":"other-project"}"#;
    let result = host_support::sanitize_query_params(params, &QueryScope::CurrentProject);
    let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
    assert!(
        parsed.get("repo").is_none(),
        "repo should be stripped, got: {}",
        result
    );
    assert_eq!(parsed.get("query").unwrap(), "test");
}

#[test]
fn sanitize_strips_all_reserved_keys() {
    let params =
        r#"{"query":"test","all_repos":true,"repo":"x","project_root":"/tmp","db_path":"/hack"}"#;
    let result = host_support::sanitize_query_params(params, &QueryScope::CurrentProject);
    let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
    for key in &["all_repos", "repo", "project_root", "db_path"] {
        assert!(
            parsed.get(key).is_none(),
            "reserved key '{}' should be stripped, got: {}",
            key,
            result
        );
    }
}

#[test]
fn sanitize_preserves_all_for_all_repos_scope() {
    let params = r#"{"query":"test","all_repos":true,"repo":"other"}"#;
    let result = host_support::sanitize_query_params(params, &QueryScope::AllRepos);
    let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
    assert_eq!(parsed.get("all_repos").unwrap(), true);
    assert_eq!(parsed.get("repo").unwrap(), "other");
}

#[test]
fn sanitize_handles_invalid_json() {
    let params = "not json";
    let result = host_support::sanitize_query_params(params, &QueryScope::CurrentProject);
    assert_eq!(
        result, "not json",
        "invalid JSON should pass through unchanged"
    );
}

#[test]
fn check_capabilities_rejects_unknown_query_kinds() {
    let m = PluginManifest {
        name: "test".into(),
        version: "0.1.0".into(),
        description: String::new(),
        world: PluginWorld::Command,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec!["scry".into(), "magic_oracle".into()],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: None,
            commands: vec![],
            ..Default::default()
        },
    };
    let err = PluginEngine::check_capabilities(&m).unwrap_err();
    assert!(
        err.to_string().contains("magic_oracle"),
        "should reject unknown kind, got: {}",
        err
    );
}

#[test]
fn check_capabilities_accepts_known_query_kinds() {
    let m = PluginManifest {
        name: "test".into(),
        version: "0.1.0".into(),
        description: String::new(),
        world: PluginWorld::Command,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec!["scry".into(), "context".into(), "assay".into()],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: None,
            commands: vec![],
            ..Default::default()
        },
    };
    assert!(PluginEngine::check_capabilities(&m).is_ok());
}

// =====================================================================
// WASM integration — load models.wasm, call handle()
// =====================================================================

/// Load the pre-compiled models.wasm fixture, instantiate it,
/// and verify the full handle() round-trip works.
#[test]
fn wasm_models_child_handle_roundtrip() {
    let wasm_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/patina_plugin_models.wasm");
    if !wasm_path.exists() {
        panic!(
            "test fixture missing: {}\n\
             Build it with: cargo build --release -p patina-plugin-models --target wasm32-wasip2\n\
             Then: cp target/wasm32-wasip2/release/patina_plugin_models.wasm tests/fixtures/",
            wasm_path.display()
        );
    }

    let engine = PluginEngine::new().expect("PluginEngine::new() failed");
    let wasm_bytes = std::fs::read(&wasm_path).expect("failed to read .wasm fixture");
    let component = engine
        .load_component(&wasm_bytes)
        .expect("load_component failed");

    // Use a manifest matching models plugin
    let manifest = PluginManifest {
        name: "patina-models".into(),
        version: "0.1.0".into(),
        description: "test".into(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: Some("models".into()),
            commands: vec![],
            ..Default::default()
        },
    };

    let child = engine
        .instantiate_child(&component, &manifest, None)
        .expect("instantiate_child failed");

    // Verify identity
    assert_eq!(child.name(), "models");

    // Test handle() round-trip: resolve_model action
    let request = crate::mother::ChildRequest {
        action: "resolve_model".into(),
        payload: serde_json::json!({"name": "e5-small"}),
    };
    let response = child.handle(&request).expect("handle() failed");

    // Verify response contains expected path
    let path = response.payload.get("path").and_then(|v| v.as_str());
    assert!(
        path.is_some_and(|p| p.contains("e5-small")),
        "expected path containing 'e5-small', got: {:?}",
        response.payload
    );
}

/// Verify that health() works on a WASM child.
#[test]
fn wasm_models_child_health() {
    let wasm_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/patina_plugin_models.wasm");
    if !wasm_path.exists() {
        return; // Skip if fixture not available
    }

    let engine = PluginEngine::new().unwrap();
    let wasm_bytes = std::fs::read(&wasm_path).unwrap();
    let component = engine.load_component(&wasm_bytes).unwrap();
    let manifest = PluginManifest {
        name: "patina-models".into(),
        version: "0.1.0".into(),
        description: "test".into(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: Some("models".into()),
            commands: vec![],
            ..Default::default()
        },
    };

    let child = engine
        .instantiate_child(&component, &manifest, None)
        .unwrap();
    match child.health() {
        crate::mother::ChildHealth::Healthy => {} // expected
        other => panic!("expected Healthy, got: {:?}", other),
    }
}

// =====================================================================
// WASM integration — load repos.wasm, test toy system end-to-end
// =====================================================================

/// Helper: load repos.wasm fixture and instantiate child.
fn load_repos_child() -> Option<Box<dyn crate::mother::MotherChild>> {
    let wasm_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/patina_plugin_repos.wasm");
    if !wasm_path.exists() {
        return None;
    }

    let engine = PluginEngine::new().unwrap();
    let wasm_bytes = std::fs::read(&wasm_path).unwrap();
    let component = engine.load_component(&wasm_bytes).unwrap();
    let manifest = PluginManifest {
        name: "patina-repos".into(),
        version: "0.1.0".into(),
        description: "test".into(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec!["git".into(), "patina".into()],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: Some("repos".into()),
            commands: vec![],
            ..Default::default()
        },
    };

    Some(
        engine
            .instantiate_child(&component, &manifest, None)
            .unwrap(),
    )
}

/// Repos child: report_repo + check_freshness handle() round-trip.
#[test]
fn wasm_repos_child_handle_roundtrip() {
    let child = match load_repos_child() {
        Some(c) => c,
        None => {
            panic!(
                "test fixture missing: tests/fixtures/patina_plugin_repos.wasm\n\
                 Build: cargo build --release -p patina-plugin-repos --target wasm32-wasip2\n\
                 Copy: cp target/wasm32-wasip2/release/patina_plugin_repos.wasm tests/fixtures/"
            );
        }
    };

    assert_eq!(child.name(), "repos");

    // Report a repo
    let request = crate::mother::ChildRequest {
        action: "report_repo".into(),
        payload: serde_json::json!({
            "name": "test-repo",
            "path": "/tmp/repos/test-repo",
            "last_indexed": 0
        }),
    };
    let response = child.handle(&request).expect("report_repo failed");
    assert_eq!(
        response.payload.get("status").and_then(|v| v.as_str()),
        Some("registered")
    );
    assert_eq!(
        response.payload.get("total_repos").and_then(|v| v.as_u64()),
        Some(1)
    );

    // Check freshness
    let request = crate::mother::ChildRequest {
        action: "check_freshness".into(),
        payload: serde_json::json!({}),
    };
    let response = child.handle(&request).expect("check_freshness failed");
    let stale_count = response.payload.get("stale_count").and_then(|v| v.as_u64());
    assert_eq!(
        stale_count,
        Some(1),
        "repo with last_indexed=0 should be stale"
    );
}

/// Repos child: tick() returns toys for stale repos — end-to-end toy system proof.
#[test]
fn wasm_repos_child_tick_returns_toys() {
    let mut child = match load_repos_child() {
        Some(c) => c,
        None => return, // Skip if fixture not available
    };

    // Report a stale repo (last_indexed = 0 means it's ancient)
    let request = crate::mother::ChildRequest {
        action: "report_repo".into(),
        payload: serde_json::json!({
            "name": "stale-repo",
            "path": "/home/user/.patina/cache/repos/stale-repo",
            "last_indexed": 0
        }),
    };
    child.handle(&request).expect("report_repo failed");

    // tick() should return toys for the stale repo
    let toys = child.tick();
    assert!(
        toys.len() >= 2,
        "expected at least 2 toys (pull + scrape), got {}",
        toys.len()
    );

    // Verify pull toy
    let pull_toy = toys.iter().find(|t| t.name.contains("pull"));
    assert!(pull_toy.is_some(), "expected a pull toy, got: {:?}", toys);
    let pull = pull_toy.unwrap();
    assert_eq!(pull.command, "git");
    assert!(
        pull.args.contains(&"-C".to_string()),
        "pull toy should use -C flag"
    );

    // Verify scrape toy
    let scrape_toy = toys.iter().find(|t| t.name.contains("scrape"));
    assert!(
        scrape_toy.is_some(),
        "expected a scrape toy, got: {:?}",
        toys
    );
    let scrape = scrape_toy.unwrap();
    assert_eq!(scrape.command, "patina");
    assert!(
        scrape.args.contains(&"scrape".to_string()),
        "scrape toy should include 'scrape' arg"
    );
}

/// Repos child: fresh repo produces no toys.
#[test]
fn wasm_repos_child_fresh_repo_no_toys() {
    let mut child = match load_repos_child() {
        Some(c) => c,
        None => return,
    };

    // Report a fresh repo (last_indexed = now)
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let request = crate::mother::ChildRequest {
        action: "report_repo".into(),
        payload: serde_json::json!({
            "name": "fresh-repo",
            "path": "/tmp/repos/fresh-repo",
            "last_indexed": now
        }),
    };
    child.handle(&request).expect("report_repo failed");

    // tick() should return no toys — repo is fresh
    let toys = child.tick();
    assert!(
        toys.is_empty(),
        "expected no toys for fresh repo, got: {:?}",
        toys
    );
}

/// Repos child: health is Healthy when no repos, Degraded when stale.
#[test]
fn wasm_repos_child_health_reflects_staleness() {
    let child = match load_repos_child() {
        Some(c) => c,
        None => return,
    };

    // No repos → Healthy
    match child.health() {
        crate::mother::ChildHealth::Healthy => {}
        other => panic!("expected Healthy with no repos, got: {:?}", other),
    }

    // Add stale repo → Degraded
    let request = crate::mother::ChildRequest {
        action: "report_repo".into(),
        payload: serde_json::json!({
            "name": "old-repo",
            "path": "/tmp/repos/old-repo",
            "last_indexed": 0
        }),
    };
    child.handle(&request).expect("report_repo failed");

    match child.health() {
        crate::mother::ChildHealth::Degraded(_) => {} // expected
        other => panic!("expected Degraded with stale repo, got: {:?}", other),
    }
}

// =====================================================================
// Toy capability gating (F4)
// =====================================================================

/// Repos child with restricted manifest: only "patina" allowed, not "git".
/// Verifies that unauthorized toy commands are filtered out by WasmChild.
#[test]
fn wasm_repos_child_toy_capability_gating() {
    let wasm_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/patina_plugin_repos.wasm");
    if !wasm_path.exists() {
        return; // Skip if fixture not available
    }

    let engine = PluginEngine::new().unwrap();
    let wasm_bytes = std::fs::read(&wasm_path).unwrap();
    let component = engine.load_component(&wasm_bytes).unwrap();

    // Manifest only allows "patina", NOT "git"
    let manifest = PluginManifest {
        name: "patina-repos".into(),
        version: "0.1.0".into(),
        description: "test".into(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec!["patina".into()], // git excluded
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: Some("repos".into()),
            commands: vec![],
            ..Default::default()
        },
    };

    let mut child = engine
        .instantiate_child(&component, &manifest, None)
        .unwrap();

    // Report a stale repo — tick() will return both git pull and patina scrape toys
    let request = crate::mother::ChildRequest {
        action: "report_repo".into(),
        payload: serde_json::json!({
            "name": "gated-repo",
            "path": "/tmp/repos/gated-repo",
            "last_indexed": 0
        }),
    };
    child.handle(&request).expect("report_repo failed");

    let toys = child.tick();

    // Only "patina" toys should pass — "git" toys should be filtered
    for toy in &toys {
        assert_eq!(
            toy.command, "patina",
            "expected only 'patina' toys, got command '{}' in toy '{}'",
            toy.command, toy.name
        );
    }
    assert!(
        !toys.is_empty(),
        "expected at least one patina toy to pass the filter"
    );
}

// =====================================================================
// Benchmarks (C2) — Instant::now() instrumentation
// =====================================================================

/// Measure PluginEngine::new(), Component::new(), instantiate_child(),
/// and handle() round-trip. Run with `cargo test -- --nocapture benchmark`.
#[test]
fn benchmark_plugin_performance() {
    use std::time::Instant;

    let wasm_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/patina_plugin_models.wasm");
    if !wasm_path.exists() {
        return;
    }

    // Warm up the process-wide engine singleton (OnceLock).
    // Without this, the first PluginEngine::new() absorbs Engine::new()
    // cold-start cost (~150ms cranelift JIT init), making the benchmark
    // flaky depending on test execution order.
    let _ = PluginEngine::new();

    // 1. PluginEngine::new() — spec threshold: <100ms
    let t0 = Instant::now();
    let engine = PluginEngine::new().unwrap();
    let engine_ms = t0.elapsed().as_secs_f64() * 1000.0;

    // 2. Component::new() — document compilation time
    let wasm_bytes = std::fs::read(&wasm_path).unwrap();
    let t1 = Instant::now();
    let component = engine.load_component(&wasm_bytes).unwrap();
    let component_ms = t1.elapsed().as_secs_f64() * 1000.0;

    // 3. instantiate_child() total — Component + WasiCtx + Store + init + name
    let manifest = PluginManifest {
        name: "patina-models".into(),
        version: "0.1.0".into(),
        description: "bench".into(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: Some("models".into()),
            commands: vec![],
            ..Default::default()
        },
    };
    let t2 = Instant::now();
    let child = engine
        .instantiate_child(&component, &manifest, None)
        .unwrap();
    let instantiate_ms = t2.elapsed().as_secs_f64() * 1000.0;

    // 4. handle() round-trip — spec threshold: <1ms
    let request = crate::mother::ChildRequest {
        action: "resolve_model".into(),
        payload: serde_json::json!({"name": "e5-small"}),
    };
    // Warm up
    let _ = child.handle(&request).unwrap();
    // Measure 10 iterations
    let t3 = Instant::now();
    let iterations = 10;
    for _ in 0..iterations {
        let _ = child.handle(&request).unwrap();
    }
    let handle_avg_ms = t3.elapsed().as_secs_f64() * 1000.0 / iterations as f64;

    eprintln!();
    eprintln!("=== Plugin System Benchmarks (C2) ===");
    eprintln!(
        "  PluginEngine::new():     {:.2}ms (threshold: <100ms) {}",
        engine_ms,
        if engine_ms < 100.0 { "PASS" } else { "FAIL" }
    );
    eprintln!(
        "  Component::new():        {:.2}ms (156KB WASM cranelift JIT)",
        component_ms
    );
    eprintln!(
        "  instantiate_child():     {:.2}ms (WasiCtx + Store + init + name)",
        instantiate_ms
    );
    eprintln!(
        "  handle() round-trip:     {:.3}ms avg over {} calls (threshold: <1ms) {}",
        handle_avg_ms,
        iterations,
        if handle_avg_ms < 1.0 { "PASS" } else { "FAIL" }
    );
    eprintln!("=====================================");

    // Assert thresholds
    assert!(
        engine_ms < 100.0,
        "PluginEngine::new() took {:.2}ms, threshold is 100ms",
        engine_ms
    );
    assert!(
        handle_avg_ms < 1.0,
        "handle() avg took {:.3}ms, threshold is 1ms",
        handle_avg_ms
    );
}

// =====================================================================
// CommandEngine — doctor.wasm integration tests
// =====================================================================

fn load_doctor_component() -> Option<(CommandEngine, wasmtime::component::Component)> {
    let wasm_path =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/patina_doctor.wasm");
    if !wasm_path.exists() {
        return None;
    }
    let engine = CommandEngine::new().expect("CommandEngine::new() failed");
    let wasm_bytes = std::fs::read(&wasm_path).expect("failed to read doctor wasm");
    let component = engine
        .load_component(&wasm_bytes)
        .expect("load_component failed");
    Some((engine, component))
}

#[test]
fn command_doctor_name() {
    let (engine, component) = match load_doctor_component() {
        Some(ec) => ec,
        None => {
            panic!(
                "test fixture missing: tests/fixtures/patina_doctor.wasm\n\
                 Build: cargo build --release -p patina-doctor --target wasm32-wasip2\n\
                 Copy: cp target/wasm32-wasip2/release/patina_doctor.wasm tests/fixtures/"
            );
        }
    };

    let name = engine
        .get_command_name(&component)
        .expect("get_command_name failed");
    assert_eq!(name, "doctor");
}

#[test]
fn command_doctor_description() {
    let (engine, component) = match load_doctor_component() {
        Some(ec) => ec,
        None => return,
    };

    let desc = engine
        .get_command_description(&component)
        .expect("get_command_description failed");
    assert!(
        desc.contains("health"),
        "expected description to mention 'health', got: {}",
        desc
    );
}

fn load_doctor_manifest() -> PluginManifest {
    PluginManifest {
        name: "patina-doctor".into(),
        version: "0.1.0".into(),
        description: "test".into(),
        world: PluginWorld::Command,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into(), "host_layer".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: None,
            commands: vec!["doctor".into()],
            ..Default::default()
        },
    }
}

#[test]
fn command_doctor_run() {
    let (engine, component) = match load_doctor_component() {
        Some(ec) => ec,
        None => return,
    };

    // Run with --json to avoid terminal output dependencies.
    // Exit code depends on project state — just verify it doesn't panic.
    let manifest = load_doctor_manifest();
    let args = vec!["--json".to_string()];
    let exit_code = engine
        .run_command(&component, &manifest, &args, None)
        .expect("run_command failed");
    // doctor returns 0 (healthy), 1 (error), 2 (warning), or 3 (critical)
    assert!(
        [0, 1, 2, 3].contains(&exit_code),
        "unexpected exit code: {}",
        exit_code
    );
}

// =====================================================================
// validate_http_url — data-level URL sanitization
// =====================================================================

#[test]
fn validate_http_url_valid_https() {
    let domain = host_support::validate_http_url("https://api.github.com/repos").unwrap();
    assert_eq!(domain, "api.github.com");
}

#[test]
fn validate_http_url_valid_https_with_port() {
    let domain = host_support::validate_http_url("https://api.github.com:443/repos").unwrap();
    assert_eq!(domain, "api.github.com");
}

#[test]
fn validate_http_url_rejects_http() {
    let err = host_support::validate_http_url("http://api.github.com/repos").unwrap_err();
    assert!(err.contains("HTTPS"), "expected HTTPS error, got: {}", err);
}

#[test]
fn validate_http_url_rejects_ipv4() {
    let err = host_support::validate_http_url("https://192.168.1.1/api").unwrap_err();
    assert!(err.contains("IP"), "expected IP error, got: {}", err);
}

#[test]
fn validate_http_url_rejects_ipv6() {
    let err = host_support::validate_http_url("https://[::1]/api").unwrap_err();
    assert!(err.contains("IP"), "expected IP error, got: {}", err);
}

#[test]
fn validate_http_url_rejects_localhost() {
    let err = host_support::validate_http_url("https://localhost/api").unwrap_err();
    assert!(
        err.contains("localhost"),
        "expected localhost error, got: {}",
        err
    );
}

#[test]
fn validate_http_url_rejects_invalid() {
    let err = host_support::validate_http_url("not-a-url").unwrap_err();
    assert!(
        err.contains("invalid"),
        "expected invalid URL error, got: {}",
        err
    );
}

// =====================================================================
// Manifest parsing — host_http
// =====================================================================

#[test]
fn manifest_parses_http_domains() {
    let f = write_temp_manifest(
        r#"
[plugin]
name = "http-plugin"
world = "mother-child"

[capabilities]
host_log = true
host_http = ["api.github.com", "hooks.slack.com"]

[provides]
child = "webhook"
"#,
    );
    let m = PluginManifest::from_path(f.path()).unwrap();
    assert_eq!(
        m.host_http_domains,
        vec!["api.github.com", "hooks.slack.com"]
    );
}

#[test]
fn manifest_no_http_domains_defaults_empty() {
    let f = write_temp_manifest(
        r#"
[plugin]
name = "no-http"
world = "mother-child"

[capabilities]
host_log = true

[provides]
child = "test"
"#,
    );
    let m = PluginManifest::from_path(f.path()).unwrap();
    assert!(m.host_http_domains.is_empty());
}

// =====================================================================
// check_capabilities — HTTP domain validation
// =====================================================================

#[test]
fn check_capabilities_rejects_empty_http_domain() {
    let m = PluginManifest {
        name: "test".into(),
        version: "0.1.0".into(),
        description: String::new(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec!["".into()],
        provides: PluginProvides {
            child: None,
            commands: vec![],
            ..Default::default()
        },
    };
    let err = PluginEngine::check_capabilities(&m).unwrap_err();
    assert!(err.to_string().contains("empty"), "got: {}", err);
}

#[test]
fn check_capabilities_rejects_http_domain_with_path() {
    let m = PluginManifest {
        name: "test".into(),
        version: "0.1.0".into(),
        description: String::new(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec!["api.github.com/repos".into()],
        provides: PluginProvides {
            child: None,
            commands: vec![],
            ..Default::default()
        },
    };
    let err = PluginEngine::check_capabilities(&m).unwrap_err();
    assert!(err.to_string().contains("path"), "got: {}", err);
}

#[test]
fn check_capabilities_accepts_valid_http_domains() {
    let m = PluginManifest {
        name: "test".into(),
        version: "0.1.0".into(),
        description: String::new(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec!["api.github.com".into(), "hooks.slack.com".into()],
        provides: PluginProvides {
            child: None,
            commands: vec![],
            ..Default::default()
        },
    };
    assert!(PluginEngine::check_capabilities(&m).is_ok());
}

// =====================================================================
// granted_capabilities — HTTP domains
// =====================================================================

#[test]
fn granted_capabilities_includes_http_domains() {
    let m = PluginManifest {
        name: "test".into(),
        version: "0.1.0".into(),
        description: String::new(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec!["scry".into()],
        host_http_domains: vec!["api.github.com".into()],
        provides: PluginProvides {
            child: None,
            commands: vec![],
            ..Default::default()
        },
    };
    let grants = m.granted_capabilities();
    assert!(grants.http_domains.contains("api.github.com"));
    assert!(grants.query_kinds.contains("scry"));
}

// =====================================================================
// HTTP conformance — defense-in-depth chain verification
// =====================================================================

/// Conformance: domain not in allowlist is denied at call time.
/// Maps to: GrantedCapabilities.http_domains check in Host impl.
#[test]
fn conformance_http_domain_not_in_allowlist_denied() {
    let grants = GrantedCapabilities {
        http_domains: ["api.github.com".to_string()].into_iter().collect(),
        ..Default::default()
    };
    // URL is valid HTTPS with a valid domain
    let domain = host_support::validate_http_url("https://evil.com/steal").unwrap();
    // But domain is NOT in the allowlist
    assert!(
        !grants.http_domains.contains(&domain),
        "evil.com should not be in allowlist"
    );
}

/// Conformance: non-HTTPS URL rejected before any network call.
/// Maps to: validate_http_url scheme check.
#[test]
fn conformance_http_rejects_plaintext() {
    let err = host_support::validate_http_url("http://api.github.com/repos").unwrap_err();
    assert!(
        err.contains("HTTPS"),
        "plaintext HTTP should be rejected: {}",
        err
    );
}

/// Conformance: IP address URL rejected before any network call.
/// Maps to: validate_http_url IP check.
#[test]
fn conformance_http_rejects_ip_address() {
    let err = host_support::validate_http_url("https://10.0.0.1/internal").unwrap_err();
    assert!(err.contains("IP"), "IP address should be rejected: {}", err);
}

/// Conformance: localhost URL rejected before any network call.
/// Maps to: validate_http_url localhost check.
#[test]
fn conformance_http_rejects_localhost() {
    let err = host_support::validate_http_url("https://localhost:8080/api").unwrap_err();
    assert!(
        err.contains("localhost"),
        "localhost should be rejected: {}",
        err
    );
}

// =====================================================================
// TaskEngine — hello-task conformance tests
// =====================================================================

fn load_hello_task_component() -> Option<(task::TaskEngine, wasmtime::component::Component)> {
    let wasm_path =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hello_task.wasm");
    if !wasm_path.exists() {
        return None;
    }
    let engine = task::TaskEngine::new().expect("TaskEngine::new() failed");
    let wasm_bytes = std::fs::read(&wasm_path).expect("failed to read hello-task wasm");
    let component = engine
        .load_component(&wasm_bytes)
        .expect("load_component failed");
    Some((engine, component))
}

fn hello_task_manifest() -> PluginManifest {
    PluginManifest {
        name: "hello-task".into(),
        version: "0.1.0".into(),
        description: "test".into(),
        world: PluginWorld::Task,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into(), "host_layer".into()],
        allowed_toy_commands: vec!["echo".into()],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: None,
            commands: vec![],
            ..Default::default()
        },
    }
}

#[test]
fn task_hello_name() {
    let (engine, component) = match load_hello_task_component() {
        Some(ec) => ec,
        None => {
            panic!(
                "test fixture missing: tests/fixtures/hello_task.wasm\n\
                 Build: cd tests/hello-task && cargo build --release --target wasm32-wasip2\n\
                 Copy: cp tests/hello-task/target/wasm32-wasip2/release/hello_task.wasm tests/fixtures/"
            );
        }
    };

    let name = engine
        .get_task_name(&component)
        .expect("get_task_name failed");
    assert_eq!(name, "hello-task");
}

#[test]
fn task_hello_description() {
    let (engine, component) = match load_hello_task_component() {
        Some(ec) => ec,
        None => return,
    };

    let desc = engine
        .get_task_description(&component)
        .expect("get_task_description failed");
    assert!(
        desc.contains("testing"),
        "expected description to mention 'testing', got: {}",
        desc
    );
}

#[test]
fn task_hello_run_exit_code() {
    let (engine, component) = match load_hello_task_component() {
        Some(ec) => ec,
        None => return,
    };

    let manifest = hello_task_manifest();
    let (exit_code, _toys) = engine
        .run_task(&component, &manifest, &[], None)
        .expect("run_task failed");
    assert_eq!(exit_code, 0, "hello-task should return exit code 0");
}

#[test]
fn task_hello_toys_filtered() {
    let (engine, component) = match load_hello_task_component() {
        Some(ec) => ec,
        None => return,
    };

    let manifest = hello_task_manifest();
    let (_exit_code, toys) = engine
        .run_task(&component, &manifest, &[], None)
        .expect("run_task failed");

    // Should have exactly 1 toy (echo approved, rm filtered out)
    assert_eq!(
        toys.len(),
        1,
        "expected 1 approved toy (echo), got {}",
        toys.len()
    );

    let toy = &toys[0];
    assert_eq!(toy.name, "greet");
    assert_eq!(toy.command, "echo");
    assert_eq!(toy.args, vec!["hello"]);
}

/// Verify that unapproved toy commands are filtered out.
#[test]
fn task_hello_unapproved_toy_denied() {
    let (engine, component) = match load_hello_task_component() {
        Some(ec) => ec,
        None => return,
    };

    // Manifest with NO allowed toy commands
    let manifest = PluginManifest {
        name: "hello-task".into(),
        version: "0.1.0".into(),
        description: "test".into(),
        world: PluginWorld::Task,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into(), "host_layer".into()],
        allowed_toy_commands: vec![], // nothing allowed
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: None,
            commands: vec![],
            ..Default::default()
        },
    };

    let (_exit_code, toys) = engine
        .run_task(&component, &manifest, &[], None)
        .expect("run_task failed");

    // All toys should be filtered out
    assert!(
        toys.is_empty(),
        "expected no toys with empty allowed list, got {}",
        toys.len()
    );
}

// =====================================================================
// PipelineEngine — echo-pipeline conformance tests
// =====================================================================

fn load_echo_pipeline_component(
) -> Option<(pipeline::PipelineEngine, wasmtime::component::Component)> {
    let wasm_path =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/echo_pipeline.wasm");
    if !wasm_path.exists() {
        return None;
    }
    let engine = pipeline::PipelineEngine::new().expect("PipelineEngine::new() failed");
    let wasm_bytes = std::fs::read(&wasm_path).expect("failed to read echo-pipeline wasm");
    let component = engine
        .load_component(&wasm_bytes)
        .expect("load_component failed");
    Some((engine, component))
}

fn echo_pipeline_manifest() -> PluginManifest {
    PluginManifest {
        name: "echo-pipeline".into(),
        version: "0.1.0".into(),
        description: "test".into(),
        world: PluginWorld::Pipeline,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            pipeline_ops: vec!["echo".into()],
            ..Default::default()
        },
    }
}

#[test]
fn pipeline_echo_name() {
    let (engine, component) = match load_echo_pipeline_component() {
        Some(ec) => ec,
        None => {
            panic!(
                "test fixture missing: tests/fixtures/echo_pipeline.wasm\n\
                 Build: cd tests/echo-pipeline && cargo build --release --target wasm32-wasip2\n\
                 Copy: cp tests/echo-pipeline/target/wasm32-wasip2/release/echo_pipeline.wasm tests/fixtures/"
            );
        }
    };

    let name = engine.get_name(&component).expect("get_name failed");
    assert_eq!(name, "echo-pipeline");
}

#[test]
fn pipeline_echo_handle_roundtrip() {
    let (engine, component) = match load_echo_pipeline_component() {
        Some(ec) => ec,
        None => return,
    };

    let manifest = echo_pipeline_manifest();
    let request = r#"{"op":"echo","version":"1","payload":{"key":"value","count":42}}"#;
    let response = engine
        .handle(&component, &manifest, request)
        .expect("handle failed");

    // Echo returns payload unchanged
    let parsed: serde_json::Value = serde_json::from_str(&response).unwrap();
    assert_eq!(parsed.get("key").and_then(|v| v.as_str()), Some("value"));
    assert_eq!(parsed.get("count").and_then(|v| v.as_i64()), Some(42));
}

#[test]
fn pipeline_echo_unknown_op_error() {
    let (engine, component) = match load_echo_pipeline_component() {
        Some(ec) => ec,
        None => return,
    };

    let manifest = echo_pipeline_manifest();
    let request = r#"{"op":"frobnicate","version":"1","payload":{}}"#;
    let result = engine.handle(&component, &manifest, request);

    assert!(
        result.is_err(),
        "unknown op should return error, got: {:?}",
        result
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("unknown op"),
        "error should mention 'unknown op', got: {}",
        err
    );
}

#[test]
fn pipeline_echo_version_mismatch_error() {
    let (engine, component) = match load_echo_pipeline_component() {
        Some(ec) => ec,
        None => return,
    };

    let manifest = echo_pipeline_manifest();
    let request = r#"{"op":"echo","version":"999","payload":{}}"#;
    let result = engine.handle(&component, &manifest, request);

    assert!(
        result.is_err(),
        "version mismatch should return error, got: {:?}",
        result
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("version"),
        "error should mention 'version', got: {}",
        err
    );
}

// =====================================================================
// Cross-world: WASM trap handling conformance test
//
// A guest plugin that deliberately panics. The host MUST catch the
// wasmtime trap and return a clean error — never crash, never unwrap()
// across the WASM boundary. All plugin calls are fallible.
// =====================================================================

/// Load the panic-pipeline WASM fixture.
fn load_panic_pipeline_component() -> Option<(PipelineEngine, wasmtime::component::Component)> {
    let wasm_path =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/panic_pipeline.wasm");
    if !wasm_path.exists() {
        return None;
    }
    let engine = PipelineEngine::new().unwrap();
    let wasm_bytes = std::fs::read(&wasm_path).unwrap();
    let component = engine.load_component(&wasm_bytes).unwrap();
    Some((engine, component))
}

/// WASM trap handling: guest panic in pipeline handle() returns Err, not crash.
#[test]
fn wasm_trap_pipeline_panic_returns_error() {
    let (engine, component) = match load_panic_pipeline_component() {
        Some(ec) => ec,
        None => return,
    };

    let manifest = PluginManifest {
        name: "panic-pipeline".into(),
        version: "0.1.0".into(),
        description: "deliberate panic".into(),
        world: PluginWorld::Pipeline,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            pipeline_ops: vec!["echo".into()],
            ..Default::default()
        },
    };

    let request = r#"{"op":"echo","version":"1","payload":{}}"#;
    let result = engine.handle(&component, &manifest, request);

    // The guest panics — host MUST catch the trap and return Err
    assert!(
        result.is_err(),
        "guest panic should be caught as error, not crash the host"
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("unreachable") || err.contains("panic") || err.contains("trap"),
        "error should indicate a WASM trap, got: {}",
        err
    );
}

// =====================================================================
// Plugin host fragility — spec exit criteria tests
// =====================================================================

// F2: Path traversal in count_layer_files returns 0 (silent reject).
#[test]
fn count_layer_files_rejects_path_traversal() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().to_path_buf();

    // Create layer/core with a .md file so a valid subdir would return >0
    let layer_core = root.join("layer").join("core");
    std::fs::create_dir_all(&layer_core).unwrap();
    std::fs::write(layer_core.join("test.md"), "# test").unwrap();

    // Valid subdir works
    assert_eq!(
        host_support::count_layer_files(&Some(root.clone()), "core"),
        1
    );

    // Path traversal variants — all must return 0
    assert_eq!(
        host_support::count_layer_files(&Some(root.clone()), "../../etc"),
        0,
        "parent dir traversal must return 0"
    );
    assert_eq!(
        host_support::count_layer_files(&Some(root.clone()), "../.."),
        0,
        "bare parent traversal must return 0"
    );
    assert_eq!(
        host_support::count_layer_files(&Some(root.clone()), "/etc"),
        0,
        "absolute path must return 0"
    );
    assert_eq!(
        host_support::count_layer_files(&Some(root.clone()), "core/../../../etc"),
        0,
        "embedded traversal must return 0"
    );

    // None project root also returns 0
    assert_eq!(host_support::count_layer_files(&None, "core"), 0);
}

// F4: Unknown world string rejected at parse time.
#[test]
fn manifest_rejects_unknown_world() {
    let f = write_temp_manifest(
        r#"
[plugin]
name = "bad-world"
world = "oracle"

[capabilities]
host_log = true

[provides]
child = "test"
"#,
    );
    let err = PluginManifest::from_path(f.path()).unwrap_err();
    assert!(
        err.to_string().contains("unknown plugin world") && err.to_string().contains("oracle"),
        "expected 'unknown plugin world: oracle', got: {}",
        err
    );
}

// F4: Pipeline manifest with host_query rejected at check_capabilities.
#[test]
fn check_capabilities_rejects_pipeline_with_query() {
    let m = PluginManifest {
        name: "bad-pipeline".into(),
        version: "0.1.0".into(),
        description: String::new(),
        world: PluginWorld::Pipeline,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into(), "host_query".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec!["scry".into()],
        host_http_domains: vec![],
        provides: PluginProvides {
            pipeline_ops: vec!["echo".into()],
            ..Default::default()
        },
    };
    let err = PluginEngine::check_capabilities(&m).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("host_query") && msg.contains("not allowed for this world"),
        "expected per-world capability rejection for host_query, got: {}",
        msg
    );
}

// F4: Pipeline manifest with host_http also rejected (pipeline only allows host_log).
#[test]
fn check_capabilities_rejects_pipeline_with_http() {
    let m = PluginManifest {
        name: "bad-pipeline".into(),
        version: "0.1.0".into(),
        description: String::new(),
        world: PluginWorld::Pipeline,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into(), "host_http".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec!["evil.com".into()],
        provides: PluginProvides {
            pipeline_ops: vec!["echo".into()],
            ..Default::default()
        },
    };
    let err = PluginEngine::check_capabilities(&m).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("host_http"),
        "expected host_http rejection, got: {}",
        msg
    );
}

// F4: PluginWorld Display impl returns kebab-case strings.
#[test]
fn plugin_world_display() {
    assert_eq!(PluginWorld::MotherChild.to_string(), "mother-child");
    assert_eq!(PluginWorld::Command.to_string(), "command");
    assert_eq!(PluginWorld::Task.to_string(), "task");
    assert_eq!(PluginWorld::Pipeline.to_string(), "pipeline");
}

// F4: PluginWorld round-trips through from_str and Display.
#[test]
fn plugin_world_roundtrip() {
    for world in [
        PluginWorld::MotherChild,
        PluginWorld::Command,
        PluginWorld::Task,
        PluginWorld::Pipeline,
    ] {
        let s = world.to_string();
        let parsed = s.parse::<PluginWorld>().unwrap();
        assert_eq!(parsed, world, "round-trip failed for {}", s);
    }
}

/// WASM trap handling: guest panic in mother-child handle() returns Err, not crash.
#[test]
fn wasm_trap_mother_child_panic_returns_error() {
    // We reuse the panic-pipeline fixture but try to load it as mother-child.
    // This will fail at instantiation (wrong world) — which also proves
    // that world mismatch produces a clean error, not a crash.
    let wasm_path =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/panic_pipeline.wasm");
    if !wasm_path.exists() {
        return;
    }

    let engine = PluginEngine::new().unwrap();
    let wasm_bytes = std::fs::read(&wasm_path).unwrap();
    let component = engine.load_component(&wasm_bytes).unwrap();
    let manifest = PluginManifest {
        name: "wrong-world".into(),
        version: "0.1.0".into(),
        description: "world mismatch".into(),
        world: PluginWorld::MotherChild,
        patina_min: "0.0.0".into(),
        capabilities: vec!["host_log".into()],
        allowed_toy_commands: vec![],
        host_query_kinds: vec![],
        host_http_domains: vec![],
        provides: PluginProvides {
            child: Some("wrong".into()),
            ..Default::default()
        },
    };

    // Instantiation with wrong world should fail cleanly
    let result = engine.instantiate_child(&component, &manifest, None);
    assert!(
        result.is_err(),
        "wrong world instantiation should return Err, not crash"
    );
}