Skip to main content

harn_skills/
lib.rs

1//! Embedded Harn skill corpus.
2//!
3//! This crate exposes the bundled corpus as metadata plus `SKILL.md`
4//! bodies. CLI commands that enumerate, dump, or install these skills
5//! are layered above this foundation.
6
7use std::collections::BTreeMap;
8use std::env;
9use std::fmt;
10use std::fs;
11use std::io;
12use std::path::{Path, PathBuf};
13use std::sync::OnceLock;
14
15/// Environment override for canonical Harn skill discovery.
16pub const HARN_SKILLS_DIR_ENV: &str = "HARN_SKILLS_DIR";
17
18/// Frontmatter fields embedded with each bundled skill.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct SkillFrontmatter {
21    pub name: &'static str,
22    pub short: &'static str,
23    pub description: &'static str,
24    pub when_to_use: Option<&'static str>,
25}
26
27/// A single skill embedded into the Harn build.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct EmbeddedSkill {
30    pub name: &'static str,
31    pub frontmatter: SkillFrontmatter,
32    pub body: &'static str,
33    /// The full original SKILL.md source — frontmatter delimiter,
34    /// frontmatter block, blank line, and body — exactly as embedded.
35    /// Use this when round-tripping a skill back to disk so the dumped
36    /// copy is byte-identical to the binary's canonical record.
37    pub source: &'static str,
38}
39
40/// Owned frontmatter fields loaded from a `SKILL.md` on disk.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct DiskSkillFrontmatter {
43    pub name: String,
44    pub short: String,
45    pub description: String,
46    pub when_to_use: Option<String>,
47}
48
49/// A single skill discovered recursively from `HARN_SKILLS_DIR`.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct DiskSkill {
52    pub name: String,
53    pub frontmatter: DiskSkillFrontmatter,
54    pub body: String,
55    pub source: String,
56    pub path: PathBuf,
57}
58
59/// The active canonical corpus used by `harn skill list/get`.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum SkillCorpus {
62    Embedded(&'static [EmbeddedSkill]),
63    Disk(Vec<DiskSkill>),
64}
65
66impl SkillCorpus {
67    pub fn is_disk(&self) -> bool {
68        matches!(self, Self::Disk(_))
69    }
70
71    pub fn len(&self) -> usize {
72        match self {
73            Self::Embedded(skills) => skills.len(),
74            Self::Disk(skills) => skills.len(),
75        }
76    }
77
78    pub fn is_empty(&self) -> bool {
79        self.len() == 0
80    }
81}
82
83/// Error returned when disk skill discovery finds malformed files.
84#[derive(Debug)]
85pub enum SkillDiscoveryError {
86    Io {
87        path: PathBuf,
88        source: io::Error,
89    },
90    MissingFrontmatter {
91        path: PathBuf,
92    },
93    MissingField {
94        path: PathBuf,
95        field: &'static str,
96    },
97    DuplicateName {
98        name: String,
99        first: PathBuf,
100        second: PathBuf,
101    },
102}
103
104impl fmt::Display for SkillDiscoveryError {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        match self {
107            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
108            Self::MissingFrontmatter { path } => {
109                write!(f, "{}: missing SKILL.md frontmatter", path.display())
110            }
111            Self::MissingField { path, field } => {
112                write!(f, "{}: missing `{field}` frontmatter field", path.display())
113            }
114            Self::DuplicateName {
115                name,
116                first,
117                second,
118            } => write!(
119                f,
120                "duplicate skill `{name}` in {} and {}",
121                first.display(),
122                second.display()
123            ),
124        }
125    }
126}
127
128impl std::error::Error for SkillDiscoveryError {}
129
130const SOURCES: &[&str] = &[
131    include_str!("corpus/harn-agent/SKILL.md"),
132    include_str!("corpus/harn-apps/SKILL.md"),
133    include_str!("corpus/harn-de-slop/SKILL.md"),
134    include_str!("corpus/harn-diagnostics/SKILL.md"),
135    include_str!("corpus/harn-docs/SKILL.md"),
136    include_str!("corpus/harn-language/SKILL.md"),
137    include_str!("corpus/harn-mcp/SKILL.md"),
138    include_str!("corpus/harn-orchestration/SKILL.md"),
139    include_str!("corpus/harn-probe/SKILL.md"),
140    include_str!("corpus/harn-product-quality/SKILL.md"),
141    include_str!("corpus/harn-providers/SKILL.md"),
142    include_str!("corpus/harn-rules/SKILL.md"),
143    include_str!("corpus/harn-testing/SKILL.md"),
144    include_str!("corpus/harn-tracing/SKILL.md"),
145    include_str!("corpus/release-harn/SKILL.md"),
146];
147
148static EMBEDDED_SKILLS: OnceLock<Box<[EmbeddedSkill]>> = OnceLock::new();
149
150/// Return every skill bundled into this build.
151pub fn list_embedded_skills() -> &'static [EmbeddedSkill] {
152    EMBEDDED_SKILLS
153        .get_or_init(|| SOURCES.iter().map(|source| parse_skill(source)).collect())
154        .as_ref()
155}
156
157/// Return one bundled skill by canonical skill name.
158pub fn get_embedded_skill(name: &str) -> Option<&'static EmbeddedSkill> {
159    list_embedded_skills()
160        .iter()
161        .find(|skill| skill.name == name)
162}
163
164/// Return the active canonical corpus. `HARN_SKILLS_DIR` wins only
165/// when it contains at least one recursively discovered `SKILL.md`;
166/// otherwise callers fall back to the embedded corpus.
167pub fn resolve_skill_corpus_from_env() -> Result<SkillCorpus, SkillDiscoveryError> {
168    let Ok(dir) = env::var(HARN_SKILLS_DIR_ENV) else {
169        return Ok(SkillCorpus::Embedded(list_embedded_skills()));
170    };
171    if dir.trim().is_empty() {
172        return Ok(SkillCorpus::Embedded(list_embedded_skills()));
173    }
174
175    let skills = list_disk_skills(dir)?;
176    if skills.is_empty() {
177        Ok(SkillCorpus::Embedded(list_embedded_skills()))
178    } else {
179        Ok(SkillCorpus::Disk(skills))
180    }
181}
182
183/// Recursively discover `SKILL.md` files under `root`.
184///
185/// A missing root is treated as an empty disk corpus so
186/// `HARN_SKILLS_DIR` can fall back cleanly to embedded skills.
187pub fn list_disk_skills(root: impl AsRef<Path>) -> Result<Vec<DiskSkill>, SkillDiscoveryError> {
188    let root = root.as_ref();
189    if !root.exists() {
190        return Ok(Vec::new());
191    }
192
193    let mut paths = Vec::new();
194    collect_skill_paths(root, &mut paths)?;
195    paths.sort();
196
197    let mut by_name: BTreeMap<String, DiskSkill> = BTreeMap::new();
198    for path in paths {
199        let skill = parse_disk_skill(&path)?;
200        if let Some(first) = by_name.get(&skill.name) {
201            return Err(SkillDiscoveryError::DuplicateName {
202                name: skill.name,
203                first: first.path.clone(),
204                second: path,
205            });
206        }
207        by_name.insert(skill.name.clone(), skill);
208    }
209
210    Ok(by_name.into_values().collect())
211}
212
213fn parse_skill(source: &'static str) -> EmbeddedSkill {
214    let (frontmatter, body) = split_frontmatter(source);
215    let frontmatter = parse_frontmatter(frontmatter);
216    EmbeddedSkill {
217        name: frontmatter.name,
218        frontmatter,
219        body,
220        source,
221    }
222}
223
224fn collect_skill_paths(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), SkillDiscoveryError> {
225    let entries = fs::read_dir(dir).map_err(|source| SkillDiscoveryError::Io {
226        path: dir.to_path_buf(),
227        source,
228    })?;
229    for entry in entries {
230        let entry = entry.map_err(|source| SkillDiscoveryError::Io {
231            path: dir.to_path_buf(),
232            source,
233        })?;
234        let path = entry.path();
235        let file_type = entry
236            .file_type()
237            .map_err(|source| SkillDiscoveryError::Io {
238                path: path.clone(),
239                source,
240            })?;
241        if file_type.is_dir() {
242            collect_skill_paths(&path, out)?;
243        } else if file_type.is_file() && entry.file_name() == "SKILL.md" {
244            out.push(path);
245        }
246    }
247    Ok(())
248}
249
250fn parse_disk_skill(path: &Path) -> Result<DiskSkill, SkillDiscoveryError> {
251    let source = fs::read_to_string(path).map_err(|source| SkillDiscoveryError::Io {
252        path: path.to_path_buf(),
253        source,
254    })?;
255    let (frontmatter, body) =
256        split_disk_frontmatter(&source).ok_or_else(|| SkillDiscoveryError::MissingFrontmatter {
257            path: path.to_path_buf(),
258        })?;
259    let frontmatter = parse_disk_frontmatter(path, frontmatter)?;
260    Ok(DiskSkill {
261        name: frontmatter.name.clone(),
262        frontmatter,
263        body: body.to_string(),
264        source,
265        path: path.to_path_buf(),
266    })
267}
268
269fn split_disk_frontmatter(source: &str) -> Option<(&str, &str)> {
270    split_frontmatter_parts(source)
271}
272
273fn parse_disk_frontmatter(
274    path: &Path,
275    frontmatter: &str,
276) -> Result<DiskSkillFrontmatter, SkillDiscoveryError> {
277    let mut name = None;
278    let mut short = None;
279    let mut description = None;
280    let mut when_to_use = None;
281
282    for line in frontmatter.lines() {
283        let Some((key, value)) = line.split_once(':') else {
284            continue;
285        };
286        let value = value.trim().to_string();
287        match key {
288            "name" => name = Some(value),
289            "short" => short = Some(value),
290            "description" => description = Some(value),
291            "when_to_use" => when_to_use = Some(value),
292            _ => {}
293        }
294    }
295
296    Ok(DiskSkillFrontmatter {
297        name: require_disk_field(path, name, "name")?,
298        short: short.unwrap_or_default(),
299        description: require_disk_field(path, description, "description")?,
300        when_to_use,
301    })
302}
303
304fn require_disk_field(
305    path: &Path,
306    value: Option<String>,
307    field: &'static str,
308) -> Result<String, SkillDiscoveryError> {
309    value.ok_or_else(|| SkillDiscoveryError::MissingField {
310        path: path.to_path_buf(),
311        field,
312    })
313}
314
315fn split_frontmatter(source: &'static str) -> (&'static str, &'static str) {
316    let Some((after_open, line_ending)) = split_opening_frontmatter(source) else {
317        panic!("embedded skill source is missing opening frontmatter delimiter");
318    };
319    let Some((frontmatter, body)) = split_closing_frontmatter(after_open, line_ending) else {
320        panic!("embedded skill source is missing closing frontmatter delimiter");
321    };
322    (frontmatter, body)
323}
324
325fn split_frontmatter_parts(source: &str) -> Option<(&str, &str)> {
326    let (after_open, line_ending) = split_opening_frontmatter(source)?;
327    split_closing_frontmatter(after_open, line_ending)
328}
329
330fn split_opening_frontmatter(source: &str) -> Option<(&str, &str)> {
331    if let Some(after_open) = source.strip_prefix("---\n") {
332        Some((after_open, "\n"))
333    } else if let Some(after_open) = source.strip_prefix("---\r\n") {
334        Some((after_open, "\r\n"))
335    } else {
336        None
337    }
338}
339
340fn split_closing_frontmatter<'a>(
341    after_open: &'a str,
342    line_ending: &str,
343) -> Option<(&'a str, &'a str)> {
344    let close = format!("{line_ending}---{line_ending}");
345    let close_offset = after_open.find(&close)?;
346    Some((
347        &after_open[..close_offset],
348        &after_open[close_offset + close.len()..],
349    ))
350}
351
352fn parse_frontmatter(frontmatter: &'static str) -> SkillFrontmatter {
353    let mut name = None;
354    let mut short = None;
355    let mut description = None;
356    let mut when_to_use = None;
357
358    for line in frontmatter.lines() {
359        let Some((key, value)) = line.split_once(':') else {
360            continue;
361        };
362        let value = value.trim();
363        match key {
364            "name" => name = Some(value),
365            "short" => short = Some(value),
366            "description" => description = Some(value),
367            "when_to_use" => when_to_use = Some(value),
368            _ => {}
369        }
370    }
371
372    SkillFrontmatter {
373        name: name.expect("embedded skill frontmatter is missing `name`"),
374        short: short.expect("embedded skill frontmatter is missing `short`"),
375        description: description.expect("embedded skill frontmatter is missing `description`"),
376        when_to_use,
377    }
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383    use std::collections::BTreeSet;
384    use tempfile::TempDir;
385
386    #[test]
387    fn lists_expected_initial_corpus() {
388        let skills = list_embedded_skills();
389        let names: Vec<&str> = skills.iter().map(|skill| skill.name).collect();
390        assert_eq!(
391            names,
392            [
393                "harn-agent",
394                "harn-apps",
395                "harn-de-slop",
396                "harn-diagnostics",
397                "harn-docs",
398                "harn-language",
399                "harn-mcp",
400                "harn-orchestration",
401                "harn-probe",
402                "harn-product-quality",
403                "harn-providers",
404                "harn-rules",
405                "harn-testing",
406                "harn-tracing",
407                "release-harn",
408            ]
409        );
410        assert_eq!(skills.len(), SOURCES.len());
411    }
412
413    #[test]
414    fn can_fetch_harn_language_skill() {
415        let skill = get_embedded_skill("harn-language").expect("harn-language skill is embedded");
416        assert_eq!(skill.frontmatter.name, "harn-language");
417        assert!(skill.body.contains("Harn language"));
418    }
419
420    #[test]
421    fn skills_have_unique_names_and_body_only_content() {
422        let mut names = BTreeSet::new();
423        for skill in list_embedded_skills() {
424            assert_eq!(skill.name, skill.frontmatter.name);
425            assert!(names.insert(skill.name), "duplicate skill {}", skill.name);
426            assert!(
427                !skill.body.trim().is_empty(),
428                "{} body is empty",
429                skill.name
430            );
431            assert!(
432                !skill.body.trim_start().starts_with("---"),
433                "{} body includes frontmatter",
434                skill.name
435            );
436        }
437    }
438
439    #[test]
440    fn skills_are_sorted_by_name() {
441        let names: Vec<&str> = list_embedded_skills()
442            .iter()
443            .map(|skill| skill.name)
444            .collect();
445        let mut sorted = names.clone();
446        sorted.sort_unstable();
447        assert_eq!(names, sorted);
448    }
449
450    #[test]
451    fn source_round_trips_to_frontmatter_and_body() {
452        for skill in list_embedded_skills() {
453            assert!(
454                split_frontmatter_parts(skill.source).is_some(),
455                "{} source missing opening fence",
456                skill.name
457            );
458            assert!(
459                skill.source.ends_with(skill.body),
460                "{} source must end with the body so dump output is byte-stable",
461                skill.name
462            );
463            assert!(
464                skill.source.contains(&format!("name: {}\n", skill.name))
465                    || skill.source.contains(&format!("name: {}\r\n", skill.name)),
466                "{} source missing canonical name field",
467                skill.name
468            );
469        }
470    }
471
472    #[test]
473    fn frontmatter_split_accepts_crlf_sources() {
474        let source = "---\r\nname: crlf\r\n---\r\n# Body\r\n";
475        let (frontmatter, body) = split_frontmatter_parts(source).expect("CRLF frontmatter");
476        assert_eq!(frontmatter, "name: crlf");
477        assert_eq!(body, "# Body\r\n");
478    }
479
480    #[test]
481    fn frontmatter_split_rejects_missing_closing_fence() {
482        assert!(split_frontmatter_parts("---\nname: missing\n# Body\n").is_none());
483    }
484
485    #[test]
486    fn embedded_corpus_stays_within_binary_budget() {
487        let bytes: usize = SOURCES.iter().map(|source| source.len()).sum();
488        assert!(
489            bytes <= 200 * 1024,
490            "embedded corpus is {bytes} bytes, expected <= 200 KiB"
491        );
492    }
493
494    #[test]
495    fn skill_bodies_are_focused_and_not_placeholders() {
496        let expectations = [
497            ("harn-agent", ["agent_loop", "session id", "approval"]),
498            ("harn-apps", ["std/ui", "ui.test.run", "harn app run"]),
499            ("harn-de-slop", ["typed", "structural guard", "rebase"]),
500            ("harn-diagnostics", ["diagnostic", "repair", "conformance"]),
501            ("harn-docs", ["diátaxis", "glossary", "slopwash"]),
502            ("harn-language", ["quickref", "type", "conformance"]),
503            ("harn-mcp", ["mcp_call", "elicitation", "harn serve mcp"]),
504            ("harn-orchestration", ["agent_loop", "workflow", "host"]),
505            ("harn-probe", ["probe", "fact", "evidence"]),
506            (
507                "harn-product-quality",
508                ["canonical path", "control", "liveness"],
509            ),
510            ("harn-providers", ["llm_call", "provider", "schema"]),
511            (
512                "harn-testing",
513                ["conformance", "deterministic", "mock_time"],
514            ),
515            ("harn-tracing", ["replay", "receipts", "transcript"]),
516            ("release-harn", ["release_ship", "merge queue", "tag"]),
517        ];
518
519        for (name, terms) in expectations {
520            let skill = get_embedded_skill(name).expect("expected embedded skill");
521            let body = skill.body.to_ascii_lowercase();
522            assert!(
523                !body.contains("embedded stub") && !body.contains("placeholder"),
524                "{name} should contain real guidance, not stub wording"
525            );
526            for term in terms {
527                assert!(
528                    body.contains(term),
529                    "{name} body should mention focused term `{term}`"
530                );
531            }
532        }
533    }
534
535    #[test]
536    fn skill_bodies_match_split_skill_contract() {
537        for skill in list_embedded_skills() {
538            let lines = skill.body.lines().count();
539            assert!(
540                lines >= 80,
541                "{} body is {lines} lines, expected at least 80",
542                skill.name
543            );
544            assert!(
545                lines <= 300,
546                "{} body is {lines} lines, expected at most 300",
547                skill.name
548            );
549        }
550    }
551
552    #[test]
553    fn language_skill_names_authoritative_spec_sources() {
554        let skill = get_embedded_skill("harn-language").expect("language skill");
555        assert!(
556            skill
557                .body
558                .contains("authoritative chapters under `spec/chapters/*.md`"),
559            "harn-language should direct spec edits to the registered source files"
560        );
561        for generated_edit_target in [
562            "Edit `spec/HARN_SPEC.md`",
563            "Edit `docs/src/language-spec.md`",
564        ] {
565            assert!(
566                !skill.body.contains(generated_edit_target),
567                "harn-language must not direct edits to generated projection `{generated_edit_target}`"
568            );
569        }
570    }
571
572    #[test]
573    fn skill_cross_links_resolve_to_embedded_skills() {
574        let names: BTreeSet<&str> = list_embedded_skills()
575            .iter()
576            .map(|skill| skill.name)
577            .collect();
578        for skill in list_embedded_skills() {
579            for reference in bracketed_skill_references(skill.body) {
580                assert!(
581                    names.contains(reference),
582                    "{} links to unknown embedded skill [[{}]]",
583                    skill.name,
584                    reference
585                );
586            }
587        }
588    }
589
590    #[test]
591    fn diagnostics_skill_mentions_all_code_categories() {
592        let skill = get_embedded_skill("harn-diagnostics").expect("diagnostics skill");
593        for category in [
594            "TYP", "PAR", "NAM", "CAP", "LLM", "ORC", "STD", "PRM", "MOD", "LNT", "FMT", "IMP",
595            "OWN", "RCV", "MAT",
596        ] {
597            assert!(
598                skill.body.contains(&format!("`{category}`")),
599                "harn-diagnostics should mention diagnostic category `{category}`"
600            );
601        }
602    }
603
604    #[test]
605    fn disk_discovery_finds_recursive_skill_files_sorted_by_name() {
606        let temp = TempDir::new().expect("temp dir");
607        write_skill(
608            &temp.path().join("zeta").join("SKILL.md"),
609            "zeta-skill",
610            "Zeta",
611        );
612        write_skill(
613            &temp.path().join("nested").join("alpha").join("SKILL.md"),
614            "alpha-skill",
615            "Alpha",
616        );
617
618        let skills = list_disk_skills(temp.path()).expect("discover disk skills");
619        let names: Vec<&str> = skills.iter().map(|skill| skill.name.as_str()).collect();
620        assert_eq!(names, ["alpha-skill", "zeta-skill"]);
621        assert_eq!(skills[0].frontmatter.description, "Alpha description");
622        assert!(skills[0].body.contains("Alpha body"));
623    }
624
625    #[test]
626    fn disk_discovery_treats_missing_root_as_empty() {
627        let temp = TempDir::new().expect("temp dir");
628        let skills = list_disk_skills(temp.path().join("missing")).expect("discover disk skills");
629        assert!(skills.is_empty());
630    }
631
632    #[test]
633    fn disk_discovery_rejects_duplicate_skill_names() {
634        let temp = TempDir::new().expect("temp dir");
635        write_skill(
636            &temp.path().join("one").join("SKILL.md"),
637            "same-skill",
638            "One",
639        );
640        write_skill(
641            &temp.path().join("two").join("SKILL.md"),
642            "same-skill",
643            "Two",
644        );
645
646        let error = list_disk_skills(temp.path()).expect_err("duplicate name should fail");
647        assert!(
648            error.to_string().contains("duplicate skill `same-skill`"),
649            "unexpected error: {error}"
650        );
651    }
652
653    fn write_skill(path: &Path, name: &str, label: &str) {
654        fs::create_dir_all(path.parent().expect("skill parent")).expect("create skill parent");
655        fs::write(
656            path,
657            format!(
658                "---\nname: {name}\nshort: {label} short\ndescription: {label} description\n---\n# {label}\n\n{label} body\n"
659            ),
660        )
661        .expect("write SKILL.md");
662    }
663
664    fn bracketed_skill_references(body: &str) -> Vec<&str> {
665        let mut references = Vec::new();
666        let mut rest = body;
667        while let Some(start) = rest.find("[[") {
668            rest = &rest[start + 2..];
669            let Some(end) = rest.find("]]") else {
670                break;
671            };
672            references.push(&rest[..end]);
673            rest = &rest[end + 2..];
674        }
675        references
676    }
677}