mahbot 0.11.2

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
//! Skills subsystem — loads workspace skills and injects them into prompts.
//!
//! Skills live in `<workspace>/skills/<name>/SKILL.md`, then `.claude/skills/`, then
//! `.agents/skills/` (priority order). Each SKILL.md is markdown with optional YAML frontmatter
//! for `name` and `description`; loaded skills render into the system prompt as name +
//! description, with a `<location>` path the model can `read` for full content.
//!
//! Within each location, subdirectories are scanned in byte-sorted name order (never `read_dir`
//! order), so identical directories render byte-identically — keeping the provider prompt-prefix
//! cache stable across renders.

use crate::Skill;
use anyhow::{Context, Result};
use std::collections::HashSet;
use std::fmt::Write;
use std::path::Path;

#[derive(Debug, Clone, Default)]
struct SkillMarkdownMeta {
    name: Option<String>,
    description: Option<String>,
}

fn parse_frontmatter(content: &str) -> SkillMarkdownMeta {
    fn strip_quotes(s: &str) -> String {
        s.trim().trim_matches('"').trim_matches('\'').to_string()
    }

    let content = content.trim();
    if !content.starts_with("---") {
        return SkillMarkdownMeta::default();
    }

    let rest = &content[3..];
    let Some(idx) = rest.find("\n---") else {
        return SkillMarkdownMeta::default();
    };

    let frontmatter = rest[..idx].trim();
    let mut meta = SkillMarkdownMeta::default();

    for line in frontmatter.lines() {
        let line = line.trim();
        if let Some(value) = line.strip_prefix("name:") {
            meta.name = Some(strip_quotes(value));
        } else if let Some(value) = line.strip_prefix("description:") {
            meta.description = Some(strip_quotes(value));
        }
    }

    meta
}

/// Load all skills from the workspace skills directories, in priority order. If several
/// directories hold a skill with the same name, the first wins.
#[must_use]
pub async fn load_skills(ws: &crate::Workspace) -> Vec<Skill> {
    let workspace = ws.as_path();
    let dirs = [
        workspace.join("skills"),
        workspace.join(".claude").join("skills"),
        workspace.join(".agents").join("skills"),
    ];

    let mut seen = HashSet::new();
    let mut skills = Vec::new();

    for dir in dirs {
        for skill in scan_skills_dir(&dir).await {
            if seen.insert(skill.name.clone()) {
                skills.push(skill);
            }
        }
    }

    skills
}

/// Scan a single directory for skill subdirectories (each containing `SKILL.md`).
///
/// Entries are processed in deterministic raw directory-name order (byte sort), not `read_dir`
/// order. Names within a directory are unique, so the sort cannot tie — case-only differences
/// order cleanly and two subdirs declaring the same frontmatter name resolve to the
/// byte-earliest name.
async fn scan_skills_dir(dir: &Path) -> Vec<Skill> {
    let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
        return Vec::new();
    };

    let mut subdirs = Vec::new();
    while let Ok(Some(entry)) = entries.next_entry().await {
        let Ok(file_type) = entry.file_type().await else {
            continue;
        };
        if !file_type.is_dir() {
            continue;
        }

        let path = entry.path();
        if !tokio::fs::try_exists(&path.join("SKILL.md"))
            .await
            .unwrap_or(false)
        {
            continue;
        }
        subdirs.push(path);
    }
    subdirs.sort_by(|a, b| a.file_name().cmp(&b.file_name()));

    let mut skills = Vec::new();
    for path in subdirs {
        if let Ok(skill) = load_skill(&path.join("SKILL.md"), &path).await {
            skills.push(skill);
        }
    }
    skills
}

async fn load_skill(path: &Path, skill_dir: &Path) -> Result<Skill> {
    let content = tokio::fs::read_to_string(path)
        .await
        .context("failed to read SKILL.md")?;
    let meta = parse_frontmatter(&content);

    Ok(Skill {
        name: meta.name.unwrap_or_else(|| {
            skill_dir
                .file_name()
                .map_or("unnamed".to_string(), |s| s.to_string_lossy().into_owned())
        }),
        description: meta
            .description
            .unwrap_or("No description provided.".to_string()),
        location: path.to_path_buf(),
    })
}

/// Render skills into the system prompt.
///
/// Only name and description are inlined; the model must use `read` with the `<location>` path
/// for the full content.
#[must_use]
pub fn skills_to_prompt(skills: &[Skill], ws: &crate::Workspace) -> String {
    let mut skills_xml = String::new();
    for skill in skills {
        let _ = writeln!(skills_xml, "  <skill>");
        write_xml_text_element(&mut skills_xml, 4, "name", &skill.name);
        write_xml_text_element(&mut skills_xml, 4, "description", &skill.description);

        let location = render_skill_location(skill, ws.as_path());
        write_xml_text_element(&mut skills_xml, 4, "location", &location);

        let _ = writeln!(skills_xml, "  </skill>");
    }
    crate::prompt::substitute(
        &crate::prompt::load_prompt("context/skills.md"),
        &[("{{skills}}", skills_xml.trim())],
    )
}

fn write_xml_text_element(w: &mut String, indent: usize, name: &str, value: &str) {
    let padding = " ".repeat(indent);
    let escaped = crate::util::html::escape_html(value);
    let _ = writeln!(w, "{padding}<{name}>{escaped}</{name}>");
}

fn render_skill_location(skill: &Skill, workspace: &Path) -> String {
    if let Ok(relative) = skill.location.strip_prefix(workspace) {
        return relative.display().to_string();
    }
    skill.location.display().to_string()
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::workspace::test_ws;

    /// Write a `SKILL.md` with frontmatter `name`/`description` at
    /// `<root>/<rel>/<dir_name>/SKILL.md`. The body is filler — no test
    /// asserts on it.
    fn write_skill(root: &Path, rel: &str, dir_name: &str, name: &str, desc: &str) {
        let sd = root.join(rel).join(dir_name);
        std::fs::create_dir_all(&sd).unwrap();
        std::fs::write(
            sd.join("SKILL.md"),
            format!("---\nname: {name}\ndescription: {desc}\n---\n\nContent"),
        )
        .unwrap();
    }

    #[tokio::test]
    async fn load_md_skill() {
        let dir = tempfile::tempdir().unwrap();
        let sd = dir.path().join("skills").join("my-skill");
        std::fs::create_dir_all(&sd).unwrap();
        std::fs::write(
                sd.join("SKILL.md"),
                "---\nname: my-skill\ndescription: A markdown skill\n---\n\n# Instructions\nDo something.",
            )
            .unwrap();
        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].name, "my-skill");
        assert_eq!(skills[0].description, "A markdown skill");
    }

    #[tokio::test]
    async fn load_md_skill_without_frontmatter() {
        let dir = tempfile::tempdir().unwrap();
        let sd = dir.path().join("skills").join("bare-skill");
        std::fs::create_dir_all(&sd).unwrap();
        std::fs::write(sd.join("SKILL.md"), "# Instructions\nDo something.").unwrap();
        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].name, "bare-skill");
        assert_eq!(skills[0].description, "No description provided.");
    }

    #[tokio::test]
    async fn load_skills_from_claude_skills_dir() {
        let dir = tempfile::tempdir().unwrap();
        write_skill(
            dir.path(),
            ".claude/skills",
            "my-skill",
            "claude-skill",
            "From .claude/skills",
        );
        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].name, "claude-skill");
    }

    #[tokio::test]
    async fn load_skills_dedup_workspace_priority() {
        let dir = tempfile::tempdir().unwrap();

        write_skill(
            dir.path(),
            "skills",
            "common",
            "common",
            "From workspace skills/",
        );
        write_skill(
            dir.path(),
            ".claude/skills",
            "common",
            "common",
            "From .claude/skills",
        );
        write_skill(
            dir.path(),
            ".agents/skills",
            "common",
            "common",
            "From .agents/skills",
        );

        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].description, "From workspace skills/");
    }

    #[tokio::test]
    async fn load_skills_dedup_claude_over_agents() {
        let dir = tempfile::tempdir().unwrap();

        write_skill(
            dir.path(),
            ".claude/skills",
            "common",
            "common",
            "From .claude/skills",
        );
        write_skill(
            dir.path(),
            ".agents/skills",
            "common",
            "common",
            "From .agents/skills",
        );

        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].description, "From .claude/skills");
    }

    #[tokio::test]
    async fn load_skills_returns_deterministic_order() {
        let dir = tempfile::tempdir().unwrap();

        // Create subdirs in deliberately scrambled order — `read_dir` order is
        // not guaranteed, so the loader must byte-sort by directory name for a
        // stable render. This asserts the sorted order directly (a byte-identical
        // two-render test would pass even pre-fix on APFS's stable-enough order).
        for name in ["zeta", "alpha", "middle"] {
            write_skill(dir.path(), "skills", name, name, &format!("Skill {name}"));
        }

        let skills = load_skills(&test_ws(dir.path())).await;
        let names: Vec<&str> = skills.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, ["alpha", "middle", "zeta"]);
    }

    #[tokio::test]
    async fn load_skills_duplicate_frontmatter_name_uses_sorted_dir_winner() {
        let dir = tempfile::tempdir().unwrap();

        // Two subdirs declaring the same frontmatter name: the winner used to
        // be whatever `read_dir` yielded first (nondeterministic); with the
        // deterministic scan it is the byte-earliest directory name.
        write_skill(dir.path(), "skills", "z-late", "common", "From z-late");
        write_skill(dir.path(), "skills", "a-early", "common", "From a-early");

        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].description, "From a-early");
    }

    #[test]
    fn write_xml_text_element_escapes_special_chars() {
        let mut out = String::new();
        write_xml_text_element(&mut out, 0, "test", "<hello> & \"world\" 'test'");
        assert_eq!(
            out,
            "<test>&lt;hello&gt; &amp; &quot;world&quot; &#39;test&#39;</test>\n"
        );
    }
}