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