| 1 | use tempfile::TempDir; |
| 2 | |
| 3 | #[test] |
| 4 | fn frontmatter_handles_bom_exact_fences_and_plain_continuations() { |
| 5 | let content = "\u{feff}---\r\nname: demo\r\ndescription: Deploy apps --- safely\r\n for X or Y: really\r\ninvocation: user\r\n---\r\n# Body\r\n"; |
| 6 | let (metadata, body) = codewhale_skill_install::frontmatter::parse_frontmatter(content) |
| 7 | .unwrap() |
| 8 | .unwrap(); |
| 9 | assert_eq!(metadata["name"], "demo"); |
| 10 | assert_eq!( |
| 11 | metadata["description"], |
| 12 | "Deploy apps --- safely for X or Y: really" |
| 13 | ); |
| 14 | assert_eq!(metadata.len(), 3, "continuation text is not a new key"); |
| 15 | assert_eq!(body.trim(), "# Body"); |
| 16 | assert!( |
| 17 | codewhale_skill_install::frontmatter::parse_frontmatter("---not a fence\n# Body") |
| 18 | .unwrap() |
| 19 | .is_none() |
| 20 | ); |
| 21 | assert!( |
| 22 | codewhale_skill_install::frontmatter::parse_frontmatter( |
| 23 | "---\nname: demo\ndescription: inline --- only" |
| 24 | ) |
| 25 | .is_err() |
| 26 | ); |
| 27 | } |
| 28 | |
| 29 | #[test] |
| 30 | fn frontmatter_block_indentation_is_character_safe_and_keeps_nested_fences() { |
| 31 | for indicator in ["|", ">"] { |
| 32 | let content = format!( |
| 33 | "---\nname: demo\ndescription: {indicator}\n first\n\u{3000}wide\n \u{a0}mixed\n ---\n nested\n---\nbody" |
| 34 | ); |
| 35 | let (metadata, body) = codewhale_skill_install::frontmatter::parse_frontmatter(&content) |
| 36 | .unwrap() |
| 37 | .unwrap(); |
| 38 | let expected = if indicator == "|" { |
| 39 | "first\nwide\nmixed\n---\n nested" |
| 40 | } else { |
| 41 | "first wide mixed --- nested" |
| 42 | }; |
| 43 | assert_eq!(metadata["description"], expected); |
| 44 | assert_eq!(body.trim(), "body"); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | #[test] |
| 49 | fn unavailable_home_fallbacks_are_fresh_nonexistent_paths() { |
| 50 | let first = super::unavailable_home_root(); |
| 51 | let second = super::unavailable_home_root(); |
| 52 | assert_ne!(first, second); |
| 53 | assert!(!first.exists()); |
| 54 | assert!(!second.exists()); |
| 55 | assert!(first.starts_with(std::env::temp_dir())); |
| 56 | assert_ne!(first, std::path::Path::new("/tmp/codewhale")); |
| 57 | } |
| 58 | |
| 59 | fn create_skill_dir(tmpdir: &TempDir, skill_name: &str, skill_content: &str) { |
| 60 | let skill_dir = tmpdir.path().join("skills").join(skill_name); |
| 61 | std::fs::create_dir_all(&skill_dir).unwrap(); |
| 62 | std::fs::write(skill_dir.join("SKILL.md"), skill_content).unwrap(); |
| 63 | } |
| 64 | |
| 65 | #[test] |
| 66 | fn unicode_skill_identity_preserves_bodies_and_legacy_activation() { |
| 67 | let tmp = TempDir::new().unwrap(); |
| 68 | let names = [ |
| 69 | "技能", |
| 70 | "分析", |
| 71 | "PDF阅读", |
| 72 | "PDF签名", |
| 73 | "skill", |
| 74 | "pdf", |
| 75 | "Café", |
| 76 | "Cafe\u{301}", |
| 77 | ]; |
| 78 | for (index, raw) in names.iter().enumerate() { |
| 79 | create_skill_dir( |
| 80 | &tmp, |
| 81 | &format!("source-{index}"), |
| 82 | &format!("---\nname: {raw}\ndescription: identity fixture\n---\nbody {index}"), |
| 83 | ); |
| 84 | } |
| 85 | let registry = super::SkillRegistry::discover(&tmp.path().join("skills")); |
| 86 | assert_eq!( |
| 87 | registry.len(), |
| 88 | names.len(), |
| 89 | "colliding old slugs must not hide bodies" |
| 90 | ); |
| 91 | for (index, raw) in names.iter().enumerate() { |
| 92 | let skill = registry.get(raw).unwrap(); |
| 93 | assert_eq!(skill.body, format!("body {index}")); |
| 94 | assert!(super::is_valid_skill_name(&skill.name)); |
| 95 | assert_eq!(registry.get(&skill.name).unwrap().body, skill.body); |
| 96 | assert_eq!( |
| 97 | super::normalize_skill_name_for_lookup(&skill.name), |
| 98 | skill.name |
| 99 | ); |
| 100 | assert!(skill.path.ends_with(format!("source-{index}/SKILL.md"))); |
| 101 | } |
| 102 | assert_eq!(registry.get("skill").unwrap().name, "skill"); |
| 103 | assert_eq!(registry.get("pdf阅读").unwrap().body, "body 2"); |
| 104 | assert_ne!( |
| 105 | registry.get("Café").unwrap().name, |
| 106 | registry.get("Cafe\u{301}").unwrap().name |
| 107 | ); |
| 108 | let long = format!("{}技能", "a".repeat(100)); |
| 109 | assert_eq!(super::normalize_skill_name_for_lookup(&long).len(), 64); |
| 110 | assert!( |
| 111 | registry |
| 112 | .warnings() |
| 113 | .iter() |
| 114 | .all(|warning| warning.contains("differs from directory")), |
| 115 | "{:?}", |
| 116 | registry.warnings() |
| 117 | ); |
| 118 | let mut malformed = registry.get("技能").unwrap().clone(); |
| 119 | malformed.name = "bad\u{1}技能".to_string(); |
| 120 | let mut validation = super::SkillRegistry::default(); |
| 121 | validation.normalize_skill_name(&mut malformed, std::path::Path::new("SKILL.md")); |
| 122 | assert_eq!( |
| 123 | validation.warnings().len(), |
| 124 | 1, |
| 125 | "control bytes remain invalid" |
| 126 | ); |
| 127 | |
| 128 | let path = tmp.path().join("skills_state.toml"); |
| 129 | let original = b"disabled = [\"skill\", \"pdf\"]\n"; |
| 130 | std::fs::write(&path, original).unwrap(); |
| 131 | let filtered = registry.clone().into_enabled_with_state( |
| 132 | codewhale_runtime::skill_state::SkillStateStore::load_from(path.clone()), |
| 133 | ); |
| 134 | assert_eq!(filtered.len(), 2); |
| 135 | assert!(filtered.get("技能").is_none()); |
| 136 | assert_eq!(std::fs::read(&path).unwrap(), original); |
| 137 | let mut state = |
| 138 | codewhale_runtime::skill_state::SkillStateStore::load_from(path.clone()).unwrap(); |
| 139 | state |
| 140 | .set_enabled(®istry.get("技能").unwrap().name, true) |
| 141 | .unwrap(); |
| 142 | state.set_enabled("skill", true).unwrap(); |
| 143 | let filtered = registry.into_enabled_with_state(Ok(state)); |
| 144 | assert_eq!(filtered.get("技能").unwrap().body, "body 0"); |
| 145 | assert_eq!(filtered.get("skill").unwrap().body, "body 4"); |
| 146 | for hidden in ["分析", "PDF阅读", "PDF签名", "pdf"] { |
| 147 | assert!(filtered.get(hidden).is_none(), "must not revive {hidden}"); |
| 148 | } |
| 149 | let rendered = super::render_skills_block(&filtered, "en", tmp.path()).unwrap(); |
| 150 | assert!(rendered.contains(&filtered.get("技能").unwrap().name)); |
| 151 | assert!(!rendered.contains("body 1")); |
| 152 | } |
| 153 | |
| 154 | #[test] |
| 155 | fn unicode_plugin_identity_keeps_exact_namespaces_and_reviewed_metadata() { |
| 156 | let tmp = TempDir::new().unwrap(); |
| 157 | let config = codewhale_plugins::discovery::DiscoveryConfig { |
| 158 | workspace: tmp.path().join("workspace"), |
| 159 | user_plugins_dir: tmp.path().join("plugins"), |
| 160 | workspace_plugins_dir: tmp.path().join("workspace-plugins"), |
| 161 | builtin_plugin_dirs: Vec::new(), |
| 162 | state_path: tmp.path().join("plugin-state/state.json"), |
| 163 | }; |
| 164 | for namespace in ["team.plugin", "team-plugin"] { |
| 165 | let root = config.user_plugins_dir.join(namespace); |
| 166 | std::fs::create_dir_all(&root).unwrap(); |
| 167 | std::fs::write( |
| 168 | root.join("plugin.json"), |
| 169 | serde_json::json!({ |
| 170 | "$schema": "https://agent-plugins.org/schemas/plugin.json", |
| 171 | "name": namespace, |
| 172 | "version": "1.0.0" |
| 173 | }) |
| 174 | .to_string(), |
| 175 | ) |
| 176 | .unwrap(); |
| 177 | for name in ["技能", "分析", "skill"] { |
| 178 | write_skill( |
| 179 | &root.join("skills"), |
| 180 | name, |
| 181 | "reviewed identity", |
| 182 | &format!("{namespace} {name}"), |
| 183 | ); |
| 184 | } |
| 185 | } |
| 186 | let mut plugins = codewhale_plugins::discovery::discover_with_config(&config); |
| 187 | assert!(plugins.validation_is_clean(), "{:?}", plugins.diagnostics()); |
| 188 | let mut registry = super::SkillRegistry::default(); |
| 189 | super::merge_active_plugin_skills(&mut registry, &plugins); |
| 190 | assert!(registry.is_empty()); |
| 191 | for namespace in ["team.plugin", "team-plugin"] { |
| 192 | plugins.trust(namespace).unwrap(); |
| 193 | plugins.enable(namespace).unwrap_or_else(|error| { |
| 194 | panic!("{error}: {:?}", plugins.get(namespace).unwrap().diagnostics) |
| 195 | }); |
| 196 | let plugin = plugins.get(namespace).unwrap(); |
| 197 | let unicode = plugin |
| 198 | .skill_snapshots |
| 199 | .iter() |
| 200 | .find(|s| s.body == format!("{namespace} 技能")) |
| 201 | .unwrap(); |
| 202 | assert_eq!(unicode.legacy_activation_name.as_deref(), Some("skill")); |
| 203 | assert!(!unicode.source_hash.is_empty()); |
| 204 | } |
| 205 | super::merge_active_plugin_skills(&mut registry, &plugins); |
| 206 | assert_eq!(registry.len(), 6); |
| 207 | let dotted = registry.get("TEAM.PLUGIN:技能").unwrap(); |
| 208 | assert_eq!(dotted.body, "team.plugin 技能"); |
| 209 | assert_eq!( |
| 210 | dotted.legacy_activation_name.as_deref(), |
| 211 | Some("team.plugin:skill") |
| 212 | ); |
| 213 | assert_eq!( |
| 214 | registry.get("TEAM-PLUGIN:技能").unwrap().body, |
| 215 | "team-plugin 技能" |
| 216 | ); |
| 217 | assert!(registry.get("team_plugin:技能").is_none()); |
| 218 | let path = tmp.path().join("skills_state.toml"); |
| 219 | std::fs::write(&path, "disabled = [\"team.plugin:skill\"]\n").unwrap(); |
| 220 | let filtered = registry.clone().into_enabled_with_state( |
| 221 | codewhale_runtime::skill_state::SkillStateStore::load_from(path), |
| 222 | ); |
| 223 | assert!(filtered.get("team.plugin:技能").is_none()); |
| 224 | assert!(filtered.get("team-plugin:技能").is_some()); |
| 225 | registry |
| 226 | .skills |
| 227 | .retain(|skill| !skill.name.starts_with("team.plugin:")); |
| 228 | assert!( |
| 229 | registry.get("team.plugin:技能").is_none(), |
| 230 | "absent dotted namespace must not select dashed namespace" |
| 231 | ); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn discovery_metrics_reset_and_snapshot_are_exact() { |
| 236 | super::reset_discovery_metrics(); |
| 237 | assert_eq!( |
| 238 | super::discovery_metrics_snapshot(), |
| 239 | super::SkillDiscoveryMetrics::default() |
| 240 | ); |
| 241 | |
| 242 | let tmpdir = TempDir::new().unwrap(); |
| 243 | let skills_root = tmpdir.path().join("skills"); |
| 244 | let vendor_root = skills_root.join("vendor"); |
| 245 | write_skill(&vendor_root, "demo", "A demo skill", "Instructions"); |
| 246 | |
| 247 | let registry = super::SkillRegistry::discover(&skills_root); |
| 248 | assert_eq!(registry.len(), 1); |
| 249 | assert_eq!( |
| 250 | super::discovery_metrics_snapshot(), |
| 251 | super::SkillDiscoveryMetrics { |
| 252 | root_discovery_calls: 1, |
| 253 | directories_visited: 2, |
| 254 | skill_md_read_attempts: 2, |
| 255 | } |
| 256 | ); |
| 257 | |
| 258 | super::reset_discovery_metrics(); |
| 259 | let missing_root = tmpdir.path().join("missing"); |
| 260 | let _registry = super::SkillRegistry::discover(&missing_root); |
| 261 | assert_eq!( |
| 262 | super::discovery_metrics_snapshot(), |
| 263 | super::SkillDiscoveryMetrics { |
| 264 | root_discovery_calls: 1, |
| 265 | directories_visited: 0, |
| 266 | skill_md_read_attempts: 0, |
| 267 | } |
| 268 | ); |
| 269 | |
| 270 | super::reset_discovery_metrics(); |
| 271 | assert_eq!( |
| 272 | super::discovery_metrics_snapshot(), |
| 273 | super::SkillDiscoveryMetrics::default() |
| 274 | ); |
| 275 | } |
| 276 | |
| 277 | #[test] |
| 278 | fn prompt_warning_sanitizer_scrubs_stale_conventional_home_roots() { |
| 279 | let workspace = std::path::Path::new("/tmp/workspace"); |
| 280 | let warning = "Skill at /Users/private-name/.agents/skills/a/SKILL.md is shadowed by /home/other/.skills/a/SKILL.md"; |
| 281 | let sanitized = super::sanitize_prompt_path_text(warning, workspace, None); |
| 282 | assert_eq!( |
| 283 | sanitized, |
| 284 | "Skill at ~/.agents/skills/a/SKILL.md is shadowed by ~/.skills/a/SKILL.md" |
| 285 | ); |
| 286 | } |
| 287 | |
| 288 | #[test] |
| 289 | fn prompt_warning_sanitizer_normalizes_windows_separators() { |
| 290 | let workspace = std::path::Path::new(r"C:\workspace"); |
| 291 | let configured_root = std::path::Path::new(r"C:\runtime\sessions\session-123\skills"); |
| 292 | let warning = r"Skill in C:\runtime\sessions\session-123\skills\visual-design\SKILL.md is not a safe command name"; |
| 293 | |
| 294 | let sanitized = super::sanitize_prompt_path_text(warning, workspace, Some(configured_root)); |
| 295 | |
| 296 | assert_eq!( |
| 297 | sanitized, |
| 298 | "Skill in <configured-skills>/visual-design/SKILL.md is not a safe command name" |
| 299 | ); |
| 300 | } |
| 301 | |
| 302 | #[test] |
| 303 | fn prompt_warning_sanitizer_replaces_configured_roots_only_at_path_boundaries() { |
| 304 | let workspace = std::path::Path::new("/tmp/workspace"); |
| 305 | let configured_root = std::path::Path::new("/tmp/work"); |
| 306 | let warning = "Skill in /tmp/workspace/.agents/skills/a/SKILL.md shadows /tmp/work/a/SKILL.md"; |
| 307 | |
| 308 | let sanitized = super::sanitize_prompt_path_text(warning, workspace, Some(configured_root)); |
| 309 | |
| 310 | assert_eq!( |
| 311 | sanitized, |
| 312 | "Skill in ./.agents/skills/a/SKILL.md shadows <configured-skills>/a/SKILL.md" |
| 313 | ); |
| 314 | } |
| 315 | |
| 316 | #[cfg(unix)] |
| 317 | #[test] |
| 318 | fn prompt_warning_sanitizer_handles_non_utf8_configured_roots() { |
| 319 | use std::os::unix::ffi::OsStringExt; |
| 320 | |
| 321 | let workspace = std::path::Path::new("/tmp/workspace"); |
| 322 | let configured_root = std::path::PathBuf::from(std::ffi::OsString::from_vec( |
| 323 | b"/tmp/session-\xff/skills".to_vec(), |
| 324 | )); |
| 325 | let warning = format!( |
| 326 | "Skill in {}/visual-design/SKILL.md is not a safe command name", |
| 327 | configured_root.display() |
| 328 | ); |
| 329 | |
| 330 | let sanitized = super::sanitize_prompt_path_text(&warning, workspace, Some(&configured_root)); |
| 331 | |
| 332 | assert_eq!( |
| 333 | sanitized, |
| 334 | "Skill in <configured-skills>/visual-design/SKILL.md is not a safe command name" |
| 335 | ); |
| 336 | } |
| 337 | |
| 338 | #[test] |
| 339 | fn render_available_skills_context_lists_paths_and_usage() { |
| 340 | let tmpdir = TempDir::new().unwrap(); |
| 341 | create_skill_dir( |
| 342 | &tmpdir, |
| 343 | "test-skill", |
| 344 | "---\nname: test-skill\ndescription: A test skill\n---\nDo something special", |
| 345 | ); |
| 346 | |
| 347 | let rendered = crate::render_available_skills_context(&tmpdir.path().join("skills")) |
| 348 | .expect("skill context"); |
| 349 | |
| 350 | // #4632: paths render relative to the skills base dir (privacy-safe), |
| 351 | // so the assertion checks the workspace-relative form. |
| 352 | let expected_path = super::prompt_display(&std::path::Path::new("test-skill").join("SKILL.md")); |
| 353 | |
| 354 | assert!(rendered.contains("## Skills")); |
| 355 | assert!(rendered.contains("- test-skill: A test skill")); |
| 356 | assert!(rendered.contains("call `load_skill` with that exact name before starting the work")); |
| 357 | assert!(rendered.contains("do not expand tool, approval, or trust authority")); |
| 358 | assert!( |
| 359 | rendered.contains(&expected_path), |
| 360 | "expected path {expected_path:?} not in rendered output" |
| 361 | ); |
| 362 | assert!(!rendered.contains(tmpdir.path().to_str().unwrap_or("/nonexistent"))); |
| 363 | assert!(rendered.contains("### Usage")); |
| 364 | } |
| 365 | |
| 366 | #[test] |
| 367 | fn workspace_prompt_omits_disabled_skills_without_configured_directory() { |
| 368 | let _env_lock = codewhale_runtime::test_support::lock_test_env(); |
| 369 | let tmpdir = TempDir::new().unwrap(); |
| 370 | let home = tmpdir.path().join("home"); |
| 371 | let workspace = tmpdir.path().join("workspace"); |
| 372 | let skills_root = workspace.join(".agents").join("skills"); |
| 373 | std::fs::create_dir_all(&home).unwrap(); |
| 374 | write_skill( |
| 375 | &skills_root, |
| 376 | "enabled-skill", |
| 377 | "Enabled skill", |
| 378 | "Instructions", |
| 379 | ); |
| 380 | write_skill( |
| 381 | &skills_root, |
| 382 | "disabled-skill", |
| 383 | "Disabled skill", |
| 384 | "Instructions", |
| 385 | ); |
| 386 | let _home = codewhale_runtime::test_support::EnvVarGuard::set("HOME", &home); |
| 387 | let _userprofile = codewhale_runtime::test_support::EnvVarGuard::set("USERPROFILE", &home); |
| 388 | let _codewhale_home = codewhale_runtime::test_support::EnvVarGuard::set( |
| 389 | "CODEWHALE_HOME", |
| 390 | home.join("isolated-product-state"), |
| 391 | ); |
| 392 | codewhale_runtime::test_support::trust_workspace(&workspace); |
| 393 | |
| 394 | let mut state = codewhale_runtime::skill_state::SkillStateStore::load_default().unwrap(); |
| 395 | state.set_enabled("disabled-skill", false).unwrap(); |
| 396 | super::clear_skill_discovery_cache(); |
| 397 | |
| 398 | let rendered = super::render_available_skills_context_for_workspace_with_mode_and_plugins( |
| 399 | &workspace, |
| 400 | super::SkillDiscoveryMode::Compatible, |
| 401 | "en", |
| 402 | None, |
| 403 | super::SkillListingConfig::default(), |
| 404 | super::MAX_AVAILABLE_SKILLS_CHARS, |
| 405 | ) |
| 406 | .expect("enabled skill context"); |
| 407 | |
| 408 | assert!(rendered.contains("enabled-skill")); |
| 409 | assert!(!rendered.contains("disabled-skill")); |
| 410 | let owned = codewhale_runtime::config::owned_skills_dir().unwrap(); |
| 411 | let mut config = codewhale_runtime::config::SkillsConfig::default(); |
| 412 | config.bundled.selected = Some(vec![ |
| 413 | "review".into(), |
| 414 | "plugin-creator".into(), |
| 415 | "forget".into(), |
| 416 | ]); |
| 417 | super::install_system_skills(&owned, &config.bundled).unwrap(); |
| 418 | write_skill( |
| 419 | &home.join(".agents/skills"), |
| 420 | "review", |
| 421 | "User review", |
| 422 | "from compatible root", |
| 423 | ); |
| 424 | let config_copy = |config: &codewhale_runtime::config::SkillsConfig| { |
| 425 | super::discover_for_workspace(&workspace, None, config, None) |
| 426 | }; |
| 427 | assert!( |
| 428 | config_copy(&config) |
| 429 | .get("review") |
| 430 | .unwrap() |
| 431 | .body |
| 432 | .contains("from compatible root") |
| 433 | ); |
| 434 | config.bundled.disabled = Some(vec![ |
| 435 | "review".into(), |
| 436 | "forget".into(), |
| 437 | "feedback".into(), |
| 438 | "v4-best-practices".into(), |
| 439 | ]); |
| 440 | config.bundled.explicit_only = Some(vec![ |
| 441 | "plugin-creator".into(), |
| 442 | "review\n".into(), |
| 443 | "odd\n\u{1b}name".into(), |
| 444 | ]); |
| 445 | let registry = config_copy(&config); |
| 446 | assert!( |
| 447 | registry |
| 448 | .get("review") |
| 449 | .unwrap() |
| 450 | .body |
| 451 | .contains("from compatible root") |
| 452 | ); |
| 453 | assert!(registry.get("forget").is_none()); |
| 454 | assert_eq!( |
| 455 | registry.get("plugin-creator").unwrap().invocation, |
| 456 | super::SkillInvocation::ExplicitOnly |
| 457 | ); |
| 458 | let index = super::render_index(&workspace, None, &config, "en", None, None).unwrap(); |
| 459 | assert!( |
| 460 | !index |
| 461 | .lines() |
| 462 | .any(|line| line.starts_with("- plugin-creator:")) |
| 463 | ); |
| 464 | let status = super::bundled_skills_status(&config, ®istry).unwrap(); |
| 465 | assert_eq!(status.retired.len(), 2); |
| 466 | assert!(status.disabled.contains(&"review")); |
| 467 | assert!(status.explicit_only.contains(&"plugin-creator")); |
| 468 | assert_eq!(status.ignored, vec![r"review\n"]); |
| 469 | assert_eq!( |
| 470 | status.unknown, |
| 471 | vec![format!( |
| 472 | "explicit_only={}", |
| 473 | "odd\n\u{1b}name".escape_debug() |
| 474 | )] |
| 475 | ); |
| 476 | assert!(!status.inspection().join("\n").contains('\u{1b}')); |
| 477 | write_skill(&owned, "feedback", "My feedback", "local guide"); |
| 478 | let source = owned.join("feedback/.installed-from"); |
| 479 | std::fs::write(&source, "github:test/feedback").unwrap(); |
| 480 | for reason in [ |
| 481 | "has .installed-from and stays active", |
| 482 | "was customized or renamed and stays active", |
| 483 | ] { |
| 484 | let current = config_copy(&config); |
| 485 | assert!(current.get("feedback").is_some()); |
| 486 | let status = super::bundled_skills_status(&config, ¤t).unwrap(); |
| 487 | assert!( |
| 488 | status |
| 489 | .retired |
| 490 | .iter() |
| 491 | .any(|row| row.starts_with("disabled=feedback (") && row.contains(reason)), |
| 492 | "{:?}", |
| 493 | status.retired |
| 494 | ); |
| 495 | if source.exists() { |
| 496 | std::fs::remove_file(&source).unwrap(); |
| 497 | } |
| 498 | } |
| 499 | write_skill(&owned, "forget", "My forget", "user owned"); |
| 500 | assert!( |
| 501 | config_copy(&config) |
| 502 | .get("forget") |
| 503 | .unwrap() |
| 504 | .body |
| 505 | .contains("user owned") |
| 506 | ); |
| 507 | std::fs::create_dir_all(owned.join("feedback")).unwrap(); |
| 508 | std::fs::write( |
| 509 | owned.join("feedback/SKILL.md"), |
| 510 | include_str!("../../../docs/skills/feedback/SKILL.md"), |
| 511 | ) |
| 512 | .unwrap(); |
| 513 | assert!(config_copy(&config).get("feedback").is_some()); |
| 514 | } |
| 515 | |
| 516 | #[test] |
| 517 | fn render_available_skills_context_uses_real_dir_name_not_frontmatter_name() { |
| 518 | // Regression: when a community-installed or manually-placed skill |
| 519 | // lives in a directory whose name differs from its frontmatter |
| 520 | // `name`, the rendered prompt must point to the real on-disk file |
| 521 | // path, not <skills_dir>/<frontmatter-name>/SKILL.md (which does |
| 522 | // not exist). |
| 523 | let tmpdir = TempDir::new().unwrap(); |
| 524 | create_skill_dir( |
| 525 | &tmpdir, |
| 526 | "weird-dir-name", |
| 527 | "---\nname: friendly-name\ndescription: drift case\n---\nbody", |
| 528 | ); |
| 529 | |
| 530 | let rendered = crate::render_available_skills_context(&tmpdir.path().join("skills")) |
| 531 | .expect("skill context"); |
| 532 | |
| 533 | // #4632: rendered relative to the skills base dir; the regression |
| 534 | // intent (real dir name, not frontmatter name) is unchanged. |
| 535 | let real_path = super::prompt_display(&std::path::Path::new("weird-dir-name").join("SKILL.md")); |
| 536 | let stale_path = super::prompt_display(&std::path::Path::new("friendly-name").join("SKILL.md")); |
| 537 | |
| 538 | assert!( |
| 539 | rendered.contains(&real_path), |
| 540 | "expected real on-disk path {real_path:?} in rendered output, got:\n{rendered}" |
| 541 | ); |
| 542 | assert!( |
| 543 | !rendered.contains(&stale_path), |
| 544 | "rendered output must not invent a path under the frontmatter name:\n{rendered}" |
| 545 | ); |
| 546 | } |
| 547 | |
| 548 | #[test] |
| 549 | fn render_available_skills_context_returns_none_when_empty() { |
| 550 | let tmpdir = TempDir::new().unwrap(); |
| 551 | let empty = tmpdir.path().join("skills"); |
| 552 | std::fs::create_dir_all(&empty).unwrap(); |
| 553 | assert!(crate::render_available_skills_context(&empty).is_none()); |
| 554 | |
| 555 | let missing = tmpdir.path().join("does-not-exist"); |
| 556 | assert!(crate::render_available_skills_context(&missing).is_none()); |
| 557 | } |
| 558 | |
| 559 | #[test] |
| 560 | fn render_skills_block_surfaces_warnings_when_no_skill_loaded() { |
| 561 | let tmpdir = TempDir::new().unwrap(); |
| 562 | let mut registry = super::SkillRegistry::default(); |
| 563 | registry |
| 564 | .warnings |
| 565 | .push("broken skill could not be parsed".to_string()); |
| 566 | |
| 567 | let rendered = |
| 568 | super::render_skills_block(®istry, "en", tmpdir.path()).expect("warning-only block"); |
| 569 | |
| 570 | assert!(rendered.contains("### Skill load warnings")); |
| 571 | assert!(rendered.contains("broken skill could not be parsed")); |
| 572 | assert!(rendered.chars().count() <= super::MAX_AVAILABLE_SKILLS_CHARS); |
| 573 | } |
| 574 | |
| 575 | #[test] |
| 576 | fn render_available_skills_context_truncates_long_descriptions() { |
| 577 | let tmpdir = TempDir::new().unwrap(); |
| 578 | let long_desc = "x".repeat(2_000); |
| 579 | let body = format!("---\nname: bigdesc\ndescription: {long_desc}\n---\nbody"); |
| 580 | create_skill_dir(&tmpdir, "bigdesc", &body); |
| 581 | let registry = super::SkillRegistry::discover(&tmpdir.path().join("skills")); |
| 582 | for cap in [80, super::DEFAULT_SKILL_DESCRIPTION_CHARS, 1024] { |
| 583 | let config = codewhale_runtime::config::SkillsConfig { |
| 584 | listing_max_description_chars: Some(cap), |
| 585 | ..Default::default() |
| 586 | }; |
| 587 | let listing = super::SkillListingConfig::from_config(&config); |
| 588 | let rendered = super::render_skills_block_with_configured_root( |
| 589 | ®istry, |
| 590 | "en", |
| 591 | tmpdir.path(), |
| 592 | None, |
| 593 | listing, |
| 594 | listing.budget_chars(None), |
| 595 | ) |
| 596 | .expect("skill context"); |
| 597 | assert!(rendered.contains('…'), "expected truncation marker"); |
| 598 | assert!( |
| 599 | !rendered.contains(&"x".repeat(cap + 1)), |
| 600 | "description exceeded {cap}" |
| 601 | ); |
| 602 | assert!( |
| 603 | rendered.contains(&format!("{cap}-character index limit")), |
| 604 | "{rendered}" |
| 605 | ); |
| 606 | assert_eq!( |
| 607 | super::shortened_skills_note(&rendered).as_deref(), |
| 608 | Some("descriptions shortened for 1 of 1 skills") |
| 609 | ); |
| 610 | assert!(super::description_exceeds_index_cap( |
| 611 | &long_desc, |
| 612 | listing.max_description_chars() |
| 613 | )); |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | #[test] |
| 618 | fn render_available_skills_context_collapses_internal_whitespace() { |
| 619 | let tmpdir = TempDir::new().unwrap(); |
| 620 | create_skill_dir( |
| 621 | &tmpdir, |
| 622 | "spaced-skill", |
| 623 | "---\nname: spaced-skill\ndescription: alpha \t beta gamma\n---\nbody", |
| 624 | ); |
| 625 | |
| 626 | let rendered = crate::render_available_skills_context(&tmpdir.path().join("skills")) |
| 627 | .expect("skill context"); |
| 628 | |
| 629 | let line = rendered |
| 630 | .lines() |
| 631 | .find(|l| l.starts_with("- spaced-skill:")) |
| 632 | .expect("skill line"); |
| 633 | assert!(line.contains("alpha beta gamma"), "got: {line:?}"); |
| 634 | } |
| 635 | |
| 636 | /// Three-tier fitting: when full descriptions overflow the budget the index |
| 637 | /// shortens them, then drops to names-only — a skill's name never vanishes |
| 638 | /// while the names themselves fit. |
| 639 | #[test] |
| 640 | fn render_available_skills_context_keeps_every_name_when_descriptions_overflow() { |
| 641 | let tmpdir = TempDir::new().unwrap(); |
| 642 | let big_desc = "y".repeat(super::DEFAULT_SKILL_DESCRIPTION_CHARS - 20); |
| 643 | for i in 0..100 { |
| 644 | let body = format!("---\nname: skill-{i:03}\ndescription: {big_desc}\n---\nbody"); |
| 645 | create_skill_dir(&tmpdir, &format!("skill-{i:03}"), &body); |
| 646 | } |
| 647 | |
| 648 | let rendered = crate::render_available_skills_context(&tmpdir.path().join("skills")) |
| 649 | .expect("skill context"); |
| 650 | |
| 651 | // 100 × 100 chars of description is ~10k, far over the default budget: |
| 652 | // tier 1 cannot fit, so descriptions shrink or names stand alone. |
| 653 | for i in 0..100 { |
| 654 | let name = format!("- skill-{i:03}"); |
| 655 | assert!(rendered.contains(&name), "missing {name}:\n{rendered}"); |
| 656 | } |
| 657 | assert!( |
| 658 | !rendered.contains("additional skills omitted"), |
| 659 | "names fit the budget; omission is the last resort, not the first" |
| 660 | ); |
| 661 | assert!( |
| 662 | !rendered.contains(&big_desc), |
| 663 | "a full-length description must not survive an overflowing index" |
| 664 | ); |
| 665 | assert!( |
| 666 | rendered.chars().count() <= super::MAX_AVAILABLE_SKILLS_CHARS, |
| 667 | "rendered length must stay within the complete block budget" |
| 668 | ); |
| 669 | } |
| 670 | |
| 671 | /// `Use when:` triggers survive shortening ahead of the summary — they are |
| 672 | /// what the model routes on. |
| 673 | #[test] |
| 674 | fn render_skills_block_shortens_summary_before_trigger() { |
| 675 | let tmpdir = TempDir::new().unwrap(); |
| 676 | let mut registry = super::SkillRegistry::default(); |
| 677 | let summary = "s".repeat(300); |
| 678 | for i in 0..120 { |
| 679 | registry.skills.push(super::Skill { |
| 680 | legacy_activation_name: None, |
| 681 | name: format!("skill-{i:03}"), |
| 682 | description: format!("{summary} Use when: the user asks for widget {i}."), |
| 683 | localized_descriptions: std::collections::HashMap::new(), |
| 684 | invocation: super::SkillInvocation::ModelAndUser, |
| 685 | dependencies: Default::default(), |
| 686 | aliases: Vec::new(), |
| 687 | argument_hint: None, |
| 688 | body: "body".to_string(), |
| 689 | path: tmpdir.path().join(format!("skill-{i:03}/SKILL.md")), |
| 690 | source: super::SkillSource::Native, |
| 691 | }); |
| 692 | } |
| 693 | let budget = 25_600; |
| 694 | let config = super::SkillListingConfig { |
| 695 | max_description_chars: 400, |
| 696 | ..Default::default() |
| 697 | }; |
| 698 | let rendered = super::render_skills_block_with_configured_root( |
| 699 | ®istry, |
| 700 | "en", |
| 701 | tmpdir.path(), |
| 702 | None, |
| 703 | config, |
| 704 | budget, |
| 705 | ) |
| 706 | .expect("skill context"); |
| 707 | let line = rendered |
| 708 | .lines() |
| 709 | .find(|l| l.starts_with("- skill-007:")) |
| 710 | .expect("row for skill-007"); |
| 711 | assert!( |
| 712 | line.contains("Use when: the user asks for widget 7"), |
| 713 | "trigger must survive shortening intact:\n{line}" |
| 714 | ); |
| 715 | assert!( |
| 716 | !line.contains(&summary), |
| 717 | "summary must be the half that shrinks:\n{line}" |
| 718 | ); |
| 719 | assert!(rendered.chars().count() <= budget); |
| 720 | } |
| 721 | |
| 722 | /// The budget follows the route window: a 1M route sees a much larger index |
| 723 | /// than a small local window, both clamped to sane bounds. |
| 724 | #[test] |
| 725 | fn skills_prompt_budget_scales_with_context_window() { |
| 726 | let small = super::SkillListingConfig::default().budget_chars(Some(8_000)); |
| 727 | let default = super::SkillListingConfig::default().budget_chars(None); |
| 728 | let large = super::SkillListingConfig::default().budget_chars(Some(1_000_000)); |
| 729 | assert_eq!(small, 2_400, "floor holds for tiny windows"); |
| 730 | assert_eq!(default, 2_400, "128k window × 4 chars × 0.2%, floored"); |
| 731 | assert_eq!(large, 8_000, "1M window × 4 chars × 0.2%"); |
| 732 | let configured = |
| 733 | super::SkillListingConfig::from_config(&codewhale_runtime::config::SkillsConfig { |
| 734 | listing_budget_fraction: Some(0.01), |
| 735 | ..Default::default() |
| 736 | }); |
| 737 | assert_eq!(configured.budget_chars(None), 5_120); |
| 738 | assert_eq!(configured.budget_chars(Some(8_000)), 2_400); |
| 739 | assert_eq!(configured.budget_chars(Some(1_000_000)), 40_000); |
| 740 | assert_eq!( |
| 741 | super::SkillListingConfig::default().budget_chars(Some(0)), |
| 742 | default, |
| 743 | "a zero window is treated as unknown" |
| 744 | ); |
| 745 | } |
| 746 | |
| 747 | #[test] |
| 748 | fn render_skills_block_holds_budget_with_five_digit_omission_counts() { |
| 749 | let tmpdir = TempDir::new().unwrap(); |
| 750 | let mut registry = super::SkillRegistry::default(); |
| 751 | for i in 0..15_000 { |
| 752 | registry.skills.push(super::Skill { |
| 753 | legacy_activation_name: None, |
| 754 | name: format!("skill-{i:05}"), |
| 755 | description: "x".to_string(), |
| 756 | localized_descriptions: std::collections::HashMap::new(), |
| 757 | invocation: super::SkillInvocation::ModelAndUser, |
| 758 | dependencies: Default::default(), |
| 759 | aliases: Vec::new(), |
| 760 | argument_hint: None, |
| 761 | body: "body".to_string(), |
| 762 | path: tmpdir.path().join(format!("skill-{i:05}/SKILL.md")), |
| 763 | source: super::SkillSource::Native, |
| 764 | }); |
| 765 | registry.warnings.push(format!("warning {i:05}")); |
| 766 | } |
| 767 | |
| 768 | let rendered = |
| 769 | super::render_skills_block(®istry, "en", tmpdir.path()).expect("skill context"); |
| 770 | let omitted_skills = rendered |
| 771 | .lines() |
| 772 | .find(|line| line.contains("additional skills omitted")) |
| 773 | .and_then(|line| line.split_whitespace().nth(2)) |
| 774 | .and_then(|count| count.parse::<usize>().ok()) |
| 775 | .expect("skill omission count"); |
| 776 | let omitted_warnings = rendered |
| 777 | .lines() |
| 778 | .find(|line| line.contains("additional warnings omitted")) |
| 779 | .and_then(|line| line.split_whitespace().nth(2)) |
| 780 | .and_then(|count| count.parse::<usize>().ok()) |
| 781 | .expect("warning omission count"); |
| 782 | |
| 783 | assert!(omitted_skills > 9_999, "fixture must exercise five digits"); |
| 784 | assert!( |
| 785 | omitted_warnings > 9_999, |
| 786 | "fixture must exercise five digits" |
| 787 | ); |
| 788 | assert!(rendered.chars().count() <= super::MAX_AVAILABLE_SKILLS_CHARS); |
| 789 | } |
| 790 | |
| 791 | #[test] |
| 792 | fn explicit_only_skills_do_not_reduce_ambient_index_capacity() { |
| 793 | let tmpdir = TempDir::new().unwrap(); |
| 794 | let mut registry = super::SkillRegistry::default(); |
| 795 | for i in 0..6 { |
| 796 | registry.skills.push(super::Skill { |
| 797 | legacy_activation_name: None, |
| 798 | name: format!("visible-{i:03}"), |
| 799 | description: "x".repeat(246), |
| 800 | localized_descriptions: std::collections::HashMap::new(), |
| 801 | invocation: super::SkillInvocation::ModelAndUser, |
| 802 | dependencies: Default::default(), |
| 803 | aliases: Vec::new(), |
| 804 | argument_hint: None, |
| 805 | body: "body".to_string(), |
| 806 | path: tmpdir.path().join(format!("visible-{i:03}/SKILL.md")), |
| 807 | source: super::SkillSource::Native, |
| 808 | }); |
| 809 | } |
| 810 | |
| 811 | let baseline = |
| 812 | super::render_skills_block(®istry, "en", tmpdir.path()).expect("skill context"); |
| 813 | assert!(!baseline.contains("additional skills omitted")); |
| 814 | |
| 815 | let mut with_explicit_only = registry.clone(); |
| 816 | for i in 0..10_000 { |
| 817 | with_explicit_only.skills.push(super::Skill { |
| 818 | legacy_activation_name: None, |
| 819 | name: format!("explicit-{i:05}"), |
| 820 | description: String::new(), |
| 821 | localized_descriptions: std::collections::HashMap::new(), |
| 822 | invocation: super::SkillInvocation::ExplicitOnly, |
| 823 | dependencies: Default::default(), |
| 824 | aliases: Vec::new(), |
| 825 | argument_hint: None, |
| 826 | body: "body".to_string(), |
| 827 | path: tmpdir.path().join(format!("explicit-{i:05}/SKILL.md")), |
| 828 | source: super::SkillSource::Native, |
| 829 | }); |
| 830 | } |
| 831 | |
| 832 | let rendered = super::render_skills_block(&with_explicit_only, "en", tmpdir.path()) |
| 833 | .expect("skill context"); |
| 834 | assert_eq!(rendered, baseline); |
| 835 | } |
| 836 | |
| 837 | #[test] |
| 838 | fn render_skills_block_preserves_registry_precedence_under_prompt_budget() { |
| 839 | let tmpdir = TempDir::new().unwrap(); |
| 840 | let mut registry = super::SkillRegistry::default(); |
| 841 | registry.skills.push(super::Skill { |
| 842 | legacy_activation_name: None, |
| 843 | name: "workspace-priority".to_string(), |
| 844 | description: "must survive truncation".to_string(), |
| 845 | localized_descriptions: std::collections::HashMap::new(), |
| 846 | invocation: super::SkillInvocation::ModelAndUser, |
| 847 | dependencies: Default::default(), |
| 848 | aliases: Vec::new(), |
| 849 | argument_hint: None, |
| 850 | body: "body".to_string(), |
| 851 | path: tmpdir |
| 852 | .path() |
| 853 | .join(".claude") |
| 854 | .join("skills") |
| 855 | .join("workspace-priority") |
| 856 | .join("SKILL.md"), |
| 857 | source: super::SkillSource::Native, |
| 858 | }); |
| 859 | |
| 860 | let big_desc = "y".repeat(super::DEFAULT_SKILL_DESCRIPTION_CHARS - 20); |
| 861 | for i in 0..200 { |
| 862 | registry.skills.push(super::Skill { |
| 863 | legacy_activation_name: None, |
| 864 | name: format!("aaa-global-{i:03}"), |
| 865 | description: big_desc.clone(), |
| 866 | localized_descriptions: std::collections::HashMap::new(), |
| 867 | invocation: super::SkillInvocation::ModelAndUser, |
| 868 | dependencies: Default::default(), |
| 869 | aliases: Vec::new(), |
| 870 | argument_hint: None, |
| 871 | body: "body".to_string(), |
| 872 | path: tmpdir |
| 873 | .path() |
| 874 | .join(".deepseek") |
| 875 | .join("skills") |
| 876 | .join(format!("aaa-global-{i:03}")) |
| 877 | .join("SKILL.md"), |
| 878 | source: super::SkillSource::Native, |
| 879 | }); |
| 880 | } |
| 881 | |
| 882 | let rendered = |
| 883 | super::render_skills_block(®istry, "en", tmpdir.path()).expect("skill context"); |
| 884 | assert!( |
| 885 | rendered.contains("workspace-priority"), |
| 886 | "higher-precedence workspace skills must not be reordered behind globals:\n{rendered}" |
| 887 | ); |
| 888 | let first_row = rendered |
| 889 | .lines() |
| 890 | .find(|line| line.starts_with("- ")) |
| 891 | .expect("at least one row"); |
| 892 | assert!( |
| 893 | first_row.starts_with("- workspace-priority"), |
| 894 | "registry order is render order:\n{rendered}" |
| 895 | ); |
| 896 | } |
| 897 | |
| 898 | // --- Localized skill descriptions (#3354) ------------------------------ |
| 899 | |
| 900 | #[test] |
| 901 | fn parse_skill_collects_localized_description_frontmatter() { |
| 902 | let content = "---\n\ |
| 903 | name: demo\n\ |
| 904 | description: A demo skill\n\ |
| 905 | description_zh: 一个演示技能\n\ |
| 906 | description_zh-Hant: 一個示範技能\n\ |
| 907 | ---\n\ |
| 908 | body"; |
| 909 | let skill = super::SkillRegistry::parse_skill(std::path::Path::new("SKILL.md"), content) |
| 910 | .expect("parse should succeed"); |
| 911 | assert_eq!(skill.description, "A demo skill"); |
| 912 | assert_eq!( |
| 913 | skill.localized_descriptions.get("zh").map(String::as_str), |
| 914 | Some("一个演示技能") |
| 915 | ); |
| 916 | // Frontmatter keys are lowercased, so zh-Hant is stored as zh-hant. |
| 917 | assert_eq!( |
| 918 | skill |
| 919 | .localized_descriptions |
| 920 | .get("zh-hant") |
| 921 | .map(String::as_str), |
| 922 | Some("一個示範技能") |
| 923 | ); |
| 924 | } |
| 925 | |
| 926 | #[test] |
| 927 | fn parse_skill_exposes_invocation_and_alias_metadata() { |
| 928 | let content = "---\n\ |
| 929 | name: spreadsheets\n\ |
| 930 | description: Spreadsheet workflows\n\ |
| 931 | invocation: explicit-only\n\ |
| 932 | aliases-for: xlsx, spreadsheet\n\ |
| 933 | ---\n\ |
| 934 | body"; |
| 935 | let skill = super::SkillRegistry::parse_skill(std::path::Path::new("SKILL.md"), content) |
| 936 | .expect("parse should succeed"); |
| 937 | |
| 938 | assert_eq!(skill.invocation, super::SkillInvocation::ExplicitOnly); |
| 939 | assert_eq!( |
| 940 | skill.aliases, |
| 941 | vec!["xlsx".to_string(), "spreadsheet".to_string()] |
| 942 | ); |
| 943 | |
| 944 | let mut registry = super::SkillRegistry::default(); |
| 945 | registry.skills.push(skill); |
| 946 | assert_eq!( |
| 947 | registry.get("spreadsheet").map(|s| s.name.as_str()), |
| 948 | Some("spreadsheets") |
| 949 | ); |
| 950 | assert_eq!( |
| 951 | registry.get("xlsx").map(|s| s.name.as_str()), |
| 952 | Some("spreadsheets") |
| 953 | ); |
| 954 | |
| 955 | assert_eq!( |
| 956 | registry.get("spreadsheets").map(|skill| skill.body.trim()), |
| 957 | Some("body") |
| 958 | ); |
| 959 | assert!( |
| 960 | super::render_skills_block(®istry, "en", std::path::Path::new("/")).is_none(), |
| 961 | "a registry containing only explicit-only skills has no model-visible catalogue" |
| 962 | ); |
| 963 | } |
| 964 | |
| 965 | #[test] |
| 966 | fn missing_or_unknown_invocation_keeps_model_and_user_compatibility() { |
| 967 | for invocation in [None, Some("future-mode")] { |
| 968 | let invocation_line = |
| 969 | invocation.map_or(String::new(), |value| format!("invocation: {value}\n")); |
| 970 | let content = |
| 971 | format!("---\nname: compatible\ndescription: compatible\n{invocation_line}---\nbody"); |
| 972 | let skill = super::SkillRegistry::parse_skill(std::path::Path::new("SKILL.md"), &content) |
| 973 | .expect("parse should succeed"); |
| 974 | assert_eq!(skill.invocation, super::SkillInvocation::ModelAndUser); |
| 975 | } |
| 976 | } |
| 977 | |
| 978 | #[test] |
| 979 | fn description_for_locale_matches_exact_then_primary_then_falls_back() { |
| 980 | let mut localized = std::collections::HashMap::new(); |
| 981 | localized.insert("zh".to_string(), "中文描述".to_string()); |
| 982 | localized.insert("ja".to_string(), "日本語の説明".to_string()); |
| 983 | let skill = super::Skill { |
| 984 | legacy_activation_name: None, |
| 985 | name: "demo".to_string(), |
| 986 | description: "English description".to_string(), |
| 987 | localized_descriptions: localized, |
| 988 | invocation: super::SkillInvocation::ModelAndUser, |
| 989 | dependencies: Default::default(), |
| 990 | aliases: Vec::new(), |
| 991 | argument_hint: None, |
| 992 | body: String::new(), |
| 993 | path: std::path::PathBuf::new(), |
| 994 | source: super::SkillSource::Native, |
| 995 | }; |
| 996 | |
| 997 | assert_eq!(skill.description_for_locale("zh"), "中文描述"); // exact |
| 998 | assert_eq!(skill.description_for_locale("ZH"), "中文描述"); // case-insensitive |
| 999 | assert_eq!(skill.description_for_locale("zh-CN"), "中文描述"); // Simplified region → zh |
| 1000 | assert_eq!(skill.description_for_locale("zh-Hans"), "中文描述"); // Simplified script → zh |
| 1001 | assert_eq!(skill.description_for_locale("ja"), "日本語の説明"); |
| 1002 | assert_eq!(skill.description_for_locale("fr"), "English description"); // fallback |
| 1003 | assert_eq!(skill.description_for_locale("en"), "English description"); |
| 1004 | |
| 1005 | // Traditional Chinese must NOT borrow the Simplified `zh` description: |
| 1006 | // with no exact zh-hant key authored, it falls back to the default. |
| 1007 | assert_eq!( |
| 1008 | skill.description_for_locale("zh-Hant"), |
| 1009 | "English description" |
| 1010 | ); |
| 1011 | assert_eq!(skill.description_for_locale("zh-TW"), "English description"); |
| 1012 | assert_eq!(skill.description_for_locale("zh-HK"), "English description"); |
| 1013 | } |
| 1014 | |
| 1015 | #[test] |
| 1016 | fn description_for_locale_uses_exact_traditional_key_when_authored() { |
| 1017 | let mut localized = std::collections::HashMap::new(); |
| 1018 | localized.insert("zh".to_string(), "简体描述".to_string()); |
| 1019 | localized.insert("zh-hant".to_string(), "繁體描述".to_string()); |
| 1020 | let skill = super::Skill { |
| 1021 | legacy_activation_name: None, |
| 1022 | name: "demo".to_string(), |
| 1023 | description: "English".to_string(), |
| 1024 | localized_descriptions: localized, |
| 1025 | invocation: super::SkillInvocation::ModelAndUser, |
| 1026 | dependencies: Default::default(), |
| 1027 | aliases: Vec::new(), |
| 1028 | argument_hint: None, |
| 1029 | body: String::new(), |
| 1030 | path: std::path::PathBuf::new(), |
| 1031 | source: super::SkillSource::Native, |
| 1032 | }; |
| 1033 | // Exact Traditional key wins for a Traditional session. |
| 1034 | assert_eq!(skill.description_for_locale("zh-Hant"), "繁體描述"); |
| 1035 | // Simplified session still gets the Simplified description. |
| 1036 | assert_eq!(skill.description_for_locale("zh-Hans"), "简体描述"); |
| 1037 | assert_eq!(skill.description_for_locale("zh"), "简体描述"); |
| 1038 | } |
| 1039 | |
| 1040 | #[test] |
| 1041 | fn description_for_locale_uses_default_when_no_localized_variants() { |
| 1042 | let skill = super::Skill { |
| 1043 | legacy_activation_name: None, |
| 1044 | name: "demo".to_string(), |
| 1045 | description: "only english".to_string(), |
| 1046 | localized_descriptions: std::collections::HashMap::new(), |
| 1047 | invocation: super::SkillInvocation::ModelAndUser, |
| 1048 | dependencies: Default::default(), |
| 1049 | aliases: Vec::new(), |
| 1050 | argument_hint: None, |
| 1051 | body: String::new(), |
| 1052 | path: std::path::PathBuf::new(), |
| 1053 | source: super::SkillSource::Native, |
| 1054 | }; |
| 1055 | assert_eq!(skill.description_for_locale("zh"), "only english"); |
| 1056 | } |
| 1057 | |
| 1058 | #[test] |
| 1059 | fn render_skills_block_selects_description_by_locale() { |
| 1060 | let mut registry = super::SkillRegistry::default(); |
| 1061 | let mut localized = std::collections::HashMap::new(); |
| 1062 | localized.insert("zh".to_string(), "压缩日志的技能".to_string()); |
| 1063 | registry.skills.push(super::Skill { |
| 1064 | legacy_activation_name: None, |
| 1065 | name: "compress".to_string(), |
| 1066 | description: "Compress logs to save space".to_string(), |
| 1067 | localized_descriptions: localized, |
| 1068 | invocation: super::SkillInvocation::ModelAndUser, |
| 1069 | dependencies: Default::default(), |
| 1070 | aliases: Vec::new(), |
| 1071 | argument_hint: None, |
| 1072 | body: "body".to_string(), |
| 1073 | path: std::path::PathBuf::from("/skills/compress/SKILL.md"), |
| 1074 | source: super::SkillSource::Native, |
| 1075 | }); |
| 1076 | |
| 1077 | let zh = super::render_skills_block(®istry, "zh-Hans", std::path::Path::new("/")) |
| 1078 | .expect("zh block"); |
| 1079 | assert!( |
| 1080 | zh.contains("压缩日志的技能"), |
| 1081 | "zh session should get the zh description:\n{zh}" |
| 1082 | ); |
| 1083 | assert!(!zh.contains("Compress logs to save space")); |
| 1084 | |
| 1085 | let en = |
| 1086 | super::render_skills_block(®istry, "en", std::path::Path::new("/")).expect("en block"); |
| 1087 | assert!( |
| 1088 | en.contains("Compress logs to save space"), |
| 1089 | "en session keeps default:\n{en}" |
| 1090 | ); |
| 1091 | } |
| 1092 | |
| 1093 | fn write_skill(dir: &std::path::Path, name: &str, description: &str, body: &str) { |
| 1094 | let skill_dir = dir.join(name); |
| 1095 | std::fs::create_dir_all(&skill_dir).unwrap(); |
| 1096 | std::fs::write( |
| 1097 | skill_dir.join("SKILL.md"), |
| 1098 | format!("---\nname: {name}\ndescription: {description}\n---\n{body}\n"), |
| 1099 | ) |
| 1100 | .unwrap(); |
| 1101 | } |
| 1102 | |
| 1103 | #[cfg(unix)] |
| 1104 | fn create_dir_symlink(target: &std::path::Path, link: &std::path::Path) -> std::io::Result<()> { |
| 1105 | std::os::unix::fs::symlink(target, link) |
| 1106 | } |
| 1107 | |
| 1108 | #[cfg(windows)] |
| 1109 | fn create_dir_symlink(target: &std::path::Path, link: &std::path::Path) -> std::io::Result<()> { |
| 1110 | std::os::windows::fs::symlink_dir(target, link) |
| 1111 | } |
| 1112 | |
| 1113 | #[test] |
| 1114 | fn skills_directories_returns_existing_dirs_in_precedence_order() { |
| 1115 | let tmpdir = TempDir::new().unwrap(); |
| 1116 | let workspace = tmpdir.path(); |
| 1117 | codewhale_runtime::test_support::trust_workspace(workspace); |
| 1118 | |
| 1119 | // Create four of the five workspace candidate dirs (skip `.opencode`). |
| 1120 | std::fs::create_dir_all(workspace.join(".agents").join("skills")).unwrap(); |
| 1121 | std::fs::create_dir_all(workspace.join("skills")).unwrap(); |
| 1122 | std::fs::create_dir_all(workspace.join(".claude").join("skills")).unwrap(); |
| 1123 | std::fs::create_dir_all(workspace.join(".cursor").join("skills")).unwrap(); |
| 1124 | |
| 1125 | let dirs = super::skills_directories_for_mode(workspace, super::SkillDiscoveryMode::Compatible); |
| 1126 | // We don't assert on the global default position because it's |
| 1127 | // host-dependent (may not exist on the test machine). |
| 1128 | let mut idx = 0; |
| 1129 | let agents = workspace.join(".agents").join("skills"); |
| 1130 | let local = workspace.join("skills"); |
| 1131 | let claude = workspace.join(".claude").join("skills"); |
| 1132 | let cursor = workspace.join(".cursor").join("skills"); |
| 1133 | |
| 1134 | assert_eq!(dirs.get(idx), Some(&agents), "agents must come first"); |
| 1135 | idx += 1; |
| 1136 | assert!( |
| 1137 | !dirs.contains(&local), |
| 1138 | "flat product content requires opt-in" |
| 1139 | ); |
| 1140 | // .opencode/skills was not created — it must NOT appear. |
| 1141 | assert!( |
| 1142 | !dirs |
| 1143 | .iter() |
| 1144 | .any(|p| p == &workspace.join(".opencode").join("skills")), |
| 1145 | "missing dir must be omitted, got: {dirs:?}" |
| 1146 | ); |
| 1147 | assert_eq!( |
| 1148 | dirs.get(idx), |
| 1149 | Some(&claude), |
| 1150 | "claude must come after agents" |
| 1151 | ); |
| 1152 | idx += 1; |
| 1153 | assert_eq!( |
| 1154 | dirs.get(idx), |
| 1155 | Some(&cursor), |
| 1156 | "cursor must come after claude" |
| 1157 | ); |
| 1158 | } |
| 1159 | |
| 1160 | #[test] |
| 1161 | fn existing_skill_dirs_orders_globals_agents_then_claude_then_deepseek() { |
| 1162 | // Pins the precedence among the three global skill roots (#902). |
| 1163 | // Workspace candidates are tested separately above; here we only |
| 1164 | // exercise the global ordering at the existing_skill_dirs level |
| 1165 | // so the assertion is host-independent. |
| 1166 | let tmpdir = TempDir::new().unwrap(); |
| 1167 | let agents_global = tmpdir.path().join(".agents").join("skills"); |
| 1168 | let claude_global = tmpdir.path().join(".claude").join("skills"); |
| 1169 | let deepseek_global = tmpdir.path().join(".deepseek").join("skills"); |
| 1170 | std::fs::create_dir_all(&agents_global).unwrap(); |
| 1171 | std::fs::create_dir_all(&claude_global).unwrap(); |
| 1172 | std::fs::create_dir_all(&deepseek_global).unwrap(); |
| 1173 | |
| 1174 | let dirs = super::existing_skill_dirs(vec![ |
| 1175 | agents_global.clone(), |
| 1176 | claude_global.clone(), |
| 1177 | deepseek_global.clone(), |
| 1178 | ]); |
| 1179 | |
| 1180 | assert_eq!(dirs, vec![agents_global, claude_global, deepseek_global]); |
| 1181 | } |
| 1182 | |
| 1183 | #[test] |
| 1184 | fn existing_skill_dirs_keeps_agents_global_before_deepseek_global() { |
| 1185 | let tmpdir = TempDir::new().unwrap(); |
| 1186 | let agents_global = tmpdir.path().join(".agents").join("skills"); |
| 1187 | let deepseek_global = tmpdir.path().join(".deepseek").join("skills"); |
| 1188 | let missing = tmpdir.path().join("missing").join("skills"); |
| 1189 | std::fs::create_dir_all(&agents_global).unwrap(); |
| 1190 | std::fs::create_dir_all(&deepseek_global).unwrap(); |
| 1191 | |
| 1192 | let dirs = super::existing_skill_dirs(vec![ |
| 1193 | missing, |
| 1194 | agents_global.clone(), |
| 1195 | deepseek_global.clone(), |
| 1196 | agents_global.clone(), |
| 1197 | ]); |
| 1198 | |
| 1199 | assert_eq!(dirs, vec![agents_global, deepseek_global]); |
| 1200 | } |
| 1201 | |
| 1202 | #[test] |
| 1203 | fn discover_in_workspace_merges_with_first_wins_precedence() { |
| 1204 | let tmpdir = TempDir::new().unwrap(); |
| 1205 | let workspace = tmpdir.path(); |
| 1206 | codewhale_runtime::test_support::trust_workspace(workspace); |
| 1207 | |
| 1208 | // Same skill name `shared` in two locations — the higher-precedence |
| 1209 | // dir's version should win. |
| 1210 | write_skill( |
| 1211 | &workspace.join(".agents").join("skills"), |
| 1212 | "shared", |
| 1213 | "agents wins", |
| 1214 | "from agents", |
| 1215 | ); |
| 1216 | write_skill( |
| 1217 | &workspace.join(".claude").join("skills"), |
| 1218 | "shared", |
| 1219 | "claude loses", |
| 1220 | "from claude", |
| 1221 | ); |
| 1222 | // Unique skill in claude — should still be discovered. |
| 1223 | write_skill( |
| 1224 | &workspace.join(".claude").join("skills"), |
| 1225 | "unique-claude", |
| 1226 | "only here", |
| 1227 | "claude-only", |
| 1228 | ); |
| 1229 | |
| 1230 | let registry = super::discover_in_workspace(workspace); |
| 1231 | let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect(); |
| 1232 | assert!( |
| 1233 | names.contains(&"shared"), |
| 1234 | "shared must be present: {names:?}" |
| 1235 | ); |
| 1236 | assert!(names.contains(&"unique-claude")); |
| 1237 | |
| 1238 | let shared = registry.get("shared").expect("shared present"); |
| 1239 | assert_eq!( |
| 1240 | shared.description, "agents wins", |
| 1241 | "first-wins precedence should keep .agents/skills version" |
| 1242 | ); |
| 1243 | assert!( |
| 1244 | shared.path.starts_with(workspace.join(".agents")), |
| 1245 | "shared.path should be from .agents/skills, got {:?}", |
| 1246 | shared.path |
| 1247 | ); |
| 1248 | assert!( |
| 1249 | registry |
| 1250 | .warnings() |
| 1251 | .iter() |
| 1252 | .any(|warning| warning.contains("shared") && warning.contains("shadowed by")), |
| 1253 | "duplicate shadowing should warn, got {:?}", |
| 1254 | registry.warnings() |
| 1255 | ); |
| 1256 | } |
| 1257 | |
| 1258 | #[test] |
| 1259 | fn same_root_slug_collision_warns_and_keeps_one() { |
| 1260 | let tmpdir = TempDir::new().unwrap(); |
| 1261 | let root = tmpdir.path(); |
| 1262 | // Two sibling directories under one root whose frontmatter names |
| 1263 | // slugify to the same command name ("my-skill"). Only one can be |
| 1264 | // reachable by name; the other must warn rather than silently coexist |
| 1265 | // as an unreachable duplicate (#3919 same-root gap). |
| 1266 | write_skill(root, "My Skill", "first", "body"); |
| 1267 | write_skill(root, "my_skill", "second", "body"); |
| 1268 | |
| 1269 | let registry = super::SkillRegistry::discover(root); |
| 1270 | let claimants = registry |
| 1271 | .list() |
| 1272 | .iter() |
| 1273 | .filter(|s| s.name == "my-skill") |
| 1274 | .count(); |
| 1275 | assert_eq!( |
| 1276 | claimants, |
| 1277 | 1, |
| 1278 | "exactly one skill should claim `my-skill`, got {:?}", |
| 1279 | registry.list().iter().map(|s| &s.name).collect::<Vec<_>>() |
| 1280 | ); |
| 1281 | assert!( |
| 1282 | registry |
| 1283 | .warnings() |
| 1284 | .iter() |
| 1285 | .any(|w| w.contains("my-skill") && w.contains("shadowed by")), |
| 1286 | "same-root slug collision should warn, got {:?}", |
| 1287 | registry.warnings() |
| 1288 | ); |
| 1289 | } |
| 1290 | |
| 1291 | #[test] |
| 1292 | fn discover_in_workspace_pulls_skills_from_opencode_dir() { |
| 1293 | let tmpdir = TempDir::new().unwrap(); |
| 1294 | let workspace = tmpdir.path(); |
| 1295 | codewhale_runtime::test_support::trust_workspace(workspace); |
| 1296 | write_skill( |
| 1297 | &workspace.join(".opencode").join("skills"), |
| 1298 | "opencode-only", |
| 1299 | "for interop", |
| 1300 | "body", |
| 1301 | ); |
| 1302 | |
| 1303 | let registry = super::discover_in_workspace(workspace); |
| 1304 | assert!( |
| 1305 | registry.get("opencode-only").is_some(), |
| 1306 | ".opencode/skills must be scanned (#432)" |
| 1307 | ); |
| 1308 | } |
| 1309 | |
| 1310 | #[test] |
| 1311 | fn discover_in_workspace_pulls_skills_from_cursor_dir() { |
| 1312 | let tmpdir = TempDir::new().unwrap(); |
| 1313 | let workspace = tmpdir.path(); |
| 1314 | codewhale_runtime::test_support::trust_workspace(workspace); |
| 1315 | write_skill( |
| 1316 | &workspace.join(".cursor").join("skills"), |
| 1317 | "cursor-only", |
| 1318 | "for cursor interop", |
| 1319 | "body", |
| 1320 | ); |
| 1321 | |
| 1322 | let registry = super::discover_in_workspace(workspace); |
| 1323 | assert!( |
| 1324 | registry.get("cursor-only").is_some(), |
| 1325 | ".cursor/skills must be scanned" |
| 1326 | ); |
| 1327 | } |
| 1328 | |
| 1329 | #[test] |
| 1330 | fn discover_accepts_plain_markdown_heading_without_frontmatter() { |
| 1331 | let tmpdir = TempDir::new().unwrap(); |
| 1332 | let skill_dir = tmpdir.path().join("plain-skill"); |
| 1333 | std::fs::create_dir_all(&skill_dir).unwrap(); |
| 1334 | std::fs::write( |
| 1335 | skill_dir.join("SKILL.md"), |
| 1336 | "# Plain Skill\n\nUse this skill without YAML frontmatter.\n", |
| 1337 | ) |
| 1338 | .unwrap(); |
| 1339 | |
| 1340 | let registry = super::SkillRegistry::discover(tmpdir.path()); |
| 1341 | let skill = registry.get("plain-skill").expect("plain skill parsed"); |
| 1342 | assert_eq!(skill.name, "plain-skill"); |
| 1343 | assert_eq!(skill.description, ""); |
| 1344 | assert!(skill.body.contains("Use this skill")); |
| 1345 | assert!( |
| 1346 | registry |
| 1347 | .warnings() |
| 1348 | .iter() |
| 1349 | .any(|warning| warning.contains("using `plain-skill` instead")), |
| 1350 | "expected slug warning, got {:?}", |
| 1351 | registry.warnings() |
| 1352 | ); |
| 1353 | } |
| 1354 | |
| 1355 | #[test] |
| 1356 | fn discover_slugifies_invalid_frontmatter_names_and_lookup_normalizes() { |
| 1357 | let tmpdir = TempDir::new().unwrap(); |
| 1358 | let root = tmpdir.path().join("skills"); |
| 1359 | let skill_dir = root.join("my-skill"); |
| 1360 | std::fs::create_dir_all(&skill_dir).unwrap(); |
| 1361 | std::fs::write( |
| 1362 | skill_dir.join("SKILL.md"), |
| 1363 | "---\nname: My Skill\ndescription: spaced name\n---\nbody", |
| 1364 | ) |
| 1365 | .unwrap(); |
| 1366 | |
| 1367 | let registry = super::SkillRegistry::discover(&root); |
| 1368 | let skill = registry.get(" MY skill ").expect("normalized lookup"); |
| 1369 | assert_eq!(skill.name, "my-skill"); |
| 1370 | assert!( |
| 1371 | registry |
| 1372 | .warnings() |
| 1373 | .iter() |
| 1374 | .any(|warning| warning.contains("My Skill") |
| 1375 | && warning.contains("using `my-skill` instead")), |
| 1376 | "expected invalid-name warning, got {:?}", |
| 1377 | registry.warnings() |
| 1378 | ); |
| 1379 | } |
| 1380 | |
| 1381 | #[test] |
| 1382 | fn discover_warns_for_plain_markdown_without_heading() { |
| 1383 | let tmpdir = TempDir::new().unwrap(); |
| 1384 | let skill_dir = tmpdir.path().join("plain-skill"); |
| 1385 | std::fs::create_dir_all(&skill_dir).unwrap(); |
| 1386 | std::fs::write( |
| 1387 | skill_dir.join("SKILL.md"), |
| 1388 | "Use this skill without a heading or YAML frontmatter.\n", |
| 1389 | ) |
| 1390 | .unwrap(); |
| 1391 | |
| 1392 | let registry = super::SkillRegistry::discover(tmpdir.path()); |
| 1393 | assert!(registry.is_empty()); |
| 1394 | assert!( |
| 1395 | registry |
| 1396 | .warnings() |
| 1397 | .iter() |
| 1398 | .any(|warning| warning.contains("no `# Heading` found")), |
| 1399 | "expected missing-heading warning, got {:?}", |
| 1400 | registry.warnings() |
| 1401 | ); |
| 1402 | } |
| 1403 | |
| 1404 | #[test] |
| 1405 | fn render_available_skills_context_for_workspace_picks_up_cross_tool_dirs() { |
| 1406 | let tmpdir = TempDir::new().unwrap(); |
| 1407 | let workspace = tmpdir.path(); |
| 1408 | codewhale_runtime::test_support::trust_workspace(workspace); |
| 1409 | write_skill( |
| 1410 | &workspace.join(".claude").join("skills"), |
| 1411 | "from-claude", |
| 1412 | "claude-style skill", |
| 1413 | "body", |
| 1414 | ); |
| 1415 | let rendered = |
| 1416 | super::render_available_skills_context_for_workspace(workspace).expect("non-empty"); |
| 1417 | assert!(rendered.contains("from-claude")); |
| 1418 | } |
| 1419 | |
| 1420 | #[test] |
| 1421 | fn codewhale_only_mode_ignores_cross_tool_skill_dirs() { |
| 1422 | let tmpdir = TempDir::new().unwrap(); |
| 1423 | let workspace = tmpdir.path().join("workspace"); |
| 1424 | let home = tmpdir.path().join("home"); |
| 1425 | let configured_dir = home.join(".codewhale").join("skills"); |
| 1426 | std::fs::create_dir_all(&workspace).unwrap(); |
| 1427 | codewhale_runtime::test_support::trust_workspace(&workspace); |
| 1428 | write_skill( |
| 1429 | &workspace.join(".claude").join("skills"), |
| 1430 | "from-claude", |
| 1431 | "claude-style skill", |
| 1432 | "body", |
| 1433 | ); |
| 1434 | write_skill( |
| 1435 | &workspace.join(".codewhale").join("skills"), |
| 1436 | "from-codewhale", |
| 1437 | "codewhale skill", |
| 1438 | "body", |
| 1439 | ); |
| 1440 | write_skill( |
| 1441 | &home.join(".agents").join("skills"), |
| 1442 | "from-agents", |
| 1443 | "agents skill", |
| 1444 | "body", |
| 1445 | ); |
| 1446 | write_skill( |
| 1447 | &configured_dir, |
| 1448 | "configured-codewhale", |
| 1449 | "configured skill", |
| 1450 | "body", |
| 1451 | ); |
| 1452 | |
| 1453 | let registry = super::discover_for_workspace_and_dir_with_home_and_mode( |
| 1454 | &workspace, |
| 1455 | &configured_dir, |
| 1456 | Some(&home), |
| 1457 | super::SkillDiscoveryMode::CodeWhaleOnly, |
| 1458 | ); |
| 1459 | let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect(); |
| 1460 | |
| 1461 | assert!(names.contains(&"from-codewhale")); |
| 1462 | assert!(names.contains(&"configured-codewhale")); |
| 1463 | assert!( |
| 1464 | !names.contains(&"from-claude") && !names.contains(&"from-agents"), |
| 1465 | "CodeWhale-only mode must not import cross-tool skills: {names:?}" |
| 1466 | ); |
| 1467 | } |
| 1468 | |
| 1469 | #[test] |
| 1470 | fn codewhale_only_mode_still_honors_explicit_configured_dir() { |
| 1471 | let tmpdir = TempDir::new().unwrap(); |
| 1472 | let workspace = tmpdir.path().join("workspace"); |
| 1473 | let home = tmpdir.path().join("home"); |
| 1474 | let configured_dir = tmpdir.path().join("my-skills"); |
| 1475 | std::fs::create_dir_all(&workspace).unwrap(); |
| 1476 | write_skill( |
| 1477 | &configured_dir, |
| 1478 | "configured-skill", |
| 1479 | "explicit configured skill", |
| 1480 | "body", |
| 1481 | ); |
| 1482 | |
| 1483 | let registry = super::discover_for_workspace_and_dir_with_home_and_mode( |
| 1484 | &workspace, |
| 1485 | &configured_dir, |
| 1486 | Some(&home), |
| 1487 | super::SkillDiscoveryMode::CodeWhaleOnly, |
| 1488 | ); |
| 1489 | let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect(); |
| 1490 | |
| 1491 | assert_eq!(names, vec!["configured-skill"]); |
| 1492 | } |
| 1493 | |
| 1494 | #[test] |
| 1495 | fn codewhale_only_mode_rejects_workspace_codewhale_symlink_escape() { |
| 1496 | let tmpdir = TempDir::new().unwrap(); |
| 1497 | let workspace = tmpdir.path().join("workspace"); |
| 1498 | let home = tmpdir.path().join("home"); |
| 1499 | let escape_target = tmpdir.path().join("escape-target"); |
| 1500 | std::fs::create_dir_all(workspace.join(".codewhale")).unwrap(); |
| 1501 | write_skill(&escape_target, "escaped-skill", "escaped skill", "body"); |
| 1502 | |
| 1503 | let link_path = workspace.join(".codewhale").join("skills"); |
| 1504 | if let Err(err) = create_dir_symlink(&escape_target, &link_path) { |
| 1505 | eprintln!("skipping symlink escape assertion: {err}"); |
| 1506 | return; |
| 1507 | } |
| 1508 | |
| 1509 | let registry = super::discover_for_workspace_and_dir_with_home_and_mode( |
| 1510 | &workspace, |
| 1511 | &tmpdir.path().join("missing-configured-skills"), |
| 1512 | Some(&home), |
| 1513 | super::SkillDiscoveryMode::CodeWhaleOnly, |
| 1514 | ); |
| 1515 | |
| 1516 | assert!( |
| 1517 | registry.get("escaped-skill").is_none(), |
| 1518 | "CodeWhale-only mode must not follow workspace .codewhale/skills outside the workspace" |
| 1519 | ); |
| 1520 | } |
| 1521 | |
| 1522 | #[test] |
| 1523 | fn discover_for_workspace_and_dir_merges_workspace_and_configured_sources() { |
| 1524 | let tmpdir = TempDir::new().unwrap(); |
| 1525 | let workspace = tmpdir.path().join("workspace"); |
| 1526 | let home = tmpdir.path().join("home"); |
| 1527 | let configured_dir = tmpdir.path().join("configured-skills"); |
| 1528 | std::fs::create_dir_all(&workspace).unwrap(); |
| 1529 | codewhale_runtime::test_support::trust_workspace(&workspace); |
| 1530 | write_skill( |
| 1531 | &workspace.join(".claude").join("skills"), |
| 1532 | "workspace-skill", |
| 1533 | "workspace visible skill", |
| 1534 | "body", |
| 1535 | ); |
| 1536 | write_skill( |
| 1537 | &configured_dir, |
| 1538 | "configured-skill", |
| 1539 | "configured visible skill", |
| 1540 | "body", |
| 1541 | ); |
| 1542 | |
| 1543 | let registry = |
| 1544 | super::discover_for_workspace_and_dir_with_home(&workspace, &configured_dir, Some(&home)); |
| 1545 | let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect(); |
| 1546 | |
| 1547 | assert!(names.contains(&"workspace-skill")); |
| 1548 | assert!(names.contains(&"configured-skill")); |
| 1549 | } |
| 1550 | |
| 1551 | #[test] |
| 1552 | fn explicit_configured_skills_dir_precedes_global_defaults() { |
| 1553 | let tmpdir = TempDir::new().unwrap(); |
| 1554 | let workspace = tmpdir.path().join("workspace"); |
| 1555 | let home = tmpdir.path().join("home"); |
| 1556 | let configured_dir = tmpdir.path().join("configured-skills"); |
| 1557 | std::fs::create_dir_all(&workspace).unwrap(); |
| 1558 | write_skill( |
| 1559 | &home.join(".agents").join("skills"), |
| 1560 | "shared-skill", |
| 1561 | "global skill", |
| 1562 | "global body", |
| 1563 | ); |
| 1564 | write_skill( |
| 1565 | &configured_dir, |
| 1566 | "shared-skill", |
| 1567 | "configured skill", |
| 1568 | "configured body", |
| 1569 | ); |
| 1570 | |
| 1571 | let registry = |
| 1572 | super::discover_for_workspace_and_dir_with_home(&workspace, &configured_dir, Some(&home)); |
| 1573 | let skill = registry |
| 1574 | .get("shared-skill") |
| 1575 | .expect("shared skill discovered"); |
| 1576 | |
| 1577 | assert_eq!(skill.description, "configured skill"); |
| 1578 | } |
| 1579 | |
| 1580 | /// Regression for the GitHub issue where users organize skills under |
| 1581 | /// vendor / category subdirectories (e.g. cloned skill repos that |
| 1582 | /// bundle several skills together). The old single-level `read_dir` |
| 1583 | /// only ever surfaced `<root>/<skill>/SKILL.md` and silently ignored |
| 1584 | /// `<root>/<vendor>/<skill>/SKILL.md`. |
| 1585 | #[test] |
| 1586 | fn discover_finds_skills_nested_under_vendor_subdirectory() { |
| 1587 | let tmpdir = TempDir::new().unwrap(); |
| 1588 | let root = tmpdir.path().join("skills"); |
| 1589 | |
| 1590 | // Two-level nesting: `<root>/<vendor>/<skill>/SKILL.md`. This |
| 1591 | // matches the `clawhub-skills/clawhub/SKILL.md` layout in the |
| 1592 | // bug report. |
| 1593 | write_skill( |
| 1594 | &root.join("clawhub-skills"), |
| 1595 | "clawhub", |
| 1596 | "claw search", |
| 1597 | "body", |
| 1598 | ); |
| 1599 | write_skill( |
| 1600 | &root.join("clawhub-skills"), |
| 1601 | "github", |
| 1602 | "github helpers", |
| 1603 | "body", |
| 1604 | ); |
| 1605 | // Three-level nesting: `<root>/<org>/<repo>/<skill>/SKILL.md`. |
| 1606 | write_skill( |
| 1607 | &root.join("pasky").join("chrome-cdp-skill"), |
| 1608 | "chrome-cdp", |
| 1609 | "browser automation", |
| 1610 | "body", |
| 1611 | ); |
| 1612 | // Mixed-depth: a flat skill alongside the nested layout still |
| 1613 | // works (this is what the bundled `skill-creator` looks like). |
| 1614 | write_skill(&root, "skill-creator", "make skills", "body"); |
| 1615 | |
| 1616 | let registry = super::SkillRegistry::discover(&root); |
| 1617 | let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect(); |
| 1618 | assert!(names.contains(&"clawhub"), "vendor/skill missed: {names:?}"); |
| 1619 | assert!(names.contains(&"github"), "vendor/skill missed: {names:?}"); |
| 1620 | assert!( |
| 1621 | names.contains(&"chrome-cdp"), |
| 1622 | "deeply-nested skill missed: {names:?}" |
| 1623 | ); |
| 1624 | assert!( |
| 1625 | names.contains(&"skill-creator"), |
| 1626 | "flat top-level skill must still load: {names:?}" |
| 1627 | ); |
| 1628 | assert!( |
| 1629 | registry.warnings().is_empty(), |
| 1630 | "well-formed nested layout should not warn: {:?}", |
| 1631 | registry.warnings() |
| 1632 | ); |
| 1633 | } |
| 1634 | |
| 1635 | #[cfg(any(unix, windows))] |
| 1636 | #[test] |
| 1637 | fn discover_follows_symlinked_skill_directories() { |
| 1638 | let tmpdir = TempDir::new().unwrap(); |
| 1639 | let source_root = tmpdir.path().join("claude-skills"); |
| 1640 | let skills_root = tmpdir.path().join(".deepseek").join("skills"); |
| 1641 | write_skill(&source_root, "agent-browser", "browser automation", "body"); |
| 1642 | std::fs::create_dir_all(&skills_root).unwrap(); |
| 1643 | let link_path = skills_root.join("agent-browser"); |
| 1644 | |
| 1645 | if let Err(err) = create_dir_symlink(&source_root.join("agent-browser"), &link_path) { |
| 1646 | eprintln!("skipping symlink discovery assertion: {err}"); |
| 1647 | return; |
| 1648 | } |
| 1649 | |
| 1650 | let registry = super::SkillRegistry::discover(&skills_root); |
| 1651 | let skill = registry |
| 1652 | .get("agent-browser") |
| 1653 | .expect("symlinked skill directory should be discovered"); |
| 1654 | assert_eq!(skill.description, "browser automation"); |
| 1655 | assert_eq!(skill.path, link_path.join("SKILL.md")); |
| 1656 | } |
| 1657 | |
| 1658 | #[cfg(any(unix, windows))] |
| 1659 | #[test] |
| 1660 | fn discover_dedupes_symlink_cycles_by_canonical_directory() { |
| 1661 | let tmpdir = TempDir::new().unwrap(); |
| 1662 | let root = tmpdir.path().join("skills"); |
| 1663 | write_skill(&root, "real-skill", "ok", "body"); |
| 1664 | let loop_parent = root.join("vendor"); |
| 1665 | std::fs::create_dir_all(&loop_parent).unwrap(); |
| 1666 | |
| 1667 | if let Err(err) = create_dir_symlink(&root, &loop_parent.join("loop")) { |
| 1668 | eprintln!("skipping symlink cycle assertion: {err}"); |
| 1669 | return; |
| 1670 | } |
| 1671 | |
| 1672 | let registry = super::SkillRegistry::discover(&root); |
| 1673 | let matches = registry |
| 1674 | .list() |
| 1675 | .iter() |
| 1676 | .filter(|skill| skill.name == "real-skill") |
| 1677 | .count(); |
| 1678 | assert_eq!( |
| 1679 | matches, 1, |
| 1680 | "symlink cycle should not rediscover the same canonical skill directory" |
| 1681 | ); |
| 1682 | } |
| 1683 | |
| 1684 | /// Once a directory is identified as a skill (has `SKILL.md`), the |
| 1685 | /// walker must NOT descend into it: any nested `SKILL.md` would be |
| 1686 | /// a fixture / example bundled with the parent skill, not a |
| 1687 | /// separately-installable one. This mirrors the contract that |
| 1688 | /// `tools::skill::collect_companion_files` already documents |
| 1689 | /// ("nested directory — skipped"). |
| 1690 | #[test] |
| 1691 | fn discover_does_not_descend_into_a_skill_directory() { |
| 1692 | let tmpdir = TempDir::new().unwrap(); |
| 1693 | let root = tmpdir.path().join("skills"); |
| 1694 | |
| 1695 | // Parent skill: <root>/parent/SKILL.md. |
| 1696 | write_skill(&root, "parent", "outer skill", "outer body"); |
| 1697 | // Fixture bundled inside the parent's directory: |
| 1698 | // <root>/parent/examples/inner-fixture/SKILL.md. The walker |
| 1699 | // must NOT descend into <root>/parent/ after finding its |
| 1700 | // SKILL.md, so `inner-fixture` must not be loaded. |
| 1701 | write_skill( |
| 1702 | &root.join("parent").join("examples"), |
| 1703 | "inner-fixture", |
| 1704 | "should not load", |
| 1705 | "fixture body", |
| 1706 | ); |
| 1707 | |
| 1708 | let registry = super::SkillRegistry::discover(&root); |
| 1709 | let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect(); |
| 1710 | assert!(names.contains(&"parent")); |
| 1711 | assert!( |
| 1712 | !names.contains(&"inner-fixture"), |
| 1713 | "nested SKILL.md inside an existing skill must be ignored: {names:?}" |
| 1714 | ); |
| 1715 | } |
| 1716 | |
| 1717 | /// Hidden subdirectories below the root (e.g. `.git`, `.cache`) must |
| 1718 | /// be skipped so a `skills_dir` that lives inside a checked-out repo |
| 1719 | /// doesn't accidentally load random `SKILL.md`-named fixtures from |
| 1720 | /// the VCS metadata. The root itself is exempt — the user explicitly |
| 1721 | /// pointed `skills_dir` at it. |
| 1722 | #[test] |
| 1723 | fn discover_skips_hidden_subdirectories_below_root() { |
| 1724 | let tmpdir = TempDir::new().unwrap(); |
| 1725 | let root = tmpdir.path().join("skills"); |
| 1726 | |
| 1727 | write_skill(&root, "real-skill", "ok", "body"); |
| 1728 | // A `<root>/.git/<junk>/SKILL.md` lookalike that mustn't load. |
| 1729 | // `.git` is a direct child of the user-provided root (depth 0 |
| 1730 | // of the walk), which is exactly the case the old `depth > 0` |
| 1731 | // gate missed. |
| 1732 | write_skill(&root.join(".git"), "vcs-noise", "should not load", "body"); |
| 1733 | |
| 1734 | let registry = super::SkillRegistry::discover(&root); |
| 1735 | let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect(); |
| 1736 | assert!(names.contains(&"real-skill")); |
| 1737 | assert!( |
| 1738 | !names.contains(&"vcs-noise"), |
| 1739 | "skills under hidden subdirs must be skipped: {names:?}" |
| 1740 | ); |
| 1741 | } |
| 1742 | |
| 1743 | /// The user explicitly chooses the root, so even a hidden path like |
| 1744 | /// `~/.agents/skills` (the layout in the bug report) must work. |
| 1745 | #[test] |
| 1746 | fn discover_honors_a_hidden_root_directory() { |
| 1747 | let tmpdir = TempDir::new().unwrap(); |
| 1748 | let root = tmpdir.path().join(".agents").join("skills"); |
| 1749 | |
| 1750 | // Matches the bug report: skills_dir = "~/.agents/skills" |
| 1751 | // with a skill nested at <root>/custom-skills/git-conventions/SKILL.md. |
| 1752 | write_skill( |
| 1753 | &root.join("custom-skills"), |
| 1754 | "git-conventions", |
| 1755 | "conventions", |
| 1756 | "body", |
| 1757 | ); |
| 1758 | |
| 1759 | let registry = super::SkillRegistry::discover(&root); |
| 1760 | let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect(); |
| 1761 | assert!( |
| 1762 | names.contains(&"git-conventions"), |
| 1763 | "hidden root must still be walked: {names:?}" |
| 1764 | ); |
| 1765 | } |
| 1766 | |
| 1767 | /// Exercises the local/global skill inventory independent of terminal layout. |
| 1768 | /// scenario without the PTY harness: a workspace-level skill in |
| 1769 | /// `.agents/skills/` and a global skill in `~/.codewhale/skills/` |
| 1770 | /// must both be discoverable. |
| 1771 | #[test] |
| 1772 | fn discover_finds_both_workspace_and_global_skills() { |
| 1773 | let tmpdir = TempDir::new().unwrap(); |
| 1774 | let workspace = tmpdir.path().join("workspace"); |
| 1775 | let home = tmpdir.path().join("home"); |
| 1776 | std::fs::create_dir_all(&workspace).unwrap(); |
| 1777 | |
| 1778 | write_skill( |
| 1779 | &workspace.join(".agents").join("skills"), |
| 1780 | "workspace-beta", |
| 1781 | "Workspace beta skill", |
| 1782 | "body", |
| 1783 | ); |
| 1784 | write_skill( |
| 1785 | &home.join(".codewhale").join("skills"), |
| 1786 | "global-alpha", |
| 1787 | "Global alpha skill", |
| 1788 | "body", |
| 1789 | ); |
| 1790 | |
| 1791 | codewhale_runtime::test_support::trust_workspace(&workspace); |
| 1792 | let skills_dir = workspace.join(".agents").join("skills"); |
| 1793 | let registry = |
| 1794 | super::discover_for_workspace_and_dir_with_home(&workspace, &skills_dir, Some(&home)); |
| 1795 | |
| 1796 | let names: Vec<&str> = registry.list().iter().map(|s| s.name.as_str()).collect(); |
| 1797 | assert!( |
| 1798 | names.contains(&"workspace-beta"), |
| 1799 | "workspace-beta from .agents/skills must be discovered: {names:?}", |
| 1800 | ); |
| 1801 | assert!( |
| 1802 | names.contains(&"global-alpha"), |
| 1803 | "global-alpha from ~/.codewhale/skills must be discovered: {names:?}", |
| 1804 | ); |
| 1805 | } |
| 1806 | |
| 1807 | // ── Block scalar parsing (YAML `>` and `|`) ──────────────── |
| 1808 | |
| 1809 | /// `>` (folded block scalar): subsequent indented lines are folded |
| 1810 | /// into a single line joined by spaces. |
| 1811 | #[test] |
| 1812 | fn parse_skill_folded_block_scalar() { |
| 1813 | let tmpdir = TempDir::new().unwrap(); |
| 1814 | create_skill_dir( |
| 1815 | &tmpdir, |
| 1816 | "folded-skill", |
| 1817 | "---\nname: folded-skill\ndescription: >\n line one chinese\n line two chinese\n---\nbody", |
| 1818 | ); |
| 1819 | let rendered = crate::render_available_skills_context(&tmpdir.path().join("skills")) |
| 1820 | .expect("skill context"); |
| 1821 | assert!( |
| 1822 | rendered.contains("line one chinese line two chinese"), |
| 1823 | "folded block scalar should join lines with space, got:\n{rendered}" |
| 1824 | ); |
| 1825 | } |
| 1826 | |
| 1827 | /// `|` (literal block scalar): subsequent indented lines preserve |
| 1828 | /// newlines. |
| 1829 | #[test] |
| 1830 | fn parse_skill_literal_block_scalar() { |
| 1831 | let tmpdir = TempDir::new().unwrap(); |
| 1832 | create_skill_dir( |
| 1833 | &tmpdir, |
| 1834 | "literal-skill", |
| 1835 | "---\nname: literal-skill\ndescription: |\n line one\n line two\n---\nbody", |
| 1836 | ); |
| 1837 | let rendered = crate::render_available_skills_context(&tmpdir.path().join("skills")) |
| 1838 | .expect("skill context"); |
| 1839 | // `truncate_for_prompt` collapses whitespace, so the newlines |
| 1840 | // become spaces. The key assertion is that the content is |
| 1841 | // captured (not just `|`). |
| 1842 | assert!( |
| 1843 | rendered.contains("line one line two"), |
| 1844 | "literal block scalar should preserve content, got:\n{rendered}" |
| 1845 | ); |
| 1846 | } |
| 1847 | |
| 1848 | /// `>-` (folded with strip chomping): same as `>` but trailing |
| 1849 | /// whitespace is stripped. |
| 1850 | #[test] |
| 1851 | fn parse_skill_folded_strip_block_scalar() { |
| 1852 | let tmpdir = TempDir::new().unwrap(); |
| 1853 | create_skill_dir( |
| 1854 | &tmpdir, |
| 1855 | "strip-skill", |
| 1856 | "---\nname: strip-skill\ndescription: >-\n alpha\n beta\n\n---\nbody", |
| 1857 | ); |
| 1858 | let rendered = crate::render_available_skills_context(&tmpdir.path().join("skills")) |
| 1859 | .expect("skill context"); |
| 1860 | assert!( |
| 1861 | rendered.contains("alpha beta"), |
| 1862 | "strip-chomped folded block should join lines, got:\n{rendered}" |
| 1863 | ); |
| 1864 | } |
| 1865 | |
| 1866 | /// Regression: a single-line description (no block scalar) must |
| 1867 | /// still parse correctly after the parser rewrite. |
| 1868 | #[test] |
| 1869 | fn parse_skill_single_line_description_still_works() { |
| 1870 | let tmpdir = TempDir::new().unwrap(); |
| 1871 | create_skill_dir( |
| 1872 | &tmpdir, |
| 1873 | "plain-skill", |
| 1874 | "---\nname: plain-skill\ndescription: A simple description\n---\nbody", |
| 1875 | ); |
| 1876 | let rendered = crate::render_available_skills_context(&tmpdir.path().join("skills")) |
| 1877 | .expect("skill context"); |
| 1878 | assert!( |
| 1879 | rendered.contains("- plain-skill: A simple description"), |
| 1880 | "single-line description should still work, got:\n{rendered}" |
| 1881 | ); |
| 1882 | } |
| 1883 | |
| 1884 | /// Direct unit test on the parsed Skill struct (not through rendering) |
| 1885 | /// so we assert the exact description value. |
| 1886 | #[test] |
| 1887 | fn parse_skill_direct_folded_result() { |
| 1888 | let skill = super::SkillRegistry::parse_skill( |
| 1889 | std::path::Path::new(""), |
| 1890 | "---\nname: test\ndescription: >\n this is a test\n used to verify parsing\n---\nbody", |
| 1891 | ) |
| 1892 | .expect("should parse"); |
| 1893 | assert_eq!(skill.name, "test"); |
| 1894 | assert_eq!(skill.description, "this is a test used to verify parsing"); |
| 1895 | } |
| 1896 | |
| 1897 | // ── Chomping behaviour ──────────────────────────────────── |
| 1898 | |
| 1899 | /// `>-` (strip): trailing empty lines are stripped. Paragraph |
| 1900 | /// breaks (empty line between text lines) are still folded to a |
| 1901 | /// single space in a block-scalar join (no newline — the simplified |
| 1902 | /// parser treats intra-block empty lines as paragraph breaks that |
| 1903 | /// become a single space in the folded output). |
| 1904 | #[test] |
| 1905 | fn parse_skill_strip_chomp_strips_trailing_empties() { |
| 1906 | let skill = super::SkillRegistry::parse_skill( |
| 1907 | std::path::Path::new(""), |
| 1908 | "---\nname: s\ndescription: >-\n hello\n world\n\n\n---\nbody", |
| 1909 | ) |
| 1910 | .expect("should parse"); |
| 1911 | // Trailing empty lines stripped: no whitespace at end, just folded text. |
| 1912 | assert_eq!(skill.description, "hello world"); |
| 1913 | } |
| 1914 | |
| 1915 | /// `>+` (keep): trailing empty lines are preserved. Each trailing |
| 1916 | /// empty line in the block becomes a newline in the description. |
| 1917 | #[test] |
| 1918 | fn parse_skill_keep_chomp_preserves_trailing_empties() { |
| 1919 | let skill = super::SkillRegistry::parse_skill( |
| 1920 | std::path::Path::new(""), |
| 1921 | "---\nname: s\ndescription: >+\n hello\n world\n\n\n---\nbody", |
| 1922 | ) |
| 1923 | .expect("should parse"); |
| 1924 | // Two trailing empty lines should become two newlines. |
| 1925 | assert_eq!(skill.description, "hello world\n\n"); |
| 1926 | } |
| 1927 | |
| 1928 | /// `>` (clip): trailing empty lines exceeding one are clipped. |
| 1929 | /// The result should have at most one trailing newline. |
| 1930 | #[test] |
| 1931 | fn parse_skill_clip_chomp_clips_excess_trailing_empties() { |
| 1932 | let skill = super::SkillRegistry::parse_skill( |
| 1933 | std::path::Path::new(""), |
| 1934 | "---\nname: s\ndescription: >\n hello\n world\n\n\n---\nbody", |
| 1935 | ) |
| 1936 | .expect("should parse"); |
| 1937 | // clip: 3 trailing empty lines → at most 1 trailing newline. |
| 1938 | assert_eq!(skill.description, "hello world\n"); |
| 1939 | } |
| 1940 | |
| 1941 | /// `>` with no trailing empty lines: clip should not add anything. |
| 1942 | #[test] |
| 1943 | fn parse_skill_clip_chomp_no_trailing_empties() { |
| 1944 | let skill = super::SkillRegistry::parse_skill( |
| 1945 | std::path::Path::new(""), |
| 1946 | "---\nname: s\ndescription: >\n hello\n world\n---\nbody", |
| 1947 | ) |
| 1948 | .expect("should parse"); |
| 1949 | assert_eq!(skill.description, "hello world"); |
| 1950 | } |
| 1951 | |
| 1952 | /// `>` with exactly one trailing empty line: clip keeps it. |
| 1953 | #[test] |
| 1954 | fn parse_skill_clip_chomp_one_trailing_empty() { |
| 1955 | let skill = super::SkillRegistry::parse_skill( |
| 1956 | std::path::Path::new(""), |
| 1957 | "---\nname: s\ndescription: >\n hello\n world\n\n---\nbody", |
| 1958 | ) |
| 1959 | .expect("should parse"); |
| 1960 | assert_eq!(skill.description, "hello world\n"); |
| 1961 | } |
| 1962 | |
| 1963 | /// `>-` strip vs `>+` keep: same block content, different |
| 1964 | /// trailing newline handling. |
| 1965 | #[test] |
| 1966 | fn parse_skill_strip_vs_keep_trailing() { |
| 1967 | let content = "---\nname: s\ndescription: >{}\n hello\n world\n\n\n---\nbody"; |
| 1968 | let strip_skill = |
| 1969 | super::SkillRegistry::parse_skill(std::path::Path::new(""), &content.replace("{}", "-")) |
| 1970 | .expect("strip parse"); |
| 1971 | let keep_skill = |
| 1972 | super::SkillRegistry::parse_skill(std::path::Path::new(""), &content.replace("{}", "+")) |
| 1973 | .expect("keep parse"); |
| 1974 | // strip drops trailing empties; keep preserves them. |
| 1975 | assert_eq!(strip_skill.description, "hello world"); |
| 1976 | assert_eq!(keep_skill.description, "hello world\n\n"); |
| 1977 | } |
| 1978 | |
| 1979 | /// `|-` literal strip: trailing newlines are stripped. |
| 1980 | #[test] |
| 1981 | fn parse_skill_literal_strip_strips_trailing_newlines() { |
| 1982 | let skill = super::SkillRegistry::parse_skill( |
| 1983 | std::path::Path::new(""), |
| 1984 | "---\nname: s\ndescription: |-\n line one\n line two\n\n\n---\nbody", |
| 1985 | ) |
| 1986 | .expect("should parse"); |
| 1987 | // literal: newlines preserved between non-empty lines. |
| 1988 | // strip: trailing empty lines removed. |
| 1989 | assert_eq!(skill.description, "line one\nline two"); |
| 1990 | } |
| 1991 | |
| 1992 | /// `|+` literal keep: trailing newlines are preserved. |
| 1993 | #[test] |
| 1994 | fn parse_skill_literal_keep_preserves_trailing_newlines() { |
| 1995 | let skill = super::SkillRegistry::parse_skill( |
| 1996 | std::path::Path::new(""), |
| 1997 | "---\nname: s\ndescription: |+\n line one\n line two\n\n\n---\nbody", |
| 1998 | ) |
| 1999 | .expect("should parse"); |
| 2000 | // literal: newlines preserved between non-empty lines. |
| 2001 | // keep: trailing empty lines are preserved as newlines. |
| 2002 | assert_eq!(skill.description, "line one\nline two\n\n"); |
| 2003 | } |
| 2004 | |
| 2005 | /// Nested relative indentation is preserved in literal (`|`) block |
| 2006 | /// scalars: only the content-level indent (from the first non-empty |
| 2007 | /// line) is stripped, and any deeper indent stays as-is. |
| 2008 | #[test] |
| 2009 | fn parse_skill_literal_preserves_relative_indentation() { |
| 2010 | let skill = super::SkillRegistry::parse_skill( |
| 2011 | std::path::Path::new(""), |
| 2012 | "---\nname: s\ndescription: |\n Usage:\n $ deepseek --model auto\n $ deepseek doctor\n---\nbody", |
| 2013 | ) |
| 2014 | .expect("should parse"); |
| 2015 | assert_eq!( |
| 2016 | skill.description, |
| 2017 | "Usage:\n $ deepseek --model auto\n $ deepseek doctor" |
| 2018 | ); |
| 2019 | } |
| 2020 | |
| 2021 | /// Folded (`>`) block scalars also preserve relative indentation |
| 2022 | /// within lines (the extra spaces survive the fold). |
| 2023 | #[test] |
| 2024 | fn parse_skill_folded_preserves_relative_indentation() { |
| 2025 | let skill = super::SkillRegistry::parse_skill( |
| 2026 | std::path::Path::new(""), |
| 2027 | "---\nname: s\ndescription: >\n See also:\n the config file\n the env var\n---\nbody", |
| 2028 | ) |
| 2029 | .expect("should parse"); |
| 2030 | assert_eq!( |
| 2031 | skill.description, |
| 2032 | "See also: the config file the env var" |
| 2033 | ); |
| 2034 | } |
| 2035 | |
| 2036 | #[test] |
| 2037 | fn plugin_skills_are_qualified_and_denied_until_trusted_and_enabled() { |
| 2038 | let tmp = TempDir::new().unwrap(); |
| 2039 | let plugin_root = tmp.path().join("plugins/demo"); |
| 2040 | std::fs::create_dir_all(plugin_root.join("skills/hello-world")).unwrap(); |
| 2041 | std::fs::write( |
| 2042 | plugin_root.join("plugin.toml"), |
| 2043 | "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n", |
| 2044 | ) |
| 2045 | .unwrap(); |
| 2046 | std::fs::write( |
| 2047 | plugin_root.join("skills/hello-world/SKILL.md"), |
| 2048 | "---\nname: hello-world\ndescription: hello\n---\nbody\n", |
| 2049 | ) |
| 2050 | .unwrap(); |
| 2051 | let config = codewhale_plugins::discovery::DiscoveryConfig { |
| 2052 | workspace: tmp.path().join("workspace"), |
| 2053 | user_plugins_dir: tmp.path().join("plugins"), |
| 2054 | workspace_plugins_dir: tmp.path().join("workspace-plugins"), |
| 2055 | builtin_plugin_dirs: Vec::new(), |
| 2056 | state_path: tmp.path().join("plugin-state/state.json"), |
| 2057 | }; |
| 2058 | let mut plugins = codewhale_plugins::discovery::discover_with_config(&config); |
| 2059 | |
| 2060 | let mut registry = super::SkillRegistry::default(); |
| 2061 | super::merge_active_plugin_skills(&mut registry, &plugins); |
| 2062 | assert!(registry.get("demo:hello-world").is_none()); |
| 2063 | |
| 2064 | plugins.trust("demo").unwrap(); |
| 2065 | super::merge_active_plugin_skills(&mut registry, &plugins); |
| 2066 | assert!(registry.get("demo:hello-world").is_none()); |
| 2067 | |
| 2068 | plugins.enable("demo").unwrap(); |
| 2069 | super::merge_active_plugin_skills(&mut registry, &plugins); |
| 2070 | let skill = registry |
| 2071 | .get("Demo:Hello_World") |
| 2072 | .expect("qualified lookup should normalize each namespace segment"); |
| 2073 | assert_eq!(skill.name, "demo:hello-world"); |
| 2074 | assert!(matches!( |
| 2075 | skill.source, |
| 2076 | super::SkillSource::Plugin { ref plugin_name, .. } if plugin_name == "demo" |
| 2077 | )); |
| 2078 | let rendered = super::render_skills_block(®istry, "en", tmp.path()).unwrap(); |
| 2079 | assert!(rendered.contains("reviewed plugin snapshot: demo")); |
| 2080 | assert!(rendered.contains("use load_skill")); |
| 2081 | assert!( |
| 2082 | rendered.contains("hello"), |
| 2083 | "plugin skill descriptions must reach the model catalogue like native skills: {rendered}" |
| 2084 | ); |
| 2085 | assert!( |
| 2086 | !rendered.contains(&plugin_root.display().to_string()), |
| 2087 | "model prompt must not expose mutable plugin files after snapshot review" |
| 2088 | ); |
| 2089 | |
| 2090 | let mut fail_closed_input = registry.clone(); |
| 2091 | fail_closed_input.skills.push(super::Skill { |
| 2092 | legacy_activation_name: None, |
| 2093 | name: "native-recovery".to_string(), |
| 2094 | description: "native recovery skill".to_string(), |
| 2095 | localized_descriptions: std::collections::HashMap::new(), |
| 2096 | invocation: super::SkillInvocation::ModelAndUser, |
| 2097 | dependencies: Default::default(), |
| 2098 | aliases: Vec::new(), |
| 2099 | argument_hint: None, |
| 2100 | body: "recovery".to_string(), |
| 2101 | path: tmp.path().join("native/SKILL.md"), |
| 2102 | source: super::SkillSource::Native, |
| 2103 | }); |
| 2104 | let fail_closed = fail_closed_input.into_enabled_with_state(Err(anyhow::anyhow!( |
| 2105 | "injected activation-state read failure" |
| 2106 | ))); |
| 2107 | assert!(fail_closed.get("native-recovery").is_some()); |
| 2108 | assert!( |
| 2109 | fail_closed.get("demo:hello-world").is_none(), |
| 2110 | "reviewed plugin Skills must not fail open when activation state is unreadable" |
| 2111 | ); |
| 2112 | assert!( |
| 2113 | fail_closed |
| 2114 | .warnings() |
| 2115 | .iter() |
| 2116 | .any(|warning| warning.contains("hidden fail-closed")) |
| 2117 | ); |
| 2118 | |
| 2119 | std::fs::remove_file(config.state_path.with_file_name("state.json.lock")).unwrap(); |
| 2120 | let mut denied = super::SkillRegistry::default(); |
| 2121 | super::merge_active_plugin_skills(&mut denied, &plugins); |
| 2122 | assert!( |
| 2123 | denied.get("demo:hello-world").is_none(), |
| 2124 | "a missing authority lock must remove plugin instructions from the prompt catalogue" |
| 2125 | ); |
| 2126 | } |
| 2127 | |
| 2128 | // --- #3921 merged discovery cache ----------------------------------------- |
| 2129 | |
| 2130 | fn discovery_delta_since(earlier: super::SkillDiscoveryMetrics) -> super::SkillDiscoveryMetrics { |
| 2131 | super::discovery_metrics_snapshot().delta_since(earlier) |
| 2132 | } |
| 2133 | |
| 2134 | /// Run a cache-hit measurement on a cache no other test emptied meanwhile. |
| 2135 | /// |
| 2136 | /// The discovery cache is process-wide. Under `cargo test` every test shares |
| 2137 | /// it, and other tests (and the app code they drive) empty it at any moment, |
| 2138 | /// which turns a genuine hit into a re-walk. Each attempt starts from an |
| 2139 | /// empty cache and is kept only if nothing else dropped the cache while it |
| 2140 | /// ran. |
| 2141 | fn measure_on_undisturbed_cache<T>(mut measure: impl FnMut() -> T) -> T { |
| 2142 | for _ in 0..200 { |
| 2143 | super::clear_skill_discovery_cache(); |
| 2144 | let drops = super::discovery_cache_drops(); |
| 2145 | let measured = measure(); |
| 2146 | if super::discovery_cache_drops() == drops { |
| 2147 | return measured; |
| 2148 | } |
| 2149 | } |
| 2150 | panic!("other tests emptied the shared skill discovery cache during every attempt"); |
| 2151 | } |
| 2152 | |
| 2153 | #[test] |
| 2154 | fn cached_discovery_reuses_unchanged_registry_without_rewalking() { |
| 2155 | let tmpdir = TempDir::new().unwrap(); |
| 2156 | let skills_root = tmpdir.path().join("skills"); |
| 2157 | write_skill(&skills_root, "demo", "A demo skill", "Instructions"); |
| 2158 | let dirs = vec![skills_root]; |
| 2159 | |
| 2160 | let (first, walked, second, rewalked) = measure_on_undisturbed_cache(|| { |
| 2161 | super::reset_discovery_metrics(); |
| 2162 | let first = super::discover_from_directories_with_plugins(dirs.clone(), None); |
| 2163 | let walked = discovery_delta_since(super::SkillDiscoveryMetrics::default()); |
| 2164 | let second = super::discover_from_directories_with_plugins(dirs.clone(), None); |
| 2165 | let rewalked = discovery_delta_since(walked); |
| 2166 | (first, walked, second, rewalked) |
| 2167 | }); |
| 2168 | |
| 2169 | assert_eq!(walked.root_discovery_calls, 1); |
| 2170 | assert_eq!(rewalked, super::SkillDiscoveryMetrics::default()); |
| 2171 | assert_eq!(first.len(), second.len()); |
| 2172 | assert_eq!(first.list()[0].description, second.list()[0].description); |
| 2173 | } |
| 2174 | |
| 2175 | #[test] |
| 2176 | fn cached_discovery_reuses_shared_roots_across_worktrees() { |
| 2177 | let temp = TempDir::new().unwrap(); |
| 2178 | let home = temp.path().join("global"); |
| 2179 | let first = temp.path().join("tree-a"); |
| 2180 | let second = temp.path().join("tree-b"); |
| 2181 | for dir in [&home, &first, &second] { |
| 2182 | write_skill(dir, "shared", "A description", &dir.to_string_lossy()); |
| 2183 | } |
| 2184 | let (delta, selected) = measure_on_undisturbed_cache(|| { |
| 2185 | super::reset_discovery_metrics(); |
| 2186 | super::discover_from_directories_in_workspace( |
| 2187 | [first.clone(), home.clone()], |
| 2188 | Some(&first), |
| 2189 | None, |
| 2190 | ); |
| 2191 | let initial = discovery_delta_since(super::SkillDiscoveryMetrics::default()); |
| 2192 | let current = super::discover_from_directories_in_workspace( |
| 2193 | [second.clone(), home.clone()], |
| 2194 | Some(&second), |
| 2195 | None, |
| 2196 | ); |
| 2197 | ( |
| 2198 | discovery_delta_since(initial), |
| 2199 | current.get("shared").unwrap().body.clone(), |
| 2200 | ) |
| 2201 | }); |
| 2202 | assert_eq!(delta.root_discovery_calls, 1); |
| 2203 | assert_eq!(delta.skill_md_read_attempts, 1); |
| 2204 | assert_eq!(selected, second.to_string_lossy()); |
| 2205 | } |
| 2206 | |
| 2207 | #[test] |
| 2208 | fn shared_snapshot_sees_a_repaired_skill_and_a_previously_absent_root() { |
| 2209 | let temp = TempDir::new().unwrap(); |
| 2210 | let root = temp.path().join("shared"); |
| 2211 | let dir = root.join("sample"); |
| 2212 | let discover = |workspace: &str| { |
| 2213 | super::discover_from_directories_in_workspace( |
| 2214 | [root.clone()], |
| 2215 | Some(&temp.path().join(workspace)), |
| 2216 | None, |
| 2217 | ) |
| 2218 | }; |
| 2219 | assert!(discover("worktree-a").is_empty()); |
| 2220 | std::fs::create_dir_all(&dir).unwrap(); |
| 2221 | std::fs::write(dir.join("SKILL.md"), "plain text without a heading").unwrap(); |
| 2222 | let broken = discover("worktree-b"); |
| 2223 | assert!(broken.is_empty()); |
| 2224 | assert!(!broken.warnings().is_empty()); |
| 2225 | write_skill(&root, "sample", "Repaired skill", "Resolve the tide."); |
| 2226 | assert_eq!( |
| 2227 | discover("worktree-a").get("sample").unwrap().body, |
| 2228 | "Resolve the tide." |
| 2229 | ); |
| 2230 | } |
| 2231 | |
| 2232 | #[cfg(unix)] |
| 2233 | #[test] |
| 2234 | fn shared_skill_snapshot_tracks_permission_only_changes() { |
| 2235 | use std::os::unix::fs::PermissionsExt; |
| 2236 | let temp = TempDir::new().unwrap(); |
| 2237 | let root = temp.path().join("global"); |
| 2238 | write_skill(&root, "demo", "Demo skill", "Read me"); |
| 2239 | let path = root.join("demo/SKILL.md"); |
| 2240 | let discover = || super::discover_from_directories_with_plugins([root.clone()], None); |
| 2241 | assert!(discover().get("demo").is_some()); |
| 2242 | std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap(); |
| 2243 | let readable = codewhale_util::fs_confined::open_user_read(&path).is_ok(); |
| 2244 | assert_eq!(discover().get("demo").is_some(), readable); |
| 2245 | std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); |
| 2246 | assert!(discover().get("demo").is_some()); |
| 2247 | } |
| 2248 | |
| 2249 | #[test] |
| 2250 | fn cached_discovery_picks_up_added_skill_on_next_call() { |
| 2251 | super::clear_skill_discovery_cache(); |
| 2252 | let tmpdir = TempDir::new().unwrap(); |
| 2253 | let skills_root = tmpdir.path().join("skills"); |
| 2254 | write_skill(&skills_root, "demo", "A demo skill", "Instructions"); |
| 2255 | let dirs = vec![skills_root.clone()]; |
| 2256 | |
| 2257 | let first = super::discover_from_directories_with_plugins(dirs.clone(), None); |
| 2258 | assert_eq!(first.len(), 1); |
| 2259 | |
| 2260 | write_skill(&skills_root, "added", "A later skill", "More"); |
| 2261 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 2262 | let second = super::discover_from_directories_with_plugins(dirs, None); |
| 2263 | assert_eq!(second.len(), 2); |
| 2264 | assert!(second.get("added").is_some()); |
| 2265 | } |
| 2266 | |
| 2267 | #[test] |
| 2268 | fn cached_discovery_picks_up_skill_content_edits() { |
| 2269 | super::clear_skill_discovery_cache(); |
| 2270 | let tmpdir = TempDir::new().unwrap(); |
| 2271 | let skills_root = tmpdir.path().join("skills"); |
| 2272 | write_skill(&skills_root, "demo", "Original description", "Instructions"); |
| 2273 | let dirs = vec![skills_root.clone()]; |
| 2274 | |
| 2275 | let first = super::discover_from_directories_with_plugins(dirs.clone(), None); |
| 2276 | assert_eq!(first.list()[0].description, "Original description"); |
| 2277 | |
| 2278 | write_skill(&skills_root, "demo", "Edited description", "Instructions"); |
| 2279 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 2280 | let second = super::discover_from_directories_with_plugins(dirs, None); |
| 2281 | assert_eq!(second.list()[0].description, "Edited description"); |
| 2282 | } |
| 2283 | |
| 2284 | #[test] |
| 2285 | fn cached_discovery_drops_removed_skills() { |
| 2286 | super::clear_skill_discovery_cache(); |
| 2287 | let tmpdir = TempDir::new().unwrap(); |
| 2288 | let skills_root = tmpdir.path().join("skills"); |
| 2289 | write_skill(&skills_root, "keep", "Keep me", "Instructions"); |
| 2290 | write_skill(&skills_root, "drop", "Drop me", "Instructions"); |
| 2291 | let dirs = vec![skills_root.clone()]; |
| 2292 | |
| 2293 | let first = super::discover_from_directories_with_plugins(dirs.clone(), None); |
| 2294 | assert_eq!(first.len(), 2); |
| 2295 | |
| 2296 | std::fs::remove_dir_all(skills_root.join("drop")).unwrap(); |
| 2297 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 2298 | let second = super::discover_from_directories_with_plugins(dirs, None); |
| 2299 | assert_eq!(second.len(), 1); |
| 2300 | assert!(second.get("drop").is_none()); |
| 2301 | } |
| 2302 | |
| 2303 | #[test] |
| 2304 | fn clear_skill_discovery_cache_forces_a_fresh_walk() { |
| 2305 | super::clear_skill_discovery_cache(); |
| 2306 | let tmpdir = TempDir::new().unwrap(); |
| 2307 | let skills_root = tmpdir.path().join("skills"); |
| 2308 | write_skill(&skills_root, "demo", "A demo skill", "Instructions"); |
| 2309 | let dirs = vec![skills_root]; |
| 2310 | |
| 2311 | let _ = super::discover_from_directories_with_plugins(dirs.clone(), None); |
| 2312 | super::clear_skill_discovery_cache(); |
| 2313 | |
| 2314 | super::reset_discovery_metrics(); |
| 2315 | let _ = super::discover_from_directories_with_plugins(dirs, None); |
| 2316 | let rewalked = discovery_delta_since(super::SkillDiscoveryMetrics::default()); |
| 2317 | assert_eq!(rewalked.root_discovery_calls, 1); |
| 2318 | } |
| 2319 | |
| 2320 | #[test] |
| 2321 | fn workspace_and_dir_entry_point_shares_the_same_cache() { |
| 2322 | let _env_lock = codewhale_runtime::test_support::lock_test_env(); |
| 2323 | super::clear_skill_discovery_cache(); |
| 2324 | let tmpdir = TempDir::new().unwrap(); |
| 2325 | let home = tmpdir.path().join("home"); |
| 2326 | let workspace = tmpdir.path().join("workspace"); |
| 2327 | let skills_dir = tmpdir.path().join("configured-skills"); |
| 2328 | std::fs::create_dir_all(&home).unwrap(); |
| 2329 | std::fs::create_dir_all(&workspace).unwrap(); |
| 2330 | write_skill( |
| 2331 | &skills_dir, |
| 2332 | "configured", |
| 2333 | "Configured skill", |
| 2334 | "Instructions", |
| 2335 | ); |
| 2336 | let _home = codewhale_runtime::test_support::EnvVarGuard::set("HOME", &home); |
| 2337 | let _userprofile = codewhale_runtime::test_support::EnvVarGuard::set("USERPROFILE", &home); |
| 2338 | let _codewhale_home = codewhale_runtime::test_support::EnvVarGuard::set( |
| 2339 | "CODEWHALE_HOME", |
| 2340 | home.join(".codewhale"), |
| 2341 | ); |
| 2342 | |
| 2343 | let (first, walked, second, rewalked) = measure_on_undisturbed_cache(|| { |
| 2344 | super::reset_discovery_metrics(); |
| 2345 | let first = super::discover_for_workspace_and_dir_with_mode_and_plugins( |
| 2346 | &workspace, |
| 2347 | &skills_dir, |
| 2348 | super::SkillDiscoveryMode::Compatible, |
| 2349 | None, |
| 2350 | ); |
| 2351 | let walked = discovery_delta_since(super::SkillDiscoveryMetrics::default()); |
| 2352 | let second = super::discover_for_workspace_and_dir_with_mode_and_plugins( |
| 2353 | &workspace, |
| 2354 | &skills_dir, |
| 2355 | super::SkillDiscoveryMode::Compatible, |
| 2356 | None, |
| 2357 | ); |
| 2358 | let rewalked = discovery_delta_since(walked); |
| 2359 | (first, walked, second, rewalked) |
| 2360 | }); |
| 2361 | |
| 2362 | assert!(walked.root_discovery_calls >= 1); |
| 2363 | assert_eq!(rewalked, super::SkillDiscoveryMetrics::default()); |
| 2364 | assert_eq!(first.len(), second.len()); |
| 2365 | assert!(second.get("configured").is_some()); |
| 2366 | } |
| 2367 | |
| 2368 | #[test] |
| 2369 | fn configured_skill_prompt_uses_a_stable_root_in_entries_and_warnings() { |
| 2370 | let _env_lock = codewhale_runtime::test_support::lock_test_env(); |
| 2371 | super::clear_skill_discovery_cache(); |
| 2372 | let tmpdir = TempDir::new().unwrap(); |
| 2373 | let home = tmpdir.path().join("home"); |
| 2374 | let workspace = home.join("workspace"); |
| 2375 | let skills_dir = home |
| 2376 | .join("runtime") |
| 2377 | .join("sessions") |
| 2378 | .join("session-123") |
| 2379 | .join("skills"); |
| 2380 | std::fs::create_dir_all(&workspace).unwrap(); |
| 2381 | write_skill( |
| 2382 | &workspace.join(".claude").join("skills"), |
| 2383 | "workspace-skill", |
| 2384 | "Workspace skill", |
| 2385 | "Instructions", |
| 2386 | ); |
| 2387 | let configured_skill = skills_dir.join("visual-design"); |
| 2388 | std::fs::create_dir_all(&configured_skill).unwrap(); |
| 2389 | std::fs::write( |
| 2390 | configured_skill.join("SKILL.md"), |
| 2391 | "---\nname: Visual Design\ndescription: Design assets\n---\nInstructions", |
| 2392 | ) |
| 2393 | .unwrap(); |
| 2394 | let _home = codewhale_runtime::test_support::EnvVarGuard::set("HOME", &home); |
| 2395 | let _userprofile = codewhale_runtime::test_support::EnvVarGuard::set("USERPROFILE", &home); |
| 2396 | let _codewhale_home = codewhale_runtime::test_support::EnvVarGuard::set( |
| 2397 | "CODEWHALE_HOME", |
| 2398 | home.join(".codewhale"), |
| 2399 | ); |
| 2400 | codewhale_runtime::test_support::trust_workspace(&workspace); |
| 2401 | |
| 2402 | let rendered = |
| 2403 | super::render_available_skills_context_for_workspace_and_dir_with_mode_and_plugins( |
| 2404 | &workspace, |
| 2405 | &skills_dir, |
| 2406 | super::SkillDiscoveryMode::Compatible, |
| 2407 | "en", |
| 2408 | None, |
| 2409 | super::SkillListingConfig::default(), |
| 2410 | super::MAX_AVAILABLE_SKILLS_CHARS, |
| 2411 | ) |
| 2412 | .expect("configured skill context"); |
| 2413 | |
| 2414 | assert!(rendered.contains("- visual-design: Design assets\n")); |
| 2415 | assert!(rendered.contains( |
| 2416 | "- workspace-skill: Workspace skill (file: .claude/skills/workspace-skill/SKILL.md)" |
| 2417 | )); |
| 2418 | assert!( |
| 2419 | rendered |
| 2420 | .contains("in <configured-skills>/visual-design/SKILL.md is not a safe command name") |
| 2421 | ); |
| 2422 | assert!(!rendered.contains("session-123"), "{rendered}"); |
| 2423 | assert!(!rendered.contains(home.to_str().unwrap()), "{rendered}"); |
| 2424 | } |
| 2425 | |
| 2426 | #[test] |
| 2427 | fn default_workspace_skill_prompt_preserves_its_discoverable_path() { |
| 2428 | let _env_lock = codewhale_runtime::test_support::lock_test_env(); |
| 2429 | super::clear_skill_discovery_cache(); |
| 2430 | let tmpdir = TempDir::new().unwrap(); |
| 2431 | let home = tmpdir.path().join("home"); |
| 2432 | let workspace = home.join("workspace"); |
| 2433 | let skills_dir = workspace.join(".agents").join("skills"); |
| 2434 | std::fs::create_dir_all(&home).unwrap(); |
| 2435 | write_skill( |
| 2436 | &skills_dir, |
| 2437 | "workspace-skill", |
| 2438 | "Workspace skill", |
| 2439 | "Instructions", |
| 2440 | ); |
| 2441 | let _home = codewhale_runtime::test_support::EnvVarGuard::set("HOME", &home); |
| 2442 | let _userprofile = codewhale_runtime::test_support::EnvVarGuard::set("USERPROFILE", &home); |
| 2443 | let _codewhale_home = codewhale_runtime::test_support::EnvVarGuard::set( |
| 2444 | "CODEWHALE_HOME", |
| 2445 | home.join(".codewhale"), |
| 2446 | ); |
| 2447 | codewhale_runtime::test_support::trust_workspace(&workspace); |
| 2448 | |
| 2449 | let rendered = |
| 2450 | super::render_available_skills_context_for_workspace_and_dir_with_mode_and_plugins( |
| 2451 | &workspace, |
| 2452 | &skills_dir, |
| 2453 | super::SkillDiscoveryMode::Compatible, |
| 2454 | "en", |
| 2455 | None, |
| 2456 | super::SkillListingConfig::default(), |
| 2457 | super::MAX_AVAILABLE_SKILLS_CHARS, |
| 2458 | ) |
| 2459 | .expect("workspace skill context"); |
| 2460 | |
| 2461 | assert!(rendered.contains( |
| 2462 | "- workspace-skill: Workspace skill (file: .agents/skills/workspace-skill/SKILL.md)" |
| 2463 | )); |
| 2464 | } |
| 2465 | |
| 2466 | #[test] |
| 2467 | fn global_skill_roots_come_from_the_os_home_only() { |
| 2468 | // §2.5: global skill roots resolve under the OS user's home (or an |
| 2469 | // explicit `$CODEWHALE_HOME`), never an account/GitHub handle. A wrong |
| 2470 | // home once produced `Failed to read /Users/<handle>/.codewhale/skills/ |
| 2471 | // delegate/SKILL.md`; pin the source so every global root is provably |
| 2472 | // under the faked OS home. |
| 2473 | let _env_lock = codewhale_runtime::test_support::lock_test_env(); |
| 2474 | let tmpdir = TempDir::new().unwrap(); |
| 2475 | let home = tmpdir.path().join("os-home"); |
| 2476 | let workspace = tmpdir.path().join("workspace"); |
| 2477 | std::fs::create_dir_all(home.join(".codewhale").join("skills")).unwrap(); |
| 2478 | std::fs::create_dir_all(&workspace).unwrap(); |
| 2479 | let _home = codewhale_runtime::test_support::EnvVarGuard::set("HOME", &home); |
| 2480 | let _userprofile = codewhale_runtime::test_support::EnvVarGuard::set("USERPROFILE", &home); |
| 2481 | let _codewhale_home = codewhale_runtime::test_support::EnvVarGuard::remove("CODEWHALE_HOME"); |
| 2482 | |
| 2483 | let dirs = |
| 2484 | super::skills_directories_for_mode(&workspace, super::SkillDiscoveryMode::Compatible); |
| 2485 | |
| 2486 | assert!( |
| 2487 | dirs.iter().any(|dir| dir.starts_with(&home)), |
| 2488 | "expected at least one global root under the OS home: {dirs:?}" |
| 2489 | ); |
| 2490 | assert!( |
| 2491 | dirs.iter() |
| 2492 | .all(|dir| dir.starts_with(&home) || dir.starts_with(&workspace)), |
| 2493 | "every runtime root is under the OS home or the workspace: {dirs:?}" |
| 2494 | ); |
| 2495 | } |
| 2496 | |
| 2497 | /// Passing a workspace skills dir as the session's `skills_dir` (as |
| 2498 | /// `resolve_skills_dir` and the runtime API did) must not re-admit what the |
| 2499 | /// root catalog's trust gate filtered out, and the warning must name the dir. |
| 2500 | fn assert_skills_dir_held_to_workspace_trust( |
| 2501 | workspace: &std::path::Path, |
| 2502 | skills_dir: &std::path::Path, |
| 2503 | mode: super::SkillDiscoveryMode, |
| 2504 | ) { |
| 2505 | write_skill( |
| 2506 | skills_dir, |
| 2507 | "repo-skill", |
| 2508 | "from the repository", |
| 2509 | "do repo things", |
| 2510 | ); |
| 2511 | |
| 2512 | let registry = super::discover_for_workspace_and_dir_with_mode_and_plugins( |
| 2513 | workspace, skills_dir, mode, None, |
| 2514 | ); |
| 2515 | assert!( |
| 2516 | registry.get("repo-skill").is_none(), |
| 2517 | "untrusted workspace skill loaded via skills_dir {}", |
| 2518 | skills_dir.display() |
| 2519 | ); |
| 2520 | assert!( |
| 2521 | !super::skill_directories_for_workspace_and_dir(workspace, skills_dir, mode) |
| 2522 | .iter() |
| 2523 | .any(|dir| super::roots::paths_refer_to_same_dir(dir, skills_dir)), |
| 2524 | "untrusted workspace skills_dir must not be searched" |
| 2525 | ); |
| 2526 | let dir_name = skills_dir |
| 2527 | .file_name() |
| 2528 | .unwrap() |
| 2529 | .to_string_lossy() |
| 2530 | .into_owned(); |
| 2531 | assert!( |
| 2532 | registry |
| 2533 | .warnings() |
| 2534 | .iter() |
| 2535 | .any(|warning| warning.contains("not trusted") && warning.contains(&dir_name)), |
| 2536 | "{:?}", |
| 2537 | registry.warnings() |
| 2538 | ); |
| 2539 | |
| 2540 | codewhale_runtime::test_support::trust_workspace(workspace); |
| 2541 | let registry = super::discover_for_workspace_and_dir_with_mode_and_plugins( |
| 2542 | workspace, skills_dir, mode, None, |
| 2543 | ); |
| 2544 | assert!(registry.get("repo-skill").is_some()); |
| 2545 | assert!( |
| 2546 | !registry |
| 2547 | .warnings() |
| 2548 | .iter() |
| 2549 | .any(|warning| warning.contains("not trusted")), |
| 2550 | "{:?}", |
| 2551 | registry.warnings() |
| 2552 | ); |
| 2553 | } |
| 2554 | |
| 2555 | #[test] |
| 2556 | fn untrusted_workspace_agents_skills_via_skills_dir_not_loaded() { |
| 2557 | let tmp = TempDir::new().unwrap(); |
| 2558 | let workspace = tmp.path().join("ws"); |
| 2559 | assert_skills_dir_held_to_workspace_trust( |
| 2560 | &workspace, |
| 2561 | &workspace.join(".agents").join("skills"), |
| 2562 | super::SkillDiscoveryMode::Compatible, |
| 2563 | ); |
| 2564 | } |
| 2565 | |
| 2566 | #[test] |
| 2567 | fn untrusted_workspace_flat_skills_via_skills_dir_not_loaded() { |
| 2568 | let tmp = TempDir::new().unwrap(); |
| 2569 | let workspace = tmp.path().join("ws"); |
| 2570 | assert_skills_dir_held_to_workspace_trust( |
| 2571 | &workspace, |
| 2572 | &workspace.join("skills"), |
| 2573 | super::SkillDiscoveryMode::Compatible, |
| 2574 | ); |
| 2575 | } |
| 2576 | |
| 2577 | #[test] |
| 2578 | fn untrusted_workspace_codewhale_only_skills_dir_not_loaded() { |
| 2579 | let tmp = TempDir::new().unwrap(); |
| 2580 | let workspace = tmp.path().join("ws"); |
| 2581 | assert_skills_dir_held_to_workspace_trust( |
| 2582 | &workspace, |
| 2583 | &workspace.join(".codewhale").join("skills"), |
| 2584 | super::SkillDiscoveryMode::CodeWhaleOnly, |
| 2585 | ); |
| 2586 | } |
| 2587 | |
| 2588 | /// An explicitly configured dir that lives inside the repository is still |
| 2589 | /// repository content: it waits for trust like the built-in project roots. |
| 2590 | #[test] |
| 2591 | fn untrusted_workspace_custom_configured_dir_inside_workspace_not_loaded() { |
| 2592 | let tmp = TempDir::new().unwrap(); |
| 2593 | let workspace = tmp.path().join("ws"); |
| 2594 | assert_skills_dir_held_to_workspace_trust( |
| 2595 | &workspace, |
| 2596 | &workspace.join("my-skills"), |
| 2597 | super::SkillDiscoveryMode::Compatible, |
| 2598 | ); |
| 2599 | } |
| 2600 | |
| 2601 | /// Repository-supplied skills are instructions nobody reviewed: they stay out |
| 2602 | /// of runtime discovery until the workspace is trusted, and discovery says so |
| 2603 | /// rather than dropping them silently. |
| 2604 | #[test] |
| 2605 | fn project_skills_require_workspace_trust() { |
| 2606 | let tmp = TempDir::new().unwrap(); |
| 2607 | let workspace = tmp.path(); |
| 2608 | write_skill( |
| 2609 | &workspace.join(".claude").join("skills"), |
| 2610 | "repo-skill", |
| 2611 | "from the repository", |
| 2612 | "do repo things", |
| 2613 | ); |
| 2614 | write_skill( |
| 2615 | &workspace.join(".codewhale").join("skills"), |
| 2616 | "owned-project-skill", |
| 2617 | "project owned", |
| 2618 | "owned", |
| 2619 | ); |
| 2620 | |
| 2621 | let registry = super::discover_in_workspace(workspace); |
| 2622 | assert!(registry.get("repo-skill").is_none()); |
| 2623 | assert!(registry.get("owned-project-skill").is_none()); |
| 2624 | assert!( |
| 2625 | registry |
| 2626 | .warnings() |
| 2627 | .iter() |
| 2628 | .any(|warning| warning.contains("not trusted") && warning.contains("/trust")), |
| 2629 | "{:?}", |
| 2630 | registry.warnings() |
| 2631 | ); |
| 2632 | |
| 2633 | codewhale_runtime::config::save_workspace_trust(workspace).expect("trust workspace"); |
| 2634 | let registry = super::discover_in_workspace(workspace); |
| 2635 | assert!(registry.get("repo-skill").is_some()); |
| 2636 | assert!(registry.get("owned-project-skill").is_some()); |
| 2637 | assert!( |
| 2638 | !registry |
| 2639 | .warnings() |
| 2640 | .iter() |
| 2641 | .any(|warning| warning.contains("not trusted")), |
| 2642 | "{:?}", |
| 2643 | registry.warnings() |
| 2644 | ); |
| 2645 | } |
| 2646 | |
| 2647 | #[test] |
| 2648 | fn hidden_and_backup_payload_changes_stale_the_trust_receipt() { |
| 2649 | use super::audit::{self, SkillAuditMode, TrustState}; |
| 2650 | use codewhale_skill_install::install::{INSTALLED_FROM_MARKER, TRUSTED_MARKER, write_trust_v2}; |
| 2651 | use codewhale_skill_install::package_digest::compute_package_digest; |
| 2652 | use std::fs; |
| 2653 | let tmp = tempfile::tempdir().unwrap(); |
| 2654 | let package = tmp.path().join(".codewhale/skills/demo"); |
| 2655 | fs::create_dir_all(&package).unwrap(); |
| 2656 | fs::write( |
| 2657 | package.join("SKILL.md"), |
| 2658 | "---\nname: demo\ndescription: test\n---\nbody", |
| 2659 | ) |
| 2660 | .unwrap(); |
| 2661 | let payloads = [ |
| 2662 | ".hidden", |
| 2663 | ".hidden-dir/run.sh", |
| 2664 | "script.bak", |
| 2665 | "script.tmp", |
| 2666 | "nested/.trusted", |
| 2667 | ]; |
| 2668 | for relative in payloads { |
| 2669 | let path = package.join(relative); |
| 2670 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 2671 | fs::write(path, "safe").unwrap(); |
| 2672 | } |
| 2673 | let digest = compute_package_digest(&package).unwrap(); |
| 2674 | write_trust_v2(&package, &digest).unwrap(); |
| 2675 | let initial = audit::scan(tmp.path(), None, SkillAuditMode::OwnedOnly, None); |
| 2676 | assert_eq!(initial.skills.len(), 1); |
| 2677 | assert_eq!( |
| 2678 | initial.skills[0].trust, |
| 2679 | TrustState::TrustedForDigest(digest.clone()) |
| 2680 | ); |
| 2681 | for relative in payloads { |
| 2682 | fs::write(package.join(relative), "evil").unwrap(); |
| 2683 | assert_ne!( |
| 2684 | compute_package_digest(&package).unwrap(), |
| 2685 | digest, |
| 2686 | "{relative}" |
| 2687 | ); |
| 2688 | let changed = audit::scan(tmp.path(), None, SkillAuditMode::OwnedOnly, None); |
| 2689 | assert_eq!( |
| 2690 | changed.skills[0].trust, |
| 2691 | TrustState::TrustStale, |
| 2692 | "{relative}" |
| 2693 | ); |
| 2694 | fs::write(package.join(relative), "safe").unwrap(); |
| 2695 | } |
| 2696 | // These root files are local bookkeeping, not executable payload. |
| 2697 | for marker in [ |
| 2698 | INSTALLED_FROM_MARKER, |
| 2699 | TRUSTED_MARKER, |
| 2700 | ".system-installed-version", |
| 2701 | ] { |
| 2702 | fs::write(package.join(marker), "local metadata").unwrap(); |
| 2703 | assert_eq!(compute_package_digest(&package).unwrap(), digest); |
| 2704 | } |
| 2705 | } |
| 2706 | |
| 2707 | #[test] |
| 2708 | fn owned_global_root_shadows_claude_compat() { |
| 2709 | let tmp = TempDir::new().unwrap(); |
| 2710 | let workspace = tmp.path().join("ws"); |
| 2711 | let home = tmp.path().join("home"); |
| 2712 | std::fs::create_dir_all(&workspace).unwrap(); |
| 2713 | write_skill( |
| 2714 | &home.join(".codewhale/skills"), |
| 2715 | "shared", |
| 2716 | "owned", |
| 2717 | "owned body", |
| 2718 | ); |
| 2719 | write_skill( |
| 2720 | &home.join(".agents/skills"), |
| 2721 | "shared", |
| 2722 | "agents", |
| 2723 | "agents body", |
| 2724 | ); |
| 2725 | write_skill( |
| 2726 | &home.join(".claude/skills"), |
| 2727 | "shared", |
| 2728 | "claude", |
| 2729 | "claude body", |
| 2730 | ); |
| 2731 | let registry = super::discover_for_workspace_and_dir_with_home( |
| 2732 | &workspace, |
| 2733 | &home.join(".codewhale/skills"), |
| 2734 | Some(&home), |
| 2735 | ); |
| 2736 | assert_eq!(registry.get("shared").unwrap().body, "owned body"); |
| 2737 | assert_eq!( |
| 2738 | registry |
| 2739 | .warnings() |
| 2740 | .iter() |
| 2741 | .filter(|warning| warning.contains("shadowed by")) |
| 2742 | .count(), |
| 2743 | 2 |
| 2744 | ); |
| 2745 | } |
| 2746 | |
| 2747 | #[test] |
| 2748 | fn installed_skill_wins_over_agents_copy() { |
| 2749 | let tmp = TempDir::new().unwrap(); |
| 2750 | let workspace = tmp.path().join("ws"); |
| 2751 | codewhale_runtime::test_support::trust_workspace(&workspace); |
| 2752 | write_skill( |
| 2753 | &workspace.join(".codewhale/skills"), |
| 2754 | "shared", |
| 2755 | "installed", |
| 2756 | "installed body", |
| 2757 | ); |
| 2758 | write_skill( |
| 2759 | &workspace.join(".agents/skills"), |
| 2760 | "shared", |
| 2761 | "compat", |
| 2762 | "compat body", |
| 2763 | ); |
| 2764 | let registry = super::discover_for_workspace_and_dir_with_home( |
| 2765 | &workspace, |
| 2766 | &workspace.join(".codewhale/skills"), |
| 2767 | None, |
| 2768 | ); |
| 2769 | assert_eq!(registry.get("shared").unwrap().body, "installed body"); |
| 2770 | assert!( |
| 2771 | registry |
| 2772 | .warnings() |
| 2773 | .iter() |
| 2774 | .any(|warning| warning.contains(".agents") |
| 2775 | && warning.contains(".codewhale") |
| 2776 | && warning.contains("shadowed by")) |
| 2777 | ); |
| 2778 | } |
| 2779 | |
| 2780 | #[test] |
| 2781 | fn flat_skills_root_opt_in() { |
| 2782 | let tmp = TempDir::new().unwrap(); |
| 2783 | let workspace = tmp.path().join("ws"); |
| 2784 | codewhale_runtime::test_support::trust_workspace(&workspace); |
| 2785 | write_skill( |
| 2786 | &workspace.join("skills"), |
| 2787 | "flat", |
| 2788 | "product content", |
| 2789 | "flat body", |
| 2790 | ); |
| 2791 | let catalog = super::roots::SkillRootCatalog::build(&workspace, None, None); |
| 2792 | assert!( |
| 2793 | catalog |
| 2794 | .audit_compatible_directories() |
| 2795 | .iter() |
| 2796 | .any(|root| root.path == workspace.join("skills") && !root.active_for_runtime) |
| 2797 | ); |
| 2798 | let default = super::discover_for_workspace_and_dir_with_home_and_mode( |
| 2799 | &workspace, |
| 2800 | &workspace.join(".codewhale/skills"), |
| 2801 | None, |
| 2802 | super::SkillDiscoveryMode::Compatible, |
| 2803 | ); |
| 2804 | assert!(default.get("flat").is_none()); |
| 2805 | let config: codewhale_runtime::config::Config = |
| 2806 | toml::from_str("[skills]\nflat_workspace_root = true\n").unwrap(); |
| 2807 | let mode = super::SkillDiscoveryMode::from_config(&config.skills_config()); |
| 2808 | assert_eq!(mode, super::SkillDiscoveryMode::CompatibleWithFlatWorkspace); |
| 2809 | let enabled = super::discover_for_workspace_and_dir_with_home_and_mode( |
| 2810 | &workspace, |
| 2811 | &workspace.join(".codewhale/skills"), |
| 2812 | None, |
| 2813 | mode, |
| 2814 | ); |
| 2815 | assert_eq!(enabled.get("flat").unwrap().body, "flat body"); |
| 2816 | let owned_only: codewhale_runtime::config::Config = |
| 2817 | toml::from_str("[skills]\nflat_workspace_root = true\nscan_codewhale_only = true\n") |
| 2818 | .unwrap(); |
| 2819 | assert_eq!( |
| 2820 | super::SkillDiscoveryMode::from_config(&owned_only.skills_config()), |
| 2821 | super::SkillDiscoveryMode::CodeWhaleOnly |
| 2822 | ); |
| 2823 | let explicit = super::discover_for_workspace_and_dir_with_home_and_mode( |
| 2824 | &workspace, |
| 2825 | &workspace.join("skills"), |
| 2826 | None, |
| 2827 | super::SkillDiscoveryMode::Compatible, |
| 2828 | ); |
| 2829 | assert!( |
| 2830 | explicit.get("flat").is_some(), |
| 2831 | "explicit skills_dir remains supported" |
| 2832 | ); |
| 2833 | } |
| 2834 | |
| 2835 | #[test] |
| 2836 | fn disable_model_invocation_maps_to_explicit_only() { |
| 2837 | for value in ["true", "yes", "on", "1"] { |
| 2838 | let skill = super::SkillRegistry::parse_skill(std::path::Path::new("demo/SKILL.md"), &format!("---\nname: demo\ndescription: routing\ndisable-model-invocation: {value}\n---\nbody")).unwrap(); |
| 2839 | assert_eq!(skill.invocation, super::SkillInvocation::ExplicitOnly); |
| 2840 | assert!(!skill.invocation.model_invocable()); |
| 2841 | assert!(skill.invocation.user_invocable()); |
| 2842 | } |
| 2843 | } |
| 2844 | |
| 2845 | #[test] |
| 2846 | fn user_invocable_false_hidden_from_slash_menu() { |
| 2847 | let content = "---\nname: demo\ndescription: routing\nuser-invocable: false\nargument-hint: '[query] [path]'\n---\nbody"; |
| 2848 | let skill = |
| 2849 | super::SkillRegistry::parse_skill(std::path::Path::new("demo/SKILL.md"), content).unwrap(); |
| 2850 | assert_eq!(skill.invocation, super::SkillInvocation::ModelOnly); |
| 2851 | assert!(skill.invocation.model_invocable()); |
| 2852 | assert!(!skill.invocation.user_invocable()); |
| 2853 | assert_eq!(skill.argument_hint.as_deref(), Some("[query] [path]")); |
| 2854 | assert!(skill.user_menu_description().contains("[query] [path]")); |
| 2855 | let disabled = super::SkillRegistry::parse_skill( |
| 2856 | std::path::Path::new("demo/SKILL.md"), |
| 2857 | &content.replace( |
| 2858 | "user-invocable: false", |
| 2859 | "user-invocable: false\ndisable-model-invocation: true", |
| 2860 | ), |
| 2861 | ) |
| 2862 | .unwrap(); |
| 2863 | assert_eq!(disabled.invocation, super::SkillInvocation::Disabled); |
| 2864 | assert!(!disabled.invocation.model_invocable()); |
| 2865 | assert!(!disabled.invocation.user_invocable()); |
| 2866 | let invalid = super::SkillRegistry::parse_skill( |
| 2867 | std::path::Path::new("demo/SKILL.md"), |
| 2868 | &content.replace( |
| 2869 | "user-invocable: false", |
| 2870 | "user-invocable: mystery\ndisable-model-invocation: mystery", |
| 2871 | ), |
| 2872 | ) |
| 2873 | .unwrap(); |
| 2874 | assert_eq!(invalid.invocation, super::SkillInvocation::Disabled); |
| 2875 | } |
| 2876 | |
| 2877 | #[test] |
| 2878 | fn when_to_use_merged_into_trigger() { |
| 2879 | let content = "---\nname: demo\ndescription: Short summary.\nwhen_to_use: fixing a failing build\n---\nbody"; |
| 2880 | let skill = |
| 2881 | super::SkillRegistry::parse_skill(std::path::Path::new("demo/SKILL.md"), content).unwrap(); |
| 2882 | assert_eq!( |
| 2883 | skill.description, |
| 2884 | "Short summary. Use when: fixing a failing build" |
| 2885 | ); |
| 2886 | let (summary, trigger) = super::split_trigger(&skill.description); |
| 2887 | assert_eq!(summary.trim(), "Short summary"); |
| 2888 | assert!(trigger.unwrap().contains("fixing a failing build")); |
| 2889 | } |
| 2890 | |
| 2891 | #[test] |
| 2892 | fn frontmatter_warnings_reach_registry_once() { |
| 2893 | let tmp = TempDir::new().unwrap(); |
| 2894 | create_skill_dir( |
| 2895 | &tmp, |
| 2896 | "directory", |
| 2897 | "---\nname: different\nallowed-tools: [Read]\nmodel: example\ncontext: fork\nmystery: ignored\n---\nbody", |
| 2898 | ); |
| 2899 | let registry = super::SkillRegistry::discover(&tmp.path().join("skills")); |
| 2900 | assert!( |
| 2901 | registry.get("different").is_some(), |
| 2902 | "runtime remains lenient" |
| 2903 | ); |
| 2904 | assert_eq!(registry.warnings().len(), 6, "{:?}", registry.warnings()); |
| 2905 | for key in [ |
| 2906 | "allowed-tools", |
| 2907 | "model", |
| 2908 | "context", |
| 2909 | "mystery", |
| 2910 | "missing description", |
| 2911 | "differs from directory", |
| 2912 | ] { |
| 2913 | assert_eq!( |
| 2914 | registry |
| 2915 | .warnings() |
| 2916 | .iter() |
| 2917 | .filter(|warning| warning.contains(key)) |
| 2918 | .count(), |
| 2919 | 1 |
| 2920 | ); |
| 2921 | } |
| 2922 | } |
| 2923 | |
| 2924 | /// A repository must not make skill discovery read outside itself: a linked |
| 2925 | /// skill directory or `SKILL.md` that leaves the workspace and a linked skills |
| 2926 | /// root under the workspace are each refused with a warning, a linked skill |
| 2927 | /// directory whose target stays inside the workspace is followed, and the same |
| 2928 | /// layout under an operator-owned root (no workspace) follows links on purpose. |
| 2929 | #[cfg(unix)] |
| 2930 | #[test] |
| 2931 | fn workspace_skill_discovery_does_not_follow_links_out_of_the_workspace() { |
| 2932 | use std::os::unix::fs::symlink; |
| 2933 | super::clear_skill_discovery_cache(); |
| 2934 | let workspace = TempDir::new().unwrap(); |
| 2935 | let outside = TempDir::new().unwrap(); |
| 2936 | write_skill( |
| 2937 | outside.path(), |
| 2938 | "smuggled-dir", |
| 2939 | "outside dir", |
| 2940 | "Outside body", |
| 2941 | ); |
| 2942 | let linked_file_skill = outside.path().join("linked-file-source"); |
| 2943 | write_skill( |
| 2944 | &linked_file_skill, |
| 2945 | "smuggled-file", |
| 2946 | "outside file", |
| 2947 | "Outside body", |
| 2948 | ); |
| 2949 | |
| 2950 | let root = workspace.path().join(".agents").join("skills"); |
| 2951 | write_skill(&root, "inside", "inside the workspace", "Inside body"); |
| 2952 | symlink(outside.path().join("smuggled-dir"), root.join("linked-dir")).unwrap(); |
| 2953 | write_skill( |
| 2954 | &workspace.path().join("docs").join("skills"), |
| 2955 | "linked-inside", |
| 2956 | "inside via link", |
| 2957 | "Inside body", |
| 2958 | ); |
| 2959 | symlink( |
| 2960 | workspace |
| 2961 | .path() |
| 2962 | .join("docs") |
| 2963 | .join("skills") |
| 2964 | .join("linked-inside"), |
| 2965 | root.join("linked-inside"), |
| 2966 | ) |
| 2967 | .unwrap(); |
| 2968 | std::fs::create_dir_all(root.join("linked-file")).unwrap(); |
| 2969 | symlink( |
| 2970 | linked_file_skill.join("smuggled-file").join("SKILL.md"), |
| 2971 | root.join("linked-file").join("SKILL.md"), |
| 2972 | ) |
| 2973 | .unwrap(); |
| 2974 | |
| 2975 | let registry = super::discover_from_directories_in_workspace( |
| 2976 | vec![root.clone()], |
| 2977 | Some(workspace.path()), |
| 2978 | None, |
| 2979 | ); |
| 2980 | let names = registry |
| 2981 | .list() |
| 2982 | .iter() |
| 2983 | .map(|skill| skill.name.as_str()) |
| 2984 | .collect::<Vec<_>>(); |
| 2985 | assert_eq!( |
| 2986 | names, |
| 2987 | vec!["inside", "linked-inside"], |
| 2988 | "{:?}", |
| 2989 | registry.warnings() |
| 2990 | ); |
| 2991 | let warnings = registry.warnings().join("\n"); |
| 2992 | assert!( |
| 2993 | warnings.contains("Refusing symlinked skill entry"), |
| 2994 | "{warnings}" |
| 2995 | ); |
| 2996 | assert!(warnings.contains("linked-dir"), "{warnings}"); |
| 2997 | assert!(!warnings.contains("linked-inside"), "{warnings}"); |
| 2998 | assert!(warnings.contains("linked-file"), "{warnings}"); |
| 2999 | |
| 3000 | // The same tree read as an operator-owned root still follows links. |
| 3001 | super::clear_skill_discovery_cache(); |
| 3002 | let operator = super::discover_from_directories_with_plugins(vec![root.clone()], None); |
| 3003 | assert!( |
| 3004 | operator |
| 3005 | .list() |
| 3006 | .iter() |
| 3007 | .any(|skill| skill.name == "smuggled-dir"), |
| 3008 | "operator-owned roots keep following links" |
| 3009 | ); |
| 3010 | |
| 3011 | // A linked skills root under the workspace is refused as a whole. |
| 3012 | super::clear_skill_discovery_cache(); |
| 3013 | let other = TempDir::new().unwrap(); |
| 3014 | std::fs::create_dir_all(other.path().join(".agents")).unwrap(); |
| 3015 | symlink(outside.path(), other.path().join(".agents").join("skills")).unwrap(); |
| 3016 | let registry = super::discover_from_directories_in_workspace( |
| 3017 | vec![other.path().join(".agents").join("skills")], |
| 3018 | Some(other.path()), |
| 3019 | None, |
| 3020 | ); |
| 3021 | assert!(registry.list().is_empty()); |
| 3022 | assert!( |
| 3023 | registry |
| 3024 | .warnings() |
| 3025 | .join("\n") |
| 3026 | .contains("Refusing symlinked path"), |
| 3027 | "{:?}", |
| 3028 | registry.warnings() |
| 3029 | ); |
| 3030 | } |
| 3031 | |
| 3032 | #[test] |
| 3033 | fn starter_pack_is_discoverable_and_user_overrides_win() { |
| 3034 | let _env_lock = codewhale_runtime::test_support::lock_test_env(); |
| 3035 | let tmpdir = TempDir::new().unwrap(); |
| 3036 | let home = tmpdir.path().join("home"); |
| 3037 | let workspace = tmpdir.path().join("workspace"); |
| 3038 | std::fs::create_dir_all(&home).unwrap(); |
| 3039 | std::fs::create_dir_all(&workspace).unwrap(); |
| 3040 | let _home = codewhale_runtime::test_support::EnvVarGuard::set("HOME", &home); |
| 3041 | let _userprofile = codewhale_runtime::test_support::EnvVarGuard::set("USERPROFILE", &home); |
| 3042 | let _codewhale_home = codewhale_runtime::test_support::EnvVarGuard::set( |
| 3043 | "CODEWHALE_HOME", |
| 3044 | home.join("isolated-product-state"), |
| 3045 | ); |
| 3046 | codewhale_runtime::test_support::trust_workspace(&workspace); |
| 3047 | super::clear_skill_discovery_cache(); |
| 3048 | |
| 3049 | let owned = codewhale_runtime::config::owned_skills_dir().unwrap(); |
| 3050 | let config = codewhale_runtime::config::SkillsConfig::default(); |
| 3051 | super::install_system_skills(&owned, &config.bundled).unwrap(); |
| 3052 | for creator_skills in [false, true] { |
| 3053 | let config = codewhale_runtime::config::SkillsConfig { |
| 3054 | creator_skills, |
| 3055 | ..Default::default() |
| 3056 | }; |
| 3057 | let registry = super::discover_for_workspace(&workspace, None, &config, None); |
| 3058 | for skill in super::system::bundled_skill_names() { |
| 3059 | let found = registry.get(skill).unwrap(); |
| 3060 | assert_eq!( |
| 3061 | found.path.canonicalize().unwrap(), |
| 3062 | owned |
| 3063 | .join(".system") |
| 3064 | .join(skill) |
| 3065 | .join("SKILL.md") |
| 3066 | .canonicalize() |
| 3067 | .unwrap() |
| 3068 | ); |
| 3069 | } |
| 3070 | assert!(registry.get("cordis-plugin-development").is_none()); |
| 3071 | } |
| 3072 | write_skill( |
| 3073 | &owned, |
| 3074 | "plugin-creator", |
| 3075 | "Personal plugin creator", |
| 3076 | "My authoring process", |
| 3077 | ); |
| 3078 | let registry = super::discover_for_workspace(&workspace, None, &config, None); |
| 3079 | assert_eq!( |
| 3080 | registry.get("plugin-creator").unwrap().description, |
| 3081 | "Personal plugin creator" |
| 3082 | ); |
| 3083 | } |
| 3084 | |
| 3085 | #[test] |
| 3086 | fn split_trigger_recognizes_multilingual_markers() { |
| 3087 | let (ru_summary, ru_trigger) = |
| 3088 | super::split_trigger("Помощник ревью кода. Триггеры: код-ревью, проверка PR."); |
| 3089 | assert_eq!(ru_summary, "Помощник ревью кода"); |
| 3090 | assert_eq!(ru_trigger.as_deref(), Some("код-ревью, проверка PR")); |
| 3091 | |
| 3092 | let (zh_summary, zh_trigger) = |
| 3093 | super::split_trigger("发布检查工具。触发条件:准备打标签或发版。"); |
| 3094 | assert_eq!(zh_summary, "发布检查工具"); |
| 3095 | assert_eq!(zh_trigger.as_deref(), Some("准备打标签或发版")); |
| 3096 | } |
| 3097 | |
| 3098 | #[test] |
| 3099 | fn tier3_names_only_preserves_skill_paths_when_budget_allows() { |
| 3100 | let tmpdir = TempDir::new().unwrap(); |
| 3101 | let mut registry = super::SkillRegistry::default(); |
| 3102 | let desc = "d".repeat(100); |
| 3103 | for i in 0..45 { |
| 3104 | registry.skills.push(super::Skill { |
| 3105 | legacy_activation_name: None, |
| 3106 | name: format!("skill-{i:02}"), |
| 3107 | description: desc.clone(), |
| 3108 | localized_descriptions: std::collections::HashMap::new(), |
| 3109 | invocation: super::SkillInvocation::ModelAndUser, |
| 3110 | dependencies: Default::default(), |
| 3111 | aliases: Vec::new(), |
| 3112 | argument_hint: None, |
| 3113 | body: "body".to_string(), |
| 3114 | path: tmpdir.path().join(format!("skills/skill-{i:02}/SKILL.md")), |
| 3115 | source: super::SkillSource::Native, |
| 3116 | }); |
| 3117 | } |
| 3118 | let rendered = super::render_skills_block_with_configured_root( |
| 3119 | ®istry, |
| 3120 | "en", |
| 3121 | tmpdir.path(), |
| 3122 | None, |
| 3123 | super::SkillListingConfig::default(), |
| 3124 | 3_000, |
| 3125 | ) |
| 3126 | .expect("skill context"); |
| 3127 | for i in 0..45 { |
| 3128 | let expected = format!("- skill-{i:02} (file: skills/skill-{i:02}/SKILL.md)"); |
| 3129 | assert!( |
| 3130 | rendered.contains(&expected), |
| 3131 | "missing {expected}:\n{rendered}" |
| 3132 | ); |
| 3133 | } |
| 3134 | } |
| 3135 | |
| 3136 | #[test] |
| 3137 | fn skills_config_rejects_unknown_keys() { |
| 3138 | let err = toml::from_str::<codewhale_runtime::config::SkillsConfig>("prompt_index = true\n") |
| 3139 | .expect_err("unknown [skills] keys must be rejected"); |
| 3140 | assert!( |
| 3141 | err.to_string().contains("unknown field `prompt_index`"), |
| 3142 | "unexpected error: {err}" |
| 3143 | ); |
| 3144 | } |
| 3145 | |
| 3146 | #[test] |
| 3147 | fn render_always_loaded_skills_loads_warns_and_caps_budgets() { |
| 3148 | let tmp = TempDir::new().unwrap(); |
| 3149 | let skills_dir = tmp.path().join(".codewhale/skills"); |
| 3150 | write_skill(&skills_dir, "alpha", "Alpha summary", "Alpha body"); |
| 3151 | let huge_body = "x".repeat(70 * 1024); |
| 3152 | write_skill(&skills_dir, "huge", "Huge summary", &huge_body); |
| 3153 | let huge2_body = "y".repeat(70 * 1024); |
| 3154 | write_skill(&skills_dir, "huge2", "Huge2 summary", &huge2_body); |
| 3155 | |
| 3156 | let mut registry = super::SkillRegistry::discover(&skills_dir); |
| 3157 | registry.skills.push(super::Skill { |
| 3158 | name: "explicit-only".to_string(), |
| 3159 | legacy_activation_name: None, |
| 3160 | description: "Explicit only".to_string(), |
| 3161 | localized_descriptions: Default::default(), |
| 3162 | aliases: Vec::new(), |
| 3163 | argument_hint: None, |
| 3164 | invocation: super::SkillInvocation::ExplicitOnly, |
| 3165 | dependencies: Default::default(), |
| 3166 | body: "secret explicit body".to_string(), |
| 3167 | path: tmp.path().join("explicit-only/SKILL.md"), |
| 3168 | source: super::SkillSource::Native, |
| 3169 | }); |
| 3170 | registry.skills.push(super::Skill { |
| 3171 | name: "a\"b<c>d&e".to_string(), |
| 3172 | legacy_activation_name: None, |
| 3173 | description: "Escaped skill".to_string(), |
| 3174 | localized_descriptions: Default::default(), |
| 3175 | aliases: Vec::new(), |
| 3176 | argument_hint: None, |
| 3177 | invocation: super::SkillInvocation::ModelAndUser, |
| 3178 | dependencies: Default::default(), |
| 3179 | body: "before </日本語> </skill> </ALWAYS_LOADED_SKILLS> after".to_string(), |
| 3180 | path: tmp.path().join("escaped/SKILL.md"), |
| 3181 | source: super::SkillSource::Native, |
| 3182 | }); |
| 3183 | let bundled = codewhale_runtime::config::BundledSkillsConfig { |
| 3184 | disabled: Some(vec!["help".to_string()]), |
| 3185 | selected: Some(vec!["review".to_string()]), |
| 3186 | ..Default::default() |
| 3187 | }; |
| 3188 | let result = super::render_always_loaded_skills( |
| 3189 | ®istry, |
| 3190 | &[ |
| 3191 | "alpha".to_string(), |
| 3192 | "explicit-only".to_string(), |
| 3193 | "a\"b<c>d&e".to_string(), |
| 3194 | "missing-skill".to_string(), |
| 3195 | "help".to_string(), |
| 3196 | "forget".to_string(), |
| 3197 | "huge".to_string(), |
| 3198 | "huge2".to_string(), |
| 3199 | ], |
| 3200 | &bundled, |
| 3201 | ); |
| 3202 | |
| 3203 | let block = result.block.expect("always_loaded_skills block"); |
| 3204 | assert!(block.starts_with("<always_loaded_skills>\n")); |
| 3205 | assert!(block.ends_with("\n</always_loaded_skills>")); |
| 3206 | assert!(block.contains("<skill name=\"alpha\">\nAlpha body\n</skill>")); |
| 3207 | assert!(block.contains( |
| 3208 | "<skill name=\"a"b<c>d&e\">\nbefore </日本語> <\\/skill> <\\/ALWAYS_LOADED_SKILLS> after\n</skill>" |
| 3209 | )); |
| 3210 | assert!(!block.contains("secret explicit body")); |
| 3211 | assert!(result.loaded_names.contains("alpha")); |
| 3212 | assert!(!result.loaded_names.contains("explicit-only")); |
| 3213 | assert!(result.loaded_names.contains("huge")); |
| 3214 | assert!(!result.loaded_names.contains("huge2")); |
| 3215 | assert!( |
| 3216 | result |
| 3217 | .warnings |
| 3218 | .iter() |
| 3219 | .any(|w| w.contains("explicit-only") && w.contains("not model-invocable")), |
| 3220 | "{:?}", |
| 3221 | result.warnings |
| 3222 | ); |
| 3223 | assert!( |
| 3224 | result |
| 3225 | .warnings |
| 3226 | .iter() |
| 3227 | .any(|w| w.contains("missing-skill") && w.contains("not found")), |
| 3228 | "{:?}", |
| 3229 | result.warnings |
| 3230 | ); |
| 3231 | assert!( |
| 3232 | result |
| 3233 | .warnings |
| 3234 | .iter() |
| 3235 | .any(|w| { w.contains("help") && w.contains("disabled in [skills.bundled] disabled") }), |
| 3236 | "{:?}", |
| 3237 | result.warnings |
| 3238 | ); |
| 3239 | assert!( |
| 3240 | result |
| 3241 | .warnings |
| 3242 | .iter() |
| 3243 | .any(|w| w.contains("forget") && w.contains("not in [skills.bundled] selected")), |
| 3244 | "{:?}", |
| 3245 | result.warnings |
| 3246 | ); |
| 3247 | assert!( |
| 3248 | result |
| 3249 | .warnings |
| 3250 | .iter() |
| 3251 | .any(|w| w.contains("huge") && w.contains("truncated")), |
| 3252 | "{:?}", |
| 3253 | result.warnings |
| 3254 | ); |
| 3255 | assert!( |
| 3256 | result |
| 3257 | .warnings |
| 3258 | .iter() |
| 3259 | .any(|w| w.contains("huge2") && w.contains("total preloaded body limit")), |
| 3260 | "{:?}", |
| 3261 | result.warnings |
| 3262 | ); |
| 3263 | assert!( |
| 3264 | !result |
| 3265 | .warnings |
| 3266 | .iter() |
| 3267 | .any(|w| w.contains("huge2") && w.contains("truncated")), |
| 3268 | "{:?}", |
| 3269 | result.warnings |
| 3270 | ); |
| 3271 | } |
| 3272 | |
| 3273 | #[test] |
| 3274 | fn render_always_loaded_skills_loads_user_override_matching_disabled_or_unselected_bundled_name() { |
| 3275 | let tmp = TempDir::new().unwrap(); |
| 3276 | let skills_dir = tmp.path().join(".codewhale/skills"); |
| 3277 | write_skill( |
| 3278 | &skills_dir, |
| 3279 | "help", |
| 3280 | "Custom help summary", |
| 3281 | "Custom help body", |
| 3282 | ); |
| 3283 | write_skill( |
| 3284 | &skills_dir, |
| 3285 | "forget", |
| 3286 | "Custom forget summary", |
| 3287 | "Custom forget body", |
| 3288 | ); |
| 3289 | |
| 3290 | let registry = super::SkillRegistry::discover(&skills_dir); |
| 3291 | let bundled = codewhale_runtime::config::BundledSkillsConfig { |
| 3292 | disabled: Some(vec!["help".to_string()]), |
| 3293 | selected: Some(vec!["review".to_string()]), |
| 3294 | ..Default::default() |
| 3295 | }; |
| 3296 | let result = super::render_always_loaded_skills( |
| 3297 | ®istry, |
| 3298 | &["help".to_string(), "forget".to_string()], |
| 3299 | &bundled, |
| 3300 | ); |
| 3301 | |
| 3302 | let block = result.block.expect("user overrides must load"); |
| 3303 | assert!(block.contains("Custom help body"), "{block}"); |
| 3304 | assert!(block.contains("Custom forget body"), "{block}"); |
| 3305 | assert!(result.loaded_names.contains("help")); |
| 3306 | assert!(result.loaded_names.contains("forget")); |
| 3307 | assert!(result.warnings.is_empty(), "{:?}", result.warnings); |
| 3308 | } |
| 3309 | |
| 3310 | #[test] |
| 3311 | fn render_available_skills_index_filters_vendor_and_empty_plugins_and_marks_preloaded() { |
| 3312 | let tmp = TempDir::new().unwrap(); |
| 3313 | let cursor_dir = tmp.path().join(".cursor/skills"); |
| 3314 | write_skill(&cursor_dir, "pdf", "Vendor PDF", "vendor body"); |
| 3315 | write_skill(&cursor_dir, "custom-cursor", "Custom Cursor", "custom body"); |
| 3316 | let codewhale_dir = tmp.path().join(".codewhale/skills"); |
| 3317 | write_skill(&codewhale_dir, "pdf", "User PDF", "user pdf body"); |
| 3318 | |
| 3319 | let mut registry = |
| 3320 | super::discover_from_directories_with_plugins([codewhale_dir, cursor_dir], None); |
| 3321 | registry.skills.push(super::Skill { |
| 3322 | name: "empty-plugin:skill".to_string(), |
| 3323 | legacy_activation_name: None, |
| 3324 | description: String::new(), |
| 3325 | localized_descriptions: Default::default(), |
| 3326 | aliases: Vec::new(), |
| 3327 | argument_hint: None, |
| 3328 | invocation: super::SkillInvocation::ModelAndUser, |
| 3329 | dependencies: Default::default(), |
| 3330 | body: "plugin body".to_string(), |
| 3331 | path: tmp.path().join("plugin/SKILL.md"), |
| 3332 | source: super::SkillSource::Plugin { |
| 3333 | plugin_id: "plug-1".to_string(), |
| 3334 | plugin_name: "Plug One".to_string(), |
| 3335 | authority: Box::new(codewhale_config::PluginAuthority { |
| 3336 | plugin_id: codewhale_config::PluginId("plug-1".to_string()), |
| 3337 | plugin_name: "Plug One".to_string(), |
| 3338 | workspace: tmp.path().to_path_buf(), |
| 3339 | state_path: tmp.path().join("state.json"), |
| 3340 | managed_policy_path: None, |
| 3341 | managed_policy_source: None, |
| 3342 | source_manifest: tmp.path().join("plugin.json"), |
| 3343 | staged_manifest: tmp.path().join("staged.json"), |
| 3344 | content_hash: "sha256:abc".to_string(), |
| 3345 | capability_hash: "sha256:def".to_string(), |
| 3346 | state_generation: 1, |
| 3347 | }), |
| 3348 | native_registration: None, |
| 3349 | }, |
| 3350 | }); |
| 3351 | |
| 3352 | let mut preloaded = std::collections::HashSet::new(); |
| 3353 | preloaded.insert("custom-cursor".to_string()); |
| 3354 | let rendered = super::render_available_skills_index( |
| 3355 | ®istry, |
| 3356 | "en", |
| 3357 | tmp.path(), |
| 3358 | None, |
| 3359 | super::SkillListingConfig::default(), |
| 3360 | 4096, |
| 3361 | &preloaded, |
| 3362 | ) |
| 3363 | .expect("index rendered"); |
| 3364 | |
| 3365 | assert!(rendered.contains("User PDF"), "{rendered}"); |
| 3366 | assert!(!rendered.contains("Vendor PDF"), "{rendered}"); |
| 3367 | assert!(!rendered.contains("empty-plugin:skill"), "{rendered}"); |
| 3368 | assert!( |
| 3369 | rendered.contains("custom-cursor") && rendered.contains("(already preloaded)"), |
| 3370 | "{rendered}" |
| 3371 | ); |
| 3372 | } |
| 3373 |