Files
hx/crates/hx-core/src/context.rs
T
johannesandClaude Sonnet 5.5 9843e5305c skills: fall back to line-based frontmatter when YAML is invalid
Descriptions with an unquoted ': ' (e.g. floorplan) failed strict YAML and
the skill was silently dropped. Read single-line known keys instead; skills
with no recognised key are still skipped and reported in /skills.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 23:36:18 +01:00

473 lines
17 KiB
Rust

//! System prompt, AGENTS.md discovery, skills.
use std::path::{Path, PathBuf};
pub const DEFAULT_PROMPT: &str = "You are hx, a coding agent working in the user's repository. \
Use the tools to read, edit and run code. Read files before editing them. Keep answers short.\n\n\
# Working rules\n\
- Inspect with the tools, not scripts: `read` for files, `rg` to search text, `fd` or `find` to list files, `ls`/`tree` for directories.\n\
- Never use node, python, perl, sed or awk to look at files or data; they need user approval every time. Read-only commands (ls cat head tail rg fd find grep wc jq sort, git status/log/diff/show) run without a prompt, also piped into each other.\n\
- One simple command per call: no `;`, `&&`, redirects, `$()`. Those need approval too.\n\
- Issue independent tool calls together in one turn; they run in parallel.\n\
- Script only when the task needs it (build, test, edit), not to explore.\n\
- After editing, run the narrowest relevant check (build, test, lint) and fix failures before saying done. Say what you ran; if no check exists, say so.\n\
- Prefer `edit` with a unique `old_string` over rewriting a whole file with `write`.";
const CONTEXT_FILES: &[&str] = &["AGENTS.md", "CLAUDE.md"];
pub fn hx_home() -> PathBuf {
std::env::var_os("HX_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| {
std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_default()
.join(".hx")
})
}
/// Context files from global (`~/.hx`) then root-most to `cwd`. First match per dir.
pub fn context_files(home: &Path, cwd: &Path) -> Vec<(PathBuf, String)> {
let mut dirs: Vec<&Path> = cwd.ancestors().collect();
dirs.reverse();
let mut out = vec![];
for d in std::iter::once(home).chain(dirs) {
for n in CONTEXT_FILES {
let p = d.join(n);
if let Ok(s) = std::fs::read_to_string(&p) {
out.push((p, s));
break;
}
}
}
out
}
#[derive(Debug, Clone, PartialEq)]
pub struct Skill {
pub name: String,
pub description: String,
pub path: PathBuf,
pub load: Load,
/// False (`disable-model-invocation: true` or `load: manual`): not in the prompt index, the
/// `skill` tool refuses it; only the user's `/<name>` reaches it.
pub model_invocable: bool,
/// `argument-hint:` shown next to `/<name>`.
pub hint: Option<String>,
/// Text after the frontmatter.
pub body: String,
}
impl Skill {
/// Skill directory (holds `SKILL.md` and its helper files).
pub fn dir(&self) -> &Path {
self.path.parent().unwrap_or(Path::new(""))
}
/// What the model or a `/<name>` command receives: base dir line + body, no frontmatter.
pub fn text(&self) -> String {
format!(
"Base directory for this skill: {}\n\n{}",
self.dir().display(),
self.body
)
}
}
/// Frontmatter `load:` key. `auto` (default): name + description in the system prompt, the model calls
/// the `skill` tool when the task matches. `always`: the body is inlined in the system prompt. `manual`:
/// alias for `disable-model-invocation: true`, only reachable as a `/<name>` command.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Load {
#[default]
Auto,
Always,
Manual,
}
/// Known frontmatter keys; everything else (`license`, ...) is ignored.
#[derive(serde::Deserialize, Default)]
struct Front {
name: Option<String>,
description: Option<String>,
load: Option<String>,
#[serde(rename = "disable-model-invocation")]
disable_model_invocation: Option<bool>,
#[serde(rename = "argument-hint")]
argument_hint: Option<String>,
}
/// Fallback for frontmatter that is not valid YAML: `key: value` on one line, value taken verbatim
/// (surrounding quotes stripped). None when no known key is found.
fn lenient_front(fm: &str) -> Option<Front> {
let mut f = Front::default();
let mut found = false;
for line in fm.lines() {
let Some((k, v)) = line.split_once(':') else {
continue;
};
let v = v.trim();
let v = v
.strip_prefix('"')
.and_then(|x| x.strip_suffix('"'))
.unwrap_or(v)
.to_string();
match k {
"name" => f.name = Some(v),
"description" => f.description = Some(v),
"load" => f.load = Some(v),
"disable-model-invocation" => f.disable_model_invocation = Some(v == "true"),
"argument-hint" => f.argument_hint = Some(v),
_ => continue,
}
found = true;
}
found.then_some(f)
}
/// Skill dirs, lowest priority first: `~/.claude/skills`, `~/.agents/skills` (shared with other agents),
/// `<hx home>/skills`, `<project>/.agents/skills`, `<project>/.claude/skills`, `<project>/.hx/skills`.
pub fn skill_dirs(home: &Path, cwd: &Path) -> Vec<PathBuf> {
let user = std::env::var_os("HOME").map(PathBuf::from);
let mut v: Vec<PathBuf> = user
.iter()
.flat_map(|h| [h.join(".claude/skills"), h.join(".agents/skills")])
.collect();
v.extend([
home.join("skills"),
cwd.join(".agents/skills"),
cwd.join(".claude/skills"),
cwd.join(".hx/skills"),
]);
v
}
pub fn skills(home: &Path, cwd: &Path) -> Vec<Skill> {
skills_in(&skill_dirs(home, cwd))
}
pub fn skills_in(dirs: &[PathBuf]) -> Vec<Skill> {
scan_skills(dirs).0
}
/// Parse one `SKILL.md`. Err: the frontmatter is not valid YAML.
pub fn parse_skill(p: &Path, s: &str) -> Result<Skill, String> {
let (fm, body) = s
.strip_prefix("---")
.and_then(|r| r.split_once("\n---"))
.map_or(("", s), |(f, b)| {
(f, b.split_once('\n').map_or("", |x| x.1))
});
let f: Front = if fm.trim().is_empty() {
Front::default()
} else {
match serde_norway::from_str(fm) {
Ok(f) => f,
// strict YAML failed (e.g. unquoted `: ` in a description): read single-line top-level keys
Err(e) => lenient_front(fm).ok_or_else(|| e.to_string())?,
}
};
let load = match f.load.as_deref() {
Some("always") => Load::Always,
Some("manual") => Load::Manual,
_ => Load::Auto,
};
Ok(Skill {
name: f.name.unwrap_or_else(|| {
p.parent()
.and_then(|d| d.file_name())
.unwrap_or_default()
.to_string_lossy()
.into()
}),
// folded (`>`) and literal (`|`) blocks become one line
description: f
.description
.unwrap_or_default()
.split_whitespace()
.collect::<Vec<_>>()
.join(" "),
load,
model_invocable: !f.disable_model_invocation.unwrap_or(false) && load != Load::Manual,
hint: f.argument_hint.filter(|h| !h.trim().is_empty()),
body: body.trim().to_string(),
path: p.to_path_buf(),
})
}
/// `<dir>/<name>/SKILL.md`. Later dirs override earlier ones by name. Skills whose frontmatter does not
/// parse are skipped and reported in the second value (shown by `/skills`).
pub fn scan_skills(dirs: &[PathBuf]) -> (Vec<Skill>, Vec<String>) {
let mut out: Vec<Skill> = vec![];
let mut warn = vec![];
for dir in dirs {
let Ok(rd) = std::fs::read_dir(dir) else {
continue;
};
let mut paths: Vec<_> = rd
.flatten()
.map(|e| e.path().join("SKILL.md"))
.filter(|p| p.is_file())
.collect();
paths.sort();
for p in paths {
let Ok(s) = std::fs::read_to_string(&p) else {
continue;
};
match parse_skill(&p, &s) {
Ok(sk) => {
out.retain(|x| x.name != sk.name);
out.push(sk);
}
Err(e) => warn.push(format!("{}: skipped, bad frontmatter: {e}", p.display())),
}
}
}
(out, warn)
}
/// One system-prompt index line for an `auto` skill.
pub fn skill_index_line(k: &Skill) -> String {
format!("- {}: {}\n", k.name, k.description)
}
pub fn system_prompt(base: Option<&str>, home: &Path, cwd: &Path) -> String {
format!(
"{}{}",
base.unwrap_or(DEFAULT_PROMPT),
prompt_tail(home, cwd)
)
}
/// Everything after the base prompt (cwd, skills, context files, memory). Scans the disk: compute once, reuse per role.
pub fn prompt_tail(home: &Path, cwd: &Path) -> String {
let mut s = String::new();
s.push_str(&format!("\n\nWorking directory: {}", cwd.display()));
let sk = skills(home, cwd);
for k in sk.iter().filter(|k| k.load == Load::Always) {
s.push_str(&format!("\n\n# Skill: {}\n{}", k.name, k.body));
}
let auto: Vec<_> = sk
.iter()
.filter(|k| k.load == Load::Auto && k.model_invocable)
.collect();
if !auto.is_empty() {
s.push_str("\n\n# Skills\nCall the `skill` tool with the name when the task matches.\n");
for k in auto {
s.push_str(&skill_index_line(k));
}
}
for (p, c) in context_files(home, cwd) {
s.push_str(&format!("\n\n# {}\n{}", p.display(), c.trim()));
}
s.push_str(&crate::memory::prompt_section(home, cwd));
s
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_prompt_has_working_rules() {
assert!(
DEFAULT_PROMPT.contains("never use node") || DEFAULT_PROMPT.contains("Never use node")
);
assert!(DEFAULT_PROMPT.contains("`rg`"));
assert!(DEFAULT_PROMPT.contains("narrowest relevant check"));
}
#[test]
fn prompt_assembly() {
let t = tempfile::tempdir().unwrap();
let home = t.path().join("home");
let proj = t.path().join("proj/sub");
std::fs::create_dir_all(home.join("skills/g")).unwrap();
std::fs::create_dir_all(proj.join(".hx/skills/g")).unwrap();
std::fs::write(home.join("AGENTS.md"), "GLOBAL").unwrap();
std::fs::write(t.path().join("proj/AGENTS.md"), "PROJ").unwrap();
std::fs::write(t.path().join("proj/CLAUDE.md"), "IGNORED").unwrap();
std::fs::write(proj.join("CLAUDE.md"), "SUB").unwrap();
std::fs::write(
home.join("skills/g/SKILL.md"),
"---\nname: g\ndescription: global\n---\nbody",
)
.unwrap();
std::fs::write(
proj.join(".hx/skills/g/SKILL.md"),
"---\nname: g\ndescription: \"local\"\n---\nBODY",
)
.unwrap();
let s = system_prompt(None, &home, &proj);
let (g, p, sub) = (
s.find("GLOBAL").unwrap(),
s.find("PROJ").unwrap(),
s.find("SUB").unwrap(),
);
assert!(g < p && p < sub);
assert!(!s.contains("IGNORED"));
assert!(s.contains("- g: local") && !s.contains("global"));
assert!(!s.contains("BODY"), "skill body must load on demand only");
assert!(system_prompt(Some("CUSTOM"), &home, &proj).starts_with("CUSTOM"));
}
#[test]
fn index_line_is_full_description() {
let k = Skill {
name: "n".into(),
description: "d".repeat(500),
path: "/p/SKILL.md".into(),
load: Load::Auto,
model_invocable: true,
hint: None,
body: String::new(),
};
assert_eq!(skill_index_line(&k), format!("- n: {}\n", "d".repeat(500)));
}
#[test]
fn frontmatter_yaml() {
let p = Path::new("/r/n/SKILL.md");
let k = parse_skill(
p,
"---\nname: n\ndescription: >\n line one\n line two\nlicense: MIT\noutput: x\nargument-hint: <pr>\ndisable-model-invocation: true\n---\nB\n",
)
.unwrap();
assert_eq!(k.description, "line one line two");
assert_eq!(k.hint.as_deref(), Some("<pr>"));
assert!(!k.model_invocable && k.load == Load::Auto);
let k = parse_skill(p, "---\nname: n\ndescription: |\n a\n b\n---\n").unwrap();
assert_eq!(k.description, "a b");
assert!(parse_skill(p, "---\noops: [oops\n---\nB").is_err());
let k = parse_skill(p, "no frontmatter").unwrap();
assert_eq!((k.name.as_str(), k.body.as_str()), ("n", "no frontmatter"));
assert!(
!parse_skill(
p,
"---
load: manual
---
"
)
.unwrap()
.model_invocable
);
}
#[test]
fn user_only_and_broken_skills() {
let t = tempfile::tempdir().unwrap();
for (n, fm) in [
("ok", "description: fine"),
("hid", "description: secret\ndisable-model-invocation: true"),
("bad", "oops: [oops"),
("colon", "description: before code exists: when asked"),
] {
let d = t.path().join("s").join(n);
std::fs::create_dir_all(&d).unwrap();
std::fs::write(d.join("SKILL.md"), format!("---\n{fm}\n---\nBODY-{n}\n")).unwrap();
}
let (sk, warn) = scan_skills(&[t.path().join("s")]);
let names: Vec<_> = sk.iter().map(|k| k.name.as_str()).collect();
assert_eq!(names, ["colon", "hid", "ok"]);
assert_eq!(sk[0].description, "before code exists: when asked");
assert!(
warn.len() == 1 && warn[0].contains("bad/SKILL.md"),
"{warn:?}"
);
let home = t.path().join("h");
std::fs::create_dir_all(home.join("skills")).unwrap();
for n in ["ok", "hid"] {
let d = home.join("skills").join(n);
std::fs::create_dir_all(&d).unwrap();
std::fs::copy(
t.path().join("s").join(n).join("SKILL.md"),
d.join("SKILL.md"),
)
.unwrap();
}
let p = system_prompt(None, &home, &t.path().join("proj"));
assert!(p.contains("- ok: fine") && !p.contains("secret"), "{p}");
assert!(p.contains("Call the `skill` tool"));
}
#[test]
fn skill_load_modes() {
let t = tempfile::tempdir().unwrap();
for (n, l) in [("a", "always"), ("m", "manual"), ("d", "")] {
let d = t.path().join(n);
std::fs::create_dir_all(&d).unwrap();
let load = if l.is_empty() {
String::new()
} else {
format!("load: {l}\n")
};
std::fs::write(
d.join("SKILL.md"),
format!("---\nname: {n}\ndescription: use when {n}\n{load}---\nBODY-{n}\n"),
)
.unwrap();
}
let sk = skills_in(&[t.path().to_path_buf()]);
let loads: Vec<_> = sk.iter().map(|s| (s.name.as_str(), s.load)).collect();
assert_eq!(
loads,
[("a", Load::Always), ("d", Load::Auto), ("m", Load::Manual)]
);
assert_eq!(sk[0].body, "BODY-a");
// prompt: always inlined, auto listed only, manual absent
let home = t.path().join("h");
std::fs::create_dir_all(home.join("skills")).unwrap();
for n in ["a", "d", "m"] {
std::fs::create_dir_all(home.join("skills").join(n)).unwrap();
std::fs::copy(
t.path().join(n).join("SKILL.md"),
home.join("skills").join(n).join("SKILL.md"),
)
.unwrap();
}
let p = system_prompt(None, &home, &t.path().join("proj"));
assert!(p.contains("BODY-a") && !p.contains("- a:"));
assert!(p.contains("- d: use when d") && !p.contains("BODY-d"));
assert!(!p.contains("BODY-m") && !p.contains("- m:"));
}
#[test]
fn agent_skills_dir() {
let t = tempfile::tempdir().unwrap();
let w = |p: &str, s: &str| {
let p = t.path().join(p);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, s).unwrap();
};
w(
"agent/a/SKILL.md",
"---\nname: a\ndescription: shared\n---\n",
);
w(
"agent/g/SKILL.md",
"---\nname: g\ndescription: shared-g\n---\n",
);
w("hx/g/SKILL.md", "---\nname: g\ndescription: hx-g\n---\n");
let sk = skills_in(&[t.path().join("agent"), t.path().join("hx")]);
let got: Vec<(&str, &str)> = sk
.iter()
.map(|s| (s.name.as_str(), s.description.as_str()))
.collect();
assert_eq!(got, [("a", "shared"), ("g", "hx-g")]);
let d = skill_dirs(Path::new("/h"), Path::new("/p"));
assert!(d[0].ends_with(".claude/skills") && d[1].ends_with(".agents/skills"));
assert_eq!(
d[2..],
[
"/h/skills",
"/p/.agents/skills",
"/p/.claude/skills",
"/p/.hx/skills"
]
.map(PathBuf::from)
);
}
}