Skip to main content

eclipse_core/
skills.rs

1//! Skills: procedures kept as files, found in several places, offered to the model as an index.
2//!
3//! A skill is a directory with a `SKILL.md` in it: frontmatter (`name`, `description`, and
4//! optionally `version`, `tags`, `requires`) between `---` fences, then a body that says what
5//! to do. It may ship `references/`, `scripts/` and `templates/` beside it. The format is the
6//! Hermes one, read as it is found: a skill that needs editing before it loads means this
7//! module is wrong, not the skill.
8//!
9//! The prompt carries an *index* (name and description), not the bodies. A body is loaded by
10//! the `skill_view` tool when the model decides it applies, which is what keeps fifty skills
11//! from costing fifty skills' worth of context on every request.
12//!
13//! This module only reads. It does not know about tools or the prompt: [`discover`] turns
14//! directories into a [`Report`], [`index`] turns a report into text under a budget, and
15//! `tools_skills` and `context_files` use those two. The frontmatter parser is written by hand
16//! because the workspace has no YAML crate and takes no new dependencies for a dozen keys; it
17//! understands the subset real skills use and skips the rest instead of rejecting it.
18//!
19//! Nothing here is silent. A skill that cannot be loaded stays in the report with the reason,
20//! a skill that loses a name to another says which path won, and an index entry that does not
21//! fit the budget is named in a note.
22
23use crate::config::{Config, EnvFn};
24use crate::plugins::Plugins;
25use std::path::{Component, Path, PathBuf};
26
27/// Default ceiling for the prompt index, in characters.
28pub const DEFAULT_INDEX_BUDGET_CHARS: usize = 4000;
29/// The file that makes a directory a skill.
30pub const SKILL_FILE: &str = "SKILL.md";
31/// The only places a skill keeps linked files, and so the only places `skill_manage` writes.
32pub const SUPPORT_DIRS: [&str; 3] = ["references", "scripts", "templates"];
33/// How many directory levels below a root are searched. Hermes groups skills in category
34/// folders (`skills/<category>/<skill>/SKILL.md`), so one level of grouping has to work; past
35/// that the walk is a guard against a pathological tree, not a feature.
36const MAX_DEPTH: usize = 3;
37/// Ceiling on the linked files listed for one skill, for the same reason.
38const MAX_LINKED: usize = 200;
39const MAX_LINKED_DEPTH: usize = 4;
40/// The largest `SKILL.md` — or file a skill links — that the loader will read. A skill is
41/// instructions, not a data store: a bigger file is reported with its size rather than slurped
42/// into memory and into the conversation. The same number is the write limit in `skill_manage`,
43/// so nothing the agent writes is too big for it to read back.
44pub const MAX_SKILL_FILE_BYTES: u64 = 256 * 1024;
45
46pub(crate) const PREAMBLE: &str =
47    "Skills are saved procedures. When a task matches one, call `skill_view` \
48with its name to load it before you start, and follow it. `skill_view` with a `path` loads a \
49file the skill links.";
50
51/// Where a skill was found. Decides who wins a name clash, and is what `skills list` prints.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Source {
54    /// `<config dir>/skills`.
55    Shared,
56    /// `<config dir>/profiles/<p>/skills`.
57    Profile(String),
58    /// `<workspace>/.eclipse/skills`.
59    Workspace,
60    /// `skills/` inside a loaded plugin's directory.
61    Plugin(String),
62}
63
64impl Source {
65    /// `shared`, `profile:<p>`, `workspace` or `plugin:<name>`.
66    pub fn label(&self) -> String {
67        match self {
68            Source::Shared => "shared".into(),
69            Source::Profile(p) => format!("profile:{p}"),
70            Source::Workspace => "workspace".into(),
71            Source::Plugin(n) => format!("plugin:{n}"),
72        }
73    }
74
75    /// Which skills are kept when the index does not fit: the narrower the scope, the more
76    /// deliberately it was put there.
77    fn keep_rank(&self) -> u8 {
78        match self {
79            Source::Workspace => 0,
80            Source::Profile(_) => 1,
81            Source::Plugin(_) => 2,
82            Source::Shared => 3,
83        }
84    }
85}
86
87/// One directory searched for skills.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct Root {
90    pub source: Source,
91    pub dir: PathBuf,
92}
93
94/// The skills directories this configuration has, in precedence order: later shadows earlier.
95///
96/// Shared, then the profile's, then the workspace's, then those shipped in loaded plugins.
97/// A plugin that is not enabled is not loaded, so its skills are not either.
98pub fn roots_for(cfg: &Config, env: EnvFn, plugins: &Plugins, workspace: &Path) -> Vec<Root> {
99    let mut roots = Vec::new();
100    if let Some(dir) = cfg.global_context_dir(env) {
101        roots.push(Root {
102            source: Source::Shared,
103            dir: dir.join("skills"),
104        });
105    }
106    if let Some(name) = &cfg.profile {
107        if let Some(dir) = crate::config::profile_dir(env, name) {
108            roots.push(Root {
109                source: Source::Profile(name.clone()),
110                dir: dir.join("skills"),
111            });
112        }
113    }
114    roots.push(Root {
115        source: Source::Workspace,
116        dir: workspace.join(".eclipse").join("skills"),
117    });
118    // `#419`: only a *enabled* plugin's skills are roots. A plugin loaded for nothing but its
119    // provider profiles is not enabled, and a `skills/` directory it happens to ship must not
120    // become visible just because the manifest was parsed for its wire settings.
121    for plugin in plugins.plugins.iter().filter(|p| p.enabled) {
122        roots.push(Root {
123            source: Source::Plugin(plugin.name.clone()),
124            dir: plugin.dir.join("skills"),
125        });
126    }
127    roots
128}
129
130/// Where `skill_manage create` puts a new skill: the profile's directory when a profile is in
131/// effect, otherwise the shared one. Never the workspace or a plugin — a new skill is the
132/// user's, not the project's or a plugin author's.
133pub fn user_root(roots: &[Root]) -> Option<&Root> {
134    roots
135        .iter()
136        .find(|r| matches!(r.source, Source::Profile(_)))
137        .or_else(|| roots.iter().find(|r| r.source == Source::Shared))
138}
139
140/// The frontmatter keys Eclipse reads. Everything else in the block is ignored.
141#[derive(Debug, Clone, Default, PartialEq, Eq)]
142pub struct Frontmatter {
143    pub name: String,
144    pub description: String,
145    pub version: Option<String>,
146    pub tags: Vec<String>,
147    /// Tools the skill expects to have. Informational: the index says so, nothing enforces it.
148    pub requires: Vec<String>,
149}
150
151/// A skill that loaded: its frontmatter and its body, trimmed of surrounding blank lines.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct Skill {
154    pub meta: Frontmatter,
155    pub body: String,
156}
157
158/// Parse the text of a `SKILL.md`.
159///
160/// The error is the reason, in a sentence, because that is what `skills list` and the startup
161/// warning print next to the path.
162pub fn parse(text: &str) -> Result<Skill, String> {
163    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
164    let first = text.lines().next().unwrap_or("");
165    if first.trim_end() != "---" {
166        return Err(
167            "missing `name`: the file has no frontmatter (it must start with a `---` line)".into(),
168        );
169    }
170    let mut rest = &text[first.len()..];
171    rest = rest.strip_prefix('\n').unwrap_or(rest);
172    let mut lines: Vec<(usize, &str)> = Vec::new();
173    let mut line_no = 1;
174    let body = loop {
175        if rest.is_empty() {
176            return Err(
177                "unterminated frontmatter: the opening `---` on line 1 has no closing \
178`---`"
179                    .into(),
180            );
181        }
182        let (line, tail) = match rest.find('\n') {
183            Some(i) => (&rest[..i], &rest[i + 1..]),
184            None => (rest, ""),
185        };
186        line_no += 1;
187        let line = line.trim_end_matches('\r');
188        if line.trim_end() == "---" {
189            break tail;
190        }
191        lines.push((line_no, line));
192        rest = tail;
193    };
194
195    let meta = read_frontmatter(&lines)?;
196    if meta.name.is_empty() {
197        return Err("missing `name` in the frontmatter".into());
198    }
199    let body = body.trim().to_string();
200    if body.is_empty() {
201        return Err("empty body: the file has frontmatter and nothing after it".into());
202    }
203    Ok(Skill { meta, body })
204}
205
206/// One top-level key with the indented lines that belong to it.
207struct Entry<'a> {
208    key: &'a str,
209    value: &'a str,
210    line: usize,
211    block: Vec<&'a str>,
212}
213
214fn read_frontmatter(lines: &[(usize, &str)]) -> Result<Frontmatter, String> {
215    let mut entries: Vec<Entry<'_>> = Vec::new();
216    for &(line, text) in lines {
217        let blank = text.trim().is_empty();
218        let top = !text.starts_with([' ', '\t']);
219        if blank || text.trim_start().starts_with('#') {
220            continue;
221        }
222        // `key:` at the left margin starts an entry. A `- item` at the margin continues the
223        // previous key's sequence (YAML allows `tags:` followed by unindented dashes).
224        if top && !text.starts_with("- ") && text.contains(':') {
225            if let Some((key, value)) = text.split_once(':') {
226                entries.push(Entry {
227                    key: key.trim(),
228                    value: value.trim(),
229                    line,
230                    block: Vec::new(),
231                });
232            }
233        } else if let Some(last) = entries.last_mut() {
234            last.block.push(text);
235        }
236    }
237
238    let mut meta = Frontmatter::default();
239    for entry in &entries {
240        match entry.key {
241            "name" => meta.name = scalar(entry)?,
242            "description" => meta.description = scalar(entry)?,
243            "version" => {
244                let v = scalar(entry)?;
245                meta.version = (!v.is_empty()).then_some(v);
246            }
247            "tags" => meta.tags = sequence(entry)?,
248            "requires" => meta.requires = sequence(entry)?,
249            _ => {}
250        }
251    }
252    Ok(meta)
253}
254
255/// A string value: quoted, plain, or a block scalar (`|` / `>`).
256fn scalar(entry: &Entry<'_>) -> Result<String, String> {
257    let value = entry.value;
258    if value.starts_with(['|', '>']) {
259        let folded = value.starts_with('>');
260        let indent = entry
261            .block
262            .iter()
263            .filter(|l| !l.trim().is_empty())
264            .map(|l| l.len() - l.trim_start().len())
265            .min()
266            .unwrap_or(0);
267        let lines: Vec<&str> = entry
268            .block
269            .iter()
270            .map(|l| l.get(indent..).unwrap_or("").trim_end())
271            .collect();
272        return Ok(if folded {
273            fold(&lines)
274        } else {
275            lines.join("\n").trim().to_string()
276        });
277    }
278    if value.starts_with(['"', '\'']) {
279        let (text, _) = quoted(value).ok_or_else(|| {
280            format!(
281                "line {}: the quote opened in `{}` is never closed",
282                entry.line, entry.key
283            )
284        })?;
285        return Ok(text);
286    }
287    let mut parts = vec![strip_comment(value).to_string()];
288    parts.extend(entry.block.iter().map(|l| l.trim().to_string()));
289    Ok(parts
290        .into_iter()
291        .filter(|p| !p.is_empty())
292        .collect::<Vec<_>>()
293        .join(" "))
294}
295
296/// `>` folding: lines join with a space, a blank line is a paragraph break.
297fn fold(lines: &[&str]) -> String {
298    let mut out = String::new();
299    for line in lines {
300        let line = line.trim();
301        if line.is_empty() {
302            if !out.ends_with('\n') && !out.is_empty() {
303                out.push('\n');
304            }
305        } else {
306            if !out.is_empty() && !out.ends_with('\n') {
307                out.push(' ');
308            }
309            out.push_str(line);
310        }
311    }
312    out.trim().to_string()
313}
314
315/// A list value: `[a, b]`, one plain item, or `- a` lines beneath the key. Empty is empty.
316fn sequence(entry: &Entry<'_>) -> Result<Vec<String>, String> {
317    let value = entry.value;
318    if let Some(inner) = value.strip_prefix('[') {
319        let end = closing_bracket(inner).ok_or_else(|| {
320            format!(
321                "line {}: the `[` opened in `{}` is never closed",
322                entry.line, entry.key
323            )
324        })?;
325        return split_flow(&inner[..end], entry);
326    }
327    if !value.is_empty() && !value.starts_with('#') {
328        return Ok(vec![scalar(&Entry {
329            key: entry.key,
330            value,
331            line: entry.line,
332            block: Vec::new(),
333        })?]);
334    }
335    let mut items = Vec::new();
336    for line in &entry.block {
337        if let Some(item) = line.trim_start().strip_prefix("- ") {
338            items.push(scalar(&Entry {
339                key: entry.key,
340                value: item.trim(),
341                line: entry.line,
342                block: Vec::new(),
343            })?);
344        }
345    }
346    Ok(items)
347}
348
349fn split_flow(inner: &str, entry: &Entry<'_>) -> Result<Vec<String>, String> {
350    let mut items = Vec::new();
351    let mut rest = inner.trim();
352    while !rest.is_empty() {
353        let (item, tail) = if rest.starts_with(['"', '\'']) {
354            let (text, tail) = quoted(rest).ok_or_else(|| {
355                format!(
356                    "line {}: a quote in `{}` is never closed",
357                    entry.line, entry.key
358                )
359            })?;
360            (text, tail.trim_start().strip_prefix(',').unwrap_or(""))
361        } else {
362            match rest.split_once(',') {
363                Some((head, tail)) => (head.trim().to_string(), tail),
364                None => (rest.trim().to_string(), ""),
365            }
366        };
367        if !item.is_empty() {
368            items.push(item);
369        }
370        rest = tail.trim_start();
371    }
372    Ok(items)
373}
374
375/// Where the `]` that ends a flow sequence is, skipping any inside quotes.
376fn closing_bracket(inner: &str) -> Option<usize> {
377    let mut quote: Option<char> = None;
378    for (i, c) in inner.char_indices() {
379        match (quote, c) {
380            (Some(q), c) if c == q => quote = None,
381            (None, '"' | '\'') => quote = Some(c),
382            (None, ']') => return Some(i),
383            _ => {}
384        }
385    }
386    None
387}
388
389/// Text before a trailing ` # comment`. A `#` with no space before it is part of the value.
390fn strip_comment(value: &str) -> &str {
391    let mut prev_space = false;
392    for (i, c) in value.char_indices() {
393        if c == '#' && prev_space {
394            return value[..i].trim_end();
395        }
396        prev_space = c.is_whitespace();
397    }
398    value.trim_end()
399}
400
401/// A quoted scalar at the start of `text`: its content and what follows the closing quote.
402/// `None` when the quote is never closed.
403fn quoted(text: &str) -> Option<(String, &str)> {
404    let mut chars = text.char_indices();
405    let (_, quote) = chars.next()?;
406    let mut out = String::new();
407    while let Some((i, c)) = chars.next() {
408        if c == quote {
409            // `''` is a literal quote inside single quotes.
410            if quote == '\'' && text[i + 1..].starts_with('\'') {
411                out.push('\'');
412                chars.next();
413                continue;
414            }
415            return Some((out, &text[i + 1..]));
416        }
417        if quote == '"' && c == '\\' {
418            match chars.next()?.1 {
419                'n' => out.push('\n'),
420                't' => out.push('\t'),
421                '"' => out.push('"'),
422                '\\' => out.push('\\'),
423                '/' => out.push('/'),
424                other => {
425                    out.push('\\');
426                    out.push(other);
427                }
428            }
429        } else {
430            out.push(c);
431        }
432    }
433    None
434}
435
436/// A discovered skill, loaded or not.
437#[derive(Debug, Clone)]
438pub struct Found {
439    /// The declared name; the directory's name when the file would not say.
440    pub name: String,
441    pub source: Source,
442    /// The skill's directory.
443    pub dir: PathBuf,
444    /// Its `SKILL.md`.
445    pub path: PathBuf,
446    /// The skill, or the reason it is broken.
447    pub state: Result<Skill, String>,
448    /// What this skill won the name from, nearest loser first. Empty when nothing clashed.
449    pub shadows: Vec<Shadowed>,
450}
451
452impl Found {
453    pub fn skill(&self) -> Option<&Skill> {
454        self.state.as_ref().ok()
455    }
456
457    pub fn broken_reason(&self) -> Option<&str> {
458        self.state.as_ref().err().map(String::as_str)
459    }
460}
461
462/// A skill that lost its name to another, kept so the report can say what was overridden.
463#[derive(Debug, Clone, PartialEq, Eq)]
464pub struct Shadowed {
465    pub source: Source,
466    pub path: PathBuf,
467}
468
469/// Everything discovery found, winners and broken skills alike, in discovery order.
470#[derive(Debug, Clone, Default)]
471pub struct Report {
472    pub found: Vec<Found>,
473    /// Directories that could not be read. A missing skills directory is normal and is not
474    /// one of these.
475    pub problems: Vec<String>,
476}
477
478impl Report {
479    /// Skills that loaded, with the entry that carries them.
480    pub fn active(&self) -> impl Iterator<Item = (&Found, &Skill)> {
481        self.found.iter().filter_map(|f| f.skill().map(|s| (f, s)))
482    }
483
484    pub fn broken(&self) -> impl Iterator<Item = &Found> {
485        self.found.iter().filter(|f| f.state.is_err())
486    }
487
488    /// The skill called `name`: the one that won it, or a broken one of that name when no
489    /// working one exists, so the caller can say why it cannot be used.
490    pub fn get(&self, name: &str) -> Option<&Found> {
491        self.active()
492            .map(|(f, _)| f)
493            .find(|f| f.name == name)
494            .or_else(|| self.broken().find(|f| f.name == name))
495    }
496
497    /// Names of the skills that loaded, grouped by source label in discovery order. What the
498    /// opening pane shows.
499    pub fn by_source(&self) -> Vec<(String, Vec<String>)> {
500        let mut groups: Vec<(String, Vec<String>)> = Vec::new();
501        for (found, _) in self.active() {
502            let label = found.source.label();
503            match groups.iter_mut().find(|(l, _)| *l == label) {
504                Some((_, names)) => names.push(found.name.clone()),
505                None => groups.push((label, vec![found.name.clone()])),
506            }
507        }
508        groups
509    }
510}
511
512/// Look in every root, load what is there, and resolve name clashes: a later root's skill
513/// shadows an earlier one's, and the winner records what it beat.
514///
515/// A broken skill never shadows. If the profile's copy of `backup` is malformed and the shared
516/// one works, the working one stays in use and the broken one is reported — losing a procedure
517/// because someone's edit left a quote open would be the worse failure.
518pub fn discover(roots: &[Root]) -> Report {
519    let mut report = Report::default();
520    for root in roots {
521        let mut dirs = Vec::new();
522        collect_skill_dirs(&root.dir, 0, &mut dirs, &mut report.problems);
523        for dir in dirs {
524            let loaded = load(root.source.clone(), dir);
525            if loaded.state.is_ok() {
526                let clash = report
527                    .found
528                    .iter()
529                    .position(|f| f.state.is_ok() && f.name == loaded.name);
530                if let Some(at) = clash {
531                    let beaten = report.found.remove(at);
532                    let mut winner = loaded;
533                    winner.shadows.push(Shadowed {
534                        source: beaten.source,
535                        path: beaten.path,
536                    });
537                    winner.shadows.extend(beaten.shadows);
538                    report.found.push(winner);
539                    continue;
540                }
541            }
542            report.found.push(loaded);
543        }
544    }
545    report
546}
547
548/// [`discover`], narrowed to the names `only` lists (`#509`).
549///
550/// `None` is every root's skill — the human's agent. `Some(names)` is exactly those names, and an
551/// empty list is a bot that sees none: a declaration that says nothing about skills leaves every
552/// root in force, and one that says `skills = []` means it. The filter lives here rather than at
553/// the five readers, so the index in the prompt and the four `skill_*` tools cannot disagree about
554/// what a bot was given.
555///
556/// A broken skill keeps its place when it was declared: dropping it would turn "your skill is
557/// malformed" into "there is no such skill", and the report says which.
558pub fn discover_only(roots: &[Root], only: Option<&[String]>) -> Report {
559    let mut report = discover(roots);
560    if let Some(names) = only {
561        report.found.retain(|found| names.contains(&found.name));
562    }
563    report
564}
565
566/// Directories under `dir` that hold a `SKILL.md`, sorted, searching category folders.
567fn collect_skill_dirs(
568    dir: &Path,
569    depth: usize,
570    out: &mut Vec<PathBuf>,
571    problems: &mut Vec<String>,
572) {
573    let entries = match std::fs::read_dir(dir) {
574        Ok(entries) => entries,
575        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
576        Err(e) => {
577            problems.push(format!(
578                "cannot read skills directory {}: {e}",
579                dir.display()
580            ));
581            return;
582        }
583    };
584    let mut children: Vec<PathBuf> = entries
585        .filter_map(|e| e.ok())
586        .filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
587        .map(|e| e.path())
588        // `metadata` follows symlinks, so a library kept elsewhere and linked in is found.
589        .filter(|p| std::fs::metadata(p).map(|m| m.is_dir()).unwrap_or(false))
590        .collect();
591    children.sort();
592    for child in children {
593        // `symlink_metadata`: a `SKILL.md` that is a directory or a dangling link is still a
594        // skill that is broken, not a folder to walk past.
595        if std::fs::symlink_metadata(child.join(SKILL_FILE)).is_ok() {
596            out.push(child);
597        } else if depth + 1 < MAX_DEPTH {
598            collect_skill_dirs(&child, depth + 1, out, problems);
599        }
600    }
601}
602
603fn load(source: Source, dir: PathBuf) -> Found {
604    let path = dir.join(SKILL_FILE);
605    let fallback = dir
606        .file_name()
607        .map(|n| n.to_string_lossy().into_owned())
608        .unwrap_or_default();
609    let state = read_skill(&path);
610    let name = match &state {
611        Ok(skill) => skill.meta.name.clone(),
612        Err(_) => fallback,
613    };
614    Found {
615        name,
616        source,
617        dir,
618        path,
619        state,
620        shadows: Vec::new(),
621    }
622}
623
624fn read_skill(path: &Path) -> Result<Skill, String> {
625    match std::fs::metadata(path) {
626        Ok(m) if m.is_dir() => return Err("`SKILL.md` is a directory, not a file".into()),
627        Ok(m) if !m.is_file() => return Err("`SKILL.md` is not a regular file".into()),
628        Ok(m) if m.len() > MAX_SKILL_FILE_BYTES => {
629            return Err(format!(
630                "`SKILL.md` is {} bytes; the limit is {MAX_SKILL_FILE_BYTES}",
631                m.len()
632            ))
633        }
634        Ok(_) => {}
635        Err(e) => return Err(format!("cannot read `SKILL.md`: {e}")),
636    }
637    let bytes = std::fs::read(path).map_err(|e| format!("cannot read `SKILL.md`: {e}"))?;
638    let text = String::from_utf8(bytes).map_err(|e| {
639        format!(
640            "`SKILL.md` is not valid UTF-8 (first bad byte at offset {})",
641            e.utf8_error().valid_up_to()
642        )
643    })?;
644    parse(&text)
645}
646
647/// The prompt index, as it will be injected.
648#[derive(Debug, Clone, PartialEq, Eq)]
649pub struct Index {
650    pub body: String,
651    pub chars: usize,
652    /// The skills that made it in, in the order listed.
653    pub names: Vec<String>,
654}
655
656/// Build the index of the skills that loaded, within `budget` characters (0 = no cap), and the
657/// notes that explain everything left out of it: skills that did not fit, skills that are
658/// broken, directories that could not be read.
659///
660/// The budget covers the whole injected text, preamble included. Entries are kept narrowest
661/// scope first (workspace, profile, plugin, shared), then by name, and what does not fit is
662/// dropped from the end of that order — so the answer to "which ones went" is always a suffix
663/// of a list a person can reproduce. A dropped skill still loads by name through `skill_view`.
664pub fn index(report: &Report, budget: usize) -> (Option<Index>, Vec<String>) {
665    let mut notes: Vec<String> = report.problems.clone();
666    for broken in report.broken() {
667        notes.push(format!(
668            "skill `{}` is broken and left out of the index: {} ({})",
669            broken.name,
670            broken.broken_reason().unwrap_or("unknown"),
671            broken.path.display()
672        ));
673    }
674
675    let mut active: Vec<(&Found, &Skill)> = report.active().collect();
676    active.sort_by(|a, b| {
677        (a.0.source.keep_rank(), &a.0.name).cmp(&(b.0.source.keep_rank(), &b.0.name))
678    });
679    let lines: Vec<String> = active
680        .iter()
681        .map(|(_, skill)| entry_line(&skill.meta))
682        .collect();
683
684    let mut used = PREAMBLE.chars().count();
685    let mut kept = 0;
686    for line in &lines {
687        // Two newlines separate the preamble from the list, one separates entries.
688        let cost = line.chars().count() + if kept == 0 { 2 } else { 1 };
689        if budget > 0 && used + cost > budget {
690            break;
691        }
692        used += cost;
693        kept += 1;
694    }
695    let dropped: Vec<String> = if kept < lines.len() {
696        let dropped: Vec<String> = active[kept..].iter().map(|(f, _)| f.name.clone()).collect();
697        notes.push(format!(
698            "skills index: left out {} of {} skills to stay under the {budget} char \
699`[skills] index_budget_chars`: {} (`skill_view` still loads them by name)",
700            dropped.len(),
701            lines.len(),
702            dropped.join(", ")
703        ));
704        dropped
705    } else {
706        Vec::new()
707    };
708    if kept == 0 {
709        return (None, notes);
710    }
711    // `#350`: the model is a reader of the omission, not just the terminal. A skill that did not
712    // fit was invisible to the one thing that could have asked for it — the note above goes to
713    // stderr, which the model never sees — so the index itself says what is missing and how to
714    // reach it. It rides outside the budget on purpose: it is the escape hatch from the budget,
715    // and truncating it would restore exactly the trap it removes.
716    let body = if dropped.is_empty() {
717        format!("{PREAMBLE}\n\n{}", lines[..kept].join("\n"))
718    } else {
719        format!(
720            "{PREAMBLE}\n\n{}\n\n({} more skill(s) exist but did not fit here; call \
721skill_search with words from the task to find them, then skill_view the one that fits.)",
722            lines[..kept].join("\n"),
723            dropped.len()
724        )
725    };
726    let names = active[..kept].iter().map(|(f, _)| f.name.clone()).collect();
727    let chars = body.chars().count();
728    (Some(Index { body, chars, names }), notes)
729}
730
731/// One line per skill in the index — and in `skill_search`'s answer, so the two read the same.
732pub(crate) fn entry_line(meta: &Frontmatter) -> String {
733    // One line per skill: a description with a newline in it would break the list.
734    let description = meta
735        .description
736        .split_whitespace()
737        .collect::<Vec<_>>()
738        .join(" ");
739    let mut line = format!("- {}", meta.name);
740    if !description.is_empty() {
741        line.push_str(&format!(": {description}"));
742    }
743    if !meta.requires.is_empty() {
744        line.push_str(&format!(" (needs tools: {})", meta.requires.join(", ")));
745    }
746    line
747}
748
749/// Files a skill links, relative to its directory with `/` separators: everything under
750/// `references/`, `scripts/` and `templates/`, sorted. Bounded in count and depth.
751pub fn linked_files(dir: &Path) -> Vec<String> {
752    fn walk(base: &Path, rel: &str, depth: usize, out: &mut Vec<String>) {
753        let Ok(entries) = std::fs::read_dir(base.join(rel)) else {
754            return;
755        };
756        let mut names: Vec<_> = entries.filter_map(|e| e.ok()).collect();
757        names.sort_by_key(|e| e.file_name());
758        for entry in names {
759            if out.len() >= MAX_LINKED {
760                return;
761            }
762            let name = entry.file_name().to_string_lossy().into_owned();
763            let child = format!("{rel}/{name}");
764            let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
765            if is_dir {
766                if depth + 1 < MAX_LINKED_DEPTH {
767                    walk(base, &child, depth + 1, out);
768                }
769            } else {
770                out.push(child);
771            }
772        }
773    }
774    let mut out = Vec::new();
775    for sub in SUPPORT_DIRS {
776        walk(dir, sub, 0, &mut out);
777    }
778    out
779}
780
781/// Resolve `rel` against a skill's directory and make sure the answer is still inside it.
782///
783/// Refused, with the reason: an empty path, an absolute one, any `..`, and a path that passes
784/// through a symlink to somewhere else. The last check follows the filesystem rather than
785/// the text, because `references/notes -> /etc` is a perfectly normal-looking relative path.
786/// The target does not have to exist yet, so the same check guards a write.
787pub fn resolve_inside(dir: &Path, rel: &str) -> Result<PathBuf, String> {
788    if rel.trim().is_empty() {
789        return Err("the path is empty".into());
790    }
791    let relative = Path::new(rel);
792    for component in relative.components() {
793        match component {
794            Component::Normal(_) | Component::CurDir => {}
795            Component::ParentDir => return Err("`..` is not allowed in a skill path".into()),
796            Component::RootDir | Component::Prefix(_) => {
797                return Err("absolute paths are not allowed; use a path inside the skill".into())
798            }
799        }
800    }
801    let root = std::fs::canonicalize(dir).map_err(|e| {
802        format!(
803            "cannot resolve the skill's directory {}: {e}",
804            dir.display()
805        )
806    })?;
807    let joined = root.join(relative);
808    let mut existing = joined.as_path();
809    // `symlink_metadata` so a dangling link is resolved (and refused) instead of skipped.
810    while std::fs::symlink_metadata(existing).is_err() {
811        existing = existing
812            .parent()
813            .ok_or_else(|| "the path has no existing ancestor".to_string())?;
814    }
815    let canon =
816        std::fs::canonicalize(existing).map_err(|e| format!("cannot resolve `{rel}`: {e}"))?;
817    if !canon.starts_with(&root) {
818        return Err(format!(
819            "`{rel}` resolves to {}, outside the skill's directory",
820            canon.display()
821        ));
822    }
823    Ok(joined)
824}
825
826#[cfg(test)]
827mod tests {
828    use super::*;
829
830    const FIXTURE: &str = concat!(
831        env!("CARGO_MANIFEST_DIR"),
832        "/tests/fixtures/hermes-skill/SKILL.md"
833    );
834
835    fn write(path: &Path, body: &str) {
836        if let Some(parent) = path.parent() {
837            std::fs::create_dir_all(parent).unwrap();
838        }
839        std::fs::write(path, body).unwrap();
840    }
841
842    fn skill_md(name: &str, description: &str) -> String {
843        format!("---\nname: {name}\ndescription: {description}\n---\n\nDo the thing for {name}.\n")
844    }
845
846    fn root(source: Source, dir: &Path) -> Root {
847        Root {
848            source,
849            dir: dir.to_path_buf(),
850        }
851    }
852
853    #[test]
854    fn plain_and_quoted_scalars_and_flow_sequences_are_read() {
855        let skill = parse(
856            "---\nname: nightly-backup\ndescription: \"Use when backing up: the media stack.\"\n\
857             version: 1.0.0\ntags: [backup, \"ops, nightly\"]\nrequires: ['shell']\n---\nSteps.\n",
858        )
859        .unwrap();
860        assert_eq!(skill.meta.name, "nightly-backup");
861        assert_eq!(
862            skill.meta.description,
863            "Use when backing up: the media stack."
864        );
865        assert_eq!(skill.meta.version.as_deref(), Some("1.0.0"));
866        assert_eq!(skill.meta.tags, ["backup", "ops, nightly"]);
867        assert_eq!(skill.meta.requires, ["shell"]);
868        assert_eq!(skill.body, "Steps.");
869    }
870
871    #[test]
872    fn empty_values_and_trailing_comments_are_tolerated() {
873        let skill = parse(
874            "---\nname: a\ndescription:\nversion:\ntags: []\nrequires: [shell]   # tools it needs\n\
875             # a comment line\n---\nbody\n",
876        )
877        .unwrap();
878        assert_eq!(skill.meta.description, "");
879        assert_eq!(skill.meta.version, None);
880        assert!(skill.meta.tags.is_empty());
881        assert_eq!(skill.meta.requires, ["shell"]);
882    }
883
884    #[test]
885    fn nested_blocks_and_unknown_keys_are_ignored_not_rejected() {
886        let skill = parse(
887            "---\nname: a\nauthor: Nox\nmetadata:\n  hermes:\n    tags: [news, search]\n    \
888             related_skills: [x, y]\n    weird: \"never closed\nlicense: MIT\ndescription: d\n---\nbody\n",
889        )
890        .unwrap();
891        assert_eq!(skill.meta.name, "a");
892        assert_eq!(skill.meta.description, "d");
893        assert!(
894            skill.meta.tags.is_empty(),
895            "`tags` nested under `metadata.hermes` is not the skill's own `tags`"
896        );
897    }
898
899    #[test]
900    fn block_sequences_and_block_scalars_are_read() {
901        let skill = parse(
902            "---\nname: a\ndescription: >-\n  first line\n  second line\ntags:\n  - one\n  - \"two\"\n\
903             requires:\n- shell\n---\nbody\n",
904        )
905        .unwrap();
906        assert_eq!(skill.meta.description, "first line second line");
907        assert_eq!(skill.meta.tags, ["one", "two"]);
908        assert_eq!(skill.meta.requires, ["shell"]);
909    }
910
911    #[test]
912    fn crlf_line_endings_and_a_byte_order_mark_are_accepted() {
913        let skill = parse("\u{feff}---\r\nname: a\r\ndescription: d\r\n---\r\nbody\r\n").unwrap();
914        assert_eq!(skill.meta.name, "a");
915        assert_eq!(skill.body, "body");
916    }
917
918    #[test]
919    fn a_missing_name_is_an_error_that_says_so() {
920        let err = parse("---\ndescription: d\n---\nbody\n").unwrap_err();
921        assert!(err.contains("missing `name`"), "{err}");
922        let err = parse("---\nname:\ndescription: d\n---\nbody\n").unwrap_err();
923        assert!(err.contains("missing `name`"), "{err}");
924        let err = parse("just a body\n").unwrap_err();
925        assert!(err.contains("no frontmatter"), "{err}");
926    }
927
928    #[test]
929    fn an_unterminated_fence_is_an_error() {
930        let err = parse("---\nname: a\ndescription: d\nbody that never closes\n").unwrap_err();
931        assert!(err.contains("unterminated frontmatter"), "{err}");
932        assert!(parse("---").unwrap_err().contains("unterminated"));
933    }
934
935    #[test]
936    fn an_empty_body_is_an_error() {
937        let err = parse("---\nname: a\ndescription: d\n---\n\n  \n").unwrap_err();
938        assert!(err.contains("empty body"), "{err}");
939    }
940
941    #[test]
942    fn an_unclosed_quote_or_bracket_on_a_key_we_read_is_an_error() {
943        let err = parse("---\nname: a\ndescription: \"oops\n---\nbody\n").unwrap_err();
944        assert!(
945            err.contains("line 3") && err.contains("description"),
946            "{err}"
947        );
948        let err = parse("---\nname: a\ntags: [x, y\n---\nbody\n").unwrap_err();
949        assert!(err.contains("`tags`"), "{err}");
950    }
951
952    #[test]
953    fn a_skill_file_over_the_size_limit_is_reported_rather_than_read() {
954        let tmp = tempfile::tempdir().unwrap();
955        let dir = tmp.path();
956        write(&dir.join("good/SKILL.md"), &skill_md("good", "works"));
957        let mut huge = skill_md("huge", "far too big");
958        huge.push_str(&"x".repeat(MAX_SKILL_FILE_BYTES as usize + 1));
959        write(&dir.join("huge/SKILL.md"), &huge);
960
961        let report = discover(&[root(Source::Shared, dir)]);
962        let broken: Vec<String> = report
963            .broken()
964            .map(|f| f.broken_reason().unwrap().to_string())
965            .collect();
966        assert_eq!(broken.len(), 1, "{broken:?}");
967        assert!(broken[0].contains("bytes; the limit is"), "{}", broken[0]);
968        assert_eq!(report.active().count(), 1, "the good skill still loads");
969    }
970
971    #[test]
972    fn a_broken_skill_is_reported_with_its_reason_and_kept_out_of_the_index() {
973        let tmp = tempfile::tempdir().unwrap();
974        let dir = tmp.path();
975        write(&dir.join("good/SKILL.md"), &skill_md("good", "works"));
976        write(
977            &dir.join("nameless/SKILL.md"),
978            "---\ndescription: d\n---\nbody\n",
979        );
980        write(&dir.join("open/SKILL.md"), "---\nname: open\n");
981        write(&dir.join("hollow/SKILL.md"), "---\nname: hollow\n---\n");
982        std::fs::create_dir_all(dir.join("dirskill/SKILL.md")).unwrap();
983        write_bytes(
984            &dir.join("binary/SKILL.md"),
985            b"---\nname: b\n---\n\xff\xfe\n",
986        );
987
988        let report = discover(&[root(Source::Shared, dir)]);
989        let reasons: Vec<(String, String)> = report
990            .broken()
991            .map(|f| (f.name.clone(), f.broken_reason().unwrap().to_string()))
992            .collect();
993        let reason_of = |n: &str| {
994            reasons
995                .iter()
996                .find(|(name, _)| name == n)
997                .unwrap_or_else(|| panic!("{n} is not reported: {reasons:?}"))
998                .1
999                .clone()
1000        };
1001        assert!(reason_of("nameless").contains("missing `name`"));
1002        assert!(reason_of("open").contains("unterminated"));
1003        assert!(reason_of("hollow").contains("empty body"));
1004        assert!(reason_of("dirskill").contains("is a directory"));
1005        assert!(reason_of("binary").contains("UTF-8"));
1006        assert_eq!(report.active().count(), 1);
1007
1008        let (index, notes) = index(&report, 0);
1009        let index = index.unwrap();
1010        assert_eq!(index.names, ["good"]);
1011        for hidden in ["nameless", "open", "hollow", "dirskill", "binary"] {
1012            assert!(
1013                !index.body.contains(hidden),
1014                "{hidden} leaked: {}",
1015                index.body
1016            );
1017            assert!(
1018                notes.iter().any(|n| n.contains(&format!("`{hidden}`"))),
1019                "{hidden} has no note: {notes:?}"
1020            );
1021        }
1022    }
1023
1024    fn write_bytes(path: &Path, bytes: &[u8]) {
1025        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1026        std::fs::write(path, bytes).unwrap();
1027    }
1028
1029    #[test]
1030    fn a_profile_skill_shadows_a_shared_one_and_the_winning_path_is_named() {
1031        let tmp = tempfile::tempdir().unwrap();
1032        let shared = tmp.path().join("shared");
1033        let profile = tmp.path().join("profile");
1034        write(
1035            &shared.join("backup/SKILL.md"),
1036            &skill_md("backup", "shared copy"),
1037        );
1038        write(
1039            &shared.join("other/SKILL.md"),
1040            &skill_md("other", "only shared"),
1041        );
1042        write(
1043            &profile.join("backup/SKILL.md"),
1044            &skill_md("backup", "profile copy"),
1045        );
1046
1047        let report = discover(&[
1048            root(Source::Shared, &shared),
1049            root(Source::Profile("work".into()), &profile),
1050        ]);
1051        let backup = report.get("backup").unwrap();
1052        assert_eq!(backup.source, Source::Profile("work".into()));
1053        assert_eq!(backup.skill().unwrap().meta.description, "profile copy");
1054        assert_eq!(backup.path, profile.join("backup/SKILL.md"));
1055        assert_eq!(
1056            backup.shadows,
1057            [Shadowed {
1058                source: Source::Shared,
1059                path: shared.join("backup/SKILL.md")
1060            }],
1061            "the report says what the winner beat, and where it lives"
1062        );
1063        assert_eq!(report.get("other").unwrap().source, Source::Shared);
1064        assert_eq!(report.active().count(), 2, "one `backup`, not two");
1065    }
1066
1067    #[test]
1068    fn precedence_runs_shared_then_profile_then_workspace_then_plugins() {
1069        let tmp = tempfile::tempdir().unwrap();
1070        let dirs: Vec<PathBuf> = ["shared", "profile", "workspace", "plugin"]
1071            .iter()
1072            .map(|d| tmp.path().join(d))
1073            .collect();
1074        for (i, dir) in dirs.iter().enumerate() {
1075            write(
1076                &dir.join("s/SKILL.md"),
1077                &skill_md("s", &format!("from {i}")),
1078            );
1079        }
1080        let roots = vec![
1081            root(Source::Shared, &dirs[0]),
1082            root(Source::Profile("p".into()), &dirs[1]),
1083            root(Source::Workspace, &dirs[2]),
1084            root(Source::Plugin("pl".into()), &dirs[3]),
1085        ];
1086        let report = discover(&roots);
1087        let won = report.get("s").unwrap();
1088        assert_eq!(won.source.label(), "plugin:pl");
1089        assert_eq!(won.shadows.len(), 3);
1090        // Without the plugin, the workspace wins: later shadows earlier, all the way down.
1091        let report = discover(&roots[..3]);
1092        assert_eq!(report.get("s").unwrap().source, Source::Workspace);
1093    }
1094
1095    #[test]
1096    fn a_broken_skill_does_not_shadow_a_working_one_of_the_same_name() {
1097        let tmp = tempfile::tempdir().unwrap();
1098        let shared = tmp.path().join("shared");
1099        let profile = tmp.path().join("profile");
1100        write(
1101            &shared.join("backup/SKILL.md"),
1102            &skill_md("backup", "works"),
1103        );
1104        write(&profile.join("backup/SKILL.md"), "---\nname: backup\n---\n");
1105
1106        let report = discover(&[
1107            root(Source::Shared, &shared),
1108            root(Source::Profile("p".into()), &profile),
1109        ]);
1110        let winner = report.get("backup").unwrap();
1111        assert_eq!(winner.source, Source::Shared);
1112        assert_eq!(
1113            report.broken().count(),
1114            1,
1115            "and the broken copy is still reported"
1116        );
1117    }
1118
1119    #[test]
1120    fn category_folders_are_searched_and_hidden_ones_are_not() {
1121        let tmp = tempfile::tempdir().unwrap();
1122        let dir = tmp.path();
1123        write(
1124            &dir.join("devops/deploy/SKILL.md"),
1125            &skill_md("deploy", "d"),
1126        );
1127        write(&dir.join(".git/hooks/SKILL.md"), &skill_md("hidden", "d"));
1128        write(&dir.join("notes/README.md"), "not a skill");
1129        let report = discover(&[root(Source::Shared, dir)]);
1130        let names: Vec<_> = report.active().map(|(f, _)| f.name.as_str()).collect();
1131        assert_eq!(names, ["deploy"]);
1132        assert!(
1133            report.problems.is_empty(),
1134            "a folder with no skills is not a problem"
1135        );
1136    }
1137
1138    #[test]
1139    fn a_missing_skills_directory_is_not_a_problem() {
1140        let tmp = tempfile::tempdir().unwrap();
1141        let report = discover(&[root(Source::Shared, &tmp.path().join("nope"))]);
1142        assert!(report.found.is_empty() && report.problems.is_empty());
1143    }
1144
1145    #[test]
1146    fn the_index_lists_name_description_and_what_a_skill_requires() {
1147        let tmp = tempfile::tempdir().unwrap();
1148        write(
1149            &tmp.path().join("a/SKILL.md"),
1150            "---\nname: a\ndescription: \"first\"\nrequires: [shell, fetch]\n---\nbody\n",
1151        );
1152        write(&tmp.path().join("b/SKILL.md"), &skill_md("b", "second"));
1153        let report = discover(&[root(Source::Shared, tmp.path())]);
1154        let (index, notes) = index(&report, 4000);
1155        let index = index.unwrap();
1156        assert!(
1157            index
1158                .body
1159                .contains("- a: first (needs tools: shell, fetch)"),
1160            "{}",
1161            index.body
1162        );
1163        assert!(index.body.contains("\n- b: second"), "{}", index.body);
1164        assert!(
1165            !index.body.contains("Do the thing"),
1166            "bodies are loaded on demand"
1167        );
1168        assert!(notes.is_empty(), "{notes:?}");
1169        assert_eq!(index.chars, index.body.chars().count());
1170    }
1171
1172    #[test]
1173    fn over_budget_the_index_drops_entries_and_names_them() {
1174        let tmp = tempfile::tempdir().unwrap();
1175        for name in ["alpha", "beta", "gamma", "delta"] {
1176            write(
1177                &tmp.path().join(name).join("SKILL.md"),
1178                &skill_md(name, &"x".repeat(60)),
1179            );
1180        }
1181        let report = discover(&[root(Source::Shared, tmp.path())]);
1182        let (full, _) = index(&report, 0);
1183        let full = full.unwrap();
1184        assert_eq!(full.names.len(), 4, "0 means no cap");
1185
1186        // Room for the preamble and the first two entries (69 and 68 chars), not a third.
1187        let budget = full.chars - 2 * 70;
1188        let (small, notes) = index(&report, budget);
1189        let small = small.unwrap();
1190        assert_eq!(
1191            small.names,
1192            ["alpha", "beta"],
1193            "name order within one source"
1194        );
1195        // `#350`: the omission line rides *outside* the budget on purpose — it is the escape
1196        // hatch from the budget, so the entries fit and the note that says what did not is the
1197        // only thing past the line.
1198        assert!(
1199            small.chars <= budget + 200,
1200            "{} > {budget} + the note",
1201            small.chars
1202        );
1203        let note = notes
1204            .iter()
1205            .find(|n| n.contains("left out 2 of 4"))
1206            .unwrap();
1207        assert!(note.contains("delta, gamma"), "{note}");
1208        assert!(note.contains("index_budget_chars"), "{note}");
1209        assert!(!small.body.contains("gamma"));
1210    }
1211
1212    /// `#350`: a dropped skill used to be invisible to the one reader that could have asked for
1213    /// it. The index now says how many are missing and which verb finds them.
1214    #[test]
1215    fn the_index_tells_the_model_what_it_left_out() {
1216        let tmp = tempfile::tempdir().unwrap();
1217        for name in ["alpha", "beta", "gamma"] {
1218            write(
1219                &tmp.path().join(name).join("SKILL.md"),
1220                &skill_md(name, &"x".repeat(60)),
1221            );
1222        }
1223        let report = discover(&[root(Source::Shared, tmp.path())]);
1224        let (full, _) = index(&report, 0);
1225        // Room for the preamble and the first entry, not a second: two of the three are dropped.
1226        let budget = full.unwrap().chars - 100;
1227        let (small, _) = index(&report, budget);
1228        let body = small.unwrap().body;
1229        assert!(body.contains("alpha"), "{body}");
1230        assert!(
1231            body.contains("2 more skill(s) exist but did not fit here"),
1232            "the model is told what is missing: {body}"
1233        );
1234        assert!(body.contains("skill_search"), "and how to reach it: {body}");
1235        assert!(!body.contains("gamma"), "the dropped entry is not listed");
1236
1237        // With room for everything there is no note: the line is for a truncation, not a fixture.
1238        let (whole, _) = index(&report, 0);
1239        assert!(!whole.unwrap().body.contains("did not fit"));
1240    }
1241
1242    #[test]
1243    fn when_the_narrower_scope_is_kept_the_shared_skills_go_first() {
1244        let tmp = tempfile::tempdir().unwrap();
1245        let shared = tmp.path().join("shared");
1246        let ws = tmp.path().join("ws");
1247        write(
1248            &shared.join("aaa/SKILL.md"),
1249            &skill_md("aaa", &"x".repeat(40)),
1250        );
1251        write(&ws.join("zzz/SKILL.md"), &skill_md("zzz", &"x".repeat(40)));
1252        let report = discover(&[root(Source::Shared, &shared), root(Source::Workspace, &ws)]);
1253        let (full, _) = index(&report, 0);
1254        let budget = full.unwrap().chars - 10;
1255        let (small, notes) = index(&report, budget);
1256        assert_eq!(small.unwrap().names, ["zzz"]);
1257        assert!(notes[0].contains("aaa"), "{notes:?}");
1258    }
1259
1260    #[test]
1261    fn a_budget_too_small_for_one_entry_leaves_no_index_and_says_why() {
1262        let tmp = tempfile::tempdir().unwrap();
1263        write(&tmp.path().join("a/SKILL.md"), &skill_md("a", "d"));
1264        let report = discover(&[root(Source::Shared, tmp.path())]);
1265        let (index, notes) = index(&report, 20);
1266        assert!(index.is_none());
1267        assert!(
1268            notes.iter().any(|n| n.contains("left out 1 of 1")),
1269            "{notes:?}"
1270        );
1271    }
1272
1273    #[test]
1274    fn a_real_hermes_skill_loads_unmodified() {
1275        let text = std::fs::read_to_string(FIXTURE).unwrap_or_else(|e| {
1276            panic!(
1277                "the Hermes fixture is missing or unreadable ({e}): expected a verbatim copy of a \
1278real Hermes SKILL.md at {FIXTURE}. Restore it with `git checkout -- crates/eclipse-core/tests/fixtures`; \
1279do not edit it to make this test pass."
1280            )
1281        });
1282        // Verbatim from a real Hermes install (`latest-news-search`): nested `metadata.hermes`
1283        // frontmatter and a quoted description.
1284        let skill = parse(&text).unwrap();
1285        assert_eq!(skill.meta.name, "latest-news-search");
1286        assert_eq!(
1287            skill.meta.description,
1288            "Search for and compile latest news on any topic with verified dates"
1289        );
1290        assert_eq!(skill.meta.version.as_deref(), Some("1.0.0"));
1291        assert!(skill.body.starts_with("## Trigger"), "{}", skill.body);
1292        assert!(skill.body.contains("skill_view('skill-router')"));
1293
1294        // And through discovery, the way a user's library would reach it.
1295        let tmp = tempfile::tempdir().unwrap();
1296        write(&tmp.path().join("news/latest-news-search/SKILL.md"), &text);
1297        let report = discover(&[root(Source::Shared, tmp.path())]);
1298        assert_eq!(report.broken().count(), 0);
1299        let (index, _) = index(&report, 4000);
1300        assert!(index
1301            .unwrap()
1302            .body
1303            .contains("- latest-news-search: Search for and compile latest news"));
1304    }
1305
1306    #[test]
1307    fn linked_files_are_listed_from_the_three_supporting_directories() {
1308        let tmp = tempfile::tempdir().unwrap();
1309        let dir = tmp.path();
1310        write(&dir.join("SKILL.md"), &skill_md("a", "d"));
1311        write(&dir.join("references/x.md"), "x");
1312        write(&dir.join("references/deep/y.md"), "y");
1313        write(&dir.join("scripts/z.sh"), "z");
1314        write(&dir.join("templates/t"), "t");
1315        write(&dir.join("notes/ignored.md"), "n");
1316        assert_eq!(
1317            linked_files(dir),
1318            [
1319                "references/deep/y.md",
1320                "references/x.md",
1321                "scripts/z.sh",
1322                "templates/t"
1323            ]
1324        );
1325    }
1326
1327    #[test]
1328    fn a_path_may_not_leave_the_skill_directory() {
1329        let tmp = tempfile::tempdir().unwrap();
1330        let dir = tmp.path().join("skill");
1331        write(&dir.join("references/x.md"), "x");
1332        write(&tmp.path().join("secret.txt"), "secret");
1333
1334        assert!(resolve_inside(&dir, "references/x.md").is_ok());
1335        assert!(
1336            resolve_inside(&dir, "references/new/file.md").is_ok(),
1337            "may not exist yet"
1338        );
1339        assert!(resolve_inside(&dir, "../secret.txt")
1340            .unwrap_err()
1341            .contains(".."));
1342        assert!(resolve_inside(&dir, "references/../../secret.txt").is_err());
1343        assert!(resolve_inside(&dir, "/etc/passwd")
1344            .unwrap_err()
1345            .contains("absolute"));
1346        assert!(resolve_inside(&dir, "").is_err());
1347    }
1348
1349    #[cfg(unix)]
1350    #[test]
1351    fn a_symlink_that_leaves_the_directory_is_refused() {
1352        let tmp = tempfile::tempdir().unwrap();
1353        let dir = tmp.path().join("skill");
1354        write(&dir.join("references/x.md"), "x");
1355        write(&tmp.path().join("outside/secret.txt"), "secret");
1356        std::os::unix::fs::symlink(tmp.path().join("outside"), dir.join("references/out")).unwrap();
1357        std::os::unix::fs::symlink(dir.join("references/x.md"), dir.join("references/inside"))
1358            .unwrap();
1359
1360        let err = resolve_inside(&dir, "references/out/secret.txt").unwrap_err();
1361        assert!(err.contains("outside the skill's directory"), "{err}");
1362        let err = resolve_inside(&dir, "references/out/new.txt").unwrap_err();
1363        assert!(
1364            err.contains("outside"),
1365            "a write through the link is refused too: {err}"
1366        );
1367        assert!(
1368            resolve_inside(&dir, "references/inside").is_ok(),
1369            "a link that stays inside is fine"
1370        );
1371    }
1372}