返回 CodeWhale
skill.rs
根目录 / crates / engine / src / tools / skill.rs
1 //! `load_skill` tool — fetch a `SKILL.md` body and its companion-file
2 //! list into the model's context (#434).
3 //!
4 //! `load_skill name=<id>` is the canonical progressive-disclosure path. It
5 //! performs a name-based host lookup, so native global skills work without
6 //! widening the model's workspace file authority, and it enumerates companion
7 //! files without a separate `list_dir`. Reviewed plugin skills are exposed
8 //! only through this tool's content-bound in-memory snapshot; their mutable
9 //! source paths and companion files are deliberately not returned.
10
11 use std::cmp::Reverse;
12 use std::collections::{BTreeMap, HashSet};
13
14 use async_trait::async_trait;
15 use serde_json::{Value, json};
16
17 use codewhale_skills::{
18 Skill, SkillCatalogGroup, SkillDiscoveryMode, SkillListingConfig, SkillRootCatalog,
19 SkillSource, discover_for_workspace, skill_directories_for_workspace_and_dir,
20 skill_root_catalog_for_workspace, skills_directories_for_mode,
21 };
22
23 use super::spec::{
24 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
25 };
26
27 const MAX_QUERY_RESULTS: usize = 25;
28 const MAX_UNKNOWN_SKILL_HINTS: usize = 20;
29
30 pub(crate) fn spawn_skill_task<T: Send + 'static>(
31 task: impl FnOnce() -> T + Send + 'static,
32 ) -> tokio::task::JoinHandle<T> {
33 let policy = codewhale_plugins::activation::extension_host_policy_enabled();
34 #[cfg(any(test, feature = "test-support"))]
35 let env_ticket = crate::test_support::env_scope_ticket();
36 #[cfg(any(test, feature = "test-support"))]
37 let test_manager = crate::extension_host::TestManagerGuard::current();
38 tokio::task::spawn_blocking(move || {
39 let _policy_scope = codewhale_plugins::activation::PolicyScope::propagate(policy);
40 #[cfg(any(test, feature = "test-support"))]
41 let _membership = crate::test_support::join_env_scope(env_ticket);
42 #[cfg(any(test, feature = "test-support"))]
43 let _test_manager = test_manager.map(crate::extension_host::TestManagerGuard::install);
44 task()
45 })
46 }
47
48 pub(super) async fn implicit_skill_read(
49 path: &std::path::Path,
50 context: &ToolContext,
51 ) -> Option<String> {
52 if path.file_name().is_none_or(|name| name != "SKILL.md") {
53 return None;
54 }
55 let path = path.to_path_buf();
56 let context = context.clone();
57 spawn_skill_task(move || {
58 let registry = discover_for_workspace(
59 &context.workspace,
60 context.skills_dir.as_deref(),
61 &context.skills_config,
62 context.plugin_registry.as_deref(),
63 )
64 .into_enabled();
65 registry
66 .list()
67 .iter()
68 .find(|skill| {
69 matches!(skill.source, SkillSource::Native)
70 && skill.invocation.model_invocable()
71 && (skill.path == path
72 || std::fs::canonicalize(&skill.path)
73 .is_ok_and(|registered| registered == path))
74 })
75 .map(|skill| skill.name.clone())
76 })
77 .await
78 .ok()
79 .flatten()
80 }
81
82 pub struct LoadSkillTool;
83
84 #[async_trait]
85 impl ToolSpec for LoadSkillTool {
86 fn name(&self) -> &'static str {
87 "load_skill"
88 }
89
90 fn description(&self) -> &'static str {
91 "Load a named skill's SKILL.md body and companion file list into this turn. There is \
92 no skills index in the prompt: pass query=\"...\" to search names, aliases, and descriptions, \
93 or name=\"list\" for project and Codewhale skills. Use include_external=true to list \
94 global compatible skills too. Load the matching skill by name before \
95 starting that work. Resolves global and plugin skills that `read` cannot reach."
96 }
97
98 fn input_schema(&self) -> Value {
99 json!({
100 "type": "object",
101 "properties": {
102 "name": {
103 "type": "string",
104 "description": "Skill id to load. Omit or pass \"list\" for the compact catalogue, or \"list-all\" to include global compatible skills."
105 },
106 "query": {
107 "type": "string",
108 "description": "Words matched against skill names, aliases, and descriptions, including global compatible skills."
109 },
110 "include_external": {
111 "type": "boolean",
112 "description": "Include individual global compatible skills in the list instead of only their counts."
113 }
114 },
115 "additionalProperties": false
116 })
117 }
118
119 fn capabilities(&self) -> Vec<ToolCapability> {
120 vec![ToolCapability::ReadOnly]
121 }
122
123 fn approval_requirement(&self) -> ApprovalRequirement {
124 ApprovalRequirement::Auto
125 }
126
127 fn supports_parallel(&self) -> bool {
128 true
129 }
130
131 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
132 let context = context.clone();
133 spawn_skill_task(move || Self::execute_sync(input, &context))
134 .await
135 .map_err(|error| {
136 ToolError::execution_failed(format!("load skill task failed: {error}"))
137 })?
138 }
139 }
140
141 impl LoadSkillTool {
142 fn execute_sync(input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
143 let name = input
144 .get("name")
145 .and_then(Value::as_str)
146 .unwrap_or("")
147 .trim();
148
149 let discovery_mode =
150 codewhale_skills::SkillDiscoveryMode::from_config(&context.skills_config);
151 let registry = discover_for_workspace(
152 &context.workspace,
153 context.skills_dir.as_deref(),
154 &context.skills_config,
155 context.plugin_registry.as_deref(),
156 )
157 .into_enabled();
158
159 let raw_query = input
160 .get("query")
161 .and_then(Value::as_str)
162 .unwrap_or("")
163 .trim();
164 let include_external = input
165 .get("include_external")
166 .and_then(Value::as_bool)
167 .unwrap_or(false);
168 let list_all_alias = name.eq_ignore_ascii_case("list-all") && registry.get(name).is_none();
169 let is_list_request = name.is_empty() || name == "*" || name == "list" || list_all_alias;
170
171 if !raw_query.is_empty() || is_list_request {
172 let (catalog, home) = skill_root_catalog_for_workspace(
173 &context.workspace,
174 context.skills_dir.as_deref(),
175 &context.skills_config,
176 );
177 let all: Vec<&Skill> = registry
178 .list()
179 .iter()
180 .filter(|skill| skill.invocation.model_invocable())
181 .collect();
182 let description_cap =
183 SkillListingConfig::from_config(&context.skills_config).max_description_chars();
184 if !raw_query.is_empty() {
185 return Ok(ToolResult::success(render_query_results(
186 raw_query,
187 &all,
188 &catalog,
189 &context.workspace,
190 home.as_deref(),
191 description_cap,
192 )));
193 }
194 return Ok(ToolResult::success(render_skill_listing(
195 &all,
196 &catalog,
197 &context.workspace,
198 home.as_deref(),
199 include_external || list_all_alias,
200 description_cap,
201 )));
202 }
203
204 let Some(skill) = registry.get(name) else {
205 let (catalog, home) = skill_root_catalog_for_workspace(
206 &context.workspace,
207 context.skills_dir.as_deref(),
208 &context.skills_config,
209 );
210 let available: Vec<&Skill> = registry
211 .list()
212 .iter()
213 .filter(|s| s.invocation.model_invocable())
214 .collect();
215 let hint = if available.is_empty() {
216 let dirs: Vec<String> = context
217 .skills_dir
218 .as_deref()
219 .map(|skills_dir| {
220 skill_directories_for_workspace_and_dir(
221 &context.workspace,
222 skills_dir,
223 discovery_mode,
224 )
225 })
226 .unwrap_or_else(|| {
227 skills_directories_for_mode(&context.workspace, discovery_mode)
228 })
229 .iter()
230 .map(|p| p.display().to_string())
231 .collect();
232 if dirs.is_empty() {
233 if discovery_mode == SkillDiscoveryMode::CodeWhaleOnly {
234 "no skills directories found; install skills under `<workspace>/.codewhale/skills/<name>/SKILL.md` or `~/.codewhale/skills/<name>/SKILL.md`"
235 .to_string()
236 } else {
237 "no skills directories found; install skills under `<workspace>/.agents/skills/<name>/SKILL.md`, `~/.codewhale/skills/<name>/SKILL.md`, or `~/.deepseek/skills/<name>/SKILL.md`"
238 .to_string()
239 }
240 } else {
241 format!("no skills installed. Searched: {}", dirs.join(", "))
242 }
243 } else {
244 format_unknown_skill_hint(
245 name,
246 &available,
247 &catalog,
248 &context.workspace,
249 home.as_deref(),
250 )
251 };
252 return Err(ToolError::execution_failed(hint));
253 };
254
255 if !skill.invocation.model_invocable() {
256 return Err(ToolError::execution_failed(format!(
257 "Skill `{}` does not allow model invocation; ask the user to invoke an enabled skill explicitly",
258 skill.name
259 )));
260 }
261 ensure_loadable_skill(
262 skill,
263 &context.workspace,
264 context.plugin_registry.as_deref(),
265 )?;
266 let mut body = format_skill_body(skill);
267 if skill.name == "forget"
268 && context.memory_path.is_none()
269 && codewhale_runtime::config::owned_skills_dir().is_some_and(|owned| {
270 codewhale_skills::is_bundled_copy(&skill.path, &skill.name, &owned)
271 })
272 {
273 body = format!(
274 "Note: Persistent user memory is currently disabled in this session (`[memory] enabled = true` or `backend = \"native\"` in `config.toml` enables `remember` and `memory_search`; an explicit `backend` overrides `enabled`). Do not direct the user to nonexistent Context Lens tools or claim a stored memory was deleted.\n\n{body}"
275 );
276 }
277 let (skill_path, skill_source) = match &skill.source {
278 SkillSource::Native => (Some(skill.path.display().to_string()), "native".to_string()),
279 SkillSource::Plugin {
280 plugin_id,
281 plugin_name,
282 ..
283 } => (
284 None,
285 format!("reviewed-plugin-snapshot:{plugin_name}:{plugin_id}"),
286 ),
287 };
288 Ok(ToolResult::success(body).with_metadata(json!({
289 "skill_name": skill.name,
290 "skill_path": skill_path,
291 "skill_source": skill_source,
292 "skill_invocation": "model",
293 "companion_files": collect_companion_files(skill)
294 .into_iter()
295 .map(|p| p.display().to_string())
296 .collect::<Vec<String>>(),
297 })))
298 }
299 }
300
301 fn format_skill_list_line(
302 skill: &Skill,
303 external_source: Option<&str>,
304 description_cap: usize,
305 ) -> String {
306 let description = codewhale_skills::compact_description(&skill.description, description_cap);
307 match (description.is_empty(), external_source) {
308 (true, None) => format!(" - {}\n", skill.name),
309 (true, Some(source)) => format!(" - {} ({source})\n", skill.name),
310 (false, None) => format!(" - {} — {description}\n", skill.name),
311 (false, Some(source)) => format!(" - {} — {description} ({source})\n", skill.name),
312 }
313 }
314
315 fn render_skill_listing(
316 skills: &[&Skill],
317 catalog: &SkillRootCatalog,
318 workspace: &std::path::Path,
319 home_dir: Option<&std::path::Path>,
320 include_external: bool,
321 description_cap: usize,
322 ) -> String {
323 if skills.is_empty() {
324 return "No skills installed.".to_string();
325 }
326 let mut primary: Vec<&Skill> = Vec::new();
327 let mut external: Vec<(&Skill, String)> = Vec::new();
328 for skill in skills {
329 match catalog.classify_skill(skill, workspace, home_dir) {
330 SkillCatalogGroup::Primary => primary.push(skill),
331 SkillCatalogGroup::External { source_label } => external.push((skill, source_label)),
332 }
333 }
334
335 let mut listing = String::new();
336 if !primary.is_empty() {
337 listing.push_str(&format!("Available skills ({}):\n", primary.len()));
338 for skill in &primary {
339 listing.push_str(&format_skill_list_line(skill, None, description_cap));
340 }
341 } else if !include_external {
342 listing.push_str("No project or Codewhale-native skills installed.\n");
343 }
344
345 if !external.is_empty() {
346 if !listing.is_empty() {
347 listing.push('\n');
348 }
349 if include_external {
350 listing.push_str(&format!("External harness skills ({}):\n", external.len()));
351 for (skill, source_label) in &external {
352 listing.push_str(&format_skill_list_line(
353 skill,
354 Some(source_label),
355 description_cap,
356 ));
357 }
358 } else {
359 let mut by_source: BTreeMap<&str, usize> = BTreeMap::new();
360 for (_, source_label) in &external {
361 *by_source.entry(source_label.as_str()).or_insert(0) += 1;
362 }
363 let summary = by_source
364 .into_iter()
365 .map(|(source, count)| format!("{source} ({count})"))
366 .collect::<Vec<_>>()
367 .join(", ");
368 listing.push_str(&format!(
369 "External harness skills ({} omitted from default list: {summary}).\n\
370 Use `load_skill` with `query=\"...\"` to search all skills, `name=\"list-all\"` (or `include_external=true`) to list external skills, or `name=\"<skill>\"` to load any skill directly.\n",
371 external.len()
372 ));
373 }
374 }
375
376 listing
377 }
378
379 fn tokenize_search_terms(text: &str) -> Vec<String> {
380 let mut seen = HashSet::new();
381 let mut tokens = Vec::new();
382 for part in text.split(|ch: char| !ch.is_alphanumeric()) {
383 if part.is_empty() {
384 continue;
385 }
386 let lower = part.to_lowercase();
387 if seen.insert(lower.clone()) {
388 tokens.push(lower);
389 }
390 }
391 if tokens.is_empty() {
392 let trimmed = text.trim().to_lowercase();
393 if !trimmed.is_empty() {
394 tokens.push(trimmed);
395 }
396 }
397 tokens
398 }
399
400 fn score_skill_query(
401 skill: &Skill,
402 query_lower: &str,
403 query_tokens: &[String],
404 ) -> Option<(usize, u32)> {
405 let name_lower = skill.name.to_lowercase();
406 let name_tokens: HashSet<String> = tokenize_search_terms(&name_lower).into_iter().collect();
407 let aliases_lower: Vec<String> = skill.aliases.iter().map(|a| a.to_lowercase()).collect();
408 let alias_tokens: HashSet<String> = aliases_lower
409 .iter()
410 .flat_map(|alias| tokenize_search_terms(alias))
411 .collect();
412 let desc_lower = skill.description.to_lowercase();
413 let localized_lower: Vec<String> = skill
414 .localized_descriptions
415 .values()
416 .map(|value| value.to_lowercase())
417 .collect();
418 let mut desc_tokens: HashSet<String> = tokenize_search_terms(&desc_lower).into_iter().collect();
419 for localized in &localized_lower {
420 desc_tokens.extend(tokenize_search_terms(localized));
421 }
422
423 let mut matched_tokens = 0usize;
424 let mut score = 0u32;
425 for token in query_tokens {
426 let token_score = if name_lower == *token {
427 100
428 } else if name_tokens.contains(token) {
429 60
430 } else if alias_tokens.contains(token) {
431 50
432 } else if name_lower.contains(token) {
433 40
434 } else if aliases_lower.iter().any(|alias| alias.contains(token)) {
435 30
436 } else if desc_tokens.contains(token) {
437 20
438 } else if desc_lower.contains(token)
439 || localized_lower.iter().any(|text| text.contains(token))
440 {
441 10
442 } else {
443 0
444 };
445 if token_score > 0 {
446 matched_tokens += 1;
447 score += token_score;
448 }
449 }
450 if matched_tokens == 0 {
451 return None;
452 }
453 if name_lower == query_lower {
454 score += 200;
455 } else if aliases_lower.iter().any(|alias| alias == query_lower) {
456 score += 150;
457 }
458 Some((matched_tokens, score))
459 }
460
461 fn render_query_results(
462 raw_query: &str,
463 skills: &[&Skill],
464 catalog: &SkillRootCatalog,
465 workspace: &std::path::Path,
466 home_dir: Option<&std::path::Path>,
467 description_cap: usize,
468 ) -> String {
469 let query_lower = raw_query.to_lowercase();
470 let query_tokens = tokenize_search_terms(raw_query);
471
472 let mut ranked: Vec<_> = skills
473 .iter()
474 .filter_map(|skill| {
475 let score = score_skill_query(skill, &query_lower, &query_tokens)?;
476 let (is_primary, external_source) =
477 match catalog.classify_skill(skill, workspace, home_dir) {
478 SkillCatalogGroup::Primary => (true, None),
479 SkillCatalogGroup::External { source_label } => (false, Some(source_label)),
480 };
481 Some((score, is_primary, *skill, external_source))
482 })
483 .collect();
484
485 if ranked.is_empty() {
486 return format!(
487 "No skill matches {query_lower:?}. Pass name=\"list\" for project/Codewhale skills or refine your query."
488 );
489 }
490
491 ranked.sort_by_key(|(score, primary, skill, _)| {
492 (Reverse(*score), Reverse(*primary), &skill.name)
493 });
494
495 let total_matches = ranked.len();
496 let shown = ranked
497 .into_iter()
498 .take(MAX_QUERY_RESULTS)
499 .collect::<Vec<_>>();
500 let mut listing = if total_matches > shown.len() {
501 format!(
502 "Skills matching {query_lower:?} (showing {} of {total_matches}):\n",
503 shown.len()
504 )
505 } else {
506 format!("Skills matching {query_lower:?} ({}):\n", shown.len())
507 };
508 for (_, _, skill, external_source) in &shown {
509 listing.push_str(&format_skill_list_line(
510 skill,
511 external_source.as_deref(),
512 description_cap,
513 ));
514 }
515 if total_matches > shown.len() {
516 listing.push_str(&format!(
517 " ... {} more match(es); refine `query` to narrow results.\n",
518 total_matches - shown.len()
519 ));
520 }
521 listing
522 }
523
524 fn format_unknown_skill_hint(
525 name: &str,
526 available: &[&Skill],
527 catalog: &SkillRootCatalog,
528 workspace: &std::path::Path,
529 home_dir: Option<&std::path::Path>,
530 ) -> String {
531 let mut primary: Vec<&str> = Vec::new();
532 let mut external: Vec<&str> = Vec::new();
533 for skill in available {
534 match catalog.classify_skill(skill, workspace, home_dir) {
535 SkillCatalogGroup::Primary => primary.push(skill.name.as_str()),
536 SkillCatalogGroup::External { .. } => external.push(skill.name.as_str()),
537 }
538 }
539 if !primary.is_empty() {
540 let mut shown = primary
541 .iter()
542 .take(MAX_UNKNOWN_SKILL_HINTS)
543 .copied()
544 .collect::<Vec<_>>()
545 .join(", ");
546 if primary.len() > MAX_UNKNOWN_SKILL_HINTS {
547 shown.push_str(&format!(
548 " (+{} more)",
549 primary.len() - MAX_UNKNOWN_SKILL_HINTS
550 ));
551 }
552 if external.is_empty() {
553 format!("skill `{name}` not found. Available: {shown}")
554 } else {
555 format!(
556 "skill `{name}` not found. Available: {shown} (plus {} external harness skill(s); use `load_skill` with `query=\"...\"` to search)",
557 external.len()
558 )
559 }
560 } else {
561 let mut shown = external
562 .iter()
563 .take(MAX_UNKNOWN_SKILL_HINTS)
564 .copied()
565 .collect::<Vec<_>>()
566 .join(", ");
567 if external.len() > MAX_UNKNOWN_SKILL_HINTS {
568 shown.push_str(&format!(
569 " (+{} more; use `load_skill` with `query=\"...\"`)",
570 external.len() - MAX_UNKNOWN_SKILL_HINTS
571 ));
572 }
573 format!("skill `{name}` not found. Available: {shown}")
574 }
575 }
576
577 /// A native registry entry whose SKILL.md vanished from disk after discovery
578 /// (deleted, or resolved under a wrong home directory) must fail loudly with
579 /// the exact path — never silently serve the stale cached body while the user
580 /// believes the skill loaded (§2.5).
581 fn ensure_native_skill_file_present(skill: &Skill) -> Result<(), ToolError> {
582 if !matches!(skill.source, SkillSource::Native) || skill.path.is_file() {
583 return Ok(());
584 }
585 let message = format!(
586 "Skill `{}` is registered at {} but that file no longer exists on disk, \
587 so the skill did not load. Restore the file, or fix the skills directory it \
588 came from (`skills_dir` in config.toml, `$CODEWHALE_HOME`, or the OS home) — \
589 the path above shows exactly where the runtime looked.",
590 skill.name,
591 skill.path.display()
592 );
593 codewhale_runtime::logging::warn(&message);
594 Err(ToolError::execution_failed(message))
595 }
596
597 #[cfg(test)]
598 fn ensure_reviewed_plugin_skill_is_current(
599 skill: &Skill,
600 workspace: &std::path::Path,
601 ) -> Result<(), ToolError> {
602 ensure_reviewed_plugin_skill_is_current_for(skill, workspace, None)
603 }
604 pub(crate) fn ensure_loadable_skill(
605 skill: &Skill,
606 workspace: &std::path::Path,
607 plugins: Option<&codewhale_plugins::PluginRegistry>,
608 ) -> Result<(), ToolError> {
609 ensure_reviewed_plugin_skill_is_current_for(skill, workspace, plugins)?;
610 ensure_native_skill_file_present(skill)
611 }
612
613 fn ensure_reviewed_plugin_skill_is_current_for(
614 skill: &Skill,
615 workspace: &std::path::Path,
616 plugins: Option<&codewhale_plugins::PluginRegistry>,
617 ) -> Result<(), ToolError> {
618 let Some(provenance) = skill.source.provenance() else {
619 return Ok(());
620 };
621 provenance.verify_for(workspace,plugins).map_err(|reason| ToolError::execution_failed(format!(
622 "Plugin skill `{}` was denied: {reason}. Reload and select the skill again before retrying", skill.name)))
623 }
624
625 /// Render the skill body the model will see. Includes the description
626 /// up top so a single tool result is self-contained. Companion-file paths
627 /// land at the bottom under a clearly-named heading so the model can
628 /// open them with `read` if they're relevant to the task.
629 pub(crate) fn format_skill_body(skill: &Skill) -> String {
630 let mut out = String::new();
631 out.push_str(&format!("# Skill: {}\n\n", skill.name));
632 if !skill.description.trim().is_empty() {
633 out.push_str(&format!("> {}\n\n", skill.description.trim()));
634 }
635 let invocation = match skill.invocation {
636 codewhale_skill_install::skill_parse::SkillInvocation::ModelAndUser => "model+user",
637 codewhale_skill_install::skill_parse::SkillInvocation::ExplicitOnly => "explicit-only",
638 codewhale_skill_install::skill_parse::SkillInvocation::ModelOnly => "model-only",
639 codewhale_skill_install::skill_parse::SkillInvocation::Disabled => "disabled",
640 };
641 out.push_str(&format!("Invocation: `{invocation}`\n"));
642 if !skill.aliases.is_empty() {
643 out.push_str(&format!("Aliases: `{}`\n", skill.aliases.join("`, `")));
644 }
645 if !skill.dependencies.mcp_servers.is_empty() {
646 out.push_str(&format!(
647 "MCP dependencies: `{}`\n",
648 skill.dependencies.mcp_servers.join("`, `")
649 ));
650 }
651 if !skill.dependencies.tools.is_empty() {
652 out.push_str(&format!(
653 "Tool dependencies: `{}`\n",
654 skill.dependencies.tools.join("`, `")
655 ));
656 }
657 out.push('\n');
658 match &skill.source {
659 SkillSource::Native => {
660 out.push_str(&format!("Source: `{}`\n", skill.path.display()));
661 if let Some(dir) = skill.path.parent() {
662 out.push_str(&format!(
663 "Base directory for this skill: `{}`\n",
664 dir.display()
665 ));
666 }
667 out.push('\n');
668 }
669 SkillSource::Plugin {
670 plugin_id,
671 plugin_name,
672 ..
673 } => out.push_str(&format!(
674 "Source: reviewed in-memory plugin snapshot `{plugin_name}` ({plugin_id})\n\n"
675 )),
676 }
677 out.push_str("## SKILL.md\n\n");
678 out.push_str(skill.body.trim());
679 out.push('\n');
680 let (companions, unlisted) = collect_companion_files_with_overflow(skill);
681 if !companions.is_empty() {
682 out.push_str("\n## Companion files\n\n");
683 out.push_str(
684 "Companion files in the skill directory. Open one with `read` (path=...) when the task requires it; a skill stored outside the workspace has to be read through `bash` instead.\n\n",
685 );
686 for path in &companions {
687 out.push_str(&format!("- `{}`\n", path.display()));
688 }
689 if unlisted > 0 {
690 out.push_str(&format!(
691 "\n{unlisted} more files not listed (limit {MAX_COMPANION_FILES} files, {MAX_COMPANION_FILES_PER_DIR} per directory).\n"
692 ));
693 }
694 }
695 out
696 }
697
698 const MAX_COMPANION_DEPTH: usize = 4;
699 const MAX_COMPANION_FILES: usize = 128;
700 const MAX_COMPANION_FILES_PER_DIR: usize = 32;
701
702 fn collect_companion_files_with_overflow(skill: &Skill) -> (Vec<std::path::PathBuf>, usize) {
703 if matches!(&skill.source, SkillSource::Plugin { .. }) {
704 return (Vec::new(), 0);
705 }
706 let Some(root) = skill.path.parent() else {
707 return (Vec::new(), 0);
708 };
709 let mut out = Vec::new();
710 let mut overflow = 0usize;
711 let mut queue = std::collections::VecDeque::new();
712 queue.push_back((root.to_path_buf(), 0usize));
713 while let Some((dir, depth)) = queue.pop_front() {
714 let Ok(rd) = std::fs::read_dir(&dir) else {
715 continue;
716 };
717 let mut children: Vec<std::fs::DirEntry> = rd.flatten().collect();
718 children.sort_by_key(|entry| entry.file_name());
719 let mut listed_here = 0usize;
720 for entry in children {
721 let name = entry.file_name();
722 let Some(name) = name.to_str() else {
723 continue;
724 };
725 if name.starts_with('.') {
726 continue;
727 }
728 let Ok(ft) = entry.file_type() else {
729 continue;
730 };
731 if ft.is_symlink() {
732 continue;
733 }
734 if ft.is_file() {
735 if depth == 0 && name == "SKILL.md" {
736 continue;
737 }
738 if out.len() < MAX_COMPANION_FILES && listed_here < MAX_COMPANION_FILES_PER_DIR {
739 out.push(entry.path());
740 listed_here += 1;
741 } else {
742 overflow += 1;
743 }
744 } else if ft.is_dir()
745 && depth < MAX_COMPANION_DEPTH
746 && name != "__pycache__"
747 && name != "node_modules"
748 {
749 queue.push_back((entry.path(), depth + 1));
750 }
751 }
752 }
753 out.sort();
754 (out, overflow)
755 }
756
757 fn collect_companion_files(skill: &Skill) -> Vec<std::path::PathBuf> {
758 collect_companion_files_with_overflow(skill).0
759 }
760
761 #[cfg(test)]
762 mod tests {
763 use super::*;
764 use codewhale_skills::SkillRegistry;
765 use std::fs;
766 use tempfile::tempdir;
767
768 fn write_skill(dir: &std::path::Path, name: &str, description: &str, body: &str) {
769 let skill_dir = dir.join(name);
770 fs::create_dir_all(&skill_dir).unwrap();
771 fs::write(
772 skill_dir.join("SKILL.md"),
773 format!("---\nname: {name}\ndescription: {description}\n---\n{body}\n"),
774 )
775 .unwrap();
776 }
777
778 #[tokio::test]
779 async fn model_reads_record_only_enabled_discovered_skill_documents() {
780 use crate::tools::file_tool::ReadTool;
781
782 let tmp = tempdir().unwrap();
783 let root = tmp.path().canonicalize().unwrap();
784 let _home = crate::test_support::SealedHome::at(&root.join("home"));
785 let workspace = root.join("workspace");
786 let skills = workspace.join(".codewhale/skills");
787 write_skill(&skills, "fixture-open", "Model skill", "Read the fixture");
788 write_skill(
789 &skills,
790 "fixture-disabled",
791 "Disabled skill",
792 "Do not activate",
793 );
794 write_skill(
795 &skills,
796 "fixture-closed",
797 "Explicit skill",
798 "Read when asked",
799 );
800 write_skill(
801 &workspace,
802 "fixture-ordinary",
803 "Ordinary document",
804 "No skill activation",
805 );
806 let policy = skills.join("fixture-closed/agents");
807 fs::create_dir(&policy).unwrap();
808 fs::write(
809 policy.join("openai.yaml"),
810 "policy:\n allow_implicit_invocation: false\n",
811 )
812 .unwrap();
813 codewhale_runtime::skill_state::SkillStateStore::load_default()
814 .unwrap()
815 .set_enabled("fixture-disabled", false)
816 .unwrap();
817 crate::test_support::trust_workspace(&workspace);
818 let workspace_context = |dir: &std::path::Path| {
819 ToolContext::new(dir).with_skills_config(
820 dir.join(".codewhale/skills"),
821 std::sync::Arc::new(codewhale_runtime::config::SkillsConfig {
822 scan_codewhale_only: Some(true),
823 ..Default::default()
824 }),
825 )
826 };
827 let context = workspace_context(&workspace);
828 let result = ReadTool
829 .execute(
830 json!({"path":".codewhale/skills/fixture-open/SKILL.md"}),
831 &context,
832 )
833 .await
834 .unwrap();
835 let metadata = result.metadata.unwrap();
836 assert_eq!(metadata["skill_invocation"], "implicit_read");
837 assert_eq!(metadata["skill_name"], "fixture-open");
838 for path in [
839 ".codewhale/skills/fixture-closed/SKILL.md",
840 ".codewhale/skills/fixture-disabled/SKILL.md",
841 "fixture-ordinary/SKILL.md",
842 ] {
843 let result = ReadTool
844 .execute(json!({"path":path}), &context)
845 .await
846 .unwrap();
847 assert!(result.metadata.unwrap().get("skill_invocation").is_none());
848 }
849 let empty = ReadTool
850 .execute(
851 json!({"path":".codewhale/skills/fixture-open/SKILL.md","limit":0}),
852 &context,
853 )
854 .await
855 .unwrap();
856 assert!(empty.metadata.unwrap().get("skill_invocation").is_none());
857 let case_peer = skills.join("Fixture-open");
858 match fs::create_dir(&case_peer) {
859 Ok(()) => {
860 let path = case_peer.join("SKILL.md");
861 fs::write(
862 &path,
863 "---\nname: case-peer\ndescription: Case peer\ndisable-model-invocation: true\n---\nExplicit body",
864 )
865 .unwrap();
866 assert!(implicit_skill_read(&path, &context).await.is_none());
867 }
868 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
869 Err(error) => panic!("create case-sensitive skill peer: {error}"),
870 }
871 #[cfg(unix)]
872 {
873 let alias = root.join("workspace-alias");
874 std::os::unix::fs::symlink(&workspace, &alias).unwrap();
875 let alias_context = workspace_context(&alias);
876 let path = skills.join("fixture-open/SKILL.md");
877 assert_eq!(
878 implicit_skill_read(&path, &alias_context).await.as_deref(),
879 Some("fixture-open")
880 );
881 }
882 }
883
884 #[test]
885 fn load_skill_returns_skill_body_with_description_header() {
886 let tmp = tempdir().unwrap();
887 write_skill(
888 tmp.path(),
889 "review-pr",
890 "Run a focused PR review",
891 "# Steps\n1. Read the diff.\n2. Comment.\n",
892 );
893 let skill = SkillRegistry::discover(tmp.path())
894 .get("review-pr")
895 .unwrap()
896 .clone();
897 let body = format_skill_body(&skill);
898 assert!(body.contains("# Skill: review-pr"));
899 assert!(body.contains("Run a focused PR review"));
900 assert!(body.contains("# Steps"));
901 assert!(body.contains("Read the diff."));
902 }
903
904 #[test]
905 fn collect_companion_files_lists_siblings_excluding_skill_md() {
906 let tmp = tempdir().unwrap();
907 let skill_dir = tmp.path().join("rich-skill");
908 fs::create_dir_all(skill_dir.join("references")).unwrap();
909 fs::create_dir_all(skill_dir.join(".hidden")).unwrap();
910 fs::write(
911 skill_dir.join("SKILL.md"),
912 "---\nname: rich-skill\ndescription: x\n---\nbody\n",
913 )
914 .unwrap();
915 fs::write(skill_dir.join("script.py"), "print('hi')").unwrap();
916 fs::write(skill_dir.join("data.json"), "{}").unwrap();
917 fs::write(skill_dir.join("references/guide.md"), "# guide").unwrap();
918 fs::write(skill_dir.join(".hidden/secret.txt"), "skip").unwrap();
919
920 let registry = SkillRegistry::discover(tmp.path());
921 let skill = registry.get("rich-skill").unwrap();
922 let files = collect_companion_files(skill);
923 let rels: Vec<String> = files
924 .iter()
925 .filter_map(|p| {
926 p.strip_prefix(&skill_dir)
927 .ok()
928 .map(|rel| rel.to_string_lossy().replace('\\', "/"))
929 })
930 .collect();
931 assert_eq!(
932 rels,
933 vec![
934 "data.json".to_string(),
935 "references/guide.md".to_string(),
936 "script.py".to_string(),
937 ]
938 );
939 }
940
941 #[test]
942 fn native_skill_with_vanished_file_fails_loudly_with_the_path() {
943 // §2.5: a registry entry pointing at a SKILL.md that no longer exists
944 // must surface the exact path instead of silently serving the stale
945 // cached body — this is the "delegate skill silently never loads"
946 // symptom class.
947 let tmp = tempdir().unwrap();
948 let missing = tmp.path().join("delegate").join("SKILL.md");
949 let skill = Skill {
950 legacy_activation_name: None,
951 name: "delegate".to_string(),
952 description: "delegate work".to_string(),
953 localized_descriptions: std::collections::HashMap::new(),
954 invocation: codewhale_skill_install::skill_parse::SkillInvocation::ModelAndUser,
955 dependencies: Default::default(),
956 aliases: Vec::new(),
957 argument_hint: None,
958 body: "cached body".to_string(),
959 path: missing.clone(),
960 source: SkillSource::Native,
961 };
962 let err = ensure_native_skill_file_present(&skill)
963 .expect_err("a vanished SKILL.md must fail loudly");
964 let message = err.to_string();
965 assert!(
966 message.contains(&missing.display().to_string()),
967 "error names the exact path: {message}"
968 );
969 assert!(
970 message.contains("did not load"),
971 "error says the skill did not load: {message}"
972 );
973
974 // An existing file passes, and plugin skills are untouched (their
975 // content-bound snapshot never consults the mutable path).
976 let present_dir = tempdir().unwrap();
977 let present = present_dir.path().join("SKILL.md");
978 fs::write(&present, "body").unwrap();
979 let mut on_disk = skill.clone();
980 on_disk.path = present;
981 ensure_native_skill_file_present(&on_disk).expect("present file loads");
982 let mut plugin = skill;
983 plugin.source = SkillSource::Plugin {
984 plugin_id: "workspace/1/demo".to_string(),
985 plugin_name: "demo".to_string(),
986 native_registration: None,
987 authority: Box::new(codewhale_config::PluginAuthority {
988 plugin_id: codewhale_config::PluginId("workspace/1/demo".to_string()),
989 plugin_name: "demo".to_string(),
990 workspace: tmp.path().to_path_buf(),
991 state_path: tmp.path().join("state.json"),
992 managed_policy_path: Some(tmp.path().join("managed-policy.json")),
993 managed_policy_source: Some(tmp.path().join("managed-policy.json")),
994 source_manifest: tmp.path().join("plugin.toml"),
995 staged_manifest: tmp.path().join("staged/plugin.toml"),
996 content_hash: "0".repeat(64),
997 capability_hash: "0".repeat(64),
998 state_generation: 0,
999 }),
1000 };
1001 ensure_native_skill_file_present(&plugin).expect("plugin snapshot skips the disk check");
1002 }
1003
1004 #[test]
1005 fn plugin_skill_body_uses_reviewed_snapshot_without_mutable_file_paths() {
1006 let tmp = tempdir().unwrap();
1007 let skill_path = tmp.path().join("SKILL.md");
1008 fs::write(&skill_path, "changed on disk").unwrap();
1009 fs::write(tmp.path().join("companion.txt"), "changed companion").unwrap();
1010 let skill = Skill {
1011 legacy_activation_name: None,
1012 name: "demo:hello".to_string(),
1013 description: "hello".to_string(),
1014 localized_descriptions: std::collections::HashMap::new(),
1015 invocation: codewhale_skill_install::skill_parse::SkillInvocation::ModelAndUser,
1016 dependencies: Default::default(),
1017 aliases: Vec::new(),
1018 argument_hint: None,
1019 body: "reviewed body".to_string(),
1020 path: skill_path.clone(),
1021 source: SkillSource::Plugin {
1022 plugin_id: "workspace/123/demo".to_string(),
1023 plugin_name: "demo".to_string(),
1024 native_registration: None,
1025 authority: Box::new(codewhale_config::PluginAuthority {
1026 plugin_id: codewhale_config::PluginId("workspace/123/demo".to_string()),
1027 plugin_name: "demo".to_string(),
1028 workspace: tmp.path().to_path_buf(),
1029 state_path: tmp.path().join("state.json"),
1030 managed_policy_path: Some(tmp.path().join("managed-policy.json")),
1031 managed_policy_source: Some(tmp.path().join("managed-policy.json")),
1032 source_manifest: tmp.path().join("plugin.toml"),
1033 staged_manifest: tmp.path().join("staged/plugin.toml"),
1034 content_hash: "0".repeat(64),
1035 capability_hash: "0".repeat(64),
1036 state_generation: 0,
1037 }),
1038 },
1039 };
1040
1041 let rendered = format_skill_body(&skill);
1042 assert!(rendered.contains("reviewed body"));
1043 assert!(rendered.contains("reviewed in-memory plugin snapshot"));
1044 assert!(!rendered.contains(&skill_path.display().to_string()));
1045 assert!(collect_companion_files(&skill).is_empty());
1046 }
1047
1048 #[test]
1049 fn plugin_skill_load_fails_closed_when_reviewed_bundle_drifts() {
1050 let _lock = crate::test_support::lock_test_env();
1051 let tmp = tempdir().unwrap();
1052 let home = tmp.path().join("home");
1053 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
1054 let bundle = tmp.path().join(".codewhale/plugins/demo");
1055 let skill_dir = bundle.join("skills/hello");
1056 fs::create_dir_all(&skill_dir).unwrap();
1057 fs::write(
1058 bundle.join("plugin.toml"),
1059 "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n",
1060 )
1061 .unwrap();
1062 fs::write(
1063 skill_dir.join("SKILL.md"),
1064 "---\nname: hello\ndescription: hello\n---\nreviewed body\n",
1065 )
1066 .unwrap();
1067 fs::write(skill_dir.join("companion.txt"), "reviewed companion").unwrap();
1068
1069 let discovery = codewhale_plugins::PluginDiscoveryContext::capture_pre_dotenv();
1070 let mut plugins = discovery.registry_for_workspace(tmp.path());
1071 std::sync::Arc::make_mut(&mut plugins)
1072 .trust("demo")
1073 .unwrap();
1074 std::sync::Arc::make_mut(&mut plugins)
1075 .enable("demo")
1076 .unwrap();
1077 let registry = codewhale_skills::discover_in_workspace_with_mode_and_plugins(
1078 tmp.path(),
1079 SkillDiscoveryMode::CodeWhaleOnly,
1080 Some(plugins.as_ref()),
1081 );
1082 let skill = registry.get("demo:hello").expect("active plugin skill");
1083 ensure_reviewed_plugin_skill_is_current(skill, tmp.path())
1084 .expect("stable reviewed snapshot");
1085
1086 fs::write(skill_dir.join("companion.txt"), "changed after review").unwrap();
1087 let error = ensure_reviewed_plugin_skill_is_current(skill, tmp.path())
1088 .expect_err("bundle drift must deny the reviewed skill snapshot");
1089 assert!(error.to_string().contains("changed after review"));
1090 }
1091
1092 #[test]
1093 fn collect_companion_files_returns_empty_for_solo_skill() {
1094 let tmp = tempdir().unwrap();
1095 write_skill(tmp.path(), "solo", "Just a skill", "body");
1096 let registry = SkillRegistry::discover(tmp.path());
1097 let skill = registry.get("solo").unwrap();
1098 assert!(collect_companion_files(skill).is_empty());
1099 }
1100
1101 #[test]
1102 fn format_skill_body_emits_companion_files_section_when_present() {
1103 let tmp = tempdir().unwrap();
1104 let skill_dir = tmp.path().join("skill-with-friends");
1105 fs::create_dir_all(&skill_dir).unwrap();
1106 fs::write(
1107 skill_dir.join("SKILL.md"),
1108 "---\nname: skill-with-friends\ndescription: x\n---\nbody\n",
1109 )
1110 .unwrap();
1111 fs::write(skill_dir.join("helper.sh"), "#!/bin/sh\necho hi").unwrap();
1112
1113 let registry = SkillRegistry::discover(tmp.path());
1114 let skill = registry.get("skill-with-friends").unwrap();
1115 let body = format_skill_body(skill);
1116 assert!(body.contains("## Companion files"));
1117 assert!(body.contains("helper.sh"));
1118 // Companion guidance names the model-visible tools only.
1119 assert!(body.contains("`read` (path=...)"), "{body}");
1120 assert!(body.contains("`bash`"), "{body}");
1121 assert!(
1122 !body.contains("File action=") && !body.contains("through Bash"),
1123 "{body}"
1124 );
1125 }
1126
1127 #[test]
1128 fn skill_list_line_keeps_localized_trigger_and_honours_cap() {
1129 let tmp = tempdir().unwrap();
1130 let summary = "Собирает подробный отчёт по результатам работы команды и оформляет его в виде структурированного документа с разделами и таблицами для руководства компании";
1131 let description = format!("{summary}. Триггеры: когда пользователь просит собрать отчёт");
1132 write_skill(tmp.path(), "report-skill", &description, "body");
1133 let registry = SkillRegistry::discover(tmp.path());
1134 let skill = registry.get("report-skill").unwrap();
1135
1136 let short = format_skill_list_line(skill, None, 120);
1137 assert!(
1138 short.contains("когда пользователь просит собрать отчёт"),
1139 "{short}"
1140 );
1141 assert!(short.contains('…'), "{short}");
1142 assert!(!short.contains("для руководства компании"), "{short}");
1143
1144 let full = format_skill_list_line(skill, None, 800);
1145 assert!(full.contains(&description), "{full}");
1146 assert!(!full.contains('…'), "{full}");
1147 }
1148
1149 #[test]
1150 fn format_skill_body_reports_companions_past_the_cap() {
1151 let tmp = tempdir().unwrap();
1152 write_skill(tmp.path(), "big-skill", "x", "body");
1153 let skill_dir = tmp.path().join("big-skill");
1154 fs::create_dir_all(skill_dir.join("assets")).unwrap();
1155 fs::create_dir_all(skill_dir.join("references")).unwrap();
1156 fs::create_dir_all(skill_dir.join("__pycache__")).unwrap();
1157 for i in 0..200 {
1158 fs::write(skill_dir.join(format!("assets/file-{i:03}.bin")), "x").unwrap();
1159 }
1160 fs::write(skill_dir.join("__pycache__/junk.pyc"), "x").unwrap();
1161 fs::write(skill_dir.join("references/guide.md"), "# guide").unwrap();
1162 fs::write(skill_dir.join("run.sh"), "echo").unwrap();
1163
1164 let registry = SkillRegistry::discover(tmp.path());
1165 let skill = registry.get("big-skill").unwrap();
1166 let body = format_skill_body(skill);
1167 assert!(body.contains("run.sh"), "{body}");
1168 let guide = std::path::Path::new("references").join("guide.md");
1169 assert!(body.contains(&*guide.to_string_lossy()), "{body}");
1170 assert!(!body.contains("junk.pyc"), "{body}");
1171 assert!(body.contains("more files not listed"), "{body}");
1172 let (listed, unlisted) = collect_companion_files_with_overflow(skill);
1173 assert!(listed.len() <= MAX_COMPANION_FILES);
1174 assert_eq!(listed.len() + unlisted, 202);
1175 }
1176
1177 #[test]
1178 fn format_skill_body_skips_companion_section_when_solo() {
1179 let tmp = tempdir().unwrap();
1180 write_skill(tmp.path(), "solo", "x", "body");
1181 let registry = SkillRegistry::discover(tmp.path());
1182 let skill = registry.get("solo").unwrap();
1183 let body = format_skill_body(skill);
1184 assert!(
1185 !body.contains("## Companion files"),
1186 "solo skills shouldn't emit an empty Companion files section"
1187 );
1188 }
1189
1190 #[tokio::test]
1191 async fn execute_lists_available_skills_for_empty_star_and_list_names() {
1192 let _lock = crate::test_support::lock_test_env();
1193 let tmp = tempdir().unwrap();
1194 // Pin home-based global skill roots to the tempdir so host skills
1195 // never leak into the listing count.
1196 let _home = crate::test_support::EnvVarGuard::set("HOME", tmp.path().join("home"));
1197 let _cw_home =
1198 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path().join("cw-home"));
1199 let workspace = tmp.path().to_path_buf();
1200 crate::test_support::trust_workspace(&workspace);
1201 let skills_dir = workspace.join(".codewhale").join("skills");
1202 write_skill(&skills_dir, "alpha-skill", "First demo skill", "Body A.");
1203 write_skill(&skills_dir, "beta-skill", "", "Body B.");
1204
1205 let context = ToolContext::new(workspace);
1206 let tool = LoadSkillTool;
1207
1208 // #4651: listing is an action inside the single load_skill tool —
1209 // empty name, "*", and "list" all enumerate the reviewed registry.
1210 for listing_name in [json!({}), json!({"name": "*"}), json!({"name": "list"})] {
1211 let result = tool
1212 .execute(listing_name.clone(), &context)
1213 .await
1214 .expect("listing should succeed");
1215 assert!(result.success);
1216 assert!(
1217 result.content.contains("Available skills (2)"),
1218 "listing for {listing_name} should count skills: {}",
1219 result.content
1220 );
1221 assert!(
1222 result.content.contains("alpha-skill — First demo skill"),
1223 "listing should include name and description: {}",
1224 result.content
1225 );
1226 assert!(
1227 result.content.contains("- beta-skill"),
1228 "listing should include description-less skills: {}",
1229 result.content
1230 );
1231 }
1232 }
1233
1234 #[tokio::test]
1235 async fn execute_listing_reports_empty_registry_plainly() {
1236 let _lock = crate::test_support::lock_test_env();
1237 let tmp = tempdir().unwrap();
1238 let _home = crate::test_support::EnvVarGuard::set("HOME", tmp.path().join("home"));
1239 let _cw_home =
1240 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path().join("cw-home"));
1241 let context = ToolContext::new(tmp.path().to_path_buf());
1242 let result = LoadSkillTool
1243 .execute(json!({"name": "list"}), &context)
1244 .await
1245 .expect("empty listing should still succeed");
1246 assert!(result.success);
1247 assert!(
1248 result.content.contains("No skills installed."),
1249 "{}",
1250 result.content
1251 );
1252 }
1253
1254 #[tokio::test]
1255 async fn execute_finds_skills_in_opencode_dir_via_workspace_discovery() {
1256 let tmp = tempdir().unwrap();
1257 let _home = crate::test_support::SealedHome::at(&tmp.path().join("home"));
1258 let workspace = tmp.path().to_path_buf();
1259 crate::test_support::trust_workspace(&workspace);
1260 // Skill installed under workspace `.opencode/skills` (#432).
1261 let opencode_dir = workspace.join(".opencode").join("skills");
1262 std::fs::create_dir_all(&opencode_dir).unwrap();
1263 write_skill(
1264 &opencode_dir,
1265 "from-opencode",
1266 "Skill installed under .opencode/skills",
1267 "Body content marker.",
1268 );
1269
1270 let context = ToolContext::new(workspace);
1271
1272 let tool = LoadSkillTool;
1273 let result = tool
1274 .execute(json!({"name": "from-opencode"}), &context)
1275 .await
1276 .expect("load_skill should succeed");
1277 assert!(result.success);
1278 assert!(
1279 result.content.contains("# Skill: from-opencode"),
1280 "body header missing: {}",
1281 result.content
1282 );
1283 assert!(result.content.contains("Body content marker."));
1284
1285 let metadata = result.metadata.expect("metadata stamped");
1286 assert_eq!(
1287 metadata
1288 .get("skill_name")
1289 .and_then(serde_json::Value::as_str),
1290 Some("from-opencode")
1291 );
1292 let path_str = metadata
1293 .get("skill_path")
1294 .and_then(serde_json::Value::as_str)
1295 .expect("skill_path stamped");
1296 assert!(
1297 path_str.contains(".opencode"),
1298 "skill_path should point at the .opencode dir: {path_str}"
1299 );
1300 }
1301
1302 #[tokio::test]
1303 async fn execute_respects_codewhale_only_skill_discovery() {
1304 let tmp = tempdir().unwrap();
1305 let _home = crate::test_support::SealedHome::at(&tmp.path().join("home"));
1306 let workspace = tmp.path().to_path_buf();
1307 crate::test_support::trust_workspace(&workspace);
1308 write_skill(
1309 &workspace.join(".claude").join("skills"),
1310 "claude-only",
1311 "Claude skill",
1312 "Body content marker.",
1313 );
1314 let codewhale_dir = workspace.join(".codewhale").join("skills");
1315 write_skill(
1316 &codewhale_dir,
1317 "codewhale-only",
1318 "CodeWhale skill",
1319 "Body content marker.",
1320 );
1321
1322 let context = ToolContext::new(workspace).with_skills_config(
1323 codewhale_dir,
1324 std::sync::Arc::new(codewhale_runtime::config::SkillsConfig {
1325 scan_codewhale_only: Some(true),
1326 ..Default::default()
1327 }),
1328 );
1329 let tool = LoadSkillTool;
1330
1331 let result = tool
1332 .execute(json!({"name": "codewhale-only"}), &context)
1333 .await
1334 .expect("CodeWhale skill should load");
1335 assert!(result.success);
1336
1337 let err = tool
1338 .execute(json!({"name": "claude-only"}), &context)
1339 .await
1340 .expect_err("Claude skill should be hidden in CodeWhale-only mode");
1341 let msg = err.to_string();
1342 assert!(
1343 msg.contains("claude-only") && msg.contains("codewhale-only"),
1344 "error should name the missing skill and available strict catalog: {msg}"
1345 );
1346 }
1347
1348 #[tokio::test]
1349 async fn execute_loads_configured_external_skill_without_workspace_trust() {
1350 let tmp = tempdir().unwrap();
1351 let workspace = tmp.path().join("workspace");
1352 let home = tmp.path().join("home");
1353 let global_skills = home.join(".codewhale/skills");
1354 fs::create_dir_all(&workspace).unwrap();
1355 write_skill(
1356 &global_skills,
1357 "global-helper",
1358 "Global helper",
1359 "Global body marker.",
1360 );
1361
1362 // Keep this test independent of the process-native home directory:
1363 // `codewhale_paths::user_home()` cannot be redirected reliably after process start
1364 // on Windows. The injected-home discovery test in `codewhale_skills::tests`
1365 // separately proves that ~/.codewhale/skills enters the default catalog.
1366 let context = ToolContext::new(&workspace)
1367 .with_skills_config(global_skills.clone(), Default::default());
1368 assert!(!context.trust_mode);
1369 assert!(
1370 context
1371 .resolve_path(
1372 global_skills
1373 .join("global-helper/SKILL.md")
1374 .to_str()
1375 .unwrap()
1376 )
1377 .is_err(),
1378 "ordinary file tools must retain the workspace boundary"
1379 );
1380
1381 let result = LoadSkillTool
1382 .execute(json!({"name": "global-helper"}), &context)
1383 .await
1384 .expect("load_skill host lookup should open a configured external skill root");
1385 assert!(result.success);
1386 assert!(result.content.contains("Global body marker."));
1387 }
1388
1389 #[tokio::test]
1390 async fn execute_returns_helpful_error_for_unknown_skill() {
1391 let tmp = tempdir().unwrap();
1392 let _home = crate::test_support::SealedHome::at(&tmp.path().join("home"));
1393 let workspace = tmp.path().to_path_buf();
1394 crate::test_support::trust_workspace(&workspace);
1395 // One real skill so the available list is non-empty.
1396 write_skill(
1397 &workspace.join(".agents").join("skills"),
1398 "real-one",
1399 "x",
1400 "body",
1401 );
1402
1403 let context = ToolContext::new(workspace);
1404 let tool = LoadSkillTool;
1405 let err = tool
1406 .execute(json!({"name": "imaginary"}), &context)
1407 .await
1408 .expect_err("unknown skill should error");
1409 let msg = err.to_string();
1410 assert!(
1411 msg.contains("imaginary") && msg.contains("real-one"),
1412 "error must name the missing skill and list available ones: {msg}"
1413 );
1414 }
1415 #[tokio::test]
1416 async fn model_load_and_listing_obey_independent_invocation_gates() {
1417 let tmp = tempfile::tempdir().unwrap();
1418 let _home = crate::test_support::SealedHome::at(&tmp.path().join("home"));
1419 let workspace = tmp.path().join("workspace");
1420 crate::test_support::trust_workspace(&workspace);
1421 let root = workspace.join(".codewhale/skills");
1422 for (name, policy) in [
1423 ("explicit", "disable-model-invocation: true"),
1424 (
1425 "disabled",
1426 "disable-model-invocation: true\nuser-invocable: false",
1427 ),
1428 ("model", "user-invocable: false"),
1429 ] {
1430 let dir = root.join(name);
1431 std::fs::create_dir_all(&dir).unwrap();
1432 std::fs::write(dir.join("SKILL.md"), format!("---\nname: {name}\ndescription: routing\n{policy}\n---\nsecret steps for {name}")).unwrap();
1433 }
1434 let context = ToolContext::new(&workspace).with_skills_config(
1435 &root,
1436 std::sync::Arc::new(codewhale_runtime::config::SkillsConfig {
1437 scan_codewhale_only: Some(true),
1438 ..Default::default()
1439 }),
1440 );
1441 let tool = LoadSkillTool;
1442 for name in ["explicit", "disabled"] {
1443 let error = tool
1444 .execute(json!({"name":name}), &context)
1445 .await
1446 .unwrap_err();
1447 assert!(
1448 error
1449 .to_string()
1450 .contains("does not allow model invocation")
1451 );
1452 }
1453 let listing = tool
1454 .execute(json!({"name":"list"}), &context)
1455 .await
1456 .unwrap();
1457 assert!(listing.content.contains("model"));
1458 assert!(!listing.content.contains(" - explicit"));
1459 assert!(!listing.content.contains(" - disabled"));
1460 let query = tool
1461 .execute(json!({"query":"explicit"}), &context)
1462 .await
1463 .unwrap();
1464 assert!(!query.content.contains("secret steps"));
1465 assert!(!query.content.contains(" - explicit"));
1466 assert!(
1467 tool.execute(json!({"name":"model"}), &context)
1468 .await
1469 .unwrap()
1470 .content
1471 .contains("secret steps for model")
1472 );
1473 }
1474
1475 #[tokio::test]
1476 async fn disabled_memory_note_is_added_only_to_the_bundled_forget_skill() {
1477 let _lock = crate::test_support::lock_test_env();
1478 for bundled in [true, false] {
1479 let tmp = tempdir().unwrap();
1480 let _home = crate::test_support::EnvVarGuard::set("HOME", tmp.path().join("home"));
1481 let _cw_home =
1482 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path().join("cw-home"));
1483 let owned = codewhale_runtime::config::owned_skills_dir().unwrap();
1484 if bundled {
1485 codewhale_skills::install_system_skills(&owned, &Default::default()).unwrap();
1486 } else {
1487 write_skill(&owned, "forget", "Forget a stash", "Drop the named stash.");
1488 }
1489 let workspace = tmp.path().join("workspace");
1490 fs::create_dir_all(&workspace).unwrap();
1491 let loaded = LoadSkillTool
1492 .execute(json!({"name": "forget"}), &ToolContext::new(workspace))
1493 .await
1494 .unwrap();
1495 assert_eq!(
1496 loaded
1497 .content
1498 .contains("Persistent user memory is currently disabled"),
1499 bundled,
1500 "{}",
1501 loaded.content
1502 );
1503 }
1504 }
1505
1506 #[test]
1507 fn native_starter_reports_its_installed_base_directory() {
1508 let tmp = tempdir().unwrap();
1509 codewhale_skills::install_system_skills(tmp.path(), &Default::default()).unwrap();
1510 let pack = tmp.path().join(".system");
1511 let registry = SkillRegistry::discover(&pack);
1512 let skill = registry.get("plugin-creator").unwrap();
1513 let rendered = format_skill_body(skill);
1514 assert!(rendered.contains(skill.body.trim()));
1515 assert!(rendered.contains(&format!(
1516 "Base directory for this skill: `{}`",
1517 skill.path.parent().unwrap().display()
1518 )));
1519 assert!(!rendered.contains("## Host notes"));
1520 }
1521
1522 #[tokio::test]
1523 async fn execute_list_omits_external_harness_skills_by_default_and_allows_direct_load() {
1524 let _lock = crate::test_support::lock_test_env();
1525 let tmp = tempdir().unwrap();
1526 let home = tmp.path().join("home");
1527 let cw_home = tmp.path().join("cw-home");
1528 let workspace = tmp.path().join("workspace");
1529 let _home = crate::test_support::EnvVarGuard::set("HOME", &home);
1530 let _cw_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &cw_home);
1531 fs::create_dir_all(&workspace).unwrap();
1532 crate::test_support::trust_workspace(&workspace);
1533
1534 let long_description = format!(
1535 "Deploy project release artifacts safely. {}",
1536 "Extra verbose detail. ".repeat(10)
1537 );
1538 write_skill(
1539 &workspace.join(".codewhale").join("skills"),
1540 "proj-deploy",
1541 &long_description,
1542 "Project body.",
1543 );
1544 write_skill(
1545 &cw_home.join("skills"),
1546 "cw-helper",
1547 "Codewhale native helper",
1548 "Native body.",
1549 );
1550 write_skill(
1551 &home.join(".claude").join("skills"),
1552 "claude-figma",
1553 "External Claude skill",
1554 "Claude external body.",
1555 );
1556 write_skill(
1557 &home.join(".agents").join("skills"),
1558 "agents-social",
1559 "External Agents skill",
1560 "Agents external body.",
1561 );
1562
1563 let context = ToolContext::new(workspace);
1564 let tool = LoadSkillTool;
1565 assert_eq!(
1566 tool.input_schema()["properties"]["include_external"]["type"],
1567 "boolean"
1568 );
1569
1570 let default_list = tool
1571 .execute(json!({"name": "list"}), &context)
1572 .await
1573 .expect("default list");
1574 assert!(default_list.success);
1575 assert!(default_list.content.contains("Available skills (2)"));
1576 assert!(default_list.content.contains("proj-deploy —"));
1577 assert!(
1578 default_list
1579 .content
1580 .contains("cw-helper — Codewhale native helper")
1581 );
1582 assert!(!default_list.content.contains(" - claude-figma"));
1583 assert!(!default_list.content.contains(" - agents-social"));
1584 assert!(
1585 default_list
1586 .content
1587 .contains("External harness skills (2 omitted")
1588 );
1589 assert!(default_list.content.contains("~/.claude/skills (1)"));
1590 assert!(default_list.content.contains("~/.agents/skills (1)"));
1591 assert!(default_list.content.contains("query="));
1592 assert!(default_list.content.contains("include_external=true"));
1593 let proj_line = default_list
1594 .content
1595 .lines()
1596 .find(|line| line.contains("proj-deploy"))
1597 .expect("proj-deploy line");
1598 assert!(proj_line.ends_with('…'), "{proj_line}");
1599
1600 let with_external = tool
1601 .execute(json!({"name": "list", "include_external": true}), &context)
1602 .await
1603 .expect("list with include_external");
1604 assert!(with_external.content.contains(" - claude-figma"));
1605 assert!(with_external.content.contains(" - agents-social"));
1606
1607 let list_all = tool
1608 .execute(json!({"name": "list-all"}), &context)
1609 .await
1610 .expect("list-all");
1611 assert!(list_all.content.contains(" - claude-figma"));
1612 assert!(list_all.content.contains(" - agents-social"));
1613
1614 let direct = tool
1615 .execute(json!({"name": "claude-figma"}), &context)
1616 .await
1617 .expect("direct load of external skill must still work");
1618 assert!(direct.content.contains("Claude external body."));
1619 }
1620
1621 #[tokio::test]
1622 async fn execute_query_ranks_multi_word_tokenized_matches() {
1623 let _lock = crate::test_support::lock_test_env();
1624 let tmp = tempdir().unwrap();
1625 let home = tmp.path().join("home");
1626 let cw_home = tmp.path().join("cw-home");
1627 let workspace = tmp.path().join("workspace");
1628 let _home = crate::test_support::EnvVarGuard::set("HOME", &home);
1629 let _cw_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &cw_home);
1630 fs::create_dir_all(&workspace).unwrap();
1631 crate::test_support::trust_workspace(&workspace);
1632
1633 let project_skills = workspace.join(".codewhale").join("skills");
1634 let gates_dir = project_skills.join("cw-gates");
1635 fs::create_dir_all(&gates_dir).unwrap();
1636 fs::write(
1637 gates_dir.join("SKILL.md"),
1638 "---\nname: cw-gates\ndescription: Verify Rust compilation, clippy, and test gates.\naliases-for: [build-checks]\n---\nGate steps.\n",
1639 )
1640 .unwrap();
1641 write_skill(
1642 &project_skills,
1643 "release-gates",
1644 "Final release build checklists and gates",
1645 "Release body.",
1646 );
1647 write_skill(
1648 &project_skills,
1649 "rust-tips",
1650 "General Rust ownership notes",
1651 "Tips body.",
1652 );
1653 write_skill(
1654 &project_skills,
1655 "moda-video",
1656 "Generate marketing videos",
1657 "Video body.",
1658 );
1659 write_skill(
1660 &home.join(".claude").join("skills"),
1661 "rust-build-runner",
1662 "Run rust build and gates in external harness",
1663 "External runner.",
1664 );
1665
1666 let context = ToolContext::new(workspace);
1667 let result = LoadSkillTool
1668 .execute(json!({"query": "rust build gates"}), &context)
1669 .await
1670 .expect("multi-word query");
1671 assert!(result.success);
1672 let content = &result.content;
1673 let gates_pos = content.find(" - cw-gates").expect("cw-gates matched");
1674 let ext_pos = content
1675 .find(" - rust-build-runner")
1676 .expect("external skill searchable via query");
1677 let partial_two_pos = content
1678 .find(" - release-gates")
1679 .expect("2-of-3 partial match included");
1680 let partial_one_pos = content
1681 .find(" - rust-tips")
1682 .expect("1-of-3 partial match included");
1683 assert!(gates_pos < partial_two_pos, "{content}");
1684 assert!(ext_pos < partial_two_pos, "{content}");
1685 assert!(partial_two_pos < partial_one_pos, "{content}");
1686 assert!(content.contains("(~/.claude/skills)"), "{content}");
1687 assert!(!content.contains("moda-video"), "{content}");
1688
1689 let punctuated = LoadSkillTool
1690 .execute(json!({"query": "rust/build, gates!"}), &context)
1691 .await
1692 .expect("punctuated multi-word query");
1693 assert!(punctuated.content.contains(" - cw-gates"));
1694
1695 let alias = LoadSkillTool
1696 .execute(json!({"query": "build-checks"}), &context)
1697 .await
1698 .expect("alias query");
1699 assert!(
1700 alias
1701 .content
1702 .lines()
1703 .nth(1)
1704 .unwrap()
1705 .contains(" - cw-gates")
1706 );
1707 }
1708 }
1709
1709 lines RUST