| 1 | //! Skills commands: skills, skill |
| 2 | |
| 3 | use std::fmt::Write; |
| 4 | |
| 5 | use codewhale_command_contract::facets::{ |
| 6 | CommandSkillGroupContext, CommandSkillsContext, RemoteRegistryOutcome, SkillActivationError, |
| 7 | SkillActivationOutcome, SkillBundledTier, SkillEntry, SkillMutationOutcome, |
| 8 | SkillMutationReceipt, SkillSourceKind, SkillSyncEntry, SkillSyncOutcome, SkillTargetScope, |
| 9 | }; |
| 10 | use codewhale_command_contract::handler::{CommandContexts, CommandHandler}; |
| 11 | use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand}; |
| 12 | |
| 13 | use crate::commands::CommandResult; |
| 14 | use crate::tui::app::AppAction; |
| 15 | |
| 16 | // --------------------------------------------------------------------------- |
| 17 | // Portable rendering helpers for the shared skill registry projection |
| 18 | // --------------------------------------------------------------------------- |
| 19 | |
| 20 | /// Render registry warnings as the baseline suffix block. |
| 21 | fn render_skill_warnings(warnings: &[String]) -> String { |
| 22 | if warnings.is_empty() { |
| 23 | return String::new(); |
| 24 | } |
| 25 | |
| 26 | let mut out = String::new(); |
| 27 | let _ = writeln!(out, "\nWarnings ({}):", warnings.len()); |
| 28 | for warning in warnings { |
| 29 | let _ = writeln!(out, " - {warning}"); |
| 30 | } |
| 31 | out |
| 32 | } |
| 33 | |
| 34 | /// Source label used by `/skills inspect` (baseline `skill_source_label`). |
| 35 | fn skill_source_label(source: &SkillSourceKind) -> String { |
| 36 | match source { |
| 37 | SkillSourceKind::Native => "native".to_string(), |
| 38 | SkillSourceKind::Plugin { |
| 39 | plugin_name, |
| 40 | plugin_id, |
| 41 | } => format!("reviewed plugin snapshot {plugin_name} ({plugin_id})"), |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | /// Network-policy approval message (baseline `needs_approval_message`). |
| 46 | fn needs_approval_message(host: &str) -> String { |
| 47 | format!( |
| 48 | "Network policy requires approval for {host}.\n\ |
| 49 | Add it to your allow list with `/network allow {host}` (or set [network].default = \"allow\" in ~/.codewhale/config.toml), then retry." |
| 50 | ) |
| 51 | } |
| 52 | |
| 53 | /// Network-policy denial message (baseline `network_denied_message`). |
| 54 | fn network_denied_message(host: &str) -> String { |
| 55 | format!( |
| 56 | "Network policy denied access to {host}.\n\ |
| 57 | Remove the deny entry from ~/.codewhale/config.toml under [network] or contact your administrator." |
| 58 | ) |
| 59 | } |
| 60 | |
| 61 | /// Render a mutation receipt byte-identically (baseline `format_mutation_receipt`). |
| 62 | fn format_mutation_receipt(receipt: &SkillMutationReceipt) -> String { |
| 63 | match &receipt.outcome { |
| 64 | SkillMutationOutcome::Installed => format!( |
| 65 | "Installed skill '{}'.\nLocation: {}\n\nManage skills with /skills.", |
| 66 | receipt.name, receipt.safe_target_path |
| 67 | ), |
| 68 | SkillMutationOutcome::Updated => format!( |
| 69 | "Skill '{}' updated.\nLocation: {}", |
| 70 | receipt.name, receipt.safe_target_path |
| 71 | ), |
| 72 | SkillMutationOutcome::NoChange => { |
| 73 | format!("Skill '{}': no upstream change.", receipt.name) |
| 74 | } |
| 75 | SkillMutationOutcome::Removed => format!("Removed skill '{}'.", receipt.name), |
| 76 | SkillMutationOutcome::Trusted => format!( |
| 77 | "Marked skill '{}' as trusted. The .trusted marker is advisory and digest-bound; it records your review intent but does not sandbox or auto-authorize scripts.", |
| 78 | receipt.name |
| 79 | ), |
| 80 | SkillMutationOutcome::Imported => format!( |
| 81 | "Imported skill '{}'.\nLocation: {}", |
| 82 | receipt.name, receipt.safe_target_path |
| 83 | ), |
| 84 | SkillMutationOutcome::AlreadyPresent => format!( |
| 85 | "Skill '{}' is already present at {} (exact duplicate).", |
| 86 | receipt.name, receipt.safe_target_path |
| 87 | ), |
| 88 | SkillMutationOutcome::NeedsApproval(host) => needs_approval_message(host), |
| 89 | SkillMutationOutcome::NetworkDenied(host) => network_denied_message(host), |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | /// Parse an optional `--project` / `--global` scope prefix (baseline |
| 94 | /// `parse_scope_args`, portable scope enum). |
| 95 | fn parse_scope_args(args: &str) -> Result<(Option<SkillTargetScope>, &str), String> { |
| 96 | let mut scope = None; |
| 97 | let mut rest = args.trim(); |
| 98 | loop { |
| 99 | if let Some(next) = rest.strip_prefix("--project") { |
| 100 | if scope.is_some() { |
| 101 | return Err("specify at most one of --project / --global".into()); |
| 102 | } |
| 103 | scope = Some(SkillTargetScope::Project); |
| 104 | rest = next.trim_start(); |
| 105 | continue; |
| 106 | } |
| 107 | if let Some(next) = rest.strip_prefix("--global") { |
| 108 | if scope.is_some() { |
| 109 | return Err("specify at most one of --project / --global".into()); |
| 110 | } |
| 111 | scope = Some(SkillTargetScope::Global); |
| 112 | rest = next.trim_start(); |
| 113 | continue; |
| 114 | } |
| 115 | break; |
| 116 | } |
| 117 | Ok((scope, rest.trim())) |
| 118 | } |
| 119 | |
| 120 | // --------------------------------------------------------------------------- |
| 121 | // /skills — portable contextual dispatch |
| 122 | // --------------------------------------------------------------------------- |
| 123 | |
| 124 | pub(in crate::commands) const SKILLS_INFO: CommandInfo = CommandInfo { |
| 125 | name: "skills", |
| 126 | aliases: &["jinengliebiao"], |
| 127 | usage: "/skills [manage|--remote|sync|inspect|suggest <task>|<prefix>] (bare opens Plugins)", |
| 128 | description_key: "cmd_skills_description", |
| 129 | }; |
| 130 | |
| 131 | pub(in crate::commands) struct SkillsCmd; |
| 132 | |
| 133 | impl RegisterCommand<CommandResult> for SkillsCmd { |
| 134 | fn info() -> &'static CommandInfo { |
| 135 | &SKILLS_INFO |
| 136 | } |
| 137 | |
| 138 | fn handler() -> CommandHandler<CommandResult> { |
| 139 | CommandHandler::Contextual { |
| 140 | capabilities: codewhale_command_contract::handler::CommandCapabilities::SKILL_GROUP, |
| 141 | handler: skills_contextual, |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | /// Contextual `/skills` dispatch (FEAT-022 D4): exactly the skill-group facet. |
| 147 | fn skills_contextual(contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult { |
| 148 | let mut parts = contexts.into_parts(); |
| 149 | let Some(skill_group) = parts.skill_group.as_deref_mut() else { |
| 150 | return CommandResult::error("Command capability unavailable: skill_group"); |
| 151 | }; |
| 152 | list_skills(skill_group, arg) |
| 153 | } |
| 154 | |
| 155 | /// Shared inventory entry, with the dedicated mutation manager kept at `/skills manage`. |
| 156 | fn list_skills(group: &mut dyn CommandSkillGroupContext, arg: Option<&str>) -> CommandResult { |
| 157 | let mut prefix: Option<String> = None; |
| 158 | if let Some(arg) = arg { |
| 159 | let trimmed = arg.trim(); |
| 160 | if trimmed == "manage" { |
| 161 | return CommandResult::action(AppAction::OpenSkillsManager); |
| 162 | } |
| 163 | if trimmed == "--remote" || trimmed == "remote" { |
| 164 | return list_remote_skills(group); |
| 165 | } |
| 166 | if trimmed == "sync" || trimmed == "--sync" { |
| 167 | return sync_skills(group); |
| 168 | } |
| 169 | if trimmed == "inspect" || trimmed == "--inspect" { |
| 170 | return inspect_skills(group); |
| 171 | } |
| 172 | if trimmed == "suggest" || trimmed == "recommend" { |
| 173 | return CommandResult::error("Usage: /skills suggest <task>"); |
| 174 | } |
| 175 | if let Some(task) = trimmed |
| 176 | .strip_prefix("suggest ") |
| 177 | .or_else(|| trimmed.strip_prefix("recommend ")) |
| 178 | { |
| 179 | return suggest_remote_skills(group, task); |
| 180 | } |
| 181 | if !trimmed.is_empty() { |
| 182 | // Anything else is treated as a name-prefix filter (#1318). |
| 183 | // Reject obviously malformed args (whitespace inside the |
| 184 | // prefix, leading dash) so future flag additions don't |
| 185 | // collide with skill names. Skill names that start with |
| 186 | // `-` aren't allowed by the loader so this is safe. |
| 187 | if trimmed.starts_with('-') || trimmed.split_whitespace().count() > 1 { |
| 188 | return CommandResult::error( |
| 189 | "Usage: /skills [--remote|sync|inspect|suggest <task>|<name-prefix>]", |
| 190 | ); |
| 191 | } |
| 192 | prefix = Some(trimmed.to_ascii_lowercase()); |
| 193 | } |
| 194 | } else { |
| 195 | // Bare inventory is owned-only and performs no network requests. |
| 196 | return CommandResult::action(AppAction::OpenExtensions { |
| 197 | tab: crate::tui::views::extensions::ExtensionsTab::Skills, |
| 198 | }); |
| 199 | } |
| 200 | |
| 201 | let projection = group.skill_registry_projection(); |
| 202 | let warnings = render_skill_warnings(&projection.warnings); |
| 203 | let skills_dir = projection.skills_dir.clone(); |
| 204 | |
| 205 | if projection.entries.is_empty() { |
| 206 | let msg = format!( |
| 207 | "No skills found.\n\n\ |
| 208 | Skills location: {}\n\n\ |
| 209 | To add skills, create directories with SKILL.md files:\n \ |
| 210 | {}/my-skill/SKILL.md\n\n\ |
| 211 | Format:\n \ |
| 212 | ---\n \ |
| 213 | name: my-skill\n \ |
| 214 | description: What this skill does\n \ |
| 215 | ---\n\n \ |
| 216 | <instructions here>{warnings}", |
| 217 | skills_dir, skills_dir |
| 218 | ); |
| 219 | return CommandResult::message(msg); |
| 220 | } |
| 221 | |
| 222 | let filtered: Vec<&SkillEntry> = if let Some(p) = prefix.as_deref() { |
| 223 | projection |
| 224 | .entries |
| 225 | .iter() |
| 226 | .filter(|s| s.name.to_ascii_lowercase().starts_with(p)) |
| 227 | .collect() |
| 228 | } else { |
| 229 | projection.entries.iter().collect() |
| 230 | }; |
| 231 | |
| 232 | if filtered.is_empty() { |
| 233 | // The user typed a prefix that matched nothing. Surface what |
| 234 | // they typed plus the full count so they can decide whether |
| 235 | // to adjust the prefix or run `/skills` for the whole list. |
| 236 | let p = prefix.as_deref().unwrap_or(""); |
| 237 | return CommandResult::message(format!( |
| 238 | "No skills match prefix `{p}` (out of {} available).\n\nRun /skills to see them all.{warnings}", |
| 239 | projection.total |
| 240 | )); |
| 241 | } |
| 242 | |
| 243 | let mut output = if let Some(p) = prefix.as_deref() { |
| 244 | format!( |
| 245 | "Available skills matching `{p}` ({} of {}):\n", |
| 246 | filtered.len(), |
| 247 | projection.total |
| 248 | ) |
| 249 | } else { |
| 250 | format!("Available skills ({}):\n", projection.total) |
| 251 | }; |
| 252 | output.push_str("─────────────────────────────\n"); |
| 253 | |
| 254 | if prefix.is_some() { |
| 255 | // Filtered view: keep the flat list — the user already narrowed. |
| 256 | for (idx, skill) in filtered.iter().enumerate() { |
| 257 | if idx > 0 { |
| 258 | output.push('\n'); |
| 259 | } |
| 260 | let _ = writeln!(output, " /{} - {}", skill.name, skill.description); |
| 261 | } |
| 262 | } else { |
| 263 | // Unfiltered view: keep user-created skills prominent, then split the |
| 264 | // shipped catalog into its two curated product tiers. The tier |
| 265 | // classification is resolved host-side into `bundled_tier` so the |
| 266 | // canonical bundle-name list is never duplicated here. |
| 267 | let (user_skills, bundled_skills): (Vec<&SkillEntry>, Vec<&SkillEntry>) = |
| 268 | filtered.iter().partition(|s| s.bundled_tier.is_none()); |
| 269 | |
| 270 | if !user_skills.is_empty() { |
| 271 | let _ = writeln!(output, "Your skills ({}):", user_skills.len()); |
| 272 | for skill in &user_skills { |
| 273 | let _ = writeln!(output, " /{} - {}", skill.name, skill.description); |
| 274 | } |
| 275 | if !bundled_skills.is_empty() { |
| 276 | output.push('\n'); |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | if !bundled_skills.is_empty() { |
| 281 | let (core, tooling): (Vec<&SkillEntry>, Vec<&SkillEntry>) = bundled_skills |
| 282 | .into_iter() |
| 283 | .partition(|skill| skill.bundled_tier == Some(SkillBundledTier::CoreAgentic)); |
| 284 | for (group_idx, (tier, skills)) in [ |
| 285 | (SkillBundledTier::CoreAgentic, core), |
| 286 | (SkillBundledTier::FormatTooling, tooling), |
| 287 | ] |
| 288 | .into_iter() |
| 289 | .enumerate() |
| 290 | { |
| 291 | if skills.is_empty() { |
| 292 | continue; |
| 293 | } |
| 294 | if group_idx > 0 { |
| 295 | output.push('\n'); |
| 296 | } |
| 297 | let _ = writeln!(output, "{} ({}):", tier.heading(), skills.len()); |
| 298 | if user_skills.is_empty() { |
| 299 | for skill in skills { |
| 300 | let _ = writeln!(output, " /{} - {}", skill.name, skill.description); |
| 301 | } |
| 302 | } else { |
| 303 | let names: Vec<String> = skills |
| 304 | .iter() |
| 305 | .map(|skill| format!("/{}", skill.name)) |
| 306 | .collect(); |
| 307 | let _ = writeln!(output, " {}", names.join(", ")); |
| 308 | } |
| 309 | } |
| 310 | if !user_skills.is_empty() { |
| 311 | output.push_str(" (run /skills <name> for details on a built-in)\n"); |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | let _ = write!( |
| 317 | output, |
| 318 | "\nUse /skill <name> to run a skill\nSkills location: {}{}", |
| 319 | skills_dir, warnings |
| 320 | ); |
| 321 | |
| 322 | CommandResult::message(output) |
| 323 | } |
| 324 | |
| 325 | /// `/skills inspect` — byte-identical discovery diagnostics. |
| 326 | fn inspect_skills(group: &mut dyn CommandSkillGroupContext) -> CommandResult { |
| 327 | let projection = group.skill_registry_projection(); |
| 328 | let warnings = render_skill_warnings(&projection.warnings); |
| 329 | |
| 330 | let mut output = String::from("Skills Inspect\n"); |
| 331 | output.push_str("─────────────────────────────\n"); |
| 332 | let _ = writeln!(output, "Discovery mode: {}", projection.mode_label); |
| 333 | let _ = writeln!(output, "Workspace: {}", projection.workspace); |
| 334 | let _ = writeln!(output, "Configured skills dir: {}", projection.skills_dir); |
| 335 | for line in &projection.bundled_status { |
| 336 | let _ = writeln!(output, "{line}"); |
| 337 | } |
| 338 | |
| 339 | if projection.dirs.is_empty() { |
| 340 | output.push_str("\nSearched directories: none found\n"); |
| 341 | } else { |
| 342 | let _ = writeln!( |
| 343 | output, |
| 344 | "\nSearched directories ({}):", |
| 345 | projection.dirs.len() |
| 346 | ); |
| 347 | for (idx, dir) in projection.dirs.iter().enumerate() { |
| 348 | let _ = writeln!(output, " {}. {}", idx + 1, dir); |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | let _ = writeln!(output, "\nAvailable skills ({}):", projection.total); |
| 353 | if projection.entries.is_empty() { |
| 354 | output.push_str(" (none)\n"); |
| 355 | } else { |
| 356 | for skill in &projection.entries { |
| 357 | if skill.description.trim().is_empty() { |
| 358 | let _ = writeln!(output, " - {}", skill.name); |
| 359 | } else { |
| 360 | let _ = writeln!(output, " - {} — {}", skill.name, skill.description); |
| 361 | } |
| 362 | let _ = writeln!(output, " source: {}", skill_source_label(&skill.source)); |
| 363 | if let Some(path) = skill |
| 364 | .path |
| 365 | .as_ref() |
| 366 | .filter(|_| matches!(skill.source, SkillSourceKind::Native)) |
| 367 | { |
| 368 | let _ = writeln!(output, " path: {}", path); |
| 369 | } |
| 370 | if let Some(note) = &skill.index_note { |
| 371 | let _ = writeln!(output, " {note}"); |
| 372 | } |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | output.push_str(&warnings); |
| 377 | CommandResult::message(output) |
| 378 | } |
| 379 | |
| 380 | /// `/skills --remote` — curated registry listing. |
| 381 | fn list_remote_skills(group: &mut dyn CommandSkillGroupContext) -> CommandResult { |
| 382 | match group.fetch_remote_registry() { |
| 383 | Ok(RemoteRegistryOutcome::Loaded { entries }) => { |
| 384 | if entries.is_empty() { |
| 385 | return CommandResult::message("Registry is empty."); |
| 386 | } |
| 387 | let mut out = format!("Available remote skills ({}):\n", entries.len()); |
| 388 | out.push_str("─────────────────────────────\n"); |
| 389 | for entry in &entries { |
| 390 | let _ = writeln!( |
| 391 | out, |
| 392 | " {} — {} (source: {})", |
| 393 | entry.name, |
| 394 | entry.description.clone().unwrap_or_default(), |
| 395 | entry.source |
| 396 | ); |
| 397 | } |
| 398 | let _ = write!(out, "\nInstall with: /skill install <name>"); |
| 399 | CommandResult::message(out) |
| 400 | } |
| 401 | Ok(RemoteRegistryOutcome::NeedsApproval(host)) => { |
| 402 | CommandResult::error(needs_approval_message(&host)) |
| 403 | } |
| 404 | Ok(RemoteRegistryOutcome::Denied(host)) => { |
| 405 | CommandResult::error(network_denied_message(&host)) |
| 406 | } |
| 407 | Err(err) => CommandResult::error(err), |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | /// `/skills suggest <task>` — ranked remote recommendations. |
| 412 | fn suggest_remote_skills(group: &mut dyn CommandSkillGroupContext, task: &str) -> CommandResult { |
| 413 | let task = task.trim(); |
| 414 | if task.chars().count() < 3 { |
| 415 | return CommandResult::error("Usage: /skills suggest <task of at least 3 characters>"); |
| 416 | } |
| 417 | |
| 418 | match group.recommend_skills(task) { |
| 419 | Ok(recommendations) => { |
| 420 | if recommendations.is_empty() { |
| 421 | return CommandResult::message(format!( |
| 422 | "No curated remote skills matched `{task}`.\n\nBrowse the catalog with /skills --remote. Nothing was installed, trusted, or enabled." |
| 423 | )); |
| 424 | } |
| 425 | |
| 426 | let mut out = format!("Suggested remote skills for `{task}`:\n"); |
| 427 | out.push_str("─────────────────────────────\n"); |
| 428 | for recommendation in &recommendations { |
| 429 | let description = recommendation |
| 430 | .description |
| 431 | .as_deref() |
| 432 | .filter(|description| !description.trim().is_empty()) |
| 433 | .unwrap_or("No description provided."); |
| 434 | let _ = writeln!(out, " {} — {description}", recommendation.name); |
| 435 | let _ = writeln!(out, " Why: {}", recommendation.matched_terms.join(", ")); |
| 436 | let _ = writeln!( |
| 437 | out, |
| 438 | " Install if you want it: /skill install {}", |
| 439 | recommendation.name |
| 440 | ); |
| 441 | } |
| 442 | out.push_str("\nNothing was installed, trusted, or enabled."); |
| 443 | CommandResult::message(out) |
| 444 | } |
| 445 | Err(err) => CommandResult::error(err), |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | /// `/skills sync` — registry sync report. |
| 450 | fn sync_skills(group: &mut dyn CommandSkillGroupContext) -> CommandResult { |
| 451 | match group.sync_registry() { |
| 452 | Ok(SkillSyncOutcome::Done { |
| 453 | total, |
| 454 | downloaded, |
| 455 | fresh, |
| 456 | failed, |
| 457 | entries, |
| 458 | }) => { |
| 459 | let mut out = String::from("Registry sync complete.\n\n"); |
| 460 | |
| 461 | for outcome in &entries { |
| 462 | match outcome { |
| 463 | SkillSyncEntry::Downloaded { name, path } => { |
| 464 | let _ = writeln!(out, " [+] {name} — downloaded to {path}"); |
| 465 | } |
| 466 | SkillSyncEntry::Fresh { name } => { |
| 467 | let _ = writeln!(out, " [=] {name} — already up to date"); |
| 468 | } |
| 469 | SkillSyncEntry::Failed { name, reason } => { |
| 470 | let _ = writeln!(out, " [!] {name} — failed: {reason}"); |
| 471 | } |
| 472 | SkillSyncEntry::Denied { name, host } => { |
| 473 | let _ = writeln!(out, " [!] {name} — network denied ({host})"); |
| 474 | } |
| 475 | SkillSyncEntry::NeedsApproval { name, host } => { |
| 476 | let _ = writeln!( |
| 477 | out, |
| 478 | " [?] {name} — needs approval for {host} (run `/network allow {host}` then retry)" |
| 479 | ); |
| 480 | } |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | let _ = write!( |
| 485 | out, |
| 486 | "\n{total} skill(s) processed: {downloaded} downloaded, {fresh} up-to-date, {failed} failed." |
| 487 | ); |
| 488 | |
| 489 | CommandResult::message(out) |
| 490 | } |
| 491 | Ok(SkillSyncOutcome::RegistryNeedsApproval(host)) => { |
| 492 | CommandResult::error(needs_approval_message(&host)) |
| 493 | } |
| 494 | Ok(SkillSyncOutcome::RegistryDenied(host)) => { |
| 495 | CommandResult::error(network_denied_message(&host)) |
| 496 | } |
| 497 | Err(err) => CommandResult::error(err), |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | // --------------------------------------------------------------------------- |
| 502 | // /skill — portable contextual dispatch |
| 503 | // --------------------------------------------------------------------------- |
| 504 | |
| 505 | pub(in crate::commands) const SKILL_INFO: CommandInfo = CommandInfo { |
| 506 | name: "skill", |
| 507 | aliases: &["jineng"], |
| 508 | usage: "/skill <name|install <spec>|update <name>|uninstall <name>|trust <name>>", |
| 509 | description_key: "cmd_skill_description", |
| 510 | }; |
| 511 | |
| 512 | pub(in crate::commands) struct SkillCmd; |
| 513 | |
| 514 | impl RegisterCommand<CommandResult> for SkillCmd { |
| 515 | fn info() -> &'static CommandInfo { |
| 516 | &SKILL_INFO |
| 517 | } |
| 518 | |
| 519 | fn handler() -> CommandHandler<CommandResult> { |
| 520 | CommandHandler::Contextual { |
| 521 | capabilities: codewhale_command_contract::handler::CommandCapabilities::SKILL_GROUP |
| 522 | .union(codewhale_command_contract::handler::CommandCapabilities::SKILLS), |
| 523 | handler: skill_contextual, |
| 524 | } |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | /// Contextual `/skill` dispatch (FEAT-022 D4): exactly the skill-group facet |
| 529 | /// plus the shared SKILLS facet (active-skill reads + cache refresh; D2). |
| 530 | fn skill_contextual(contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult { |
| 531 | let mut parts = contexts.into_parts(); |
| 532 | let Some(skill_group) = parts.skill_group.as_deref_mut() else { |
| 533 | return CommandResult::error("Command capability unavailable: skill_group"); |
| 534 | }; |
| 535 | let Some(skills) = parts.skills.as_deref_mut() else { |
| 536 | return CommandResult::error("Command capability unavailable: skills"); |
| 537 | }; |
| 538 | run_skill(skill_group, skills, arg) |
| 539 | } |
| 540 | |
| 541 | /// Portable `/skill` dispatch — byte-identical to the baseline handler. |
| 542 | fn run_skill( |
| 543 | group: &mut dyn CommandSkillGroupContext, |
| 544 | skills: &mut dyn CommandSkillsContext, |
| 545 | arg: Option<&str>, |
| 546 | ) -> CommandResult { |
| 547 | let raw = match arg { |
| 548 | Some(n) => n.trim(), |
| 549 | None => { |
| 550 | return CommandResult::error( |
| 551 | "Usage: /skill <name>\n\nSubcommands:\n /skill install [--project|--global] <github:owner/repo|https://…|<registry-name>>\n /skill update [--project|--global] <name>\n /skill uninstall [--project|--global] <name>\n /skill trust [--project|--global] <name>", |
| 552 | ); |
| 553 | } |
| 554 | }; |
| 555 | |
| 556 | // Sub-command dispatch happens before the activation path so users can't |
| 557 | // accidentally activate a skill literally named "install". |
| 558 | let mut iter = raw.splitn(2, char::is_whitespace); |
| 559 | let head = iter.next().unwrap_or("").trim(); |
| 560 | let rest = iter.next().unwrap_or("").trim(); |
| 561 | match head { |
| 562 | "install" => return install_skill(group, skills, rest), |
| 563 | "update" => return update_skill(group, skills, rest), |
| 564 | "uninstall" => return uninstall_skill(group, skills, rest), |
| 565 | "trust" => return trust_skill(group, rest), |
| 566 | _ => {} |
| 567 | } |
| 568 | |
| 569 | let task = (!rest.is_empty()).then_some(rest); |
| 570 | activate_skill_portable(group, head, task) |
| 571 | } |
| 572 | |
| 573 | fn format_skill_activation_outcome( |
| 574 | outcome: SkillActivationOutcome, |
| 575 | task: Option<&str>, |
| 576 | ) -> CommandResult { |
| 577 | let mut result = CommandResult::message(format!( |
| 578 | "Skill '{}' activated.\n\nDescription: {}\n\nType your request and the skill instructions will be applied.", |
| 579 | outcome.name, outcome.description |
| 580 | )); |
| 581 | if let Some(task) = task.map(str::trim).filter(|task| !task.is_empty()) { |
| 582 | result.action = Some(AppAction::SendMessage(task.to_string())); |
| 583 | } |
| 584 | result |
| 585 | } |
| 586 | |
| 587 | pub(in crate::commands) fn try_activate_skill_portable( |
| 588 | group: &mut dyn CommandSkillGroupContext, |
| 589 | name: &str, |
| 590 | task: Option<&str>, |
| 591 | ) -> Option<CommandResult> { |
| 592 | let name = if name == "new" { "skill-creator" } else { name }; |
| 593 | match group.activate_skill(name) { |
| 594 | Ok(outcome) => Some(format_skill_activation_outcome(outcome, task)), |
| 595 | Err(SkillActivationError::NotFound { .. }) => None, |
| 596 | Err(SkillActivationError::InvocationRejected { name, reason }) => Some( |
| 597 | CommandResult::error(format!("Skill '{}' could not be activated: {reason}", name)), |
| 598 | ), |
| 599 | Err(SkillActivationError::PluginRejected { name, reason }) => Some(CommandResult::error( |
| 600 | format!("Plugin skill '{}' is no longer active: {reason}", name), |
| 601 | )), |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | /// Portable activation — the host performs lookup, authority verification, and |
| 606 | /// side effects; the handler composes the byte-identical messages/actions. |
| 607 | fn activate_skill_portable( |
| 608 | group: &mut dyn CommandSkillGroupContext, |
| 609 | name: &str, |
| 610 | task: Option<&str>, |
| 611 | ) -> CommandResult { |
| 612 | // `/skill new` is a friendly alias for `/skill skill-creator`; the alias is |
| 613 | // resolved here (parsing stays portable) so the not-found message uses the |
| 614 | // mapped name exactly like the baseline. |
| 615 | let name = if name == "new" { "skill-creator" } else { name }; |
| 616 | |
| 617 | match group.activate_skill(name) { |
| 618 | Ok(outcome) => format_skill_activation_outcome(outcome, task), |
| 619 | Err(SkillActivationError::NotFound { |
| 620 | requested, |
| 621 | available, |
| 622 | warnings, |
| 623 | }) => { |
| 624 | let warnings = render_skill_warnings(&warnings); |
| 625 | if available.is_empty() { |
| 626 | CommandResult::error(format!( |
| 627 | "Skill '{requested}' not found. No skills installed.\n\nUse /skills to see how to add skills.{warnings}" |
| 628 | )) |
| 629 | } else { |
| 630 | CommandResult::error(format!( |
| 631 | "Skill '{}' not found.\n\nAvailable skills: {}{}", |
| 632 | requested, |
| 633 | available.join(", "), |
| 634 | warnings |
| 635 | )) |
| 636 | } |
| 637 | } |
| 638 | Err(SkillActivationError::InvocationRejected { name, reason }) => { |
| 639 | CommandResult::error(format!("Skill '{}' could not be activated: {reason}", name)) |
| 640 | } |
| 641 | Err(SkillActivationError::PluginRejected { name, reason }) => CommandResult::error( |
| 642 | format!("Plugin skill '{}' is no longer active: {reason}", name), |
| 643 | ), |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | // ─── /skill install ──────────────────────────────────────────────────────── |
| 648 | |
| 649 | fn install_skill( |
| 650 | group: &mut dyn CommandSkillGroupContext, |
| 651 | skills: &mut dyn CommandSkillsContext, |
| 652 | args: &str, |
| 653 | ) -> CommandResult { |
| 654 | let (scope, spec) = match parse_scope_args(args) { |
| 655 | Ok(v) => v, |
| 656 | Err(err) => return CommandResult::error(err), |
| 657 | }; |
| 658 | if spec.is_empty() { |
| 659 | return CommandResult::error( |
| 660 | "Usage: /skill install [--project|--global] <github:owner/repo|https://…|<registry-name>>", |
| 661 | ); |
| 662 | } |
| 663 | match group.install_skill(scope, spec) { |
| 664 | Ok(receipt) => { |
| 665 | // Cache refresh is a D2 shared-SKILLS operation: the host returns |
| 666 | // the receipt; the portable handler owns the refresh policy. |
| 667 | if matches!(receipt.outcome, SkillMutationOutcome::Installed) { |
| 668 | skills.refresh_skill_cache(); |
| 669 | } |
| 670 | let message = format_mutation_receipt(&receipt); |
| 671 | if matches!( |
| 672 | receipt.outcome, |
| 673 | SkillMutationOutcome::NeedsApproval(_) | SkillMutationOutcome::NetworkDenied(_) |
| 674 | ) { |
| 675 | CommandResult::error(message) |
| 676 | } else { |
| 677 | CommandResult::message(message) |
| 678 | } |
| 679 | } |
| 680 | Err(err) => CommandResult::error(err), |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | // ─── /skill update ───────────────────────────────────────────────────────── |
| 685 | |
| 686 | fn update_skill( |
| 687 | group: &mut dyn CommandSkillGroupContext, |
| 688 | skills: &mut dyn CommandSkillsContext, |
| 689 | args: &str, |
| 690 | ) -> CommandResult { |
| 691 | let (scope, name) = match parse_scope_args(args) { |
| 692 | Ok(v) => v, |
| 693 | Err(err) => return CommandResult::error(err), |
| 694 | }; |
| 695 | if name.is_empty() { |
| 696 | return CommandResult::error("Usage: /skill update [--project|--global] <name>"); |
| 697 | } |
| 698 | match group.update_skill(scope, name) { |
| 699 | Ok(receipt) => { |
| 700 | if matches!(receipt.outcome, SkillMutationOutcome::Updated) { |
| 701 | skills.refresh_skill_cache(); |
| 702 | } |
| 703 | let message = format_mutation_receipt(&receipt); |
| 704 | if matches!( |
| 705 | receipt.outcome, |
| 706 | SkillMutationOutcome::NeedsApproval(_) | SkillMutationOutcome::NetworkDenied(_) |
| 707 | ) { |
| 708 | CommandResult::error(message) |
| 709 | } else { |
| 710 | CommandResult::message(message) |
| 711 | } |
| 712 | } |
| 713 | Err(err) => CommandResult::error(err), |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | // ─── /skill uninstall ────────────────────────────────────────────────────── |
| 718 | |
| 719 | fn uninstall_skill( |
| 720 | group: &mut dyn CommandSkillGroupContext, |
| 721 | skills: &mut dyn CommandSkillsContext, |
| 722 | args: &str, |
| 723 | ) -> CommandResult { |
| 724 | let (scope, name) = match parse_scope_args(args) { |
| 725 | Ok(v) => v, |
| 726 | Err(err) => return CommandResult::error(err), |
| 727 | }; |
| 728 | if name.is_empty() { |
| 729 | return CommandResult::error("Usage: /skill uninstall [--project|--global] <name>"); |
| 730 | } |
| 731 | match group.uninstall_skill(scope, name) { |
| 732 | Ok(receipt) => { |
| 733 | skills.refresh_skill_cache(); |
| 734 | CommandResult::message(format_mutation_receipt(&receipt)) |
| 735 | } |
| 736 | Err(err) => CommandResult::error(err), |
| 737 | } |
| 738 | } |
| 739 | |
| 740 | // ─── /skill trust ────────────────────────────────────────────────────────── |
| 741 | |
| 742 | fn trust_skill(group: &mut dyn CommandSkillGroupContext, args: &str) -> CommandResult { |
| 743 | let (scope, name) = match parse_scope_args(args) { |
| 744 | Ok(v) => v, |
| 745 | Err(err) => return CommandResult::error(err), |
| 746 | }; |
| 747 | if name.is_empty() { |
| 748 | return CommandResult::error("Usage: /skill trust [--project|--global] <name>"); |
| 749 | } |
| 750 | match group.trust_skill(scope, name) { |
| 751 | Ok(receipt) => CommandResult::message(format_mutation_receipt(&receipt)), |
| 752 | Err(err) => CommandResult::error(err), |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | #[cfg(test)] |
| 757 | mod tests { |
| 758 | use super::*; |
| 759 | use codewhale_command_contract::facets::{ |
| 760 | CommandApprovalState, RemoteRegistryOutcome, RemoteSkillEntry, ReviewOutcome, |
| 761 | SkillActivationError, SkillActivationOutcome, SkillRecommendation, SkillRegistryProjection, |
| 762 | SkillSourceKind, SnapshotEntry, |
| 763 | }; |
| 764 | |
| 765 | /// Shared SKILLS fake: read-only getters + cache refresh (D2 surface). |
| 766 | struct FakeSkills { |
| 767 | refreshed: bool, |
| 768 | } |
| 769 | impl CommandSkillsContext for FakeSkills { |
| 770 | fn active_skill(&self) -> Option<String> { |
| 771 | None |
| 772 | } |
| 773 | fn active_skill_provenance(&self) -> Option<String> { |
| 774 | None |
| 775 | } |
| 776 | fn refresh_skill_cache(&mut self) { |
| 777 | self.refreshed = true; |
| 778 | } |
| 779 | } |
| 780 | |
| 781 | /// Counting fake for preserving the baseline's exact cache-refresh policy. |
| 782 | #[derive(Default)] |
| 783 | struct CountingSkills { |
| 784 | refresh_count: usize, |
| 785 | } |
| 786 | impl CommandSkillsContext for CountingSkills { |
| 787 | fn active_skill(&self) -> Option<String> { |
| 788 | None |
| 789 | } |
| 790 | fn active_skill_provenance(&self) -> Option<String> { |
| 791 | None |
| 792 | } |
| 793 | fn refresh_skill_cache(&mut self) { |
| 794 | self.refresh_count += 1; |
| 795 | } |
| 796 | } |
| 797 | |
| 798 | /// Deterministic fake skill-group facet over portable values only. |
| 799 | struct FakeSkillGroup { |
| 800 | projection: SkillRegistryProjection, |
| 801 | activation: Result<SkillActivationOutcome, SkillActivationError>, |
| 802 | activated: Option<String>, |
| 803 | install: Result<SkillMutationReceipt, String>, |
| 804 | update: Result<SkillMutationReceipt, String>, |
| 805 | uninstall: Result<SkillMutationReceipt, String>, |
| 806 | trust: Result<SkillMutationReceipt, String>, |
| 807 | remote: Result<RemoteRegistryOutcome, String>, |
| 808 | recommend: Result<Vec<SkillRecommendation>, String>, |
| 809 | sync: Result<SkillSyncOutcome, String>, |
| 810 | review: Result<ReviewOutcome, String>, |
| 811 | snapshots: Result<Vec<SnapshotEntry>, String>, |
| 812 | restore: Result<(), String>, |
| 813 | approval: CommandApprovalState, |
| 814 | } |
| 815 | |
| 816 | impl FakeSkillGroup { |
| 817 | fn new(entries: Vec<SkillEntry>) -> Self { |
| 818 | let total = entries.len(); |
| 819 | Self { |
| 820 | projection: SkillRegistryProjection { |
| 821 | workspace: "/ws".to_string(), |
| 822 | skills_dir: "/ws/.codewhale/skills".to_string(), |
| 823 | mode_label: "compatible".to_string(), |
| 824 | bundled_status: vec![], |
| 825 | dirs: vec!["/ws/.codewhale/skills".to_string()], |
| 826 | entries, |
| 827 | warnings: vec![], |
| 828 | total, |
| 829 | }, |
| 830 | activation: Ok(SkillActivationOutcome { |
| 831 | name: "demo".to_string(), |
| 832 | description: "Demo skill".to_string(), |
| 833 | }), |
| 834 | activated: None, |
| 835 | install: Ok(SkillMutationReceipt { |
| 836 | name: "demo".to_string(), |
| 837 | safe_target_path: "/ws/.codewhale/skills/demo".to_string(), |
| 838 | outcome: SkillMutationOutcome::Installed, |
| 839 | }), |
| 840 | update: Ok(SkillMutationReceipt { |
| 841 | name: "demo".to_string(), |
| 842 | safe_target_path: "/ws/.codewhale/skills/demo".to_string(), |
| 843 | outcome: SkillMutationOutcome::Updated, |
| 844 | }), |
| 845 | uninstall: Ok(SkillMutationReceipt { |
| 846 | name: "demo".to_string(), |
| 847 | safe_target_path: "/ws/.codewhale/skills/demo".to_string(), |
| 848 | outcome: SkillMutationOutcome::Removed, |
| 849 | }), |
| 850 | trust: Ok(SkillMutationReceipt { |
| 851 | name: "demo".to_string(), |
| 852 | safe_target_path: "/ws/.codewhale/skills/demo".to_string(), |
| 853 | outcome: SkillMutationOutcome::Trusted, |
| 854 | }), |
| 855 | remote: Ok(RemoteRegistryOutcome::Loaded { |
| 856 | entries: vec![RemoteSkillEntry { |
| 857 | name: "remote-demo".to_string(), |
| 858 | description: Some("Remote demo".to_string()), |
| 859 | source: "github.com/acme/skills".to_string(), |
| 860 | }], |
| 861 | }), |
| 862 | recommend: Ok(vec![SkillRecommendation { |
| 863 | name: "remote-demo".to_string(), |
| 864 | description: Some("Remote demo".to_string()), |
| 865 | matched_terms: vec!["demo".to_string()], |
| 866 | }]), |
| 867 | sync: Ok(SkillSyncOutcome::Done { |
| 868 | total: 1, |
| 869 | downloaded: 1, |
| 870 | fresh: 0, |
| 871 | failed: 0, |
| 872 | entries: vec![SkillSyncEntry::Downloaded { |
| 873 | name: "demo".to_string(), |
| 874 | path: "/cache/demo".to_string(), |
| 875 | }], |
| 876 | }), |
| 877 | review: Ok(ReviewOutcome::Ready), |
| 878 | snapshots: Ok(vec![SnapshotEntry { |
| 879 | id: "abcdef123456".to_string(), |
| 880 | label: "pre-turn:1".to_string(), |
| 881 | timestamp: 1_700_000_000, |
| 882 | }]), |
| 883 | restore: Ok(()), |
| 884 | approval: CommandApprovalState { |
| 885 | yolo: true, |
| 886 | trust_mode: false, |
| 887 | }, |
| 888 | } |
| 889 | } |
| 890 | } |
| 891 | |
| 892 | impl CommandSkillGroupContext for FakeSkillGroup { |
| 893 | fn skill_registry_projection(&self) -> SkillRegistryProjection { |
| 894 | self.projection.clone() |
| 895 | } |
| 896 | fn activate_skill( |
| 897 | &mut self, |
| 898 | name: &str, |
| 899 | ) -> Result<SkillActivationOutcome, SkillActivationError> { |
| 900 | self.activated = Some(name.to_string()); |
| 901 | self.activation.clone() |
| 902 | } |
| 903 | fn install_skill( |
| 904 | &mut self, |
| 905 | _scope: Option<SkillTargetScope>, |
| 906 | _spec: &str, |
| 907 | ) -> Result<SkillMutationReceipt, String> { |
| 908 | self.install.clone() |
| 909 | } |
| 910 | fn update_skill( |
| 911 | &mut self, |
| 912 | _scope: Option<SkillTargetScope>, |
| 913 | _name: &str, |
| 914 | ) -> Result<SkillMutationReceipt, String> { |
| 915 | self.update.clone() |
| 916 | } |
| 917 | fn uninstall_skill( |
| 918 | &mut self, |
| 919 | _scope: Option<SkillTargetScope>, |
| 920 | _name: &str, |
| 921 | ) -> Result<SkillMutationReceipt, String> { |
| 922 | self.uninstall.clone() |
| 923 | } |
| 924 | fn trust_skill( |
| 925 | &mut self, |
| 926 | _scope: Option<SkillTargetScope>, |
| 927 | _name: &str, |
| 928 | ) -> Result<SkillMutationReceipt, String> { |
| 929 | self.trust.clone() |
| 930 | } |
| 931 | fn fetch_remote_registry(&mut self) -> Result<RemoteRegistryOutcome, String> { |
| 932 | self.remote.clone() |
| 933 | } |
| 934 | fn recommend_skills(&mut self, _task: &str) -> Result<Vec<SkillRecommendation>, String> { |
| 935 | self.recommend.clone() |
| 936 | } |
| 937 | fn sync_registry(&mut self) -> Result<SkillSyncOutcome, String> { |
| 938 | self.sync.clone() |
| 939 | } |
| 940 | fn run_review(&mut self) -> Result<ReviewOutcome, String> { |
| 941 | self.review.clone() |
| 942 | } |
| 943 | fn snapshot_list(&mut self, _limit: usize) -> Result<Vec<SnapshotEntry>, String> { |
| 944 | self.snapshots.clone() |
| 945 | } |
| 946 | fn restore_snapshot(&mut self, _id: &str) -> Result<(), String> { |
| 947 | self.restore.clone() |
| 948 | } |
| 949 | fn approval_state(&self) -> CommandApprovalState { |
| 950 | self.approval |
| 951 | } |
| 952 | } |
| 953 | |
| 954 | fn demo_entry() -> SkillEntry { |
| 955 | SkillEntry { |
| 956 | index_note: None, |
| 957 | name: "demo".to_string(), |
| 958 | description: "Demo skill".to_string(), |
| 959 | source: SkillSourceKind::Native, |
| 960 | path: Some("/ws/.codewhale/skills/demo".to_string()), |
| 961 | bundled_tier: None, |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | fn bundled_entry(name: &str, tier: SkillBundledTier) -> SkillEntry { |
| 966 | SkillEntry { |
| 967 | index_note: None, |
| 968 | name: name.to_string(), |
| 969 | description: format!("{name} skill"), |
| 970 | source: SkillSourceKind::Native, |
| 971 | path: None, |
| 972 | bundled_tier: Some(tier), |
| 973 | } |
| 974 | } |
| 975 | |
| 976 | // ── /skills parity ──────────────────────────────────────────────────── |
| 977 | |
| 978 | #[test] |
| 979 | fn bare_skills_opens_extensions_and_manage_keeps_mutation_manager() { |
| 980 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 981 | let result = list_skills(&mut group, None); |
| 982 | assert!(result.message.is_none()); |
| 983 | assert!(matches!( |
| 984 | result.action, |
| 985 | Some(AppAction::OpenExtensions { |
| 986 | tab: crate::tui::views::extensions::ExtensionsTab::Skills |
| 987 | }) |
| 988 | )); |
| 989 | assert!(matches!( |
| 990 | list_skills(&mut group, Some("manage")).action, |
| 991 | Some(AppAction::OpenSkillsManager) |
| 992 | )); |
| 993 | } |
| 994 | |
| 995 | #[test] |
| 996 | fn skills_empty_registry_message_is_exact() { |
| 997 | let mut group = FakeSkillGroup::new(vec![]); |
| 998 | let result = list_skills(&mut group, Some("")); |
| 999 | let msg = result.message.expect("expected message"); |
| 1000 | assert!( |
| 1001 | msg.starts_with("No skills found.\n\nSkills location: /ws/.codewhale/skills\n"), |
| 1002 | "{msg}" |
| 1003 | ); |
| 1004 | assert!(msg.contains("/ws/.codewhale/skills/my-skill/SKILL.md")); |
| 1005 | } |
| 1006 | |
| 1007 | #[test] |
| 1008 | fn skills_prefix_listing_flat_format_is_exact() { |
| 1009 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1010 | let result = list_skills(&mut group, Some("de")); |
| 1011 | let msg = result.message.expect("expected message"); |
| 1012 | assert!( |
| 1013 | msg.starts_with("Available skills matching `de` (1 of 1):\n"), |
| 1014 | "{msg}" |
| 1015 | ); |
| 1016 | assert!(msg.contains(" /demo - Demo skill")); |
| 1017 | } |
| 1018 | |
| 1019 | #[test] |
| 1020 | fn skills_no_match_reports_prefix_and_total() { |
| 1021 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1022 | let result = list_skills(&mut group, Some("zzz")); |
| 1023 | let msg = result.message.expect("expected message"); |
| 1024 | assert!( |
| 1025 | msg.starts_with("No skills match prefix `zzz` (out of 1 available)."), |
| 1026 | "{msg}" |
| 1027 | ); |
| 1028 | } |
| 1029 | |
| 1030 | #[test] |
| 1031 | fn skills_unfiltered_splits_user_and_bundled_tiers() { |
| 1032 | let mut group = FakeSkillGroup::new(vec![ |
| 1033 | demo_entry(), |
| 1034 | bundled_entry("skill-creator", SkillBundledTier::FormatTooling), |
| 1035 | bundled_entry("help", SkillBundledTier::CoreAgentic), |
| 1036 | ]); |
| 1037 | let result = list_skills(&mut group, Some("")); |
| 1038 | let msg = result.message.expect("expected message"); |
| 1039 | assert!(msg.contains("Your skills (1):"), "{msg}"); |
| 1040 | assert!(msg.contains("Core agentic (1):"), "{msg}"); |
| 1041 | assert!(msg.contains(" /help"), "{msg}"); |
| 1042 | assert!(msg.contains("Format & tooling (1):"), "{msg}"); |
| 1043 | assert!(msg.contains(" /skill-creator"), "{msg}"); |
| 1044 | assert!( |
| 1045 | msg.contains("(run /skills <name> for details on a built-in)"), |
| 1046 | "{msg}" |
| 1047 | ); |
| 1048 | } |
| 1049 | |
| 1050 | #[test] |
| 1051 | fn skills_rejects_flag_like_and_multiword_prefixes() { |
| 1052 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1053 | let result = list_skills(&mut group, Some("-x")); |
| 1054 | assert!(result.is_error); |
| 1055 | assert!( |
| 1056 | result |
| 1057 | .message |
| 1058 | .unwrap() |
| 1059 | .contains("Usage: /skills [--remote|sync|inspect|suggest <task>|<name-prefix>]") |
| 1060 | ); |
| 1061 | let result = list_skills(&mut group, Some("two words")); |
| 1062 | assert!(result.is_error); |
| 1063 | } |
| 1064 | |
| 1065 | #[test] |
| 1066 | fn skills_suggest_requires_meaningful_task() { |
| 1067 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1068 | let result = list_skills(&mut group, Some("suggest")); |
| 1069 | assert!(result.is_error); |
| 1070 | assert!( |
| 1071 | result |
| 1072 | .message |
| 1073 | .unwrap() |
| 1074 | .contains("Usage: /skills suggest <task>") |
| 1075 | ); |
| 1076 | let result = list_skills(&mut group, Some("suggest ab")); |
| 1077 | assert!(result.is_error); |
| 1078 | assert!(result.message.unwrap().contains("at least 3 characters")); |
| 1079 | } |
| 1080 | |
| 1081 | #[test] |
| 1082 | fn skills_inspect_reports_discovery_details() { |
| 1083 | let mut entry = demo_entry(); |
| 1084 | entry.index_note = Some("Indice limité à 80 caractères".to_string()); |
| 1085 | let mut group = FakeSkillGroup::new(vec![entry]); |
| 1086 | group.projection.bundled_status = vec![ |
| 1087 | "Bundled skills: install=none".into(), |
| 1088 | "pdf: explicit-only by config (/owned/pdf/SKILL.md)".into(), |
| 1089 | ]; |
| 1090 | let result = list_skills(&mut group, Some("inspect")); |
| 1091 | let msg = result.message.expect("expected message"); |
| 1092 | assert!(msg.starts_with("Skills Inspect\n"), "{msg}"); |
| 1093 | assert!(msg.contains("Discovery mode: compatible")); |
| 1094 | assert!(msg.contains("Workspace: /ws")); |
| 1095 | assert!(msg.contains("Configured skills dir: /ws/.codewhale/skills")); |
| 1096 | assert!(msg.contains("Searched directories (1):")); |
| 1097 | assert!(msg.contains("Available skills (1):")); |
| 1098 | assert!(msg.contains("source: native")); |
| 1099 | assert!(msg.contains("path: /ws/.codewhale/skills/demo")); |
| 1100 | assert!(msg.contains("Indice limité à 80 caractères")); |
| 1101 | assert!(msg.contains("Bundled skills: install=none")); |
| 1102 | assert!(msg.contains("pdf: explicit-only by config (/owned/pdf/SKILL.md)")); |
| 1103 | } |
| 1104 | |
| 1105 | #[test] |
| 1106 | fn skills_remote_lists_entries_and_policy_errors() { |
| 1107 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1108 | let result = list_skills(&mut group, Some("--remote")); |
| 1109 | let msg = result.message.expect("expected message"); |
| 1110 | assert!(msg.contains("Available remote skills (1):"), "{msg}"); |
| 1111 | assert!(msg.contains("remote-demo — Remote demo (source: github.com/acme/skills)")); |
| 1112 | assert!(msg.contains("\nInstall with: /skill install <name>")); |
| 1113 | |
| 1114 | group.remote = Ok(RemoteRegistryOutcome::NeedsApproval("acme.com".to_string())); |
| 1115 | let result = list_skills(&mut group, Some("remote")); |
| 1116 | assert!(result.is_error); |
| 1117 | assert!( |
| 1118 | result |
| 1119 | .message |
| 1120 | .unwrap() |
| 1121 | .contains("Network policy requires approval for acme.com") |
| 1122 | ); |
| 1123 | |
| 1124 | group.remote = Ok(RemoteRegistryOutcome::Denied("acme.com".to_string())); |
| 1125 | let result = list_skills(&mut group, Some("remote")); |
| 1126 | assert!(result.is_error); |
| 1127 | assert!( |
| 1128 | result |
| 1129 | .message |
| 1130 | .unwrap() |
| 1131 | .contains("Network policy denied access to acme.com") |
| 1132 | ); |
| 1133 | |
| 1134 | group.remote = Err("Failed to fetch registry: boom".to_string()); |
| 1135 | let result = list_skills(&mut group, Some("--remote")); |
| 1136 | assert!(result.is_error); |
| 1137 | assert_eq!( |
| 1138 | result.message.unwrap(), |
| 1139 | "Error: Failed to fetch registry: boom" |
| 1140 | ); |
| 1141 | } |
| 1142 | |
| 1143 | #[test] |
| 1144 | fn skills_suggest_renders_recommendations() { |
| 1145 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1146 | let result = list_skills(&mut group, Some("suggest demo")); |
| 1147 | let msg = result.message.expect("expected message"); |
| 1148 | assert!(msg.contains("Suggested remote skills for `demo`:"), "{msg}"); |
| 1149 | assert!(msg.contains(" remote-demo — Remote demo")); |
| 1150 | assert!(msg.contains(" Why: demo")); |
| 1151 | assert!(msg.contains(" Install if you want it: /skill install remote-demo")); |
| 1152 | assert!(msg.contains("\nNothing was installed, trusted, or enabled.")); |
| 1153 | } |
| 1154 | |
| 1155 | #[test] |
| 1156 | fn skills_sync_renders_per_skill_report() { |
| 1157 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1158 | let result = list_skills(&mut group, Some("sync")); |
| 1159 | let msg = result.message.expect("expected message"); |
| 1160 | assert!(msg.starts_with("Registry sync complete.\n"), "{msg}"); |
| 1161 | assert!(msg.contains(" [+] demo — downloaded to /cache/demo")); |
| 1162 | assert!(msg.contains("\n1 skill(s) processed: 1 downloaded, 0 up-to-date, 0 failed.")); |
| 1163 | |
| 1164 | group.sync = Ok(SkillSyncOutcome::RegistryNeedsApproval( |
| 1165 | "acme.com".to_string(), |
| 1166 | )); |
| 1167 | let result = list_skills(&mut group, Some("sync")); |
| 1168 | assert!(result.is_error); |
| 1169 | assert!( |
| 1170 | result |
| 1171 | .message |
| 1172 | .unwrap() |
| 1173 | .contains("requires approval for acme.com") |
| 1174 | ); |
| 1175 | } |
| 1176 | |
| 1177 | // ── /skill parity ───────────────────────────────────────────────────── |
| 1178 | |
| 1179 | #[test] |
| 1180 | fn skill_without_arg_prints_usage() { |
| 1181 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1182 | let mut skills = FakeSkills { refreshed: false }; |
| 1183 | let result = run_skill(&mut group, &mut skills, None); |
| 1184 | assert!(result.is_error); |
| 1185 | assert!(result.message.unwrap().contains("Usage: /skill <name>")); |
| 1186 | } |
| 1187 | |
| 1188 | #[test] |
| 1189 | fn skill_activation_success_composes_message_and_task_action() { |
| 1190 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1191 | let mut skills = FakeSkills { refreshed: false }; |
| 1192 | let result = run_skill(&mut group, &mut skills, Some("demo")); |
| 1193 | assert!(!result.is_error); |
| 1194 | let msg = result.message.expect("expected message"); |
| 1195 | assert!( |
| 1196 | msg.starts_with("Skill 'demo' activated.\n\nDescription: Demo skill"), |
| 1197 | "{msg}" |
| 1198 | ); |
| 1199 | assert!(result.action.is_none()); |
| 1200 | |
| 1201 | let result = run_skill(&mut group, &mut skills, Some("demo do the thing")); |
| 1202 | assert!( |
| 1203 | matches!(result.action, Some(AppAction::SendMessage(ref t)) if t == "do the thing") |
| 1204 | ); |
| 1205 | } |
| 1206 | |
| 1207 | #[test] |
| 1208 | fn skill_new_aliases_skill_creator_in_not_found_message() { |
| 1209 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1210 | group.activation = Err(SkillActivationError::NotFound { |
| 1211 | requested: "skill-creator".to_string(), |
| 1212 | available: vec!["demo".to_string()], |
| 1213 | warnings: vec![], |
| 1214 | }); |
| 1215 | let mut skills = FakeSkills { refreshed: false }; |
| 1216 | let result = run_skill(&mut group, &mut skills, Some("new")); |
| 1217 | assert!(result.is_error); |
| 1218 | assert!( |
| 1219 | result |
| 1220 | .message |
| 1221 | .unwrap() |
| 1222 | .contains("Skill 'skill-creator' not found.") |
| 1223 | ); |
| 1224 | } |
| 1225 | |
| 1226 | #[test] |
| 1227 | fn skill_not_found_lists_available_and_warnings() { |
| 1228 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1229 | group.activation = Err(SkillActivationError::NotFound { |
| 1230 | requested: "missing".to_string(), |
| 1231 | available: vec!["demo".to_string()], |
| 1232 | warnings: vec!["one warning".to_string()], |
| 1233 | }); |
| 1234 | let mut skills = FakeSkills { refreshed: false }; |
| 1235 | let result = run_skill(&mut group, &mut skills, Some("missing")); |
| 1236 | assert!(result.is_error); |
| 1237 | let msg = result.message.unwrap(); |
| 1238 | assert!(msg.contains("Skill 'missing' not found."), "{msg}"); |
| 1239 | assert!(msg.contains("Available skills: demo"), "{msg}"); |
| 1240 | assert!(msg.contains("Warnings (1):"), "{msg}"); |
| 1241 | assert!(msg.contains(" - one warning"), "{msg}"); |
| 1242 | } |
| 1243 | |
| 1244 | #[test] |
| 1245 | fn skill_not_found_with_no_skills_uses_install_hint() { |
| 1246 | let mut group = FakeSkillGroup::new(vec![]); |
| 1247 | group.activation = Err(SkillActivationError::NotFound { |
| 1248 | requested: "missing".to_string(), |
| 1249 | available: vec![], |
| 1250 | warnings: vec![], |
| 1251 | }); |
| 1252 | let mut skills = FakeSkills { refreshed: false }; |
| 1253 | let result = run_skill(&mut group, &mut skills, Some("missing")); |
| 1254 | assert!(result.is_error); |
| 1255 | assert!( |
| 1256 | result |
| 1257 | .message |
| 1258 | .unwrap() |
| 1259 | .contains("No skills installed.\n\nUse /skills to see how to add skills.") |
| 1260 | ); |
| 1261 | } |
| 1262 | |
| 1263 | #[test] |
| 1264 | fn skill_invocation_rejected_is_honest_and_preserves_plugin_denial() { |
| 1265 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1266 | group.activation = Err(SkillActivationError::InvocationRejected { |
| 1267 | name: "demo".into(), |
| 1268 | reason: "frontmatter does not allow user invocation".into(), |
| 1269 | }); |
| 1270 | let mut skills = FakeSkills { refreshed: false }; |
| 1271 | let result = run_skill(&mut group, &mut skills, Some("demo")); |
| 1272 | assert!(result.is_error); |
| 1273 | assert_eq!( |
| 1274 | result.message.as_deref(), |
| 1275 | Some( |
| 1276 | "Error: Skill 'demo' could not be activated: frontmatter does not allow user invocation" |
| 1277 | ) |
| 1278 | ); |
| 1279 | } |
| 1280 | |
| 1281 | #[test] |
| 1282 | fn skill_plugin_rejected_renders_exact_error() { |
| 1283 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1284 | group.activation = Err(SkillActivationError::PluginRejected { |
| 1285 | name: "plug".to_string(), |
| 1286 | reason: "authority revoked".to_string(), |
| 1287 | }); |
| 1288 | let mut skills = FakeSkills { refreshed: false }; |
| 1289 | let result = run_skill(&mut group, &mut skills, Some("plug")); |
| 1290 | assert!(result.is_error); |
| 1291 | assert_eq!( |
| 1292 | result.message.unwrap(), |
| 1293 | "Error: Plugin skill 'plug' is no longer active: authority revoked" |
| 1294 | ); |
| 1295 | } |
| 1296 | |
| 1297 | #[test] |
| 1298 | fn try_activate_skill_portable_returns_none_on_not_found_and_activates_with_task() { |
| 1299 | let mut missing = FakeSkillGroup::new(vec![]); |
| 1300 | missing.activation = Err(SkillActivationError::NotFound { |
| 1301 | requested: "nope".to_string(), |
| 1302 | available: vec![], |
| 1303 | warnings: vec![], |
| 1304 | }); |
| 1305 | assert!(try_activate_skill_portable(&mut missing, "nope", None).is_none()); |
| 1306 | |
| 1307 | let mut present = FakeSkillGroup::new(vec![demo_entry()]); |
| 1308 | let result = try_activate_skill_portable(&mut present, "new", Some("ship it")) |
| 1309 | .expect("known skill activates"); |
| 1310 | assert!(!result.is_error); |
| 1311 | assert_eq!(present.activated.as_deref(), Some("skill-creator")); |
| 1312 | assert!(matches!( |
| 1313 | result.action, |
| 1314 | Some(AppAction::SendMessage(ref msg)) if msg == "ship it" |
| 1315 | )); |
| 1316 | } |
| 1317 | |
| 1318 | #[test] |
| 1319 | fn skill_install_receipt_refreshes_cache_exactly_once() { |
| 1320 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1321 | let mut skills = CountingSkills::default(); |
| 1322 | let result = run_skill(&mut group, &mut skills, Some("install github:acme/demo")); |
| 1323 | assert!(!result.is_error); |
| 1324 | assert!( |
| 1325 | result |
| 1326 | .message |
| 1327 | .unwrap() |
| 1328 | .starts_with("Installed skill 'demo'.\nLocation: /ws/.codewhale/skills/demo"), |
| 1329 | ); |
| 1330 | assert_eq!( |
| 1331 | skills.refresh_count, 1, |
| 1332 | "Installed receipt must refresh the skill cache exactly once" |
| 1333 | ); |
| 1334 | } |
| 1335 | |
| 1336 | #[test] |
| 1337 | fn skill_update_and_uninstall_refresh_cache_exactly_once_each() { |
| 1338 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1339 | let mut skills = CountingSkills::default(); |
| 1340 | let result = run_skill(&mut group, &mut skills, Some("update demo")); |
| 1341 | assert!(!result.is_error); |
| 1342 | assert_eq!(skills.refresh_count, 1, "update refresh count"); |
| 1343 | |
| 1344 | skills.refresh_count = 0; |
| 1345 | let result = run_skill(&mut group, &mut skills, Some("uninstall --global demo")); |
| 1346 | assert!(!result.is_error); |
| 1347 | assert_eq!(skills.refresh_count, 1, "uninstall refresh count"); |
| 1348 | assert!(result.message.unwrap().contains("Removed skill 'demo'.")); |
| 1349 | } |
| 1350 | |
| 1351 | #[test] |
| 1352 | fn skill_trust_does_not_refresh_cache() { |
| 1353 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1354 | let mut skills = CountingSkills::default(); |
| 1355 | let result = run_skill(&mut group, &mut skills, Some("trust demo")); |
| 1356 | assert!(!result.is_error); |
| 1357 | assert_eq!(skills.refresh_count, 0, "trust must not refresh the cache"); |
| 1358 | assert!( |
| 1359 | result |
| 1360 | .message |
| 1361 | .unwrap() |
| 1362 | .contains("Marked skill 'demo' as trusted.") |
| 1363 | ); |
| 1364 | } |
| 1365 | |
| 1366 | #[test] |
| 1367 | fn skill_install_empty_spec_prints_usage() { |
| 1368 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1369 | let mut skills = FakeSkills { refreshed: false }; |
| 1370 | let result = run_skill(&mut group, &mut skills, Some("install")); |
| 1371 | assert!(result.is_error); |
| 1372 | assert!(result.message.unwrap().contains("Usage: /skill install")); |
| 1373 | } |
| 1374 | |
| 1375 | #[test] |
| 1376 | fn skill_scope_conflict_errors() { |
| 1377 | let mut group = FakeSkillGroup::new(vec![demo_entry()]); |
| 1378 | let mut skills = FakeSkills { refreshed: false }; |
| 1379 | let result = run_skill( |
| 1380 | &mut group, |
| 1381 | &mut skills, |
| 1382 | Some("install --project --global x"), |
| 1383 | ); |
| 1384 | assert!(result.is_error); |
| 1385 | assert!( |
| 1386 | result |
| 1387 | .message |
| 1388 | .unwrap() |
| 1389 | .contains("specify at most one of --project / --global") |
| 1390 | ); |
| 1391 | } |
| 1392 | |
| 1393 | #[test] |
| 1394 | fn skill_missing_facet_errors_are_safe() { |
| 1395 | let result = skills_contextual(CommandContexts::empty(), Some("demo")); |
| 1396 | assert!(result.is_error); |
| 1397 | assert_eq!( |
| 1398 | result.message.unwrap(), |
| 1399 | "Error: Command capability unavailable: skill_group" |
| 1400 | ); |
| 1401 | } |
| 1402 | } |
| 1403 |