返回 CodeWhale
discovery.rs
根目录 / crates / plugins / src / discovery.rs
1 use std::collections::{BTreeMap, BTreeSet, HashSet};
2 use std::fs;
3 use std::path::{Path, PathBuf};
4 use std::time::SystemTime;
5
6 use sha2::{Digest, Sha256};
7
8 use super::agent_plugin::resolve_manifest_path;
9 use super::manifest::{PluginManifest, ValidatedManifest};
10 use super::registry::PluginRegistry;
11 use super::types::{
12 LoadedPlugin, PluginDiagnostic, PluginOrigin, PluginScope, PluginSkillSnapshot,
13 PluginTrustStatus,
14 };
15 use codewhale_config::PluginId;
16 use codewhale_util::path_identity::metadata_is_link_or_reparse;
17
18 pub const MAX_SKILLS_PER_OWNER: usize = 128;
19 pub const MAX_BYTES_PER_OWNER: usize = 4 * 1024 * 1024;
20
21 #[derive(Debug, Clone)]
22 pub struct DiscoveryConfig {
23 pub workspace: PathBuf,
24 pub user_plugins_dir: PathBuf,
25 pub workspace_plugins_dir: PathBuf,
26 pub builtin_plugin_dirs: Vec<PathBuf>,
27 pub state_path: PathBuf,
28 }
29
30 /// Cheap on-disk catalog fingerprint: plugin-bundle directories plus the
31 /// content of the plugin state file.
32 ///
33 /// Used to apply or nudge a reload when a bundle appears, disappears, or is
34 /// rewritten, or when another process installs, enables or disables a plugin.
35 /// The state file is compared by content digest, never by mtime, so a rewrite
36 /// with identical bytes is not a change and a same-second rewrite is.
37 #[derive(Debug, Clone, PartialEq, Eq, Default)]
38 pub struct PluginCatalogStamp {
39 entries: BTreeMap<PathBuf, Option<SystemTime>>,
40 state: Option<[u8; 32]>,
41 }
42
43 const MAX_STAMPED_FILE_BYTES: u64 = 8 * 1024 * 1024;
44
45 /// SHA-256 of a small file's bytes, or `None` when it is absent, unreadable or
46 /// larger than the stamp bound.
47 #[must_use]
48 pub fn file_content_digest(path: &Path) -> Option<[u8; 32]> {
49 use std::io::Read;
50 let file = fs::File::open(path).ok()?;
51 let mut bytes = Vec::new();
52 file.take(MAX_STAMPED_FILE_BYTES + 1)
53 .read_to_end(&mut bytes)
54 .ok()?;
55 if bytes.len() as u64 > MAX_STAMPED_FILE_BYTES {
56 return None;
57 }
58 Some(Sha256::digest(&bytes).into())
59 }
60
61 impl PluginCatalogStamp {
62 #[must_use]
63 pub fn capture(roots: impl IntoIterator<Item = PathBuf>, state_path: &Path) -> Self {
64 let mut entries = BTreeMap::new();
65 for root in roots {
66 let Ok(read) = fs::read_dir(&root) else {
67 continue;
68 };
69 for entry in read.flatten() {
70 let path = entry.path();
71 let Ok(metadata) = fs::symlink_metadata(&path) else {
72 continue;
73 };
74 if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
75 continue;
76 }
77 entries.insert(path, metadata.modified().ok());
78 }
79 }
80 Self {
81 entries,
82 state: file_content_digest(state_path),
83 }
84 }
85
86 pub fn refresh_state(&mut self, state_path: &Path) {
87 self.state = file_content_digest(state_path);
88 }
89 }
90
91 #[must_use]
92 pub fn default_user_plugins_dir() -> PathBuf {
93 codewhale_config::codewhale_home()
94 .map(|path| path.join("plugins"))
95 .unwrap_or_else(|error| {
96 // Never fall back to a shared, predictable temporary directory:
97 // that would turn a home-resolution failure into ambient plugin
98 // discovery. A fresh nonexistent sentinel keeps startup read-only
99 // and fail-closed on every supported platform.
100 tracing::warn!(
101 target: "plugins",
102 %error,
103 "Codewhale home could not be resolved; user plugin discovery is disabled"
104 );
105 std::env::temp_dir()
106 .join(format!(
107 ".codewhale-home-unavailable-{}",
108 uuid::Uuid::new_v4().simple()
109 ))
110 .join("plugins")
111 })
112 }
113
114 #[must_use]
115 pub fn default_workspace_plugins_dir(workspace: &Path) -> PathBuf {
116 workspace.join(".codewhale").join("plugins")
117 }
118
119 #[cfg(any(test, feature = "test-support"))]
120 #[must_use]
121 pub fn discover_with_config(config: &DiscoveryConfig) -> PluginRegistry {
122 let context = super::context::PluginDiscoveryContext::from_config_and_environment(
123 config,
124 super::context::HostEnvironment::capture(),
125 );
126 discover_with_context(config, context)
127 }
128
129 #[must_use]
130 pub fn discover_with_context(
131 config: &DiscoveryConfig,
132 context: std::sync::Arc<super::context::PluginDiscoveryContext>,
133 ) -> PluginRegistry {
134 let mut diagnostics = Vec::new();
135 let mut candidates = Vec::new();
136
137 for root in &config.builtin_plugin_dirs {
138 scan_root(
139 root,
140 PluginScope::Builtin,
141 PluginOrigin::Builtin,
142 &mut candidates,
143 &mut diagnostics,
144 );
145 }
146 scan_root(
147 &config.user_plugins_dir,
148 PluginScope::User,
149 PluginOrigin::CodeWhaleHome,
150 &mut candidates,
151 &mut diagnostics,
152 );
153 scan_root(
154 &config.workspace_plugins_dir,
155 PluginScope::Workspace,
156 PluginOrigin::Workspace,
157 &mut candidates,
158 &mut diagnostics,
159 );
160
161 candidates.sort_by(|left, right| {
162 left.scope
163 .cmp(&right.scope)
164 .then_with(|| left.name().cmp(right.name()))
165 .then_with(|| left.canonical_root.cmp(&right.canonical_root))
166 });
167
168 let mut seen_roots = HashSet::new();
169 let mut seen_names = BTreeSet::new();
170 let mut plugins = Vec::new();
171 for plugin in candidates {
172 if !seen_roots.insert(plugin.canonical_root.clone()) {
173 diagnostics.push(PluginDiagnostic::warning(
174 "duplicate-root",
175 format!(
176 "Ignoring duplicate plugin discovery at {}",
177 plugin.canonical_root.display()
178 ),
179 Some(plugin.canonical_root.clone()),
180 ));
181 continue;
182 }
183 if !seen_names.insert(plugin.name().to_string()) {
184 diagnostics.push(PluginDiagnostic::warning(
185 "name-conflict",
186 format!(
187 "Plugin `{}` at {} is shadowed by the higher-precedence bundle with the same name",
188 plugin.name(),
189 plugin.canonical_root.display()
190 ),
191 Some(plugin.canonical_root.clone()),
192 ));
193 continue;
194 }
195 plugins.push(plugin);
196 }
197
198 PluginRegistry::from_discovery(
199 plugins,
200 diagnostics,
201 config.state_path.clone(),
202 config.workspace.clone(),
203 Some(context),
204 )
205 }
206
207 // These exact operation-name shapes are reserved by stage::fresh_staging_dir
208 // and place::finalize_install. Do not hide human paths such as demo.bak or
209 // .staging-not-a-uuid, which can legitimately contain reviewed bundles.
210 fn is_internal_publication_directory(name: &std::ffi::OsStr) -> bool {
211 let Some(name) = name.to_str() else {
212 return false;
213 };
214 name.strip_prefix(".staging-").is_some_and(|suffix| {
215 suffix.len() == 32
216 && suffix
217 .bytes()
218 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
219 }) || name.strip_prefix(".plugin-backup-").is_some_and(|suffix| {
220 suffix.len() == 16 && suffix.bytes().all(|byte| byte.is_ascii_alphanumeric())
221 })
222 }
223
224 fn scan_root(
225 root: &Path,
226 scope: PluginScope,
227 origin: PluginOrigin,
228 plugins: &mut Vec<LoadedPlugin>,
229 diagnostics: &mut Vec<PluginDiagnostic>,
230 ) {
231 let Ok(metadata) = fs::symlink_metadata(root) else {
232 return;
233 };
234 if metadata_is_link_or_reparse(&metadata) {
235 diagnostics.push(PluginDiagnostic::error(
236 "root-symlink",
237 format!(
238 "Plugin discovery root may not be a symbolic link or reparse point: {}",
239 root.display()
240 ),
241 Some(root.to_path_buf()),
242 ));
243 return;
244 }
245 if !metadata.is_dir() {
246 diagnostics.push(PluginDiagnostic::error(
247 "root-not-directory",
248 format!(
249 "Plugin discovery root is not a directory: {}",
250 root.display()
251 ),
252 Some(root.to_path_buf()),
253 ));
254 return;
255 }
256 let canonical_discovery_root = match root.canonicalize() {
257 Ok(root) => root,
258 Err(error) => {
259 diagnostics.push(PluginDiagnostic::error(
260 "root-canonicalize-failed",
261 format!(
262 "Failed to canonicalize plugin root {}: {error}",
263 root.display()
264 ),
265 Some(root.to_path_buf()),
266 ));
267 return;
268 }
269 };
270
271 let mut entries = match fs::read_dir(root) {
272 Ok(entries) => match entries.collect::<Result<Vec<_>, _>>() {
273 Ok(entries) => entries,
274 Err(error) => {
275 diagnostics.push(PluginDiagnostic::error(
276 "root-read-failed",
277 format!("Failed to read plugin root {}: {error}", root.display()),
278 Some(root.to_path_buf()),
279 ));
280 return;
281 }
282 },
283 Err(error) => {
284 diagnostics.push(PluginDiagnostic::error(
285 "root-read-failed",
286 format!("Failed to read plugin root {}: {error}", root.display()),
287 Some(root.to_path_buf()),
288 ));
289 return;
290 }
291 };
292 entries.sort_by_key(fs::DirEntry::file_name);
293
294 for entry in entries {
295 if is_internal_publication_directory(&entry.file_name()) {
296 continue;
297 }
298 let plugin_root = entry.path();
299 let Ok(metadata) = fs::symlink_metadata(&plugin_root) else {
300 continue;
301 };
302 if metadata_is_link_or_reparse(&metadata) {
303 diagnostics.push(PluginDiagnostic::error(
304 "bundle-symlink",
305 format!(
306 "Plugin bundle directory may not be a symbolic link or reparse point: {}",
307 plugin_root.display()
308 ),
309 Some(plugin_root),
310 ));
311 continue;
312 }
313 if !metadata.is_dir() {
314 continue;
315 }
316 // Agent Plugins v1.0.0 `plugin.json` is preferred; a legacy
317 // `plugin.toml` in the same bundle stays readable.
318 let Some(manifest_path) = resolve_manifest_path(&plugin_root) else {
319 continue;
320 };
321 match load_plugin(&manifest_path, &canonical_discovery_root, scope, origin) {
322 Ok(plugin) => plugins.push(plugin),
323 Err(error) => diagnostics.push(PluginDiagnostic::error(
324 "manifest-invalid",
325 error,
326 Some(manifest_path),
327 )),
328 }
329 }
330 }
331
332 fn load_plugin(
333 manifest_path: &Path,
334 canonical_discovery_root: &Path,
335 scope: PluginScope,
336 origin: PluginOrigin,
337 ) -> Result<LoadedPlugin, String> {
338 let validated = PluginManifest::validate_from_path(manifest_path)?;
339 if validated.canonical_root.parent() != Some(canonical_discovery_root) {
340 return Err(format!(
341 "plugin bundle resolved outside its Codewhale-owned discovery root: {}",
342 validated.canonical_root.display()
343 ));
344 }
345 let id = plugin_id(
346 scope,
347 &validated.manifest.plugin.name,
348 &validated.canonical_root,
349 );
350 let mut diagnostics = validated
351 .warnings
352 .iter()
353 .map(|warning| {
354 PluginDiagnostic::warning(
355 "manifest-legacy",
356 warning.clone(),
357 Some(manifest_path.to_path_buf()),
358 )
359 })
360 .collect::<Vec<_>>();
361
362 let (skill_snapshots, skill_diagnostics) = parse_skill_snapshots(&validated)?;
363 diagnostics.extend(skill_diagnostics);
364
365 let unsupported = validated.inventory.unsupported_labels();
366 if !unsupported.is_empty() {
367 diagnostics.push(PluginDiagnostic::warning(
368 "component-inactive",
369 format!(
370 "compatibility {}; inactive components remain inventoried but are not activated: {}",
371 validated.inventory.compatibility().as_str(),
372 unsupported.join(", ")
373 ),
374 Some(manifest_path.to_path_buf()),
375 ));
376 }
377 // Under the extension-host policy a `native` entry is executable host
378 // code. Report invalid entries during validation and review, before
379 // activation refuses the bundle because it has an error diagnostic.
380 if super::activation::PluginActivationPolicy::current()
381 .is_supported(super::activation::PluginActivationCapability::Native)
382 {
383 for entry in &validated.components.native {
384 // Every regular bundle file is hashed; a directory is not.
385 let is_regular_file = entry
386 .strip_prefix(&validated.canonical_root)
387 .is_ok_and(|relative| validated.file_hashes.contains_key(relative));
388 if let Some(problem) = super::runtime::native_entry_problem(entry, is_regular_file) {
389 diagnostics.push(PluginDiagnostic::error(
390 "native-entry-invalid",
391 format!("native entry {}: {problem}", entry.display()),
392 Some(entry.clone()),
393 ));
394 }
395 }
396 }
397
398 // Skill parsing happens after hashing. Revalidate once so a concurrent
399 // bundle edit cannot pair a reviewed hash with different in-memory Skill
400 // instructions or MCP configuration. Active Skill bodies are replaced by
401 // snapshots parsed from the Codewhale-owned staged tree in `apply_state`.
402 let refreshed = PluginManifest::validate_from_path(manifest_path)?;
403 if refreshed.content_hash != validated.content_hash
404 || refreshed.capability_hash != validated.capability_hash
405 {
406 return Err(format!(
407 "plugin `{}` changed during discovery; reload and review the stable bundle",
408 validated.manifest.plugin.name
409 ));
410 }
411 let validated = refreshed;
412
413 let install_nonce = match read_install_nonce(&validated.canonical_root) {
414 Ok(nonce) => nonce,
415 Err(error) => {
416 diagnostics.push(PluginDiagnostic::warning(
417 "install-record-invalid",
418 error,
419 Some(
420 validated
421 .canonical_root
422 .join(codewhale_skill_install::install::INSTALLED_FROM_MARKER),
423 ),
424 ));
425 None
426 }
427 };
428
429 Ok(LoadedPlugin {
430 id,
431 manifest: validated.manifest,
432 base_path: validated.canonical_root.clone(),
433 canonical_root: validated.canonical_root,
434 staged_root: None,
435 scope,
436 origin,
437 enabled: false,
438 trust_status: PluginTrustStatus::NeverReviewed,
439 applicable: validated.applicable,
440 inventory: validated.inventory,
441 components: validated.components,
442 content_hash: validated.content_hash,
443 capability_hash: validated.capability_hash,
444 state_generation: 0,
445 approved_by: None,
446 enabled_by: None,
447 host_services: Vec::new(),
448 outside_reach: false,
449 reviewed_at: None,
450 review_history: Vec::new(),
451 install_nonce,
452 skill_snapshots,
453 diagnostics,
454 })
455 }
456
457 pub(crate) fn read_install_nonce(root: &Path) -> Result<Option<String>, String> {
458 use std::io::Read as _;
459
460 let path = root.join(codewhale_skill_install::install::INSTALLED_FROM_MARKER);
461 let metadata = match fs::symlink_metadata(&path) {
462 Ok(metadata) => metadata,
463 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
464 Err(error) => {
465 return Err(format!("failed to inspect {}: {error}", path.display()));
466 }
467 };
468 if metadata_is_link_or_reparse(&metadata) || !metadata.file_type().is_file() {
469 return Err(format!(
470 "{} is not an ordinary regular file",
471 path.display()
472 ));
473 }
474 let file = codewhale_util::bundle_file::open_bundle_file(&path)
475 .map_err(|error| format!("failed to open {}: {error}", path.display()))?;
476 let mut raw = String::new();
477 file.take(64 * 1024 + 1)
478 .read_to_string(&mut raw)
479 .map_err(|error| format!("failed to read {}: {error}", path.display()))?;
480 if raw.len() > 64 * 1024 {
481 return Err(format!("{} exceeds maximum marker size", path.display()));
482 }
483 Ok(
484 serde_json::from_str::<codewhale_skill_install::install::InstalledFromMarker>(&raw)
485 .ok()
486 .and_then(|marker| marker.install_nonce().map(str::to_string)),
487 )
488 }
489
490 fn parse_skill_snapshots(
491 validated: &ValidatedManifest,
492 ) -> Result<(Vec<PluginSkillSnapshot>, Vec<PluginDiagnostic>), String> {
493 parse_skill_snapshots_for_roots(validated, &validated.components.skills, false)
494 }
495
496 /// One parser for declared and programmable roots. Only the byte inventory
497 /// that produced the reviewed bundle hash chooses files; discovery never
498 /// parses a mutable/unreviewed file before its receipt has been checked.
499 fn parse_skill_snapshots_for_roots(
500 validated: &ValidatedManifest,
501 roots: &[PathBuf],
502 bounded_native: bool,
503 ) -> Result<(Vec<PluginSkillSnapshot>, Vec<PluginDiagnostic>), String> {
504 let mut diagnostics = Vec::new();
505 let mut skill_snapshots = Vec::new();
506 let mut parsed_files = 0usize;
507 let mut parsed_bytes = 0usize;
508 for root in roots {
509 let root_relative = root
510 .strip_prefix(&validated.canonical_root)
511 .map_err(|_| "Skill root escaped the reviewed bundle".to_string())?;
512 let mut candidates: Vec<_> = validated
513 .file_hashes
514 .iter()
515 .filter(|(path, _)| {
516 let Ok(relative) = path.strip_prefix(root_relative) else {
517 return false;
518 };
519 let components: Vec<_> = relative.components().collect();
520 path.file_name().is_some_and(|name| name == "SKILL.md")
521 && components.len() >= 2
522 && components.len() - 2
523 <= codewhale_skill_install::skill_parse::MAX_DISCOVERY_DEPTH
524 && components[..components.len() - 1].iter().all(|component| {
525 !component
526 .as_os_str()
527 .to_str()
528 .is_some_and(|name| name.starts_with('.'))
529 })
530 })
531 .collect();
532 candidates.sort_by(|(a, _), (b, _)| {
533 a.components()
534 .count()
535 .cmp(&b.components().count())
536 .then_with(|| a.cmp(b))
537 });
538 let mut claimed = BTreeSet::<PathBuf>::new();
539 for (relative, expected_hash) in candidates {
540 let directory = relative.parent().expect("SKILL.md has a parent");
541 if claimed.iter().any(|parent| directory.starts_with(parent)) {
542 continue;
543 }
544 // Even an invalid parent Skill claims its package, so nested
545 // examples cannot become independent instructions.
546 claimed.insert(directory.to_path_buf());
547 if bounded_native && parsed_files >= crate::discovery::MAX_SKILLS_PER_OWNER {
548 return Err("skill root exceeds the bounded candidate count".to_string());
549 }
550 parsed_files += 1;
551 let path = validated.canonical_root.join(relative);
552 let bytes = read_skill_bytes(&validated.canonical_root, &path)?;
553 parsed_bytes = parsed_bytes.saturating_add(bytes.len());
554 if bounded_native && parsed_bytes > crate::discovery::MAX_BYTES_PER_OWNER {
555 return Err("skill root exceeds the bounded instruction byte limit".to_string());
556 }
557 let actual_hash = hash_skill_bytes(&bytes);
558 if &actual_hash != expected_hash {
559 return Err("plugin Skill changed between review hashing and parsing".to_string());
560 }
561 let content = std::str::from_utf8(&bytes)
562 .map_err(|_| "plugin Skill must be valid UTF-8".to_string())?;
563 let (skill, warnings) =
564 match codewhale_skill_install::skill_parse::parse_verified_content(&path, content) {
565 Ok(parsed) => parsed,
566 Err(reason) => {
567 diagnostics.push(PluginDiagnostic::warning(
568 "skill-invalid",
569 reason,
570 Some(path),
571 ));
572 continue;
573 }
574 };
575 for warning in warnings {
576 diagnostics.push(PluginDiagnostic::warning(
577 "skill-invalid",
578 warning,
579 Some(path.clone()),
580 ));
581 }
582 let receipt_path = directory.join("agents/openai.yaml");
583 let mut invocation = skill.invocation;
584 let mut dependencies = Default::default();
585 if let Some(expected_policy_hash) = validated.file_hashes.get(&receipt_path) {
586 let policy_path = validated.canonical_root.join(receipt_path);
587 let policy =
588 read_skill_bytes(&validated.canonical_root, &policy_path).and_then(|bytes| {
589 if hash_skill_bytes(&bytes) != *expected_policy_hash {
590 return Err("plugin Skill policy changed after review".to_string());
591 }
592 if bytes.len() > 16 * 1024 {
593 return Err("plugin Skill policy exceeds the parse limit".to_string());
594 }
595 let text =
596 std::str::from_utf8(&bytes).map_err(|error| error.to_string())?;
597 codewhale_skill_install::frontmatter::codex_skill_metadata(text)
598 });
599 match policy {
600 Ok(metadata) => {
601 if !metadata.allows_implicit_invocation {
602 invocation = invocation.restrict_implicit();
603 }
604 dependencies = metadata.dependencies;
605 }
606 Err(error) => {
607 diagnostics.push(PluginDiagnostic::warning(
608 "skill-invalid",
609 error,
610 Some(policy_path),
611 ));
612 invocation = invocation.restrict_implicit();
613 }
614 }
615 }
616 skill_snapshots.push(PluginSkillSnapshot {
617 name: skill.name,
618 legacy_activation_name: skill.legacy_activation_name,
619 description: skill.description,
620 localized_descriptions: skill.localized_descriptions,
621 invocation,
622 dependencies,
623 aliases: skill.aliases,
624 argument_hint: skill.argument_hint,
625 body: skill.body,
626 path,
627 source_hash: actual_hash,
628 });
629 }
630 }
631 skill_snapshots.sort_by(|left, right| {
632 left.name
633 .cmp(&right.name)
634 .then_with(|| left.path.cmp(&right.path))
635 });
636 let mut seen_skills = BTreeSet::new();
637 for skill in &skill_snapshots {
638 if !seen_skills.insert(skill.name.clone()) {
639 return Err(format!(
640 "plugin `{}` declares duplicate skill name `{}`",
641 validated.manifest.plugin.name, skill.name
642 ));
643 }
644 }
645 Ok((skill_snapshots, diagnostics))
646 }
647
648 fn read_skill_bytes(root: &Path, path: &Path) -> Result<Vec<u8>, String> {
649 use std::io::Read as _;
650 let file = codewhale_util::fs_confined::open_read(root, path)
651 .map_err(|e| format!("failed to open plugin Skill without following links: {e}"))?;
652 let mut bytes = Vec::new();
653 file.take(1024 * 1024 + 1)
654 .read_to_end(&mut bytes)
655 .map_err(|e| format!("failed to read plugin Skill: {e}"))?;
656 if bytes.len() > 1024 * 1024 {
657 return Err("plugin Skill exceeds the one-megabyte parse limit".to_string());
658 }
659 Ok(bytes)
660 }
661
662 fn hash_skill_bytes(bytes: &[u8]) -> String {
663 let mut hasher = Sha256::new();
664 hasher.update(b"codewhale-plugin-file-bytes-v1\0");
665 hasher.update(bytes);
666 hasher
667 .finalize()
668 .iter()
669 .map(|byte| format!("{byte:02x}"))
670 .collect()
671 }
672
673 pub fn load_staged_skill_snapshots(
674 staged_root: &Path,
675 expected_content_hash: &str,
676 expected_capability_hash: &str,
677 ) -> Result<Vec<PluginSkillSnapshot>, String> {
678 load_staged_skill_snapshots_with_roots(
679 staged_root,
680 expected_content_hash,
681 expected_capability_hash,
682 None,
683 )
684 }
685
686 pub fn load_staged_skill_root_snapshots(
687 authority: &codewhale_config::PluginAuthority,
688 relative: &Path,
689 ) -> Result<Vec<PluginSkillSnapshot>, String> {
690 let staged_root = super::agent_plugin::plugin_root_for_manifest(&authority.staged_manifest)
691 .ok_or_else(|| "reviewed plugin has no staged root".to_string())?;
692 let root = staged_root.join(relative);
693 codewhale_util::files::reject_linked_path(staged_root, &root).map_err(|e| e.to_string())?;
694 if !root.is_dir() {
695 return Err("skill root must be a directory inside the reviewed bundle".to_string());
696 }
697 let snapshots = load_staged_skill_snapshots_with_roots(
698 staged_root,
699 &authority.content_hash,
700 &authority.capability_hash,
701 Some(&[root]),
702 )?;
703 if snapshots.is_empty() {
704 return Err("skill root contains no valid reviewed Skills".to_string());
705 }
706 Ok(snapshots)
707 }
708
709 fn load_staged_skill_snapshots_with_roots(
710 staged_root: &Path,
711 expected_content_hash: &str,
712 expected_capability_hash: &str,
713 roots: Option<&[PathBuf]>,
714 ) -> Result<Vec<PluginSkillSnapshot>, String> {
715 let finalized = super::registry::verify_finalized_stage_root(staged_root, None)?;
716 let staged_manifest = resolve_manifest_path(staged_root)
717 .ok_or_else(|| "staged plugin has no plugin.json, .claude-plugin/plugin.json, kimi.plugin.json, or plugin.toml".to_string())?;
718 let validated = PluginManifest::validate_from_path(&staged_manifest)?;
719 if validated.canonical_root != staged_root
720 || validated.content_hash != expected_content_hash
721 || validated.capability_hash != expected_capability_hash
722 {
723 return Err("staged plugin Skill snapshot no longer matches reviewed content".to_string());
724 }
725 let (snapshots, diagnostics) = match roots {
726 Some(roots) => parse_skill_snapshots_for_roots(&validated, roots, true)?,
727 None => parse_skill_snapshots(&validated)?,
728 };
729 if let Some(diagnostic) = diagnostics.first() {
730 return Err(format!(
731 "staged plugin Skill snapshot is invalid: {}",
732 diagnostic.message
733 ));
734 }
735 // Parsing is explicitly bound to the first validation's file inventory;
736 // a final whole-bundle pass also rejects additions/removals/config drift
737 // that occurred during directory traversal.
738 let refreshed = PluginManifest::validate_from_path(&staged_manifest)?;
739 if refreshed.content_hash != validated.content_hash
740 || refreshed.capability_hash != validated.capability_hash
741 || refreshed.file_hashes != validated.file_hashes
742 {
743 return Err("staged plugin changed while its Skill snapshots were parsed".to_string());
744 }
745 super::registry::verify_finalized_stage_root(staged_root, Some(&finalized))?;
746 Ok(snapshots)
747 }
748
749 pub(super) fn plugin_id(scope: PluginScope, name: &str, canonical_root: &Path) -> PluginId {
750 PluginId(format!(
751 "{}/{}/{name}",
752 scope.as_str(),
753 plugin_root_hash(scope, canonical_root)
754 ))
755 }
756
757 /// The path-derived middle segment of a plugin id. It depends only on the
758 /// scope and canonical root, never the manifest name, so a persisted record
759 /// can be matched to a directory on disk even when its manifest no longer parses.
760 pub(super) fn plugin_root_hash(scope: PluginScope, canonical_root: &Path) -> String {
761 let mut hasher = Sha256::new();
762 // v2 intentionally invalidates receipts produced by the former lossy
763 // Unicode path identity.
764 hasher.update(b"codewhale-plugin-id-v2\0");
765 hasher.update(scope.as_str().as_bytes());
766 hasher.update(b"\0");
767 codewhale_util::path_identity::hash_os_path(
768 &mut hasher,
769 b"canonical-plugin-root",
770 canonical_root,
771 );
772 let digest = hasher.finalize();
773 digest[..6]
774 .iter()
775 .map(|byte| format!("{byte:02x}"))
776 .collect::<String>()
777 }
778
779 #[cfg(test)]
780 mod tests {
781 use super::*;
782
783 fn write_plugin(root: &Path, dir: &str, name: &str) -> PathBuf {
784 let plugin = root.join(dir);
785 fs::create_dir_all(&plugin).unwrap();
786 fs::write(
787 plugin.join("plugin.toml"),
788 format!("schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n"),
789 )
790 .unwrap();
791 plugin
792 }
793
794 fn config(tmp: &Path) -> DiscoveryConfig {
795 DiscoveryConfig {
796 workspace: tmp.join("project"),
797 user_plugins_dir: tmp.join("user"),
798 workspace_plugins_dir: tmp.join("workspace"),
799 builtin_plugin_dirs: vec![tmp.join("builtin")],
800 state_path: tmp.join("state.json"),
801 }
802 }
803
804 #[test]
805 fn user_and_workspace_bundles_are_disabled_and_untrusted_by_default() {
806 let tmp = tempfile::tempdir().unwrap();
807 let cfg = config(tmp.path());
808 write_plugin(&cfg.user_plugins_dir, "a", "user-plugin");
809 write_plugin(&cfg.workspace_plugins_dir, "b", "workspace-plugin");
810
811 let registry = discover_with_config(&cfg);
812 assert_eq!(registry.len(), 2);
813 assert!(registry.list().iter().all(|plugin| !plugin.enabled));
814 assert!(registry.list().iter().all(|plugin| !plugin.trusted()));
815 assert!(!cfg.state_path.exists(), "discovery must be read-only");
816 }
817
818 #[test]
819 fn precedence_is_builtin_then_user_then_workspace() {
820 let tmp = tempfile::tempdir().unwrap();
821 let cfg = config(tmp.path());
822 write_plugin(&cfg.builtin_plugin_dirs[0], "z", "same");
823 write_plugin(&cfg.user_plugins_dir, "a", "same");
824 write_plugin(&cfg.workspace_plugins_dir, "b", "same");
825
826 let registry = discover_with_config(&cfg);
827 assert_eq!(registry.len(), 1);
828 assert_eq!(registry.get("same").unwrap().scope, PluginScope::Builtin);
829 assert_eq!(
830 registry
831 .diagnostics()
832 .iter()
833 .filter(|diagnostic| diagnostic.code == "name-conflict")
834 .count(),
835 2
836 );
837 }
838
839 #[test]
840 fn discovery_is_sorted_and_plugin_ids_are_deterministic() {
841 let tmp = tempfile::tempdir().unwrap();
842 let cfg = config(tmp.path());
843 write_plugin(&cfg.user_plugins_dir, "z", "zulu");
844 write_plugin(&cfg.user_plugins_dir, "a", "alpha");
845
846 let first = discover_with_config(&cfg);
847 let second = discover_with_config(&cfg);
848 let names = first
849 .list()
850 .iter()
851 .map(|plugin| plugin.name())
852 .collect::<Vec<_>>();
853 assert_eq!(names, vec!["alpha", "zulu"]);
854 assert_eq!(
855 first.get("alpha").unwrap().id,
856 second.get("alpha").unwrap().id
857 );
858 }
859
860 #[cfg(unix)]
861 #[test]
862 fn plugin_ids_distinguish_lossy_colliding_native_roots() {
863 use std::ffi::OsString;
864 use std::os::unix::ffi::OsStringExt as _;
865
866 let tmp = tempfile::tempdir().unwrap();
867 let left_name = OsString::from_vec(vec![b'p', 0xff]);
868 let right_name = OsString::from_vec(vec![b'p', 0xfe]);
869 assert_eq!(left_name.to_string_lossy(), right_name.to_string_lossy());
870 let left = tmp.path().join(left_name);
871 let right = tmp.path().join(right_name);
872 assert_ne!(
873 plugin_id(PluginScope::User, "same", &left),
874 plugin_id(PluginScope::User, "same", &right)
875 );
876 }
877
878 #[cfg(unix)]
879 #[test]
880 fn symlinked_discovery_root_fails_closed() {
881 use std::os::unix::fs::symlink;
882
883 let tmp = tempfile::tempdir().unwrap();
884 let outside = tempfile::tempdir().unwrap();
885 write_plugin(outside.path(), "a", "outside");
886 let cfg = config(tmp.path());
887 symlink(outside.path(), &cfg.workspace_plugins_dir).unwrap();
888
889 let registry = discover_with_config(&cfg);
890 assert!(registry.is_empty());
891 assert!(
892 registry
893 .diagnostics()
894 .iter()
895 .any(|diagnostic| diagnostic.code == "root-symlink")
896 );
897 }
898
899 #[cfg(windows)]
900 fn create_junction(link: &Path, target: &Path) {
901 let output = std::process::Command::new("cmd")
902 .args(["/C", "mklink", "/J"])
903 .arg(link)
904 .arg(target)
905 .output()
906 .expect("invoke Windows junction creation");
907 assert!(
908 output.status.success(),
909 "failed to create junction: stdout={} stderr={}",
910 String::from_utf8_lossy(&output.stdout),
911 String::from_utf8_lossy(&output.stderr)
912 );
913 }
914
915 #[cfg(windows)]
916 #[test]
917 fn junction_discovery_root_fails_closed() {
918 let tmp = tempfile::tempdir().unwrap();
919 let outside = tempfile::tempdir().unwrap();
920 write_plugin(outside.path(), "a", "outside");
921 let cfg = config(tmp.path());
922 create_junction(&cfg.workspace_plugins_dir, outside.path());
923
924 let registry = discover_with_config(&cfg);
925 assert!(registry.is_empty());
926 assert!(
927 registry
928 .diagnostics()
929 .iter()
930 .any(|diagnostic| diagnostic.code == "root-symlink")
931 );
932 }
933
934 #[cfg(windows)]
935 #[test]
936 fn junction_bundle_entry_fails_closed() {
937 let tmp = tempfile::tempdir().unwrap();
938 let outside = tempfile::tempdir().unwrap();
939 let target = write_plugin(outside.path(), "actual", "outside");
940 let cfg = config(tmp.path());
941 fs::create_dir_all(&cfg.workspace_plugins_dir).unwrap();
942 create_junction(&cfg.workspace_plugins_dir.join("linked"), &target);
943
944 let registry = discover_with_config(&cfg);
945 assert!(registry.is_empty());
946 assert!(
947 registry
948 .diagnostics()
949 .iter()
950 .any(|diagnostic| diagnostic.code == "bundle-symlink")
951 );
952 }
953
954 #[test]
955 fn discovery_ignores_ambient_compatibility_roots() {
956 let _lock = codewhale_runtime::test_support::lock_test_env();
957 let tmp = tempfile::tempdir().unwrap();
958 let home = tmp.path().join("home");
959 let workspace = tmp.path().join("workspace");
960 let _home = codewhale_runtime::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
961 write_plugin(
962 &workspace.join(".claude/plugins"),
963 "ambient",
964 "ambient-plugin",
965 );
966 write_plugin(
967 &workspace.join(".cursor/plugins"),
968 "ambient",
969 "cursor-plugin",
970 );
971
972 let discovery = crate::PluginDiscoveryContext::capture_pre_dotenv();
973 let registry = discovery.registry_for_workspace(&workspace);
974 assert!(registry.get("ambient-plugin").is_none());
975 assert!(registry.get("cursor-plugin").is_none());
976 // Only what Codewhale itself ships is present: no ambient root loaded.
977 assert_eq!(
978 registry
979 .list()
980 .iter()
981 .filter(|plugin| plugin.scope != PluginScope::Builtin)
982 .count(),
983 0
984 );
985 assert!(!home.join("plugins/state.json").exists());
986 }
987 }
988
989 #[cfg(test)]
990 #[path = "discovery_internal_paths_tests.rs"]
991 mod internal_publication_tests;
992
992 lines RUST