Skip to main content

tinyharness_lib/
skill.rs

1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3
4use serde::{Deserialize, Serialize};
5
6/// Maximum size for a skill content (characters).
7/// Skills exceeding this are truncated with a notice.
8const SKILL_MAX_CHARS: usize = 10_000;
9
10/// A skill discovered from a SKILL.md file.
11///
12/// Skills are reusable instruction sets that can be invoked by the user
13/// (via `/skill <name>`) or automatically by the model (via the `invoke_skill`
14/// signal tool). They live in `<config_dir>/skills/<name>/SKILL.md` (personal,
15/// e.g. `~/.config/tinyharness/skills/`), the legacy `~/.tinyharness/skills/`,
16/// or `.tinyharness/skills/<name>/SKILL.md` (project-local).
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct Skill {
19    /// The skill name (from frontmatter `name` field or directory name).
20    pub name: String,
21    /// A short description of when and how to use this skill.
22    pub description: String,
23    /// Optional hint shown to the user about what argument to pass (e.g. "file path to review").
24    pub argument_hint: Option<String>,
25    /// Optional compatibility string (e.g. "rust", "python", "any").
26    pub compatibility: Option<String>,
27    /// If true, the model may NOT auto-invoke this skill; only manual `/skill` invocation is allowed.
28    pub disable_model_invocation: bool,
29    /// Optional license identifier (e.g. "MIT", "Apache-2.0").
30    pub license: Option<String>,
31    /// Optional arbitrary metadata as key-value pairs.
32    pub metadata: Option<HashMap<String, String>>,
33    /// If true, the skill can be invoked by the user via `/skill <name>`.
34    pub user_invocable: bool,
35    /// The full markdown content of the SKILL.md file (after frontmatter).
36    pub content: String,
37    /// The filesystem path where this skill was found.
38    pub path: PathBuf,
39    /// Whether this is a personal (home) or project-local skill.
40    pub source: SkillSource,
41}
42
43/// Where a skill was discovered from.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45pub enum SkillSource {
46    /// `<config_dir>/skills/<name>/SKILL.md` (personal), or the legacy
47    /// `~/.tinyharness/skills/<name>/SKILL.md`
48    Personal,
49    /// `.tinyharness/skills/<name>/SKILL.md` (in project directory)
50    Project,
51}
52
53/// Parsed frontmatter fields from a SKILL.md file.
54///
55/// Supported fields (compatible with VS Code agent skills):
56/// - `name` — skill name (defaults to directory name)
57/// - `description` — short description
58/// - `argument-hint` — hint about what argument to pass
59/// - `compatibility` — compatibility info (e.g. "rust", "python")
60/// - `disable-model-invocation` — if true, model cannot auto-invoke
61/// - `license` — license identifier
62/// - `metadata` — arbitrary key-value pairs (indented block)
63/// - `user-invocable` — if true, user can invoke via `/skill <name>`
64struct ParsedFrontmatter {
65    name: Option<String>,
66    description: Option<String>,
67    argument_hint: Option<String>,
68    compatibility: Option<String>,
69    disable_model_invocation: bool,
70    license: Option<String>,
71    metadata: Option<HashMap<String, String>>,
72    user_invocable: bool,
73}
74
75/// Parse simple YAML-like frontmatter (key: value pairs with optional
76/// indented metadata block). This avoids pulling in serde_yaml for what
77/// is essentially flat `key: value` data.
78fn parse_frontmatter(text: &str) -> ParsedFrontmatter {
79    let mut name = None;
80    let mut description = None;
81    let mut argument_hint = None;
82    let mut compatibility = None;
83    let mut disable_model_invocation = false;
84    let mut license = None;
85    let mut user_invocable = true;
86    let mut metadata: Option<HashMap<String, String>> = None;
87
88    let lines: Vec<&str> = text.lines().collect();
89    let mut i = 0;
90
91    while i < lines.len() {
92        let line = lines[i];
93
94        // Skip blank lines
95        if line.trim().is_empty() {
96            i += 1;
97            continue;
98        }
99
100        // Check for indented line — metadata sub-properties
101        if line.starts_with("  ") || line.starts_with("\t") {
102            // This is a continuation of a metadata block
103            if let Some(ref mut map) = metadata {
104                let trimmed = line.trim();
105                if let Some((k, v)) = trimmed.split_once(':') {
106                    map.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
107                }
108            }
109            i += 1;
110            continue;
111        }
112
113        // Top-level key: value
114        if let Some((key, value)) = line.split_once(':') {
115            let key = key.trim();
116            let value = value.trim();
117
118            match key {
119                "name" => name = Some(value.trim_matches('"').to_string()),
120                "description" => description = Some(value.trim_matches('"').to_string()),
121                "argument-hint" => argument_hint = Some(value.trim_matches('"').to_string()),
122                "compatibility" => compatibility = Some(value.trim_matches('"').to_string()),
123                "disable-model-invocation" => disable_model_invocation = value == "true",
124                "license" => license = Some(value.trim_matches('"').to_string()),
125                "user-invocable" => user_invocable = value == "true" || value.is_empty(),
126                "metadata" => {
127                    // Start a metadata block; value after "metadata:" is ignored
128                    metadata.get_or_insert_with(HashMap::new);
129                }
130                _ => {} // ignore unknown keys
131            }
132        }
133
134        i += 1;
135    }
136
137    ParsedFrontmatter {
138        name,
139        description,
140        argument_hint,
141        compatibility,
142        disable_model_invocation,
143        license,
144        metadata,
145        user_invocable,
146    }
147}
148
149/// Parse a SKILL.md file into a `Skill`.
150///
151/// The file format is:
152/// ```markdown
153/// ---
154/// name: my-skill
155/// description: A short description of what this skill does
156/// argument-hint: file path to review
157/// compatibility: rust
158/// disable-model-invocation: false
159/// license: MIT
160/// metadata:
161///   version: "1.0"
162/// user-invocable: true
163/// ---
164///
165/// # My Skill
166///
167/// Instructions for the skill go here...
168/// ```
169///
170/// The frontmatter is optional. If missing, the skill name is derived from
171/// the directory name and description defaults to an empty string.
172pub fn parse_skill_md(content: &str, path: &Path, source: SkillSource) -> Result<Skill, String> {
173    let (frontmatter, body) = extract_frontmatter(content);
174
175    let fm = frontmatter.map(|s| parse_frontmatter(&s));
176
177    // Name: frontmatter > directory name
178    let name = fm
179        .as_ref()
180        .and_then(|f| f.name.clone())
181        .or_else(|| {
182            path.parent()
183                .and_then(|p| p.file_name())
184                .map(|n| n.to_string_lossy().to_string())
185        })
186        .ok_or_else(|| format!("Cannot determine skill name for {}", path.display()))?;
187
188    let description = fm
189        .as_ref()
190        .and_then(|f| f.description.clone())
191        .unwrap_or_default();
192    let argument_hint = fm.as_ref().and_then(|f| f.argument_hint.clone());
193    let compatibility = fm.as_ref().and_then(|f| f.compatibility.clone());
194    let disable_model_invocation = fm
195        .as_ref()
196        .map(|f| f.disable_model_invocation)
197        .unwrap_or(false);
198    let license = fm.as_ref().and_then(|f| f.license.clone());
199    let metadata = fm.as_ref().and_then(|f| f.metadata.clone());
200    let user_invocable = fm.as_ref().map(|f| f.user_invocable).unwrap_or(true);
201
202    let content = truncate_skill_content(body.trim(), &name);
203
204    Ok(Skill {
205        name,
206        description,
207        argument_hint,
208        compatibility,
209        disable_model_invocation,
210        license,
211        metadata,
212        user_invocable,
213        content,
214        path: path.to_path_buf(),
215        source,
216    })
217}
218
219/// Extract YAML frontmatter from a markdown file.
220/// Returns (Some(frontmatter_str), body_str) if frontmatter exists,
221/// or (None, full_content) if no frontmatter is found.
222fn extract_frontmatter(content: &str) -> (Option<String>, String) {
223    let trimmed = content.trim_start();
224    if !trimmed.starts_with("---") {
225        return (None, content.to_string());
226    }
227
228    // Find the closing ---
229    let after_first = &trimmed[3..]; // skip opening ---
230    // Skip whitespace after opening ---
231    let after_first = after_first.trim_start();
232
233    if let Some(end_pos) = after_first.find("\n---") {
234        let yaml_content = after_first[..end_pos].to_string();
235        // Body starts after the closing ---
236        let body_start = end_pos + 4; // skip "\n---"
237        let body = after_first[body_start..].to_string();
238        (Some(yaml_content), body)
239    } else if let Some(end_pos) = after_first.find("---") {
240        let yaml_content = after_first[..end_pos].to_string();
241        let body_start = end_pos + 3; // skip "---"
242        let body = after_first[body_start..].to_string();
243        (Some(yaml_content), body)
244    } else {
245        (None, content.to_string())
246    }
247}
248
249/// Truncate skill content that exceeds the maximum size.
250fn truncate_skill_content(content: &str, name: &str) -> String {
251    if content.len() <= SKILL_MAX_CHARS {
252        return content.to_string();
253    }
254
255    let head_ratio = 0.70;
256    let head_end = (SKILL_MAX_CHARS as f64 * head_ratio) as usize;
257    let tail_size = SKILL_MAX_CHARS - head_end;
258
259    let head = &content[..content.floor_char_boundary(head_end)];
260    let tail_start = content.len().saturating_sub(tail_size);
261    let tail = &content[content.floor_char_boundary(tail_start)..];
262
263    format!(
264        "{head}\n\n[...truncated skill '{name}': showing first {head_end} + last {tail_size} chars. Use the read tool to view the full file.]\n\n{tail}"
265    )
266}
267
268/// Personal skills directory: `<config_dir>/skills` (e.g.
269/// `~/.config/tinyharness/skills`).
270///
271/// Returns the *primary* location. The legacy `~/.tinyharness/skills` is also
272/// searched by [`discover_skills`] — use [`personal_skills_dirs`] to see the
273/// full ordered list.
274pub fn personal_skills_dir() -> PathBuf {
275    crate::paths::Paths::default()
276        .personal_skills_dirs()
277        .into_iter()
278        .next()
279        .expect("personal_skills_dirs is never empty")
280}
281
282/// All personal skill directories, in decreasing precedence order.
283///
284/// Resolved from the ambient environment — see
285/// [`Paths::personal_skills_dirs`](crate::paths::Paths::personal_skills_dirs)
286/// for the injectable form.
287pub fn personal_skills_dirs() -> Vec<PathBuf> {
288    crate::paths::Paths::default().personal_skills_dirs()
289}
290
291/// Project-local skills directory: `.tinyharness/skills/` (relative to CWD)
292pub fn project_skills_dir() -> PathBuf {
293    crate::paths::Paths::default().project_skills_dir()
294}
295
296/// Discover all skills from the personal and project directories.
297///
298/// Resolved from the ambient environment and process CWD — use
299/// [`discover_skills_in`] when the caller has a
300/// [`Paths`](crate::paths::Paths).
301pub fn discover_skills() -> Vec<Skill> {
302    discover_skills_in(&crate::paths::Paths::default())
303}
304
305/// Discover all skills for an injected set of paths.
306///
307/// Scans `<dir>/*/SKILL.md` in each personal directory returned by
308/// [`Paths::personal_skills_dirs`](crate::paths::Paths::personal_skills_dirs),
309/// then the project directory. Precedence,
310/// highest last (a later source overrides an earlier one on name collision):
311///
312/// 1. `<config_dir>/skills` (documented XDG location)
313/// 2. `~/.tinyharness/skills` (legacy location, still supported)
314/// 3. `<project_dir>/.tinyharness/skills`
315pub fn discover_skills_in(paths: &crate::paths::Paths) -> Vec<Skill> {
316    let mut skills = Vec::new();
317
318    // Personal skills: earlier directories win, so the XDG location takes
319    // precedence over the legacy dot-directory.
320    for personal_dir in paths.personal_skills_dirs() {
321        if let Ok(entries) = discover_skills_from_dir(&personal_dir, SkillSource::Personal) {
322            for skill in entries {
323                if !skills.iter().any(|s: &Skill| s.name == skill.name) {
324                    skills.push(skill);
325                }
326            }
327        }
328    }
329
330    // Project skills override personal skills with the same name.
331    let project_dir = paths.project_skills_dir();
332    if let Ok(entries) = discover_skills_from_dir(&project_dir, SkillSource::Project) {
333        for skill in entries {
334            if let Some(pos) = skills.iter().position(|s| s.name == skill.name) {
335                skills[pos] = skill;
336            } else {
337                skills.push(skill);
338            }
339        }
340    }
341
342    // Sort alphabetically by name
343    skills.sort_by(|a, b| a.name.cmp(&b.name));
344    skills
345}
346
347/// Discover skills from a specific directory.
348fn discover_skills_from_dir(dir: &Path, source: SkillSource) -> Result<Vec<Skill>, std::io::Error> {
349    let mut skills = Vec::new();
350
351    if !dir.is_dir() {
352        return Ok(skills);
353    }
354
355    for entry in std::fs::read_dir(dir)? {
356        let entry = entry?;
357        let path = entry.path();
358
359        if !path.is_dir() {
360            continue;
361        }
362
363        let skill_file = path.join("SKILL.md");
364        if !skill_file.is_file() {
365            continue;
366        }
367
368        let content = match std::fs::read_to_string(&skill_file) {
369            Ok(c) => c,
370            Err(e) => {
371                tracing::warn!("Failed to read skill file {}: {e}", skill_file.display(),);
372                continue;
373            }
374        };
375
376        match parse_skill_md(&content, &skill_file, source) {
377            Ok(skill) => skills.push(skill),
378            Err(e) => {
379                tracing::warn!("Failed to parse skill file {}: {e}", skill_file.display(),);
380                continue;
381            }
382        }
383    }
384
385    Ok(skills)
386}
387
388/// A registry of discovered skills, used by the agent loop and commands.
389#[derive(Debug, Clone, Serialize, Deserialize)]
390pub struct SkillRegistry {
391    pub skills: Vec<Skill>,
392}
393
394impl SkillRegistry {
395    /// Discover and build a registry of all available skills.
396    ///
397    /// Resolved from the ambient environment — use [`SkillRegistry::discover_in`]
398    /// when the caller has a [`Paths`](crate::paths::Paths).
399    pub fn discover() -> Self {
400        Self::discover_in(&crate::paths::Paths::default())
401    }
402
403    /// Discover and build a registry for an injected set of paths.
404    pub fn discover_in(paths: &crate::paths::Paths) -> Self {
405        SkillRegistry {
406            skills: discover_skills_in(paths),
407        }
408    }
409
410    /// Look up a skill by name (case-insensitive).
411    pub fn get(&self, name: &str) -> Option<&Skill> {
412        let name_lower = name.to_lowercase();
413        self.skills
414            .iter()
415            .find(|s| s.name.to_lowercase() == name_lower)
416    }
417
418    /// Get all skills that can be auto-invoked by the model.
419    pub fn auto_invocable_skills(&self) -> Vec<&Skill> {
420        self.skills
421            .iter()
422            .filter(|s| !s.disable_model_invocation)
423            .collect()
424    }
425
426    /// Format the skill index for injection into the system prompt.
427    ///
428    /// Returns a string listing all available skills with names and descriptions,
429    /// and compatibility/argument hints for auto-invocable skills.
430    pub fn format_index_for_prompt(&self) -> String {
431        if self.skills.is_empty() {
432            return String::new();
433        }
434
435        let mut lines = Vec::new();
436        lines.push("## Available Skills\n".to_string());
437        lines.push("You can invoke a skill using the `invoke_skill` tool with the skill name. Skills provide specialized instructions for specific tasks.\n".to_string());
438
439        for skill in &self.skills {
440            let mut parts = vec![format!("**{}**", skill.name)];
441
442            if !skill.description.is_empty() {
443                parts.push(format!(": {}", skill.description));
444            }
445
446            if let Some(hint) = &skill.argument_hint {
447                parts.push(format!(" (arg: {})", hint));
448            }
449
450            if let Some(compat) = &skill.compatibility {
451                parts.push(format!(" [{}]", compat));
452            }
453
454            if skill.disable_model_invocation {
455                parts.push(" _(manual invocation only)_".to_string());
456            }
457
458            lines.push(format!("- {}", parts.join("")));
459        }
460
461        lines.push("\nUse `invoke_skill` to activate a skill. The skill's full instructions will be injected into the conversation.".to_string());
462        lines.join("\n")
463    }
464
465    /// Format the full content of a skill for injection into the system prompt
466    /// when the skill is active.
467    pub fn format_skill_content(&self, skill: &Skill) -> String {
468        format!(
469            "## Active Skill: {}\n\n{}\n\n---\nSkill instructions:\n{}",
470            skill.name, skill.description, skill.content
471        )
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478    use std::fs;
479
480    #[test]
481    fn test_parse_skill_md_with_frontmatter() {
482        let content = r#"---
483name: test-skill
484description: A test skill for unit tests
485argument-hint: file path to test
486compatibility: rust
487disable-model-invocation: false
488license: MIT
489metadata:
490  version: "1.0"
491user-invocable: true
492---
493
494# Test Skill
495
496This is the body of the test skill.
497"#;
498        let dir = tempfile::tempdir().unwrap();
499        let skill_path = dir.path().join("test-skill").join("SKILL.md");
500        fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
501        fs::write(&skill_path, content).unwrap();
502
503        let skill = parse_skill_md(content, &skill_path, SkillSource::Personal).unwrap();
504        assert_eq!(skill.name, "test-skill");
505        assert_eq!(skill.description, "A test skill for unit tests");
506        assert_eq!(skill.argument_hint, Some("file path to test".to_string()));
507        assert_eq!(skill.compatibility, Some("rust".to_string()));
508        assert!(!skill.disable_model_invocation);
509        assert_eq!(skill.license, Some("MIT".to_string()));
510        assert!(skill.user_invocable);
511        assert!(skill.content.contains("# Test Skill"));
512        assert!(skill.content.contains("body of the test skill"));
513    }
514
515    #[test]
516    fn test_parse_skill_md_without_frontmatter() {
517        let content = "# My Skill\n\nThis is a skill without frontmatter.";
518        let dir = tempfile::tempdir().unwrap();
519        let skill_path = dir.path().join("my-skill").join("SKILL.md");
520        fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
521
522        let skill = parse_skill_md(content, &skill_path, SkillSource::Project).unwrap();
523        assert_eq!(skill.name, "my-skill"); // Falls back to directory name
524        assert_eq!(skill.description, ""); // Defaults to empty
525        assert!(skill.argument_hint.is_none());
526        assert!(skill.compatibility.is_none());
527        assert!(!skill.disable_model_invocation);
528        assert!(skill.user_invocable); // Defaults to true
529    }
530
531    #[test]
532    fn test_parse_skill_md_minimal_frontmatter() {
533        let content = "---\nname: minimal\n---\n\nJust the name, no description.";
534        let dir = tempfile::tempdir().unwrap();
535        let skill_path = dir.path().join("minimal").join("SKILL.md");
536        fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
537
538        let skill = parse_skill_md(content, &skill_path, SkillSource::Personal).unwrap();
539        assert_eq!(skill.name, "minimal");
540        assert_eq!(skill.description, "");
541    }
542
543    #[test]
544    fn test_extract_frontmatter() {
545        let content = "---\nname: test\n---\nBody text";
546        let (fm, body) = extract_frontmatter(content);
547        assert!(fm.is_some());
548        assert!(body.contains("Body text"));
549    }
550
551    #[test]
552    fn test_extract_frontmatter_none() {
553        let content = "No frontmatter here, just text.";
554        let (fm, body) = extract_frontmatter(content);
555        assert!(fm.is_none());
556        assert_eq!(body, content);
557    }
558
559    #[test]
560    fn test_parse_frontmatter_with_metadata() {
561        let fm = parse_frontmatter("metadata:\n  version: \"1.0\"\n  author: test");
562        assert!(fm.metadata.is_some());
563        let meta = fm.metadata.unwrap();
564        assert_eq!(meta.get("version").unwrap(), "1.0");
565        assert_eq!(meta.get("author").unwrap(), "test");
566    }
567
568    #[test]
569    fn test_parse_frontmatter_boolean_fields() {
570        let fm = parse_frontmatter("disable-model-invocation: true\nuser-invocable: false");
571        assert!(fm.disable_model_invocation);
572        assert!(!fm.user_invocable);
573    }
574
575    #[test]
576    fn test_parse_frontmatter_defaults() {
577        let fm = parse_frontmatter("name: hello");
578        assert_eq!(fm.name, Some("hello".to_string()));
579        assert!(!fm.disable_model_invocation); // defaults to false
580        assert!(fm.user_invocable); // defaults to true
581        assert!(fm.description.is_none());
582        assert!(fm.argument_hint.is_none());
583        assert!(fm.metadata.is_none());
584    }
585
586    #[test]
587    fn test_skill_registry_format_index() {
588        let skill = Skill {
589            name: "rust-dev".to_string(),
590            description: "Rust development best practices".to_string(),
591            argument_hint: Some("Rust file or module".to_string()),
592            compatibility: Some("rust".to_string()),
593            disable_model_invocation: false,
594            license: None,
595            metadata: None,
596            user_invocable: true,
597            content: "Instructions...".to_string(),
598            path: PathBuf::from("/test/SKILL.md"),
599            source: SkillSource::Personal,
600        };
601
602        let registry = SkillRegistry {
603            skills: vec![skill],
604        };
605
606        let index = registry.format_index_for_prompt();
607        assert!(index.contains("rust-dev"));
608        assert!(index.contains("invoke_skill"));
609        assert!(index.contains("arg:"));
610        assert!(index.contains("[rust]"));
611    }
612
613    #[test]
614    fn test_skill_registry_format_disabled() {
615        let skill = Skill {
616            name: "manual-only".to_string(),
617            description: "Manual invocation only".to_string(),
618            argument_hint: None,
619            compatibility: None,
620            disable_model_invocation: true,
621            license: None,
622            metadata: None,
623            user_invocable: true,
624            content: "Instructions...".to_string(),
625            path: PathBuf::from("/test/SKILL.md"),
626            source: SkillSource::Personal,
627        };
628
629        let registry = SkillRegistry {
630            skills: vec![skill],
631        };
632
633        let index = registry.format_index_for_prompt();
634        assert!(index.contains("manual invocation only"));
635    }
636}