supercode-harness 0.4.16

The optional native Supercode agent and tool harness
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
//! ORCH-11 (observed tier): read-only enumeration of the skill packages each
//! harness has installed.
//!
//! supercode never installs, removes, or edits a skill here — it opens the
//! directories the harness's own loader opens and reports what is there. The
//! roots below are transcribed from each harness's documented/primary source:
//!
//! * Claude Code — enterprise (managed) > personal `~/.claude/skills/` >
//!   project `.claude/skills/`, nested `.claude/skills/` in subdirectories,
//!   plugin skills namespaced `plugin:skill`
//!   (`docs/composable-harness/inventory/claude-code.md` "Skill locations &
//!   precedence"; `docs:skills#where-skills-live`).
//! * Codex — repo `.agents/skills` from cwd to the repo root, user
//!   `~/.agents/skills` (plus the deprecated `$CODEX_HOME/skills`), admin
//!   `/etc/codex/skills`, and the bundled cache `$CODEX_HOME/skills/.system`
//!   (`inventory/codex.md` §7 Skills; `codex-rs/core-skills/src/loader.rs`).
//!   `[skills]` in `$CODEX_HOME/config.toml` is an enable/disable overlay
//!   (`SkillConfig { path, name, enabled }`), not an extra root, so it is
//!   read for `enabled` only (`codex-rs/config/src/skills_config.rs:12-36`
//!   at the pinned commit `1f0566d3`).
//! * opencode — `{skill,skills}/**/SKILL.md` under every `.opencode` dir plus
//!   the global config dir (`inventory/opencode.md` §7 Skills,
//!   `packages/opencode/src/skill/index.ts:23-25`).
//! * pi — `~/.pi/agent/skills/`, `~/.agents/skills/`, project `.pi/skills/`
//!   and `.agents/skills/` in cwd and its ancestors (`inventory/pi.md` §2
//!   Skills, `src:core/skills.ts`).
//! * Hermes 0.21.0 — `HERMES_HOME/skills` (`get_skills_dir()` =
//!   `get_hermes_home() / "skills"`, `hermes_constants.py:1195-1197`), and
//!   because profile mode sets `HERMES_HOME` to `<root>/profiles/<name>`
//!   (`hermes_constants.py:160-190`), `<root>/profiles/<name>/skills` too.
//!   Hermes groups skills by category, so a root is walked, not listed.
//! * OpenClaw 2026.7.1-2 — managed `<config>/skills`, plugin
//!   `<config>/plugin-skills`, workspace `<workspace>/skills` and
//!   `<workspace>/.agents/skills`, personal `~/.agents/skills`
//!   (`src/skills/loading/workspace.ts:1155-1215` at tag `v2026.7.1-2`).
//!
//! `enabled` is `None` wherever the harness's own source does not say; only
//! Codex's `[skills]` overlay and a skill's own frontmatter produce a bool.

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

use serde::{Deserialize, Serialize};

use crate::HarnessId;

/// Where a skill package was found, in the vocabulary shared by all six
/// harnesses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SkillScope {
    /// Enterprise / admin / harness-managed directory.
    Managed,
    /// The user's own config home.
    User,
    /// A directory under the working tree.
    Project,
    /// Contributed by an installed plugin bundle.
    Plugin,
    /// Shipped with the harness itself.
    Bundled,
}

impl SkillScope {
    /// Stable wire spelling, also accepted by `--scope`.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Managed => "managed",
            Self::User => "user",
            Self::Project => "project",
            Self::Plugin => "plugin",
            Self::Bundled => "bundled",
        }
    }

    /// Parse one wire spelling.
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "managed" => Some(Self::Managed),
            "user" => Some(Self::User),
            "project" => Some(Self::Project),
            "plugin" => Some(Self::Plugin),
            "bundled" => Some(Self::Bundled),
            _ => None,
        }
    }
}

/// One installed skill package, as one harness holds it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SkillRow {
    /// Frontmatter `name` when present, else the directory name.
    pub name: String,
    /// Which harness's root this was read from.
    pub harness: HarnessId,
    /// Precedence class of the root.
    pub scope: SkillScope,
    /// Absolute path of the skill's own directory.
    pub location: PathBuf,
    /// Frontmatter `description`, trimmed to one line.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Frontmatter `version`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// `None` when the harness's own source does not express enablement.
    pub enabled: Option<bool>,
}

/// Config homes the skill roots hang off. Defaults follow each harness's own
/// environment contract; a caller may override any of them (tests, probes).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SkillHomes {
    /// `CLAUDE_CONFIG_DIR` or `~/.claude`.
    pub claude_code: PathBuf,
    /// `CODEX_HOME` or `~/.codex`.
    pub codex: PathBuf,
    /// opencode's global config dir (`$OPENCODE_CONFIG_DIR`, else
    /// `$XDG_CONFIG_HOME/opencode`, else `~/.config/opencode`).
    pub opencode: PathBuf,
    /// `PI_CODING_AGENT_DIR` or `~/.pi/agent`.
    pub pi: PathBuf,
    /// `HERMES_HOME` or `~/.hermes`.
    pub hermes: PathBuf,
    /// OpenClaw's `CONFIG_DIR` (`OPENCLAW_STATE_DIR`, else
    /// `$OPENCLAW_HOME/.openclaw`, else `~/.openclaw`).
    pub openclaw: PathBuf,
    /// The cross-harness Agent Skills personal root, `~/.agents`.
    pub agents: PathBuf,
}

fn home_dir() -> PathBuf {
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."))
}

impl Default for SkillHomes {
    fn default() -> Self {
        let home = home_dir();
        Self {
            claude_code: std::env::var_os("CLAUDE_CONFIG_DIR")
                .map(PathBuf::from)
                .unwrap_or_else(|| home.join(".claude")),
            codex: std::env::var_os("CODEX_HOME")
                .map(PathBuf::from)
                .unwrap_or_else(|| home.join(".codex")),
            opencode: std::env::var_os("OPENCODE_CONFIG_DIR")
                .map(PathBuf::from)
                .unwrap_or_else(|| {
                    std::env::var_os("XDG_CONFIG_HOME")
                        .map(PathBuf::from)
                        .unwrap_or_else(|| home.join(".config"))
                        .join("opencode")
                }),
            pi: std::env::var_os("PI_CODING_AGENT_DIR")
                .map(PathBuf::from)
                .unwrap_or_else(|| home.join(".pi").join("agent")),
            hermes: std::env::var_os("HERMES_HOME")
                .map(PathBuf::from)
                .unwrap_or_else(|| home.join(".hermes")),
            openclaw: std::env::var_os("OPENCLAW_STATE_DIR")
                .map(PathBuf::from)
                .or_else(|| {
                    std::env::var_os("OPENCLAW_HOME")
                        .map(|root| PathBuf::from(root).join(".openclaw"))
                })
                .unwrap_or_else(|| home.join(".openclaw")),
            agents: home.join(".agents"),
        }
    }
}

/// `harness.v1.skills.list` request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct SkillsQuery {
    /// Only this harness id. `None` lists every harness.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness: Option<String>,
    /// Only this precedence class.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<SkillScope>,
    /// Working tree whose project roots are scanned. Defaults to the process
    /// working directory.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<PathBuf>,
    /// Config homes to read.
    pub homes: SkillHomes,
}

/// Every harness that has a skills root, in product order.
pub const SKILL_HARNESSES: &[&str] = &[
    HarnessId::CLAUDE_CODE,
    HarnessId::CODEX,
    HarnessId::OPENCODE,
    HarnessId::PI,
    HarnessId::HERMES,
    HarnessId::OPENCLAW,
];

/// How deep a grouped skills root is walked. Hermes groups by category
/// (`skills/<category>/<skill>/SKILL.md`) and OpenClaw allows one grouping
/// level, so three is a whole category tree plus slack.
const MAX_GROUP_DEPTH: usize = 3;
/// How far up from `cwd` project roots are looked for.
const MAX_ANCESTORS: usize = 32;
/// Bytes of a `SKILL.md` read to find its frontmatter.
const FRONTMATTER_READ_BYTES: usize = 8 * 1024;
/// Ceiling on rows from one root, so a mistaken root cannot hang a listing.
const MAX_ROWS_PER_ROOT: usize = 512;

/// Directory names never treated as a skill or walked into.
const SKIPPED_DIRS: &[&str] = &["node_modules", "target", ".git", "scripts", "references"];

/// List every installed skill package the query selects.
///
/// Read-only: nothing here creates, writes, or removes a path.
pub fn list_skills(query: &SkillsQuery) -> Vec<SkillRow> {
    let cwd = query
        .cwd
        .clone()
        .or_else(|| std::env::current_dir().ok())
        .unwrap_or_else(|| PathBuf::from("."));
    let mut rows = Vec::new();
    let mut seen: BTreeSet<(String, PathBuf)> = BTreeSet::new();
    for harness in SKILL_HARNESSES {
        if let Some(wanted) = query.harness.as_deref() {
            if wanted != *harness {
                continue;
            }
        }
        let id = HarnessId::new(*harness);
        for (scope, root) in skill_roots(*harness, &query.homes, &cwd) {
            if query.scope.is_some_and(|wanted| wanted != scope) {
                continue;
            }
            let mut found = Vec::new();
            collect_root(&id, scope, &root, 0, &mut found);
            for row in found {
                if seen.insert((row.harness.as_str().to_string(), row.location.clone())) {
                    rows.push(row);
                }
            }
        }
    }
    apply_codex_enablement(&query.homes, &mut rows);
    rows.sort_by(|a, b| {
        a.harness
            .as_str()
            .cmp(b.harness.as_str())
            .then(a.scope.cmp(&b.scope))
            .then(a.name.cmp(&b.name))
            .then(a.location.cmp(&b.location))
    });
    rows
}

/// Every `(scope, root)` a harness's own loader would consult, restricted to
/// the roots that exist right now.
pub fn skill_roots(harness: &str, homes: &SkillHomes, cwd: &Path) -> Vec<(SkillScope, PathBuf)> {
    let mut roots: Vec<(SkillScope, PathBuf)> = Vec::new();
    match harness {
        HarnessId::CLAUDE_CODE => {
            for managed in claude_managed_roots() {
                roots.push((SkillScope::Managed, managed));
            }
            roots.push((SkillScope::User, homes.claude_code.join("skills")));
            for plugin in claude_plugin_roots(&homes.claude_code) {
                roots.push((SkillScope::Plugin, plugin));
            }
            for project in project_roots(cwd, &[&[".claude", "skills"]]) {
                roots.push((SkillScope::Project, project));
            }
        }
        HarnessId::CODEX => {
            roots.push((SkillScope::Managed, PathBuf::from("/etc/codex/skills")));
            roots.push((
                SkillScope::Bundled,
                homes.codex.join("skills").join(".system"),
            ));
            roots.push((SkillScope::User, homes.agents.join("skills")));
            roots.push((SkillScope::User, homes.codex.join("skills")));
            for project in project_roots(cwd, &[&[".agents", "skills"]]) {
                roots.push((SkillScope::Project, project));
            }
        }
        HarnessId::OPENCODE => {
            roots.push((SkillScope::User, homes.opencode.join("skill")));
            roots.push((SkillScope::User, homes.opencode.join("skills")));
            for project in project_roots(cwd, &[&[".opencode", "skill"], &[".opencode", "skills"]])
            {
                roots.push((SkillScope::Project, project));
            }
        }
        HarnessId::PI => {
            roots.push((SkillScope::User, homes.pi.join("skills")));
            roots.push((SkillScope::User, homes.agents.join("skills")));
            for project in project_roots(cwd, &[&[".pi", "skills"], &[".agents", "skills"]]) {
                roots.push((SkillScope::Project, project));
            }
        }
        HarnessId::HERMES => {
            roots.push((SkillScope::User, homes.hermes.join("skills")));
            for profile in hermes_profile_roots(&homes.hermes) {
                roots.push((SkillScope::User, profile));
            }
        }
        HarnessId::OPENCLAW => {
            roots.push((SkillScope::Managed, homes.openclaw.join("skills")));
            roots.push((SkillScope::Plugin, homes.openclaw.join("plugin-skills")));
            roots.push((SkillScope::User, homes.agents.join("skills")));
            let workspace = homes.openclaw.join("workspace");
            roots.push((SkillScope::Project, workspace.join("skills")));
            roots.push((
                SkillScope::Project,
                workspace.join(".agents").join("skills"),
            ));
        }
        _ => {}
    }
    roots.retain(|(_, root)| root.is_dir());
    roots
}

/// The roots supercode may WRITE a skill package into, in the harness's own
/// precedence order — the same table [`skill_roots`] reads, narrowed to the
/// two scopes a client may address and NOT filtered by existence (an install
/// creates the root the harness's loader would then read).
///
/// Empty means "no writable root": every scope a harness owns rather than the
/// user (`managed`, `plugin`, `bundled`), Hermes's and OpenClaw's roots (whose
/// door is their own CLI verb, never a directory supercode writes behind their
/// back), and every harness with no skills root at all.
pub fn writable_skill_roots(
    harness: &str,
    scope: SkillScope,
    homes: &SkillHomes,
    cwd: &Path,
) -> Vec<PathBuf> {
    if !matches!(scope, SkillScope::User | SkillScope::Project) {
        return Vec::new();
    }
    let project = |markers: &[&[&str]]| -> Vec<PathBuf> {
        markers
            .iter()
            .map(|marker| {
                let mut root = cwd.to_path_buf();
                for segment in *marker {
                    root = root.join(segment);
                }
                root
            })
            .collect()
    };
    match (harness, scope) {
        (HarnessId::CLAUDE_CODE, SkillScope::User) => vec![homes.claude_code.join("skills")],
        (HarnessId::CLAUDE_CODE, SkillScope::Project) => project(&[&[".claude", "skills"]]),
        (HarnessId::CODEX, SkillScope::User) => {
            vec![homes.agents.join("skills"), homes.codex.join("skills")]
        }
        (HarnessId::CODEX, SkillScope::Project) => project(&[&[".agents", "skills"]]),
        (HarnessId::OPENCODE, SkillScope::User) => {
            vec![homes.opencode.join("skill"), homes.opencode.join("skills")]
        }
        (HarnessId::OPENCODE, SkillScope::Project) => {
            project(&[&[".opencode", "skill"], &[".opencode", "skills"]])
        }
        (HarnessId::PI, SkillScope::User) => {
            vec![homes.pi.join("skills"), homes.agents.join("skills")]
        }
        (HarnessId::PI, SkillScope::Project) => {
            project(&[&[".pi", "skills"], &[".agents", "skills"]])
        }
        _ => Vec::new(),
    }
}

/// A skill package's own declared name: `SKILL.md` frontmatter `name`, else
/// the directory's own name — exactly the rule [`list_skills`] applies, so a
/// row installed here is found again by the name the loader will report.
///
/// `None` when the directory holds no `SKILL.md` at all.
pub fn declared_skill_name(dir: &Path) -> Option<String> {
    let manifest = dir.join("SKILL.md");
    if !manifest.is_file() {
        return None;
    }
    let front = read_frontmatter(&manifest);
    front
        .get("name")
        .map(String::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
        .or_else(|| {
            dir.file_name()
                .and_then(|name| name.to_str())
                .map(str::to_string)
        })
}

/// Claude Code's enterprise-managed skill directory, per platform.
fn claude_managed_roots() -> Vec<PathBuf> {
    #[cfg(target_os = "macos")]
    {
        vec![PathBuf::from(
            "/Library/Application Support/ClaudeCode/skills",
        )]
    }
    #[cfg(not(target_os = "macos"))]
    {
        vec![PathBuf::from("/etc/claude-code/skills")]
    }
}

/// `<claude home>/plugins/cache/<marketplace>/<plugin>/<version>/skills` — the
/// installed, materialized plugin bundles. Fixed depth, so this stays cheap.
fn claude_plugin_roots(claude_home: &Path) -> Vec<PathBuf> {
    let cache = claude_home.join("plugins").join("cache");
    let mut roots = Vec::new();
    for marketplace in child_dirs(&cache) {
        for plugin in child_dirs(&marketplace) {
            for version in child_dirs(&plugin) {
                let skills = version.join("skills");
                if skills.is_dir() {
                    roots.push(skills);
                }
            }
        }
    }
    roots
}

/// `<HERMES_HOME>/profiles/<name>/skills` — profile mode points `HERMES_HOME`
/// at `<root>/profiles/<name>`, so both layouts are read from one root.
fn hermes_profile_roots(hermes_home: &Path) -> Vec<PathBuf> {
    child_dirs(&hermes_home.join("profiles"))
        .into_iter()
        .map(|profile| profile.join("skills"))
        .filter(|root| root.is_dir())
        .collect()
}

fn child_dirs(dir: &Path) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut out: Vec<PathBuf> = entries
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| path.is_dir())
        .collect();
    out.sort();
    out
}

/// Project roots under `cwd` and its ancestors, for each relative marker.
///
/// The walk stops at the enclosing repository (the first ancestor holding
/// `.git`, inclusive) — Codex and opencode both bound their own project scan
/// that way ("every dir cwd→repo-root", "cwd→worktree root") — and at
/// [`MAX_ANCESTORS`] otherwise.
fn project_roots(cwd: &Path, markers: &[&[&str]]) -> Vec<PathBuf> {
    let mut roots = Vec::new();
    let mut seen = BTreeSet::new();
    for ancestor in cwd.ancestors().take(MAX_ANCESTORS) {
        for marker in markers {
            let mut root = ancestor.to_path_buf();
            for segment in *marker {
                root = root.join(segment);
            }
            if root.is_dir() && seen.insert(root.clone()) {
                roots.push(root);
            }
        }
        if ancestor.join(".git").exists() {
            break;
        }
    }
    roots
}

/// Walk one root. A directory holding `SKILL.md` is a skill; a directory that
/// only groups other skills (Hermes categories, OpenClaw groups) is walked
/// through; a leaf directory with neither still lists, by its own name.
fn collect_root(
    harness: &HarnessId,
    scope: SkillScope,
    root: &Path,
    depth: usize,
    out: &mut Vec<SkillRow>,
) {
    if out.len() >= MAX_ROWS_PER_ROOT {
        return;
    }
    for dir in child_dirs(root) {
        if out.len() >= MAX_ROWS_PER_ROOT {
            return;
        }
        let Some(name) = dir.file_name().and_then(|name| name.to_str()) else {
            continue;
        };
        if SKIPPED_DIRS.contains(&name) || name.starts_with('.') {
            continue;
        }
        let manifest = dir.join("SKILL.md");
        if manifest.is_file() {
            out.push(read_skill(harness, scope, &dir, name, &manifest));
            continue;
        }
        let before = out.len();
        if depth + 1 < MAX_GROUP_DEPTH {
            collect_root(harness, scope, &dir, depth + 1, out);
        }
        if out.len() == before {
            // A directory with no manifest and no skills under it is still an
            // installed package by name — the harness names it the same way.
            out.push(SkillRow {
                name: name.to_string(),
                harness: harness.clone(),
                scope,
                location: dir.clone(),
                description: None,
                version: None,
                enabled: None,
            });
        }
    }
}

fn read_skill(
    harness: &HarnessId,
    scope: SkillScope,
    dir: &Path,
    dir_name: &str,
    manifest: &Path,
) -> SkillRow {
    let front = read_frontmatter(manifest);
    SkillRow {
        name: front
            .get("name")
            .map(String::as_str)
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .unwrap_or(dir_name)
            .to_string(),
        harness: harness.clone(),
        scope,
        location: dir.to_path_buf(),
        description: front.get("description").map(|value| one_line(value)),
        version: front
            .get("version")
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty()),
        enabled: frontmatter_enabled(&front),
    }
}

/// A skill's own frontmatter is the only per-skill enablement statement the
/// SKILL.md standard makes: `enabled: false`, or pi's
/// `disable-model-invocation: true` (`inventory/pi.md` §2).
fn frontmatter_enabled(front: &std::collections::BTreeMap<String, String>) -> Option<bool> {
    if let Some(value) = front.get("enabled") {
        return parse_bool(value);
    }
    if let Some(value) = front.get("disable-model-invocation") {
        return parse_bool(value).map(|disabled| !disabled);
    }
    None
}

fn parse_bool(value: &str) -> Option<bool> {
    match value
        .trim()
        .trim_matches(['"', '\''])
        .to_ascii_lowercase()
        .as_str()
    {
        "true" | "yes" | "on" => Some(true),
        "false" | "no" | "off" => Some(false),
        _ => None,
    }
}

fn one_line(value: &str) -> String {
    value.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Lenient YAML-frontmatter scan: a leading `---` fence, then top-level
/// `key: value` lines until the closing fence. Indented lines, list items,
/// and anything unparseable are skipped rather than failing the skill —
/// every harness's own loader is lenient here too.
pub(crate) fn read_frontmatter(manifest: &Path) -> std::collections::BTreeMap<String, String> {
    let mut out = std::collections::BTreeMap::new();
    let Ok(text) = std::fs::read_to_string(manifest) else {
        return out;
    };
    let head: String = text.chars().take(FRONTMATTER_READ_BYTES).collect();
    let mut lines = head.lines();
    match lines.next().map(str::trim) {
        Some("---") => {}
        _ => return out,
    }
    // BP-5: a key whose value is empty opens a YAML BLOCK SEQUENCE — the
    // shape `paths:`/`allowed-tools:` are usually written in (`  - src/**`).
    // Its items are collected into the same comma-joined single-line form an
    // inline list (`paths: [a, b]`) already produces, so every consumer reads
    // one spelling through [`frontmatter_list`].
    let mut pending_block: Option<String> = None;
    for line in lines {
        let trimmed = line.trim_end();
        if trimmed.trim() == "---" || trimmed.trim() == "..." {
            break;
        }
        if trimmed.is_empty() || trimmed.trim_start().starts_with('#') {
            continue;
        }
        if trimmed.starts_with(char::is_whitespace) {
            let item = trimmed.trim();
            if let (Some(key), Some(item)) = (pending_block.as_ref(), item.strip_prefix("- ")) {
                let item = item.trim().trim_matches(['"', '\'']).trim().to_string();
                if !item.is_empty() {
                    out.entry(key.clone())
                        .and_modify(|v| {
                            if !v.is_empty() {
                                v.push_str(", ");
                            }
                            v.push_str(&item);
                        })
                        .or_insert(item);
                }
            }
            continue;
        }
        pending_block = None;
        let Some((key, value)) = trimmed.split_once(':') else {
            continue;
        };
        let key = key.trim().to_ascii_lowercase();
        let value = value.trim().trim_matches(['"', '\'']).trim().to_string();
        if key.is_empty() {
            continue;
        }
        if value.is_empty() {
            pending_block = Some(key);
            continue;
        }
        out.entry(key).or_insert(value);
    }
    out
}

/// BP-5: one frontmatter value read as a LIST — the inline form
/// (`paths: [a, b]`, `allowed-tools: Bash(git status:*), Read`) and the
/// block form [`read_frontmatter`] flattens into it. Splitting is on commas
/// only, because a rule/tool pattern legitimately contains spaces
/// (`Bash(git status:*)`).
pub(crate) fn frontmatter_list(value: &str) -> Vec<String> {
    value
        .trim()
        .trim_start_matches('[')
        .trim_end_matches(']')
        .split(',')
        .map(|item| item.trim().trim_matches(['"', '\'']).trim().to_string())
        .filter(|item| !item.is_empty())
        .collect()
}

/// Codex's `[skills]` block is an enable/disable overlay keyed by name or by
/// absolute path (`codex-rs/config/src/skills_config.rs` at pin `1f0566d3`),
/// plus `[skills.bundled] enabled` for the bundled cache. Apply it to the
/// Codex rows; every other harness keeps `enabled: None`.
fn apply_codex_enablement(homes: &SkillHomes, rows: &mut [SkillRow]) {
    let config = homes.codex.join("config.toml");
    let Ok(text) = std::fs::read_to_string(&config) else {
        return;
    };
    let Ok(doc) = text.parse::<toml::Value>() else {
        return;
    };
    let Some(skills) = doc.get("skills") else {
        return;
    };
    let bundled = skills
        .get("bundled")
        .and_then(|value| value.get("enabled"))
        .and_then(toml::Value::as_bool);
    let entries: Vec<(Option<String>, Option<PathBuf>, bool)> = skills
        .get("config")
        .and_then(toml::Value::as_array)
        .map(|array| {
            array
                .iter()
                .filter_map(|entry| {
                    let enabled = entry.get("enabled").and_then(toml::Value::as_bool)?;
                    let name = entry
                        .get("name")
                        .and_then(toml::Value::as_str)
                        .map(str::to_string);
                    let path = entry
                        .get("path")
                        .and_then(toml::Value::as_str)
                        .map(PathBuf::from);
                    Some((name, path, enabled))
                })
                .collect()
        })
        .unwrap_or_default();
    for row in rows.iter_mut() {
        if row.harness.as_str() != HarnessId::CODEX {
            continue;
        }
        if row.scope == SkillScope::Bundled {
            if let Some(enabled) = bundled {
                row.enabled = Some(enabled);
            }
        }
        for (name, path, enabled) in &entries {
            let matches_name = name.as_deref() == Some(row.name.as_str());
            let matches_path = path.as_deref() == Some(row.location.as_path());
            if matches_name || matches_path {
                row.enabled = Some(*enabled);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// BP-6: the LOOP's own skill set (catalog D1 "Skill-invocation surface",
// D2 "Skills (progressive-disclosure packages)", D7 "Skill discovery from
// multiple roots").
//
// ORCH-11 above answers "what has this OTHER harness installed?" — a
// read-only observation. Everything below answers "what will supercode's own
// agent loop load?", and it answers it by reusing exactly the same root table
// and the same `SKILL.md` frontmatter reader, so the loop can never discover a
// set `supercode skills list` disagrees with.
//
// The preset NAMES whose root table to read (`[core.skills] harness`), so
// `cc-parity` discovers skills the way Claude Code documents
// (enterprise/managed > `~/.claude/skills` > plugins > project
// `.claude/skills`, plus nested subdirectory skills as `dir:skill`) and
// `cx-parity` the way Codex documents (`/etc/codex/skills`, the bundled
// `.system` cache, `~/.agents/skills` + `$CODEX_HOME/skills`, repo
// `.agents/skills` from cwd to the repo root).
// ---------------------------------------------------------------------------

/// How far BELOW `cwd` nested project skill roots are looked for (Claude
/// Code's "nested `.claude/skills/` in subdirectories", `dir:skill`).
const MAX_NESTED_DEPTH: usize = 3;

/// Ceiling on directories visited by the nested scan, so a huge working tree
/// cannot make agent construction expensive.
const MAX_NESTED_DIRS: usize = 400;

/// Ceiling on the bytes of a skill body handed to the model in one load.
pub const MAX_SKILL_BODY_BYTES: usize = 64 * 1024;

/// The substitution token a skill body uses for the text that followed its
/// invocation (`docs:skills#available-string-substitutions`).
const ARGUMENTS_TOKEN: &str = "$ARGUMENTS";

/// One SKILL.md package the supercode loop itself will load.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoopSkill {
    /// The name the loop invokes it by — frontmatter `name` (else the
    /// directory name), qualified `plugin:skill` / `dir:skill` where the
    /// source harness qualifies it.
    pub name: String,
    /// Frontmatter `description`, one line. The INDEX line's whole payload;
    /// a skill without one is still invocable, just undescribed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Frontmatter `version`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// Precedence class of the root it came from.
    pub scope: SkillScope,
    /// The skill's own directory.
    pub dir: PathBuf,
    /// `<dir>/SKILL.md` — where the BODY lives, read only on invocation.
    pub manifest: PathBuf,
    /// Whether the model may see it in the prompt index at all. `false` for
    /// `enabled: false` / `disable-model-invocation: true` frontmatter: the
    /// skill stays user-invocable by name, it is simply not advertised
    /// (cc§7 "Invocation control", pi§2).
    pub model_invocable: bool,
    /// BP-5 (cc§7 "Invocation control": "pre-approved tools while active"):
    /// the package's own `allowed-tools` frontmatter, verbatim. Its only
    /// consumer is [`ShellInjection::expand`], where it pre-approves this
    /// body's OWN `` !`cmd` `` commands and nothing else — it never widens
    /// what the model's tool calls are allowed to do.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allowed_tools: Vec<String>,
    /// BP-5 (cc§7 "Skill frontmatter": `arguments` (named positional)): the
    /// package's ARGUMENT SCHEMA — the names its body substitutes as
    /// `$name`, in positional order. Empty when the body only uses
    /// `$ARGUMENTS`/`$1`..`$9`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub argument_names: Vec<String>,
    /// BP-5 (cc§7 `argument-hint`): the one-line usage hint shown beside
    /// this package in the prompt index, so a model calling it by name knows
    /// what the trailing text should be.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub argument_hint: Option<String>,
}

impl LoopSkill {
    /// The prompt-index line: name and description only — never the body.
    pub fn index_line(&self) -> String {
        let mut line = match self.description.as_deref() {
            Some(description) if !description.is_empty() => {
                format!("- {}: {description}", self.name)
            }
            _ => format!("- {}", self.name),
        };
        // BP-5: the argument schema travels with the index line, so a caller
        // knows the shape of the trailing text before loading the body.
        if let Some(hint) = self.argument_hint.as_deref().filter(|h| !h.is_empty()) {
            line.push_str(&format!(" (arguments: {hint})"));
        } else if !self.argument_names.is_empty() {
            line.push_str(&format!(" (arguments: {})", self.argument_names.join(" ")));
        }
        line
    }

    /// Read this skill's BODY (everything after the frontmatter fence),
    /// substituting `$ARGUMENTS` / `$1`..`$9` with the invocation's trailing
    /// text. This is the ONLY function that spends a body's tokens; nothing
    /// on the discovery path reads past the frontmatter.
    pub fn body(&self, arguments: &str) -> std::io::Result<String> {
        let text = std::fs::read_to_string(&self.manifest)?;
        Ok(substitute_arguments(
            &strip_frontmatter(&text),
            arguments,
            &self.argument_names,
        ))
    }

    /// BP-5: [`Self::body`], then the `` !`cmd` `` expansion `shell`
    /// authorizes (cc§7 "Dynamic context injection"). This is the door every
    /// invocation surface uses — the `skill` tool, `/name`, `/skill:name`
    /// and `$slug` — so one body cannot mean two things depending on which
    /// door loaded it. With shell injection off (the default) this is
    /// exactly [`Self::body`].
    pub fn body_with_shell(
        &self,
        arguments: &str,
        shell: &ShellInjection,
    ) -> std::io::Result<String> {
        let body = self.body(arguments)?;
        Ok(shell.expand(&body, &self.allowed_tools))
    }
}

/// Everything after a leading `---` frontmatter fence (the whole text when
/// there is no fence), capped at [`MAX_SKILL_BODY_BYTES`].
pub(crate) fn strip_frontmatter(text: &str) -> String {
    let body = match text.strip_prefix("---") {
        Some(rest) => match rest.split_once("\n---") {
            Some((_, after)) => after
                .trim_start_matches(['-', '\r'])
                .trim_start_matches('\n'),
            None => text,
        },
        None => text,
    };
    let body = body.trim();
    if body.len() <= MAX_SKILL_BODY_BYTES {
        return body.to_string();
    }
    let mut cut = MAX_SKILL_BODY_BYTES;
    while cut > 0 && !body.is_char_boundary(cut) {
        cut -= 1;
    }
    format!("{}\n\n[skill body truncated]", &body[..cut])
}

/// `$ARGUMENTS`, `$ARGUMENTS[N]`, `$1`..`$9` and — BP-5 — `$name` for each
/// name in the package's own `arguments` frontmatter, substituted in
/// positional order (cc§7 "String substitutions").
///
/// Named substitution runs FIRST so a schema name can never be shadowed by
/// a positional token, and a name with no matching argument substitutes
/// empty rather than leaving a live `$name` in the model's instructions.
fn substitute_arguments(body: &str, arguments: &str, argument_names: &[String]) -> String {
    let positional: Vec<&str> = arguments.split_whitespace().collect();
    let mut out = body.to_string();
    for (index, name) in argument_names.iter().enumerate() {
        let token = format!("${name}");
        if !out.contains(&token) {
            continue;
        }
        out = out.replace(&token, positional.get(index).copied().unwrap_or(""));
    }
    for (index, value) in positional.iter().enumerate() {
        let token = format!("{ARGUMENTS_TOKEN}[{index}]");
        if out.contains(&token) {
            out = out.replace(&token, value);
        }
    }
    out = out.replace(ARGUMENTS_TOKEN, arguments);
    for index in 1..=9usize {
        let token = format!("${index}");
        if !out.contains(&token) {
            continue;
        }
        out = out.replace(&token, positional.get(index - 1).copied().unwrap_or(""));
    }
    out
}

// ---------------------------------------------------------------------------
// BP-5 (catalog D2 "Shell-output injection in templates/skills", cc§7
// "Dynamic context injection": "`` !`command` `` inline and ```` ```! ````
// block shell execution inside skill bodies at load time (disable org-wide
// with `disableSkillShellExecution`)").
//
// The whole gate is the ONE permissions engine (`crate::permissions`): the
// config's own deny/ask/allow rules, its protected-path floor and its
// approval default decide every command, exactly as they decide a `bash`
// tool call. A body's own `allowed-tools` frontmatter contributes to the
// ALLOW tier only, and only for its own commands — a deny rule still wins
// first-match, so a body cannot pre-approve itself past a protected path.
// ---------------------------------------------------------------------------

/// Ceiling on the bytes one command's output contributes to a body.
const MAX_INJECTED_OUTPUT_BYTES: usize = 8 * 1024;

/// How long one injected command may run before it is killed.
const SHELL_INJECTION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// How many commands one body may run, so a hostile body cannot turn prompt
/// assembly into an unbounded batch of subprocesses.
const MAX_INJECTED_COMMANDS: usize = 16;

/// The authorization a `` !`cmd` `` expansion runs under — built from a
/// resolved [`crate::Config`], never assembled ad hoc at a call site.
#[derive(Debug, Clone)]
pub struct ShellInjection {
    enabled: bool,
    cwd: PathBuf,
    rules: crate::permissions::RuleSet,
    default: crate::permissions::Decision,
}

impl ShellInjection {
    /// The policy `config` authorizes. Disabled (the default) makes
    /// [`Self::expand`] an identity function that spawns nothing.
    pub fn from_config(config: &crate::Config) -> Self {
        Self {
            enabled: config.skills_shell_injection,
            cwd: config.cwd.clone(),
            rules: crate::permissions::rules_for_config(config),
            // The same baseline a `bash` tool call gets under this config —
            // `bash` is the tool actually being asked for here.
            default: crate::permissions::default_decision(config, "bash"),
        }
    }

    /// A policy that executes nothing — the shape every caller that has no
    /// config at hand must use.
    pub fn disabled() -> Self {
        Self {
            enabled: false,
            cwd: PathBuf::from("."),
            rules: crate::permissions::RuleSet::default(),
            default: crate::permissions::Decision::Ask,
        }
    }

    /// Whether this policy may run anything at all.
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Replace every `` !`cmd` `` (and ```` ```! ```` block) in `body` with
    /// that command's output. `allowed_tools` is the BODY's own
    /// `allowed-tools` frontmatter, folded into the allow tier for these
    /// commands only.
    ///
    /// A command the engine does not resolve to
    /// [`crate::permissions::Decision::Allow`] is never run: the token is
    /// replaced by the refusal and its reason, in place, so the model reads
    /// what was withheld instead of silently receiving nothing.
    pub fn expand(&self, body: &str, allowed_tools: &[String]) -> String {
        if !self.enabled || !(body.contains("!`") || body.contains("```!")) {
            return body.to_string();
        }
        let mut rules = self.rules.clone();
        rules
            .allow
            .extend(allowed_tools_to_allow_rules(allowed_tools));
        let mut out = String::with_capacity(body.len());
        let mut rest = body;
        let mut ran = 0usize;
        while let Some((before, command, after, closing)) = next_injection(rest) {
            out.push_str(before);
            ran += 1;
            if ran > MAX_INJECTED_COMMANDS {
                out.push_str(&format!(
                    "[supercode: shell injection stopped after {MAX_INJECTED_COMMANDS} commands]"
                ));
                out.push_str(closing);
                rest = after;
                continue;
            }
            out.push_str(&self.run_one(&rules, &command));
            out.push_str(closing);
            rest = after;
        }
        out.push_str(rest);
        out
    }

    /// One command: gate first, then run. Never the other order.
    fn run_one(&self, rules: &crate::permissions::RuleSet, command: &str) -> String {
        use crate::permissions::Decision;
        let command = command.trim();
        if command.is_empty() {
            return String::new();
        }
        let decision = crate::permissions::evaluate_command(rules, "bash", command, self.default);
        if decision != Decision::Allow {
            return format!(
                "[supercode: `{command}` was not run — permissions engine: {decision:?}. \
                 Allow it with a permission rule or the body's own `allowed-tools`.]"
            );
        }
        match run_injected_command(&self.cwd, command) {
            Ok(text) => text,
            Err(e) => format!("[supercode: `{command}` failed: {e}]"),
        }
    }
}

/// Translate Claude Code's `allowed-tools` spellings (`Bash(git status:*)`,
/// `Read`, `Bash`) into this engine's own rule syntax
/// ([`crate::permissions::RuleSet`]): the tool name lowercased, and cc's
/// `cmd:*` prefix form rewritten as the `cmd*` glob this engine matches
/// canonicalized command text with. An entry that names no recognizable
/// tool contributes NOTHING — a frontmatter typo must never widen a rule
/// set.
fn allowed_tools_to_allow_rules(entries: &[String]) -> Vec<String> {
    let mut out = Vec::new();
    for entry in entries {
        let entry = entry.trim();
        if entry.is_empty() {
            continue;
        }
        let (tool, subject) = match entry.split_once('(') {
            Some((tool, rest)) => match rest.strip_suffix(')') {
                Some(subject) => (tool.trim(), Some(subject.trim())),
                None => continue,
            },
            None => (entry, None),
        };
        // Only the shell tools matter here: this rule set gates `!`cmd``
        // and nothing else, so a `Read`/`Edit` entry is simply not about
        // this surface.
        let tool = tool.to_ascii_lowercase();
        if !matches!(tool.as_str(), "bash" | "shell" | "powershell") {
            continue;
        }
        match subject {
            None => out.push("bash".to_string()),
            Some(subject) => {
                let glob = subject.replace(":*", "*");
                out.push(format!("bash({glob})"));
            }
        }
    }
    out
}

/// Find the next `` !`cmd` `` or ```` ```! ```` block in `text`. Returns
/// `(text before it, the command, the text after it, the closing text to
/// re-emit)`. The block form re-emits nothing of its own — the fence is
/// consumed with the command.
fn next_injection(text: &str) -> Option<(&str, String, &str, &'static str)> {
    let inline = text.find("!`");
    let block = text.find("```!");
    match (inline, block) {
        (Some(i), Some(b)) if b < i => split_block(text, b),
        (Some(i), _) => split_inline(text, i),
        (None, Some(b)) => split_block(text, b),
        (None, None) => None,
    }
}

fn split_inline(text: &str, at: usize) -> Option<(&str, String, &str, &'static str)> {
    let after_open = &text[at + 2..];
    let end = after_open.find('`')?;
    Some((
        &text[..at],
        after_open[..end].to_string(),
        &after_open[end + 1..],
        "",
    ))
}

fn split_block(text: &str, at: usize) -> Option<(&str, String, &str, &'static str)> {
    let after_open = &text[at + 4..];
    let body_start = after_open.find('\n')? + 1;
    let body = &after_open[body_start..];
    let end = body.find("```")?;
    let after = &body[end + 3..];
    Some((&text[..at], body[..end].trim().to_string(), after, ""))
}

/// Run one authorized command and render its output for a prompt: stdout
/// (plus stderr when the command failed), trimmed, capped at
/// [`MAX_INJECTED_OUTPUT_BYTES`], killed at [`SHELL_INJECTION_TIMEOUT`].
///
/// Synchronous on purpose: body expansion happens on the prompt-assembly
/// path, which is not an async context in every caller (`Agent::expand_prompt`
/// is a sync method with sync callers).
fn run_injected_command(cwd: &Path, command: &str) -> std::io::Result<String> {
    use std::process::{Command, Stdio};
    let mut child = Command::new("sh")
        .arg("-c")
        .arg(command)
        .current_dir(cwd)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    let deadline = std::time::Instant::now() + SHELL_INJECTION_TIMEOUT;
    loop {
        match child.try_wait()? {
            Some(_) => break,
            None if std::time::Instant::now() >= deadline => {
                let _ = child.kill();
                let _ = child.wait();
                return Ok(format!(
                    "[supercode: `{command}` timed out after {}s]",
                    SHELL_INJECTION_TIMEOUT.as_secs()
                ));
            }
            None => std::thread::sleep(std::time::Duration::from_millis(10)),
        }
    }
    let output = child.wait_with_output()?;
    let mut text = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if !output.status.success() {
        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
        if !err.is_empty() {
            if !text.is_empty() {
                text.push('\n');
            }
            text.push_str(&err);
        }
    }
    if text.len() > MAX_INJECTED_OUTPUT_BYTES {
        let mut cut = MAX_INJECTED_OUTPUT_BYTES;
        while cut > 0 && !text.is_char_boundary(cut) {
            cut -= 1;
        }
        text.truncate(cut);
        text.push_str("\n[output truncated]");
    }
    Ok(text)
}

/// Resolve one invocation name against a discovered set: exact, then
/// case-insensitively, then the unqualified leaf of a `dir:skill` /
/// `plugin:skill` name when exactly one skill owns that leaf. A leading `/`
/// or `$` sigil is stripped first, so the same resolver serves the slash
/// command, the mention, and the `skill` tool — one name, one answer.
pub fn find_skill<'a>(skills: &'a [LoopSkill], name: &str) -> Option<&'a LoopSkill> {
    let wanted = name.trim().trim_start_matches(['/', '$']).trim();
    if wanted.is_empty() {
        return None;
    }
    if let Some(hit) = skills.iter().find(|skill| skill.name == wanted) {
        return Some(hit);
    }
    if let Some(hit) = skills
        .iter()
        .find(|skill| skill.name.eq_ignore_ascii_case(wanted))
    {
        return Some(hit);
    }
    let mut leaves = skills.iter().filter(|skill| {
        skill
            .name
            .rsplit_once(':')
            .is_some_and(|(_, leaf)| leaf.eq_ignore_ascii_case(wanted))
    });
    let first = leaves.next()?;
    match leaves.next() {
        // Ambiguous leaf: refuse rather than guess — the qualified form is
        // exactly what the harnesses require here.
        Some(_) => None,
        None => Some(first),
    }
}

/// The envelope a loaded body arrives in, identical whichever door invoked
/// it (`skill` tool result, `/name` expansion, `$slug` mention), so a
/// transcript reads the same way in all three.
pub fn render_skill(skill: &LoopSkill, body: &str) -> String {
    format!(
        "# Skill: {}\n(loaded from {})\n\n{body}",
        skill.name,
        skill.dir.display()
    )
}

/// Words too common to identify a skill by. Deliberately tiny: the rule
/// below already requires TWO distinct hits from one description.
const IMPLICIT_STOPWORDS: &[&str] = &[
    "about", "after", "again", "their", "there", "these", "those", "which", "while", "would",
    "should", "could", "every", "other", "using", "when", "with", "that", "this", "from", "into",
];

/// BP-6 (cx§7 "implicit (description-matched) invocation"): the single
/// best skill a message DESCRIBES, or `None`.
///
/// Off by default (`[core.skills] implicit_match`), because an implicit
/// load spends a body's tokens the user never asked for. The rule is
/// deliberately conservative: the skill's own name appearing as a word, or
/// TWO distinct significant words from its description. At most one skill
/// is ever matched implicitly.
pub fn implicit_skill_match<'a>(skills: &'a [LoopSkill], text: &str) -> Option<&'a LoopSkill> {
    let haystack: BTreeSet<String> = text
        .split(|c: char| !c.is_alphanumeric() && c != '-')
        .map(|word| word.to_ascii_lowercase())
        .filter(|word| word.len() >= 4)
        .collect();
    if haystack.is_empty() {
        return None;
    }
    let mut best: Option<(usize, &LoopSkill)> = None;
    for skill in skills.iter().filter(|skill| skill.model_invocable) {
        let name = skill.name.to_ascii_lowercase();
        if haystack.contains(&name) {
            return Some(skill);
        }
        let Some(description) = skill.description.as_deref() else {
            continue;
        };
        let hits = description
            .split(|c: char| !c.is_alphanumeric() && c != '-')
            .map(|word| word.to_ascii_lowercase())
            .filter(|word| word.len() >= 5 && !IMPLICIT_STOPWORDS.contains(&word.as_str()))
            .collect::<BTreeSet<String>>()
            .into_iter()
            .filter(|word| haystack.contains(word))
            .count();
        if hits >= 2 && best.is_none_or(|(previous, _)| hits > previous) {
            best = Some((hits, skill));
        }
    }
    best.map(|(_, skill)| skill)
}

/// Discover every SKILL.md package the loop will load, in PRECEDENCE order:
/// the config's own extra roots first (a root a config names is more
/// specific than a discovered one), then the named harness's own documented
/// root table in its own order, then — for Claude Code — nested
/// `<subdir>/.claude/skills` packages under `cwd`, qualified `dir:skill`.
///
/// De-duplicated by invocation NAME (first root wins, the collision rule
/// every one of these harnesses states) and by location (one directory
/// reachable through two roots is one skill).
pub fn load_loop_skills(
    harness: &str,
    homes: &SkillHomes,
    cwd: &Path,
    extra_dirs: &[PathBuf],
) -> Vec<LoopSkill> {
    let id = HarnessId::new(harness);
    let mut roots: Vec<(SkillScope, PathBuf)> = extra_dirs
        .iter()
        .filter(|root| root.is_dir())
        .map(|root| (SkillScope::Project, root.clone()))
        .collect();
    roots.extend(skill_roots(harness, homes, cwd));

    let mut out: Vec<LoopSkill> = Vec::new();
    let mut seen_names: BTreeSet<String> = BTreeSet::new();
    let mut seen_dirs: BTreeSet<PathBuf> = BTreeSet::new();
    for (scope, root) in roots {
        let mut found = Vec::new();
        collect_root(&id, scope, &root, 0, &mut found);
        let qualifier = plugin_qualifier(scope, &root);
        for row in found {
            push_loop_skill(
                row,
                qualifier.as_deref(),
                &mut seen_names,
                &mut seen_dirs,
                &mut out,
            );
        }
    }
    if harness == HarnessId::CLAUDE_CODE {
        for (qualifier, root) in nested_claude_roots(cwd) {
            let mut found = Vec::new();
            collect_root(&id, SkillScope::Project, &root, 0, &mut found);
            for row in found {
                push_loop_skill(
                    row,
                    Some(qualifier.as_str()),
                    &mut seen_names,
                    &mut seen_dirs,
                    &mut out,
                );
            }
        }
        // BP-5 (cc§7 Skills: "custom commands (`.claude/commands/*.md`)
        // merged into skills (same engine, `$ARGUMENTS` etc.)"): a command
        // file IS a skill in Claude Code — one markdown file rather than a
        // directory with a SKILL.md. They are collected LAST, so cc's own
        // collision rule ("skills override same-name … commands") falls out
        // of the same first-root-wins de-duplication every other root uses.
        for (scope, root) in command_roots(homes, cwd) {
            collect_command_root(scope, &root, &mut seen_names, &mut out);
        }
    }
    out
}

/// BP-5: Claude Code's markdown-command roots, personal before project —
/// the same precedence its skill roots use (cc§7 "Skill locations &
/// precedence").
fn command_roots(homes: &SkillHomes, cwd: &Path) -> Vec<(SkillScope, PathBuf)> {
    let mut roots = vec![(SkillScope::User, homes.claude_code.join("commands"))];
    for root in project_roots(cwd, &[&[".claude", "commands"]]) {
        roots.push((SkillScope::Project, root));
    }
    roots.into_iter().filter(|(_, r)| r.is_dir()).collect()
}

/// How deep a command root's subdirectories are read. Claude Code namespaces
/// a command in a subdirectory as `dir:name`; deeper nesting is not a shape
/// this reads.
const MAX_COMMAND_DEPTH: usize = 1;

/// Collect every `*.md` command file under `root` (plus one level of
/// namespacing subdirectories) as a [`LoopSkill`] whose manifest is the
/// markdown file itself.
fn collect_command_root(
    scope: SkillScope,
    root: &Path,
    seen_names: &mut BTreeSet<String>,
    out: &mut Vec<LoopSkill>,
) {
    collect_command_dir(scope, root, None, 0, seen_names, out);
}

fn collect_command_dir(
    scope: SkillScope,
    dir: &Path,
    qualifier: Option<&str>,
    depth: usize,
    seen_names: &mut BTreeSet<String>,
    out: &mut Vec<LoopSkill>,
) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    let mut files: Vec<PathBuf> = Vec::new();
    let mut dirs: Vec<PathBuf> = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            dirs.push(path);
        } else if path.extension().and_then(|e| e.to_str()) == Some("md") {
            files.push(path);
        }
    }
    files.sort();
    dirs.sort();
    for file in files {
        push_command_file(scope, &file, qualifier, seen_names, out);
    }
    if depth >= MAX_COMMAND_DEPTH {
        return;
    }
    for child in dirs {
        let Some(label) = child.file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        if label.starts_with('.') {
            continue;
        }
        let label = label.to_string();
        collect_command_dir(scope, &child, Some(&label), depth + 1, seen_names, out);
    }
}

/// One `.claude/commands/<name>.md` file as a loop skill: frontmatter
/// `name` (else the file stem), qualified `dir:name` inside a namespacing
/// subdirectory, body loaded on invocation exactly like a SKILL.md's.
fn push_command_file(
    scope: SkillScope,
    file: &Path,
    qualifier: Option<&str>,
    seen_names: &mut BTreeSet<String>,
    out: &mut Vec<LoopSkill>,
) {
    let Some(stem) = file.file_stem().and_then(|s| s.to_str()) else {
        return;
    };
    let front = read_frontmatter(file);
    let bare = front
        .get("name")
        .cloned()
        .unwrap_or_else(|| stem.to_string());
    let name = match qualifier {
        Some(prefix) => format!("{prefix}:{bare}"),
        None => bare,
    };
    if !seen_names.insert(name.clone()) {
        return;
    }
    out.push(LoopSkill {
        name,
        description: front.get("description").map(|d| one_line(d)),
        version: front.get("version").cloned(),
        scope,
        dir: file.parent().unwrap_or(file).to_path_buf(),
        manifest: file.to_path_buf(),
        model_invocable: frontmatter_enabled(&front).unwrap_or(true),
        allowed_tools: front
            .get("allowed-tools")
            .map(|v| frontmatter_list(v))
            .unwrap_or_default(),
        argument_names: front
            .get("arguments")
            .map(|v| frontmatter_list(v))
            .unwrap_or_default(),
        argument_hint: front.get("argument-hint").cloned(),
    });
}

/// The loop's skill set for a resolved [`crate::Config`] — empty unless
/// `[core.skills] enabled` is on AND the config names a harness whose root
/// table to read, so a config that says nothing about skills discovers
/// nothing (byte-identical to the pre-BP-6 loop).
pub fn load_for_config(config: &crate::Config) -> Vec<LoopSkill> {
    if !config.skills_enabled {
        return Vec::new();
    }
    let Some(harness) = config.skills_harness.as_deref() else {
        return Vec::new();
    };
    load_loop_skills(
        harness,
        &SkillHomes::default(),
        &config.cwd,
        &config.skills_dirs,
    )
}

/// A skill row becomes a loop skill unless it has no `SKILL.md` at all (a
/// bare grouping directory lists in ORCH-11's inventory, but there is
/// nothing to disclose), it duplicates a directory already taken, or its
/// name is already claimed by a higher-precedence root.
fn push_loop_skill(
    row: SkillRow,
    qualifier: Option<&str>,
    seen_names: &mut BTreeSet<String>,
    seen_dirs: &mut BTreeSet<PathBuf>,
    out: &mut Vec<LoopSkill>,
) {
    let manifest = row.location.join("SKILL.md");
    if !manifest.is_file() {
        return;
    }
    let name = match qualifier {
        Some(prefix) => format!("{prefix}:{}", row.name),
        None => row.name.clone(),
    };
    if !seen_dirs.insert(row.location.clone()) || !seen_names.insert(name.clone()) {
        return;
    }
    let front = read_frontmatter(&manifest);
    out.push(LoopSkill {
        name,
        description: row.description,
        version: row.version,
        scope: row.scope,
        dir: row.location,
        model_invocable: row.enabled.unwrap_or(true),
        allowed_tools: front
            .get("allowed-tools")
            .map(|v| frontmatter_list(v))
            .unwrap_or_default(),
        argument_names: front
            .get("arguments")
            .map(|v| frontmatter_list(v))
            .unwrap_or_default(),
        argument_hint: front.get("argument-hint").cloned(),
        manifest,
    });
}

/// `<plugin>` for a Claude Code plugin root
/// (`.../plugins/cache/<marketplace>/<plugin>/<version>/skills`), so its
/// skills invoke as `plugin:skill` the way Claude Code namespaces them.
fn plugin_qualifier(scope: SkillScope, root: &Path) -> Option<String> {
    if scope != SkillScope::Plugin {
        return None;
    }
    root.parent()
        .and_then(Path::parent)
        .and_then(|dir| dir.file_name())
        .and_then(|name| name.to_str())
        .map(str::to_string)
}

/// Nested `<subdir>/.claude/skills` roots BELOW `cwd`, each with the
/// subdirectory name that qualifies its skills (`dir:skill`, cc§7 "Skill
/// locations & precedence"). Bounded by [`MAX_NESTED_DEPTH`] and
/// [`MAX_NESTED_DIRS`] so this stays cheap in a large working tree.
fn nested_claude_roots(cwd: &Path) -> Vec<(String, PathBuf)> {
    let mut out = Vec::new();
    let mut visited = 0usize;
    let mut frontier: Vec<(String, PathBuf)> = child_dirs(cwd)
        .into_iter()
        .filter_map(|dir| nested_candidate(&dir))
        .collect();
    for _ in 0..MAX_NESTED_DEPTH {
        let mut next = Vec::new();
        for (label, dir) in frontier {
            visited += 1;
            if visited > MAX_NESTED_DIRS {
                return out;
            }
            let root = dir.join(".claude").join("skills");
            if root.is_dir() {
                out.push((label.clone(), root));
            }
            for child in child_dirs(&dir) {
                if let Some((_, child_dir)) = nested_candidate(&child) {
                    next.push((label.clone(), child_dir));
                }
            }
        }
        if next.is_empty() {
            break;
        }
        frontier = next;
    }
    out
}

/// A directory the nested scan may descend into, with the label its skills
/// are qualified by (its own name).
fn nested_candidate(dir: &Path) -> Option<(String, PathBuf)> {
    let name = dir.file_name().and_then(|name| name.to_str())?;
    if name.starts_with('.') || SKIPPED_DIRS.contains(&name) {
        return None;
    }
    Some((name.to_string(), dir.to_path_buf()))
}

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

    fn fixtures() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")
    }

    fn empty_homes(root: &Path) -> SkillHomes {
        let void = root.join("__absent__");
        SkillHomes {
            claude_code: void.clone(),
            codex: void.clone(),
            opencode: void.clone(),
            pi: void.clone(),
            hermes: void.clone(),
            openclaw: void.clone(),
            agents: void,
        }
    }

    #[test]
    fn hermes_categories_flatten_and_frontmatter_wins() {
        let fixtures = fixtures();
        let mut homes = empty_homes(&fixtures);
        homes.hermes = fixtures.join("hermes_home");
        let rows = list_skills(&SkillsQuery {
            harness: Some(HarnessId::HERMES.into()),
            cwd: Some(fixtures.join("hermes_home")),
            homes,
            ..SkillsQuery::default()
        });
        let names: Vec<&str> = rows.iter().map(|row| row.name.as_str()).collect();
        assert!(names.contains(&"arxiv-search"), "{names:?}");
        assert!(names.contains(&"bare-skill"), "{names:?}");
        let arxiv = rows.iter().find(|row| row.name == "arxiv-search").unwrap();
        assert_eq!(arxiv.version.as_deref(), Some("1.4.0"));
        assert_eq!(arxiv.scope, SkillScope::User);
        assert!(arxiv
            .description
            .as_deref()
            .unwrap_or_default()
            .contains("arXiv"));
        let bare = rows.iter().find(|row| row.name == "bare-skill").unwrap();
        assert_eq!(bare.description, None);
        assert_eq!(bare.enabled, None);
    }

    #[test]
    fn openclaw_managed_root_is_read() {
        let fixtures = fixtures();
        let mut homes = empty_homes(&fixtures);
        homes.openclaw = fixtures.join("openclaw_home");
        let rows = list_skills(&SkillsQuery {
            harness: Some(HarnessId::OPENCLAW.into()),
            cwd: Some(fixtures.join("openclaw_home")),
            homes,
            ..SkillsQuery::default()
        });
        assert_eq!(rows.len(), 1, "{rows:?}");
        assert_eq!(rows[0].name, "clawhub-demo");
        assert_eq!(rows[0].scope, SkillScope::Managed);
        assert_eq!(rows[0].enabled, Some(false));
        assert_eq!(rows[0].version.as_deref(), Some("0.3.1"));
    }

    #[test]
    fn scope_filter_selects_one_class() {
        let fixtures = fixtures();
        let mut homes = empty_homes(&fixtures);
        homes.hermes = fixtures.join("hermes_home");
        let base = SkillsQuery {
            harness: Some(HarnessId::HERMES.into()),
            cwd: Some(fixtures.join("hermes_home")),
            homes,
            ..SkillsQuery::default()
        };
        let managed = list_skills(&SkillsQuery {
            scope: Some(SkillScope::Managed),
            ..base.clone()
        });
        assert!(managed.is_empty(), "{managed:?}");
        let user = list_skills(&SkillsQuery {
            scope: Some(SkillScope::User),
            ..base
        });
        assert!(!user.is_empty());
        assert!(
            user.iter().all(|row| row.scope == SkillScope::User),
            "{user:?}"
        );
    }

    /// The unified listing: one call, both fixture harnesses, rows carrying
    /// their own harness.
    #[test]
    fn one_listing_spans_harnesses() {
        let fixtures = fixtures();
        let mut homes = empty_homes(&fixtures);
        homes.hermes = fixtures.join("hermes_home");
        homes.openclaw = fixtures.join("openclaw_home");
        let rows = list_skills(&SkillsQuery {
            cwd: Some(fixtures.join("openclaw_home")),
            homes,
            ..SkillsQuery::default()
        });
        let harnesses: BTreeSet<&str> = rows.iter().map(|row| row.harness.as_str()).collect();
        assert!(harnesses.contains(HarnessId::HERMES), "{harnesses:?}");
        assert!(harnesses.contains(HarnessId::OPENCLAW), "{harnesses:?}");
    }
}