eclipse-core 0.13.2

Core library for eclipse: providers, tools, sessions, config, runtime
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
//! Skills: procedures kept as files, found in several places, offered to the model as an index.
//!
//! A skill is a directory with a `SKILL.md` in it: frontmatter (`name`, `description`, and
//! optionally `version`, `tags`, `requires`) between `---` fences, then a body that says what
//! to do. It may ship `references/`, `scripts/` and `templates/` beside it. The format is the
//! Hermes one, read as it is found: a skill that needs editing before it loads means this
//! module is wrong, not the skill.
//!
//! The prompt carries an *index* (name and description), not the bodies. A body is loaded by
//! the `skill_view` tool when the model decides it applies, which is what keeps fifty skills
//! from costing fifty skills' worth of context on every request.
//!
//! This module only reads. It does not know about tools or the prompt: [`discover`] turns
//! directories into a [`Report`], [`index`] turns a report into text under a budget, and
//! `tools_skills` and `context_files` use those two. The frontmatter parser is written by hand
//! because the workspace has no YAML crate and takes no new dependencies for a dozen keys; it
//! understands the subset real skills use and skips the rest instead of rejecting it.
//!
//! Nothing here is silent. A skill that cannot be loaded stays in the report with the reason,
//! a skill that loses a name to another says which path won, and an index entry that does not
//! fit the budget is named in a note.

use crate::config::{Config, EnvFn};
use crate::plugins::Plugins;
use std::path::{Component, Path, PathBuf};

/// Default ceiling for the prompt index, in characters.
pub const DEFAULT_INDEX_BUDGET_CHARS: usize = 4000;
/// The file that makes a directory a skill.
pub const SKILL_FILE: &str = "SKILL.md";
/// The only places a skill keeps linked files, and so the only places `skill_manage` writes.
pub const SUPPORT_DIRS: [&str; 3] = ["references", "scripts", "templates"];
/// How many directory levels below a root are searched. Hermes groups skills in category
/// folders (`skills/<category>/<skill>/SKILL.md`), so one level of grouping has to work; past
/// that the walk is a guard against a pathological tree, not a feature.
const MAX_DEPTH: usize = 3;
/// Ceiling on the linked files listed for one skill, for the same reason.
const MAX_LINKED: usize = 200;
const MAX_LINKED_DEPTH: usize = 4;
/// The largest `SKILL.md` — or file a skill links — that the loader will read. A skill is
/// instructions, not a data store: a bigger file is reported with its size rather than slurped
/// into memory and into the conversation. The same number is the write limit in `skill_manage`,
/// so nothing the agent writes is too big for it to read back.
pub const MAX_SKILL_FILE_BYTES: u64 = 256 * 1024;

pub(crate) const PREAMBLE: &str =
    "Skills are saved procedures. When a task matches one, call `skill_view` \
with its name to load it before you start, and follow it. `skill_view` with a `path` loads a \
file the skill links.";

/// Where a skill was found. Decides who wins a name clash, and is what `skills list` prints.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
    /// `<config dir>/skills`.
    Shared,
    /// `<config dir>/profiles/<p>/skills`.
    Profile(String),
    /// `<workspace>/.eclipse/skills`.
    Workspace,
    /// `skills/` inside a loaded plugin's directory.
    Plugin(String),
}

impl Source {
    /// `shared`, `profile:<p>`, `workspace` or `plugin:<name>`.
    pub fn label(&self) -> String {
        match self {
            Source::Shared => "shared".into(),
            Source::Profile(p) => format!("profile:{p}"),
            Source::Workspace => "workspace".into(),
            Source::Plugin(n) => format!("plugin:{n}"),
        }
    }

    /// Which skills are kept when the index does not fit: the narrower the scope, the more
    /// deliberately it was put there.
    fn keep_rank(&self) -> u8 {
        match self {
            Source::Workspace => 0,
            Source::Profile(_) => 1,
            Source::Plugin(_) => 2,
            Source::Shared => 3,
        }
    }
}

/// One directory searched for skills.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Root {
    pub source: Source,
    pub dir: PathBuf,
}

/// The skills directories this configuration has, in precedence order: later shadows earlier.
///
/// Shared, then the profile's, then the workspace's, then those shipped in loaded plugins.
/// A plugin that is not enabled is not loaded, so its skills are not either.
pub fn roots_for(cfg: &Config, env: EnvFn, plugins: &Plugins, workspace: &Path) -> Vec<Root> {
    let mut roots = Vec::new();
    if let Some(dir) = cfg.global_context_dir(env) {
        roots.push(Root {
            source: Source::Shared,
            dir: dir.join("skills"),
        });
    }
    if let Some(name) = &cfg.profile {
        if let Some(dir) = crate::config::profile_dir(env, name) {
            roots.push(Root {
                source: Source::Profile(name.clone()),
                dir: dir.join("skills"),
            });
        }
    }
    roots.push(Root {
        source: Source::Workspace,
        dir: workspace.join(".eclipse").join("skills"),
    });
    // `#419`: only a *enabled* plugin's skills are roots. A plugin loaded for nothing but its
    // provider profiles is not enabled, and a `skills/` directory it happens to ship must not
    // become visible just because the manifest was parsed for its wire settings.
    for plugin in plugins.plugins.iter().filter(|p| p.enabled) {
        roots.push(Root {
            source: Source::Plugin(plugin.name.clone()),
            dir: plugin.dir.join("skills"),
        });
    }
    roots
}

/// Where `skill_manage create` puts a new skill: the profile's directory when a profile is in
/// effect, otherwise the shared one. Never the workspace or a plugin — a new skill is the
/// user's, not the project's or a plugin author's.
pub fn user_root(roots: &[Root]) -> Option<&Root> {
    roots
        .iter()
        .find(|r| matches!(r.source, Source::Profile(_)))
        .or_else(|| roots.iter().find(|r| r.source == Source::Shared))
}

/// The frontmatter keys Eclipse reads. Everything else in the block is ignored.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Frontmatter {
    pub name: String,
    pub description: String,
    pub version: Option<String>,
    pub tags: Vec<String>,
    /// Tools the skill expects to have. Informational: the index says so, nothing enforces it.
    pub requires: Vec<String>,
}

/// A skill that loaded: its frontmatter and its body, trimmed of surrounding blank lines.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Skill {
    pub meta: Frontmatter,
    pub body: String,
}

/// Parse the text of a `SKILL.md`.
///
/// The error is the reason, in a sentence, because that is what `skills list` and the startup
/// warning print next to the path.
pub fn parse(text: &str) -> Result<Skill, String> {
    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
    let first = text.lines().next().unwrap_or("");
    if first.trim_end() != "---" {
        return Err(
            "missing `name`: the file has no frontmatter (it must start with a `---` line)".into(),
        );
    }
    let mut rest = &text[first.len()..];
    rest = rest.strip_prefix('\n').unwrap_or(rest);
    let mut lines: Vec<(usize, &str)> = Vec::new();
    let mut line_no = 1;
    let body = loop {
        if rest.is_empty() {
            return Err(
                "unterminated frontmatter: the opening `---` on line 1 has no closing \
`---`"
                    .into(),
            );
        }
        let (line, tail) = match rest.find('\n') {
            Some(i) => (&rest[..i], &rest[i + 1..]),
            None => (rest, ""),
        };
        line_no += 1;
        let line = line.trim_end_matches('\r');
        if line.trim_end() == "---" {
            break tail;
        }
        lines.push((line_no, line));
        rest = tail;
    };

    let meta = read_frontmatter(&lines)?;
    if meta.name.is_empty() {
        return Err("missing `name` in the frontmatter".into());
    }
    let body = body.trim().to_string();
    if body.is_empty() {
        return Err("empty body: the file has frontmatter and nothing after it".into());
    }
    Ok(Skill { meta, body })
}

/// One top-level key with the indented lines that belong to it.
struct Entry<'a> {
    key: &'a str,
    value: &'a str,
    line: usize,
    block: Vec<&'a str>,
}

fn read_frontmatter(lines: &[(usize, &str)]) -> Result<Frontmatter, String> {
    let mut entries: Vec<Entry<'_>> = Vec::new();
    for &(line, text) in lines {
        let blank = text.trim().is_empty();
        let top = !text.starts_with([' ', '\t']);
        if blank || text.trim_start().starts_with('#') {
            continue;
        }
        // `key:` at the left margin starts an entry. A `- item` at the margin continues the
        // previous key's sequence (YAML allows `tags:` followed by unindented dashes).
        if top && !text.starts_with("- ") && text.contains(':') {
            if let Some((key, value)) = text.split_once(':') {
                entries.push(Entry {
                    key: key.trim(),
                    value: value.trim(),
                    line,
                    block: Vec::new(),
                });
            }
        } else if let Some(last) = entries.last_mut() {
            last.block.push(text);
        }
    }

    let mut meta = Frontmatter::default();
    for entry in &entries {
        match entry.key {
            "name" => meta.name = scalar(entry)?,
            "description" => meta.description = scalar(entry)?,
            "version" => {
                let v = scalar(entry)?;
                meta.version = (!v.is_empty()).then_some(v);
            }
            "tags" => meta.tags = sequence(entry)?,
            "requires" => meta.requires = sequence(entry)?,
            _ => {}
        }
    }
    Ok(meta)
}

/// A string value: quoted, plain, or a block scalar (`|` / `>`).
fn scalar(entry: &Entry<'_>) -> Result<String, String> {
    let value = entry.value;
    if value.starts_with(['|', '>']) {
        let folded = value.starts_with('>');
        let indent = entry
            .block
            .iter()
            .filter(|l| !l.trim().is_empty())
            .map(|l| l.len() - l.trim_start().len())
            .min()
            .unwrap_or(0);
        let lines: Vec<&str> = entry
            .block
            .iter()
            .map(|l| l.get(indent..).unwrap_or("").trim_end())
            .collect();
        return Ok(if folded {
            fold(&lines)
        } else {
            lines.join("\n").trim().to_string()
        });
    }
    if value.starts_with(['"', '\'']) {
        let (text, _) = quoted(value).ok_or_else(|| {
            format!(
                "line {}: the quote opened in `{}` is never closed",
                entry.line, entry.key
            )
        })?;
        return Ok(text);
    }
    let mut parts = vec![strip_comment(value).to_string()];
    parts.extend(entry.block.iter().map(|l| l.trim().to_string()));
    Ok(parts
        .into_iter()
        .filter(|p| !p.is_empty())
        .collect::<Vec<_>>()
        .join(" "))
}

/// `>` folding: lines join with a space, a blank line is a paragraph break.
fn fold(lines: &[&str]) -> String {
    let mut out = String::new();
    for line in lines {
        let line = line.trim();
        if line.is_empty() {
            if !out.ends_with('\n') && !out.is_empty() {
                out.push('\n');
            }
        } else {
            if !out.is_empty() && !out.ends_with('\n') {
                out.push(' ');
            }
            out.push_str(line);
        }
    }
    out.trim().to_string()
}

/// A list value: `[a, b]`, one plain item, or `- a` lines beneath the key. Empty is empty.
fn sequence(entry: &Entry<'_>) -> Result<Vec<String>, String> {
    let value = entry.value;
    if let Some(inner) = value.strip_prefix('[') {
        let end = closing_bracket(inner).ok_or_else(|| {
            format!(
                "line {}: the `[` opened in `{}` is never closed",
                entry.line, entry.key
            )
        })?;
        return split_flow(&inner[..end], entry);
    }
    if !value.is_empty() && !value.starts_with('#') {
        return Ok(vec![scalar(&Entry {
            key: entry.key,
            value,
            line: entry.line,
            block: Vec::new(),
        })?]);
    }
    let mut items = Vec::new();
    for line in &entry.block {
        if let Some(item) = line.trim_start().strip_prefix("- ") {
            items.push(scalar(&Entry {
                key: entry.key,
                value: item.trim(),
                line: entry.line,
                block: Vec::new(),
            })?);
        }
    }
    Ok(items)
}

fn split_flow(inner: &str, entry: &Entry<'_>) -> Result<Vec<String>, String> {
    let mut items = Vec::new();
    let mut rest = inner.trim();
    while !rest.is_empty() {
        let (item, tail) = if rest.starts_with(['"', '\'']) {
            let (text, tail) = quoted(rest).ok_or_else(|| {
                format!(
                    "line {}: a quote in `{}` is never closed",
                    entry.line, entry.key
                )
            })?;
            (text, tail.trim_start().strip_prefix(',').unwrap_or(""))
        } else {
            match rest.split_once(',') {
                Some((head, tail)) => (head.trim().to_string(), tail),
                None => (rest.trim().to_string(), ""),
            }
        };
        if !item.is_empty() {
            items.push(item);
        }
        rest = tail.trim_start();
    }
    Ok(items)
}

/// Where the `]` that ends a flow sequence is, skipping any inside quotes.
fn closing_bracket(inner: &str) -> Option<usize> {
    let mut quote: Option<char> = None;
    for (i, c) in inner.char_indices() {
        match (quote, c) {
            (Some(q), c) if c == q => quote = None,
            (None, '"' | '\'') => quote = Some(c),
            (None, ']') => return Some(i),
            _ => {}
        }
    }
    None
}

/// Text before a trailing ` # comment`. A `#` with no space before it is part of the value.
fn strip_comment(value: &str) -> &str {
    let mut prev_space = false;
    for (i, c) in value.char_indices() {
        if c == '#' && prev_space {
            return value[..i].trim_end();
        }
        prev_space = c.is_whitespace();
    }
    value.trim_end()
}

/// A quoted scalar at the start of `text`: its content and what follows the closing quote.
/// `None` when the quote is never closed.
fn quoted(text: &str) -> Option<(String, &str)> {
    let mut chars = text.char_indices();
    let (_, quote) = chars.next()?;
    let mut out = String::new();
    while let Some((i, c)) = chars.next() {
        if c == quote {
            // `''` is a literal quote inside single quotes.
            if quote == '\'' && text[i + 1..].starts_with('\'') {
                out.push('\'');
                chars.next();
                continue;
            }
            return Some((out, &text[i + 1..]));
        }
        if quote == '"' && c == '\\' {
            match chars.next()?.1 {
                'n' => out.push('\n'),
                't' => out.push('\t'),
                '"' => out.push('"'),
                '\\' => out.push('\\'),
                '/' => out.push('/'),
                other => {
                    out.push('\\');
                    out.push(other);
                }
            }
        } else {
            out.push(c);
        }
    }
    None
}

/// A discovered skill, loaded or not.
#[derive(Debug, Clone)]
pub struct Found {
    /// The declared name; the directory's name when the file would not say.
    pub name: String,
    pub source: Source,
    /// The skill's directory.
    pub dir: PathBuf,
    /// Its `SKILL.md`.
    pub path: PathBuf,
    /// The skill, or the reason it is broken.
    pub state: Result<Skill, String>,
    /// What this skill won the name from, nearest loser first. Empty when nothing clashed.
    pub shadows: Vec<Shadowed>,
}

impl Found {
    pub fn skill(&self) -> Option<&Skill> {
        self.state.as_ref().ok()
    }

    pub fn broken_reason(&self) -> Option<&str> {
        self.state.as_ref().err().map(String::as_str)
    }
}

/// A skill that lost its name to another, kept so the report can say what was overridden.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Shadowed {
    pub source: Source,
    pub path: PathBuf,
}

/// Everything discovery found, winners and broken skills alike, in discovery order.
#[derive(Debug, Clone, Default)]
pub struct Report {
    pub found: Vec<Found>,
    /// Directories that could not be read. A missing skills directory is normal and is not
    /// one of these.
    pub problems: Vec<String>,
}

impl Report {
    /// Skills that loaded, with the entry that carries them.
    pub fn active(&self) -> impl Iterator<Item = (&Found, &Skill)> {
        self.found.iter().filter_map(|f| f.skill().map(|s| (f, s)))
    }

    pub fn broken(&self) -> impl Iterator<Item = &Found> {
        self.found.iter().filter(|f| f.state.is_err())
    }

    /// The skill called `name`: the one that won it, or a broken one of that name when no
    /// working one exists, so the caller can say why it cannot be used.
    pub fn get(&self, name: &str) -> Option<&Found> {
        self.active()
            .map(|(f, _)| f)
            .find(|f| f.name == name)
            .or_else(|| self.broken().find(|f| f.name == name))
    }

    /// Names of the skills that loaded, grouped by source label in discovery order. What the
    /// opening pane shows.
    pub fn by_source(&self) -> Vec<(String, Vec<String>)> {
        let mut groups: Vec<(String, Vec<String>)> = Vec::new();
        for (found, _) in self.active() {
            let label = found.source.label();
            match groups.iter_mut().find(|(l, _)| *l == label) {
                Some((_, names)) => names.push(found.name.clone()),
                None => groups.push((label, vec![found.name.clone()])),
            }
        }
        groups
    }
}

/// Look in every root, load what is there, and resolve name clashes: a later root's skill
/// shadows an earlier one's, and the winner records what it beat.
///
/// A broken skill never shadows. If the profile's copy of `backup` is malformed and the shared
/// one works, the working one stays in use and the broken one is reported — losing a procedure
/// because someone's edit left a quote open would be the worse failure.
pub fn discover(roots: &[Root]) -> Report {
    let mut report = Report::default();
    for root in roots {
        let mut dirs = Vec::new();
        collect_skill_dirs(&root.dir, 0, &mut dirs, &mut report.problems);
        for dir in dirs {
            let loaded = load(root.source.clone(), dir);
            if loaded.state.is_ok() {
                let clash = report
                    .found
                    .iter()
                    .position(|f| f.state.is_ok() && f.name == loaded.name);
                if let Some(at) = clash {
                    let beaten = report.found.remove(at);
                    let mut winner = loaded;
                    winner.shadows.push(Shadowed {
                        source: beaten.source,
                        path: beaten.path,
                    });
                    winner.shadows.extend(beaten.shadows);
                    report.found.push(winner);
                    continue;
                }
            }
            report.found.push(loaded);
        }
    }
    report
}

/// [`discover`], narrowed to the names `only` lists (`#509`).
///
/// `None` is every root's skill — the human's agent. `Some(names)` is exactly those names, and an
/// empty list is a bot that sees none: a declaration that says nothing about skills leaves every
/// root in force, and one that says `skills = []` means it. The filter lives here rather than at
/// the five readers, so the index in the prompt and the four `skill_*` tools cannot disagree about
/// what a bot was given.
///
/// A broken skill keeps its place when it was declared: dropping it would turn "your skill is
/// malformed" into "there is no such skill", and the report says which.
pub fn discover_only(roots: &[Root], only: Option<&[String]>) -> Report {
    let mut report = discover(roots);
    if let Some(names) = only {
        report.found.retain(|found| names.contains(&found.name));
    }
    report
}

/// Directories under `dir` that hold a `SKILL.md`, sorted, searching category folders.
fn collect_skill_dirs(
    dir: &Path,
    depth: usize,
    out: &mut Vec<PathBuf>,
    problems: &mut Vec<String>,
) {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
        Err(e) => {
            problems.push(format!(
                "cannot read skills directory {}: {e}",
                dir.display()
            ));
            return;
        }
    };
    let mut children: Vec<PathBuf> = entries
        .filter_map(|e| e.ok())
        .filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
        .map(|e| e.path())
        // `metadata` follows symlinks, so a library kept elsewhere and linked in is found.
        .filter(|p| std::fs::metadata(p).map(|m| m.is_dir()).unwrap_or(false))
        .collect();
    children.sort();
    for child in children {
        // `symlink_metadata`: a `SKILL.md` that is a directory or a dangling link is still a
        // skill that is broken, not a folder to walk past.
        if std::fs::symlink_metadata(child.join(SKILL_FILE)).is_ok() {
            out.push(child);
        } else if depth + 1 < MAX_DEPTH {
            collect_skill_dirs(&child, depth + 1, out, problems);
        }
    }
}

fn load(source: Source, dir: PathBuf) -> Found {
    let path = dir.join(SKILL_FILE);
    let fallback = dir
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_default();
    let state = read_skill(&path);
    let name = match &state {
        Ok(skill) => skill.meta.name.clone(),
        Err(_) => fallback,
    };
    Found {
        name,
        source,
        dir,
        path,
        state,
        shadows: Vec::new(),
    }
}

fn read_skill(path: &Path) -> Result<Skill, String> {
    match std::fs::metadata(path) {
        Ok(m) if m.is_dir() => return Err("`SKILL.md` is a directory, not a file".into()),
        Ok(m) if !m.is_file() => return Err("`SKILL.md` is not a regular file".into()),
        Ok(m) if m.len() > MAX_SKILL_FILE_BYTES => {
            return Err(format!(
                "`SKILL.md` is {} bytes; the limit is {MAX_SKILL_FILE_BYTES}",
                m.len()
            ))
        }
        Ok(_) => {}
        Err(e) => return Err(format!("cannot read `SKILL.md`: {e}")),
    }
    let bytes = std::fs::read(path).map_err(|e| format!("cannot read `SKILL.md`: {e}"))?;
    let text = String::from_utf8(bytes).map_err(|e| {
        format!(
            "`SKILL.md` is not valid UTF-8 (first bad byte at offset {})",
            e.utf8_error().valid_up_to()
        )
    })?;
    parse(&text)
}

/// The prompt index, as it will be injected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Index {
    pub body: String,
    pub chars: usize,
    /// The skills that made it in, in the order listed.
    pub names: Vec<String>,
}

/// Build the index of the skills that loaded, within `budget` characters (0 = no cap), and the
/// notes that explain everything left out of it: skills that did not fit, skills that are
/// broken, directories that could not be read.
///
/// The budget covers the whole injected text, preamble included. Entries are kept narrowest
/// scope first (workspace, profile, plugin, shared), then by name, and what does not fit is
/// dropped from the end of that order — so the answer to "which ones went" is always a suffix
/// of a list a person can reproduce. A dropped skill still loads by name through `skill_view`.
pub fn index(report: &Report, budget: usize) -> (Option<Index>, Vec<String>) {
    let mut notes: Vec<String> = report.problems.clone();
    for broken in report.broken() {
        notes.push(format!(
            "skill `{}` is broken and left out of the index: {} ({})",
            broken.name,
            broken.broken_reason().unwrap_or("unknown"),
            broken.path.display()
        ));
    }

    let mut active: Vec<(&Found, &Skill)> = report.active().collect();
    active.sort_by(|a, b| {
        (a.0.source.keep_rank(), &a.0.name).cmp(&(b.0.source.keep_rank(), &b.0.name))
    });
    let lines: Vec<String> = active
        .iter()
        .map(|(_, skill)| entry_line(&skill.meta))
        .collect();

    let mut used = PREAMBLE.chars().count();
    let mut kept = 0;
    for line in &lines {
        // Two newlines separate the preamble from the list, one separates entries.
        let cost = line.chars().count() + if kept == 0 { 2 } else { 1 };
        if budget > 0 && used + cost > budget {
            break;
        }
        used += cost;
        kept += 1;
    }
    let dropped: Vec<String> = if kept < lines.len() {
        let dropped: Vec<String> = active[kept..].iter().map(|(f, _)| f.name.clone()).collect();
        notes.push(format!(
            "skills index: left out {} of {} skills to stay under the {budget} char \
`[skills] index_budget_chars`: {} (`skill_view` still loads them by name)",
            dropped.len(),
            lines.len(),
            dropped.join(", ")
        ));
        dropped
    } else {
        Vec::new()
    };
    if kept == 0 {
        return (None, notes);
    }
    // `#350`: the model is a reader of the omission, not just the terminal. A skill that did not
    // fit was invisible to the one thing that could have asked for it — the note above goes to
    // stderr, which the model never sees — so the index itself says what is missing and how to
    // reach it. It rides outside the budget on purpose: it is the escape hatch from the budget,
    // and truncating it would restore exactly the trap it removes.
    let body = if dropped.is_empty() {
        format!("{PREAMBLE}\n\n{}", lines[..kept].join("\n"))
    } else {
        format!(
            "{PREAMBLE}\n\n{}\n\n({} more skill(s) exist but did not fit here; call \
skill_search with words from the task to find them, then skill_view the one that fits.)",
            lines[..kept].join("\n"),
            dropped.len()
        )
    };
    let names = active[..kept].iter().map(|(f, _)| f.name.clone()).collect();
    let chars = body.chars().count();
    (Some(Index { body, chars, names }), notes)
}

/// One line per skill in the index — and in `skill_search`'s answer, so the two read the same.
pub(crate) fn entry_line(meta: &Frontmatter) -> String {
    // One line per skill: a description with a newline in it would break the list.
    let description = meta
        .description
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    let mut line = format!("- {}", meta.name);
    if !description.is_empty() {
        line.push_str(&format!(": {description}"));
    }
    if !meta.requires.is_empty() {
        line.push_str(&format!(" (needs tools: {})", meta.requires.join(", ")));
    }
    line
}

/// Files a skill links, relative to its directory with `/` separators: everything under
/// `references/`, `scripts/` and `templates/`, sorted. Bounded in count and depth.
pub fn linked_files(dir: &Path) -> Vec<String> {
    fn walk(base: &Path, rel: &str, depth: usize, out: &mut Vec<String>) {
        let Ok(entries) = std::fs::read_dir(base.join(rel)) else {
            return;
        };
        let mut names: Vec<_> = entries.filter_map(|e| e.ok()).collect();
        names.sort_by_key(|e| e.file_name());
        for entry in names {
            if out.len() >= MAX_LINKED {
                return;
            }
            let name = entry.file_name().to_string_lossy().into_owned();
            let child = format!("{rel}/{name}");
            let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
            if is_dir {
                if depth + 1 < MAX_LINKED_DEPTH {
                    walk(base, &child, depth + 1, out);
                }
            } else {
                out.push(child);
            }
        }
    }
    let mut out = Vec::new();
    for sub in SUPPORT_DIRS {
        walk(dir, sub, 0, &mut out);
    }
    out
}

/// Resolve `rel` against a skill's directory and make sure the answer is still inside it.
///
/// Refused, with the reason: an empty path, an absolute one, any `..`, and a path that passes
/// through a symlink to somewhere else. The last check follows the filesystem rather than
/// the text, because `references/notes -> /etc` is a perfectly normal-looking relative path.
/// The target does not have to exist yet, so the same check guards a write.
pub fn resolve_inside(dir: &Path, rel: &str) -> Result<PathBuf, String> {
    if rel.trim().is_empty() {
        return Err("the path is empty".into());
    }
    let relative = Path::new(rel);
    for component in relative.components() {
        match component {
            Component::Normal(_) | Component::CurDir => {}
            Component::ParentDir => return Err("`..` is not allowed in a skill path".into()),
            Component::RootDir | Component::Prefix(_) => {
                return Err("absolute paths are not allowed; use a path inside the skill".into())
            }
        }
    }
    let root = std::fs::canonicalize(dir).map_err(|e| {
        format!(
            "cannot resolve the skill's directory {}: {e}",
            dir.display()
        )
    })?;
    let joined = root.join(relative);
    let mut existing = joined.as_path();
    // `symlink_metadata` so a dangling link is resolved (and refused) instead of skipped.
    while std::fs::symlink_metadata(existing).is_err() {
        existing = existing
            .parent()
            .ok_or_else(|| "the path has no existing ancestor".to_string())?;
    }
    let canon =
        std::fs::canonicalize(existing).map_err(|e| format!("cannot resolve `{rel}`: {e}"))?;
    if !canon.starts_with(&root) {
        return Err(format!(
            "`{rel}` resolves to {}, outside the skill's directory",
            canon.display()
        ));
    }
    Ok(joined)
}

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

    const FIXTURE: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/fixtures/hermes-skill/SKILL.md"
    );

    fn write(path: &Path, body: &str) {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, body).unwrap();
    }

    fn skill_md(name: &str, description: &str) -> String {
        format!("---\nname: {name}\ndescription: {description}\n---\n\nDo the thing for {name}.\n")
    }

    fn root(source: Source, dir: &Path) -> Root {
        Root {
            source,
            dir: dir.to_path_buf(),
        }
    }

    #[test]
    fn plain_and_quoted_scalars_and_flow_sequences_are_read() {
        let skill = parse(
            "---\nname: nightly-backup\ndescription: \"Use when backing up: the media stack.\"\n\
             version: 1.0.0\ntags: [backup, \"ops, nightly\"]\nrequires: ['shell']\n---\nSteps.\n",
        )
        .unwrap();
        assert_eq!(skill.meta.name, "nightly-backup");
        assert_eq!(
            skill.meta.description,
            "Use when backing up: the media stack."
        );
        assert_eq!(skill.meta.version.as_deref(), Some("1.0.0"));
        assert_eq!(skill.meta.tags, ["backup", "ops, nightly"]);
        assert_eq!(skill.meta.requires, ["shell"]);
        assert_eq!(skill.body, "Steps.");
    }

    #[test]
    fn empty_values_and_trailing_comments_are_tolerated() {
        let skill = parse(
            "---\nname: a\ndescription:\nversion:\ntags: []\nrequires: [shell]   # tools it needs\n\
             # a comment line\n---\nbody\n",
        )
        .unwrap();
        assert_eq!(skill.meta.description, "");
        assert_eq!(skill.meta.version, None);
        assert!(skill.meta.tags.is_empty());
        assert_eq!(skill.meta.requires, ["shell"]);
    }

    #[test]
    fn nested_blocks_and_unknown_keys_are_ignored_not_rejected() {
        let skill = parse(
            "---\nname: a\nauthor: Nox\nmetadata:\n  hermes:\n    tags: [news, search]\n    \
             related_skills: [x, y]\n    weird: \"never closed\nlicense: MIT\ndescription: d\n---\nbody\n",
        )
        .unwrap();
        assert_eq!(skill.meta.name, "a");
        assert_eq!(skill.meta.description, "d");
        assert!(
            skill.meta.tags.is_empty(),
            "`tags` nested under `metadata.hermes` is not the skill's own `tags`"
        );
    }

    #[test]
    fn block_sequences_and_block_scalars_are_read() {
        let skill = parse(
            "---\nname: a\ndescription: >-\n  first line\n  second line\ntags:\n  - one\n  - \"two\"\n\
             requires:\n- shell\n---\nbody\n",
        )
        .unwrap();
        assert_eq!(skill.meta.description, "first line second line");
        assert_eq!(skill.meta.tags, ["one", "two"]);
        assert_eq!(skill.meta.requires, ["shell"]);
    }

    #[test]
    fn crlf_line_endings_and_a_byte_order_mark_are_accepted() {
        let skill = parse("\u{feff}---\r\nname: a\r\ndescription: d\r\n---\r\nbody\r\n").unwrap();
        assert_eq!(skill.meta.name, "a");
        assert_eq!(skill.body, "body");
    }

    #[test]
    fn a_missing_name_is_an_error_that_says_so() {
        let err = parse("---\ndescription: d\n---\nbody\n").unwrap_err();
        assert!(err.contains("missing `name`"), "{err}");
        let err = parse("---\nname:\ndescription: d\n---\nbody\n").unwrap_err();
        assert!(err.contains("missing `name`"), "{err}");
        let err = parse("just a body\n").unwrap_err();
        assert!(err.contains("no frontmatter"), "{err}");
    }

    #[test]
    fn an_unterminated_fence_is_an_error() {
        let err = parse("---\nname: a\ndescription: d\nbody that never closes\n").unwrap_err();
        assert!(err.contains("unterminated frontmatter"), "{err}");
        assert!(parse("---").unwrap_err().contains("unterminated"));
    }

    #[test]
    fn an_empty_body_is_an_error() {
        let err = parse("---\nname: a\ndescription: d\n---\n\n  \n").unwrap_err();
        assert!(err.contains("empty body"), "{err}");
    }

    #[test]
    fn an_unclosed_quote_or_bracket_on_a_key_we_read_is_an_error() {
        let err = parse("---\nname: a\ndescription: \"oops\n---\nbody\n").unwrap_err();
        assert!(
            err.contains("line 3") && err.contains("description"),
            "{err}"
        );
        let err = parse("---\nname: a\ntags: [x, y\n---\nbody\n").unwrap_err();
        assert!(err.contains("`tags`"), "{err}");
    }

    #[test]
    fn a_skill_file_over_the_size_limit_is_reported_rather_than_read() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        write(&dir.join("good/SKILL.md"), &skill_md("good", "works"));
        let mut huge = skill_md("huge", "far too big");
        huge.push_str(&"x".repeat(MAX_SKILL_FILE_BYTES as usize + 1));
        write(&dir.join("huge/SKILL.md"), &huge);

        let report = discover(&[root(Source::Shared, dir)]);
        let broken: Vec<String> = report
            .broken()
            .map(|f| f.broken_reason().unwrap().to_string())
            .collect();
        assert_eq!(broken.len(), 1, "{broken:?}");
        assert!(broken[0].contains("bytes; the limit is"), "{}", broken[0]);
        assert_eq!(report.active().count(), 1, "the good skill still loads");
    }

    #[test]
    fn a_broken_skill_is_reported_with_its_reason_and_kept_out_of_the_index() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        write(&dir.join("good/SKILL.md"), &skill_md("good", "works"));
        write(
            &dir.join("nameless/SKILL.md"),
            "---\ndescription: d\n---\nbody\n",
        );
        write(&dir.join("open/SKILL.md"), "---\nname: open\n");
        write(&dir.join("hollow/SKILL.md"), "---\nname: hollow\n---\n");
        std::fs::create_dir_all(dir.join("dirskill/SKILL.md")).unwrap();
        write_bytes(
            &dir.join("binary/SKILL.md"),
            b"---\nname: b\n---\n\xff\xfe\n",
        );

        let report = discover(&[root(Source::Shared, dir)]);
        let reasons: Vec<(String, String)> = report
            .broken()
            .map(|f| (f.name.clone(), f.broken_reason().unwrap().to_string()))
            .collect();
        let reason_of = |n: &str| {
            reasons
                .iter()
                .find(|(name, _)| name == n)
                .unwrap_or_else(|| panic!("{n} is not reported: {reasons:?}"))
                .1
                .clone()
        };
        assert!(reason_of("nameless").contains("missing `name`"));
        assert!(reason_of("open").contains("unterminated"));
        assert!(reason_of("hollow").contains("empty body"));
        assert!(reason_of("dirskill").contains("is a directory"));
        assert!(reason_of("binary").contains("UTF-8"));
        assert_eq!(report.active().count(), 1);

        let (index, notes) = index(&report, 0);
        let index = index.unwrap();
        assert_eq!(index.names, ["good"]);
        for hidden in ["nameless", "open", "hollow", "dirskill", "binary"] {
            assert!(
                !index.body.contains(hidden),
                "{hidden} leaked: {}",
                index.body
            );
            assert!(
                notes.iter().any(|n| n.contains(&format!("`{hidden}`"))),
                "{hidden} has no note: {notes:?}"
            );
        }
    }

    fn write_bytes(path: &Path, bytes: &[u8]) {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, bytes).unwrap();
    }

    #[test]
    fn a_profile_skill_shadows_a_shared_one_and_the_winning_path_is_named() {
        let tmp = tempfile::tempdir().unwrap();
        let shared = tmp.path().join("shared");
        let profile = tmp.path().join("profile");
        write(
            &shared.join("backup/SKILL.md"),
            &skill_md("backup", "shared copy"),
        );
        write(
            &shared.join("other/SKILL.md"),
            &skill_md("other", "only shared"),
        );
        write(
            &profile.join("backup/SKILL.md"),
            &skill_md("backup", "profile copy"),
        );

        let report = discover(&[
            root(Source::Shared, &shared),
            root(Source::Profile("work".into()), &profile),
        ]);
        let backup = report.get("backup").unwrap();
        assert_eq!(backup.source, Source::Profile("work".into()));
        assert_eq!(backup.skill().unwrap().meta.description, "profile copy");
        assert_eq!(backup.path, profile.join("backup/SKILL.md"));
        assert_eq!(
            backup.shadows,
            [Shadowed {
                source: Source::Shared,
                path: shared.join("backup/SKILL.md")
            }],
            "the report says what the winner beat, and where it lives"
        );
        assert_eq!(report.get("other").unwrap().source, Source::Shared);
        assert_eq!(report.active().count(), 2, "one `backup`, not two");
    }

    #[test]
    fn precedence_runs_shared_then_profile_then_workspace_then_plugins() {
        let tmp = tempfile::tempdir().unwrap();
        let dirs: Vec<PathBuf> = ["shared", "profile", "workspace", "plugin"]
            .iter()
            .map(|d| tmp.path().join(d))
            .collect();
        for (i, dir) in dirs.iter().enumerate() {
            write(
                &dir.join("s/SKILL.md"),
                &skill_md("s", &format!("from {i}")),
            );
        }
        let roots = vec![
            root(Source::Shared, &dirs[0]),
            root(Source::Profile("p".into()), &dirs[1]),
            root(Source::Workspace, &dirs[2]),
            root(Source::Plugin("pl".into()), &dirs[3]),
        ];
        let report = discover(&roots);
        let won = report.get("s").unwrap();
        assert_eq!(won.source.label(), "plugin:pl");
        assert_eq!(won.shadows.len(), 3);
        // Without the plugin, the workspace wins: later shadows earlier, all the way down.
        let report = discover(&roots[..3]);
        assert_eq!(report.get("s").unwrap().source, Source::Workspace);
    }

    #[test]
    fn a_broken_skill_does_not_shadow_a_working_one_of_the_same_name() {
        let tmp = tempfile::tempdir().unwrap();
        let shared = tmp.path().join("shared");
        let profile = tmp.path().join("profile");
        write(
            &shared.join("backup/SKILL.md"),
            &skill_md("backup", "works"),
        );
        write(&profile.join("backup/SKILL.md"), "---\nname: backup\n---\n");

        let report = discover(&[
            root(Source::Shared, &shared),
            root(Source::Profile("p".into()), &profile),
        ]);
        let winner = report.get("backup").unwrap();
        assert_eq!(winner.source, Source::Shared);
        assert_eq!(
            report.broken().count(),
            1,
            "and the broken copy is still reported"
        );
    }

    #[test]
    fn category_folders_are_searched_and_hidden_ones_are_not() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        write(
            &dir.join("devops/deploy/SKILL.md"),
            &skill_md("deploy", "d"),
        );
        write(&dir.join(".git/hooks/SKILL.md"), &skill_md("hidden", "d"));
        write(&dir.join("notes/README.md"), "not a skill");
        let report = discover(&[root(Source::Shared, dir)]);
        let names: Vec<_> = report.active().map(|(f, _)| f.name.as_str()).collect();
        assert_eq!(names, ["deploy"]);
        assert!(
            report.problems.is_empty(),
            "a folder with no skills is not a problem"
        );
    }

    #[test]
    fn a_missing_skills_directory_is_not_a_problem() {
        let tmp = tempfile::tempdir().unwrap();
        let report = discover(&[root(Source::Shared, &tmp.path().join("nope"))]);
        assert!(report.found.is_empty() && report.problems.is_empty());
    }

    #[test]
    fn the_index_lists_name_description_and_what_a_skill_requires() {
        let tmp = tempfile::tempdir().unwrap();
        write(
            &tmp.path().join("a/SKILL.md"),
            "---\nname: a\ndescription: \"first\"\nrequires: [shell, fetch]\n---\nbody\n",
        );
        write(&tmp.path().join("b/SKILL.md"), &skill_md("b", "second"));
        let report = discover(&[root(Source::Shared, tmp.path())]);
        let (index, notes) = index(&report, 4000);
        let index = index.unwrap();
        assert!(
            index
                .body
                .contains("- a: first (needs tools: shell, fetch)"),
            "{}",
            index.body
        );
        assert!(index.body.contains("\n- b: second"), "{}", index.body);
        assert!(
            !index.body.contains("Do the thing"),
            "bodies are loaded on demand"
        );
        assert!(notes.is_empty(), "{notes:?}");
        assert_eq!(index.chars, index.body.chars().count());
    }

    #[test]
    fn over_budget_the_index_drops_entries_and_names_them() {
        let tmp = tempfile::tempdir().unwrap();
        for name in ["alpha", "beta", "gamma", "delta"] {
            write(
                &tmp.path().join(name).join("SKILL.md"),
                &skill_md(name, &"x".repeat(60)),
            );
        }
        let report = discover(&[root(Source::Shared, tmp.path())]);
        let (full, _) = index(&report, 0);
        let full = full.unwrap();
        assert_eq!(full.names.len(), 4, "0 means no cap");

        // Room for the preamble and the first two entries (69 and 68 chars), not a third.
        let budget = full.chars - 2 * 70;
        let (small, notes) = index(&report, budget);
        let small = small.unwrap();
        assert_eq!(
            small.names,
            ["alpha", "beta"],
            "name order within one source"
        );
        // `#350`: the omission line rides *outside* the budget on purpose — it is the escape
        // hatch from the budget, so the entries fit and the note that says what did not is the
        // only thing past the line.
        assert!(
            small.chars <= budget + 200,
            "{} > {budget} + the note",
            small.chars
        );
        let note = notes
            .iter()
            .find(|n| n.contains("left out 2 of 4"))
            .unwrap();
        assert!(note.contains("delta, gamma"), "{note}");
        assert!(note.contains("index_budget_chars"), "{note}");
        assert!(!small.body.contains("gamma"));
    }

    /// `#350`: a dropped skill used to be invisible to the one reader that could have asked for
    /// it. The index now says how many are missing and which verb finds them.
    #[test]
    fn the_index_tells_the_model_what_it_left_out() {
        let tmp = tempfile::tempdir().unwrap();
        for name in ["alpha", "beta", "gamma"] {
            write(
                &tmp.path().join(name).join("SKILL.md"),
                &skill_md(name, &"x".repeat(60)),
            );
        }
        let report = discover(&[root(Source::Shared, tmp.path())]);
        let (full, _) = index(&report, 0);
        // Room for the preamble and the first entry, not a second: two of the three are dropped.
        let budget = full.unwrap().chars - 100;
        let (small, _) = index(&report, budget);
        let body = small.unwrap().body;
        assert!(body.contains("alpha"), "{body}");
        assert!(
            body.contains("2 more skill(s) exist but did not fit here"),
            "the model is told what is missing: {body}"
        );
        assert!(body.contains("skill_search"), "and how to reach it: {body}");
        assert!(!body.contains("gamma"), "the dropped entry is not listed");

        // With room for everything there is no note: the line is for a truncation, not a fixture.
        let (whole, _) = index(&report, 0);
        assert!(!whole.unwrap().body.contains("did not fit"));
    }

    #[test]
    fn when_the_narrower_scope_is_kept_the_shared_skills_go_first() {
        let tmp = tempfile::tempdir().unwrap();
        let shared = tmp.path().join("shared");
        let ws = tmp.path().join("ws");
        write(
            &shared.join("aaa/SKILL.md"),
            &skill_md("aaa", &"x".repeat(40)),
        );
        write(&ws.join("zzz/SKILL.md"), &skill_md("zzz", &"x".repeat(40)));
        let report = discover(&[root(Source::Shared, &shared), root(Source::Workspace, &ws)]);
        let (full, _) = index(&report, 0);
        let budget = full.unwrap().chars - 10;
        let (small, notes) = index(&report, budget);
        assert_eq!(small.unwrap().names, ["zzz"]);
        assert!(notes[0].contains("aaa"), "{notes:?}");
    }

    #[test]
    fn a_budget_too_small_for_one_entry_leaves_no_index_and_says_why() {
        let tmp = tempfile::tempdir().unwrap();
        write(&tmp.path().join("a/SKILL.md"), &skill_md("a", "d"));
        let report = discover(&[root(Source::Shared, tmp.path())]);
        let (index, notes) = index(&report, 20);
        assert!(index.is_none());
        assert!(
            notes.iter().any(|n| n.contains("left out 1 of 1")),
            "{notes:?}"
        );
    }

    #[test]
    fn a_real_hermes_skill_loads_unmodified() {
        let text = std::fs::read_to_string(FIXTURE).unwrap_or_else(|e| {
            panic!(
                "the Hermes fixture is missing or unreadable ({e}): expected a verbatim copy of a \
real Hermes SKILL.md at {FIXTURE}. Restore it with `git checkout -- crates/eclipse-core/tests/fixtures`; \
do not edit it to make this test pass."
            )
        });
        // Verbatim from a real Hermes install (`latest-news-search`): nested `metadata.hermes`
        // frontmatter and a quoted description.
        let skill = parse(&text).unwrap();
        assert_eq!(skill.meta.name, "latest-news-search");
        assert_eq!(
            skill.meta.description,
            "Search for and compile latest news on any topic with verified dates"
        );
        assert_eq!(skill.meta.version.as_deref(), Some("1.0.0"));
        assert!(skill.body.starts_with("## Trigger"), "{}", skill.body);
        assert!(skill.body.contains("skill_view('skill-router')"));

        // And through discovery, the way a user's library would reach it.
        let tmp = tempfile::tempdir().unwrap();
        write(&tmp.path().join("news/latest-news-search/SKILL.md"), &text);
        let report = discover(&[root(Source::Shared, tmp.path())]);
        assert_eq!(report.broken().count(), 0);
        let (index, _) = index(&report, 4000);
        assert!(index
            .unwrap()
            .body
            .contains("- latest-news-search: Search for and compile latest news"));
    }

    #[test]
    fn linked_files_are_listed_from_the_three_supporting_directories() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        write(&dir.join("SKILL.md"), &skill_md("a", "d"));
        write(&dir.join("references/x.md"), "x");
        write(&dir.join("references/deep/y.md"), "y");
        write(&dir.join("scripts/z.sh"), "z");
        write(&dir.join("templates/t"), "t");
        write(&dir.join("notes/ignored.md"), "n");
        assert_eq!(
            linked_files(dir),
            [
                "references/deep/y.md",
                "references/x.md",
                "scripts/z.sh",
                "templates/t"
            ]
        );
    }

    #[test]
    fn a_path_may_not_leave_the_skill_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("skill");
        write(&dir.join("references/x.md"), "x");
        write(&tmp.path().join("secret.txt"), "secret");

        assert!(resolve_inside(&dir, "references/x.md").is_ok());
        assert!(
            resolve_inside(&dir, "references/new/file.md").is_ok(),
            "may not exist yet"
        );
        assert!(resolve_inside(&dir, "../secret.txt")
            .unwrap_err()
            .contains(".."));
        assert!(resolve_inside(&dir, "references/../../secret.txt").is_err());
        assert!(resolve_inside(&dir, "/etc/passwd")
            .unwrap_err()
            .contains("absolute"));
        assert!(resolve_inside(&dir, "").is_err());
    }

    #[cfg(unix)]
    #[test]
    fn a_symlink_that_leaves_the_directory_is_refused() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("skill");
        write(&dir.join("references/x.md"), "x");
        write(&tmp.path().join("outside/secret.txt"), "secret");
        std::os::unix::fs::symlink(tmp.path().join("outside"), dir.join("references/out")).unwrap();
        std::os::unix::fs::symlink(dir.join("references/x.md"), dir.join("references/inside"))
            .unwrap();

        let err = resolve_inside(&dir, "references/out/secret.txt").unwrap_err();
        assert!(err.contains("outside the skill's directory"), "{err}");
        let err = resolve_inside(&dir, "references/out/new.txt").unwrap_err();
        assert!(
            err.contains("outside"),
            "a write through the link is refused too: {err}"
        );
        assert!(
            resolve_inside(&dir, "references/inside").is_ok(),
            "a link that stays inside is fine"
        );
    }
}