返回 CodeWhale
roots.rs
根目录 / crates / skills / src / roots.rs
1 //! Single source of truth for skill root enumeration, ownership, scope, and
2 //! runtime precedence.
3 //!
4 //! Runtime discovery and (later) audit/mutation share this catalog so
5 //! precedence cannot drift between modules. Discovery directories are not
6 //! write targets: only explicitly owned CodeWhale roots are writable.
7
8 use std::collections::HashSet;
9 use std::fs;
10 use std::path::{Path, PathBuf};
11
12 /// Stable identifier for a skill root within a catalog snapshot.
13 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
14 pub struct SkillRootId(String);
15
16 impl std::fmt::Display for SkillRootId {
17 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 f.write_str(&self.0)
19 }
20 }
21
22 /// External harness layouts that CodeWhale can discover/audit but never owns.
23 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24 pub enum CompatibleHarness {
25 Agents,
26 Claude,
27 Cursor,
28 OpenCode,
29 Codex,
30 DeepSeekLegacy,
31 /// Flat `<workspace>/skills` layout.
32 FlatProjectSkills,
33 }
34
35 impl CompatibleHarness {
36 #[must_use]
37 pub fn label(self) -> &'static str {
38 match self {
39 Self::Agents => "agents",
40 Self::Claude => "claude",
41 Self::Cursor => "cursor",
42 Self::OpenCode => "opencode",
43 Self::Codex => "codex",
44 Self::DeepSeekLegacy => "deepseek",
45 Self::FlatProjectSkills => "flat-skills",
46 }
47 }
48 }
49
50 /// Kind of skill root on disk (or logical source).
51 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52 pub enum SkillRootKind {
53 CodeWhaleProject,
54 CodeWhaleGlobal,
55 CompatibleProject(CompatibleHarness),
56 CompatibleGlobal(CompatibleHarness),
57 /// Explicitly configured `skills_dir` that is not one of the owned roots.
58 Configured,
59 BuiltIn,
60 ReviewedPluginSnapshot,
61 RegistryCache,
62 }
63
64 /// Whether CodeWhale may mutate files under this root.
65 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66 pub enum SkillRootAccess {
67 /// CodeWhale-owned project/global install targets.
68 WritableOwned,
69 /// Compatible harness roots and unclassified configured dirs — read only.
70 ReadOnlyExternal,
71 /// Built-in / reviewed plugin snapshot content.
72 Immutable,
73 /// Registry download cache — not an active install target.
74 CacheOnly,
75 }
76
77 /// Project vs global scope for owned and compatible roots.
78 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79 pub enum SkillScope {
80 Project,
81 Global,
82 /// Logical / non-filesystem sources (built-in, plugin snapshot, cache).
83 Logical,
84 }
85
86 /// One enumerated skill root with ownership and precedence metadata.
87 #[derive(Debug, Clone, PartialEq, Eq)]
88 pub struct SkillRootDescriptor {
89 pub id: SkillRootId,
90 pub kind: SkillRootKind,
91 pub access: SkillRootAccess,
92 pub scope: SkillScope,
93 pub path: PathBuf,
94 pub canonical_path: Option<PathBuf>,
95 /// Lower value = higher precedence for first-wins runtime merge.
96 pub precedence: Option<usize>,
97 /// When true, runtime skill discovery includes this root.
98 pub active_for_runtime: bool,
99 /// When true, owned-only / compatible audit may include this root.
100 pub active_for_audit: bool,
101 }
102
103 impl SkillRootDescriptor {
104 #[must_use]
105 pub fn is_writable_owned(&self) -> bool {
106 self.access == SkillRootAccess::WritableOwned
107 }
108 }
109
110 #[derive(Debug, Clone, PartialEq, Eq)]
111 pub enum SkillCatalogGroup {
112 Primary,
113 External { source_label: String },
114 }
115
116 /// Catalog of skill roots for a workspace (+ optional HOME override for tests).
117 #[derive(Debug, Clone, PartialEq, Eq)]
118 pub struct SkillRootCatalog {
119 roots: Vec<SkillRootDescriptor>,
120 }
121
122 impl SkillRootCatalog {
123 /// Build the full catalog: owned + compatible (including Codex audit-only)
124 /// plus optional configured dir and logical sources.
125 #[must_use]
126 pub fn build(
127 workspace: &Path,
128 home_dir: Option<&Path>,
129 configured_skills_dir: Option<&Path>,
130 ) -> Self {
131 let mut roots = Vec::new();
132 let mut precedence = 0usize;
133
134 // Codewhale-owned roots win within each scope: installing or
135 // updating a skill must change the copy runtime discovery selects.
136 push_descriptor(
137 &mut roots,
138 &mut precedence,
139 SkillRootKind::CodeWhaleProject,
140 SkillRootAccess::WritableOwned,
141 SkillScope::Project,
142 workspace.join(".codewhale/skills"),
143 true,
144 true,
145 "project-codewhale",
146 true,
147 );
148 for (harness, directory, id) in [
149 (CompatibleHarness::Agents, ".agents", "project-agents"),
150 (CompatibleHarness::Claude, ".claude", "project-claude"),
151 (CompatibleHarness::OpenCode, ".opencode", "project-opencode"),
152 (CompatibleHarness::Cursor, ".cursor", "project-cursor"),
153 ] {
154 push_existing(
155 &mut roots,
156 &mut precedence,
157 SkillRootKind::CompatibleProject(harness),
158 SkillRootAccess::ReadOnlyExternal,
159 SkillScope::Project,
160 workspace.join(directory).join("skills"),
161 true,
162 true,
163 id,
164 );
165 }
166 // Product repositories often keep ordinary content in skills/.
167 // It is an audit candidate until session configuration opts in.
168 push_existing(
169 &mut roots,
170 &mut precedence,
171 SkillRootKind::CompatibleProject(CompatibleHarness::FlatProjectSkills),
172 SkillRootAccess::ReadOnlyExternal,
173 SkillScope::Project,
174 workspace.join("skills"),
175 false,
176 true,
177 "project-flat-skills",
178 );
179
180 // Codex project: audit-compatible only; never active for runtime in #4651.
181 push_existing(
182 &mut roots,
183 &mut precedence,
184 SkillRootKind::CompatibleProject(CompatibleHarness::Codex),
185 SkillRootAccess::ReadOnlyExternal,
186 SkillScope::Project,
187 workspace.join(".codex").join("skills"),
188 false,
189 true,
190 "project-codex",
191 );
192
193 if let Some(global_owned) = owned_global_skills_dir(home_dir) {
194 push_descriptor(
195 &mut roots,
196 &mut precedence,
197 SkillRootKind::CodeWhaleGlobal,
198 SkillRootAccess::WritableOwned,
199 SkillScope::Global,
200 global_owned,
201 true,
202 true,
203 "global-codewhale",
204 true,
205 );
206 }
207 if let Some(home) = home_dir {
208 for (harness, directory, id) in [
209 (CompatibleHarness::Agents, ".agents", "global-agents"),
210 (CompatibleHarness::Claude, ".claude", "global-claude"),
211 (
212 CompatibleHarness::DeepSeekLegacy,
213 ".deepseek",
214 "global-deepseek",
215 ),
216 ] {
217 push_existing(
218 &mut roots,
219 &mut precedence,
220 SkillRootKind::CompatibleGlobal(harness),
221 SkillRootAccess::ReadOnlyExternal,
222 SkillScope::Global,
223 home.join(directory).join("skills"),
224 true,
225 true,
226 id,
227 );
228 }
229
230 // Codex global: audit-compatible only.
231 push_existing(
232 &mut roots,
233 &mut precedence,
234 SkillRootKind::CompatibleGlobal(CompatibleHarness::Codex),
235 SkillRootAccess::ReadOnlyExternal,
236 SkillScope::Global,
237 home.join(".codex").join("skills"),
238 false,
239 true,
240 "global-codex",
241 );
242
243 // Registry cache is never an active skill root.
244 let cache = home.join(".codewhale").join("cache").join("skills");
245 push_descriptor(
246 &mut roots,
247 &mut precedence,
248 SkillRootKind::RegistryCache,
249 SkillRootAccess::CacheOnly,
250 SkillScope::Logical,
251 cache,
252 false,
253 false,
254 "registry-cache",
255 false,
256 );
257 }
258
259 if let Some(configured) = configured_skills_dir {
260 insert_configured_root(&mut roots, workspace, home_dir, configured, &mut precedence);
261 }
262
263 if let Some(global) = owned_global_skills_dir(home_dir) {
264 let system = global.join(".system");
265 if codewhale_util::files::reject_linked_path(&global, &system).is_ok() {
266 push_existing(
267 &mut roots,
268 &mut precedence,
269 SkillRootKind::BuiltIn,
270 SkillRootAccess::Immutable,
271 SkillScope::Global,
272 system,
273 true,
274 true,
275 "system",
276 );
277 }
278 }
279 Self { roots }
280 }
281
282 /// Apply session policy without changing ownership or audit visibility.
283 pub fn with_flat_workspace_root(mut self, enabled: bool) -> Self {
284 for root in &mut self.roots {
285 if root.kind == SkillRootKind::CompatibleProject(CompatibleHarness::FlatProjectSkills) {
286 root.active_for_runtime = enabled;
287 }
288 }
289 self
290 }
291
292 /// Paths used by runtime discovery for the given mode (existing dirs only,
293 /// first-wins order preserved). CodeWhale-only applies the workspace
294 /// containment check for the project owned root.
295 #[must_use]
296 pub fn runtime_directories(
297 &self,
298 workspace: &Path,
299 mode: super::SkillDiscoveryMode,
300 ) -> Vec<PathBuf> {
301 let mut out = Vec::new();
302 let mut seen = HashSet::new();
303 // Repository-supplied skills are instructions the user never
304 // reviewed; they load only once the workspace is trusted. Resolved
305 // lazily so a workspace without project skill dirs never reads config.
306 let mut workspace_trusted = None;
307
308 for root in &self.roots {
309 if !root.active_for_runtime {
310 continue;
311 }
312 if root.scope == SkillScope::Project
313 && path_is_existing_dir(&root.path)
314 && !*workspace_trusted.get_or_insert_with(|| {
315 codewhale_runtime::config::is_workspace_trusted(workspace)
316 })
317 {
318 continue;
319 }
320 match mode {
321 super::SkillDiscoveryMode::Compatible
322 | super::SkillDiscoveryMode::CompatibleWithFlatWorkspace => {}
323 super::SkillDiscoveryMode::CodeWhaleOnly => {
324 if !matches!(
325 root.kind,
326 SkillRootKind::CodeWhaleProject
327 | SkillRootKind::CodeWhaleGlobal
328 | SkillRootKind::Configured
329 | SkillRootKind::BuiltIn
330 ) {
331 continue;
332 }
333 if root.kind == SkillRootKind::CodeWhaleProject
334 && !codewhale_project_root_is_inside_workspace(workspace, &root.path)
335 {
336 continue;
337 }
338 }
339 }
340
341 if !path_is_existing_dir(&root.path) {
342 continue;
343 }
344 let Ok(canonical) = fs::canonicalize(&root.path) else {
345 continue;
346 };
347 if !canonical.is_dir() || !seen.insert(canonical) {
348 continue;
349 }
350 out.push(root.path.clone());
351 }
352 out
353 }
354
355 /// Owned CodeWhale project + global roots (may not exist yet).
356 #[must_use]
357 pub fn owned_writable_roots(&self) -> Vec<&SkillRootDescriptor> {
358 self.roots
359 .iter()
360 .filter(|r| r.is_writable_owned())
361 .collect()
362 }
363
364 /// Roots eligible for owned-only audit (writable owned roots that exist).
365 #[must_use]
366 pub fn audit_owned_directories(&self) -> Vec<&SkillRootDescriptor> {
367 self.roots
368 .iter()
369 .filter(|r| {
370 (r.is_writable_owned() || r.kind == SkillRootKind::BuiltIn)
371 && r.active_for_audit
372 && path_is_existing_dir(&r.path)
373 })
374 .collect()
375 }
376
377 /// Owned + compatible roots for explicit `--compatible` audit, including
378 /// Codex. Does not change runtime activation.
379 #[must_use]
380 pub fn audit_compatible_directories(&self) -> Vec<&SkillRootDescriptor> {
381 self.roots
382 .iter()
383 .filter(|r| {
384 r.active_for_audit
385 && !matches!(
386 r.kind,
387 SkillRootKind::RegistryCache
388 | SkillRootKind::BuiltIn
389 | SkillRootKind::ReviewedPluginSnapshot
390 )
391 && path_is_existing_dir(&r.path)
392 })
393 .collect()
394 }
395
396 #[must_use]
397 pub fn classify_skill(
398 &self,
399 skill: &super::Skill,
400 workspace: &Path,
401 home_dir: Option<&Path>,
402 ) -> SkillCatalogGroup {
403 if !matches!(skill.source, super::SkillSource::Native) {
404 return SkillCatalogGroup::Primary;
405 }
406 let Some(root) = self.root_for_path(&skill.path) else {
407 return SkillCatalogGroup::Primary;
408 };
409 let is_external = matches!(root.kind, SkillRootKind::CompatibleGlobal(_))
410 || (matches!(root.kind, SkillRootKind::CompatibleProject(_))
411 && home_dir.is_some_and(|home| paths_refer_to_same_dir(home, workspace)));
412 if is_external {
413 SkillCatalogGroup::External {
414 source_label: safe_display_path(&root.path, None, home_dir),
415 }
416 } else {
417 SkillCatalogGroup::Primary
418 }
419 }
420
421 fn root_for_path(&self, skill_path: &Path) -> Option<&SkillRootDescriptor> {
422 let mut best: Option<(usize, &SkillRootDescriptor)> = None;
423 for root in self.roots.iter().filter(|root| root.active_for_runtime) {
424 if skill_path.starts_with(&root.path) {
425 let depth = root.path.components().count();
426 if best.is_none_or(|(best_depth, _)| depth > best_depth) {
427 best = Some((depth, root));
428 }
429 }
430 }
431 if let Some((_, root)) = best {
432 return Some(root);
433 }
434 let canonical = fs::canonicalize(skill_path).ok()?;
435 for root in self.roots.iter().filter(|root| root.active_for_runtime) {
436 if let Some(canonical_root) = root.canonical_path.as_ref()
437 && canonical.starts_with(canonical_root)
438 {
439 let depth = canonical_root.components().count();
440 if best.is_none_or(|(best_depth, _)| depth > best_depth) {
441 best = Some((depth, root));
442 }
443 }
444 }
445 best.map(|(_, root)| root)
446 }
447 }
448
449 /// Project skill directories that exist but were not loaded because the
450 /// workspace is not trusted, so discovery can say so instead of dropping them
451 /// silently.
452 #[must_use]
453 pub fn untrusted_project_skill_dirs(
454 workspace: &Path,
455 home_dir: Option<&Path>,
456 configured_skills_dir: Option<&Path>,
457 mode: super::SkillDiscoveryMode,
458 ) -> Vec<PathBuf> {
459 let catalog = SkillRootCatalog::build(workspace, home_dir, configured_skills_dir)
460 .with_flat_workspace_root(mode.flat_workspace_root());
461 let present: Vec<PathBuf> = catalog
462 .roots
463 .iter()
464 .filter(|root| {
465 let explicit = configured_skills_dir
466 .is_some_and(|configured| paths_refer_to_same_dir(configured, &root.path));
467 root.scope == SkillScope::Project
468 && (root.active_for_runtime || explicit)
469 && (mode != super::SkillDiscoveryMode::CodeWhaleOnly
470 || root.is_writable_owned()
471 || explicit)
472 && path_is_existing_dir(&root.path)
473 })
474 .map(|root| root.path.clone())
475 .collect();
476 if present.is_empty() || codewhale_runtime::config::is_workspace_trusted(workspace) {
477 return Vec::new();
478 }
479 present
480 }
481
482 /// Whether `skills_dir` may load right now. A directory in project scope
483 /// (repository-supplied, resolving inside the workspace) is held to the same
484 /// workspace-trust gate as [`SkillRootCatalog::runtime_directories`], so an
485 /// explicit or resolved skills dir cannot re-admit what the catalog filtered.
486 /// A session rooted at the home directory is exempt: every path under it is
487 /// the user's own global content, which the catalog also loads as global.
488 #[must_use]
489 pub fn skills_dir_allowed_by_workspace_trust(
490 workspace: &Path,
491 home_dir: Option<&Path>,
492 skills_dir: &Path,
493 ) -> bool {
494 classify_configured_skills_dir(workspace, home_dir, skills_dir).2 != SkillScope::Project
495 || home_dir.is_some_and(|home| paths_refer_to_same_dir(home, workspace))
496 || codewhale_runtime::config::is_workspace_trusted(workspace)
497 }
498
499 /// Resolve candidate skill directories for runtime discovery (existing paths
500 /// only), preserving historical precedence.
501 #[must_use]
502 pub fn skills_directories_with_home_and_mode(
503 workspace: &Path,
504 home_dir: Option<&Path>,
505 mode: super::SkillDiscoveryMode,
506 ) -> Vec<PathBuf> {
507 SkillRootCatalog::build(workspace, home_dir, None)
508 .with_flat_workspace_root(mode.flat_workspace_root())
509 .runtime_directories(workspace, mode)
510 }
511
512 /// CodeWhale project skills dir when it exists and stays inside the workspace.
513 #[must_use]
514 pub fn codewhale_workspace_skills_dir(workspace: &Path) -> Option<PathBuf> {
515 let skills_dir = workspace.join(".codewhale").join("skills");
516 codewhale_project_root_is_inside_workspace(workspace, &skills_dir).then_some(skills_dir)
517 }
518
519 /// Filter candidate paths to existing directories, preserving order and
520 /// de-duplicating by canonical path.
521 #[cfg(any(test, feature = "test-support"))]
522 #[must_use]
523 pub fn existing_skill_dirs(candidates: impl IntoIterator<Item = PathBuf>) -> Vec<PathBuf> {
524 let mut out = Vec::new();
525 let mut seen = HashSet::new();
526 for path in candidates {
527 let Ok(canonical_path) = fs::canonicalize(&path) else {
528 continue;
529 };
530 if canonical_path.is_dir() && seen.insert(canonical_path) {
531 out.push(path);
532 }
533 }
534 out
535 }
536
537 /// Classify a configured `skills_dir`: owned only when it is exactly a
538 /// CodeWhale project/global root; compatible harness paths stay read-only.
539 #[must_use]
540 pub fn classify_configured_skills_dir(
541 workspace: &Path,
542 home_dir: Option<&Path>,
543 skills_dir: &Path,
544 ) -> (SkillRootKind, SkillRootAccess, SkillScope) {
545 let project_owned = workspace.join(".codewhale").join("skills");
546 if paths_refer_to_same_dir(&project_owned, skills_dir) {
547 return (
548 SkillRootKind::CodeWhaleProject,
549 SkillRootAccess::WritableOwned,
550 SkillScope::Project,
551 );
552 }
553 if let Some(global_owned) = owned_global_skills_dir(home_dir)
554 && paths_refer_to_same_dir(&global_owned, skills_dir)
555 {
556 return (
557 SkillRootKind::CodeWhaleGlobal,
558 SkillRootAccess::WritableOwned,
559 SkillScope::Global,
560 );
561 }
562
563 if let Some(harness) = match_compatible_project(workspace, skills_dir) {
564 return (
565 SkillRootKind::CompatibleProject(harness),
566 SkillRootAccess::ReadOnlyExternal,
567 SkillScope::Project,
568 );
569 }
570 if let Some(home) = home_dir
571 && let Some(harness) = match_compatible_global(home, skills_dir)
572 {
573 return (
574 SkillRootKind::CompatibleGlobal(harness),
575 SkillRootAccess::ReadOnlyExternal,
576 SkillScope::Global,
577 );
578 }
579
580 // Unknown configured path: treat as external until an explicit owned-root
581 // marker exists (Issue #4651 first cut — do not guess writability).
582 let scope = fs::canonicalize(workspace)
583 .ok()
584 .map_or(SkillScope::Global, |root| {
585 fs::canonicalize(skills_dir)
586 .ok()
587 .filter(|p| p.starts_with(&root))
588 .map_or(SkillScope::Global, |_| SkillScope::Project)
589 });
590 (
591 SkillRootKind::Configured,
592 SkillRootAccess::ReadOnlyExternal,
593 scope,
594 )
595 }
596
597 #[must_use]
598 pub fn safe_display_path(path: &Path, workspace: Option<&Path>, home: Option<&Path>) -> String {
599 // Prefer workspace when both apply so project roots stay distinct from
600 // `~/...` global paths that happen to live under the same home tree.
601 if let Some(workspace) = workspace
602 && let Ok(stripped) = path.strip_prefix(workspace)
603 {
604 return format!("<workspace>/{}", stripped.display()).replace('\\', "/");
605 }
606 if let Some(home) = home
607 && let Ok(stripped) = path.strip_prefix(home)
608 {
609 return format!("~/{}", stripped.display()).replace('\\', "/");
610 }
611 // Last resort: basename chain without expanding unrelated absolute parents.
612 path.file_name()
613 .map(|name| name.to_string_lossy().into_owned())
614 .unwrap_or_else(|| path.display().to_string())
615 }
616
617 #[must_use]
618 pub fn paths_refer_to_same_dir(left: &Path, right: &Path) -> bool {
619 if left == right {
620 return true;
621 }
622 match (fs::canonicalize(left), fs::canonicalize(right)) {
623 (Ok(left), Ok(right)) => left == right,
624 _ => false,
625 }
626 }
627
628 fn codewhale_project_root_is_inside_workspace(workspace: &Path, skills_dir: &Path) -> bool {
629 let Ok(canonical_workspace) = fs::canonicalize(workspace) else {
630 return false;
631 };
632 let Ok(canonical_skills) = fs::canonicalize(skills_dir) else {
633 return false;
634 };
635 canonical_skills.is_dir() && canonical_skills.starts_with(canonical_workspace)
636 }
637
638 fn path_is_existing_dir(path: &Path) -> bool {
639 match fs::symlink_metadata(path) {
640 Ok(meta) if meta.file_type().is_symlink() => {
641 fs::canonicalize(path).ok().is_some_and(|p| p.is_dir())
642 }
643 Ok(meta) => meta.is_dir(),
644 Err(_) => false,
645 }
646 }
647
648 fn match_compatible_project(workspace: &Path, skills_dir: &Path) -> Option<CompatibleHarness> {
649 let candidates = [
650 (
651 CompatibleHarness::Agents,
652 workspace.join(".agents").join("skills"),
653 ),
654 (
655 CompatibleHarness::FlatProjectSkills,
656 workspace.join("skills"),
657 ),
658 (
659 CompatibleHarness::OpenCode,
660 workspace.join(".opencode").join("skills"),
661 ),
662 (
663 CompatibleHarness::Claude,
664 workspace.join(".claude").join("skills"),
665 ),
666 (
667 CompatibleHarness::Cursor,
668 workspace.join(".cursor").join("skills"),
669 ),
670 (
671 CompatibleHarness::Codex,
672 workspace.join(".codex").join("skills"),
673 ),
674 ];
675 for (harness, candidate) in candidates {
676 if paths_refer_to_same_dir(&candidate, skills_dir) {
677 return Some(harness);
678 }
679 }
680 None
681 }
682
683 fn match_compatible_global(home: &Path, skills_dir: &Path) -> Option<CompatibleHarness> {
684 let candidates = [
685 (
686 CompatibleHarness::Agents,
687 home.join(".agents").join("skills"),
688 ),
689 (
690 CompatibleHarness::Claude,
691 home.join(".claude").join("skills"),
692 ),
693 (
694 CompatibleHarness::DeepSeekLegacy,
695 home.join(".deepseek").join("skills"),
696 ),
697 (CompatibleHarness::Codex, home.join(".codex").join("skills")),
698 ];
699 for (harness, candidate) in candidates {
700 if paths_refer_to_same_dir(&candidate, skills_dir) {
701 return Some(harness);
702 }
703 }
704 None
705 }
706
707 #[allow(clippy::too_many_arguments)] // catalog rows keep ownership flags explicit at call sites
708 fn push_existing(
709 roots: &mut Vec<SkillRootDescriptor>,
710 precedence: &mut usize,
711 kind: SkillRootKind,
712 access: SkillRootAccess,
713 scope: SkillScope,
714 path: PathBuf,
715 active_for_runtime: bool,
716 active_for_audit: bool,
717 id: &str,
718 ) {
719 push_descriptor(
720 roots,
721 precedence,
722 kind,
723 access,
724 scope,
725 path,
726 active_for_runtime,
727 active_for_audit,
728 id,
729 false,
730 );
731 }
732
733 #[allow(clippy::too_many_arguments)] // shared constructor for the explicit catalog table above
734 fn push_descriptor(
735 roots: &mut Vec<SkillRootDescriptor>,
736 precedence: &mut usize,
737 kind: SkillRootKind,
738 access: SkillRootAccess,
739 scope: SkillScope,
740 path: PathBuf,
741 active_for_runtime: bool,
742 active_for_audit: bool,
743 id: &str,
744 include_missing: bool,
745 ) {
746 let exists = path_is_existing_dir(&path);
747 if !include_missing && !exists {
748 return;
749 }
750 let canonical_path = fs::canonicalize(&path).ok();
751 let slot = *precedence;
752 *precedence += 1;
753 roots.push(SkillRootDescriptor {
754 id: SkillRootId(id.to_string()),
755 kind,
756 access,
757 scope,
758 path,
759 canonical_path,
760 precedence: Some(slot),
761 active_for_runtime,
762 active_for_audit,
763 });
764 }
765
766 fn insert_configured_root(
767 roots: &mut Vec<SkillRootDescriptor>,
768 workspace: &Path,
769 home_dir: Option<&Path>,
770 skills_dir: &Path,
771 precedence: &mut usize,
772 ) {
773 if !path_is_existing_dir(skills_dir) {
774 return;
775 }
776 if roots
777 .iter()
778 .any(|root| paths_refer_to_same_dir(&root.path, skills_dir))
779 {
780 return;
781 }
782
783 let (kind, access, scope) = classify_configured_skills_dir(workspace, home_dir, skills_dir);
784 let workspace_root = fs::canonicalize(workspace).ok();
785 let insert_at = workspace_root
786 .as_ref()
787 .and_then(|root| {
788 roots.iter().position(|dir| {
789 fs::canonicalize(&dir.path).map_or(true, |dir| !dir.starts_with(root))
790 })
791 })
792 .unwrap_or(roots.len());
793
794 let canonical_path = fs::canonicalize(skills_dir).ok();
795 let slot = *precedence;
796 *precedence += 1;
797 let descriptor = SkillRootDescriptor {
798 id: SkillRootId(format!("configured-{slot}")),
799 kind,
800 access,
801 scope,
802 path: skills_dir.to_path_buf(),
803 canonical_path,
804 precedence: Some(slot),
805 active_for_runtime: true,
806 active_for_audit: true,
807 };
808 roots.insert(insert_at, descriptor);
809 // Re-number precedence after insertion so catalog order stays consistent.
810 for (idx, root) in roots.iter_mut().enumerate() {
811 root.precedence = Some(idx);
812 }
813 *precedence = roots.len();
814 }
815
816 fn owned_global_skills_dir(home: Option<&Path>) -> Option<PathBuf> {
817 if home == codewhale_paths::user_home().as_deref() {
818 codewhale_runtime::config::owned_skills_dir()
819 } else {
820 home.map(|home| home.join(".codewhale/skills"))
821 }
822 }
823
824 #[cfg(test)]
825 mod tests {
826 use super::*;
827 use crate::SkillDiscoveryMode;
828 use tempfile::TempDir;
829
830 fn write_dir(path: &Path) {
831 std::fs::create_dir_all(path).unwrap();
832 }
833
834 #[test]
835 fn unavailable_home_has_no_ambient_global_or_cache_root() {
836 let tmp = TempDir::new().unwrap();
837 let catalog = SkillRootCatalog::build(tmp.path(), None, None);
838 assert!(
839 catalog
840 .roots
841 .iter()
842 .all(|root| root.scope == SkillScope::Project)
843 );
844 let owned = catalog.owned_writable_roots();
845 assert_eq!(owned.len(), 1);
846 assert_eq!(owned[0].kind, SkillRootKind::CodeWhaleProject);
847 assert_eq!(owned[0].path, tmp.path().join(".codewhale/skills"));
848 }
849
850 #[test]
851 fn runtime_compatible_prioritizes_owned_workspace_roots() {
852 let tmp = TempDir::new().unwrap();
853 let workspace = tmp.path().join("ws");
854 let home = tmp.path().join("home");
855 codewhale_runtime::test_support::trust_workspace(&workspace);
856 write_dir(&workspace.join(".agents").join("skills"));
857 write_dir(&workspace.join("skills"));
858 write_dir(&workspace.join(".claude").join("skills"));
859 write_dir(&workspace.join(".cursor").join("skills"));
860 write_dir(&workspace.join(".codewhale").join("skills"));
861 write_dir(&workspace.join(".codex").join("skills"));
862 write_dir(&home.join(".codewhale").join("skills"));
863
864 let catalog = SkillRootCatalog::build(&workspace, Some(&home), None);
865 let dirs = catalog.runtime_directories(&workspace, SkillDiscoveryMode::Compatible);
866
867 assert_eq!(
868 dirs,
869 vec![
870 workspace.join(".codewhale").join("skills"),
871 workspace.join(".agents").join("skills"),
872 workspace.join(".claude").join("skills"),
873 workspace.join(".cursor").join("skills"),
874 home.join(".codewhale").join("skills"),
875 ]
876 );
877 assert!(
878 !dirs
879 .iter()
880 .any(|p| p == &workspace.join(".codex").join("skills")),
881 "codex must not activate for runtime"
882 );
883 }
884
885 #[test]
886 fn audit_compatible_includes_codex_without_runtime_activation() {
887 let tmp = TempDir::new().unwrap();
888 let workspace = tmp.path().join("ws");
889 let home = tmp.path().join("home");
890 write_dir(&workspace.join(".codewhale").join("skills"));
891 write_dir(&workspace.join(".codex").join("skills"));
892 write_dir(&home.join(".codewhale").join("skills"));
893 write_dir(&home.join(".codex").join("skills"));
894
895 let catalog = SkillRootCatalog::build(&workspace, Some(&home), None);
896 let audit: Vec<_> = catalog
897 .audit_compatible_directories()
898 .into_iter()
899 .map(|r| r.path.clone())
900 .collect();
901 assert!(audit.contains(&workspace.join(".codex").join("skills")));
902 assert!(audit.contains(&home.join(".codex").join("skills")));
903
904 let runtime = catalog.runtime_directories(&workspace, SkillDiscoveryMode::Compatible);
905 assert!(!runtime.contains(&workspace.join(".codex").join("skills")));
906 assert!(!runtime.contains(&home.join(".codex").join("skills")));
907 }
908
909 #[test]
910 fn owned_roots_are_writable_and_codewhale_only() {
911 let tmp = TempDir::new().unwrap();
912 let workspace = tmp.path().join("ws");
913 let home = tmp.path().join("home");
914 codewhale_runtime::test_support::trust_workspace(&workspace);
915 write_dir(&workspace.join(".agents").join("skills"));
916 write_dir(&workspace.join(".codewhale").join("skills"));
917 write_dir(&home.join(".codewhale").join("skills"));
918 write_dir(&home.join(".agents").join("skills"));
919
920 let catalog = SkillRootCatalog::build(&workspace, Some(&home), None);
921 let owned = catalog.owned_writable_roots();
922 assert_eq!(owned.len(), 2);
923 assert!(owned.iter().all(|r| r.is_writable_owned()));
924
925 let runtime = catalog.runtime_directories(&workspace, SkillDiscoveryMode::CodeWhaleOnly);
926 assert_eq!(
927 runtime,
928 vec![
929 workspace.join(".codewhale").join("skills"),
930 home.join(".codewhale").join("skills"),
931 ]
932 );
933 }
934
935 #[test]
936 fn configured_compatible_path_stays_read_only() {
937 let tmp = TempDir::new().unwrap();
938 let workspace = tmp.path().join("ws");
939 let home = tmp.path().join("home");
940 let agents = workspace.join(".agents").join("skills");
941 write_dir(&workspace);
942 write_dir(&agents);
943
944 let (kind, access, scope) =
945 classify_configured_skills_dir(&workspace, Some(&home), &agents);
946 assert_eq!(
947 kind,
948 SkillRootKind::CompatibleProject(CompatibleHarness::Agents)
949 );
950 assert_eq!(access, SkillRootAccess::ReadOnlyExternal);
951 assert_eq!(scope, SkillScope::Project);
952 }
953
954 #[test]
955 fn safe_display_path_prefers_home_then_workspace() {
956 let home = PathBuf::from("/home/user");
957 let workspace = home.join("proj");
958 let path = home.join(".codewhale").join("skills");
959 assert_eq!(
960 safe_display_path(&path, Some(&workspace), Some(&home)),
961 "~/.codewhale/skills"
962 );
963 let project = workspace.join(".codewhale").join("skills");
964 assert_eq!(
965 safe_display_path(&project, Some(&workspace), Some(&home)),
966 "<workspace>/.codewhale/skills"
967 );
968 }
969 #[test]
970 fn flat_workspace_root_remains_audit_only_until_opted_in() {
971 let tmp = TempDir::new().unwrap();
972 let workspace = tmp.path().join("ws");
973 codewhale_runtime::test_support::trust_workspace(&workspace);
974 let flat = workspace.join("skills");
975 write_dir(&flat);
976 let catalog = SkillRootCatalog::build(&workspace, None, None);
977 assert!(
978 catalog
979 .audit_compatible_directories()
980 .iter()
981 .any(|root| root.path == flat && !root.active_for_runtime)
982 );
983 assert!(
984 !catalog
985 .runtime_directories(&workspace, SkillDiscoveryMode::Compatible)
986 .contains(&flat)
987 );
988 let enabled = catalog.with_flat_workspace_root(true);
989 assert!(
990 enabled
991 .runtime_directories(&workspace, SkillDiscoveryMode::CompatibleWithFlatWorkspace)
992 .contains(&flat)
993 );
994 assert!(
995 !enabled
996 .runtime_directories(&workspace, SkillDiscoveryMode::CodeWhaleOnly)
997 .contains(&flat)
998 );
999 }
1000 }
1001
1001 lines RUST