use crate::config::{Config, EnvFn};
use crate::plugins::Plugins;
use std::path::{Component, Path, PathBuf};
pub const DEFAULT_INDEX_BUDGET_CHARS: usize = 4000;
pub const SKILL_FILE: &str = "SKILL.md";
pub const SUPPORT_DIRS: [&str; 3] = ["references", "scripts", "templates"];
const MAX_DEPTH: usize = 3;
const MAX_LINKED: usize = 200;
const MAX_LINKED_DEPTH: usize = 4;
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.";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
Shared,
Profile(String),
Workspace,
Plugin(String),
}
impl Source {
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}"),
}
}
fn keep_rank(&self) -> u8 {
match self {
Source::Workspace => 0,
Source::Profile(_) => 1,
Source::Plugin(_) => 2,
Source::Shared => 3,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Root {
pub source: Source,
pub dir: PathBuf,
}
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"),
});
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
}
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))
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Frontmatter {
pub name: String,
pub description: String,
pub version: Option<String>,
pub tags: Vec<String>,
pub requires: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Skill {
pub meta: Frontmatter,
pub body: String,
}
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 })
}
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;
}
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)
}
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(" "))
}
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()
}
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)
}
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
}
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()
}
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 {
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
}
#[derive(Debug, Clone)]
pub struct Found {
pub name: String,
pub source: Source,
pub dir: PathBuf,
pub path: PathBuf,
pub state: Result<Skill, String>,
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)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Shadowed {
pub source: Source,
pub path: PathBuf,
}
#[derive(Debug, Clone, Default)]
pub struct Report {
pub found: Vec<Found>,
pub problems: Vec<String>,
}
impl Report {
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())
}
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))
}
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
}
}
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
}
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
}
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())
.filter(|p| std::fs::metadata(p).map(|m| m.is_dir()).unwrap_or(false))
.collect();
children.sort();
for child in children {
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)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Index {
pub body: String,
pub chars: usize,
pub names: Vec<String>,
}
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 {
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);
}
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)
}
pub(crate) fn entry_line(meta: &Frontmatter) -> String {
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
}
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
}
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();
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);
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");
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"
);
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"));
}
#[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);
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");
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."
)
});
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')"));
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"
);
}
}