#![allow(
clippy::disallowed_methods,
clippy::disallowed_types,
reason = "Skills command runs synchronously before the tokio runtime is constructed"
)]
use std::{
fmt,
path::{Path, PathBuf},
};
include!(concat!(env!("OUT_DIR"), "/skills_manifest.rs"));
use clap::{ArgAction, Args, Subcommand, ValueEnum};
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum AgentPlatform {
Claude,
Codex,
OpenCode,
Gemini,
Copilot,
Qoder,
Pi,
}
impl AgentPlatform {
#[must_use]
pub fn skills_dir_name(self) -> &'static str {
match self {
AgentPlatform::Claude => ".claude/skills",
AgentPlatform::Codex => ".codex/skills",
AgentPlatform::OpenCode => ".opencode/skills",
AgentPlatform::Gemini => ".gemini/skills",
AgentPlatform::Copilot => ".copilot/skills",
AgentPlatform::Qoder => ".qoder-cn/skills",
AgentPlatform::Pi => ".pi/agent/skills",
}
}
#[must_use]
pub fn global_skills_dir_name(self) -> &'static str {
match self {
AgentPlatform::OpenCode => ".config/opencode/skills",
other => other.skills_dir_name(),
}
}
#[must_use]
pub fn detect() -> Self {
AgentPlatform::Claude
}
}
#[derive(Debug, Subcommand)]
pub enum SkillsCommand {
Suggest(SuggestArgs),
Install(InstallArgs),
List(ListArgs),
Uninstall(UninstallArgs),
Update(SkillsUpdateArgs),
}
#[derive(Debug, Args)]
pub struct SuggestArgs {
#[arg(long, conflicts_with = "stdin")]
pub query: Option<String>,
#[arg(long)]
pub stdin: bool,
#[arg(long, conflicts_with = "live")]
pub response: Option<String>,
#[arg(long)]
pub live: bool,
}
#[derive(Debug, Args)]
pub struct InstallArgs {
#[arg(short = 'g', long, action = ArgAction::SetTrue)]
pub global: bool,
#[arg(long, value_enum)]
pub agent: Option<AgentPlatform>,
#[arg(long = "path")]
pub custom_path: Option<String>,
#[arg(short = 'f', long, action = ArgAction::SetTrue)]
pub force: bool,
#[arg(long, value_enum)]
pub source: Option<SkillSource>,
}
#[derive(Debug, Clone, clap::ValueEnum)]
pub enum SkillSource {
Superpowers,
Mattpocock,
}
#[derive(Debug, Args)]
pub struct ListArgs {
#[arg(short = 'g', long, action = ArgAction::SetTrue)]
pub global: bool,
#[arg(long, value_enum)]
pub agent: Option<AgentPlatform>,
#[arg(long = "path")]
pub custom_path: Option<String>,
}
#[derive(Debug, Args)]
pub struct UninstallArgs {
#[arg(short = 'g', long, action = ArgAction::SetTrue)]
pub global: bool,
#[arg(long, value_enum)]
pub agent: Option<AgentPlatform>,
#[arg(long = "path")]
pub custom_path: Option<String>,
}
#[derive(Debug, Args)]
pub struct SkillsUpdateArgs {
#[arg(short = 'g', long, action = ArgAction::SetTrue)]
pub global: bool,
#[arg(long, value_enum)]
pub agent: Option<AgentPlatform>,
#[arg(long = "path")]
pub custom_path: Option<String>,
}
fn resolve_target_dir(
global: bool,
agent: Option<AgentPlatform>,
custom_path: Option<&str>,
) -> miette::Result<PathBuf> {
if let Some(p) = custom_path {
let safe = gitflow_core::SafePath::new_allow_absolute(p)
.map_err(|e| miette::miette!("无效的 --path 参数: {e}"))?;
return Ok(safe.as_path().to_path_buf());
}
let platform = agent.unwrap_or_else(AgentPlatform::detect);
if global {
let home = dirs::home_dir().ok_or_else(|| miette::miette!("无法确定 HOME 目录"))?;
Ok(home.join(platform.global_skills_dir_name()))
} else {
let repo_root = git_repo_root()?;
Ok(resolve_project_target(&repo_root, platform))
}
}
fn resolve_project_target(repo_root: &std::path::Path, agent: AgentPlatform) -> PathBuf {
repo_root.join(agent.skills_dir_name())
}
fn skills_source_dir() -> PathBuf {
if let Ok(exe) = std::env::current_exe()
&& let Some(exe_dir) = exe.parent()
{
let candidate = exe_dir.join("skills");
if candidate.exists() {
return candidate;
}
if let Some(parent) = exe_dir.parent() {
let candidate = parent.join("skills");
if candidate.exists() {
return candidate;
}
}
}
PathBuf::from("skills")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkillSourceKind {
Superpowers,
Mattpocock,
}
impl fmt::Display for SkillSourceKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Superpowers => write!(f, "superpowers"),
Self::Mattpocock => write!(f, "mattpocock"),
}
}
}
const SUPERPOWERS_PLUGIN_PREFIX: &str = "superpowers@";
const MATTPOCOCK_PLUGIN_PREFIX: &str = "mattpocock-skills@";
const SUPERPOWERS_BARE_SENTINELS: &[&str] = &["brainstorming", "writing-plans"];
const MATTPOCOCK_BARE_SENTINELS: &[&str] = &["to-spec", "grilling"];
fn plugin_source_present(home: &Path, prefix: &str) -> bool {
let path = home.join(".claude/plugins/installed_plugins.json");
let Ok(content) = std::fs::read_to_string(&path) else {
return false;
};
let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&content) else {
return false;
};
parsed
.get("plugins")
.and_then(serde_json::Value::as_object)
.is_some_and(|plugins| plugins.keys().any(|key| key.starts_with(prefix)))
}
fn bare_sentinels_present(home: &Path, sentinels: &[&str]) -> bool {
sentinels
.iter()
.all(|name| home.join(".claude/skills").join(name).is_dir())
}
#[must_use]
pub fn detect_skill_sources(home: &Path) -> Vec<SkillSourceKind> {
let mut found = Vec::new();
if plugin_source_present(home, SUPERPOWERS_PLUGIN_PREFIX)
|| bare_sentinels_present(home, SUPERPOWERS_BARE_SENTINELS)
{
found.push(SkillSourceKind::Superpowers);
}
if plugin_source_present(home, MATTPOCOCK_PLUGIN_PREFIX)
|| bare_sentinels_present(home, MATTPOCOCK_BARE_SENTINELS)
{
found.push(SkillSourceKind::Mattpocock);
}
found
}
fn check_skill_source(platform: AgentPlatform) -> miette::Result<()> {
if !matches!(platform, AgentPlatform::Claude) {
println!("ℹ 非 Claude 平台,跳过技能来源检测");
return Ok(());
}
let home = dirs::home_dir().ok_or_else(|| miette::miette!("无法确定 HOME 目录"))?;
check_skill_source_at(&home)
}
const SKILL_SOURCE_GUIDANCE: &str = "\
⛔ 未检测到任何技能来源,gf-workflow 无法运行。请先安装其一:
· claude plugins install superpowers
· claude plugins install mattpocock-skills
· npx skills@latest add mattpocock/skills
提示:安装 mattpocock-skills / npx skills 需要 Node.js ≥ 22.20.0,先运行 `node --version` 确认。";
fn check_skill_source_at(home: &Path) -> miette::Result<()> {
let sources = detect_skill_sources(home);
if sources.is_empty() {
eprintln!("{SKILL_SOURCE_GUIDANCE}");
return Err(miette::miette!("技能来源缺失,安装中止"));
}
let names: Vec<String> = sources.iter().map(ToString::to_string).collect();
println!("✓ 检测到技能来源: {}", names.join(" + "));
Ok(())
}
pub async fn handle(command: &SkillsCommand, output: crate::OutputFormat) -> miette::Result<()> {
match command {
SkillsCommand::Suggest(args) => super::skills_suggest::handle(args, output).await,
SkillsCommand::Install(args) => install_skills(args),
SkillsCommand::List(args) => list_skills(args),
SkillsCommand::Uninstall(args) => uninstall_skills(args),
SkillsCommand::Update(args) => update_skills(args),
}
}
fn install_skills(args: &InstallArgs) -> miette::Result<()> {
let platform = args.agent.unwrap_or_else(AgentPlatform::detect);
if let Some(source) = &args.source {
return install_external_skills(source, args, platform);
}
check_skill_source(platform)?;
let target = resolve_target_dir(args.global, Some(platform), args.custom_path.as_deref())?;
let source = skills_source_dir();
let has_source = source.exists();
let has_bundled = !SKILLS.is_empty();
if has_source {
let level = if args.global { "全局" } else { "项目级" };
println!("目标: {} ({level})", target.display());
let result = copy_skills_dir(&source, &target, args.force)?;
println!();
println!(
"安装完成: 新增 {} 个,覆盖 {} 个,跳过 {} 个",
result.installed, result.overwritten, result.skipped
);
if !result.failures.is_empty() {
println!(
"⚠ 失败 {} 个: {}",
result.failures.len(),
result.failures.join(", ")
);
return Err(miette::miette!(
"{} 个 skill 安装失败: {}",
result.failures.len(),
result.failures.join(", ")
));
}
} else if has_bundled {
install_skills_bundled(&target, args)?;
} else {
println!("⚠ Skills 源目录未找到,且 binary 未内嵌 skills 数据");
println!(" 请从源码目录运行,或手动指定 --source <skills 目录路径>");
}
Ok(())
}
#[derive(Debug)]
struct CopySkillsResult {
installed: u32,
overwritten: u32,
skipped: u32,
failures: Vec<String>,
}
fn copy_skills_dir(source: &Path, target: &Path, force: bool) -> miette::Result<CopySkillsResult> {
std::fs::create_dir_all(target)
.map_err(|e| miette::miette!("无法创建目标目录 {}: {e}", target.display()))?;
let mut result = CopySkillsResult {
installed: 0,
overwritten: 0,
skipped: 0,
failures: Vec::new(),
};
for entry in std::fs::read_dir(source)
.map_err(|e| miette::miette!("无法读取 skills 源目录 {}: {e}", source.display()))?
{
let entry = entry.map_err(|e| miette::miette!("读取目录项失败: {e}"))?;
let name = entry.file_name();
let name_str = name.to_string_lossy();
if !name_str.starts_with("gf-") {
continue;
}
let dest = target.join(&name);
if dest.exists() {
if force {
if let Err(e) = std::fs::remove_dir_all(&dest) {
result.failures.push(name_str.to_string());
eprintln!("⚠ 失败: {name_str} — 无法删除旧版本: {e}");
continue;
}
if let Err(e) = copy_dir_all(&entry.path(), &dest) {
result.failures.push(name_str.to_string());
eprintln!("⚠ 失败: {name_str} — 复制失败: {e}");
continue;
}
println!("♻ 已覆盖: {name_str}");
result.overwritten += 1;
} else {
eprintln!("⚠ 跳过已存在: {name_str}");
result.skipped += 1;
}
continue;
}
if let Err(e) = copy_dir_all(&entry.path(), &dest) {
result.failures.push(name_str.to_string());
eprintln!("⚠ 失败: {name_str} — 复制失败: {e}");
continue;
}
println!("✅ 已安装: {name_str}");
result.installed += 1;
}
Ok(result)
}
pub fn update_skills(args: &SkillsUpdateArgs) -> miette::Result<()> {
let platform = args.agent.unwrap_or_else(AgentPlatform::detect);
let target = resolve_target_dir(args.global, Some(platform), args.custom_path.as_deref())?;
let source = skills_source_dir();
let has_source = source.exists();
let has_bundled = !SKILLS.is_empty();
if !target.exists() {
println!("(未安装任何 skills)");
println!("目录: {}", target.display());
return Ok(());
}
if has_source {
let result = copy_skills_dir(&source, &target, true)?;
println!();
println!(
"✅ Skills 已更新: 覆盖 {} 个,新增 {} 个,跳过 {} 个",
result.overwritten, result.installed, result.skipped
);
if !result.failures.is_empty() {
println!(
"⚠ 失败 {} 个: {}",
result.failures.len(),
result.failures.join(", ")
);
return Err(miette::miette!(
"{} 个 skill 更新失败: {}",
result.failures.len(),
result.failures.join(", ")
));
}
} else if has_bundled {
let install_args = InstallArgs {
global: args.global,
agent: args.agent,
custom_path: args.custom_path.clone(),
force: true,
source: None,
};
install_skills_bundled(&target, &install_args)?;
} else {
println!("⚠ Skills 源目录未找到,且 binary 未内嵌 skills 数据");
println!(" 请从源码目录运行,或手动指定 --path <skills 目录路径>");
}
Ok(())
}
fn install_skills_bundled(target: &std::path::Path, args: &InstallArgs) -> miette::Result<()> {
std::fs::create_dir_all(target).map_err(|e| miette::miette!("无法创建目标目录: {e}"))?;
println!(
"目标: {} ({})",
target.display(),
if args.global { "全局" } else { "项目级" }
);
println!("使用内嵌 skills 数据({} 个文件)", SKILLS.len());
let mut skill_dirs: std::collections::HashMap<&str, Vec<(&str, &[u8])>> =
std::collections::HashMap::new();
for (path, data) in SKILLS {
let parts: Vec<&str> = path.split('/').collect();
if parts.len() >= 2
&& parts.first().is_some_and(|f| f.starts_with("gf-"))
&& let Some(&first) = parts.first()
{
let relative = &path[first.len() + 1..];
skill_dirs.entry(first).or_default().push((relative, *data));
}
}
let mut installed = 0u32;
let mut skipped = 0u32;
let mut overwritten = 0u32;
for (skill_name, files) in &skill_dirs {
let dest = target.join(skill_name);
install_single_skill_bundled(
&dest,
files,
args,
&mut installed,
&mut skipped,
&mut overwritten,
)?;
}
println!();
println!("安装完成: 新增 {installed} 个,覆盖 {overwritten} 个,跳过 {skipped} 个");
Ok(())
}
fn install_single_skill_bundled(
dest: &std::path::Path,
files: &[(&str, &[u8])],
args: &InstallArgs,
installed: &mut u32,
skipped: &mut u32,
overwritten: &mut u32,
) -> miette::Result<()> {
let is_overwrite = dest.exists();
if is_overwrite {
if args.force {
std::fs::remove_dir_all(dest).map_err(|e| miette::miette!("无法删除: {e}"))?;
} else {
eprintln!("⚠ 跳过已存在: {}", dest.display());
*skipped += 1;
return Ok(());
}
}
for (rel_path, data) in files {
let file_path = dest.join(rel_path);
if let Some(parent) = file_path.parent() {
std::fs::create_dir_all(parent).map_err(|e| miette::miette!("创建目录失败: {e}"))?;
}
std::fs::write(&file_path, data).map_err(|e| miette::miette!("写入失败: {e}"))?;
}
if is_overwrite && args.force {
println!("♻ 已覆盖: {}", dest.display());
*overwritten += 1;
} else {
println!("✅ 已安装: {}", dest.display());
*installed += 1;
}
Ok(())
}
#[allow(
clippy::disallowed_methods,
reason = "Sync process invocation for git clone during skill installation"
)]
fn install_external_skills(
source: &SkillSource,
args: &InstallArgs,
platform: AgentPlatform,
) -> miette::Result<()> {
let target = resolve_target_dir(args.global, Some(platform), args.custom_path.as_deref())?;
let (repo_url, skills_subdir) = match source {
SkillSource::Superpowers => ("https://github.com/anthropics/superpowers.git", "skills"),
SkillSource::Mattpocock => ("https://github.com/mattpocock/skills.git", "skills"),
};
println!("📦 从 {repo_url} 克隆技能集...");
let temp_dir = tempfile::tempdir().map_err(|e| miette::miette!("创建临时目录失败: {e}"))?;
let clone_path = temp_dir.path().join("repo");
let output = std::process::Command::new("git")
.args([
"clone",
"--depth",
"1",
"--filter=blob:none",
repo_url,
&clone_path.to_string_lossy(),
])
.output()
.map_err(|e| miette::miette!("git clone 失败: {e}\n请确保已安装 git"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(miette::miette!("git clone 失败:\n{}", stderr.trim()));
}
println!("✅ 克隆完成,正在提取 skills...");
let skills_source = clone_path.join(skills_subdir);
if !skills_source.exists() {
return Err(miette::miette!(
"未找到 skills 目录: {}\n仓库结构可能已变更",
skills_source.display()
));
}
let level = if args.global { "全局" } else { "项目级" };
println!("目标: {} ({})", target.display(), level);
let result = copy_skills_dir(&skills_source, &target, args.force)?;
drop(temp_dir);
println!();
println!(
"安装完成: 新增 {} 个,覆盖 {} 个,跳过 {} 个",
result.installed, result.overwritten, result.skipped
);
if !result.failures.is_empty() {
println!(
"⚠ 失败 {} 个: {}",
result.failures.len(),
result.failures.join(", ")
);
return Err(miette::miette!(
"{} 个 skill 安装失败: {}",
result.failures.len(),
result.failures.join(", ")
));
}
Ok(())
}
fn git_repo_root() -> miette::Result<std::path::PathBuf> {
let output = std::process::Command::new("git")
.args(["rev-parse", "--show-toplevel"])
.output();
match output {
Ok(out) if out.status.success() => Ok(std::path::PathBuf::from(
String::from_utf8_lossy(&out.stdout).trim(),
)),
_ => std::env::current_dir().map_err(|e| miette::miette!("无法获取当前目录: {e}")),
}
}
fn list_skills(args: &ListArgs) -> miette::Result<()> {
let target = resolve_target_dir(args.global, args.agent, args.custom_path.as_deref())?;
if !target.exists() {
println!("(未安装任何 skills)");
println!("目录: {}", target.display());
return Ok(());
}
println!("目录: {}", target.display());
println!();
let mut found = 0u32;
for entry in std::fs::read_dir(&target)
.map_err(|e| miette::miette!("读取目录失败 {}: {e}", target.display()))?
{
let entry = entry.map_err(|e| miette::miette!("读取目录项失败: {e}"))?;
let name_str = entry.file_name().to_string_lossy().into_owned();
if name_str.starts_with("gf-") {
println!(" {name_str}");
found += 1;
}
}
if found == 0 {
println!("(未安装任何 gf skills)");
} else {
println!();
println!("共 {found} 个 skills");
}
Ok(())
}
fn uninstall_skills(args: &UninstallArgs) -> miette::Result<()> {
let platform = args.agent.unwrap_or_else(AgentPlatform::detect);
let target = resolve_target_dir(args.global, Some(platform), args.custom_path.as_deref())?;
if !target.exists() {
println!("(未安装任何 skills)");
println!("目录: {}", target.display());
return Ok(());
}
println!("目录: {}", target.display());
println!();
let mut removed = 0u32;
for entry in std::fs::read_dir(&target)
.map_err(|e| miette::miette!("读取目录失败 {}: {e}", target.display()))?
{
let entry = entry.map_err(|e| miette::miette!("读取目录项失败: {e}"))?;
let name_str = entry.file_name().to_string_lossy().into_owned();
if name_str.starts_with("gf-") {
let path = entry.path();
if path.is_dir() {
std::fs::remove_dir_all(&path)
.map_err(|e| miette::miette!("删除 {} 失败: {e}", path.display()))?;
} else {
std::fs::remove_file(&path)
.map_err(|e| miette::miette!("删除 {} 失败: {e}", path.display()))?;
}
println!("✅ 已卸载: {name_str}");
removed += 1;
}
}
if removed == 0 {
println!("(未安装任何 gf skills)");
} else {
println!();
println!("已卸载 {removed} 个 skills");
}
Ok(())
}
fn copy_dir_all(src: &PathBuf, dst: &PathBuf) -> std::io::Result<()> {
std::fs::create_dir_all(dst)?;
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let ty = entry.file_type()?;
let dest_path = dst.join(entry.file_name());
if ty.is_dir() {
copy_dir_all(&entry.path(), &dest_path)?;
} else {
std::fs::copy(entry.path(), &dest_path)?;
}
}
Ok(())
}
pub(crate) fn confirm(prompt: &str, default: bool) -> miette::Result<bool> {
let stdin = std::io::stdin();
let mut reader = stdin.lock();
confirm_with_reader(prompt, default, &mut reader)
}
#[allow(
dead_code,
reason = "called by `confirm`; direct calls from tests for isolation"
)]
fn confirm_with_reader(
prompt: &str,
default: bool,
reader: &mut impl std::io::BufRead,
) -> miette::Result<bool> {
use std::io::Write;
let hint = if default { "[Y/n]" } else { "[y/N]" };
print!("{prompt} {hint} ");
let _ = std::io::stdout().flush();
for _ in 0..3 {
let mut line = String::new();
let bytes_read = reader
.read_line(&mut line)
.map_err(|e| miette::miette!("读取输入失败: {e}"))?;
if bytes_read == 0 {
return Ok(default);
}
match line.trim().to_lowercase().as_str() {
"" => return Ok(default),
"y" | "yes" => return Ok(true),
"n" | "no" => return Ok(false),
_ => {
print!("请输入 y 或 n: ");
let _ = std::io::stdout().flush();
}
}
}
Ok(default)
}
#[cfg(test)]
#[allow(
clippy::expect_used,
clippy::unwrap_used,
clippy::panic,
reason = "允许在测试中使用 expect/unwrap/panic"
)]
mod tests {
use super::*;
#[test]
fn test_agent_platform_claude_dir() {
assert_eq!(AgentPlatform::Claude.skills_dir_name(), ".claude/skills");
}
#[test]
fn test_agent_platform_codex_dir() {
assert_eq!(AgentPlatform::Codex.skills_dir_name(), ".codex/skills");
}
#[test]
fn test_agent_platform_opencode_dir() {
assert_eq!(
AgentPlatform::OpenCode.skills_dir_name(),
".opencode/skills"
);
}
#[test]
fn test_agent_platform_qoder_dir() {
assert_eq!(AgentPlatform::Qoder.skills_dir_name(), ".qoder-cn/skills");
}
#[test]
fn test_agent_platform_pi_dir() {
assert_eq!(AgentPlatform::Pi.skills_dir_name(), ".pi/agent/skills");
}
#[test]
fn test_agent_platform_gemini_dir() {
assert_eq!(AgentPlatform::Gemini.skills_dir_name(), ".gemini/skills");
}
#[test]
fn test_agent_platform_copilot_dir() {
assert_eq!(AgentPlatform::Copilot.skills_dir_name(), ".copilot/skills");
}
#[test]
fn test_agent_detect_always_returns_claude() {
assert_eq!(AgentPlatform::detect(), AgentPlatform::Claude);
}
#[test]
fn test_resolve_global_target_claude() {
let dir = resolve_target_dir(true, Some(AgentPlatform::Claude), None).expect("resolve");
assert!(dir.ends_with(".claude/skills"));
}
#[test]
fn test_resolve_global_target_codex() {
let dir = resolve_target_dir(true, Some(AgentPlatform::Codex), None).expect("resolve");
assert!(dir.ends_with(".codex/skills"));
}
#[test]
fn test_resolve_global_target_gemini() {
let dir = resolve_target_dir(true, Some(AgentPlatform::Gemini), None).expect("resolve");
assert!(dir.ends_with(".gemini/skills"));
}
#[test]
fn test_resolve_global_target_qoder() {
let dir = resolve_target_dir(true, Some(AgentPlatform::Qoder), None).expect("resolve");
assert!(dir.ends_with(".qoder-cn/skills"));
}
#[test]
fn test_resolve_global_target_opencode_xdg() {
let dir = resolve_target_dir(true, Some(AgentPlatform::OpenCode), None).expect("resolve");
assert!(
dir.ends_with(".config/opencode/skills"),
"OpenCode global must use XDG path, got {}",
dir.display()
);
}
#[test]
fn test_resolve_global_target_pi() {
let dir = resolve_target_dir(true, Some(AgentPlatform::Pi), None).expect("resolve");
assert!(dir.ends_with(".pi/agent/skills"));
}
#[test]
fn test_resolve_global_target_copilot() {
let dir = resolve_target_dir(true, Some(AgentPlatform::Copilot), None).expect("resolve");
assert!(dir.ends_with(".copilot/skills"));
}
#[test]
fn test_global_skills_dir_name_defaults_to_skills_dir() {
assert_eq!(
AgentPlatform::Claude.global_skills_dir_name(),
AgentPlatform::Claude.skills_dir_name()
);
assert_eq!(
AgentPlatform::Pi.global_skills_dir_name(),
".pi/agent/skills"
);
}
#[test]
fn test_global_skills_dir_name_opencode_xdg() {
assert_eq!(
AgentPlatform::OpenCode.global_skills_dir_name(),
".config/opencode/skills"
);
assert_ne!(
AgentPlatform::OpenCode.global_skills_dir_name(),
AgentPlatform::OpenCode.skills_dir_name()
);
}
#[test]
fn test_resolve_project_target_respects_agent() {
let repo = PathBuf::from("/tmp/test-repo-skills");
let dir = resolve_project_target(&repo, AgentPlatform::Codex);
assert!(
dir.ends_with(".codex/skills"),
"project-level install must respect --agent, got {}",
dir.display()
);
let dir_gemini = resolve_project_target(&repo, AgentPlatform::Gemini);
assert!(dir_gemini.ends_with(".gemini/skills"));
let dir_qoder = resolve_project_target(&repo, AgentPlatform::Qoder);
assert!(dir_qoder.ends_with(".qoder-cn/skills"));
}
#[test]
fn test_resolve_custom_path_overrides_all() {
let dir = resolve_target_dir(false, Some(AgentPlatform::Claude), Some("/tmp/my-skills"))
.expect("resolve");
assert_eq!(dir, PathBuf::from("/tmp/my-skills"));
}
#[test]
fn test_resolve_custom_path_rejects_parent_dir_traversal() {
let result = resolve_target_dir(
false,
Some(AgentPlatform::Claude),
Some("/tmp/my-skills/../../etc"),
);
assert!(result.is_err());
}
#[test]
fn test_resolve_custom_path_rejects_null_byte() {
let result = resolve_target_dir(false, Some(AgentPlatform::Claude), Some("/tmp/x\0y"));
assert!(result.is_err());
}
#[test]
fn test_skills_source_dir_is_valid_path() {
let dir = skills_source_dir();
assert!(dir.ends_with("skills"));
}
#[test]
fn test_should_count_overwritten_in_bundled_path() {
let tmp = tempfile::tempdir().expect("create temp dir");
let dest_fresh = tmp.path().join("fresh-skill");
let args = InstallArgs {
agent: Some(AgentPlatform::Claude),
global: false,
force: true,
custom_path: None,
source: None,
};
let files: &[(&str, &[u8])] = &[("test.md", b"# Test Skill")];
let mut installed = 0u32;
let mut skipped = 0u32;
let mut overwritten = 0u32;
install_single_skill_bundled(
&dest_fresh,
files,
&args,
&mut installed,
&mut skipped,
&mut overwritten,
)
.expect("install should succeed");
assert_eq!(
overwritten, 0,
"fresh install with force=true should NOT count as overwritten"
);
assert_eq!(installed, 1, "fresh install should count as installed");
assert_eq!(skipped, 0, "fresh install should not count as skipped");
let mut installed = 0u32;
let mut skipped = 0u32;
let mut overwritten = 0u32;
let dest_existing = tmp.path().join("existing-skill");
std::fs::create_dir_all(&dest_existing).expect("create dest dir");
std::fs::write(dest_existing.join("old.txt"), b"old data").expect("write old file");
install_single_skill_bundled(
&dest_existing,
files,
&args,
&mut installed,
&mut skipped,
&mut overwritten,
)
.expect("install should succeed");
assert_eq!(
overwritten, 1,
"overwrite of existing dir with force=true should increment overwritten"
);
assert_eq!(installed, 0, "overwrite should not count as fresh install");
assert_eq!(
skipped, 0,
"overwrite with force should not count as skipped"
);
}
#[test]
fn test_should_return_default_on_empty_input() {
let input = b"\n";
let result = confirm_with_reader("Continue?", true, &mut &input[..]).expect("confirm");
assert!(result, "empty input should return default=true");
let result = confirm_with_reader("Continue?", false, &mut &input[..]).expect("confirm");
assert!(!result, "empty input should return default=false");
}
#[test]
fn test_should_accept_yes_variants() {
for answer in &[b"y\n" as &[u8], b"Y\n", b"yes\n", b"YES\n"] {
let result = confirm_with_reader("Continue?", false, &mut &**answer).expect("confirm");
assert!(result, "input {answer:?} should be accepted as yes");
}
}
#[test]
fn test_should_accept_no_variants() {
for answer in &[b"n\n" as &[u8], b"N\n", b"no\n", b"NO\n"] {
let result = confirm_with_reader("Continue?", true, &mut &**answer).expect("confirm");
assert!(!result, "input {answer:?} should be accepted as no");
}
}
#[test]
fn test_should_return_default_on_eof() {
let input: &[u8] = b"";
let result = confirm_with_reader("Continue?", true, &mut &input[..]).expect("confirm");
assert!(result, "EOF should return default=true");
}
fn seed_plugin_registry(home: &std::path::Path, plugin_keys: &[&str]) {
let dir = home.join(".claude/plugins");
std::fs::create_dir_all(&dir).expect("create plugins dir");
let mut plugins = serde_json::Map::new();
for key in plugin_keys {
plugins.insert((*key).to_string(), serde_json::json!([]));
}
let content = serde_json::json!({ "version": 2, "plugins": plugins });
std::fs::write(
dir.join("installed_plugins.json"),
serde_json::to_string(&content).expect("serialize"),
)
.expect("write registry");
}
fn seed_bare_skills(home: &std::path::Path, names: &[&str]) {
for name in names {
let dir = home.join(".claude/skills").join(name);
std::fs::create_dir_all(&dir).expect("create skill dir");
std::fs::write(dir.join("SKILL.md"), "---\nname: x\n---\n").expect("write SKILL.md");
}
}
#[test]
fn test_detect_plugin_superpowers() {
let tmp = tempfile::tempdir().expect("temp dir");
seed_plugin_registry(tmp.path(), &["superpowers@claude-plugins-official"]);
let found = detect_skill_sources(tmp.path());
assert_eq!(found, vec![SkillSourceKind::Superpowers]);
}
#[test]
fn test_detect_plugin_mattpocock() {
let tmp = tempfile::tempdir().expect("temp dir");
seed_plugin_registry(tmp.path(), &["mattpocock-skills@mattpocock"]);
let found = detect_skill_sources(tmp.path());
assert_eq!(found, vec![SkillSourceKind::Mattpocock]);
}
#[test]
fn test_detect_bare_mattpocock_requires_double_sentinel() {
let tmp = tempfile::tempdir().expect("temp dir");
seed_bare_skills(tmp.path(), &["to-spec", "grilling"]);
let found = detect_skill_sources(tmp.path());
assert_eq!(found, vec![SkillSourceKind::Mattpocock]);
}
#[test]
fn test_detect_bare_partial_sentinel_is_not_detected() {
let tmp = tempfile::tempdir().expect("temp dir");
seed_bare_skills(tmp.path(), &["to-spec"]);
assert!(
detect_skill_sources(tmp.path()).is_empty(),
"partial sentinel hit must not be detected"
);
}
#[test]
fn test_detect_bare_superpowers_requires_double_sentinel() {
let tmp = tempfile::tempdir().expect("temp dir");
seed_bare_skills(tmp.path(), &["brainstorming", "writing-plans"]);
let found = detect_skill_sources(tmp.path());
assert_eq!(found, vec![SkillSourceKind::Superpowers]);
}
#[test]
fn test_detect_empty_home_finds_nothing() {
let tmp = tempfile::tempdir().expect("temp dir");
assert!(detect_skill_sources(tmp.path()).is_empty());
}
#[test]
fn test_detect_both_sources_when_both_installed() {
let tmp = tempfile::tempdir().expect("temp dir");
seed_plugin_registry(
tmp.path(),
&[
"superpowers@claude-plugins-official",
"mattpocock-skills@mattpocock",
],
);
let found = detect_skill_sources(tmp.path());
assert_eq!(found.len(), 2, "both sources must be reported: {found:?}");
}
#[test]
fn test_detect_malformed_registry_falls_back_to_bare() {
let tmp = tempfile::tempdir().expect("temp dir");
let dir = tmp.path().join(".claude/plugins");
std::fs::create_dir_all(&dir).expect("create dir");
std::fs::write(dir.join("installed_plugins.json"), "not json").expect("write");
seed_bare_skills(tmp.path(), &["to-spec", "grilling"]);
let found = detect_skill_sources(tmp.path());
assert_eq!(found, vec![SkillSourceKind::Mattpocock]);
}
#[test]
fn test_install_check_blocks_when_no_skill_source() {
let tmp = tempfile::tempdir().expect("temp dir");
let result = check_skill_source_at(tmp.path());
let err = result.expect_err("must block when no source installed");
assert!(
err.to_string().contains("技能来源缺失"),
"error must state missing source: {err}"
);
}
#[test]
fn test_should_include_node_version_hint_in_skill_source_guidance() {
assert!(
SKILL_SOURCE_GUIDANCE.contains("Node.js"),
"guidance must mention Node.js: {SKILL_SOURCE_GUIDANCE}"
);
assert!(
SKILL_SOURCE_GUIDANCE.contains("22.20.0"),
"guidance must state the Node.js minimum version 22.20.0: {SKILL_SOURCE_GUIDANCE}"
);
}
#[test]
fn test_install_check_passes_when_source_detected() {
let tmp = tempfile::tempdir().expect("temp dir");
seed_plugin_registry(tmp.path(), &["superpowers@claude-plugins-official"]);
check_skill_source_at(tmp.path()).expect("must pass with source present");
}
#[test]
fn test_install_check_skips_non_claude_platform() {
check_skill_source(AgentPlatform::Codex).expect("non-claude must skip check");
}
fn seed_source(tmp: &tempfile::TempDir, names: &[&str]) {
for name in names {
let dir = tmp.path().join("source").join(name);
std::fs::create_dir_all(&dir).expect("create source skill dir");
std::fs::write(dir.join("SKILL.md"), format!("# {name}\n")).expect("write SKILL.md");
}
std::fs::create_dir_all(tmp.path().join("source/not-a-skill")).expect("create non-gf dir");
}
fn seed_target(tmp: &tempfile::TempDir, names: &[&str]) {
for name in names {
let dir = tmp.path().join("target").join(name);
std::fs::create_dir_all(&dir).expect("create target skill dir");
std::fs::write(dir.join("SKILL.md"), "old\n").expect("write old content");
}
}
#[test]
fn test_copy_skills_dir_overwrites_existing() {
let tmp = tempfile::tempdir().expect("tempdir");
seed_source(&tmp, &["gf-alpha"]);
seed_target(&tmp, &["gf-alpha"]);
let result = copy_skills_dir(&tmp.path().join("source"), &tmp.path().join("target"), true)
.expect("copy");
assert_eq!(result.installed, 0);
assert_eq!(result.overwritten, 1);
assert_eq!(result.skipped, 0);
assert!(result.failures.is_empty());
let content = std::fs::read_to_string(tmp.path().join("target/gf-alpha/SKILL.md"))
.expect("read updated");
assert_eq!(content, "# gf-alpha\n", "content must be replaced");
}
#[test]
fn test_copy_skills_dir_installs_new() {
let tmp = tempfile::tempdir().expect("tempdir");
seed_source(&tmp, &["gf-alpha", "gf-beta"]);
seed_target(&tmp, &["gf-alpha"]);
let result = copy_skills_dir(&tmp.path().join("source"), &tmp.path().join("target"), true)
.expect("copy");
assert_eq!(result.installed, 1, "gf-beta must be newly installed");
assert_eq!(result.overwritten, 1);
assert!(result.failures.is_empty());
assert!(tmp.path().join("target/gf-beta/SKILL.md").exists());
}
#[test]
fn test_copy_skills_dir_preserves_other_dirs() {
let tmp = tempfile::tempdir().expect("tempdir");
seed_source(&tmp, &["gf-alpha"]);
seed_target(&tmp, &["gf-alpha"]);
let other = tmp.path().join("target/not-a-skill");
std::fs::create_dir_all(&other).expect("create other dir");
std::fs::write(other.join("README.md"), "keep me\n").expect("write other dir");
copy_skills_dir(&tmp.path().join("source"), &tmp.path().join("target"), true)
.expect("copy");
assert!(
other.join("README.md").exists(),
"non-gf-* dirs must be left untouched"
);
}
#[test]
fn test_copy_skills_dir_collects_failures_and_continues() {
let tmp = tempfile::tempdir().expect("tempdir");
seed_source(&tmp, &["gf-alpha", "gf-beta", "gf-gamma"]);
std::fs::create_dir_all(tmp.path().join("target")).expect("create target");
std::fs::write(tmp.path().join("target/gf-beta"), "i am a file, not a dir")
.expect("write file where skill dir should be");
let result = copy_skills_dir(&tmp.path().join("source"), &tmp.path().join("target"), true)
.expect("copy_skills_dir must not abort on individual skill failure");
assert!(
tmp.path().join("target/gf-alpha/SKILL.md").exists(),
"gf-alpha must be installed despite gf-beta failure"
);
assert!(
tmp.path().join("target/gf-gamma/SKILL.md").exists(),
"gf-gamma must be installed despite gf-beta failure"
);
assert_eq!(result.failures.len(), 1, "exactly one failure");
assert_eq!(result.failures[0], "gf-beta");
assert_eq!(result.installed, 2);
assert_eq!(result.overwritten, 0);
assert_eq!(result.skipped, 0);
}
#[test]
fn test_update_skills_args_parse() {
use clap::Parser;
#[derive(Debug, Parser)]
struct TestCli {
#[command(subcommand)]
cmd: TestCmd,
}
#[derive(Debug, Subcommand)]
enum TestCmd {
Update(SkillsUpdateArgs),
}
let cli = TestCli::parse_from([
"test", "update", "-g", "--agent", "codex", "--path", "/tmp/x",
]);
let TestCmd::Update(args) = cli.cmd;
assert!(args.global);
assert_eq!(args.agent, Some(AgentPlatform::Codex));
assert_eq!(args.custom_path.as_deref(), Some("/tmp/x"));
}
}