agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
use serde::Serialize;
use std::path::{Path, PathBuf};

use super::{content_hash, skill_metadata};

/// Join a base path with a forward-slash relative string, splitting each `/`
/// component so `PathBuf::join` emits the platform separator on every segment.
fn portable_join(base: &Path, relative: &str) -> PathBuf {
    relative
        .split('/')
        .fold(base.to_path_buf(), |acc, part| acc.join(part))
}

/// Lightweight config describing where an agent keeps project-level skills.
#[derive(Debug, Clone)]
pub struct AgentSkillConfig {
    pub key: String,
    pub display_name: String,
    /// Relative path from project root to the skills directory (e.g. ".claude/skills").
    pub relative_skills_dir: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct ProjectSkillInfo {
    pub name: String,
    pub dir_name: String,
    #[serde(default)]
    pub relative_path: String,
    pub description: Option<String>,
    pub path: String,
    pub files: Vec<String>,
    pub enabled: bool,
    /// Agent key that owns this skill (e.g. "claude_code", "cursor").
    #[serde(default)]
    pub agent: String,
    /// Human-readable agent name (e.g. "Claude Code", "Cursor").
    #[serde(default)]
    pub agent_display_name: String,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub in_center: bool,
    #[serde(default)]
    pub sync_status: String,
    #[serde(default)]
    pub center_skill_id: Option<String>,
    #[serde(skip_serializing)]
    pub last_modified_at: Option<i64>,
    #[serde(skip_serializing)]
    pub content_hash: Option<String>,
}

/// Read skills from all configured agents' project-level skill directories.
pub fn read_project_skills(
    project_path: &Path,
    agent_configs: &[AgentSkillConfig],
) -> Vec<ProjectSkillInfo> {
    let mut skills = Vec::new();

    for config in agent_configs {
        let skills_dir = portable_join(project_path, &config.relative_skills_dir);
        let disabled_dir = portable_join(
            project_path,
            &format!("{}-disabled", config.relative_skills_dir),
        );

        read_skills_from_dir(
            &skills_dir,
            true,
            &config.key,
            &config.display_name,
            &mut skills,
            true,
        );
        read_skills_from_dir(
            &disabled_dir,
            false,
            &config.key,
            &config.display_name,
            &mut skills,
            true,
        );
    }

    skills.sort_by_key(|a| a.name.to_lowercase());
    skills
}

pub fn read_linked_workspace_skills(
    skills_root: &Path,
    disabled_root: Option<&Path>,
    agent_key: &str,
    agent_display_name: &str,
    recursive: bool,
) -> Vec<ProjectSkillInfo> {
    let mut skills = Vec::new();
    read_skills_from_dir(
        skills_root,
        true,
        agent_key,
        agent_display_name,
        &mut skills,
        recursive,
    );
    if let Some(disabled_root) = disabled_root {
        read_skills_from_dir(
            disabled_root,
            false,
            agent_key,
            agent_display_name,
            &mut skills,
            recursive,
        );
    }
    skills.sort_by_key(|a| a.name.to_lowercase());
    skills
}

fn should_skip_dir(root: &Path, dir: &Path) -> bool {
    let name = dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
    if name.starts_with('.') {
        return true;
    }

    // Ignore embedded plugin/cache bundle layouts such as:
    // <bundle>/<version>/skills/<skill>/SKILL.md
    // The workspace root itself may be named "skills", so only skip nested
    // container directories that introduce another "skills" subtree.
    dir != root && dir.join("skills").is_dir()
}

fn read_skills_from_dir(
    dir: &Path,
    enabled: bool,
    agent: &str,
    agent_display_name: &str,
    skills: &mut Vec<ProjectSkillInfo>,
    recursive: bool,
) {
    if !dir.is_dir() {
        return;
    }
    let mut visited = std::collections::HashSet::new();
    if let Ok(canon) = std::fs::canonicalize(dir) {
        visited.insert(canon);
    }
    read_skills_from_dir_recursive(
        dir,
        dir,
        enabled,
        agent,
        agent_display_name,
        skills,
        &mut visited,
        recursive,
    );
}

// Recursive scanner passes immutable traversal context alongside its output buffer.
#[allow(clippy::too_many_arguments)]
fn read_skills_from_dir_recursive(
    root: &Path,
    current: &Path,
    enabled: bool,
    agent: &str,
    agent_display_name: &str,
    skills: &mut Vec<ProjectSkillInfo>,
    visited: &mut std::collections::HashSet<PathBuf>,
    recursive: bool,
) {
    let Ok(entries) = std::fs::read_dir(current) else {
        return;
    };

    for entry in entries.filter_map(|e| e.ok()) {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }

        if skill_metadata::is_valid_skill_dir(&path) {
            let dir_name = path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| "unknown".to_string());
            let relative_path = path
                .strip_prefix(root)
                .unwrap_or(&path)
                .to_string_lossy()
                .replace('\\', "/");

            let meta = skill_metadata::parse_skill_md(&path);
            let name = meta
                .name
                .filter(|n| !n.is_empty())
                .unwrap_or_else(|| dir_name.clone());

            let files = list_files(&path);

            // One recursive walk feeds both the content hash and the
            // last-modified time (#248). Previously this ran three separate
            // walks per skill: `hash_directory`, plus `latest_modified_millis`
            // which called `canonicalize()` on every node, so the workspace
            // scan cost scaled at ~3× the necessary syscalls per skill.
            let content_entries = content_hash::list_content_files(&path);
            let content_hash = Some(content_hash::hash_entries(&content_entries));
            let last_modified_at = content_hash::latest_modified_ms(&content_entries);

            skills.push(ProjectSkillInfo {
                name,
                dir_name: dir_name.clone(),
                relative_path,
                description: meta.description,
                path: path.to_string_lossy().to_string(),
                files,
                enabled,
                agent: agent.to_string(),
                agent_display_name: agent_display_name.to_string(),
                tags: Vec::new(),
                in_center: false,
                sync_status: "project_only".to_string(),
                center_skill_id: None,
                last_modified_at,
                content_hash,
            });
            continue;
        }

        // Only check visited set before recursing into namespace dirs
        // to prevent symlink cycles. Skill dirs (above) are leaf nodes and
        // are allowed to alias the same canonical target.

        if !recursive || should_skip_dir(root, &path) {
            continue;
        }

        let canon = match std::fs::canonicalize(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        if !visited.insert(canon) {
            continue;
        }
        read_skills_from_dir_recursive(
            root,
            &path,
            enabled,
            agent,
            agent_display_name,
            skills,
            visited,
            recursive,
        );
    }
}

/// Scan a root directory for projects containing any agent's skills directory.
pub fn scan_projects_in_dir(
    root: &Path,
    max_depth: usize,
    agent_configs: &[AgentSkillConfig],
) -> Vec<String> {
    let mut results = Vec::new();
    scan_recursive(root, 0, max_depth, agent_configs, &mut results);
    results.sort();
    results
}

fn has_any_agent_skills(dir: &Path, agent_configs: &[AgentSkillConfig]) -> bool {
    agent_configs
        .iter()
        .any(|config| dir.join(&config.relative_skills_dir).is_dir())
}

fn scan_recursive(
    dir: &Path,
    depth: usize,
    max_depth: usize,
    agent_configs: &[AgentSkillConfig],
    results: &mut Vec<String>,
) {
    if depth > max_depth {
        return;
    }

    if has_any_agent_skills(dir, agent_configs) {
        results.push(dir.to_string_lossy().to_string());
        return; // don't recurse into subdirectories of a matched project
    }

    if depth == max_depth {
        return;
    }

    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.filter_map(|e| e.ok()) {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            // Skip hidden directories and common non-project dirs
            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if name.starts_with('.')
                || name == "node_modules"
                || name == "target"
                || name == "__pycache__"
            {
                continue;
            }
            scan_recursive(&path, depth + 1, max_depth, agent_configs, results);
        }
    }
}

fn list_files(dir: &Path) -> Vec<String> {
    let mut files = Vec::new();
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.filter_map(|e| e.ok()) {
            let path = entry.path();
            if path.is_file() {
                if let Some(name) = path.file_name() {
                    files.push(name.to_string_lossy().to_string());
                }
            }
        }
    }
    files.sort();
    files
}

#[cfg(test)]
mod tests;