Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

refactor(host-core): move capability test modules beside their sources

vastsaea7effa5e8a3
diff --git a/apps/desktop/test/agent-capability-settings.test.mjs b/apps/desktop/test/agent-capability-settings.test.mjs
index 98952271a..3187a11a6 100644
--- a/apps/desktop/test/agent-capability-settings.test.mjs
+++ b/apps/desktop/test/agent-capability-settings.test.mjs
@@ -314,7 +314,13 @@ test("capability state stays outside capability files and active merge shadows d
const skillRegistry = read("../../../crates/host-core/src/user_skills.rs");
assert.match(capabilities, /agent-capabilities/);
assert.match(mcpRegistry, /\.agents\/servers/);
- assert.match(skillRegistry, /\.agents\/skills/);
+ // `.agents/skills` was only ever spelled in this file's own Rust test
+ // fixtures, which now live beside the module they cover
+ // (crates/host-core/src/user_skills/tests.rs). Pin the production pair
+ // instead: the skills leaf the registry resolves, and the `.agents` root
+ // capability_dir resolves it under.
+ assert.match(capabilities, /pub const AGENTS_DIR: &str = "\.agents";/);
+ assert.match(skillRegistry, /capability_dir\([^;]*"skills"/);
assert.match(mcpRegistry, /existing\.id != record\.id/);
assert.match(mcpRegistry, /if record\.enabled \{/);
assert.match(skillRegistry, /existing\.id != record\.id/);
diff --git a/crates/host-core/src/agent_capabilities.rs b/crates/host-core/src/agent_capabilities.rs
index bb3fcc5f6..476c357a3 100644
--- a/crates/host-core/src/agent_capabilities.rs
+++ b/crates/host-core/src/agent_capabilities.rs
@@ -756,361 +756,4 @@ pub(crate) mod test_support {
}
#[cfg(test)]
-mod tests {
- use super::*;
- use tempfile::tempdir;
-
- #[test]
- fn front_matter_and_body_round_trip() {
- let (fields, body) =
- parse_front_matter("---\nname: Review\ndescription: Check code\n---\n\nDo it.\n");
- assert_eq!(fields.get("name").map(String::as_str), Some("Review"));
- assert_eq!(
- fields.get("description").map(String::as_str),
- Some("Check code")
- );
- assert_eq!(body, "Do it.");
- }
-
- #[test]
- fn front_matter_reads_folded_yaml_descriptions() {
- let raw = "---\nname: find-skills\ndescription: >\n Discover skills when asked\n how to do X.\n---\n\nFollow the steps.\n";
- let (fields, body) = parse_front_matter(raw);
- assert_eq!(fields.get("name").map(String::as_str), Some("find-skills"));
- assert_eq!(
- fields.get("description").map(String::as_str),
- Some("Discover skills when asked how to do X.")
- );
- assert_eq!(body, "Follow the steps.");
- }
-
- #[test]
- fn capability_id_falls_back_to_skill_directory_then_hash() {
- let dir_skill = Path::new("/tmp/code-review/SKILL.md");
- assert_eq!(capability_id("代码审查", dir_skill, 64), "code-review");
- assert_eq!(path_stem_for_id(dir_skill), "code-review");
-
- let hashed = capability_id("代码审查", Path::new("/tmp/代码审查.md"), 64);
- assert!(hashed.starts_with("skill-"));
- assert!(valid_capability_id(&hashed, 64));
- assert_eq!(
- hashed,
- capability_id("代码审查", Path::new("/elsewhere/代码审查.md"), 64)
- );
- assert_eq!(
- capability_id("代码审查", Path::new("/Users/me/Downloads/SKILL.md"), 64),
- hashed
- );
- assert_ne!(
- capability_id("代码审查", Path::new("/Users/me/Downloads/SKILL.md"), 64),
- "downloads"
- );
- }
-
- #[test]
- fn state_defaults_on_and_is_project_specific() {
- let dir = tempdir().unwrap();
- let mut state = CapabilityState::new(dir.path(), "skills");
- assert!(state.enabled("skills", CapabilityLevel::Global, "review", Some("/a")));
- state
- .set_enabled(
- "skills",
- CapabilityLevel::Global,
- "review",
- Some("/a"),
- false,
- )
- .unwrap();
- assert!(!state.enabled("skills", CapabilityLevel::Global, "review", Some("/a")));
- assert!(state.enabled("skills", CapabilityLevel::Global, "review", Some("/b")));
- let reopened = CapabilityState::new(dir.path(), "skills");
- assert!(!reopened.enabled("skills", CapabilityLevel::Global, "review", Some("/a")));
-
- let mut orphaned = reopened;
- orphaned
- .prune(
- "skills",
- CapabilityLevel::Global,
- None,
- &std::collections::HashSet::new(),
- )
- .unwrap();
- assert!(orphaned.enabled("skills", CapabilityLevel::Global, "review", Some("/a")));
- }
-
- #[test]
- fn suffix_keeps_the_preferred_id_when_it_is_free() {
- let taken = HashSet::new();
- assert_eq!(
- suffixed_capability_id("review", &taken, 64),
- Some(("review".to_string(), 0))
- );
- }
-
- #[test]
- fn suffix_walks_past_every_taken_id_and_stays_inside_the_budget() {
- let taken: HashSet<String> = ["review".to_string(), "review-2".to_string()]
- .into_iter()
- .collect();
- assert_eq!(
- suffixed_capability_id("review", &taken, 64),
- Some(("review-3".to_string(), 3))
- );
-
- // A 64-character id has no room for the suffix, so the base is trimmed
- // rather than the candidate growing past what the id validator accepts.
- let long = "a".repeat(64);
- let taken: HashSet<String> = [long.clone()].into_iter().collect();
- let (candidate, ordinal) = suffixed_capability_id(&long, &taken, 64).unwrap();
- assert_eq!(ordinal, 2);
- assert_eq!(candidate.len(), 64);
- assert!(valid_capability_id(&candidate, 64));
- }
-
- #[test]
- fn suffix_reports_exhaustion_instead_of_reusing_a_taken_id() {
- let taken: HashSet<String> = ["review".to_string()].into_iter().collect();
- // `max_chars` below the suffix length leaves nothing to build on.
- assert_eq!(suffixed_capability_id("review", &taken, 2), None);
- }
-
- #[test]
- fn display_name_suffix_is_case_insensitive_like_shadowing() {
- let taken: HashSet<String> = ["review".to_string()].into_iter().collect();
- assert_eq!(suffixed_display_name("Review", &taken, 120), "Review (2)");
- assert_eq!(suffixed_display_name("Files", &taken, 120), "Files");
- }
-
- #[test]
- fn suffix_ignores_id_case_so_a_case_insensitive_volume_keeps_both_files() {
- // Callers pass the taken set lowercased, mirroring the filesystem, so
- // `MyServer` must not be treated as free next to `myserver`.
- let taken: HashSet<String> = ["myserver".to_string()].into_iter().collect();
- assert_eq!(
- suffixed_capability_id("MyServer", &taken, 64),
- Some(("MyServer-2".to_string(), 2))
- );
- }
-
- #[test]
- fn display_name_suffix_stays_distinct_at_the_character_budget() {
- let full = "a".repeat(120);
- let taken: HashSet<String> = [full.clone()].into_iter().collect();
- let renamed = suffixed_display_name(&full, &taken, 120);
- assert_ne!(renamed, full);
- assert!(renamed.chars().count() <= 120);
- assert_eq!(renamed, format!("{} (2)", "a".repeat(116)));
-
- // Each ordinal still yields its own candidate once the earlier ones
- // are taken, instead of collapsing onto the truncated base name.
- let taken: HashSet<String> = [full.clone(), renamed.clone()]
- .into_iter()
- .map(|value| value.to_lowercase())
- .collect();
- let third = suffixed_display_name(&full, &taken, 120);
- assert_ne!(third, full);
- assert_ne!(third, renamed);
- assert!(third.chars().count() <= 120);
-
- // The suffix follows a base that was cut mid-word without a stray
- // space, and ordinal 1 is the plain name.
- assert_eq!(display_name_candidate("Review", 1, 120), "Review");
- assert_eq!(display_name_candidate("Review", 2, 8), "Revi (2)");
- assert_eq!(display_name_candidate("Review more", 2, 11), "Review (2)");
- }
-
- #[test]
- fn project_target_requires_a_project_path() {
- assert!(CapabilityTarget::new(CapabilityLevel::Project, None).is_err());
- assert!(CapabilityTarget::new(CapabilityLevel::Project, Some(" ")).is_err());
- assert!(CapabilityTarget::new(CapabilityLevel::Global, None).is_ok());
- assert_eq!(
- CapabilityTarget::new(CapabilityLevel::Project, Some("/repo/"))
- .unwrap()
- .project_path
- .as_deref(),
- Some("/repo")
- );
- }
-
- #[test]
- fn global_targets_share_one_directory_whatever_project_context_they_carry() {
- let plain = CapabilityTarget::new(CapabilityLevel::Global, None).unwrap();
- let contextual = CapabilityTarget::new(CapabilityLevel::Global, Some("/repo")).unwrap();
- assert!(plain.same_directory(&contextual));
- let project = CapabilityTarget::new(CapabilityLevel::Project, Some("/repo")).unwrap();
- assert!(!plain.same_directory(&project));
- let other = CapabilityTarget::new(CapabilityLevel::Project, Some("/other")).unwrap();
- assert!(!project.same_directory(&other));
- }
-
- #[test]
- fn global_root_follows_the_environment_override() {
- let dir = tempdir().unwrap();
- test_support::with_global_agents(dir.path(), || {
- assert_eq!(global_agents_dir(), dir.path());
- assert_eq!(
- capability_dir(CapabilityLevel::Global, None, "skills").unwrap(),
- dir.path().join("skills")
- );
- });
- }
-
- #[test]
- fn forget_drops_every_project_override_for_one_document() {
- let dir = tempdir().unwrap();
- let mut state = CapabilityState::new(dir.path(), "skills");
- state
- .set_enabled("skills", CapabilityLevel::Global, "review", None, false)
- .unwrap();
- state
- .set_enabled(
- "skills",
- CapabilityLevel::Global,
- "review",
- Some("/repo"),
- true,
- )
- .unwrap();
- state
- .set_enabled(
- "skills",
- CapabilityLevel::Project,
- "review",
- Some("/repo"),
- false,
- )
- .unwrap();
- assert!(!state.enabled("skills", CapabilityLevel::Global, "review", None));
-
- state
- .forget("skills", CapabilityLevel::Global, "review", None)
- .unwrap();
- // Back to the default, and the unrelated project-level entry survives.
- assert!(state.enabled("skills", CapabilityLevel::Global, "review", Some("/repo")));
- assert!(!state.enabled("skills", CapabilityLevel::Project, "review", Some("/repo")));
- }
-
- #[test]
- fn project_level_forget_keeps_other_projects_entries() {
- let dir = tempdir().unwrap();
- let mut state = CapabilityState::new(dir.path(), "skills");
- state
- .set_enabled(
- "skills",
- CapabilityLevel::Project,
- "review",
- Some("/a"),
- false,
- )
- .unwrap();
- state
- .set_enabled(
- "skills",
- CapabilityLevel::Project,
- "review",
- Some("/b"),
- false,
- )
- .unwrap();
-
- state
- .forget("skills", CapabilityLevel::Project, "review", Some("/a"))
- .unwrap();
- // Only the owner's entry is gone: another project's same-named document
- // is a different file and keeps its own state.
- assert!(state.enabled("skills", CapabilityLevel::Project, "review", Some("/a")));
- assert!(!state.enabled("skills", CapabilityLevel::Project, "review", Some("/b")));
- }
-
- #[test]
- fn moving_a_project_document_leaves_other_projects_state_alone() {
- let dir = tempdir().unwrap();
- let mut state = CapabilityState::new(dir.path(), "mcp");
- state
- .set_enabled("mcp", CapabilityLevel::Project, "files", Some("/a"), false)
- .unwrap();
- state
- .set_enabled("mcp", CapabilityLevel::Project, "files", Some("/b"), false)
- .unwrap();
-
- set_moved_capability_state(
- &mut state,
- "mcp",
- CapabilityLevel::Project,
- "files",
- Some("/a"),
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- "files",
- false,
- )
- .unwrap();
-
- // The departed project's entry moved with the document; the other
- // project still owns its own state for the same id.
- assert!(state.enabled("mcp", CapabilityLevel::Project, "files", Some("/a")));
- assert!(!state.enabled("mcp", CapabilityLevel::Project, "files", Some("/b")));
- assert!(!state.enabled("mcp", CapabilityLevel::Global, "files", Some("/b")));
- }
-
- #[test]
- fn copy_directory_tree_overwrites_stale_files_and_can_skip_the_document() {
- let dir = tempdir().unwrap();
- let from = dir.path().join("from");
- let to = dir.path().join("to");
- fs::create_dir_all(from.join("nested")).unwrap();
- fs::write(from.join("SKILL.md"), "doc").unwrap();
- fs::write(from.join("notes.txt"), "keep me").unwrap();
- fs::write(from.join("nested/page.html"), "<p>page</p>").unwrap();
- // A leftover from an interrupted copy must not survive: skipping it
- // would silently drop the resource.
- fs::create_dir_all(&to).unwrap();
- fs::write(to.join("notes.txt"), "stale").unwrap();
-
- copy_directory_tree(&from, &to, true).unwrap();
- assert!(!to.join("SKILL.md").exists());
- assert_eq!(fs::read_to_string(to.join("notes.txt")).unwrap(), "keep me");
- assert_eq!(
- fs::read_to_string(to.join("nested/page.html")).unwrap(),
- "<p>page</p>"
- );
-
- let whole = dir.path().join("whole");
- copy_directory_tree(&from, &whole, false).unwrap();
- assert_eq!(fs::read_to_string(whole.join("SKILL.md")).unwrap(), "doc");
- }
-
- #[test]
- fn moving_a_directory_capability_carries_its_tree() {
- let dir = tempdir().unwrap();
- let from = dir.path().join("skill");
- let to = dir.path().join("moved/skill");
- fs::create_dir_all(from.join("templates")).unwrap();
- fs::write(from.join("SKILL.md"), "doc").unwrap();
- fs::write(from.join("templates/page.html"), "<p>page</p>").unwrap();
-
- move_capability_file(&from, &to).unwrap();
- assert!(!from.exists());
- assert_eq!(fs::read_to_string(to.join("SKILL.md")).unwrap(), "doc");
- assert_eq!(
- fs::read_to_string(to.join("templates/page.html")).unwrap(),
- "<p>page</p>"
- );
- }
-
- #[test]
- fn moving_a_file_never_replaces_an_existing_destination() {
- let dir = tempdir().unwrap();
- let from = dir.path().join("from.md");
- let to = dir.path().join("nested/to.md");
- fs::write(&from, "source").unwrap();
- move_capability_file(&from, &to).unwrap();
- assert!(!from.exists());
- assert_eq!(fs::read_to_string(&to).unwrap(), "source");
-
- fs::write(&from, "second").unwrap();
- assert!(move_capability_file(&from, &to).is_err());
- assert_eq!(fs::read_to_string(&to).unwrap(), "source");
- assert_eq!(fs::read_to_string(&from).unwrap(), "second");
- }
-}
+mod tests;
diff --git a/crates/host-core/src/agent_capabilities/tests.rs b/crates/host-core/src/agent_capabilities/tests.rs
new file mode 100644
index 000000000..f464aabc5
--- /dev/null
+++ b/crates/host-core/src/agent_capabilities/tests.rs
@@ -0,0 +1,356 @@
+use super::*;
+use tempfile::tempdir;
+
+#[test]
+fn front_matter_and_body_round_trip() {
+ let (fields, body) =
+ parse_front_matter("---\nname: Review\ndescription: Check code\n---\n\nDo it.\n");
+ assert_eq!(fields.get("name").map(String::as_str), Some("Review"));
+ assert_eq!(
+ fields.get("description").map(String::as_str),
+ Some("Check code")
+ );
+ assert_eq!(body, "Do it.");
+}
+
+#[test]
+fn front_matter_reads_folded_yaml_descriptions() {
+ let raw = "---\nname: find-skills\ndescription: >\n Discover skills when asked\n how to do X.\n---\n\nFollow the steps.\n";
+ let (fields, body) = parse_front_matter(raw);
+ assert_eq!(fields.get("name").map(String::as_str), Some("find-skills"));
+ assert_eq!(
+ fields.get("description").map(String::as_str),
+ Some("Discover skills when asked how to do X.")
+ );
+ assert_eq!(body, "Follow the steps.");
+}
+
+#[test]
+fn capability_id_falls_back_to_skill_directory_then_hash() {
+ let dir_skill = Path::new("/tmp/code-review/SKILL.md");
+ assert_eq!(capability_id("代码审查", dir_skill, 64), "code-review");
+ assert_eq!(path_stem_for_id(dir_skill), "code-review");
+
+ let hashed = capability_id("代码审查", Path::new("/tmp/代码审查.md"), 64);
+ assert!(hashed.starts_with("skill-"));
+ assert!(valid_capability_id(&hashed, 64));
+ assert_eq!(
+ hashed,
+ capability_id("代码审查", Path::new("/elsewhere/代码审查.md"), 64)
+ );
+ assert_eq!(
+ capability_id("代码审查", Path::new("/Users/me/Downloads/SKILL.md"), 64),
+ hashed
+ );
+ assert_ne!(
+ capability_id("代码审查", Path::new("/Users/me/Downloads/SKILL.md"), 64),
+ "downloads"
+ );
+}
+
+#[test]
+fn state_defaults_on_and_is_project_specific() {
+ let dir = tempdir().unwrap();
+ let mut state = CapabilityState::new(dir.path(), "skills");
+ assert!(state.enabled("skills", CapabilityLevel::Global, "review", Some("/a")));
+ state
+ .set_enabled(
+ "skills",
+ CapabilityLevel::Global,
+ "review",
+ Some("/a"),
+ false,
+ )
+ .unwrap();
+ assert!(!state.enabled("skills", CapabilityLevel::Global, "review", Some("/a")));
+ assert!(state.enabled("skills", CapabilityLevel::Global, "review", Some("/b")));
+ let reopened = CapabilityState::new(dir.path(), "skills");
+ assert!(!reopened.enabled("skills", CapabilityLevel::Global, "review", Some("/a")));
+
+ let mut orphaned = reopened;
+ orphaned
+ .prune(
+ "skills",
+ CapabilityLevel::Global,
+ None,
+ &std::collections::HashSet::new(),
+ )
+ .unwrap();
+ assert!(orphaned.enabled("skills", CapabilityLevel::Global, "review", Some("/a")));
+}
+
+#[test]
+fn suffix_keeps_the_preferred_id_when_it_is_free() {
+ let taken = HashSet::new();
+ assert_eq!(
+ suffixed_capability_id("review", &taken, 64),
+ Some(("review".to_string(), 0))
+ );
+}
+
+#[test]
+fn suffix_walks_past_every_taken_id_and_stays_inside_the_budget() {
+ let taken: HashSet<String> = ["review".to_string(), "review-2".to_string()]
+ .into_iter()
+ .collect();
+ assert_eq!(
+ suffixed_capability_id("review", &taken, 64),
+ Some(("review-3".to_string(), 3))
+ );
+
+ // A 64-character id has no room for the suffix, so the base is trimmed
+ // rather than the candidate growing past what the id validator accepts.
+ let long = "a".repeat(64);
+ let taken: HashSet<String> = [long.clone()].into_iter().collect();
+ let (candidate, ordinal) = suffixed_capability_id(&long, &taken, 64).unwrap();
+ assert_eq!(ordinal, 2);
+ assert_eq!(candidate.len(), 64);
+ assert!(valid_capability_id(&candidate, 64));
+}
+
+#[test]
+fn suffix_reports_exhaustion_instead_of_reusing_a_taken_id() {
+ let taken: HashSet<String> = ["review".to_string()].into_iter().collect();
+ // `max_chars` below the suffix length leaves nothing to build on.
+ assert_eq!(suffixed_capability_id("review", &taken, 2), None);
+}
+
+#[test]
+fn display_name_suffix_is_case_insensitive_like_shadowing() {
+ let taken: HashSet<String> = ["review".to_string()].into_iter().collect();
+ assert_eq!(suffixed_display_name("Review", &taken, 120), "Review (2)");
+ assert_eq!(suffixed_display_name("Files", &taken, 120), "Files");
+}
+
+#[test]
+fn suffix_ignores_id_case_so_a_case_insensitive_volume_keeps_both_files() {
+ // Callers pass the taken set lowercased, mirroring the filesystem, so
+ // `MyServer` must not be treated as free next to `myserver`.
+ let taken: HashSet<String> = ["myserver".to_string()].into_iter().collect();
+ assert_eq!(
+ suffixed_capability_id("MyServer", &taken, 64),
+ Some(("MyServer-2".to_string(), 2))
+ );
+}
+
+#[test]
+fn display_name_suffix_stays_distinct_at_the_character_budget() {
+ let full = "a".repeat(120);
+ let taken: HashSet<String> = [full.clone()].into_iter().collect();
+ let renamed = suffixed_display_name(&full, &taken, 120);
+ assert_ne!(renamed, full);
+ assert!(renamed.chars().count() <= 120);
+ assert_eq!(renamed, format!("{} (2)", "a".repeat(116)));
+
+ // Each ordinal still yields its own candidate once the earlier ones
+ // are taken, instead of collapsing onto the truncated base name.
+ let taken: HashSet<String> = [full.clone(), renamed.clone()]
+ .into_iter()
+ .map(|value| value.to_lowercase())
+ .collect();
+ let third = suffixed_display_name(&full, &taken, 120);
+ assert_ne!(third, full);
+ assert_ne!(third, renamed);
+ assert!(third.chars().count() <= 120);
+
+ // The suffix follows a base that was cut mid-word without a stray
+ // space, and ordinal 1 is the plain name.
+ assert_eq!(display_name_candidate("Review", 1, 120), "Review");
+ assert_eq!(display_name_candidate("Review", 2, 8), "Revi (2)");
+ assert_eq!(display_name_candidate("Review more", 2, 11), "Review (2)");
+}
+
+#[test]
+fn project_target_requires_a_project_path() {
+ assert!(CapabilityTarget::new(CapabilityLevel::Project, None).is_err());
+ assert!(CapabilityTarget::new(CapabilityLevel::Project, Some(" ")).is_err());
+ assert!(CapabilityTarget::new(CapabilityLevel::Global, None).is_ok());
+ assert_eq!(
+ CapabilityTarget::new(CapabilityLevel::Project, Some("/repo/"))
+ .unwrap()
+ .project_path
+ .as_deref(),
+ Some("/repo")
+ );
+}
+
+#[test]
+fn global_targets_share_one_directory_whatever_project_context_they_carry() {
+ let plain = CapabilityTarget::new(CapabilityLevel::Global, None).unwrap();
+ let contextual = CapabilityTarget::new(CapabilityLevel::Global, Some("/repo")).unwrap();
+ assert!(plain.same_directory(&contextual));
+ let project = CapabilityTarget::new(CapabilityLevel::Project, Some("/repo")).unwrap();
+ assert!(!plain.same_directory(&project));
+ let other = CapabilityTarget::new(CapabilityLevel::Project, Some("/other")).unwrap();
+ assert!(!project.same_directory(&other));
+}
+
+#[test]
+fn global_root_follows_the_environment_override() {
+ let dir = tempdir().unwrap();
+ test_support::with_global_agents(dir.path(), || {
+ assert_eq!(global_agents_dir(), dir.path());
+ assert_eq!(
+ capability_dir(CapabilityLevel::Global, None, "skills").unwrap(),
+ dir.path().join("skills")
+ );
+ });
+}
+
+#[test]
+fn forget_drops_every_project_override_for_one_document() {
+ let dir = tempdir().unwrap();
+ let mut state = CapabilityState::new(dir.path(), "skills");
+ state
+ .set_enabled("skills", CapabilityLevel::Global, "review", None, false)
+ .unwrap();
+ state
+ .set_enabled(
+ "skills",
+ CapabilityLevel::Global,
+ "review",
+ Some("/repo"),
+ true,
+ )
+ .unwrap();
+ state
+ .set_enabled(
+ "skills",
+ CapabilityLevel::Project,
+ "review",
+ Some("/repo"),
+ false,
+ )
+ .unwrap();
+ assert!(!state.enabled("skills", CapabilityLevel::Global, "review", None));
+
+ state
+ .forget("skills", CapabilityLevel::Global, "review", None)
+ .unwrap();
+ // Back to the default, and the unrelated project-level entry survives.
+ assert!(state.enabled("skills", CapabilityLevel::Global, "review", Some("/repo")));
+ assert!(!state.enabled("skills", CapabilityLevel::Project, "review", Some("/repo")));
+}
+
+#[test]
+fn project_level_forget_keeps_other_projects_entries() {
+ let dir = tempdir().unwrap();
+ let mut state = CapabilityState::new(dir.path(), "skills");
+ state
+ .set_enabled(
+ "skills",
+ CapabilityLevel::Project,
+ "review",
+ Some("/a"),
+ false,
+ )
+ .unwrap();
+ state
+ .set_enabled(
+ "skills",
+ CapabilityLevel::Project,
+ "review",
+ Some("/b"),
+ false,
+ )
+ .unwrap();
+
+ state
+ .forget("skills", CapabilityLevel::Project, "review", Some("/a"))
+ .unwrap();
+ // Only the owner's entry is gone: another project's same-named document
+ // is a different file and keeps its own state.
+ assert!(state.enabled("skills", CapabilityLevel::Project, "review", Some("/a")));
+ assert!(!state.enabled("skills", CapabilityLevel::Project, "review", Some("/b")));
+}
+
+#[test]
+fn moving_a_project_document_leaves_other_projects_state_alone() {
+ let dir = tempdir().unwrap();
+ let mut state = CapabilityState::new(dir.path(), "mcp");
+ state
+ .set_enabled("mcp", CapabilityLevel::Project, "files", Some("/a"), false)
+ .unwrap();
+ state
+ .set_enabled("mcp", CapabilityLevel::Project, "files", Some("/b"), false)
+ .unwrap();
+
+ set_moved_capability_state(
+ &mut state,
+ "mcp",
+ CapabilityLevel::Project,
+ "files",
+ Some("/a"),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ "files",
+ false,
+ )
+ .unwrap();
+
+ // The departed project's entry moved with the document; the other
+ // project still owns its own state for the same id.
+ assert!(state.enabled("mcp", CapabilityLevel::Project, "files", Some("/a")));
+ assert!(!state.enabled("mcp", CapabilityLevel::Project, "files", Some("/b")));
+ assert!(!state.enabled("mcp", CapabilityLevel::Global, "files", Some("/b")));
+}
+
+#[test]
+fn copy_directory_tree_overwrites_stale_files_and_can_skip_the_document() {
+ let dir = tempdir().unwrap();
+ let from = dir.path().join("from");
+ let to = dir.path().join("to");
+ fs::create_dir_all(from.join("nested")).unwrap();
+ fs::write(from.join("SKILL.md"), "doc").unwrap();
+ fs::write(from.join("notes.txt"), "keep me").unwrap();
+ fs::write(from.join("nested/page.html"), "<p>page</p>").unwrap();
+ // A leftover from an interrupted copy must not survive: skipping it
+ // would silently drop the resource.
+ fs::create_dir_all(&to).unwrap();
+ fs::write(to.join("notes.txt"), "stale").unwrap();
+
+ copy_directory_tree(&from, &to, true).unwrap();
+ assert!(!to.join("SKILL.md").exists());
+ assert_eq!(fs::read_to_string(to.join("notes.txt")).unwrap(), "keep me");
+ assert_eq!(
+ fs::read_to_string(to.join("nested/page.html")).unwrap(),
+ "<p>page</p>"
+ );
+
+ let whole = dir.path().join("whole");
+ copy_directory_tree(&from, &whole, false).unwrap();
+ assert_eq!(fs::read_to_string(whole.join("SKILL.md")).unwrap(), "doc");
+}
+
+#[test]
+fn moving_a_directory_capability_carries_its_tree() {
+ let dir = tempdir().unwrap();
+ let from = dir.path().join("skill");
+ let to = dir.path().join("moved/skill");
+ fs::create_dir_all(from.join("templates")).unwrap();
+ fs::write(from.join("SKILL.md"), "doc").unwrap();
+ fs::write(from.join("templates/page.html"), "<p>page</p>").unwrap();
+
+ move_capability_file(&from, &to).unwrap();
+ assert!(!from.exists());
+ assert_eq!(fs::read_to_string(to.join("SKILL.md")).unwrap(), "doc");
+ assert_eq!(
+ fs::read_to_string(to.join("templates/page.html")).unwrap(),
+ "<p>page</p>"
+ );
+}
+
+#[test]
+fn moving_a_file_never_replaces_an_existing_destination() {
+ let dir = tempdir().unwrap();
+ let from = dir.path().join("from.md");
+ let to = dir.path().join("nested/to.md");
+ fs::write(&from, "source").unwrap();
+ move_capability_file(&from, &to).unwrap();
+ assert!(!from.exists());
+ assert_eq!(fs::read_to_string(&to).unwrap(), "source");
+
+ fs::write(&from, "second").unwrap();
+ assert!(move_capability_file(&from, &to).is_err());
+ assert_eq!(fs::read_to_string(&to).unwrap(), "source");
+ assert_eq!(fs::read_to_string(&from).unwrap(), "second");
+}
diff --git a/crates/host-core/src/mcp_servers.rs b/crates/host-core/src/mcp_servers.rs
index b2307dada..03da468ca 100644
--- a/crates/host-core/src/mcp_servers.rs
+++ b/crates/host-core/src/mcp_servers.rs
@@ -624,438 +624,4 @@ impl McpServerRegistry {
}
#[cfg(test)]
-mod tests {
- use super::*;
- use crate::agent_capabilities::test_support;
- use tempfile::tempdir;
-
- /// A registry plus the two directories a level switch needs.
- fn scaffolding() -> (tempfile::TempDir, tempfile::TempDir, tempfile::TempDir) {
- (tempdir().unwrap(), tempdir().unwrap(), tempdir().unwrap())
- }
-
- fn stdio(id: &str) -> McpServerInput {
- McpServerInput {
- id: id.into(),
- transport: Some("stdio".into()),
- command: Some("npx".into()),
- args: Some(vec!["-y".into(), "server".into()]),
- ..Default::default()
- }
- }
-
- #[test]
- fn validation_accepts_http_endpoints_and_rejects_bad_ids() {
- assert!(!valid_id("1files"));
- assert!(check_url("http://localhost:3000/mcp").is_ok());
- assert!(check_url("http://192.168.1.20:8080/mcp").is_ok());
- assert!(check_url("https://example.com/mcp").is_ok());
- assert!(check_url("ftp://example.com/mcp").is_err());
- let mut config = McpConfig {
- id: "files".into(),
- label: "Files".into(),
- transport: "stdio".into(),
- command: Some("node..bin".into()),
- ..Default::default()
- };
- assert!(McpServerRegistry::validate_config(&config).is_err());
- config.command = Some("node".into());
- assert!(McpServerRegistry::validate_config(&config).is_ok());
- }
-
- #[test]
- fn config_round_trips_without_activation_fields() {
- let config = McpConfig {
- id: "files".into(),
- label: "Files".into(),
- transport: "stdio".into(),
- command: Some("npx".into()),
- ..Default::default()
- };
- let raw = serde_json::to_string(&config).unwrap();
- assert!(!raw.contains("enabled"));
- assert_eq!(serde_json::from_str::<McpConfig>(&raw).unwrap().id, "files");
- }
-
- #[test]
- fn disabled_project_server_shadows_global_server() {
- let global = McpServerRecord {
- id: "files".into(),
- label: "Files".into(),
- level: Some("global".into()),
- project_path: None,
- path: None,
- description: None,
- transport: "stdio".into(),
- command: Some("npx".into()),
- args: Vec::new(),
- env: BTreeMap::new(),
- url: None,
- headers: BTreeMap::new(),
- enabled: true,
- scope: ActivationScope::default(),
- created_at: String::new(),
- updated_at: String::new(),
- };
- let mut project = global.clone();
- project.level = Some("project".into());
- project.project_path = Some("/repo".into());
- project.enabled = false;
-
- let active = merge_active_records(vec![global], vec![project]);
- assert!(active.is_empty());
- }
-
- #[test]
- fn project_server_is_copied_and_state_is_pruned_after_removal() {
- let dir = tempdir().unwrap();
- let project_path = dir.path().to_str().unwrap().to_string();
- let mut registry = McpServerRegistry::new(dir.path());
- let mut first = stdio("files");
- first.label = Some("Files".into());
- first.level = Some("project".into());
- first.project_path = Some(project_path.clone());
- let record = registry.upsert(first).unwrap();
- let normalized_project = crate::agent_capabilities::normalize_project_path(&project_path);
- let target = crate::agent_capabilities::capability_dir(
- CapabilityLevel::Project,
- Some(&normalized_project),
- "servers",
- )
- .unwrap()
- .join("files.json");
- assert_eq!(record.path.as_deref(), target.to_str());
- assert!(!fs::read_to_string(&target).unwrap().contains("enabled"));
-
- let mut duplicate = stdio("other");
- duplicate.label = Some("files".into());
- duplicate.level = Some("project".into());
- duplicate.project_path = Some(project_path.clone());
- assert!(registry.upsert(duplicate).is_err());
-
- let disabled = registry
- .set_enabled(
- "files",
- false,
- Some(CapabilityLevel::Project),
- Some(&project_path),
- )
- .unwrap()
- .unwrap();
- assert!(!disabled.enabled);
- assert!(!registry.state.enabled(
- MCP_KIND,
- CapabilityLevel::Project,
- "files",
- Some(&project_path)
- ));
-
- assert!(registry
- .remove("files", Some(CapabilityLevel::Project), Some(&project_path))
- .unwrap());
- assert!(!target.exists());
- assert!(registry.state.enabled(
- MCP_KIND,
- CapabilityLevel::Project,
- "files",
- Some(&project_path)
- ));
- }
-
- #[test]
- fn a_global_server_moves_into_a_project_with_its_state() {
- let (home, app, project) = scaffolding();
- let project_path = project.path().to_str().unwrap().to_string();
- test_support::with_global_agents(home.path(), || {
- let mut registry = McpServerRegistry::new(app.path());
- let mut input = stdio("files");
- input.label = Some("Files".into());
- registry.upsert(input).unwrap();
- // Turned off for this one project only, which is the value a move
- // has to carry because it is what the user was looking at.
- registry
- .set_enabled(
- "files",
- false,
- Some(CapabilityLevel::Global),
- Some(&project_path),
- )
- .unwrap();
-
- let moved = registry
- .transfer(
- "files",
- &CapabilityTarget::new(CapabilityLevel::Global, Some(&project_path)).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- )
- .unwrap();
-
- assert_eq!(moved.level.as_deref(), Some("project"));
- assert_eq!(moved.project_path.as_deref(), Some(project_path.as_str()));
- assert!(!moved.enabled);
- assert!(!home.path().join("servers/files.json").exists());
- assert!(project.path().join(".agents/servers/files.json").is_file());
- assert!(registry
- .list(CapabilityLevel::Global, None)
- .unwrap()
- .is_empty());
- // The global override is gone with the document, not left pointing
- // at an id the global directory no longer holds.
- assert!(registry.state.enabled(
- MCP_KIND,
- CapabilityLevel::Global,
- "files",
- Some(&project_path)
- ));
- });
- }
-
- #[test]
- fn a_destination_collision_renames_the_arriving_server() {
- let (home, app, project) = scaffolding();
- let project_path = project.path().to_str().unwrap().to_string();
- test_support::with_global_agents(home.path(), || {
- let mut registry = McpServerRegistry::new(app.path());
- let mut global = stdio("files");
- global.label = Some("Files".into());
- registry.upsert(global).unwrap();
- let mut local = stdio("files");
- local.label = Some("Files".into());
- local.level = Some("project".into());
- local.project_path = Some(project_path.clone());
- registry.upsert(local).unwrap();
-
- let moved = registry
- .transfer(
- "files",
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- )
- .unwrap();
-
- assert_eq!(moved.id, "files-2");
- assert_eq!(moved.label, "Files (2)");
- assert!(!home.path().join("servers/files.json").exists());
- let listed = registry
- .list(CapabilityLevel::Project, Some(&project_path))
- .unwrap();
- assert_eq!(listed.len(), 2);
- // The server that was already there is untouched.
- assert!(listed
- .iter()
- .any(|record| record.id == "files" && record.label == "Files"));
- let document =
- fs::read_to_string(project.path().join(".agents/servers/files-2.json")).unwrap();
- assert!(document.contains("\"id\": \"files-2\""));
- assert!(document.contains("\"label\": \"Files (2)\""));
- });
- }
-
- #[test]
- fn a_project_server_moves_to_global_without_leaving_a_project_override() {
- let (home, app, project) = scaffolding();
- let project_path = project.path().to_str().unwrap().to_string();
- test_support::with_global_agents(home.path(), || {
- let mut registry = McpServerRegistry::new(app.path());
- let mut input = stdio("files");
- input.label = Some("Files".into());
- input.level = Some("project".into());
- input.project_path = Some(project_path.clone());
- input.enabled = Some(false);
- registry.upsert(input).unwrap();
-
- let moved = registry
- .transfer(
- "files",
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- )
- .unwrap();
-
- assert_eq!(moved.level.as_deref(), Some("global"));
- assert_eq!(moved.project_path, None);
- assert!(!moved.enabled);
- assert!(home.path().join("servers/files.json").is_file());
- assert!(!project.path().join(".agents/servers/files.json").exists());
- // The disabled state is now the global default: it follows the
- // document, and no project-only entry is left behind.
- assert!(!registry.state.enabled(
- MCP_KIND,
- CapabilityLevel::Global,
- "files",
- Some("/elsewhere")
- ));
- assert!(registry.state.enabled(
- MCP_KIND,
- CapabilityLevel::Project,
- "files",
- Some(&project_path)
- ));
- });
- }
-
- #[test]
- fn transferring_within_one_directory_changes_nothing() {
- let (home, app, project) = scaffolding();
- let project_path = project.path().to_str().unwrap().to_string();
- test_support::with_global_agents(home.path(), || {
- let mut registry = McpServerRegistry::new(app.path());
- let mut input = stdio("files");
- input.label = Some("Files".into());
- input.level = Some("project".into());
- input.project_path = Some(project_path.clone());
- registry.upsert(input).unwrap();
-
- let target =
- CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap();
- let same = registry.transfer("files", &target, &target).unwrap();
- assert_eq!(same.id, "files");
- assert!(project.path().join(".agents/servers/files.json").is_file());
- });
- }
-
- #[test]
- fn transferring_an_unknown_server_is_an_error() {
- let (home, app, _project) = scaffolding();
- test_support::with_global_agents(home.path(), || {
- let mut registry = McpServerRegistry::new(app.path());
- let error = registry
- .transfer(
- "missing",
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- )
- .unwrap_err();
- assert!(error.to_string().contains("MCP_INVALID"));
- });
- }
-
- #[test]
- fn a_case_differing_id_at_the_destination_is_not_overwritten() {
- let (home, app, project) = scaffolding();
- let project_path = project.path().to_str().unwrap().to_string();
- test_support::with_global_agents(home.path(), || {
- let mut registry = McpServerRegistry::new(app.path());
- let mut global = stdio("files");
- global.label = Some("Files".into());
- registry.upsert(global).unwrap();
- let mut local = stdio("FILES");
- local.label = Some("Uppercase files".into());
- local.level = Some("project".into());
- local.project_path = Some(project_path.clone());
- registry.upsert(local).unwrap();
- let existing =
- fs::read_to_string(project.path().join(".agents/servers/FILES.json")).unwrap();
-
- let moved = registry
- .transfer(
- "files",
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- )
- .unwrap();
-
- // `FILES` and `files` are the same file on macOS and Windows, so the
- // arriving server must take a genuinely free id instead.
- assert_eq!(moved.id, "files-2");
- assert!(!home.path().join("servers/files.json").exists());
- assert_eq!(
- fs::read_to_string(project.path().join(".agents/servers/FILES.json")).unwrap(),
- existing
- );
- assert!(project
- .path()
- .join(".agents/servers/files-2.json")
- .is_file());
- let listed = registry
- .list(CapabilityLevel::Project, Some(&project_path))
- .unwrap();
- assert_eq!(listed.len(), 2);
- });
- }
-
- #[test]
- fn a_rename_never_writes_over_a_file_the_scan_does_not_list() {
- let (home, app, project) = scaffolding();
- let project_path = project.path().to_str().unwrap().to_string();
- test_support::with_global_agents(home.path(), || {
- let mut registry = McpServerRegistry::new(app.path());
- let mut global = stdio("files");
- global.label = Some("Files".into());
- registry.upsert(global).unwrap();
- // Two project entries: one listed server whose label forces the
- // arriving server to rename, plus an unparseable file that occupies
- // the destination path without appearing in any scan.
- let mut local = stdio("other");
- local.label = Some("Files".into());
- local.level = Some("project".into());
- local.project_path = Some(project_path.clone());
- registry.upsert(local).unwrap();
- let bogus = project.path().join(".agents/servers/files.json");
- fs::write(&bogus, "not a server config").unwrap();
-
- let error = registry
- .transfer(
- "files",
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- )
- .unwrap_err();
-
- assert!(error.to_string().contains("MCP_INVALID"));
- assert_eq!(fs::read_to_string(&bogus).unwrap(), "not a server config");
- // The move refused before deleting anything.
- assert!(home.path().join("servers/files.json").is_file());
- });
- }
-
- #[test]
- fn moving_one_projects_server_to_global_keeps_another_projects_state() {
- let (home, app, project) = scaffolding();
- let other = tempdir().unwrap();
- let project_a = project.path().to_str().unwrap().to_string();
- let project_b = other.path().to_str().unwrap().to_string();
- test_support::with_global_agents(home.path(), || {
- let mut registry = McpServerRegistry::new(app.path());
- let mut a = stdio("files");
- a.label = Some("Files".into());
- a.level = Some("project".into());
- a.project_path = Some(project_a.clone());
- a.enabled = Some(false);
- registry.upsert(a).unwrap();
- let mut b = stdio("files");
- b.label = Some("Files".into());
- b.level = Some("project".into());
- b.project_path = Some(project_b.clone());
- b.enabled = Some(false);
- registry.upsert(b).unwrap();
-
- registry
- .transfer(
- "files",
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_a)).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- )
- .unwrap();
-
- // Project B's document and its disabled state survive: moving A's
- // same-id server says nothing about B.
- assert!(other.path().join(".agents/servers/files.json").is_file());
- assert!(!registry.state.enabled(
- MCP_KIND,
- CapabilityLevel::Project,
- "files",
- Some(&project_b)
- ));
- assert!(registry.state.enabled(
- MCP_KIND,
- CapabilityLevel::Project,
- "files",
- Some(&project_a)
- ));
- assert!(!registry
- .state
- .enabled(MCP_KIND, CapabilityLevel::Global, "files", None));
- });
- }
-}
+mod tests;
diff --git a/crates/host-core/src/mcp_servers/tests.rs b/crates/host-core/src/mcp_servers/tests.rs
new file mode 100644
index 000000000..d2cf2112c
--- /dev/null
+++ b/crates/host-core/src/mcp_servers/tests.rs
@@ -0,0 +1,432 @@
+use super::*;
+use crate::agent_capabilities::test_support;
+use tempfile::tempdir;
+
+/// A registry plus the two directories a level switch needs.
+fn scaffolding() -> (tempfile::TempDir, tempfile::TempDir, tempfile::TempDir) {
+ (tempdir().unwrap(), tempdir().unwrap(), tempdir().unwrap())
+}
+
+fn stdio(id: &str) -> McpServerInput {
+ McpServerInput {
+ id: id.into(),
+ transport: Some("stdio".into()),
+ command: Some("npx".into()),
+ args: Some(vec!["-y".into(), "server".into()]),
+ ..Default::default()
+ }
+}
+
+#[test]
+fn validation_accepts_http_endpoints_and_rejects_bad_ids() {
+ assert!(!valid_id("1files"));
+ assert!(check_url("http://localhost:3000/mcp").is_ok());
+ assert!(check_url("http://192.168.1.20:8080/mcp").is_ok());
+ assert!(check_url("https://example.com/mcp").is_ok());
+ assert!(check_url("ftp://example.com/mcp").is_err());
+ let mut config = McpConfig {
+ id: "files".into(),
+ label: "Files".into(),
+ transport: "stdio".into(),
+ command: Some("node..bin".into()),
+ ..Default::default()
+ };
+ assert!(McpServerRegistry::validate_config(&config).is_err());
+ config.command = Some("node".into());
+ assert!(McpServerRegistry::validate_config(&config).is_ok());
+}
+
+#[test]
+fn config_round_trips_without_activation_fields() {
+ let config = McpConfig {
+ id: "files".into(),
+ label: "Files".into(),
+ transport: "stdio".into(),
+ command: Some("npx".into()),
+ ..Default::default()
+ };
+ let raw = serde_json::to_string(&config).unwrap();
+ assert!(!raw.contains("enabled"));
+ assert_eq!(serde_json::from_str::<McpConfig>(&raw).unwrap().id, "files");
+}
+
+#[test]
+fn disabled_project_server_shadows_global_server() {
+ let global = McpServerRecord {
+ id: "files".into(),
+ label: "Files".into(),
+ level: Some("global".into()),
+ project_path: None,
+ path: None,
+ description: None,
+ transport: "stdio".into(),
+ command: Some("npx".into()),
+ args: Vec::new(),
+ env: BTreeMap::new(),
+ url: None,
+ headers: BTreeMap::new(),
+ enabled: true,
+ scope: ActivationScope::default(),
+ created_at: String::new(),
+ updated_at: String::new(),
+ };
+ let mut project = global.clone();
+ project.level = Some("project".into());
+ project.project_path = Some("/repo".into());
+ project.enabled = false;
+
+ let active = merge_active_records(vec![global], vec![project]);
+ assert!(active.is_empty());
+}
+
+#[test]
+fn project_server_is_copied_and_state_is_pruned_after_removal() {
+ let dir = tempdir().unwrap();
+ let project_path = dir.path().to_str().unwrap().to_string();
+ let mut registry = McpServerRegistry::new(dir.path());
+ let mut first = stdio("files");
+ first.label = Some("Files".into());
+ first.level = Some("project".into());
+ first.project_path = Some(project_path.clone());
+ let record = registry.upsert(first).unwrap();
+ let normalized_project = crate::agent_capabilities::normalize_project_path(&project_path);
+ let target = crate::agent_capabilities::capability_dir(
+ CapabilityLevel::Project,
+ Some(&normalized_project),
+ "servers",
+ )
+ .unwrap()
+ .join("files.json");
+ assert_eq!(record.path.as_deref(), target.to_str());
+ assert!(!fs::read_to_string(&target).unwrap().contains("enabled"));
+
+ let mut duplicate = stdio("other");
+ duplicate.label = Some("files".into());
+ duplicate.level = Some("project".into());
+ duplicate.project_path = Some(project_path.clone());
+ assert!(registry.upsert(duplicate).is_err());
+
+ let disabled = registry
+ .set_enabled(
+ "files",
+ false,
+ Some(CapabilityLevel::Project),
+ Some(&project_path),
+ )
+ .unwrap()
+ .unwrap();
+ assert!(!disabled.enabled);
+ assert!(!registry.state.enabled(
+ MCP_KIND,
+ CapabilityLevel::Project,
+ "files",
+ Some(&project_path)
+ ));
+
+ assert!(registry
+ .remove("files", Some(CapabilityLevel::Project), Some(&project_path))
+ .unwrap());
+ assert!(!target.exists());
+ assert!(registry.state.enabled(
+ MCP_KIND,
+ CapabilityLevel::Project,
+ "files",
+ Some(&project_path)
+ ));
+}
+
+#[test]
+fn a_global_server_moves_into_a_project_with_its_state() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut input = stdio("files");
+ input.label = Some("Files".into());
+ registry.upsert(input).unwrap();
+ // Turned off for this one project only, which is the value a move
+ // has to carry because it is what the user was looking at.
+ registry
+ .set_enabled(
+ "files",
+ false,
+ Some(CapabilityLevel::Global),
+ Some(&project_path),
+ )
+ .unwrap();
+
+ let moved = registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Global, Some(&project_path)).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.level.as_deref(), Some("project"));
+ assert_eq!(moved.project_path.as_deref(), Some(project_path.as_str()));
+ assert!(!moved.enabled);
+ assert!(!home.path().join("servers/files.json").exists());
+ assert!(project.path().join(".agents/servers/files.json").is_file());
+ assert!(registry
+ .list(CapabilityLevel::Global, None)
+ .unwrap()
+ .is_empty());
+ // The global override is gone with the document, not left pointing
+ // at an id the global directory no longer holds.
+ assert!(registry.state.enabled(
+ MCP_KIND,
+ CapabilityLevel::Global,
+ "files",
+ Some(&project_path)
+ ));
+ });
+}
+
+#[test]
+fn a_destination_collision_renames_the_arriving_server() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut global = stdio("files");
+ global.label = Some("Files".into());
+ registry.upsert(global).unwrap();
+ let mut local = stdio("files");
+ local.label = Some("Files".into());
+ local.level = Some("project".into());
+ local.project_path = Some(project_path.clone());
+ registry.upsert(local).unwrap();
+
+ let moved = registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "files-2");
+ assert_eq!(moved.label, "Files (2)");
+ assert!(!home.path().join("servers/files.json").exists());
+ let listed = registry
+ .list(CapabilityLevel::Project, Some(&project_path))
+ .unwrap();
+ assert_eq!(listed.len(), 2);
+ // The server that was already there is untouched.
+ assert!(listed
+ .iter()
+ .any(|record| record.id == "files" && record.label == "Files"));
+ let document =
+ fs::read_to_string(project.path().join(".agents/servers/files-2.json")).unwrap();
+ assert!(document.contains("\"id\": \"files-2\""));
+ assert!(document.contains("\"label\": \"Files (2)\""));
+ });
+}
+
+#[test]
+fn a_project_server_moves_to_global_without_leaving_a_project_override() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut input = stdio("files");
+ input.label = Some("Files".into());
+ input.level = Some("project".into());
+ input.project_path = Some(project_path.clone());
+ input.enabled = Some(false);
+ registry.upsert(input).unwrap();
+
+ let moved = registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.level.as_deref(), Some("global"));
+ assert_eq!(moved.project_path, None);
+ assert!(!moved.enabled);
+ assert!(home.path().join("servers/files.json").is_file());
+ assert!(!project.path().join(".agents/servers/files.json").exists());
+ // The disabled state is now the global default: it follows the
+ // document, and no project-only entry is left behind.
+ assert!(!registry.state.enabled(
+ MCP_KIND,
+ CapabilityLevel::Global,
+ "files",
+ Some("/elsewhere")
+ ));
+ assert!(registry.state.enabled(
+ MCP_KIND,
+ CapabilityLevel::Project,
+ "files",
+ Some(&project_path)
+ ));
+ });
+}
+
+#[test]
+fn transferring_within_one_directory_changes_nothing() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut input = stdio("files");
+ input.label = Some("Files".into());
+ input.level = Some("project".into());
+ input.project_path = Some(project_path.clone());
+ registry.upsert(input).unwrap();
+
+ let target = CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap();
+ let same = registry.transfer("files", &target, &target).unwrap();
+ assert_eq!(same.id, "files");
+ assert!(project.path().join(".agents/servers/files.json").is_file());
+ });
+}
+
+#[test]
+fn transferring_an_unknown_server_is_an_error() {
+ let (home, app, _project) = scaffolding();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let error = registry
+ .transfer(
+ "missing",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ )
+ .unwrap_err();
+ assert!(error.to_string().contains("MCP_INVALID"));
+ });
+}
+
+#[test]
+fn a_case_differing_id_at_the_destination_is_not_overwritten() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut global = stdio("files");
+ global.label = Some("Files".into());
+ registry.upsert(global).unwrap();
+ let mut local = stdio("FILES");
+ local.label = Some("Uppercase files".into());
+ local.level = Some("project".into());
+ local.project_path = Some(project_path.clone());
+ registry.upsert(local).unwrap();
+ let existing =
+ fs::read_to_string(project.path().join(".agents/servers/FILES.json")).unwrap();
+
+ let moved = registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ // `FILES` and `files` are the same file on macOS and Windows, so the
+ // arriving server must take a genuinely free id instead.
+ assert_eq!(moved.id, "files-2");
+ assert!(!home.path().join("servers/files.json").exists());
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/servers/FILES.json")).unwrap(),
+ existing
+ );
+ assert!(project
+ .path()
+ .join(".agents/servers/files-2.json")
+ .is_file());
+ let listed = registry
+ .list(CapabilityLevel::Project, Some(&project_path))
+ .unwrap();
+ assert_eq!(listed.len(), 2);
+ });
+}
+
+#[test]
+fn a_rename_never_writes_over_a_file_the_scan_does_not_list() {
+ let (home, app, project) = scaffolding();
+ let project_path = project.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut global = stdio("files");
+ global.label = Some("Files".into());
+ registry.upsert(global).unwrap();
+ // Two project entries: one listed server whose label forces the
+ // arriving server to rename, plus an unparseable file that occupies
+ // the destination path without appearing in any scan.
+ let mut local = stdio("other");
+ local.label = Some("Files".into());
+ local.level = Some("project".into());
+ local.project_path = Some(project_path.clone());
+ registry.upsert(local).unwrap();
+ let bogus = project.path().join(".agents/servers/files.json");
+ fs::write(&bogus, "not a server config").unwrap();
+
+ let error = registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap_err();
+
+ assert!(error.to_string().contains("MCP_INVALID"));
+ assert_eq!(fs::read_to_string(&bogus).unwrap(), "not a server config");
+ // The move refused before deleting anything.
+ assert!(home.path().join("servers/files.json").is_file());
+ });
+}
+
+#[test]
+fn moving_one_projects_server_to_global_keeps_another_projects_state() {
+ let (home, app, project) = scaffolding();
+ let other = tempdir().unwrap();
+ let project_a = project.path().to_str().unwrap().to_string();
+ let project_b = other.path().to_str().unwrap().to_string();
+ test_support::with_global_agents(home.path(), || {
+ let mut registry = McpServerRegistry::new(app.path());
+ let mut a = stdio("files");
+ a.label = Some("Files".into());
+ a.level = Some("project".into());
+ a.project_path = Some(project_a.clone());
+ a.enabled = Some(false);
+ registry.upsert(a).unwrap();
+ let mut b = stdio("files");
+ b.label = Some("Files".into());
+ b.level = Some("project".into());
+ b.project_path = Some(project_b.clone());
+ b.enabled = Some(false);
+ registry.upsert(b).unwrap();
+
+ registry
+ .transfer(
+ "files",
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_a)).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ )
+ .unwrap();
+
+ // Project B's document and its disabled state survive: moving A's
+ // same-id server says nothing about B.
+ assert!(other.path().join(".agents/servers/files.json").is_file());
+ assert!(!registry.state.enabled(
+ MCP_KIND,
+ CapabilityLevel::Project,
+ "files",
+ Some(&project_b)
+ ));
+ assert!(registry.state.enabled(
+ MCP_KIND,
+ CapabilityLevel::Project,
+ "files",
+ Some(&project_a)
+ ));
+ assert!(!registry
+ .state
+ .enabled(MCP_KIND, CapabilityLevel::Global, "files", None));
+ });
+}
diff --git a/crates/host-core/src/user_skills.rs b/crates/host-core/src/user_skills.rs
index beabc6329..6aa8500a9 100644
--- a/crates/host-core/src/user_skills.rs
+++ b/crates/host-core/src/user_skills.rs
@@ -841,677 +841,4 @@ fn scope_for(level: CapabilityLevel, project_path: Option<&str>) -> ActivationSc
}
#[cfg(test)]
-mod tests {
- use super::*;
- use crate::agent_capabilities::test_support;
- use tempfile::tempdir;
-
- fn input(name: &str, level: &str, project_path: Option<&str>) -> UserSkillInput {
- UserSkillInput {
- name: Some(name.into()),
- level: Some(level.into()),
- project_path: project_path.map(str::to_string),
- description: Some("Check the relevant files".into()),
- body: Some("Do the thing.".into()),
- ..Default::default()
- }
- }
-
- #[test]
- fn imports_one_file_into_the_selected_agents_directory() {
- let app = tempdir().unwrap();
- let source = app.path().join("incoming.md");
- let raw = "---\nname: Review\ndescription: Check code\n---\n\nDo it.\n";
- fs::write(&source, raw).unwrap();
- let mut registry = UserSkillRegistry::new(app.path());
- let record = registry
- .import(
- source.to_str().unwrap(),
- input("Ignored", "project", Some(app.path().to_str().unwrap())),
- )
- .unwrap();
- let target = app.path().join(".agents/skills/review.md");
- assert_eq!(record.level.as_deref(), Some("project"));
- let normalized_project =
- crate::agent_capabilities::normalize_project_path(app.path().to_str().unwrap());
- let expected = crate::agent_capabilities::capability_dir(
- CapabilityLevel::Project,
- Some(&normalized_project),
- "skills",
- )
- .unwrap()
- .join("review.md");
- assert_eq!(record.path, expected.to_string_lossy());
- assert_eq!(fs::read_to_string(target).unwrap(), raw);
- assert!(source.is_file());
- }
-
- #[test]
- fn project_skills_shadow_global_skills_by_name() {
- let app = tempdir().unwrap();
- let global = app.path().join("global");
- let project = app.path().join("project");
- fs::create_dir_all(global.join("skills")).unwrap();
- fs::create_dir_all(project.join(".agents/skills")).unwrap();
- fs::write(
- global.join("skills/review.md"),
- "---\nname: Review\n---\n\nGlobal\n",
- )
- .unwrap();
- fs::write(
- project.join(".agents/skills/review.md"),
- "---\nname: Review\n---\n\nProject\n",
- )
- .unwrap();
- let (fields, body) = parse_front_matter(
- &fs::read_to_string(project.join(".agents/skills/review.md")).unwrap(),
- );
- assert_eq!(fields.get("name").map(String::as_str), Some("Review"));
- assert_eq!(body, "Project");
- }
-
- #[test]
- fn disabled_project_skill_shadows_global_skill() {
- let global = UserSkillRecord {
- id: "review".into(),
- name: "Review".into(),
- level: Some("global".into()),
- project_path: None,
- description: Some("Global".into()),
- enabled: true,
- scope: ActivationScope::default(),
- source: "imported".into(),
- path: "/global/review.md".into(),
- size_bytes: 1,
- created_at: String::new(),
- updated_at: String::new(),
- };
- let mut project = global.clone();
- project.level = Some("project".into());
- project.project_path = Some("/repo".into());
- project.enabled = false;
-
- let active = merge_active_records(vec![global.clone()], vec![project]);
- assert!(active.is_empty());
-
- let mut project = global.clone();
- project.level = Some("project".into());
- project.project_path = Some("/repo".into());
- project.path = "/repo/.agents/skills/review.md".into();
- let active = merge_active_records(vec![global], vec![project.clone()]);
- assert_eq!(active, vec![project]);
- }
-
- #[test]
- fn capability_state_is_not_written_into_skill_documents() {
- let app = tempdir().unwrap();
- let mut state = CapabilityState::new(app.path(), SKILL_KIND);
- state
- .set_enabled(
- SKILL_KIND,
- CapabilityLevel::Project,
- "review",
- Some("/repo"),
- false,
- )
- .unwrap();
- assert!(!app
- .path()
- .join("agent-capabilities/skills.json")
- .to_string_lossy()
- .contains(".agents"));
- }
-
- #[test]
- fn import_uses_parent_directory_when_name_is_not_ascii() {
- let app = tempdir().unwrap();
- let source_dir = app.path().join("incoming/code-review");
- fs::create_dir_all(&source_dir).unwrap();
- let source = source_dir.join("SKILL.md");
- fs::write(
- &source,
- "---\nname: 代码审查\ndescription: >\n Review diffs before merge.\n---\n\nCheck the patch.\n",
- )
- .unwrap();
- let mut registry = UserSkillRegistry::new(app.path());
- let record = registry
- .import(
- source.to_str().unwrap(),
- input("Ignored", "project", Some(app.path().to_str().unwrap())),
- )
- .unwrap();
- assert_eq!(record.id, "code-review");
- assert_eq!(record.name, "代码审查");
- assert_eq!(
- record.description.as_deref(),
- Some("Review diffs before merge.")
- );
- let listed = registry
- .list(CapabilityLevel::Project, Some(app.path().to_str().unwrap()))
- .unwrap();
- assert_eq!(listed.len(), 1);
- assert_eq!(listed[0].id, "code-review");
- assert_eq!(listed[0].name, "代码审查");
- }
-
- #[test]
- fn directory_skills_do_not_collide_on_the_skill_file_stem() {
- let app = tempdir().unwrap();
- let project = app.path().to_str().unwrap();
- fs::create_dir_all(app.path().join(".agents/skills/pdf")).unwrap();
- fs::create_dir_all(app.path().join(".agents/skills/docx")).unwrap();
- fs::write(
- app.path().join(".agents/skills/pdf/SKILL.md"),
- "# PDF\n\nExtract text.\n",
- )
- .unwrap();
- fs::write(
- app.path().join(".agents/skills/docx/SKILL.md"),
- "# DOCX\n\nEdit documents.\n",
- )
- .unwrap();
- let mut registry = UserSkillRegistry::new(app.path());
- let listed = registry
- .list(CapabilityLevel::Project, Some(project))
- .unwrap();
- let ids: Vec<_> = listed.iter().map(|record| record.id.as_str()).collect();
- assert_eq!(ids, vec!["docx", "pdf"]);
- }
-
- /// A global skill document plus the project directory it can move into.
- fn skill_home(home: &Path) {
- fs::create_dir_all(home.join("skills")).unwrap();
- }
-
- fn project_dir(project: &Path) -> String {
- project.to_str().unwrap().to_string()
- }
-
- fn record(id: &str, name: &str) -> UserSkillRecord {
- UserSkillRecord {
- id: id.into(),
- name: name.into(),
- level: None,
- project_path: None,
- description: None,
- enabled: true,
- scope: ActivationScope::default(),
- source: "imported".into(),
- path: String::new(),
- size_bytes: 0,
- created_at: String::new(),
- updated_at: String::new(),
- }
- }
-
- /// A level may never list two records with the same id or the same name:
- /// either collision makes one of them disappear from the catalog.
- fn assert_unique_records(records: &[UserSkillRecord]) {
- let ids: HashSet<&str> = records.iter().map(|record| record.id.as_str()).collect();
- let names: HashSet<String> = records
- .iter()
- .map(|record| record.name.to_lowercase())
- .collect();
- assert_eq!(ids.len(), records.len(), "duplicate ids: {records:?}");
- assert_eq!(names.len(), records.len(), "duplicate names: {records:?}");
- }
-
- #[test]
- fn a_global_skill_moves_into_a_project() {
- let home = tempdir().unwrap();
- let app = tempdir().unwrap();
- let project = tempdir().unwrap();
- let project_path = project_dir(project.path());
- test_support::with_global_agents(home.path(), || {
- skill_home(home.path());
- fs::write(
- home.path().join("skills/review.md"),
- "---\nname: Review\ndescription: Check code\n---\n\nDo it.\n",
- )
- .unwrap();
- let mut registry = UserSkillRegistry::new(app.path());
-
- let moved = registry
- .transfer(
- "review",
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- )
- .unwrap();
-
- assert_eq!(moved.id, "review");
- assert_eq!(moved.level.as_deref(), Some("project"));
- assert_eq!(moved.project_path.as_deref(), Some(project_path.as_str()));
- assert!(!home.path().join("skills/review.md").exists());
- let target = project.path().join(".agents/skills/review.md");
- assert_eq!(
- fs::read_to_string(&target).unwrap(),
- "---\nname: Review\ndescription: Check code\n---\n\nDo it.\n"
- );
- assert!(registry
- .list(CapabilityLevel::Global, None)
- .unwrap()
- .is_empty());
- });
- }
-
- #[test]
- fn a_name_collision_rewrites_only_the_documents_name_line() {
- let home = tempdir().unwrap();
- let app = tempdir().unwrap();
- let project = tempdir().unwrap();
- let project_path = project_dir(project.path());
- test_support::with_global_agents(home.path(), || {
- skill_home(home.path());
- fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
- // Extra frontmatter and deliberate body formatting: a renaming move
- // must not reformat the document the user only asked to relocate.
- let original = "---\nname: Review\nlicense: MIT\n---\n\n## Step 1\n\n indented\n";
- fs::write(home.path().join("skills/review.md"), original).unwrap();
- fs::write(
- project.path().join(".agents/skills/review.md"),
- "---\nname: Review\n---\n\nProject copy\n",
- )
- .unwrap();
- let mut registry = UserSkillRegistry::new(app.path());
-
- let moved = registry
- .transfer(
- "review",
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- )
- .unwrap();
-
- assert_eq!(moved.id, "review-2");
- assert_eq!(moved.name, "Review (2)");
- let document =
- fs::read_to_string(project.path().join(".agents/skills/review-2.md")).unwrap();
- assert_eq!(
- document,
- "---\nname: Review (2)\nlicense: MIT\n---\n\n## Step 1\n\n indented\n"
- );
- // The skill that was already there is untouched.
- assert_eq!(
- fs::read_to_string(project.path().join(".agents/skills/review.md")).unwrap(),
- "---\nname: Review\n---\n\nProject copy\n"
- );
- });
- }
-
- #[test]
- fn a_directory_skill_moves_with_its_resources() {
- let home = tempdir().unwrap();
- let app = tempdir().unwrap();
- let project = tempdir().unwrap();
- let project_path = project_dir(project.path());
- test_support::with_global_agents(home.path(), || {
- skill_home(home.path());
- let source = home.path().join("skills/pdf");
- fs::create_dir_all(source.join("templates")).unwrap();
- fs::write(source.join("SKILL.md"), "# PDF\n\nExtract text.\n").unwrap();
- fs::write(source.join("templates/page.html"), "<p>page</p>").unwrap();
- let mut registry = UserSkillRegistry::new(app.path());
-
- let moved = registry
- .transfer(
- "pdf",
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- )
- .unwrap();
-
- assert_eq!(moved.id, "pdf");
- assert!(!source.exists());
- let target = project.path().join(".agents/skills/pdf");
- assert_eq!(
- fs::read_to_string(target.join("SKILL.md")).unwrap(),
- "# PDF\n\nExtract text.\n"
- );
- // The resource beside the document is part of the skill.
- assert_eq!(
- fs::read_to_string(target.join("templates/page.html")).unwrap(),
- "<p>page</p>"
- );
- });
- }
-
- #[test]
- fn a_renamed_directory_skill_keeps_its_resources() {
- let home = tempdir().unwrap();
- let app = tempdir().unwrap();
- let project = tempdir().unwrap();
- let project_path = project_dir(project.path());
- test_support::with_global_agents(home.path(), || {
- skill_home(home.path());
- fs::create_dir_all(project.path().join(".agents/skills/pdf")).unwrap();
- fs::write(
- project.path().join(".agents/skills/pdf/SKILL.md"),
- "# PDF\n\nProject copy.\n",
- )
- .unwrap();
- let source = home.path().join("skills/pdf");
- fs::create_dir_all(&source).unwrap();
- fs::write(source.join("SKILL.md"), "# PDF\n\nGlobal copy.\n").unwrap();
- fs::write(source.join("notes.txt"), "keep me").unwrap();
- let mut registry = UserSkillRegistry::new(app.path());
-
- let moved = registry
- .transfer(
- "pdf",
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- )
- .unwrap();
-
- assert_eq!(moved.id, "pdf-2");
- assert!(!source.exists());
- let target = project.path().join(".agents/skills/pdf-2");
- assert_eq!(
- fs::read_to_string(target.join("notes.txt")).unwrap(),
- "keep me"
- );
- assert_eq!(
- fs::read_to_string(project.path().join(".agents/skills/pdf/SKILL.md")).unwrap(),
- "# PDF\n\nProject copy.\n"
- );
- });
- }
-
- #[test]
- fn a_disabled_project_skill_becomes_the_global_default() {
- let home = tempdir().unwrap();
- let app = tempdir().unwrap();
- let project = tempdir().unwrap();
- let project_path = project_dir(project.path());
- test_support::with_global_agents(home.path(), || {
- skill_home(home.path());
- let mut registry = UserSkillRegistry::new(app.path());
- let mut request = input("Review", "project", Some(&project_path));
- request.enabled = Some(false);
- registry.create(request).unwrap();
-
- let moved = registry
- .transfer(
- "review",
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- )
- .unwrap();
-
- assert_eq!(moved.level.as_deref(), Some("global"));
- assert!(!moved.enabled);
- assert!(home.path().join("skills/review.md").is_file());
- assert!(!project.path().join(".agents/skills/review.md").exists());
- // Off everywhere, because the document is off and its state is now
- // the global default rather than one project's leftover override.
- assert!(!registry.state.enabled(
- SKILL_KIND,
- CapabilityLevel::Global,
- "review",
- Some("/elsewhere")
- ));
- });
- }
-
- #[test]
- fn a_skill_without_frontmatter_gains_a_name_when_it_has_to_rename() {
- let home = tempdir().unwrap();
- let app = tempdir().unwrap();
- let project = tempdir().unwrap();
- let project_path = project_dir(project.path());
- test_support::with_global_agents(home.path(), || {
- skill_home(home.path());
- fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
- // No frontmatter: the display name falls back to the file stem, so a
- // move that must rename has to open a block to carry the new name.
- fs::write(home.path().join("skills/review.md"), "# Review\n\nDo it.\n").unwrap();
- fs::write(
- project.path().join(".agents/skills/review.md"),
- "---\nname: Review\n---\n\nProject copy\n",
- )
- .unwrap();
- let mut registry = UserSkillRegistry::new(app.path());
-
- let moved = registry
- .transfer(
- "review",
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- )
- .unwrap();
- // With no stored name the display name is the file stem, so that is
- // what the suffix is applied to.
- assert_eq!(moved.id, "review-2");
- assert_eq!(moved.name, "review (2)");
- assert_eq!(
- fs::read_to_string(project.path().join(".agents/skills/review-2.md")).unwrap(),
- "---\nname: review (2)\n---\n\n# Review\n\nDo it.\n"
- );
- });
- }
-
- #[test]
- fn placement_uses_the_id_the_scan_will_derive_from_the_name() {
- let directory = tempdir().unwrap();
- let source = record("code-review", "代码审查");
- let existing = vec![record("code-review", "代码审查")];
-
- let placement = plan_skill_placement(&source, directory.path(), true, &existing).unwrap();
- assert_eq!(placement.name, "代码审查 (2)");
- // The rename's slug is `2`, not the file stem the move started from, so
- // that is what both the directory and the next scan will call it.
- assert_eq!(placement.stem, "2");
- let document = skill_document_path(directory.path(), &placement.stem, true);
- assert_eq!(
- capability_id(&placement.name, &document, 64),
- placement.stem
- );
-
- // A flat destination derives the same id from the `.md` stem.
- let placement = plan_skill_placement(&source, directory.path(), false, &existing).unwrap();
- let document = skill_document_path(directory.path(), &placement.stem, false);
- assert_eq!(
- capability_id(&placement.name, &document, 64),
- placement.stem
- );
- }
-
- #[test]
- fn placement_reports_exhaustion_instead_of_reusing_a_taken_name() {
- let directory = tempdir().unwrap();
- let source = record("review", "Review");
- let existing: Vec<UserSkillRecord> = (1..=MAX_ID_SUFFIX)
- .map(|ordinal| {
- record(
- &format!("other-{ordinal}"),
- &display_name_candidate("Review", ordinal, MAX_NAME_CHARS),
- )
- })
- .collect();
- // Every candidate the planner could use is already a displayed name, so
- // there is no collision-free placement and the move must refuse rather
- // than write a duplicate.
- assert!(plan_skill_placement(&source, directory.path(), false, &existing).is_none());
- }
-
- #[test]
- fn a_chinese_named_skill_moves_without_hiding_the_other_levels_copy() {
- let home = tempdir().unwrap();
- let app = tempdir().unwrap();
- let project = tempdir().unwrap();
- let project_path = project_dir(project.path());
- test_support::with_global_agents(home.path(), || {
- skill_home(home.path());
- fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
- // Both names slug to nothing, so each document's id comes from its
- // file stem — while the renamed candidate `代码审查 (2)` slugs to
- // `2`, which is nothing like the stem the old move would have used.
- fs::write(
- home.path().join("skills/code-review.md"),
- "---\nname: 代码审查\n---\n\nGlobal copy.\n",
- )
- .unwrap();
- fs::write(
- project.path().join(".agents/skills/code-review.md"),
- "---\nname: 代码审查\n---\n\nProject copy.\n",
- )
- .unwrap();
- let mut registry = UserSkillRegistry::new(app.path());
-
- let moved = registry
- .transfer(
- "code-review",
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- )
- .unwrap();
-
- assert_eq!(moved.id, "2");
- assert_eq!(moved.name, "代码审查 (2)");
- assert!(!home.path().join("skills/code-review.md").exists());
- assert_eq!(
- fs::read_to_string(project.path().join(".agents/skills/2.md")).unwrap(),
- "---\nname: 代码审查 (2)\n---\n\nGlobal copy.\n"
- );
- // The project's own copy is untouched and both documents are listed
- // under distinct ids and names.
- assert_eq!(
- fs::read_to_string(project.path().join(".agents/skills/code-review.md")).unwrap(),
- "---\nname: 代码审查\n---\n\nProject copy.\n"
- );
- let listed = registry
- .list(CapabilityLevel::Project, Some(&project_path))
- .unwrap();
- assert_eq!(listed.len(), 2);
- assert_unique_records(&listed);
- assert!(listed.iter().any(|record| record.name == "代码审查"));
- assert!(listed.iter().any(|record| record.name == "代码审查 (2)"));
-
- // The same document moves back to the global level under its new
- // name, keeping the id the scan gave it.
- let back = registry
- .transfer(
- "2",
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- )
- .unwrap();
- assert_eq!(back.id, "2");
- assert_eq!(back.name, "代码审查 (2)");
- assert!(home.path().join("skills/2.md").is_file());
- assert_unique_records(
- &registry
- .list(CapabilityLevel::Project, Some(&project_path))
- .unwrap(),
- );
- });
- }
-
- #[test]
- fn a_names_slug_is_not_used_when_that_id_belongs_to_another_document() {
- let home = tempdir().unwrap();
- let app = tempdir().unwrap();
- let project = tempdir().unwrap();
- let project_path = project_dir(project.path());
- test_support::with_global_agents(home.path(), || {
- skill_home(home.path());
- fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
- fs::write(
- home.path().join("skills/code-review.md"),
- "---\nname: 代码审查\n---\n\nGlobal copy.\n",
- )
- .unwrap();
- fs::write(
- project.path().join(".agents/skills/code-review.md"),
- "---\nname: 代码审查\n---\n\nProject copy.\n",
- )
- .unwrap();
- // This document's id is exactly the slug the renamed candidate
- // `代码审查 (2)` would produce, so that candidate cannot be used.
- fs::write(
- project.path().join(".agents/skills/2.md"),
- "---\nname: 2\n---\n\nTakes the id 2.\n",
- )
- .unwrap();
- let mut registry = UserSkillRegistry::new(app.path());
-
- let moved = registry
- .transfer(
- "code-review",
- &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
- &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
- )
- .unwrap();
-
- assert_eq!(moved.name, "代码审查 (3)");
- assert_eq!(moved.id, "3");
- assert!(project.path().join(".agents/skills/3.md").is_file());
- assert_eq!(
- fs::read_to_string(project.path().join(".agents/skills/2.md")).unwrap(),
- "---\nname: 2\n---\n\nTakes the id 2.\n"
- );
- let listed = registry
- .list(CapabilityLevel::Project, Some(&project_path))
- .unwrap();
- assert_eq!(listed.len(), 3);
- assert_unique_records(&listed);
- });
- }
- #[test]
- fn rewriting_a_name_keeps_the_frontmatter_shaped_document_intact() {
- // The helper is unit-tested directly because it is the only place a move
- // edits a document, and every byte it does not touch is a byte the user
- // gets to keep.
- let with_extra_fields =
- "---\nlicense: MIT\nname: Review\nallowed-tools: Read\n---\n\nBody\n";
- assert_eq!(
- rewrite_document_name(with_extra_fields, "Review (2)"),
- "---\nlicense: MIT\nname: Review (2)\nallowed-tools: Read\n---\n\nBody\n"
- );
- assert_eq!(
- rewrite_document_name("---\r\nname: A\r\n---\r\n\r\nBody\r\n", "B"),
- "---\nname: B\n---\r\n\r\nBody\r\n"
- );
- assert_eq!(
- rewrite_document_name("no frontmatter\n", "B"),
- "---\nname: B\n---\n\nno frontmatter\n"
- );
- assert_eq!(
- rewrite_document_name("---\nname: A\nnever closed\n", "B"),
- "---\nname: B\n---\n\n---\nname: A\nnever closed\n"
- );
- // A newline in the name would break the block it is written into.
- assert_eq!(
- rewrite_document_name("---\nname: A\n---\n\nBody\n", "Two\nLines"),
- "---\nname: Two Lines\n---\n\nBody\n"
- );
- // The parser keeps the *last* `name:` line, so a stale second one must
- // be dropped: keeping it would make the old name win again on the next
- // scan, silently defeating the rename.
- assert_eq!(
- rewrite_document_name("---\nname: A\nname: B\n---\n\nBody\n", "C"),
- "---\nname: C\n---\n\nBody\n"
- );
- assert_eq!(
- rewrite_document_name("---\nname: A\nlicense: MIT\nname: B\n---\n\nBody\n", "C"),
- "---\nname: C\nlicense: MIT\n---\n\nBody\n"
- );
- // A first line that only trims to `---` still opens frontmatter. Not
- // recognizing it would copy the old block into the new body, leaving
- // two frontmatter blocks in the document.
- assert_eq!(
- rewrite_document_name("--- \nname: A\n---\n\nBody\n", "C"),
- "---\nname: C\n---\n\nBody\n"
- );
- assert_eq!(
- rewrite_document_name("--- \r\nname: A\r\n---\r\n\r\nBody\r\n", "C"),
- "---\nname: C\n---\r\n\r\nBody\r\n"
- );
- // An indented `name:` is a nested map value, not the document's name.
- assert_eq!(
- rewrite_document_name("---\nmeta:\n name: A\nname: B\n---\n\nBody\n", "C"),
- "---\nmeta:\n name: A\nname: C\n---\n\nBody\n"
- );
- }
-}
+mod tests;
diff --git a/crates/host-core/src/user_skills/tests.rs b/crates/host-core/src/user_skills/tests.rs
new file mode 100644
index 000000000..74879b352
--- /dev/null
+++ b/crates/host-core/src/user_skills/tests.rs
@@ -0,0 +1,670 @@
+use super::*;
+use crate::agent_capabilities::test_support;
+use tempfile::tempdir;
+
+fn input(name: &str, level: &str, project_path: Option<&str>) -> UserSkillInput {
+ UserSkillInput {
+ name: Some(name.into()),
+ level: Some(level.into()),
+ project_path: project_path.map(str::to_string),
+ description: Some("Check the relevant files".into()),
+ body: Some("Do the thing.".into()),
+ ..Default::default()
+ }
+}
+
+#[test]
+fn imports_one_file_into_the_selected_agents_directory() {
+ let app = tempdir().unwrap();
+ let source = app.path().join("incoming.md");
+ let raw = "---\nname: Review\ndescription: Check code\n---\n\nDo it.\n";
+ fs::write(&source, raw).unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+ let record = registry
+ .import(
+ source.to_str().unwrap(),
+ input("Ignored", "project", Some(app.path().to_str().unwrap())),
+ )
+ .unwrap();
+ let target = app.path().join(".agents/skills/review.md");
+ assert_eq!(record.level.as_deref(), Some("project"));
+ let normalized_project =
+ crate::agent_capabilities::normalize_project_path(app.path().to_str().unwrap());
+ let expected = crate::agent_capabilities::capability_dir(
+ CapabilityLevel::Project,
+ Some(&normalized_project),
+ "skills",
+ )
+ .unwrap()
+ .join("review.md");
+ assert_eq!(record.path, expected.to_string_lossy());
+ assert_eq!(fs::read_to_string(target).unwrap(), raw);
+ assert!(source.is_file());
+}
+
+#[test]
+fn project_skills_shadow_global_skills_by_name() {
+ let app = tempdir().unwrap();
+ let global = app.path().join("global");
+ let project = app.path().join("project");
+ fs::create_dir_all(global.join("skills")).unwrap();
+ fs::create_dir_all(project.join(".agents/skills")).unwrap();
+ fs::write(
+ global.join("skills/review.md"),
+ "---\nname: Review\n---\n\nGlobal\n",
+ )
+ .unwrap();
+ fs::write(
+ project.join(".agents/skills/review.md"),
+ "---\nname: Review\n---\n\nProject\n",
+ )
+ .unwrap();
+ let (fields, body) =
+ parse_front_matter(&fs::read_to_string(project.join(".agents/skills/review.md")).unwrap());
+ assert_eq!(fields.get("name").map(String::as_str), Some("Review"));
+ assert_eq!(body, "Project");
+}
+
+#[test]
+fn disabled_project_skill_shadows_global_skill() {
+ let global = UserSkillRecord {
+ id: "review".into(),
+ name: "Review".into(),
+ level: Some("global".into()),
+ project_path: None,
+ description: Some("Global".into()),
+ enabled: true,
+ scope: ActivationScope::default(),
+ source: "imported".into(),
+ path: "/global/review.md".into(),
+ size_bytes: 1,
+ created_at: String::new(),
+ updated_at: String::new(),
+ };
+ let mut project = global.clone();
+ project.level = Some("project".into());
+ project.project_path = Some("/repo".into());
+ project.enabled = false;
+
+ let active = merge_active_records(vec![global.clone()], vec![project]);
+ assert!(active.is_empty());
+
+ let mut project = global.clone();
+ project.level = Some("project".into());
+ project.project_path = Some("/repo".into());
+ project.path = "/repo/.agents/skills/review.md".into();
+ let active = merge_active_records(vec![global], vec![project.clone()]);
+ assert_eq!(active, vec![project]);
+}
+
+#[test]
+fn capability_state_is_not_written_into_skill_documents() {
+ let app = tempdir().unwrap();
+ let mut state = CapabilityState::new(app.path(), SKILL_KIND);
+ state
+ .set_enabled(
+ SKILL_KIND,
+ CapabilityLevel::Project,
+ "review",
+ Some("/repo"),
+ false,
+ )
+ .unwrap();
+ assert!(!app
+ .path()
+ .join("agent-capabilities/skills.json")
+ .to_string_lossy()
+ .contains(".agents"));
+}
+
+#[test]
+fn import_uses_parent_directory_when_name_is_not_ascii() {
+ let app = tempdir().unwrap();
+ let source_dir = app.path().join("incoming/code-review");
+ fs::create_dir_all(&source_dir).unwrap();
+ let source = source_dir.join("SKILL.md");
+ fs::write(
+ &source,
+ "---\nname: 代码审查\ndescription: >\n Review diffs before merge.\n---\n\nCheck the patch.\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+ let record = registry
+ .import(
+ source.to_str().unwrap(),
+ input("Ignored", "project", Some(app.path().to_str().unwrap())),
+ )
+ .unwrap();
+ assert_eq!(record.id, "code-review");
+ assert_eq!(record.name, "代码审查");
+ assert_eq!(
+ record.description.as_deref(),
+ Some("Review diffs before merge.")
+ );
+ let listed = registry
+ .list(CapabilityLevel::Project, Some(app.path().to_str().unwrap()))
+ .unwrap();
+ assert_eq!(listed.len(), 1);
+ assert_eq!(listed[0].id, "code-review");
+ assert_eq!(listed[0].name, "代码审查");
+}
+
+#[test]
+fn directory_skills_do_not_collide_on_the_skill_file_stem() {
+ let app = tempdir().unwrap();
+ let project = app.path().to_str().unwrap();
+ fs::create_dir_all(app.path().join(".agents/skills/pdf")).unwrap();
+ fs::create_dir_all(app.path().join(".agents/skills/docx")).unwrap();
+ fs::write(
+ app.path().join(".agents/skills/pdf/SKILL.md"),
+ "# PDF\n\nExtract text.\n",
+ )
+ .unwrap();
+ fs::write(
+ app.path().join(".agents/skills/docx/SKILL.md"),
+ "# DOCX\n\nEdit documents.\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+ let listed = registry
+ .list(CapabilityLevel::Project, Some(project))
+ .unwrap();
+ let ids: Vec<_> = listed.iter().map(|record| record.id.as_str()).collect();
+ assert_eq!(ids, vec!["docx", "pdf"]);
+}
+
+/// A global skill document plus the project directory it can move into.
+fn skill_home(home: &Path) {
+ fs::create_dir_all(home.join("skills")).unwrap();
+}
+
+fn project_dir(project: &Path) -> String {
+ project.to_str().unwrap().to_string()
+}
+
+fn record(id: &str, name: &str) -> UserSkillRecord {
+ UserSkillRecord {
+ id: id.into(),
+ name: name.into(),
+ level: None,
+ project_path: None,
+ description: None,
+ enabled: true,
+ scope: ActivationScope::default(),
+ source: "imported".into(),
+ path: String::new(),
+ size_bytes: 0,
+ created_at: String::new(),
+ updated_at: String::new(),
+ }
+}
+
+/// A level may never list two records with the same id or the same name:
+/// either collision makes one of them disappear from the catalog.
+fn assert_unique_records(records: &[UserSkillRecord]) {
+ let ids: HashSet<&str> = records.iter().map(|record| record.id.as_str()).collect();
+ let names: HashSet<String> = records
+ .iter()
+ .map(|record| record.name.to_lowercase())
+ .collect();
+ assert_eq!(ids.len(), records.len(), "duplicate ids: {records:?}");
+ assert_eq!(names.len(), records.len(), "duplicate names: {records:?}");
+}
+
+#[test]
+fn a_global_skill_moves_into_a_project() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::write(
+ home.path().join("skills/review.md"),
+ "---\nname: Review\ndescription: Check code\n---\n\nDo it.\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "review",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "review");
+ assert_eq!(moved.level.as_deref(), Some("project"));
+ assert_eq!(moved.project_path.as_deref(), Some(project_path.as_str()));
+ assert!(!home.path().join("skills/review.md").exists());
+ let target = project.path().join(".agents/skills/review.md");
+ assert_eq!(
+ fs::read_to_string(&target).unwrap(),
+ "---\nname: Review\ndescription: Check code\n---\n\nDo it.\n"
+ );
+ assert!(registry
+ .list(CapabilityLevel::Global, None)
+ .unwrap()
+ .is_empty());
+ });
+}
+
+#[test]
+fn a_name_collision_rewrites_only_the_documents_name_line() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
+ // Extra frontmatter and deliberate body formatting: a renaming move
+ // must not reformat the document the user only asked to relocate.
+ let original = "---\nname: Review\nlicense: MIT\n---\n\n## Step 1\n\n indented\n";
+ fs::write(home.path().join("skills/review.md"), original).unwrap();
+ fs::write(
+ project.path().join(".agents/skills/review.md"),
+ "---\nname: Review\n---\n\nProject copy\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "review",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "review-2");
+ assert_eq!(moved.name, "Review (2)");
+ let document =
+ fs::read_to_string(project.path().join(".agents/skills/review-2.md")).unwrap();
+ assert_eq!(
+ document,
+ "---\nname: Review (2)\nlicense: MIT\n---\n\n## Step 1\n\n indented\n"
+ );
+ // The skill that was already there is untouched.
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/review.md")).unwrap(),
+ "---\nname: Review\n---\n\nProject copy\n"
+ );
+ });
+}
+
+#[test]
+fn a_directory_skill_moves_with_its_resources() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ let source = home.path().join("skills/pdf");
+ fs::create_dir_all(source.join("templates")).unwrap();
+ fs::write(source.join("SKILL.md"), "# PDF\n\nExtract text.\n").unwrap();
+ fs::write(source.join("templates/page.html"), "<p>page</p>").unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "pdf",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "pdf");
+ assert!(!source.exists());
+ let target = project.path().join(".agents/skills/pdf");
+ assert_eq!(
+ fs::read_to_string(target.join("SKILL.md")).unwrap(),
+ "# PDF\n\nExtract text.\n"
+ );
+ // The resource beside the document is part of the skill.
+ assert_eq!(
+ fs::read_to_string(target.join("templates/page.html")).unwrap(),
+ "<p>page</p>"
+ );
+ });
+}
+
+#[test]
+fn a_renamed_directory_skill_keeps_its_resources() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::create_dir_all(project.path().join(".agents/skills/pdf")).unwrap();
+ fs::write(
+ project.path().join(".agents/skills/pdf/SKILL.md"),
+ "# PDF\n\nProject copy.\n",
+ )
+ .unwrap();
+ let source = home.path().join("skills/pdf");
+ fs::create_dir_all(&source).unwrap();
+ fs::write(source.join("SKILL.md"), "# PDF\n\nGlobal copy.\n").unwrap();
+ fs::write(source.join("notes.txt"), "keep me").unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "pdf",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "pdf-2");
+ assert!(!source.exists());
+ let target = project.path().join(".agents/skills/pdf-2");
+ assert_eq!(
+ fs::read_to_string(target.join("notes.txt")).unwrap(),
+ "keep me"
+ );
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/pdf/SKILL.md")).unwrap(),
+ "# PDF\n\nProject copy.\n"
+ );
+ });
+}
+
+#[test]
+fn a_disabled_project_skill_becomes_the_global_default() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ let mut registry = UserSkillRegistry::new(app.path());
+ let mut request = input("Review", "project", Some(&project_path));
+ request.enabled = Some(false);
+ registry.create(request).unwrap();
+
+ let moved = registry
+ .transfer(
+ "review",
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.level.as_deref(), Some("global"));
+ assert!(!moved.enabled);
+ assert!(home.path().join("skills/review.md").is_file());
+ assert!(!project.path().join(".agents/skills/review.md").exists());
+ // Off everywhere, because the document is off and its state is now
+ // the global default rather than one project's leftover override.
+ assert!(!registry.state.enabled(
+ SKILL_KIND,
+ CapabilityLevel::Global,
+ "review",
+ Some("/elsewhere")
+ ));
+ });
+}
+
+#[test]
+fn a_skill_without_frontmatter_gains_a_name_when_it_has_to_rename() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
+ // No frontmatter: the display name falls back to the file stem, so a
+ // move that must rename has to open a block to carry the new name.
+ fs::write(home.path().join("skills/review.md"), "# Review\n\nDo it.\n").unwrap();
+ fs::write(
+ project.path().join(".agents/skills/review.md"),
+ "---\nname: Review\n---\n\nProject copy\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "review",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+ // With no stored name the display name is the file stem, so that is
+ // what the suffix is applied to.
+ assert_eq!(moved.id, "review-2");
+ assert_eq!(moved.name, "review (2)");
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/review-2.md")).unwrap(),
+ "---\nname: review (2)\n---\n\n# Review\n\nDo it.\n"
+ );
+ });
+}
+
+#[test]
+fn placement_uses_the_id_the_scan_will_derive_from_the_name() {
+ let directory = tempdir().unwrap();
+ let source = record("code-review", "代码审查");
+ let existing = vec![record("code-review", "代码审查")];
+
+ let placement = plan_skill_placement(&source, directory.path(), true, &existing).unwrap();
+ assert_eq!(placement.name, "代码审查 (2)");
+ // The rename's slug is `2`, not the file stem the move started from, so
+ // that is what both the directory and the next scan will call it.
+ assert_eq!(placement.stem, "2");
+ let document = skill_document_path(directory.path(), &placement.stem, true);
+ assert_eq!(
+ capability_id(&placement.name, &document, 64),
+ placement.stem
+ );
+
+ // A flat destination derives the same id from the `.md` stem.
+ let placement = plan_skill_placement(&source, directory.path(), false, &existing).unwrap();
+ let document = skill_document_path(directory.path(), &placement.stem, false);
+ assert_eq!(
+ capability_id(&placement.name, &document, 64),
+ placement.stem
+ );
+}
+
+#[test]
+fn placement_reports_exhaustion_instead_of_reusing_a_taken_name() {
+ let directory = tempdir().unwrap();
+ let source = record("review", "Review");
+ let existing: Vec<UserSkillRecord> = (1..=MAX_ID_SUFFIX)
+ .map(|ordinal| {
+ record(
+ &format!("other-{ordinal}"),
+ &display_name_candidate("Review", ordinal, MAX_NAME_CHARS),
+ )
+ })
+ .collect();
+ // Every candidate the planner could use is already a displayed name, so
+ // there is no collision-free placement and the move must refuse rather
+ // than write a duplicate.
+ assert!(plan_skill_placement(&source, directory.path(), false, &existing).is_none());
+}
+
+#[test]
+fn a_chinese_named_skill_moves_without_hiding_the_other_levels_copy() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
+ // Both names slug to nothing, so each document's id comes from its
+ // file stem — while the renamed candidate `代码审查 (2)` slugs to
+ // `2`, which is nothing like the stem the old move would have used.
+ fs::write(
+ home.path().join("skills/code-review.md"),
+ "---\nname: 代码审查\n---\n\nGlobal copy.\n",
+ )
+ .unwrap();
+ fs::write(
+ project.path().join(".agents/skills/code-review.md"),
+ "---\nname: 代码审查\n---\n\nProject copy.\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "code-review",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.id, "2");
+ assert_eq!(moved.name, "代码审查 (2)");
+ assert!(!home.path().join("skills/code-review.md").exists());
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/2.md")).unwrap(),
+ "---\nname: 代码审查 (2)\n---\n\nGlobal copy.\n"
+ );
+ // The project's own copy is untouched and both documents are listed
+ // under distinct ids and names.
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/code-review.md")).unwrap(),
+ "---\nname: 代码审查\n---\n\nProject copy.\n"
+ );
+ let listed = registry
+ .list(CapabilityLevel::Project, Some(&project_path))
+ .unwrap();
+ assert_eq!(listed.len(), 2);
+ assert_unique_records(&listed);
+ assert!(listed.iter().any(|record| record.name == "代码审查"));
+ assert!(listed.iter().any(|record| record.name == "代码审查 (2)"));
+
+ // The same document moves back to the global level under its new
+ // name, keeping the id the scan gave it.
+ let back = registry
+ .transfer(
+ "2",
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ )
+ .unwrap();
+ assert_eq!(back.id, "2");
+ assert_eq!(back.name, "代码审查 (2)");
+ assert!(home.path().join("skills/2.md").is_file());
+ assert_unique_records(
+ &registry
+ .list(CapabilityLevel::Project, Some(&project_path))
+ .unwrap(),
+ );
+ });
+}
+
+#[test]
+fn a_names_slug_is_not_used_when_that_id_belongs_to_another_document() {
+ let home = tempdir().unwrap();
+ let app = tempdir().unwrap();
+ let project = tempdir().unwrap();
+ let project_path = project_dir(project.path());
+ test_support::with_global_agents(home.path(), || {
+ skill_home(home.path());
+ fs::create_dir_all(project.path().join(".agents/skills")).unwrap();
+ fs::write(
+ home.path().join("skills/code-review.md"),
+ "---\nname: 代码审查\n---\n\nGlobal copy.\n",
+ )
+ .unwrap();
+ fs::write(
+ project.path().join(".agents/skills/code-review.md"),
+ "---\nname: 代码审查\n---\n\nProject copy.\n",
+ )
+ .unwrap();
+ // This document's id is exactly the slug the renamed candidate
+ // `代码审查 (2)` would produce, so that candidate cannot be used.
+ fs::write(
+ project.path().join(".agents/skills/2.md"),
+ "---\nname: 2\n---\n\nTakes the id 2.\n",
+ )
+ .unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+
+ let moved = registry
+ .transfer(
+ "code-review",
+ &CapabilityTarget::new(CapabilityLevel::Global, None).unwrap(),
+ &CapabilityTarget::new(CapabilityLevel::Project, Some(&project_path)).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(moved.name, "代码审查 (3)");
+ assert_eq!(moved.id, "3");
+ assert!(project.path().join(".agents/skills/3.md").is_file());
+ assert_eq!(
+ fs::read_to_string(project.path().join(".agents/skills/2.md")).unwrap(),
+ "---\nname: 2\n---\n\nTakes the id 2.\n"
+ );
+ let listed = registry
+ .list(CapabilityLevel::Project, Some(&project_path))
+ .unwrap();
+ assert_eq!(listed.len(), 3);
+ assert_unique_records(&listed);
+ });
+}
+#[test]
+fn rewriting_a_name_keeps_the_frontmatter_shaped_document_intact() {
+ // The helper is unit-tested directly because it is the only place a move
+ // edits a document, and every byte it does not touch is a byte the user
+ // gets to keep.
+ let with_extra_fields = "---\nlicense: MIT\nname: Review\nallowed-tools: Read\n---\n\nBody\n";
+ assert_eq!(
+ rewrite_document_name(with_extra_fields, "Review (2)"),
+ "---\nlicense: MIT\nname: Review (2)\nallowed-tools: Read\n---\n\nBody\n"
+ );
+ assert_eq!(
+ rewrite_document_name("---\r\nname: A\r\n---\r\n\r\nBody\r\n", "B"),
+ "---\nname: B\n---\r\n\r\nBody\r\n"
+ );
+ assert_eq!(
+ rewrite_document_name("no frontmatter\n", "B"),
+ "---\nname: B\n---\n\nno frontmatter\n"
+ );
+ assert_eq!(
+ rewrite_document_name("---\nname: A\nnever closed\n", "B"),
+ "---\nname: B\n---\n\n---\nname: A\nnever closed\n"
+ );
+ // A newline in the name would break the block it is written into.
+ assert_eq!(
+ rewrite_document_name("---\nname: A\n---\n\nBody\n", "Two\nLines"),
+ "---\nname: Two Lines\n---\n\nBody\n"
+ );
+ // The parser keeps the *last* `name:` line, so a stale second one must
+ // be dropped: keeping it would make the old name win again on the next
+ // scan, silently defeating the rename.
+ assert_eq!(
+ rewrite_document_name("---\nname: A\nname: B\n---\n\nBody\n", "C"),
+ "---\nname: C\n---\n\nBody\n"
+ );
+ assert_eq!(
+ rewrite_document_name("---\nname: A\nlicense: MIT\nname: B\n---\n\nBody\n", "C"),
+ "---\nname: C\nlicense: MIT\n---\n\nBody\n"
+ );
+ // A first line that only trims to `---` still opens frontmatter. Not
+ // recognizing it would copy the old block into the new body, leaving
+ // two frontmatter blocks in the document.
+ assert_eq!(
+ rewrite_document_name("--- \nname: A\n---\n\nBody\n", "C"),
+ "---\nname: C\n---\n\nBody\n"
+ );
+ assert_eq!(
+ rewrite_document_name("--- \r\nname: A\r\n---\r\n\r\nBody\r\n", "C"),
+ "---\nname: C\n---\r\n\r\nBody\r\n"
+ );
+ // An indented `name:` is a nested map value, not the document's name.
+ assert_eq!(
+ rewrite_document_name("---\nmeta:\n name: A\nname: B\n---\n\nBody\n", "C"),
+ "---\nmeta:\n name: A\nname: C\n---\n\nBody\n"
+ );
+}