返回 CodeWhale
skills.rs
根目录 / crates / engine / src / extension_host / skills.rs
1 //! Owned reviewed roots feed the existing SkillRegistry; no parser or store here.
2 use std::path::{Component, Path, PathBuf};
3 use std::sync::Arc;
4 use std::sync::atomic::Ordering;
5
6 use codewhale_skills::NativeSkillRef;
7
8 use super::ManagerShared;
9 use super::protocol::{RegisterParams, RegisterResult};
10 use super::supervisor::HostRequestContext;
11 use super::tier::{HostCohort, HostTier};
12 use codewhale_config::OwnerRef;
13 use codewhale_config::PluginAuthority;
14 use codewhale_plugins::activation::PluginActivationCapability;
15 use codewhale_plugins::types::PluginSkillSnapshot;
16
17 pub use codewhale_plugins::discovery::{MAX_BYTES_PER_OWNER, MAX_SKILLS_PER_OWNER};
18 pub const MAX_ROOTS_PER_OWNER: usize = 8;
19 pub const MAX_ROOTS_PER_HOST: usize = 64;
20 pub const MAX_SKILLS_PER_HOST: usize = 1024;
21 pub const MAX_BYTES_PER_HOST: usize = 32 * 1024 * 1024;
22
23 #[derive(Debug, Clone)]
24 pub struct SkillRootRegistration {
25 pub handle: u64,
26 pub owner: OwnerRef,
27 pub scope: Option<codewhale_config::EntryRef>,
28 pub host_generation: u64,
29 pub content_hash: String,
30 pub path: String,
31 pub snapshots: Vec<PluginSkillSnapshot>,
32 pub bytes: usize,
33 }
34
35 pub fn root_path(path: &str) -> Result<PathBuf, String> {
36 if path.is_empty()
37 || path.len() > 512
38 || path
39 .chars()
40 .any(|c| c.is_control() || matches!(c, '\\' | ':'))
41 || path
42 .split('/')
43 .any(|part| part.is_empty() || matches!(part, "." | ".."))
44 || Path::new(path)
45 .components()
46 .any(|component| !matches!(component, Component::Normal(_)))
47 {
48 return Err("skill root must be a bounded bundle-relative path with normal slash-separated components".to_string());
49 }
50 Ok(PathBuf::from(path))
51 }
52
53 pub fn snapshot_bytes(skill: &PluginSkillSnapshot) -> usize {
54 skill.name.len()
55 + skill.description.len()
56 + skill.body.len()
57 + skill.source_hash.len()
58 + skill.legacy_activation_name.as_ref().map_or(0, String::len)
59 + skill.argument_hint.as_ref().map_or(0, String::len)
60 + skill.aliases.iter().map(String::len).sum::<usize>()
61 + skill
62 .localized_descriptions
63 .iter()
64 .map(|(key, value)| key.len() + value.len())
65 .sum::<usize>()
66 }
67
68 /// The existing asynchronous request seam performs disk work outside every
69 /// registry lock; final admission rechecks cancellation and exact lifetimes.
70 pub(super) async fn admit_root(
71 shared: &Arc<ManagerShared>,
72 cohort: &HostCohort,
73 host_generation: u64,
74 params: RegisterParams,
75 cx: &HostRequestContext,
76 ) -> RegisterResult {
77 let result = async {
78 params.check_spec()?;
79 if !params.spec.description.is_empty() {
80 return Err("skill root has no description".to_string());
81 }
82 let relative = root_path(&params.spec.name)?;
83 if cohort.tier() != HostTier::Plugin {
84 return Err("skill roots require a reviewed plugin bundle".to_string());
85 }
86 let authority = shared
87 .live_owner_authority(cohort, |registry| {
88 registry
89 .authority_for(&params.owner)
90 .ok_or_else(|| "stale or unknown skill owner".to_string())?;
91 Ok(params.owner.clone())
92 })?
93 .ok_or_else(|| "skill owner has no reviewed authority".to_string())?;
94 let snapshots =
95 bounded_review_check(Arc::clone(&shared.skill_admission), &cx.cancel, move || {
96 // One permit covers every disk check, including the Native receipt
97 // phase; cancellation never leaves that phase outside the bound.
98 codewhale_plugins::registry::verify_plugin_component_authority(
99 &authority,
100 PluginActivationCapability::Native,
101 )?;
102 let snapshots = codewhale_plugins::discovery::load_staged_skill_root_snapshots(
103 &authority, &relative,
104 )?;
105 codewhale_plugins::registry::verify_plugin_component_authority(
106 &authority,
107 PluginActivationCapability::Native,
108 )?;
109 Ok(snapshots)
110 })
111 .await?;
112 shared
113 .ready_host(cohort)
114 .map_err(|status| status.to_string())?;
115 let runtime = shared
116 .cohort_runtime(cohort)
117 .ok_or_else(|| "cohort runtime gone".to_string())?;
118 let _slot = runtime.host.lock().expect("host lock");
119 if runtime.host_generation.load(Ordering::SeqCst) != host_generation
120 || cx.cancel.is_cancelled()
121 {
122 return Err(
123 "skill root host generation changed or admission was cancelled".to_string(),
124 );
125 }
126 shared
127 .registry
128 .lock()
129 .expect("registry lock")
130 .register_skill_root(&params, snapshots, host_generation)
131 }
132 .await;
133 match result {
134 Ok(handle) => RegisterResult::Admitted { handle },
135 Err(refused) => {
136 shared.plugin_diagnostic(
137 &params.owner.plugin_id,
138 format!("skill root refused: {refused}"),
139 );
140 RegisterResult::Refused { refused }
141 }
142 }
143 }
144
145 /// Every Native root or MCP disk phase uses this job. Its permit belongs to the
146 /// blocking closure, so RPC cancellation or abandonment cannot release it
147 /// until receipt validation and parsing actually stop.
148 pub(super) async fn bounded_review_check<T: Send + 'static>(
149 admission: Arc<tokio::sync::Semaphore>,
150 cancel: &tokio_util::sync::CancellationToken,
151 check: impl FnOnce() -> Result<T, String> + Send + 'static,
152 ) -> Result<T, String> {
153 if cancel.is_cancelled() {
154 return Err("Native review admission cancelled".to_string());
155 }
156 let permit = tokio::select! {
157 _ = cancel.cancelled() => return Err("Native review admission cancelled".to_string()),
158 permit = admission.acquire_owned() => permit.map_err(|_| "Native review admission is unavailable".to_string())?,
159 };
160 if cancel.is_cancelled() {
161 return Err("Native review admission cancelled".to_string());
162 }
163 let policy = super::activation::extension_host_policy_enabled();
164 #[cfg(any(test, feature = "test-support"))]
165 let env_scope = crate::test_support::env_scope_ticket();
166 let work = tokio::task::spawn_blocking(move || {
167 let _permit = permit;
168 #[cfg(any(test, feature = "test-support"))]
169 let _env_scope = crate::test_support::join_env_scope(env_scope);
170 let _policy = codewhale_plugins::activation::PolicyScope::propagate(policy);
171 check()
172 });
173 tokio::select! {
174 _ = cancel.cancelled() => Err("Native review admission cancelled".to_string()),
175 result = work => result.map_err(|error| format!("Native review check failed: {error}"))?,
176 }
177 }
178
179 fn live(
180 manager: &super::ExtensionHostManager,
181 authority: &PluginAuthority,
182 reference: &NativeSkillRef,
183 ) -> Result<(), String> {
184 if reference.boot_id != crate::session_manager::current_session_boot_id() {
185 return Err(
186 "native skill belongs to an earlier Codewhale process; select the skill again"
187 .to_string(),
188 );
189 }
190 if !super::activation::extension_host_policy_enabled() {
191 return Err("plugin host is disabled".to_string());
192 }
193 let cohort = manager
194 .shared
195 .registry
196 .lock()
197 .expect("registry lock")
198 .cohort_of_plugin_id(authority.plugin_id.as_str())
199 .ok_or_else(|| "native skill owner has no cohort".to_string())?;
200 let host = manager
201 .shared
202 .ready_host(&cohort)
203 .map_err(|status| status.to_string())?;
204 if host.generation != reference.host_generation {
205 return Err("native skill host restarted; select the skill again".to_string());
206 }
207 let registry = manager.shared.registry.lock().expect("registry lock");
208 if !registry.is_live_skill_root(
209 reference.handle,
210 authority.plugin_id.as_str(),
211 reference.owner_generation,
212 reference.host_generation,
213 &authority.content_hash,
214 authority.state_generation,
215 ) {
216 return Err(
217 "native skill registration was disposed, revoked or replaced; select the skill again"
218 .to_string(),
219 );
220 }
221 Ok(())
222 }
223
224 pub fn verify_native_skill(
225 authority: &PluginAuthority,
226 reference: &NativeSkillRef,
227 ) -> Result<(), String> {
228 let manager = super::manager();
229 if reference.scope.is_some()
230 && !reference.selection.is_some_and(|selected| {
231 manager.shared.selection_current(
232 selected,
233 authority.plugin_id.as_str(),
234 &authority.content_hash,
235 reference.scope.as_ref(),
236 )
237 })
238 {
239 return Err("Native skill is no longer selected".into());
240 }
241 live(&manager, authority, reference)?;
242 codewhale_plugins::registry::verify_plugin_component_authority(
243 authority,
244 PluginActivationCapability::Native,
245 )?;
246 // Full receipt validation does disk I/O; do not accept a registration
247 // removed while that check was in progress.
248 live(&manager, authority, reference)?;
249 if reference.scope.is_some()
250 && !reference.selection.is_some_and(|selected| {
251 manager.shared.selection_current(
252 selected,
253 authority.plugin_id.as_str(),
254 &authority.content_hash,
255 reference.scope.as_ref(),
256 )
257 })
258 {
259 return Err("Native skill selection changed during verification".into());
260 }
261 Ok(())
262 }
263
264 /// Caller-snapshot scope, rather than the first workspace that activated an
265 /// owner. All normal discovery consumers use this one existing catalog merge.
266 pub fn roots_for_plugins(
267 plugins: &codewhale_plugins::PluginRegistry,
268 ) -> Vec<(SkillRootRegistration, PluginAuthority, NativeSkillRef)> {
269 if !super::activation::extension_host_policy_enabled() {
270 return Vec::new();
271 }
272 if plugins.state_path().is_none() {
273 return Vec::new();
274 }
275 let manager = super::manager();
276 let roots = manager
277 .shared
278 .registry
279 .lock()
280 .expect("registry lock")
281 .live_skill_roots();
282 let mut selected: Vec<_> = roots
283 .into_iter()
284 .filter_map(|root| {
285 let plugin = plugins.get(&root.owner.plugin_id)?;
286 if !plugin.component_active(PluginActivationCapability::Native)
287 || plugin.content_hash != root.content_hash
288 {
289 return None;
290 }
291 let authority = plugins.authority_for(plugin.id.as_str())?;
292 let selected = plugins.caller_selection();
293 if root.scope.is_some()
294 && !selected.is_some_and(|selection| {
295 manager.shared.selection_current(
296 selection,
297 &root.owner.plugin_id,
298 &root.content_hash,
299 root.scope.as_ref(),
300 )
301 })
302 {
303 return None;
304 }
305 let reference = NativeSkillRef {
306 boot_id: crate::session_manager::current_session_boot_id().to_string(),
307 host_generation: root.host_generation,
308 owner_generation: root.owner.generation,
309 handle: root.handle,
310 selection: selected,
311 scope: root.scope.clone(),
312 };
313 verify_native_skill(&authority, &reference).ok()?;
314 Some((root, authority, reference))
315 })
316 .collect();
317 let mut counts = std::collections::BTreeMap::new();
318 for (root, _, _) in &selected {
319 for skill in &root.snapshots {
320 *counts
321 .entry((root.owner.plugin_id.clone(), skill.name.clone()))
322 .or_insert(0usize) += 1;
323 }
324 }
325 for (root, _, _) in &mut selected {
326 root.snapshots
327 .retain(|skill| counts[&(root.owner.plugin_id.clone(), skill.name.clone())] == 1);
328 }
329 selected.retain(|(root, _, _)| !root.snapshots.is_empty());
330 selected
331 }
332
333 #[cfg(test)]
334 mod tests {
335 use super::*;
336 use crate::extension_host::protocol::{RegisterKind, RegisterSpecWire};
337 use crate::extension_host::registry::OwnerRegistry;
338 use crate::extension_host::test_support::{FixturePlugins, fake_authority, node_for_tests};
339 use crate::tools::spec::{ToolContext, ToolSpec};
340 use codewhale_plugins::activation::TestPolicyGuard;
341 use codewhale_skill_install::skill_parse::SkillInvocation;
342 use codewhale_skills::{SkillDiscoveryMode, SkillProvenance};
343 use std::collections::HashMap;
344
345 fn params(owner: &OwnerRef, path: &str) -> RegisterParams {
346 RegisterParams {
347 scope: None,
348 owner: owner.clone(),
349 kind: RegisterKind::SkillRoot,
350 spec: RegisterSpecWire {
351 name: path.to_string(),
352 description: String::new(),
353 input_schema: None,
354 argument_hint: None,
355 },
356 }
357 }
358 fn owner(registry: &mut OwnerRegistry, id: &str) -> OwnerRef {
359 registry
360 .begin_owner(
361 HostCohort::reviewed(),
362 id,
363 id,
364 Some(fake_authority(id)),
365 &format!("hash-{id}"),
366 )
367 .unwrap()
368 }
369 fn snapshot(name: &str, body: String) -> PluginSkillSnapshot {
370 PluginSkillSnapshot {
371 name: name.to_string(),
372 legacy_activation_name: None,
373 description: "focused fixture".to_string(),
374 localized_descriptions: HashMap::new(),
375 invocation: SkillInvocation::ModelAndUser,
376 dependencies: Default::default(),
377 aliases: Vec::new(),
378 argument_hint: None,
379 body,
380 path: PathBuf::from(format!("/staged/skills/{name}/SKILL.md")),
381 source_hash: "0".repeat(64),
382 }
383 }
384
385 #[tokio::test(flavor = "current_thread")]
386 async fn cancelled_native_root_disk_job_keeps_admission_permit_until_completion() {
387 // Exercise the production helper for both cooperative cancellation and
388 // a channel abandoning its handler. A blocked first disk phase cannot
389 // release its permit or start another queued check in either case.
390 for abandon_handler in [false, true] {
391 let admission = Arc::new(tokio::sync::Semaphore::new(1));
392 let cancel = tokio_util::sync::CancellationToken::new();
393 let (entered, started) = tokio::sync::oneshot::channel();
394 let (release, wait) = std::sync::mpsc::channel();
395 let running_admission = Arc::clone(&admission);
396 let running_cancel = cancel.clone();
397 let running = tokio::spawn(async move {
398 bounded_review_check(running_admission, &running_cancel, move || {
399 let _ = entered.send(());
400 wait.recv().map_err(|error| error.to_string())?;
401 Ok(7)
402 })
403 .await
404 });
405 started.await.unwrap();
406 if abandon_handler {
407 running.abort();
408 assert!(running.await.unwrap_err().is_cancelled());
409 } else {
410 cancel.cancel();
411 assert!(running.await.unwrap().unwrap_err().contains("cancelled"));
412 }
413 assert_eq!(
414 admission.available_permits(),
415 0,
416 "cancelled handler must not release the live disk job's permit"
417 );
418 let queued_cancel = tokio_util::sync::CancellationToken::new();
419 let ran = Arc::new(std::sync::atomic::AtomicBool::new(false));
420 let queued_ran = Arc::clone(&ran);
421 let queued_admission = Arc::clone(&admission);
422 let queued_token = queued_cancel.clone();
423 let queued = tokio::spawn(async move {
424 bounded_review_check(queued_admission, &queued_token, move || {
425 queued_ran.store(true, Ordering::SeqCst);
426 Ok(9)
427 })
428 .await
429 });
430 tokio::task::yield_now().await;
431 queued_cancel.cancel();
432 assert!(queued.await.unwrap().is_err());
433 assert!(
434 !ran.load(Ordering::SeqCst),
435 "a cancelled queued check never enters the blocking pool"
436 );
437 release.send(()).unwrap();
438 let resumed = tokio::time::timeout(
439 std::time::Duration::from_secs(2),
440 bounded_review_check(
441 Arc::clone(&admission),
442 &tokio_util::sync::CancellationToken::new(),
443 || Ok(11),
444 ),
445 )
446 .await
447 .unwrap()
448 .unwrap();
449 assert_eq!(
450 resumed, 11,
451 "completed disk work releases admission for the next live owner"
452 );
453 assert_eq!(admission.available_permits(), 1);
454 }
455 }
456
457 #[test]
458 fn skill_root_paths_are_bounded_and_bundle_relative() {
459 assert!(root_path("profiles/review-skills").is_ok());
460 for path in [
461 "",
462 "/absolute",
463 "../outside",
464 "./same",
465 "a/../b",
466 "a//b",
467 "a/",
468 "C:/disk",
469 "a\\b",
470 "a\u{1b}b",
471 ] {
472 assert!(root_path(path).is_err(), "{path:?}");
473 }
474 assert!(root_path(&"界".repeat(171)).is_err());
475 }
476
477 #[test]
478 fn skill_root_withdrawal_is_exact_and_owner_generation_is_not_reusable() {
479 let mut registry = OwnerRegistry::new();
480 let a = owner(&mut registry, "a");
481 let b = owner(&mut registry, "b");
482 let handle = registry
483 .register_skill_root(
484 &params(&a, "skills"),
485 vec![snapshot("one", "body".into())],
486 7,
487 )
488 .unwrap();
489 assert!(registry.live_skill_roots().is_empty());
490 registry.mark_active(&a);
491 assert!(registry.is_live_skill_root(handle, "a", a.generation, 7, "hash-a", 1));
492 registry.unregister(&b, handle);
493 assert_eq!(registry.live_skill_roots().len(), 1);
494 registry.unregister(&a, handle);
495 assert!(registry.live_skill_roots().is_empty());
496 let next = registry
497 .register_skill_root(
498 &params(&a, "skills"),
499 vec![snapshot("one", "body".into())],
500 7,
501 )
502 .unwrap();
503 assert_ne!(handle, next);
504 registry.revoke_owner("a");
505 let replacement = owner(&mut registry, "a");
506 registry.mark_active(&replacement);
507 assert!(!registry.is_live_skill_root(next, "a", a.generation, 7, "hash-a", 1));
508 assert!(
509 registry
510 .register_skill_root(
511 &params(&a, "skills"),
512 vec![snapshot("one", "body".into())],
513 7
514 )
515 .is_err()
516 );
517 }
518
519 #[test]
520 fn skill_root_caps_retire_on_plugin_exit_and_preserve_other_tier() {
521 let mut registry = OwnerRegistry::new();
522 for index in 0..8 {
523 let current = owner(&mut registry, &format!("p{index}"));
524 for root in 0..8 {
525 registry
526 .register_skill_root(
527 &params(&current, &format!("s{root}")),
528 vec![snapshot(&format!("skill{root}"), "body".into())],
529 7,
530 )
531 .unwrap();
532 }
533 registry.mark_active(&current);
534 }
535 let extra = owner(&mut registry, "extra");
536 assert!(
537 registry
538 .register_skill_root(
539 &params(&extra, "skills"),
540 vec![snapshot("one", "body".into())],
541 7
542 )
543 .is_err()
544 );
545 registry.host_exited(HostCohort::Builtin, "builtin crash");
546 assert_eq!(registry.live_skill_roots().len(), MAX_ROOTS_PER_HOST);
547 registry.host_exited(HostCohort::reviewed(), "plugin crash");
548 assert!(registry.live_skill_roots().is_empty());
549 let replacement = owner(&mut registry, "replacement");
550 registry
551 .register_skill_root(
552 &params(&replacement, "skills"),
553 vec![snapshot("one", "body".into())],
554 8,
555 )
556 .unwrap();
557 registry.revoke_all(HostCohort::reviewed(), "shutdown");
558 let restarted = owner(&mut registry, "replacement");
559 registry
560 .register_skill_root(
561 &params(&restarted, "skills"),
562 vec![snapshot("one", "body".into())],
563 9,
564 )
565 .unwrap();
566 }
567
568 #[test]
569 fn skill_root_admission_enforces_owner_count_bytes_and_duplicate_names() {
570 let mut registry = OwnerRegistry::new();
571 let current = owner(&mut registry, "a");
572 assert!(
573 registry
574 .register_skill_root(
575 &params(&current, "oversized"),
576 vec![snapshot("big", "x".repeat(MAX_BYTES_PER_OWNER))],
577 7
578 )
579 .is_err()
580 );
581 assert!(
582 registry
583 .register_skill_root(
584 &params(&current, "too-many"),
585 (0..129)
586 .map(|i| snapshot(&format!("s{i}"), "x".into()))
587 .collect(),
588 7
589 )
590 .is_err()
591 );
592 registry
593 .register_skill_root(
594 &params(&current, "first"),
595 vec![snapshot("one", "x".into())],
596 7,
597 )
598 .unwrap();
599 assert!(
600 registry
601 .register_skill_root(
602 &params(&current, "second"),
603 vec![snapshot("one", "x".into())],
604 7
605 )
606 .is_err()
607 );
608 for i in 1..8 {
609 registry
610 .register_skill_root(
611 &params(&current, &format!("r{i}")),
612 vec![snapshot(&format!("s{i}"), "x".into())],
613 7,
614 )
615 .unwrap();
616 }
617 assert!(
618 registry
619 .register_skill_root(
620 &params(&current, "ninth"),
621 vec![snapshot("last", "x".into())],
622 7
623 )
624 .is_err()
625 );
626 }
627
628 #[test]
629 fn queued_skill_provenance_preserves_legacy_receipts_and_rejects_process_restart() {
630 super::super::install_ports();
631 let authority = fake_authority("a");
632 let legacy = serde_json::to_string(&authority).unwrap();
633 let parsed: SkillProvenance = serde_json::from_str(&legacy).unwrap();
634 assert_eq!(serde_json::to_string(&parsed).unwrap(), legacy);
635 assert!(parsed.authority().managed_policy_source.is_none());
636 let mut old_receipt = serde_json::to_value(&authority).unwrap();
637 old_receipt
638 .as_object_mut()
639 .unwrap()
640 .remove("managed_policy_path");
641 let old_receipt: SkillProvenance = serde_json::from_value(old_receipt).unwrap();
642 assert!(old_receipt.authority().managed_policy_path.is_none());
643 assert!(
644 codewhale_plugins::registry::verify_plugin_state_authority(old_receipt.authority())
645 .unwrap_err()
646 .contains("managed policy source")
647 );
648 let provenance = SkillProvenance::NativeRoot(codewhale_skills::NativeSkillProvenance {
649 authority: authority.clone(),
650 registration: NativeSkillRef {
651 selection: None,
652 scope: None,
653 boot_id: "earlier-process".into(),
654 host_generation: 1,
655 owner_generation: 1,
656 handle: 1,
657 },
658 });
659 let restored: SkillProvenance =
660 serde_json::from_str(&serde_json::to_string(&provenance).unwrap()).unwrap();
661 assert!(
662 restored
663 .verify(&authority.workspace)
664 .unwrap_err()
665 .contains("earlier Codewhale process")
666 );
667 assert!(
668 restored
669 .verify(Path::new("/other"))
670 .unwrap_err()
671 .contains("different workspace")
672 );
673 }
674
675 fn parser_bundle(skills: usize, bytes: usize) -> (tempfile::TempDir, PluginAuthority) {
676 let temp = tempfile::tempdir().unwrap();
677 std::fs::write(temp.path().join("plugin.json"), r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"bounded-skills","version":"0.1.0","description":"bounded fixture","extensions":{"net.codewhale":{"native":{"path":"index.mjs"}}}}"#).unwrap();
678 std::fs::write(
679 temp.path().join("index.mjs"),
680 "export function apply() {}\n",
681 )
682 .unwrap();
683 for index in 0..skills {
684 let directory = temp.path().join("skills").join(format!("s{index}"));
685 std::fs::create_dir_all(&directory).unwrap();
686 std::fs::write(
687 directory.join("SKILL.md"),
688 format!(
689 "---\nname: s{index}\ndescription: bounded fixture\n---\n{}",
690 "x".repeat(bytes)
691 ),
692 )
693 .unwrap();
694 }
695 let validated = codewhale_plugins::manifest::PluginManifest::validate_from_path(
696 &temp.path().join("plugin.json"),
697 )
698 .unwrap();
699 let mut authority = fake_authority("bounded-skills");
700 authority.staged_manifest = validated.canonical_root.join("plugin.json");
701 authority.content_hash = validated.content_hash;
702 authority.capability_hash = validated.capability_hash;
703 (temp, authority)
704 }
705
706 #[test]
707 fn reviewed_skill_root_parser_bounds_accumulation_and_parent_claims() {
708 let (many, authority) = parser_bundle(129, 1);
709 let _many_stage =
710 codewhale_plugins::test_fixture::finalize_staged_bundle(many.path()).unwrap();
711 assert!(
712 codewhale_plugins::discovery::load_staged_skill_root_snapshots(
713 &authority,
714 Path::new("skills")
715 )
716 .unwrap_err()
717 .contains("candidate count")
718 );
719 let (large, authority) = parser_bundle(8, 600 * 1024);
720 let _large_stage =
721 codewhale_plugins::test_fixture::finalize_staged_bundle(large.path()).unwrap();
722 assert!(
723 codewhale_plugins::discovery::load_staged_skill_root_snapshots(
724 &authority,
725 Path::new("skills")
726 )
727 .unwrap_err()
728 .contains("byte limit")
729 );
730 let (one, mut authority) = parser_bundle(1, 1);
731 let nested = one.path().join("skills/s0/examples/nested");
732 std::fs::create_dir_all(&nested).unwrap();
733 std::fs::write(
734 nested.join("SKILL.md"),
735 "---\nname: nested\ndescription: nested fixture\n---\nbody",
736 )
737 .unwrap();
738 let validated = codewhale_plugins::manifest::PluginManifest::validate_from_path(
739 &authority.staged_manifest,
740 )
741 .unwrap();
742 authority.content_hash = validated.content_hash;
743 authority.capability_hash = validated.capability_hash;
744 let _one_stage =
745 codewhale_plugins::test_fixture::finalize_staged_bundle(one.path()).unwrap();
746 let snapshots = codewhale_plugins::discovery::load_staged_skill_root_snapshots(
747 &authority,
748 Path::new("skills"),
749 )
750 .unwrap();
751 assert_eq!(
752 snapshots
753 .iter()
754 .map(|s| s.name.as_str())
755 .collect::<Vec<_>>(),
756 ["s0"]
757 );
758 }
759
760 #[test]
761 fn declared_and_native_reviewed_roots_share_nested_hidden_and_depth_semantics() {
762 let (temp, _) = parser_bundle(1, 1);
763 let skill_root = temp.path().join("skills");
764 for (relative, name) in [
765 ("vendor/organized", "organized"),
766 ("s0/examples/nested", "nested"),
767 (".hidden/hidden", "hidden"),
768 ("a/b/c/d/e/f/g/h/deep8", "deep8"),
769 ("a/b/c/d/e/f/g/h/i/deep9", "deep9"),
770 ] {
771 let directory = skill_root.join(relative);
772 std::fs::create_dir_all(&directory).unwrap();
773 std::fs::write(
774 directory.join("SKILL.md"),
775 format!("---\nname: {name}\ndescription: parity fixture\n---\n{name} body"),
776 )
777 .unwrap();
778 }
779 std::fs::remove_file(temp.path().join("plugin.json")).unwrap();
780 let manifest = temp.path().join("plugin.toml");
781 std::fs::write(&manifest, "schema_version = 1\n[plugin]\nname = \"bounded-skills\"\nversion = \"0.1.0\"\n[skills]\npath = \"skills\"\n[native]\npath = \"index.mjs\"\n").unwrap();
782 let validated =
783 codewhale_plugins::manifest::PluginManifest::validate_from_path(&manifest).unwrap();
784 let _stage = codewhale_plugins::test_fixture::finalize_staged_bundle(temp.path()).unwrap();
785 let declared = codewhale_plugins::discovery::load_staged_skill_snapshots(
786 &validated.canonical_root,
787 &validated.content_hash,
788 &validated.capability_hash,
789 )
790 .unwrap();
791 let mut authority = fake_authority("bounded-skills");
792 authority.staged_manifest = validated.canonical_root.join("plugin.toml");
793 authority.content_hash = validated.content_hash;
794 authority.capability_hash = validated.capability_hash;
795 let native = codewhale_plugins::discovery::load_staged_skill_root_snapshots(
796 &authority,
797 Path::new("skills"),
798 )
799 .unwrap();
800 let baseline = codewhale_skills::SkillRegistry::discover(&skill_root);
801 let projection = |snapshots: &[PluginSkillSnapshot]| {
802 snapshots
803 .iter()
804 .map(|skill| (skill.name.clone(), skill.body.clone()))
805 .collect::<std::collections::BTreeMap<_, _>>()
806 };
807 let expected = baseline
808 .list()
809 .iter()
810 .map(|skill| (skill.name.clone(), skill.body.clone()))
811 .collect::<std::collections::BTreeMap<_, _>>();
812 assert_eq!(
813 expected.keys().map(String::as_str).collect::<Vec<_>>(),
814 ["deep8", "organized", "s0"]
815 );
816 assert_eq!(projection(&declared), expected);
817 assert_eq!(projection(&native), expected);
818 }
819
820 #[tokio::test(flavor = "current_thread")]
821 async fn native_only_root_reaches_shared_catalog_model_tool_and_queued_provenance() {
822 let Some(node) = node_for_tests(
823 "native_only_root_reaches_shared_catalog_model_tool_and_queued_provenance",
824 ) else {
825 return;
826 };
827 let _home = crate::test_support::SealedHome::new();
828 let _policy = TestPolicyGuard::extension_host(true);
829 let fixture = FixturePlugins::new(&["skills-root"]).await;
830 let plugins = fixture.registry();
831 let plugin = plugins.get("skills-root").unwrap();
832 assert_eq!(plugin.inventory.skills, 0);
833 assert!(
834 plugin.skill_snapshots.is_empty(),
835 "fixture has no declarative Skill adapter snapshots"
836 );
837 let manager = fixture.manager(node);
838 let _manager = super::super::TestManagerGuard::install(Arc::clone(&manager));
839 let engine = manager.attach(Arc::clone(&plugins));
840 engine.sync().await.unwrap();
841 let plugins = engine.plugin_view();
842 let skills_dir = fixture.workspace().join("empty-skills");
843 let catalog = codewhale_skills::discover_for_workspace_and_dir_with_mode_and_plugins(
844 fixture.workspace(),
845 &skills_dir,
846 SkillDiscoveryMode::CodeWhaleOnly,
847 Some(&plugins),
848 );
849 let skill = catalog
850 .get("skills-root:quick-check")
851 .expect("Native-only root merged into existing catalog");
852 assert!(skill.invocation.user_invocable());
853 let provenance = skill.source.provenance().unwrap();
854 provenance
855 .verify_for(fixture.workspace(), Some(&plugins))
856 .unwrap();
857 let block = codewhale_skills::render_available_skills_context_for_workspace_and_dir_with_mode_and_plugins(fixture.workspace(), &skills_dir, SkillDiscoveryMode::CodeWhaleOnly, "en", Some(&plugins), codewhale_skills::SkillListingConfig::default(), 8192).unwrap();
858 assert!(block.contains("skills-root:quick-check"));
859 let context =
860 ToolContext::new(fixture.workspace()).with_plugin_registry(Arc::clone(&plugins));
861 let result = crate::tools::skill::LoadSkillTool
862 .execute(
863 serde_json::json!({"name":"skills-root:quick-check"}),
864 &context,
865 )
866 .await
867 .unwrap();
868 assert!(result.content.contains("Inspect the exact source"));
869 assert!(result.metadata.as_ref().unwrap()["skill_path"].is_null());
870 let restored: SkillProvenance =
871 serde_json::from_str(&serde_json::to_string(&provenance).unwrap()).unwrap();
872 let root = manager
873 .shared
874 .registry
875 .lock()
876 .unwrap()
877 .live_skill_roots()
878 .pop()
879 .unwrap();
880 manager
881 .shared
882 .registry
883 .lock()
884 .unwrap()
885 .unregister(&root.owner, root.handle);
886 assert!(
887 restored
888 .verify_for(fixture.workspace(), Some(&plugins))
889 .is_err()
890 );
891 let empty = codewhale_skills::discover_for_workspace_and_dir_with_mode_and_plugins(
892 fixture.workspace(),
893 &skills_dir,
894 SkillDiscoveryMode::CodeWhaleOnly,
895 Some(&plugins),
896 );
897 assert!(
898 empty.get("skills-root:quick-check").is_none(),
899 "the cache must not retain disposed roots"
900 );
901 manager.shutdown().await;
902 }
903
904 #[tokio::test(flavor = "current_thread")]
905 async fn native_skill_receipt_refuses_disable_source_tamper_and_host_restart() {
906 let Some(node) =
907 node_for_tests("native_skill_receipt_refuses_disable_source_tamper_and_host_restart")
908 else {
909 return;
910 };
911 let _home = crate::test_support::SealedHome::new();
912 let _policy = TestPolicyGuard::extension_host(true);
913 let fixture = FixturePlugins::new(&["skills-root"]).await;
914 let plugins = fixture.registry();
915 let manager = fixture.manager(node);
916 let _manager = super::super::TestManagerGuard::install(Arc::clone(&manager));
917 let engine = manager.attach(Arc::clone(&plugins));
918 engine.sync().await.unwrap();
919 let plugins = engine.plugin_view();
920 let catalog = codewhale_skills::discover_in_workspace_with_mode_and_plugins(
921 fixture.workspace(),
922 SkillDiscoveryMode::CodeWhaleOnly,
923 Some(&plugins),
924 );
925 let provenance = catalog
926 .get("skills-root:quick-check")
927 .unwrap()
928 .source
929 .provenance()
930 .unwrap();
931 manager.shutdown().await;
932 assert!(
933 provenance
934 .verify_for(fixture.workspace(), Some(&plugins))
935 .is_err()
936 );
937 let id = plugins.get("skills-root").unwrap().id.as_str();
938 assert!(matches!(
939 manager.owner_state(id),
940 Some(super::super::registry::OwnerState::Failed(_))
941 ));
942 engine.sync().await.unwrap();
943 assert!(
944 manager
945 .shared
946 .registry
947 .lock()
948 .unwrap()
949 .live_skill_roots()
950 .is_empty(),
951 "unchanged failed activations require an explicit retry"
952 );
953 manager.retry();
954 engine.sync().await.unwrap();
955 assert_eq!(
956 manager.owner_state(id),
957 Some(super::super::registry::OwnerState::Active),
958 "owner: {:?}; diagnostics: {:?}",
959 manager.owner_state(id),
960 manager.diagnostics()
961 );
962 assert!(
963 provenance
964 .verify_for(fixture.workspace(), Some(&plugins))
965 .is_err(),
966 "restart must not revive old handles"
967 );
968 let current = codewhale_skills::discover_in_workspace_with_mode_and_plugins(
969 fixture.workspace(),
970 SkillDiscoveryMode::CodeWhaleOnly,
971 Some(&plugins),
972 );
973 let current = current
974 .get("skills-root:quick-check")
975 .unwrap_or_else(|| {
976 panic!(
977 "Native root missing after explicit retry; owner: {:?}; diagnostics: {:?}",
978 manager.owner_state(id),
979 manager.diagnostics()
980 )
981 })
982 .source
983 .provenance()
984 .unwrap();
985 let source_root = codewhale_plugins::agent_plugin::plugin_root_for_manifest(
986 &current.authority().source_manifest,
987 )
988 .unwrap();
989 let source_skill = source_root.join("profiles/review-skills/quick-check/SKILL.md");
990 let reviewed = std::fs::read(&source_skill).unwrap();
991 std::fs::write(&source_skill, "changed after review").unwrap();
992 assert!(
993 current
994 .verify_for(fixture.workspace(), Some(&plugins))
995 .is_err(),
996 "mutable source tamper fails before reconcile"
997 );
998 std::fs::write(&source_skill, reviewed).unwrap();
999 current
1000 .verify_for(fixture.workspace(), Some(&plugins))
1001 .unwrap();
1002 fixture.disable("skills-root");
1003 assert!(
1004 current
1005 .verify_for(fixture.workspace(), Some(&plugins))
1006 .is_err(),
1007 "persisted disable wins before reconcile"
1008 );
1009 manager.shutdown().await;
1010 }
1011 }
1012
1012 lines RUST