1use 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
15pub const HARN_SKILLS_DIR_ENV: &str = "HARN_SKILLS_DIR";
17
18#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct EmbeddedSkill {
30 pub name: &'static str,
31 pub frontmatter: SkillFrontmatter,
32 pub body: &'static str,
33 pub source: &'static str,
38}
39
40#[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#[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#[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#[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-de-slop/SKILL.md"),
133 include_str!("corpus/harn-diagnostics/SKILL.md"),
134 include_str!("corpus/harn-language/SKILL.md"),
135 include_str!("corpus/harn-orchestration/SKILL.md"),
136 include_str!("corpus/harn-probe/SKILL.md"),
137 include_str!("corpus/harn-providers/SKILL.md"),
138 include_str!("corpus/harn-rules/SKILL.md"),
139 include_str!("corpus/harn-testing/SKILL.md"),
140 include_str!("corpus/harn-tracing/SKILL.md"),
141 include_str!("corpus/release-harn/SKILL.md"),
142];
143
144static EMBEDDED_SKILLS: OnceLock<Box<[EmbeddedSkill]>> = OnceLock::new();
145
146pub fn list_embedded_skills() -> &'static [EmbeddedSkill] {
148 EMBEDDED_SKILLS
149 .get_or_init(|| SOURCES.iter().map(|source| parse_skill(source)).collect())
150 .as_ref()
151}
152
153pub fn get_embedded_skill(name: &str) -> Option<&'static EmbeddedSkill> {
155 list_embedded_skills()
156 .iter()
157 .find(|skill| skill.name == name)
158}
159
160pub fn resolve_skill_corpus_from_env() -> Result<SkillCorpus, SkillDiscoveryError> {
164 let Ok(dir) = env::var(HARN_SKILLS_DIR_ENV) else {
165 return Ok(SkillCorpus::Embedded(list_embedded_skills()));
166 };
167 if dir.trim().is_empty() {
168 return Ok(SkillCorpus::Embedded(list_embedded_skills()));
169 }
170
171 let skills = list_disk_skills(dir)?;
172 if skills.is_empty() {
173 Ok(SkillCorpus::Embedded(list_embedded_skills()))
174 } else {
175 Ok(SkillCorpus::Disk(skills))
176 }
177}
178
179pub fn list_disk_skills(root: impl AsRef<Path>) -> Result<Vec<DiskSkill>, SkillDiscoveryError> {
184 let root = root.as_ref();
185 if !root.exists() {
186 return Ok(Vec::new());
187 }
188
189 let mut paths = Vec::new();
190 collect_skill_paths(root, &mut paths)?;
191 paths.sort();
192
193 let mut by_name: BTreeMap<String, DiskSkill> = BTreeMap::new();
194 for path in paths {
195 let skill = parse_disk_skill(&path)?;
196 if let Some(first) = by_name.get(&skill.name) {
197 return Err(SkillDiscoveryError::DuplicateName {
198 name: skill.name,
199 first: first.path.clone(),
200 second: path,
201 });
202 }
203 by_name.insert(skill.name.clone(), skill);
204 }
205
206 Ok(by_name.into_values().collect())
207}
208
209fn parse_skill(source: &'static str) -> EmbeddedSkill {
210 let (frontmatter, body) = split_frontmatter(source);
211 let frontmatter = parse_frontmatter(frontmatter);
212 EmbeddedSkill {
213 name: frontmatter.name,
214 frontmatter,
215 body,
216 source,
217 }
218}
219
220fn collect_skill_paths(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), SkillDiscoveryError> {
221 let entries = fs::read_dir(dir).map_err(|source| SkillDiscoveryError::Io {
222 path: dir.to_path_buf(),
223 source,
224 })?;
225 for entry in entries {
226 let entry = entry.map_err(|source| SkillDiscoveryError::Io {
227 path: dir.to_path_buf(),
228 source,
229 })?;
230 let path = entry.path();
231 let file_type = entry
232 .file_type()
233 .map_err(|source| SkillDiscoveryError::Io {
234 path: path.clone(),
235 source,
236 })?;
237 if file_type.is_dir() {
238 collect_skill_paths(&path, out)?;
239 } else if file_type.is_file() && entry.file_name() == "SKILL.md" {
240 out.push(path);
241 }
242 }
243 Ok(())
244}
245
246fn parse_disk_skill(path: &Path) -> Result<DiskSkill, SkillDiscoveryError> {
247 let source = fs::read_to_string(path).map_err(|source| SkillDiscoveryError::Io {
248 path: path.to_path_buf(),
249 source,
250 })?;
251 let (frontmatter, body) =
252 split_disk_frontmatter(&source).ok_or_else(|| SkillDiscoveryError::MissingFrontmatter {
253 path: path.to_path_buf(),
254 })?;
255 let frontmatter = parse_disk_frontmatter(path, frontmatter)?;
256 Ok(DiskSkill {
257 name: frontmatter.name.clone(),
258 frontmatter,
259 body: body.to_string(),
260 source,
261 path: path.to_path_buf(),
262 })
263}
264
265fn split_disk_frontmatter(source: &str) -> Option<(&str, &str)> {
266 split_frontmatter_parts(source)
267}
268
269fn parse_disk_frontmatter(
270 path: &Path,
271 frontmatter: &str,
272) -> Result<DiskSkillFrontmatter, SkillDiscoveryError> {
273 let mut name = None;
274 let mut short = None;
275 let mut description = None;
276 let mut when_to_use = None;
277
278 for line in frontmatter.lines() {
279 let Some((key, value)) = line.split_once(':') else {
280 continue;
281 };
282 let value = value.trim().to_string();
283 match key {
284 "name" => name = Some(value),
285 "short" => short = Some(value),
286 "description" => description = Some(value),
287 "when_to_use" => when_to_use = Some(value),
288 _ => {}
289 }
290 }
291
292 Ok(DiskSkillFrontmatter {
293 name: require_disk_field(path, name, "name")?,
294 short: short.unwrap_or_default(),
295 description: require_disk_field(path, description, "description")?,
296 when_to_use,
297 })
298}
299
300fn require_disk_field(
301 path: &Path,
302 value: Option<String>,
303 field: &'static str,
304) -> Result<String, SkillDiscoveryError> {
305 value.ok_or_else(|| SkillDiscoveryError::MissingField {
306 path: path.to_path_buf(),
307 field,
308 })
309}
310
311fn split_frontmatter(source: &'static str) -> (&'static str, &'static str) {
312 let Some((after_open, line_ending)) = split_opening_frontmatter(source) else {
313 panic!("embedded skill source is missing opening frontmatter delimiter");
314 };
315 let Some((frontmatter, body)) = split_closing_frontmatter(after_open, line_ending) else {
316 panic!("embedded skill source is missing closing frontmatter delimiter");
317 };
318 (frontmatter, body)
319}
320
321fn split_frontmatter_parts(source: &str) -> Option<(&str, &str)> {
322 let (after_open, line_ending) = split_opening_frontmatter(source)?;
323 split_closing_frontmatter(after_open, line_ending)
324}
325
326fn split_opening_frontmatter(source: &str) -> Option<(&str, &str)> {
327 if let Some(after_open) = source.strip_prefix("---\n") {
328 Some((after_open, "\n"))
329 } else if let Some(after_open) = source.strip_prefix("---\r\n") {
330 Some((after_open, "\r\n"))
331 } else {
332 None
333 }
334}
335
336fn split_closing_frontmatter<'a>(
337 after_open: &'a str,
338 line_ending: &str,
339) -> Option<(&'a str, &'a str)> {
340 let close = format!("{line_ending}---{line_ending}");
341 let close_offset = after_open.find(&close)?;
342 Some((
343 &after_open[..close_offset],
344 &after_open[close_offset + close.len()..],
345 ))
346}
347
348fn parse_frontmatter(frontmatter: &'static str) -> SkillFrontmatter {
349 let mut name = None;
350 let mut short = None;
351 let mut description = None;
352 let mut when_to_use = None;
353
354 for line in frontmatter.lines() {
355 let Some((key, value)) = line.split_once(':') else {
356 continue;
357 };
358 let value = value.trim();
359 match key {
360 "name" => name = Some(value),
361 "short" => short = Some(value),
362 "description" => description = Some(value),
363 "when_to_use" => when_to_use = Some(value),
364 _ => {}
365 }
366 }
367
368 SkillFrontmatter {
369 name: name.expect("embedded skill frontmatter is missing `name`"),
370 short: short.expect("embedded skill frontmatter is missing `short`"),
371 description: description.expect("embedded skill frontmatter is missing `description`"),
372 when_to_use,
373 }
374}
375
376#[cfg(test)]
377mod tests {
378 use super::*;
379 use std::collections::BTreeSet;
380 use tempfile::TempDir;
381
382 #[test]
383 fn lists_expected_initial_corpus() {
384 let skills = list_embedded_skills();
385 let names: Vec<&str> = skills.iter().map(|skill| skill.name).collect();
386 assert_eq!(
387 names,
388 [
389 "harn-agent",
390 "harn-de-slop",
391 "harn-diagnostics",
392 "harn-language",
393 "harn-orchestration",
394 "harn-probe",
395 "harn-providers",
396 "harn-rules",
397 "harn-testing",
398 "harn-tracing",
399 "release-harn",
400 ]
401 );
402 assert_eq!(skills.len(), SOURCES.len());
403 }
404
405 #[test]
406 fn can_fetch_harn_language_skill() {
407 let skill = get_embedded_skill("harn-language").expect("harn-language skill is embedded");
408 assert_eq!(skill.frontmatter.name, "harn-language");
409 assert!(skill.body.contains("Harn language"));
410 }
411
412 #[test]
413 fn skills_have_unique_names_and_body_only_content() {
414 let mut names = BTreeSet::new();
415 for skill in list_embedded_skills() {
416 assert_eq!(skill.name, skill.frontmatter.name);
417 assert!(names.insert(skill.name), "duplicate skill {}", skill.name);
418 assert!(
419 !skill.body.trim().is_empty(),
420 "{} body is empty",
421 skill.name
422 );
423 assert!(
424 !skill.body.trim_start().starts_with("---"),
425 "{} body includes frontmatter",
426 skill.name
427 );
428 }
429 }
430
431 #[test]
432 fn skills_are_sorted_by_name() {
433 let names: Vec<&str> = list_embedded_skills()
434 .iter()
435 .map(|skill| skill.name)
436 .collect();
437 let mut sorted = names.clone();
438 sorted.sort_unstable();
439 assert_eq!(names, sorted);
440 }
441
442 #[test]
443 fn source_round_trips_to_frontmatter_and_body() {
444 for skill in list_embedded_skills() {
445 assert!(
446 split_frontmatter_parts(skill.source).is_some(),
447 "{} source missing opening fence",
448 skill.name
449 );
450 assert!(
451 skill.source.ends_with(skill.body),
452 "{} source must end with the body so dump output is byte-stable",
453 skill.name
454 );
455 assert!(
456 skill.source.contains(&format!("name: {}\n", skill.name))
457 || skill.source.contains(&format!("name: {}\r\n", skill.name)),
458 "{} source missing canonical name field",
459 skill.name
460 );
461 }
462 }
463
464 #[test]
465 fn frontmatter_split_accepts_crlf_sources() {
466 let source = "---\r\nname: crlf\r\n---\r\n# Body\r\n";
467 let (frontmatter, body) = split_frontmatter_parts(source).expect("CRLF frontmatter");
468 assert_eq!(frontmatter, "name: crlf");
469 assert_eq!(body, "# Body\r\n");
470 }
471
472 #[test]
473 fn frontmatter_split_rejects_missing_closing_fence() {
474 assert!(split_frontmatter_parts("---\nname: missing\n# Body\n").is_none());
475 }
476
477 #[test]
478 fn embedded_corpus_stays_within_binary_budget() {
479 let bytes: usize = SOURCES.iter().map(|source| source.len()).sum();
480 assert!(
481 bytes <= 200 * 1024,
482 "embedded corpus is {bytes} bytes, expected <= 200 KiB"
483 );
484 }
485
486 #[test]
487 fn skill_bodies_are_focused_and_not_placeholders() {
488 let expectations = [
489 ("harn-agent", ["agent_loop", "session id", "approval"]),
490 ("harn-de-slop", ["typed", "structural guard", "rebase"]),
491 ("harn-diagnostics", ["diagnostic", "repair", "conformance"]),
492 ("harn-language", ["quickref", "type", "conformance"]),
493 ("harn-orchestration", ["agent_loop", "workflow", "host"]),
494 ("harn-probe", ["probe", "fact", "evidence"]),
495 ("harn-providers", ["llm_call", "provider", "schema"]),
496 (
497 "harn-testing",
498 ["conformance", "deterministic", "mock_time"],
499 ),
500 ("harn-tracing", ["replay", "receipts", "transcript"]),
501 ("release-harn", ["release_ship", "merge queue", "tag"]),
502 ];
503
504 for (name, terms) in expectations {
505 let skill = get_embedded_skill(name).expect("expected embedded skill");
506 let body = skill.body.to_ascii_lowercase();
507 assert!(
508 !body.contains("embedded stub") && !body.contains("placeholder"),
509 "{name} should contain real guidance, not stub wording"
510 );
511 for term in terms {
512 assert!(
513 body.contains(term),
514 "{name} body should mention focused term `{term}`"
515 );
516 }
517 }
518 }
519
520 #[test]
521 fn skill_bodies_match_split_skill_contract() {
522 for skill in list_embedded_skills() {
523 let lines = skill.body.lines().count();
524 assert!(
525 lines >= 80,
526 "{} body is {lines} lines, expected at least 80",
527 skill.name
528 );
529 assert!(
530 lines <= 300,
531 "{} body is {lines} lines, expected at most 300",
532 skill.name
533 );
534 }
535 }
536
537 #[test]
538 fn skill_cross_links_resolve_to_embedded_skills() {
539 let names: BTreeSet<&str> = list_embedded_skills()
540 .iter()
541 .map(|skill| skill.name)
542 .collect();
543 for skill in list_embedded_skills() {
544 for reference in bracketed_skill_references(skill.body) {
545 assert!(
546 names.contains(reference),
547 "{} links to unknown embedded skill [[{}]]",
548 skill.name,
549 reference
550 );
551 }
552 }
553 }
554
555 #[test]
556 fn diagnostics_skill_mentions_all_code_categories() {
557 let skill = get_embedded_skill("harn-diagnostics").expect("diagnostics skill");
558 for category in [
559 "TYP", "PAR", "NAM", "CAP", "LLM", "ORC", "STD", "PRM", "MOD", "LNT", "FMT", "IMP",
560 "OWN", "RCV", "MAT",
561 ] {
562 assert!(
563 skill.body.contains(&format!("`{category}`")),
564 "harn-diagnostics should mention diagnostic category `{category}`"
565 );
566 }
567 }
568
569 #[test]
570 fn disk_discovery_finds_recursive_skill_files_sorted_by_name() {
571 let temp = TempDir::new().expect("temp dir");
572 write_skill(
573 &temp.path().join("zeta").join("SKILL.md"),
574 "zeta-skill",
575 "Zeta",
576 );
577 write_skill(
578 &temp.path().join("nested").join("alpha").join("SKILL.md"),
579 "alpha-skill",
580 "Alpha",
581 );
582
583 let skills = list_disk_skills(temp.path()).expect("discover disk skills");
584 let names: Vec<&str> = skills.iter().map(|skill| skill.name.as_str()).collect();
585 assert_eq!(names, ["alpha-skill", "zeta-skill"]);
586 assert_eq!(skills[0].frontmatter.description, "Alpha description");
587 assert!(skills[0].body.contains("Alpha body"));
588 }
589
590 #[test]
591 fn disk_discovery_treats_missing_root_as_empty() {
592 let temp = TempDir::new().expect("temp dir");
593 let skills = list_disk_skills(temp.path().join("missing")).expect("discover disk skills");
594 assert!(skills.is_empty());
595 }
596
597 #[test]
598 fn disk_discovery_rejects_duplicate_skill_names() {
599 let temp = TempDir::new().expect("temp dir");
600 write_skill(
601 &temp.path().join("one").join("SKILL.md"),
602 "same-skill",
603 "One",
604 );
605 write_skill(
606 &temp.path().join("two").join("SKILL.md"),
607 "same-skill",
608 "Two",
609 );
610
611 let error = list_disk_skills(temp.path()).expect_err("duplicate name should fail");
612 assert!(
613 error.to_string().contains("duplicate skill `same-skill`"),
614 "unexpected error: {error}"
615 );
616 }
617
618 fn write_skill(path: &Path, name: &str, label: &str) {
619 fs::create_dir_all(path.parent().expect("skill parent")).expect("create skill parent");
620 fs::write(
621 path,
622 format!(
623 "---\nname: {name}\nshort: {label} short\ndescription: {label} description\n---\n# {label}\n\n{label} body\n"
624 ),
625 )
626 .expect("write SKILL.md");
627 }
628
629 fn bracketed_skill_references(body: &str) -> Vec<&str> {
630 let mut references = Vec::new();
631 let mut rest = body;
632 while let Some(start) = rest.find("[[") {
633 rest = &rest[start + 2..];
634 let Some(end) = rest.find("]]") else {
635 break;
636 };
637 references.push(&rest[..end]);
638 rest = &rest[end + 2..];
639 }
640 references
641 }
642}