codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
use tempfile::TempDir;

fn create_skill_dir(tmpdir: &TempDir, skill_name: &str, skill_content: &str) {
    let skill_dir = tmpdir.path().join("skills").join(skill_name);
    std::fs::create_dir_all(&skill_dir).unwrap();
    std::fs::write(skill_dir.join("SKILL.md"), skill_content).unwrap();
}

#[test]
fn discovery_metrics_reset_and_snapshot_are_exact() {
    super::reset_discovery_metrics();
    assert_eq!(
        super::discovery_metrics_snapshot(),
        super::SkillDiscoveryMetrics::default()
    );

    let tmpdir = TempDir::new().unwrap();
    let skills_root = tmpdir.path().join("skills");
    let vendor_root = skills_root.join("vendor");
    write_skill(&vendor_root, "demo", "A demo skill", "Instructions");

    let registry = super::SkillRegistry::discover(&skills_root);
    assert_eq!(registry.len(), 1);
    assert_eq!(
        super::discovery_metrics_snapshot(),
        super::SkillDiscoveryMetrics {
            root_discovery_calls: 1,
            directories_visited: 2,
            skill_md_read_attempts: 2,
        }
    );

    super::reset_discovery_metrics();
    let missing_root = tmpdir.path().join("missing");
    let _registry = super::SkillRegistry::discover(&missing_root);
    assert_eq!(
        super::discovery_metrics_snapshot(),
        super::SkillDiscoveryMetrics {
            root_discovery_calls: 1,
            directories_visited: 0,
            skill_md_read_attempts: 0,
        }
    );

    super::reset_discovery_metrics();
    assert_eq!(
        super::discovery_metrics_snapshot(),
        super::SkillDiscoveryMetrics::default()
    );
}

#[test]
fn prompt_warning_sanitizer_scrubs_stale_conventional_home_roots() {
    let workspace = std::path::Path::new("/tmp/workspace");
    let warning = "Skill at /Users/private-name/.agents/skills/a/SKILL.md is shadowed by /home/other/.skills/a/SKILL.md";
    let sanitized = super::sanitize_prompt_path_text(warning, workspace);
    assert_eq!(
        sanitized,
        "Skill at ~/.agents/skills/a/SKILL.md is shadowed by ~/.skills/a/SKILL.md"
    );
}

#[test]
fn render_available_skills_context_lists_paths_and_usage() {
    let tmpdir = TempDir::new().unwrap();
    create_skill_dir(
        &tmpdir,
        "test-skill",
        "---\nname: test-skill\ndescription: A test skill\n---\nDo something special",
    );

    let rendered = crate::skills::render_available_skills_context(&tmpdir.path().join("skills"))
        .expect("skill context");

    // #4632: paths render relative to the skills base dir (privacy-safe),
    // so the assertion checks the workspace-relative form.
    let expected_path = std::path::Path::new("test-skill")
        .join("SKILL.md")
        .display()
        .to_string();

    assert!(rendered.contains("## Skills"));
    assert!(rendered.contains("- test-skill: A test skill"));
    assert!(rendered.contains("load the exact skill before applying it"));
    assert!(rendered.contains("do not expand tool, approval, or trust authority"));
    assert!(
        rendered.contains(&expected_path),
        "expected path {expected_path:?} not in rendered output"
    );
    assert!(!rendered.contains(tmpdir.path().to_str().unwrap_or("/nonexistent")));
    assert!(rendered.contains("### Usage"));
}

#[test]
fn workspace_prompt_omits_disabled_skills_without_configured_directory() {
    let _env_lock = crate::test_support::lock_test_env();
    let tmpdir = TempDir::new().unwrap();
    let home = tmpdir.path().join("home");
    let workspace = tmpdir.path().join("workspace");
    let skills_root = workspace.join(".agents").join("skills");
    std::fs::create_dir_all(&home).unwrap();
    write_skill(
        &skills_root,
        "enabled-skill",
        "Enabled skill",
        "Instructions",
    );
    write_skill(
        &skills_root,
        "disabled-skill",
        "Disabled skill",
        "Instructions",
    );
    let _home = crate::test_support::EnvVarGuard::set("HOME", &home);
    let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", &home);
    let _codewhale_home =
        crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale"));

    let mut state = crate::skill_state::SkillStateStore::load_default().unwrap();
    state.set_enabled("disabled-skill", false).unwrap();
    super::clear_skill_discovery_cache();

    let rendered = super::render_available_skills_context_for_workspace_with_mode_and_plugins(
        &workspace,
        super::SkillDiscoveryMode::Compatible,
        "en",
        None,
    )
    .expect("enabled skill context");

    assert!(rendered.contains("enabled-skill"));
    assert!(!rendered.contains("disabled-skill"));
}

#[test]
fn render_available_skills_context_uses_real_dir_name_not_frontmatter_name() {
    // Regression: when a community-installed or manually-placed skill
    // lives in a directory whose name differs from its frontmatter
    // `name`, the rendered prompt must point to the real on-disk file
    // path, not <skills_dir>/<frontmatter-name>/SKILL.md (which does
    // not exist).
    let tmpdir = TempDir::new().unwrap();
    create_skill_dir(
        &tmpdir,
        "weird-dir-name",
        "---\nname: friendly-name\ndescription: drift case\n---\nbody",
    );

    let rendered = crate::skills::render_available_skills_context(&tmpdir.path().join("skills"))
        .expect("skill context");

    // #4632: rendered relative to the skills base dir; the regression
    // intent (real dir name, not frontmatter name) is unchanged.
    let real_path = std::path::Path::new("weird-dir-name")
        .join("SKILL.md")
        .display()
        .to_string();
    let stale_path = std::path::Path::new("friendly-name")
        .join("SKILL.md")
        .display()
        .to_string();

    assert!(
        rendered.contains(&real_path),
        "expected real on-disk path {real_path:?} in rendered output, got:\n{rendered}"
    );
    assert!(
        !rendered.contains(&stale_path),
        "rendered output must not invent a path under the frontmatter name:\n{rendered}"
    );
}

#[test]
fn render_available_skills_context_returns_none_when_empty() {
    let tmpdir = TempDir::new().unwrap();
    let empty = tmpdir.path().join("skills");
    std::fs::create_dir_all(&empty).unwrap();
    assert!(crate::skills::render_available_skills_context(&empty).is_none());

    let missing = tmpdir.path().join("does-not-exist");
    assert!(crate::skills::render_available_skills_context(&missing).is_none());
}

#[test]
fn render_skills_block_surfaces_warnings_when_no_skill_loaded() {
    let tmpdir = TempDir::new().unwrap();
    let mut registry = super::SkillRegistry::default();
    registry
        .warnings
        .push("broken skill could not be parsed".to_string());

    let rendered =
        super::render_skills_block(&registry, "en", tmpdir.path()).expect("warning-only block");

    assert!(rendered.contains("### Skill load warnings"));
    assert!(rendered.contains("broken skill could not be parsed"));
    assert!(rendered.chars().count() <= super::MAX_AVAILABLE_SKILLS_CHARS);
}

#[test]
fn render_available_skills_context_truncates_long_descriptions() {
    let tmpdir = TempDir::new().unwrap();
    let long_desc = "x".repeat(2_000);
    let body = format!("---\nname: bigdesc\ndescription: {long_desc}\n---\nbody");
    create_skill_dir(&tmpdir, "bigdesc", &body);

    let rendered = crate::skills::render_available_skills_context(&tmpdir.path().join("skills"))
        .expect("skill context");

    let max = super::MAX_SKILL_DESCRIPTION_CHARS;
    assert!(rendered.contains('โ€ฆ'), "expected truncation marker");
    assert!(
        !rendered.contains(&"x".repeat(max + 1)),
        "untruncated long run should not appear"
    );
}

#[test]
fn render_available_skills_context_collapses_internal_whitespace() {
    let tmpdir = TempDir::new().unwrap();
    create_skill_dir(
        &tmpdir,
        "spaced-skill",
        "---\nname: spaced-skill\ndescription: alpha  \t  beta   gamma\n---\nbody",
    );

    let rendered = crate::skills::render_available_skills_context(&tmpdir.path().join("skills"))
        .expect("skill context");

    let line = rendered
        .lines()
        .find(|l| l.starts_with("- spaced-skill:"))
        .expect("skill line");
    assert!(line.contains("alpha beta gamma"), "got: {line:?}");
}

#[test]
fn render_available_skills_context_omits_overflowing_skills() {
    let tmpdir = TempDir::new().unwrap();
    let big_desc = "y".repeat(super::MAX_SKILL_DESCRIPTION_CHARS - 20);
    for i in 0..200 {
        let body = format!("---\nname: skill-{i:03}\ndescription: {big_desc}\n---\nbody");
        create_skill_dir(&tmpdir, &format!("skill-{i:03}"), &body);
    }

    let rendered = crate::skills::render_available_skills_context(&tmpdir.path().join("skills"))
        .expect("skill context");

    assert!(
        rendered.contains("additional skills omitted"),
        "expected overflow notice"
    );
    assert!(
        rendered.chars().count() <= super::MAX_AVAILABLE_SKILLS_CHARS,
        "rendered length must stay within the complete block budget"
    );
}

#[test]
fn render_skills_block_holds_budget_with_five_digit_omission_counts() {
    let tmpdir = TempDir::new().unwrap();
    let mut registry = super::SkillRegistry::default();
    for i in 0..11_000 {
        registry.skills.push(super::Skill {
            name: format!("skill-{i:05}"),
            description: "x".to_string(),
            localized_descriptions: std::collections::HashMap::new(),
            invocation: super::SkillInvocation::ModelAndUser,
            aliases: Vec::new(),
            body: "body".to_string(),
            path: tmpdir.path().join(format!("skill-{i:05}/SKILL.md")),
            source: super::SkillSource::Native,
        });
        registry.warnings.push(format!("warning {i:05}"));
    }

    let rendered =
        super::render_skills_block(&registry, "en", tmpdir.path()).expect("skill context");
    let omitted_skills = rendered
        .lines()
        .find(|line| line.contains("additional skills omitted"))
        .and_then(|line| line.split_whitespace().nth(2))
        .and_then(|count| count.parse::<usize>().ok())
        .expect("skill omission count");
    let omitted_warnings = rendered
        .lines()
        .find(|line| line.contains("additional warnings omitted"))
        .and_then(|line| line.split_whitespace().nth(2))
        .and_then(|count| count.parse::<usize>().ok())
        .expect("warning omission count");

    assert!(omitted_skills > 9_999, "fixture must exercise five digits");
    assert!(
        omitted_warnings > 9_999,
        "fixture must exercise five digits"
    );
    assert!(rendered.chars().count() <= super::MAX_AVAILABLE_SKILLS_CHARS);
}

#[test]
fn explicit_only_skills_do_not_reduce_ambient_index_capacity() {
    let tmpdir = TempDir::new().unwrap();
    let mut registry = super::SkillRegistry::default();
    for i in 0..6 {
        registry.skills.push(super::Skill {
            name: format!("visible-{i:03}"),
            description: "x".repeat(246),
            localized_descriptions: std::collections::HashMap::new(),
            invocation: super::SkillInvocation::ModelAndUser,
            aliases: Vec::new(),
            body: "body".to_string(),
            path: tmpdir.path().join(format!("visible-{i:03}/SKILL.md")),
            source: super::SkillSource::Native,
        });
    }

    let baseline =
        super::render_skills_block(&registry, "en", tmpdir.path()).expect("skill context");
    assert!(!baseline.contains("additional skills omitted"));

    let mut with_explicit_only = registry.clone();
    for i in 0..10_000 {
        with_explicit_only.skills.push(super::Skill {
            name: format!("explicit-{i:05}"),
            description: String::new(),
            localized_descriptions: std::collections::HashMap::new(),
            invocation: super::SkillInvocation::ExplicitOnly,
            aliases: Vec::new(),
            body: "body".to_string(),
            path: tmpdir.path().join(format!("explicit-{i:05}/SKILL.md")),
            source: super::SkillSource::Native,
        });
    }

    let rendered = super::render_skills_block(&with_explicit_only, "en", tmpdir.path())
        .expect("skill context");
    assert_eq!(rendered, baseline);
}

#[test]
fn render_skills_block_preserves_registry_precedence_under_prompt_budget() {
    let tmpdir = TempDir::new().unwrap();
    let mut registry = super::SkillRegistry::default();
    registry.skills.push(super::Skill {
        name: "workspace-priority".to_string(),
        description: "must survive truncation".to_string(),
        localized_descriptions: std::collections::HashMap::new(),
        invocation: super::SkillInvocation::ModelAndUser,
        aliases: Vec::new(),
        body: "body".to_string(),
        path: tmpdir
            .path()
            .join(".claude")
            .join("skills")
            .join("workspace-priority")
            .join("SKILL.md"),
        source: super::SkillSource::Native,
    });

    let big_desc = "y".repeat(super::MAX_SKILL_DESCRIPTION_CHARS - 20);
    for i in 0..200 {
        registry.skills.push(super::Skill {
            name: format!("aaa-global-{i:03}"),
            description: big_desc.clone(),
            localized_descriptions: std::collections::HashMap::new(),
            invocation: super::SkillInvocation::ModelAndUser,
            aliases: Vec::new(),
            body: "body".to_string(),
            path: tmpdir
                .path()
                .join(".deepseek")
                .join("skills")
                .join(format!("aaa-global-{i:03}"))
                .join("SKILL.md"),
            source: super::SkillSource::Native,
        });
    }

    let rendered =
        super::render_skills_block(&registry, "en", tmpdir.path()).expect("skill context");
    assert!(
        rendered.contains("workspace-priority"),
        "higher-precedence workspace skills must not be reordered behind globals:\n{rendered}"
    );
    assert!(
        rendered.contains("additional skills omitted"),
        "fixture should exceed prompt budget"
    );
}

// --- Localized skill descriptions (#3354) ------------------------------

#[test]
fn parse_skill_collects_localized_description_frontmatter() {
    let content = "---\n\
name: demo\n\
description: A demo skill\n\
description_zh: ไธ€ไธชๆผ”็คบๆŠ€่ƒฝ\n\
description_zh-Hant: ไธ€ๅ€‹็คบ็ฏ„ๆŠ€่ƒฝ\n\
---\n\
body";
    let skill = super::SkillRegistry::parse_skill(std::path::Path::new("SKILL.md"), content)
        .expect("parse should succeed");
    assert_eq!(skill.description, "A demo skill");
    assert_eq!(
        skill.localized_descriptions.get("zh").map(String::as_str),
        Some("ไธ€ไธชๆผ”็คบๆŠ€่ƒฝ")
    );
    // Frontmatter keys are lowercased, so zh-Hant is stored as zh-hant.
    assert_eq!(
        skill
            .localized_descriptions
            .get("zh-hant")
            .map(String::as_str),
        Some("ไธ€ๅ€‹็คบ็ฏ„ๆŠ€่ƒฝ")
    );
}

#[test]
fn parse_skill_exposes_invocation_and_alias_metadata() {
    let content = "---\n\
name: spreadsheets\n\
description: Spreadsheet workflows\n\
invocation: explicit-only\n\
aliases-for: xlsx, spreadsheet\n\
---\n\
body";
    let skill = super::SkillRegistry::parse_skill(std::path::Path::new("SKILL.md"), content)
        .expect("parse should succeed");

    assert_eq!(skill.invocation, super::SkillInvocation::ExplicitOnly);
    assert_eq!(
        skill.aliases,
        vec!["xlsx".to_string(), "spreadsheet".to_string()]
    );

    let mut registry = super::SkillRegistry::default();
    registry.skills.push(skill);
    assert_eq!(
        registry.get("spreadsheet").map(|s| s.name.as_str()),
        Some("spreadsheets")
    );
    assert_eq!(
        registry.get("xlsx").map(|s| s.name.as_str()),
        Some("spreadsheets")
    );

    let rendered = super::render_skills_block(&registry, "en", std::path::Path::new("/"));
    assert!(
        rendered.is_some(),
        "an explicit-only skill remains loadable"
    );
    assert!(
        !rendered.unwrap_or_default().contains("spreadsheets"),
        "explicit-only skills must not enter the model catalogue"
    );
}

#[test]
fn missing_or_unknown_invocation_keeps_model_and_user_compatibility() {
    for invocation in [None, Some("future-mode")] {
        let invocation_line =
            invocation.map_or(String::new(), |value| format!("invocation: {value}\n"));
        let content =
            format!("---\nname: compatible\ndescription: compatible\n{invocation_line}---\nbody");
        let skill = super::SkillRegistry::parse_skill(std::path::Path::new("SKILL.md"), &content)
            .expect("parse should succeed");
        assert_eq!(skill.invocation, super::SkillInvocation::ModelAndUser);
    }
}

#[test]
fn description_for_locale_matches_exact_then_primary_then_falls_back() {
    let mut localized = std::collections::HashMap::new();
    localized.insert("zh".to_string(), "ไธญๆ–‡ๆ่ฟฐ".to_string());
    localized.insert("ja".to_string(), "ๆ—ฅๆœฌ่ชžใฎ่ชฌๆ˜Ž".to_string());
    let skill = super::Skill {
        name: "demo".to_string(),
        description: "English description".to_string(),
        localized_descriptions: localized,
        invocation: super::SkillInvocation::ModelAndUser,
        aliases: Vec::new(),
        body: String::new(),
        path: std::path::PathBuf::new(),
        source: super::SkillSource::Native,
    };

    assert_eq!(skill.description_for_locale("zh"), "ไธญๆ–‡ๆ่ฟฐ"); // exact
    assert_eq!(skill.description_for_locale("ZH"), "ไธญๆ–‡ๆ่ฟฐ"); // case-insensitive
    assert_eq!(skill.description_for_locale("zh-CN"), "ไธญๆ–‡ๆ่ฟฐ"); // Simplified region โ†’ zh
    assert_eq!(skill.description_for_locale("zh-Hans"), "ไธญๆ–‡ๆ่ฟฐ"); // Simplified script โ†’ zh
    assert_eq!(skill.description_for_locale("ja"), "ๆ—ฅๆœฌ่ชžใฎ่ชฌๆ˜Ž");
    assert_eq!(skill.description_for_locale("fr"), "English description"); // fallback
    assert_eq!(skill.description_for_locale("en"), "English description");

    // Traditional Chinese must NOT borrow the Simplified `zh` description:
    // with no exact zh-hant key authored, it falls back to the default.
    assert_eq!(
        skill.description_for_locale("zh-Hant"),
        "English description"
    );
    assert_eq!(skill.description_for_locale("zh-TW"), "English description");
    assert_eq!(skill.description_for_locale("zh-HK"), "English description");
}

#[test]
fn description_for_locale_uses_exact_traditional_key_when_authored() {
    let mut localized = std::collections::HashMap::new();
    localized.insert("zh".to_string(), "็ฎ€ไฝ“ๆ่ฟฐ".to_string());
    localized.insert("zh-hant".to_string(), "็น้ซ”ๆ่ฟฐ".to_string());
    let skill = super::Skill {
        name: "demo".to_string(),
        description: "English".to_string(),
        localized_descriptions: localized,
        invocation: super::SkillInvocation::ModelAndUser,
        aliases: Vec::new(),
        body: String::new(),
        path: std::path::PathBuf::new(),
        source: super::SkillSource::Native,
    };
    // Exact Traditional key wins for a Traditional session.
    assert_eq!(skill.description_for_locale("zh-Hant"), "็น้ซ”ๆ่ฟฐ");
    // Simplified session still gets the Simplified description.
    assert_eq!(skill.description_for_locale("zh-Hans"), "็ฎ€ไฝ“ๆ่ฟฐ");
    assert_eq!(skill.description_for_locale("zh"), "็ฎ€ไฝ“ๆ่ฟฐ");
}

#[test]
fn description_for_locale_uses_default_when_no_localized_variants() {
    let skill = super::Skill {
        name: "demo".to_string(),
        description: "only english".to_string(),
        localized_descriptions: std::collections::HashMap::new(),
        invocation: super::SkillInvocation::ModelAndUser,
        aliases: Vec::new(),
        body: String::new(),
        path: std::path::PathBuf::new(),
        source: super::SkillSource::Native,
    };
    assert_eq!(skill.description_for_locale("zh"), "only english");
}

#[test]
fn render_skills_block_selects_description_by_locale() {
    let mut registry = super::SkillRegistry::default();
    let mut localized = std::collections::HashMap::new();
    localized.insert("zh".to_string(), "ๅŽ‹็ผฉๆ—ฅๅฟ—็š„ๆŠ€่ƒฝ".to_string());
    registry.skills.push(super::Skill {
        name: "compress".to_string(),
        description: "Compress logs to save space".to_string(),
        localized_descriptions: localized,
        invocation: super::SkillInvocation::ModelAndUser,
        aliases: Vec::new(),
        body: "body".to_string(),
        path: std::path::PathBuf::from("/skills/compress/SKILL.md"),
        source: super::SkillSource::Native,
    });

    let zh = super::render_skills_block(&registry, "zh-Hans", std::path::Path::new("/"))
        .expect("zh block");
    assert!(
        zh.contains("ๅŽ‹็ผฉๆ—ฅๅฟ—็š„ๆŠ€่ƒฝ"),
        "zh session should get the zh description:\n{zh}"
    );
    assert!(!zh.contains("Compress logs to save space"));

    let en =
        super::render_skills_block(&registry, "en", std::path::Path::new("/")).expect("en block");
    assert!(
        en.contains("Compress logs to save space"),
        "en session keeps default:\n{en}"
    );
}

fn write_skill(dir: &std::path::Path, name: &str, description: &str, body: &str) {
    let skill_dir = dir.join(name);
    std::fs::create_dir_all(&skill_dir).unwrap();
    std::fs::write(
        skill_dir.join("SKILL.md"),
        format!("---\nname: {name}\ndescription: {description}\n---\n{body}\n"),
    )
    .unwrap();
}

#[cfg(unix)]
fn create_dir_symlink(target: &std::path::Path, link: &std::path::Path) -> std::io::Result<()> {
    std::os::unix::fs::symlink(target, link)
}

#[cfg(windows)]
fn create_dir_symlink(target: &std::path::Path, link: &std::path::Path) -> std::io::Result<()> {
    std::os::windows::fs::symlink_dir(target, link)
}

#[test]
fn skills_directories_returns_existing_dirs_in_precedence_order() {
    let tmpdir = TempDir::new().unwrap();
    let workspace = tmpdir.path();

    // Create four of the five workspace candidate dirs (skip `.opencode`).
    std::fs::create_dir_all(workspace.join(".agents").join("skills")).unwrap();
    std::fs::create_dir_all(workspace.join("skills")).unwrap();
    std::fs::create_dir_all(workspace.join(".claude").join("skills")).unwrap();
    std::fs::create_dir_all(workspace.join(".cursor").join("skills")).unwrap();

    let dirs = super::skills_directories_for_mode(workspace, super::SkillDiscoveryMode::Compatible);
    // We don't assert on the global default position because it's
    // host-dependent (may not exist on the test machine).
    let mut idx = 0;
    let agents = workspace.join(".agents").join("skills");
    let local = workspace.join("skills");
    let claude = workspace.join(".claude").join("skills");
    let cursor = workspace.join(".cursor").join("skills");

    assert_eq!(dirs.get(idx), Some(&agents), "agents must come first");
    idx += 1;
    assert_eq!(dirs.get(idx), Some(&local), "local must come second");
    idx += 1;
    // .opencode/skills was not created โ€” it must NOT appear.
    assert!(
        !dirs
            .iter()
            .any(|p| p == &workspace.join(".opencode").join("skills")),
        "missing dir must be omitted, got: {dirs:?}"
    );
    assert_eq!(dirs.get(idx), Some(&claude), "claude must come after local");
    idx += 1;
    assert_eq!(
        dirs.get(idx),
        Some(&cursor),
        "cursor must come after claude"
    );
}

#[test]
fn existing_skill_dirs_orders_globals_agents_then_claude_then_deepseek() {
    // Pins the precedence among the three global skill roots (#902).
    // Workspace candidates are tested separately above; here we only
    // exercise the global ordering at the existing_skill_dirs level
    // so the assertion is host-independent.
    let tmpdir = TempDir::new().unwrap();
    let agents_global = tmpdir.path().join(".agents").join("skills");
    let claude_global = tmpdir.path().join(".claude").join("skills");
    let deepseek_global = tmpdir.path().join(".deepseek").join("skills");
    std::fs::create_dir_all(&agents_global).unwrap();
    std::fs::create_dir_all(&claude_global).unwrap();
    std::fs::create_dir_all(&deepseek_global).unwrap();

    let dirs = super::existing_skill_dirs(vec![
        agents_global.clone(),
        claude_global.clone(),
        deepseek_global.clone(),
    ]);

    assert_eq!(dirs, vec![agents_global, claude_global, deepseek_global]);
}

#[test]
fn existing_skill_dirs_keeps_agents_global_before_deepseek_global() {
    let tmpdir = TempDir::new().unwrap();
    let agents_global = tmpdir.path().join(".agents").join("skills");
    let deepseek_global = tmpdir.path().join(".deepseek").join("skills");
    let missing = tmpdir.path().join("missing").join("skills");
    std::fs::create_dir_all(&agents_global).unwrap();
    std::fs::create_dir_all(&deepseek_global).unwrap();

    let dirs = super::existing_skill_dirs(vec![
        missing,
        agents_global.clone(),
        deepseek_global.clone(),
        agents_global.clone(),
    ]);

    assert_eq!(dirs, vec![agents_global, deepseek_global]);
}

#[test]
fn discover_in_workspace_merges_with_first_wins_precedence() {
    let tmpdir = TempDir::new().unwrap();
    let workspace = tmpdir.path();

    // Same skill name `shared` in two locations โ€” the higher-precedence
    // dir's version should win.
    write_skill(
        &workspace.join(".agents").join("skills"),
        "shared",
        "agents wins",
        "from agents",
    );
    write_skill(
        &workspace.join(".claude").join("skills"),
        "shared",
        "claude loses",
        "from claude",
    );
    // Unique skill in claude โ€” should still be discovered.
    write_skill(
        &workspace.join(".claude").join("skills"),
        "unique-claude",
        "only here",
        "claude-only",
    );

    let registry = super::discover_in_workspace(workspace);
    let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect();
    assert!(
        names.contains(&"shared"),
        "shared must be present: {names:?}"
    );
    assert!(names.contains(&"unique-claude"));

    let shared = registry.get("shared").expect("shared present");
    assert_eq!(
        shared.description, "agents wins",
        "first-wins precedence should keep .agents/skills version"
    );
    assert!(
        shared.path.starts_with(workspace.join(".agents")),
        "shared.path should be from .agents/skills, got {:?}",
        shared.path
    );
    assert!(
        registry
            .warnings()
            .iter()
            .any(|warning| warning.contains("shared") && warning.contains("shadowed by")),
        "duplicate shadowing should warn, got {:?}",
        registry.warnings()
    );
}

#[test]
fn same_root_slug_collision_warns_and_keeps_one() {
    let tmpdir = TempDir::new().unwrap();
    let root = tmpdir.path();
    // Two sibling directories under one root whose frontmatter names
    // slugify to the same command name ("my-skill"). Only one can be
    // reachable by name; the other must warn rather than silently coexist
    // as an unreachable duplicate (#3919 same-root gap).
    write_skill(root, "My Skill", "first", "body");
    write_skill(root, "my_skill", "second", "body");

    let registry = super::SkillRegistry::discover(root);
    let claimants = registry
        .list()
        .iter()
        .filter(|s| s.name == "my-skill")
        .count();
    assert_eq!(
        claimants,
        1,
        "exactly one skill should claim `my-skill`, got {:?}",
        registry.list().iter().map(|s| &s.name).collect::<Vec<_>>()
    );
    assert!(
        registry
            .warnings()
            .iter()
            .any(|w| w.contains("my-skill") && w.contains("shadowed by")),
        "same-root slug collision should warn, got {:?}",
        registry.warnings()
    );
}

#[test]
fn discover_in_workspace_pulls_skills_from_opencode_dir() {
    let tmpdir = TempDir::new().unwrap();
    let workspace = tmpdir.path();
    write_skill(
        &workspace.join(".opencode").join("skills"),
        "opencode-only",
        "for interop",
        "body",
    );

    let registry = super::discover_in_workspace(workspace);
    assert!(
        registry.get("opencode-only").is_some(),
        ".opencode/skills must be scanned (#432)"
    );
}

#[test]
fn discover_in_workspace_pulls_skills_from_cursor_dir() {
    let tmpdir = TempDir::new().unwrap();
    let workspace = tmpdir.path();
    write_skill(
        &workspace.join(".cursor").join("skills"),
        "cursor-only",
        "for cursor interop",
        "body",
    );

    let registry = super::discover_in_workspace(workspace);
    assert!(
        registry.get("cursor-only").is_some(),
        ".cursor/skills must be scanned"
    );
}

#[test]
fn discover_accepts_plain_markdown_heading_without_frontmatter() {
    let tmpdir = TempDir::new().unwrap();
    let skill_dir = tmpdir.path().join("plain-skill");
    std::fs::create_dir_all(&skill_dir).unwrap();
    std::fs::write(
        skill_dir.join("SKILL.md"),
        "# Plain Skill\n\nUse this skill without YAML frontmatter.\n",
    )
    .unwrap();

    let registry = super::SkillRegistry::discover(tmpdir.path());
    let skill = registry.get("plain-skill").expect("plain skill parsed");
    assert_eq!(skill.name, "plain-skill");
    assert_eq!(skill.description, "");
    assert!(skill.body.contains("Use this skill"));
    assert!(
        registry
            .warnings()
            .iter()
            .any(|warning| warning.contains("using `plain-skill` instead")),
        "expected slug warning, got {:?}",
        registry.warnings()
    );
}

#[test]
fn discover_slugifies_invalid_frontmatter_names_and_lookup_normalizes() {
    let tmpdir = TempDir::new().unwrap();
    let root = tmpdir.path().join("skills");
    let skill_dir = root.join("my-skill");
    std::fs::create_dir_all(&skill_dir).unwrap();
    std::fs::write(
        skill_dir.join("SKILL.md"),
        "---\nname: My Skill\ndescription: spaced name\n---\nbody",
    )
    .unwrap();

    let registry = super::SkillRegistry::discover(&root);
    let skill = registry.get("  MY   skill  ").expect("normalized lookup");
    assert_eq!(skill.name, "my-skill");
    assert!(
        registry
            .warnings()
            .iter()
            .any(|warning| warning.contains("My Skill")
                && warning.contains("using `my-skill` instead")),
        "expected invalid-name warning, got {:?}",
        registry.warnings()
    );
}

#[test]
fn discover_warns_for_plain_markdown_without_heading() {
    let tmpdir = TempDir::new().unwrap();
    let skill_dir = tmpdir.path().join("plain-skill");
    std::fs::create_dir_all(&skill_dir).unwrap();
    std::fs::write(
        skill_dir.join("SKILL.md"),
        "Use this skill without a heading or YAML frontmatter.\n",
    )
    .unwrap();

    let registry = super::SkillRegistry::discover(tmpdir.path());
    assert!(registry.is_empty());
    assert!(
        registry
            .warnings()
            .iter()
            .any(|warning| warning.contains("no `# Heading` found")),
        "expected missing-heading warning, got {:?}",
        registry.warnings()
    );
}

#[test]
fn render_available_skills_context_for_workspace_picks_up_cross_tool_dirs() {
    let tmpdir = TempDir::new().unwrap();
    let workspace = tmpdir.path();
    write_skill(
        &workspace.join(".claude").join("skills"),
        "from-claude",
        "claude-style skill",
        "body",
    );
    let rendered =
        super::render_available_skills_context_for_workspace(workspace).expect("non-empty");
    assert!(rendered.contains("from-claude"));
}

#[test]
fn codewhale_only_mode_ignores_cross_tool_skill_dirs() {
    let tmpdir = TempDir::new().unwrap();
    let workspace = tmpdir.path().join("workspace");
    let home = tmpdir.path().join("home");
    let configured_dir = home.join(".codewhale").join("skills");
    std::fs::create_dir_all(&workspace).unwrap();
    write_skill(
        &workspace.join(".claude").join("skills"),
        "from-claude",
        "claude-style skill",
        "body",
    );
    write_skill(
        &workspace.join(".codewhale").join("skills"),
        "from-codewhale",
        "codewhale skill",
        "body",
    );
    write_skill(
        &home.join(".agents").join("skills"),
        "from-agents",
        "agents skill",
        "body",
    );
    write_skill(
        &configured_dir,
        "configured-codewhale",
        "configured skill",
        "body",
    );

    let registry = super::discover_for_workspace_and_dir_with_home_and_mode(
        &workspace,
        &configured_dir,
        Some(&home),
        super::SkillDiscoveryMode::CodeWhaleOnly,
    );
    let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect();

    assert!(names.contains(&"from-codewhale"));
    assert!(names.contains(&"configured-codewhale"));
    assert!(
        !names.contains(&"from-claude") && !names.contains(&"from-agents"),
        "CodeWhale-only mode must not import cross-tool skills: {names:?}"
    );
}

#[test]
fn codewhale_only_mode_still_honors_explicit_configured_dir() {
    let tmpdir = TempDir::new().unwrap();
    let workspace = tmpdir.path().join("workspace");
    let home = tmpdir.path().join("home");
    let configured_dir = tmpdir.path().join("my-skills");
    std::fs::create_dir_all(&workspace).unwrap();
    write_skill(
        &configured_dir,
        "configured-skill",
        "explicit configured skill",
        "body",
    );

    let registry = super::discover_for_workspace_and_dir_with_home_and_mode(
        &workspace,
        &configured_dir,
        Some(&home),
        super::SkillDiscoveryMode::CodeWhaleOnly,
    );
    let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect();

    assert_eq!(names, vec!["configured-skill"]);
}

#[test]
fn codewhale_only_mode_rejects_workspace_codewhale_symlink_escape() {
    let tmpdir = TempDir::new().unwrap();
    let workspace = tmpdir.path().join("workspace");
    let home = tmpdir.path().join("home");
    let escape_target = tmpdir.path().join("escape-target");
    std::fs::create_dir_all(workspace.join(".codewhale")).unwrap();
    write_skill(&escape_target, "escaped-skill", "escaped skill", "body");

    let link_path = workspace.join(".codewhale").join("skills");
    if let Err(err) = create_dir_symlink(&escape_target, &link_path) {
        eprintln!("skipping symlink escape assertion: {err}");
        return;
    }

    let registry = super::discover_for_workspace_and_dir_with_home_and_mode(
        &workspace,
        &tmpdir.path().join("missing-configured-skills"),
        Some(&home),
        super::SkillDiscoveryMode::CodeWhaleOnly,
    );

    assert!(
        registry.get("escaped-skill").is_none(),
        "CodeWhale-only mode must not follow workspace .codewhale/skills outside the workspace"
    );
}

#[test]
fn discover_for_workspace_and_dir_merges_workspace_and_configured_sources() {
    let tmpdir = TempDir::new().unwrap();
    let workspace = tmpdir.path().join("workspace");
    let home = tmpdir.path().join("home");
    let configured_dir = tmpdir.path().join("configured-skills");
    std::fs::create_dir_all(&workspace).unwrap();
    write_skill(
        &workspace.join(".claude").join("skills"),
        "workspace-skill",
        "workspace visible skill",
        "body",
    );
    write_skill(
        &configured_dir,
        "configured-skill",
        "configured visible skill",
        "body",
    );

    let registry =
        super::discover_for_workspace_and_dir_with_home(&workspace, &configured_dir, Some(&home));
    let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect();

    assert!(names.contains(&"workspace-skill"));
    assert!(names.contains(&"configured-skill"));
}

#[test]
fn explicit_configured_skills_dir_precedes_global_defaults() {
    let tmpdir = TempDir::new().unwrap();
    let workspace = tmpdir.path().join("workspace");
    let home = tmpdir.path().join("home");
    let configured_dir = tmpdir.path().join("configured-skills");
    std::fs::create_dir_all(&workspace).unwrap();
    write_skill(
        &home.join(".agents").join("skills"),
        "shared-skill",
        "global skill",
        "global body",
    );
    write_skill(
        &configured_dir,
        "shared-skill",
        "configured skill",
        "configured body",
    );

    let registry =
        super::discover_for_workspace_and_dir_with_home(&workspace, &configured_dir, Some(&home));
    let skill = registry
        .get("shared-skill")
        .expect("shared skill discovered");

    assert_eq!(skill.description, "configured skill");
}

/// Regression for the GitHub issue where users organize skills under
/// vendor / category subdirectories (e.g. cloned skill repos that
/// bundle several skills together). The old single-level `read_dir`
/// only ever surfaced `<root>/<skill>/SKILL.md` and silently ignored
/// `<root>/<vendor>/<skill>/SKILL.md`.
#[test]
fn discover_finds_skills_nested_under_vendor_subdirectory() {
    let tmpdir = TempDir::new().unwrap();
    let root = tmpdir.path().join("skills");

    // Two-level nesting: `<root>/<vendor>/<skill>/SKILL.md`. This
    // matches the `clawhub-skills/clawhub/SKILL.md` layout in the
    // bug report.
    write_skill(
        &root.join("clawhub-skills"),
        "clawhub",
        "claw search",
        "body",
    );
    write_skill(
        &root.join("clawhub-skills"),
        "github",
        "github helpers",
        "body",
    );
    // Three-level nesting: `<root>/<org>/<repo>/<skill>/SKILL.md`.
    write_skill(
        &root.join("pasky").join("chrome-cdp-skill"),
        "chrome-cdp",
        "browser automation",
        "body",
    );
    // Mixed-depth: a flat skill alongside the nested layout still
    // works (this is what the bundled `skill-creator` looks like).
    write_skill(&root, "skill-creator", "make skills", "body");

    let registry = super::SkillRegistry::discover(&root);
    let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"clawhub"), "vendor/skill missed: {names:?}");
    assert!(names.contains(&"github"), "vendor/skill missed: {names:?}");
    assert!(
        names.contains(&"chrome-cdp"),
        "deeply-nested skill missed: {names:?}"
    );
    assert!(
        names.contains(&"skill-creator"),
        "flat top-level skill must still load: {names:?}"
    );
    assert!(
        registry.warnings().is_empty(),
        "well-formed nested layout should not warn: {:?}",
        registry.warnings()
    );
}

#[cfg(any(unix, windows))]
#[test]
fn discover_follows_symlinked_skill_directories() {
    let tmpdir = TempDir::new().unwrap();
    let source_root = tmpdir.path().join("claude-skills");
    let skills_root = tmpdir.path().join(".deepseek").join("skills");
    write_skill(&source_root, "agent-browser", "browser automation", "body");
    std::fs::create_dir_all(&skills_root).unwrap();
    let link_path = skills_root.join("agent-browser");

    if let Err(err) = create_dir_symlink(&source_root.join("agent-browser"), &link_path) {
        eprintln!("skipping symlink discovery assertion: {err}");
        return;
    }

    let registry = super::SkillRegistry::discover(&skills_root);
    let skill = registry
        .get("agent-browser")
        .expect("symlinked skill directory should be discovered");
    assert_eq!(skill.description, "browser automation");
    assert_eq!(skill.path, link_path.join("SKILL.md"));
}

#[cfg(any(unix, windows))]
#[test]
fn discover_dedupes_symlink_cycles_by_canonical_directory() {
    let tmpdir = TempDir::new().unwrap();
    let root = tmpdir.path().join("skills");
    write_skill(&root, "real-skill", "ok", "body");
    let loop_parent = root.join("vendor");
    std::fs::create_dir_all(&loop_parent).unwrap();

    if let Err(err) = create_dir_symlink(&root, &loop_parent.join("loop")) {
        eprintln!("skipping symlink cycle assertion: {err}");
        return;
    }

    let registry = super::SkillRegistry::discover(&root);
    let matches = registry
        .list()
        .iter()
        .filter(|skill| skill.name == "real-skill")
        .count();
    assert_eq!(
        matches, 1,
        "symlink cycle should not rediscover the same canonical skill directory"
    );
}

/// Once a directory is identified as a skill (has `SKILL.md`), the
/// walker must NOT descend into it: any nested `SKILL.md` would be
/// a fixture / example bundled with the parent skill, not a
/// separately-installable one. This mirrors the contract that
/// `tools::skill::collect_companion_files` already documents
/// ("nested directory โ€” skipped").
#[test]
fn discover_does_not_descend_into_a_skill_directory() {
    let tmpdir = TempDir::new().unwrap();
    let root = tmpdir.path().join("skills");

    // Parent skill: <root>/parent/SKILL.md.
    write_skill(&root, "parent", "outer skill", "outer body");
    // Fixture bundled inside the parent's directory:
    // <root>/parent/examples/inner-fixture/SKILL.md. The walker
    // must NOT descend into <root>/parent/ after finding its
    // SKILL.md, so `inner-fixture` must not be loaded.
    write_skill(
        &root.join("parent").join("examples"),
        "inner-fixture",
        "should not load",
        "fixture body",
    );

    let registry = super::SkillRegistry::discover(&root);
    let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"parent"));
    assert!(
        !names.contains(&"inner-fixture"),
        "nested SKILL.md inside an existing skill must be ignored: {names:?}"
    );
}

/// Hidden subdirectories below the root (e.g. `.git`, `.cache`) must
/// be skipped so a `skills_dir` that lives inside a checked-out repo
/// doesn't accidentally load random `SKILL.md`-named fixtures from
/// the VCS metadata. The root itself is exempt โ€” the user explicitly
/// pointed `skills_dir` at it.
#[test]
fn discover_skips_hidden_subdirectories_below_root() {
    let tmpdir = TempDir::new().unwrap();
    let root = tmpdir.path().join("skills");

    write_skill(&root, "real-skill", "ok", "body");
    // A `<root>/.git/<junk>/SKILL.md` lookalike that mustn't load.
    // `.git` is a direct child of the user-provided root (depth 0
    // of the walk), which is exactly the case the old `depth > 0`
    // gate missed.
    write_skill(&root.join(".git"), "vcs-noise", "should not load", "body");

    let registry = super::SkillRegistry::discover(&root);
    let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"real-skill"));
    assert!(
        !names.contains(&"vcs-noise"),
        "skills under hidden subdirs must be skipped: {names:?}"
    );
}

/// The user explicitly chooses the root, so even a hidden path like
/// `~/.agents/skills` (the layout in the bug report) must work.
#[test]
fn discover_honors_a_hidden_root_directory() {
    let tmpdir = TempDir::new().unwrap();
    let root = tmpdir.path().join(".agents").join("skills");

    // Matches the bug report: skills_dir = "~/.agents/skills"
    // with a skill nested at <root>/custom-skills/git-conventions/SKILL.md.
    write_skill(
        &root.join("custom-skills"),
        "git-conventions",
        "conventions",
        "body",
    );

    let registry = super::SkillRegistry::discover(&root);
    let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect();
    assert!(
        names.contains(&"git-conventions"),
        "hidden root must still be walked: {names:?}"
    );
}

/// Mirrors the qa_pty `skills_menu_shows_local_and_global_skills`
/// scenario without the PTY harness: a workspace-level skill in
/// `.agents/skills/` and a global skill in `~/.codewhale/skills/`
/// must both be discoverable.
#[test]
fn discover_finds_both_workspace_and_global_skills() {
    let tmpdir = TempDir::new().unwrap();
    let workspace = tmpdir.path().join("workspace");
    let home = tmpdir.path().join("home");
    std::fs::create_dir_all(&workspace).unwrap();

    write_skill(
        &workspace.join(".agents").join("skills"),
        "workspace-beta",
        "Workspace beta skill",
        "body",
    );
    write_skill(
        &home.join(".codewhale").join("skills"),
        "global-alpha",
        "Global alpha skill",
        "body",
    );

    let skills_dir = workspace.join(".agents").join("skills");
    let registry =
        super::discover_for_workspace_and_dir_with_home(&workspace, &skills_dir, Some(&home));

    let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect();
    assert!(
        names.contains(&"workspace-beta"),
        "workspace-beta from .agents/skills must be discovered: {names:?}",
    );
    assert!(
        names.contains(&"global-alpha"),
        "global-alpha from ~/.codewhale/skills must be discovered: {names:?}",
    );
}

// โ”€โ”€ Block scalar parsing (YAML `>` and `|`) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// `>` (folded block scalar): subsequent indented lines are folded
/// into a single line joined by spaces.
#[test]
fn parse_skill_folded_block_scalar() {
    let tmpdir = TempDir::new().unwrap();
    create_skill_dir(
        &tmpdir,
        "folded-skill",
        "---\nname: folded-skill\ndescription: >\n  line one chinese\n  line two chinese\n---\nbody",
    );
    let rendered = crate::skills::render_available_skills_context(&tmpdir.path().join("skills"))
        .expect("skill context");
    assert!(
        rendered.contains("line one chinese line two chinese"),
        "folded block scalar should join lines with space, got:\n{rendered}"
    );
}

/// `|` (literal block scalar): subsequent indented lines preserve
/// newlines.
#[test]
fn parse_skill_literal_block_scalar() {
    let tmpdir = TempDir::new().unwrap();
    create_skill_dir(
        &tmpdir,
        "literal-skill",
        "---\nname: literal-skill\ndescription: |\n  line one\n  line two\n---\nbody",
    );
    let rendered = crate::skills::render_available_skills_context(&tmpdir.path().join("skills"))
        .expect("skill context");
    // `truncate_for_prompt` collapses whitespace, so the newlines
    // become spaces. The key assertion is that the content is
    // captured (not just `|`).
    assert!(
        rendered.contains("line one line two"),
        "literal block scalar should preserve content, got:\n{rendered}"
    );
}

/// `>-` (folded with strip chomping): same as `>` but trailing
/// whitespace is stripped.
#[test]
fn parse_skill_folded_strip_block_scalar() {
    let tmpdir = TempDir::new().unwrap();
    create_skill_dir(
        &tmpdir,
        "strip-skill",
        "---\nname: strip-skill\ndescription: >-\n  alpha\n  beta\n\n---\nbody",
    );
    let rendered = crate::skills::render_available_skills_context(&tmpdir.path().join("skills"))
        .expect("skill context");
    assert!(
        rendered.contains("alpha beta"),
        "strip-chomped folded block should join lines, got:\n{rendered}"
    );
}

/// Regression: a single-line description (no block scalar) must
/// still parse correctly after the parser rewrite.
#[test]
fn parse_skill_single_line_description_still_works() {
    let tmpdir = TempDir::new().unwrap();
    create_skill_dir(
        &tmpdir,
        "plain-skill",
        "---\nname: plain-skill\ndescription: A simple description\n---\nbody",
    );
    let rendered = crate::skills::render_available_skills_context(&tmpdir.path().join("skills"))
        .expect("skill context");
    assert!(
        rendered.contains("- plain-skill: A simple description"),
        "single-line description should still work, got:\n{rendered}"
    );
}

/// Direct unit test on the parsed Skill struct (not through rendering)
/// so we assert the exact description value.
#[test]
fn parse_skill_direct_folded_result() {
    let skill = super::SkillRegistry::parse_skill(
        std::path::Path::new(""),
        "---\nname: test\ndescription: >\n  this is a test\n  used to verify parsing\n---\nbody",
    )
    .expect("should parse");
    assert_eq!(skill.name, "test");
    assert_eq!(skill.description, "this is a test used to verify parsing");
}

// โ”€โ”€ Chomping behaviour โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// `>-` (strip): trailing empty lines are stripped. Paragraph
/// breaks (empty line between text lines) are still folded to a
/// single space in a block-scalar join (no newline โ€” the simplified
/// parser treats intra-block empty lines as paragraph breaks that
/// become a single space in the folded output).
#[test]
fn parse_skill_strip_chomp_strips_trailing_empties() {
    let skill = super::SkillRegistry::parse_skill(
        std::path::Path::new(""),
        "---\nname: s\ndescription: >-\n  hello\n  world\n\n\n---\nbody",
    )
    .expect("should parse");
    // Trailing empty lines stripped: no whitespace at end, just folded text.
    assert_eq!(skill.description, "hello world");
}

/// `>+` (keep): trailing empty lines are preserved. Each trailing
/// empty line in the block becomes a newline in the description.
#[test]
fn parse_skill_keep_chomp_preserves_trailing_empties() {
    let skill = super::SkillRegistry::parse_skill(
        std::path::Path::new(""),
        "---\nname: s\ndescription: >+\n  hello\n  world\n\n\n---\nbody",
    )
    .expect("should parse");
    // Two trailing empty lines should become two newlines.
    assert_eq!(skill.description, "hello world\n\n");
}

/// `>` (clip): trailing empty lines exceeding one are clipped.
/// The result should have at most one trailing newline.
#[test]
fn parse_skill_clip_chomp_clips_excess_trailing_empties() {
    let skill = super::SkillRegistry::parse_skill(
        std::path::Path::new(""),
        "---\nname: s\ndescription: >\n  hello\n  world\n\n\n---\nbody",
    )
    .expect("should parse");
    // clip: 3 trailing empty lines โ†’ at most 1 trailing newline.
    assert_eq!(skill.description, "hello world\n");
}

/// `>` with no trailing empty lines: clip should not add anything.
#[test]
fn parse_skill_clip_chomp_no_trailing_empties() {
    let skill = super::SkillRegistry::parse_skill(
        std::path::Path::new(""),
        "---\nname: s\ndescription: >\n  hello\n  world\n---\nbody",
    )
    .expect("should parse");
    assert_eq!(skill.description, "hello world");
}

/// `>` with exactly one trailing empty line: clip keeps it.
#[test]
fn parse_skill_clip_chomp_one_trailing_empty() {
    let skill = super::SkillRegistry::parse_skill(
        std::path::Path::new(""),
        "---\nname: s\ndescription: >\n  hello\n  world\n\n---\nbody",
    )
    .expect("should parse");
    assert_eq!(skill.description, "hello world\n");
}

/// `>-` strip vs `>+` keep: same block content, different
/// trailing newline handling.
#[test]
fn parse_skill_strip_vs_keep_trailing() {
    let content = "---\nname: s\ndescription: >{}\n  hello\n  world\n\n\n---\nbody";
    let strip_skill =
        super::SkillRegistry::parse_skill(std::path::Path::new(""), &content.replace("{}", "-"))
            .expect("strip parse");
    let keep_skill =
        super::SkillRegistry::parse_skill(std::path::Path::new(""), &content.replace("{}", "+"))
            .expect("keep parse");
    // strip drops trailing empties; keep preserves them.
    assert_eq!(strip_skill.description, "hello world");
    assert_eq!(keep_skill.description, "hello world\n\n");
}

/// `|-` literal strip: trailing newlines are stripped.
#[test]
fn parse_skill_literal_strip_strips_trailing_newlines() {
    let skill = super::SkillRegistry::parse_skill(
        std::path::Path::new(""),
        "---\nname: s\ndescription: |-\n  line one\n  line two\n\n\n---\nbody",
    )
    .expect("should parse");
    // literal: newlines preserved between non-empty lines.
    // strip: trailing empty lines removed.
    assert_eq!(skill.description, "line one\nline two");
}

/// `|+` literal keep: trailing newlines are preserved.
#[test]
fn parse_skill_literal_keep_preserves_trailing_newlines() {
    let skill = super::SkillRegistry::parse_skill(
        std::path::Path::new(""),
        "---\nname: s\ndescription: |+\n  line one\n  line two\n\n\n---\nbody",
    )
    .expect("should parse");
    // literal: newlines preserved between non-empty lines.
    // keep: trailing empty lines are preserved as newlines.
    assert_eq!(skill.description, "line one\nline two\n\n");
}

/// Nested relative indentation is preserved in literal (`|`) block
/// scalars: only the content-level indent (from the first non-empty
/// line) is stripped, and any deeper indent stays as-is.
#[test]
fn parse_skill_literal_preserves_relative_indentation() {
    let skill = super::SkillRegistry::parse_skill(
        std::path::Path::new(""),
        "---\nname: s\ndescription: |\n  Usage:\n    $ deepseek --model auto\n    $ deepseek doctor\n---\nbody",
    )
    .expect("should parse");
    assert_eq!(
        skill.description,
        "Usage:\n  $ deepseek --model auto\n  $ deepseek doctor"
    );
}

/// Folded (`>`) block scalars also preserve relative indentation
/// within lines (the extra spaces survive the fold).
#[test]
fn parse_skill_folded_preserves_relative_indentation() {
    let skill = super::SkillRegistry::parse_skill(
        std::path::Path::new(""),
        "---\nname: s\ndescription: >\n  See also:\n    the config file\n    the env var\n---\nbody",
    )
    .expect("should parse");
    assert_eq!(
        skill.description,
        "See also:   the config file   the env var"
    );
}

#[test]
fn plugin_skills_are_qualified_and_denied_until_trusted_and_enabled() {
    let tmp = TempDir::new().unwrap();
    let plugin_root = tmp.path().join("plugins/demo");
    std::fs::create_dir_all(plugin_root.join("skills/hello-world")).unwrap();
    std::fs::write(
        plugin_root.join("plugin.toml"),
        "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n",
    )
    .unwrap();
    std::fs::write(
        plugin_root.join("skills/hello-world/SKILL.md"),
        "---\nname: hello-world\ndescription: hello\n---\nbody\n",
    )
    .unwrap();
    let config = crate::plugins::discovery::DiscoveryConfig {
        workspace: tmp.path().join("workspace"),
        user_plugins_dir: tmp.path().join("plugins"),
        workspace_plugins_dir: tmp.path().join("workspace-plugins"),
        builtin_plugin_dirs: Vec::new(),
        state_path: tmp.path().join("plugin-state/state.json"),
    };
    let mut plugins = crate::plugins::discovery::discover_with_config(&config);

    let mut registry = super::SkillRegistry::default();
    super::merge_active_plugin_skills(&mut registry, &plugins);
    assert!(registry.get("demo:hello-world").is_none());

    plugins.trust("demo").unwrap();
    super::merge_active_plugin_skills(&mut registry, &plugins);
    assert!(registry.get("demo:hello-world").is_none());

    plugins.enable("demo").unwrap();
    super::merge_active_plugin_skills(&mut registry, &plugins);
    let skill = registry
        .get("Demo:Hello_World")
        .expect("qualified lookup should normalize each namespace segment");
    assert_eq!(skill.name, "demo:hello-world");
    assert!(matches!(
        skill.source,
        super::SkillSource::Plugin { ref plugin_name, .. } if plugin_name == "demo"
    ));
    let rendered = super::render_skills_block(&registry, "en", tmp.path()).unwrap();
    assert!(rendered.contains("reviewed plugin snapshot: demo"));
    assert!(rendered.contains("use load_skill"));
    assert!(
        !rendered.contains(&plugin_root.display().to_string()),
        "model prompt must not expose mutable plugin files after snapshot review"
    );

    let mut fail_closed_input = registry.clone();
    fail_closed_input.skills.push(super::Skill {
        name: "native-recovery".to_string(),
        description: "native recovery skill".to_string(),
        localized_descriptions: std::collections::HashMap::new(),
        invocation: super::SkillInvocation::ModelAndUser,
        aliases: Vec::new(),
        body: "recovery".to_string(),
        path: tmp.path().join("native/SKILL.md"),
        source: super::SkillSource::Native,
    });
    let fail_closed = fail_closed_input.into_enabled_with_state(Err(anyhow::anyhow!(
        "injected activation-state read failure"
    )));
    assert!(fail_closed.get("native-recovery").is_some());
    assert!(
        fail_closed.get("demo:hello-world").is_none(),
        "reviewed plugin Skills must not fail open when activation state is unreadable"
    );
    assert!(
        fail_closed
            .warnings()
            .iter()
            .any(|warning| warning.contains("hidden fail-closed"))
    );

    std::fs::remove_file(config.state_path.with_file_name("state.json.lock")).unwrap();
    let mut denied = super::SkillRegistry::default();
    super::merge_active_plugin_skills(&mut denied, &plugins);
    assert!(
        denied.get("demo:hello-world").is_none(),
        "a missing authority lock must remove plugin instructions from the prompt catalogue"
    );
}

// --- #3921 merged discovery cache -----------------------------------------

fn discovery_delta_since(earlier: super::SkillDiscoveryMetrics) -> super::SkillDiscoveryMetrics {
    super::discovery_metrics_snapshot().delta_since(earlier)
}

#[test]
fn cached_discovery_reuses_unchanged_registry_without_rewalking() {
    super::clear_skill_discovery_cache();
    let tmpdir = TempDir::new().unwrap();
    let skills_root = tmpdir.path().join("skills");
    write_skill(&skills_root, "demo", "A demo skill", "Instructions");
    let dirs = vec![skills_root];

    super::reset_discovery_metrics();
    let first = super::discover_from_directories_with_plugins(dirs.clone(), None);
    let walked = discovery_delta_since(super::SkillDiscoveryMetrics::default());
    let second = super::discover_from_directories_with_plugins(dirs, None);
    let rewalked = discovery_delta_since(walked);

    assert_eq!(walked.root_discovery_calls, 1);
    assert_eq!(rewalked, super::SkillDiscoveryMetrics::default());
    assert_eq!(first.len(), second.len());
    assert_eq!(first.list()[0].description, second.list()[0].description);
}

#[test]
fn cached_discovery_picks_up_added_skill_on_next_call() {
    super::clear_skill_discovery_cache();
    let tmpdir = TempDir::new().unwrap();
    let skills_root = tmpdir.path().join("skills");
    write_skill(&skills_root, "demo", "A demo skill", "Instructions");
    let dirs = vec![skills_root.clone()];

    let first = super::discover_from_directories_with_plugins(dirs.clone(), None);
    assert_eq!(first.len(), 1);

    write_skill(&skills_root, "added", "A later skill", "More");
    std::thread::sleep(std::time::Duration::from_millis(10));
    let second = super::discover_from_directories_with_plugins(dirs, None);
    assert_eq!(second.len(), 2);
    assert!(second.get("added").is_some());
}

#[test]
fn cached_discovery_picks_up_skill_content_edits() {
    super::clear_skill_discovery_cache();
    let tmpdir = TempDir::new().unwrap();
    let skills_root = tmpdir.path().join("skills");
    write_skill(&skills_root, "demo", "Original description", "Instructions");
    let dirs = vec![skills_root.clone()];

    let first = super::discover_from_directories_with_plugins(dirs.clone(), None);
    assert_eq!(first.list()[0].description, "Original description");

    write_skill(&skills_root, "demo", "Edited description", "Instructions");
    std::thread::sleep(std::time::Duration::from_millis(10));
    let second = super::discover_from_directories_with_plugins(dirs, None);
    assert_eq!(second.list()[0].description, "Edited description");
}

#[test]
fn cached_discovery_drops_removed_skills() {
    super::clear_skill_discovery_cache();
    let tmpdir = TempDir::new().unwrap();
    let skills_root = tmpdir.path().join("skills");
    write_skill(&skills_root, "keep", "Keep me", "Instructions");
    write_skill(&skills_root, "drop", "Drop me", "Instructions");
    let dirs = vec![skills_root.clone()];

    let first = super::discover_from_directories_with_plugins(dirs.clone(), None);
    assert_eq!(first.len(), 2);

    std::fs::remove_dir_all(skills_root.join("drop")).unwrap();
    std::thread::sleep(std::time::Duration::from_millis(10));
    let second = super::discover_from_directories_with_plugins(dirs, None);
    assert_eq!(second.len(), 1);
    assert!(second.get("drop").is_none());
}

#[test]
fn clear_skill_discovery_cache_forces_a_fresh_walk() {
    super::clear_skill_discovery_cache();
    let tmpdir = TempDir::new().unwrap();
    let skills_root = tmpdir.path().join("skills");
    write_skill(&skills_root, "demo", "A demo skill", "Instructions");
    let dirs = vec![skills_root];

    let _ = super::discover_from_directories_with_plugins(dirs.clone(), None);
    super::clear_skill_discovery_cache();

    super::reset_discovery_metrics();
    let _ = super::discover_from_directories_with_plugins(dirs, None);
    let rewalked = discovery_delta_since(super::SkillDiscoveryMetrics::default());
    assert_eq!(rewalked.root_discovery_calls, 1);
}

#[test]
fn workspace_and_dir_entry_point_shares_the_same_cache() {
    let _env_lock = crate::test_support::lock_test_env();
    super::clear_skill_discovery_cache();
    let tmpdir = TempDir::new().unwrap();
    let home = tmpdir.path().join("home");
    let workspace = tmpdir.path().join("workspace");
    let skills_dir = tmpdir.path().join("configured-skills");
    std::fs::create_dir_all(&home).unwrap();
    std::fs::create_dir_all(&workspace).unwrap();
    write_skill(
        &skills_dir,
        "configured",
        "Configured skill",
        "Instructions",
    );
    let _home = crate::test_support::EnvVarGuard::set("HOME", &home);
    let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", &home);
    let _codewhale_home =
        crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale"));

    super::reset_discovery_metrics();
    let first = super::discover_for_workspace_and_dir_with_mode_and_plugins(
        &workspace,
        &skills_dir,
        super::SkillDiscoveryMode::Compatible,
        None,
    );
    let walked = discovery_delta_since(super::SkillDiscoveryMetrics::default());
    let second = super::discover_for_workspace_and_dir_with_mode_and_plugins(
        &workspace,
        &skills_dir,
        super::SkillDiscoveryMode::Compatible,
        None,
    );
    let rewalked = discovery_delta_since(walked);

    assert!(walked.root_discovery_calls >= 1);
    assert_eq!(rewalked, super::SkillDiscoveryMetrics::default());
    assert_eq!(first.len(), second.len());
    assert!(second.get("configured").is_some());
}

#[test]
fn global_skill_roots_come_from_the_os_home_only() {
    // ยง2.5: global skill roots resolve under the OS user's home (or an
    // explicit `$CODEWHALE_HOME`), never an account/GitHub handle. A wrong
    // home once produced `Failed to read /Users/<handle>/.codewhale/skills/
    // delegate/SKILL.md`; pin the source so every global root is provably
    // under the faked OS home.
    let _env_lock = crate::test_support::lock_test_env();
    let tmpdir = TempDir::new().unwrap();
    let home = tmpdir.path().join("os-home");
    let workspace = tmpdir.path().join("workspace");
    std::fs::create_dir_all(home.join(".codewhale").join("skills")).unwrap();
    std::fs::create_dir_all(&workspace).unwrap();
    let _home = crate::test_support::EnvVarGuard::set("HOME", &home);
    let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", &home);
    let _codewhale_home = crate::test_support::EnvVarGuard::remove("CODEWHALE_HOME");

    let dirs =
        super::skills_directories_for_mode(&workspace, super::SkillDiscoveryMode::Compatible);

    assert!(
        dirs.iter().any(|dir| dir.starts_with(&home)),
        "expected at least one global root under the OS home: {dirs:?}"
    );
    assert!(
        dirs.iter()
            .all(|dir| dir.starts_with(&home) || dir.starts_with(&workspace)),
        "every runtime root is under the OS home or the workspace: {dirs:?}"
    );
}