返回 CodeWhale
tests.rs
根目录 / crates / plugins / src / tests.rs
1 use std::fs;
2 use std::path::{Path, PathBuf};
3
4 use super::activation::PluginActivationCapability;
5 use super::discovery::{DiscoveryConfig, discover_with_config};
6 use super::managed_policy::{
7 MANAGED_POLICY_FILE_NAME, MANAGED_POLICY_PATH_ENV, MANAGED_POLICY_SCHEMA_VERSION,
8 ManagedPluginPolicy,
9 };
10 use super::manifest::PluginCompatibility;
11 use super::types::{PluginDiagnosticLevel, PluginTrustStatus};
12
13 fn config(root: &Path) -> DiscoveryConfig {
14 DiscoveryConfig {
15 workspace: root.join("project"),
16 user_plugins_dir: root.join("user"),
17 workspace_plugins_dir: root.join("workspace"),
18 builtin_plugin_dirs: Vec::new(),
19 state_path: root.join("state/plugin-state.json"),
20 }
21 }
22
23 fn write_plugin(config: &DiscoveryConfig, extra: &str) -> PathBuf {
24 write_named_plugin(config, "demo", extra)
25 }
26
27 fn write_named_plugin(config: &DiscoveryConfig, name: &str, extra: &str) -> PathBuf {
28 let plugin = config.user_plugins_dir.join(name);
29 fs::create_dir_all(&plugin).unwrap();
30 fs::write(
31 plugin.join("plugin.toml"),
32 format!("schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n{extra}"),
33 )
34 .unwrap();
35 plugin
36 }
37
38 #[test]
39 fn catalog_stamp_changes_when_only_state_bytes_change() {
40 let tmp = tempfile::tempdir().unwrap();
41 let config = config(tmp.path());
42 write_plugin(&config, "");
43 let registry = discover_with_config(&config);
44 assert!(!registry.on_disk_catalog_changed());
45
46 std::fs::create_dir_all(config.state_path.parent().unwrap()).unwrap();
47 std::fs::write(&config.state_path, "{\"version\":1}").unwrap();
48 assert!(registry.on_disk_catalog_changed());
49
50 let reloaded = registry.rediscover_for_workspace(&config.workspace);
51 assert!(!reloaded.on_disk_catalog_changed());
52 std::fs::write(&config.state_path, "{\"version\":1}").unwrap();
53 assert!(!reloaded.on_disk_catalog_changed());
54 std::fs::write(&config.state_path, "{\"version\":2}").unwrap();
55 assert!(reloaded.on_disk_catalog_changed());
56 }
57
58 #[test]
59 fn on_disk_catalog_change_nudges_reload_once_until_rediscover() {
60 let tmp = tempfile::tempdir().unwrap();
61 let config = config(tmp.path());
62 write_plugin(&config, "");
63
64 let registry = discover_with_config(&config);
65 assert!(
66 !registry.on_disk_catalog_changed(),
67 "fresh discovery must match the on-disk stamp"
68 );
69
70 let mut last_nudged = None;
71 assert!(
72 crate::plugin_reload_nudge(&registry, &mut last_nudged).is_none(),
73 "unchanged catalog must not nudge"
74 );
75
76 write_named_plugin(&config, "extra", "");
77 assert!(
78 registry.on_disk_catalog_changed(),
79 "a new bundle directory is a catalog change"
80 );
81 assert_eq!(
82 crate::plugin_reload_nudge(&registry, &mut last_nudged),
83 Some(crate::PLUGIN_RELOAD_NUDGE)
84 );
85 assert!(
86 crate::plugin_reload_nudge(&registry, &mut last_nudged).is_none(),
87 "the same unseen catalog must nudge only once"
88 );
89
90 let reloaded = registry.rediscover_for_workspace(&config.workspace);
91 assert!(!reloaded.on_disk_catalog_changed());
92 assert!(crate::plugin_reload_nudge(&reloaded, &mut last_nudged).is_none());
93 }
94
95 #[test]
96 fn trust_and_enablement_are_separate_atomic_state_transitions() {
97 let tmp = tempfile::tempdir().unwrap();
98 let config = config(tmp.path());
99 write_plugin(&config, "");
100
101 let mut registry = discover_with_config(&config);
102 assert!(registry.enable("demo").is_err());
103 assert!(!config.state_path.exists());
104
105 registry.trust("demo").unwrap();
106 assert!(registry.get("demo").unwrap().trusted());
107 assert!(!registry.get("demo").unwrap().enabled);
108 registry.enable("demo").unwrap();
109 assert!(registry.is_active("demo"));
110 registry.revoke_trust("demo").unwrap();
111 assert!(registry.get("demo").unwrap().enabled);
112 registry.trust("demo").unwrap();
113 assert!(registry.get("demo").unwrap().trusted());
114 assert!(
115 !registry.get("demo").unwrap().enabled,
116 "trust must never reuse an old enablement bit"
117 );
118 assert!(!registry.is_active("demo"));
119 registry.enable("demo").unwrap();
120 assert!(registry.is_active("demo"));
121
122 let raw = fs::read_to_string(&config.state_path).unwrap();
123 let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
124 assert_eq!(parsed["schema_version"], 1);
125 let receipt = parsed["plugins"]
126 .as_object()
127 .and_then(|plugins| plugins.values().next())
128 .and_then(|plugin| plugin.get("trust"))
129 .expect("trust receipt");
130 assert!(receipt["content_hash"].as_str().is_some());
131 assert!(receipt["capability_hash"].as_str().is_some());
132 assert_eq!(receipt["reviewed_capabilities"]["skills"], 0);
133 assert!(receipt["reviewed_at"].as_str().is_some());
134 let history = parsed["plugins"]
135 .as_object()
136 .and_then(|plugins| plugins.values().next())
137 .and_then(|plugin| plugin["review_history"].as_array())
138 .expect("review history");
139 assert_eq!(history.len(), 2);
140 assert_eq!(history[1]["content_hash"], receipt["content_hash"]);
141 #[cfg(unix)]
142 {
143 use std::os::unix::fs::PermissionsExt;
144 assert_eq!(
145 fs::metadata(config.state_path.parent().unwrap())
146 .unwrap()
147 .permissions()
148 .mode()
149 & 0o777,
150 0o700
151 );
152 assert_eq!(
153 fs::metadata(&config.state_path)
154 .unwrap()
155 .permissions()
156 .mode()
157 & 0o777,
158 0o600
159 );
160 }
161 let entries = fs::read_dir(config.state_path.parent().unwrap())
162 .unwrap()
163 .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
164 .collect::<Vec<_>>();
165 assert!(entries.iter().any(|name| name == "plugin-state.json"));
166 assert!(entries.iter().any(|name| name == "plugin-state.json.lock"));
167 assert!(entries.iter().any(|name| name == ".runtime"));
168 assert!(
169 entries.iter().all(|name| !name.contains(".tmp")),
170 "atomic persistence must not strand temp files: {entries:?}"
171 );
172 }
173
174 #[test]
175 fn native_review_mutation_finishes_then_rechecks_current_default_receipt() {
176 let _policy = super::activation::TestPolicyGuard::extension_host(true);
177 let tmp = tempfile::tempdir().unwrap();
178 let config = config(tmp.path());
179 let plugin = config.user_plugins_dir.join("native-preset");
180 fs::create_dir_all(&plugin).unwrap();
181 fs::write(
182 plugin.join("plugin.json"),
183 r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"native-preset","version":"1.0.0","extensions":{"net.codewhale":{"native":{"paths":["index.mjs"]}}}}"#,
184 )
185 .unwrap();
186 fs::write(
187 plugin.join("index.mjs"),
188 "// codewhale-native-preset-v1 {\"id\":\"reviewer\",\"trust\":\"user\",\"is_default\":true}\nexport function apply() {}\n",
189 )
190 .unwrap();
191 let mut registry = discover_with_config(&config);
192 registry.trust("native-preset").unwrap();
193 registry.enable("native-preset").unwrap();
194 let selected = registry.selected_native_entries().to_vec();
195 assert_eq!(selected.len(), 1);
196 let fresh = discover_with_config(&config);
197 assert_eq!(fresh.selected_native_entries(), selected);
198 assert!(fresh.with_native_preset(selected[0].clone()).is_ok());
199
200 registry.disable("native-preset").unwrap();
201 assert!(registry.with_native_preset(selected[0].clone()).is_err());
202 assert!(!discover_with_config(&config).is_active("native-preset"));
203 registry.enable("native-preset").unwrap();
204 assert!(registry.with_native_preset(selected[0].clone()).is_ok());
205 registry.revoke_trust("native-preset").unwrap();
206 assert!(registry.with_native_preset(selected[0].clone()).is_err());
207 assert!(!discover_with_config(&config).is_active("native-preset"));
208 }
209
210 #[test]
211 fn declarative_runtime_sources_survive_restart_only_from_the_staged_snapshot() {
212 let fixture = super::test_fixture::DeclarativePluginFixture::new();
213 let plugin = fixture.registry.get("runtime-demo").expect("plugin");
214 let staged_root = plugin.staged_root.as_deref().expect("staged root");
215 for capability in [
216 PluginActivationCapability::Commands,
217 PluginActivationCapability::Agents,
218 PluginActivationCapability::Hooks,
219 ] {
220 let (sources, errors) =
221 super::runtime::active_component_sources(&fixture.registry, capability);
222 assert!(errors.is_empty(), "{capability:?}: {errors:?}");
223 assert_eq!(sources.len(), 1, "{capability:?}");
224 assert!(sources[0].path.starts_with(staged_root), "{capability:?}");
225 assert!(
226 !sources[0].path.starts_with(&plugin.canonical_root),
227 "{capability:?} must never execute from mutable source"
228 );
229 }
230 assert!(staged_root.join("commands/plugin-hello.md").is_file());
231 let root = fixture.workspace.parent().unwrap().to_path_buf();
232 drop(fixture);
233 assert!(!root.try_exists().unwrap());
234 }
235
236 #[test]
237 fn content_change_invalidates_trust_without_changing_capabilities() {
238 let tmp = tempfile::tempdir().unwrap();
239 let config = config(tmp.path());
240 let plugin = write_plugin(&config, "\n[skills]\npath = \"skills\"\n");
241 fs::create_dir_all(plugin.join("skills/demo")).unwrap();
242 fs::write(
243 plugin.join("skills/demo/SKILL.md"),
244 "---\nname: demo\ndescription: first\n---\nbody\n",
245 )
246 .unwrap();
247
248 let mut first = discover_with_config(&config);
249 first.trust("demo").unwrap();
250 first.enable("demo").unwrap();
251 assert!(first.is_active("demo"));
252
253 fs::write(
254 plugin.join("skills/demo/SKILL.md"),
255 "---\nname: demo\ndescription: changed\n---\nbody\n",
256 )
257 .unwrap();
258 let second = discover_with_config(&config);
259 let plugin = second.get("demo").unwrap();
260 assert!(plugin.enabled, "enablement is independent from trust");
261 assert_eq!(plugin.trust_status, PluginTrustStatus::ContentChanged);
262 assert!(!plugin.active());
263 }
264
265 #[test]
266 fn staged_skill_snapshot_restricts_implicit_use_from_reviewed_sidecar() {
267 let tmp = tempfile::tempdir().unwrap();
268 let config = config(tmp.path());
269 let plugin = write_plugin(&config, "\n[skills]\npath = \"skills\"\n");
270 fs::create_dir_all(plugin.join("skills/demo/agents")).unwrap();
271 fs::write(
272 plugin.join("skills/demo/SKILL.md"),
273 "---\nname: demo\ndescription: packaged fixture\n---\nbody\n",
274 )
275 .unwrap();
276 fs::write(
277 plugin.join("skills/demo/agents/openai.yaml"),
278 "policy:\n allow_implicit_invocation: false\n",
279 )
280 .unwrap();
281 let mut registry = discover_with_config(&config);
282 registry.trust("demo").unwrap();
283 registry.enable("demo").unwrap();
284 let plugin = registry.get("demo").unwrap();
285 assert!(plugin.active());
286 assert!(plugin.skill_snapshots[0].invocation.user_invocable());
287 assert!(!plugin.skill_snapshots[0].invocation.model_invocable());
288 }
289
290 #[test]
291 fn aba_source_skill_body_is_replaced_by_the_staged_snapshot_before_activation() {
292 let tmp = tempfile::tempdir().unwrap();
293 let config = config(tmp.path());
294 let plugin = write_plugin(&config, "\n[skills]\npath = \"skills\"\n");
295 let skill_path = plugin.join("skills/demo/SKILL.md");
296 fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
297 fs::write(
298 &skill_path,
299 "---\nname: demo\ndescription: stable\n---\nbody A\n",
300 )
301 .unwrap();
302
303 // Capture authority A, parse a transient B body, then restore source A.
304 // This deterministically models the old discovery A -> B -> A race.
305 let mut authority_a = discover_with_config(&config);
306 fs::write(
307 &skill_path,
308 "---\nname: demo\ndescription: transient\n---\nbody B\n",
309 )
310 .unwrap();
311 let transient_b = discover_with_config(&config)
312 .get("demo")
313 .unwrap()
314 .skill_snapshots
315 .clone();
316 fs::write(
317 &skill_path,
318 "---\nname: demo\ndescription: stable\n---\nbody A\n",
319 )
320 .unwrap();
321 authority_a.replace_skill_snapshots_for_test("demo", transient_b);
322 assert!(
323 authority_a.get("demo").unwrap().skill_snapshots[0]
324 .body
325 .contains("body B")
326 );
327
328 authority_a.trust("demo").unwrap();
329 authority_a.enable("demo").unwrap();
330 let active = authority_a.get("demo").unwrap();
331 assert!(active.active());
332 assert!(active.skill_snapshots[0].body.contains("body A"));
333 assert!(!active.skill_snapshots[0].body.contains("body B"));
334 let staged_bytes = fs::read(&active.skill_snapshots[0].path).unwrap();
335 let mut digest = sha2::Sha256::new();
336 use sha2::Digest as _;
337 digest.update(b"codewhale-plugin-file-bytes-v1\0");
338 digest.update(staged_bytes);
339 let staged_hash = digest
340 .finalize()
341 .iter()
342 .map(|byte| format!("{byte:02x}"))
343 .collect::<String>();
344 assert_eq!(active.skill_snapshots[0].source_hash, staged_hash);
345 assert!(
346 active.skill_snapshots[0]
347 .path
348 .starts_with(active.staged_root.as_ref().unwrap()),
349 "active Skill paths must point into the Codewhale-owned staged tree"
350 );
351 }
352
353 #[test]
354 fn capability_escalation_invalidates_trust_and_stays_inactive() {
355 let tmp = tempfile::tempdir().unwrap();
356 let config = config(tmp.path());
357 let plugin = write_plugin(&config, "");
358
359 let mut first = discover_with_config(&config);
360 first.trust("demo").unwrap();
361 first.enable("demo").unwrap();
362
363 fs::create_dir_all(plugin.join("hooks")).unwrap();
364 fs::write(
365 plugin.join("plugin.toml"),
366 "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n[hooks]\npath = \"hooks\"\n",
367 )
368 .unwrap();
369 let second = discover_with_config(&config);
370 let plugin = second.get("demo").unwrap();
371 assert_eq!(plugin.trust_status, PluginTrustStatus::CapabilitiesChanged);
372 assert!(plugin.enabled);
373 assert!(!plugin.active());
374 }
375
376 #[test]
377 fn malformed_state_is_fail_closed_and_never_overwritten() {
378 let tmp = tempfile::tempdir().unwrap();
379 let config = config(tmp.path());
380 write_plugin(&config, "");
381 fs::create_dir_all(config.state_path.parent().unwrap()).unwrap();
382 #[cfg(unix)]
383 {
384 use std::os::unix::fs::PermissionsExt as _;
385 fs::set_permissions(
386 config.state_path.parent().unwrap(),
387 fs::Permissions::from_mode(0o700),
388 )
389 .unwrap();
390 }
391 fs::write(&config.state_path, "{ malformed").unwrap();
392
393 let mut registry = discover_with_config(&config);
394 assert!(registry.state_error().is_some());
395 assert!(!registry.get("demo").unwrap().enabled);
396 assert!(!registry.get("demo").unwrap().trusted());
397 assert!(registry.trust("demo").is_err());
398 assert_eq!(
399 fs::read_to_string(&config.state_path).unwrap(),
400 "{ malformed"
401 );
402 }
403
404 #[test]
405 fn atomic_write_failure_does_not_mutate_live_enablement() {
406 let tmp = tempfile::tempdir().unwrap();
407 let config = config(tmp.path());
408 write_plugin(&config, "");
409
410 let mut registry = discover_with_config(&config);
411 registry.trust("demo").unwrap();
412 fs::remove_file(&config.state_path).unwrap();
413 fs::create_dir(&config.state_path).unwrap();
414
415 assert!(registry.enable("demo").is_err());
416 let plugin = registry.get("demo").unwrap();
417 assert!(plugin.trusted());
418 assert!(!plugin.enabled);
419 assert!(!plugin.active());
420 }
421
422 #[test]
423 fn revoking_trust_does_not_rewrite_enablement() {
424 let tmp = tempfile::tempdir().unwrap();
425 let config = config(tmp.path());
426 write_plugin(&config, "");
427
428 let mut registry = discover_with_config(&config);
429 registry.trust("demo").unwrap();
430 registry.enable("demo").unwrap();
431 registry.revoke_trust("demo").unwrap();
432
433 let plugin = registry.get("demo").unwrap();
434 assert!(plugin.enabled);
435 assert!(!plugin.trusted());
436 assert!(!plugin.active());
437 }
438
439 #[test]
440 fn all_unsupported_bundles_can_be_reviewed_but_not_enabled() {
441 let tmp = tempfile::tempdir().unwrap();
442 let config = config(tmp.path());
443 let plugin = write_plugin(&config, "\n[lsp]\npath = \"lsp\"\n");
444 fs::create_dir_all(plugin.join("lsp")).unwrap();
445
446 let mut registry = discover_with_config(&config);
447 let plugin = registry.get("demo").unwrap();
448 assert_eq!(plugin.compatibility(), PluginCompatibility::Unsupported);
449 assert!(!plugin.inventory.has_supported_components());
450 registry.trust("demo").unwrap();
451 let error = registry.enable("demo").unwrap_err();
452 assert!(
453 error.contains("no supported declarative components"),
454 "all-unsupported enable must name the missing supported surfaces: {error}"
455 );
456 assert!(error.contains("lsp"), "{error}");
457 assert!(!registry.is_active("demo"));
458 let plugin = registry.get("demo").unwrap();
459 assert!(plugin.trusted());
460 assert!(!plugin.enabled);
461 assert_eq!(plugin.state_label(), "disabled");
462 assert_eq!(plugin.compatibility(), PluginCompatibility::Unsupported);
463 }
464
465 #[test]
466 fn fatal_manifest_errors_fail_closed_and_do_not_activate_mixed_looking_bundles() {
467 let tmp = tempfile::tempdir().unwrap();
468 let config = config(tmp.path());
469 let plugin = write_plugin(
470 &config,
471 "\n[skills]\npath = \"skills\"\n[commands]\npath = \"commands\"\nunknown_field = true\n",
472 );
473 fs::create_dir_all(plugin.join("skills/demo")).unwrap();
474 fs::write(
475 plugin.join("skills/demo/SKILL.md"),
476 "---\nname: demo\ndescription: first\n---\nbody\n",
477 )
478 .unwrap();
479 fs::create_dir_all(plugin.join("commands")).unwrap();
480
481 let mut registry = discover_with_config(&config);
482 assert!(registry.get("demo").is_none());
483 assert!(
484 registry.diagnostics().iter().any(|diagnostic| {
485 diagnostic.level == PluginDiagnosticLevel::Error
486 && diagnostic.code == "manifest-invalid"
487 }),
488 "fatal parse errors must remain registry-level errors: {:?}",
489 registry.diagnostics()
490 );
491 assert!(registry.trust("demo").is_err());
492 assert!(registry.enable("demo").is_err());
493 assert!(!registry.is_active("demo"));
494 }
495
496 #[test]
497 fn stale_concurrent_registries_do_not_lose_updates() {
498 let tmp = tempfile::tempdir().unwrap();
499 let config = config(tmp.path());
500 write_named_plugin(&config, "alpha", "");
501 write_named_plugin(&config, "beta", "");
502
503 let left = discover_with_config(&config);
504 let right = discover_with_config(&config);
505 let barrier = std::sync::Arc::new(std::sync::Barrier::new(2));
506 let left_barrier = std::sync::Arc::clone(&barrier);
507 let left = std::thread::spawn(move || {
508 let mut registry = left;
509 left_barrier.wait();
510 registry.trust("alpha").unwrap();
511 registry.enable("alpha").unwrap();
512 });
513 let right = std::thread::spawn(move || {
514 let mut registry = right;
515 barrier.wait();
516 registry.trust("beta").unwrap();
517 registry.enable("beta").unwrap();
518 });
519 left.join().unwrap();
520 right.join().unwrap();
521
522 let fresh = discover_with_config(&config);
523 assert!(fresh.is_active("alpha"));
524 assert!(fresh.is_active("beta"));
525 }
526
527 #[test]
528 fn stale_enable_cannot_resurrect_revoked_trust() {
529 let tmp = tempfile::tempdir().unwrap();
530 let config = config(tmp.path());
531 write_plugin(&config, "");
532 let mut initial = discover_with_config(&config);
533 initial.trust("demo").unwrap();
534 initial.enable("demo").unwrap();
535
536 let mut stale = discover_with_config(&config);
537 let authority = stale.authority_for("demo").unwrap();
538 let mut revoker = discover_with_config(&config);
539 revoker.revoke_trust("demo").unwrap();
540 assert!(super::registry::verify_plugin_state_authority(&authority).is_err());
541
542 let revoked_state = fs::read(&config.state_path).unwrap();
543 assert!(stale.enable("demo").unwrap_err().contains("changed"));
544 assert_eq!(fs::read(&config.state_path).unwrap(), revoked_state);
545 let fresh = discover_with_config(&config);
546 assert!(fresh.get("demo").unwrap().enabled);
547 assert!(!fresh.get("demo").unwrap().trusted());
548 assert!(!fresh.is_active("demo"));
549
550 revoker.trust("demo").unwrap();
551 let reviewed_state = fs::read(&config.state_path).unwrap();
552 assert!(stale.enable("demo").unwrap_err().contains("changed"));
553 assert_eq!(fs::read(&config.state_path).unwrap(), reviewed_state);
554 let fresh = discover_with_config(&config);
555 assert!(!fresh.get("demo").unwrap().enabled);
556 assert!(fresh.get("demo").unwrap().trusted());
557 assert!(!fresh.is_active("demo"));
558 }
559
560 #[cfg(unix)]
561 #[test]
562 fn staging_is_owner_only_and_uses_the_reviewed_executable_shape() {
563 use std::os::unix::fs::PermissionsExt;
564
565 let tmp = tempfile::tempdir().unwrap();
566 let config = config(tmp.path());
567 let plugin = write_plugin(&config, "");
568 let executable = plugin.join("server.sh");
569 fs::write(&executable, "#!/bin/sh\nexit 0\n").unwrap();
570 fs::set_permissions(&executable, fs::Permissions::from_mode(0o755)).unwrap();
571
572 let mut registry = discover_with_config(&config);
573 registry.trust("demo").unwrap();
574 registry.enable("demo").unwrap();
575 let staged = registry.get("demo").unwrap().staged_root.as_ref().unwrap();
576 assert_ne!(staged, &plugin);
577 let state_parent = config.state_path.parent().unwrap().canonicalize().unwrap();
578 let relative_stage = staged.strip_prefix(state_parent).unwrap();
579 assert!(
580 relative_stage.starts_with(Path::new(".runtime/v2")),
581 "runtime authority must use the v2 staging domain: {}",
582 staged.display()
583 );
584 assert_eq!(
585 fs::metadata(staged).unwrap().permissions().mode() & 0o777,
586 0o500
587 );
588 assert_eq!(
589 fs::metadata(staged.join("plugin.toml"))
590 .unwrap()
591 .permissions()
592 .mode()
593 & 0o777,
594 0o400
595 );
596 assert_eq!(
597 fs::metadata(staged.join("server.sh"))
598 .unwrap()
599 .permissions()
600 .mode()
601 & 0o777,
602 0o500
603 );
604 }
605
606 #[cfg(unix)]
607 #[test]
608 fn discovery_does_not_rewrite_existing_state_or_lock_permissions() {
609 use std::os::unix::fs::PermissionsExt as _;
610
611 let tmp = tempfile::tempdir().unwrap();
612 let config = config(tmp.path());
613 write_plugin(&config, "");
614 fs::create_dir_all(config.state_path.parent().unwrap()).unwrap();
615 fs::set_permissions(
616 config.state_path.parent().unwrap(),
617 fs::Permissions::from_mode(0o700),
618 )
619 .unwrap();
620 fs::write(
621 &config.state_path,
622 "{\"schema_version\":1,\"plugins\":{}}\n",
623 )
624 .unwrap();
625 let lock = config.state_path.with_file_name("plugin-state.json.lock");
626 fs::write(&lock, b"sentinel").unwrap();
627 fs::set_permissions(&config.state_path, fs::Permissions::from_mode(0o644)).unwrap();
628 fs::set_permissions(&lock, fs::Permissions::from_mode(0o666)).unwrap();
629
630 let state_before = fs::metadata(&config.state_path).unwrap();
631 let lock_before = fs::metadata(&lock).unwrap();
632 let state_body = fs::read(&config.state_path).unwrap();
633 let lock_body = fs::read(&lock).unwrap();
634 let registry = discover_with_config(&config);
635
636 assert!(registry.state_error().is_none());
637 assert_eq!(fs::read(&config.state_path).unwrap(), state_body);
638 assert_eq!(fs::read(&lock).unwrap(), lock_body);
639 assert_eq!(
640 fs::metadata(&config.state_path)
641 .unwrap()
642 .permissions()
643 .mode(),
644 state_before.permissions().mode()
645 );
646 assert_eq!(
647 fs::metadata(&lock).unwrap().permissions().mode(),
648 lock_before.permissions().mode()
649 );
650 }
651
652 #[cfg(unix)]
653 #[test]
654 fn discovery_rejects_an_insecure_state_parent_without_mutating_it() {
655 use std::os::unix::fs::PermissionsExt as _;
656
657 let tmp = tempfile::tempdir().unwrap();
658 let config = config(tmp.path());
659 write_plugin(&config, "");
660 let state_parent = config.state_path.parent().unwrap();
661 fs::create_dir_all(state_parent).unwrap();
662 let state_body = b"{\"schema_version\":1,\"plugins\":{}}\n";
663 fs::write(&config.state_path, state_body).unwrap();
664 fs::set_permissions(state_parent, fs::Permissions::from_mode(0o777)).unwrap();
665
666 let registry = discover_with_config(&config);
667
668 assert!(registry.state_error().is_some());
669 assert_eq!(fs::read(&config.state_path).unwrap(), state_body);
670 assert_eq!(
671 fs::metadata(state_parent).unwrap().permissions().mode() & 0o777,
672 0o777,
673 "read-only discovery must not repair directory permissions"
674 );
675 }
676
677 #[cfg(unix)]
678 #[test]
679 fn trust_rejects_an_existing_group_accessible_state_parent_without_repairing_it() {
680 use std::os::unix::fs::PermissionsExt as _;
681
682 let tmp = tempfile::tempdir().unwrap();
683 let config = config(tmp.path());
684 write_plugin(&config, "");
685 let state_parent = config.state_path.parent().unwrap();
686 fs::create_dir_all(state_parent).unwrap();
687 fs::set_permissions(state_parent, fs::Permissions::from_mode(0o777)).unwrap();
688 let mut registry = discover_with_config(&config);
689 assert!(registry.state_error().is_some());
690
691 assert!(registry.trust("demo").is_err());
692
693 assert_eq!(
694 fs::metadata(state_parent).unwrap().permissions().mode() & 0o777,
695 0o777,
696 "trust must not silently repair a pre-existing unsafe authority directory"
697 );
698 assert!(!config.state_path.exists());
699 }
700
701 #[cfg(unix)]
702 #[test]
703 fn discovery_rejects_a_symlinked_state_parent_without_touching_its_target() {
704 use std::os::unix::fs::{PermissionsExt as _, symlink};
705
706 let tmp = tempfile::tempdir().unwrap();
707 let config = config(tmp.path());
708 write_plugin(&config, "");
709 let target = tmp.path().join("state-target");
710 fs::create_dir(&target).unwrap();
711 fs::set_permissions(&target, fs::Permissions::from_mode(0o700)).unwrap();
712 let state_body = b"{\"schema_version\":1,\"plugins\":{}}\n";
713 fs::write(target.join("plugin-state.json"), state_body).unwrap();
714 symlink(&target, config.state_path.parent().unwrap()).unwrap();
715
716 let mut registry = discover_with_config(&config);
717
718 assert!(registry.state_error().is_some());
719 assert!(registry.trust("demo").is_err());
720 assert_eq!(
721 fs::read(target.join("plugin-state.json")).unwrap(),
722 state_body
723 );
724 assert!(
725 fs::symlink_metadata(config.state_path.parent().unwrap())
726 .unwrap()
727 .file_type()
728 .is_symlink(),
729 "discovery and trust must leave the state-parent link in place"
730 );
731 }
732
733 #[cfg(unix)]
734 #[test]
735 fn discovery_rejects_linked_state_and_lock_without_touching_targets() {
736 use std::os::unix::fs::{PermissionsExt as _, symlink};
737
738 for linked_entry in ["state", "lock"] {
739 let tmp = tempfile::tempdir().unwrap();
740 let config = config(tmp.path());
741 write_plugin(&config, "");
742 fs::create_dir_all(config.state_path.parent().unwrap()).unwrap();
743 fs::set_permissions(
744 config.state_path.parent().unwrap(),
745 fs::Permissions::from_mode(0o700),
746 )
747 .unwrap();
748 let target = tmp.path().join(format!("{linked_entry}-target"));
749 fs::write(&target, "{\"schema_version\":1,\"plugins\":{}}\n").unwrap();
750 fs::set_permissions(&target, fs::Permissions::from_mode(0o644)).unwrap();
751 let target_before = fs::read(&target).unwrap();
752 let target_mode = fs::metadata(&target).unwrap().permissions().mode();
753 if linked_entry == "state" {
754 symlink(&target, &config.state_path).unwrap();
755 } else {
756 fs::write(
757 &config.state_path,
758 "{\"schema_version\":1,\"plugins\":{}}\n",
759 )
760 .unwrap();
761 symlink(
762 &target,
763 config.state_path.with_file_name("plugin-state.json.lock"),
764 )
765 .unwrap();
766 }
767
768 let registry = discover_with_config(&config);
769 assert!(
770 registry.state_error().is_some(),
771 "linked {linked_entry} must fail closed"
772 );
773 assert_eq!(fs::read(&target).unwrap(), target_before);
774 assert_eq!(
775 fs::metadata(&target).unwrap().permissions().mode(),
776 target_mode
777 );
778 }
779 }
780
781 #[cfg(unix)]
782 #[test]
783 fn staging_rejects_root_swaps_symlinked_runtime_parents_and_hardlinks() {
784 use std::os::unix::fs::{PermissionsExt as _, symlink};
785
786 let tmp = tempfile::tempdir().unwrap();
787 let config = config(tmp.path());
788 let plugin = write_plugin(&config, "");
789 let mut swapped = discover_with_config(&config);
790 let original = plugin.with_file_name("demo-original");
791 fs::rename(&plugin, &original).unwrap();
792 let outside = tmp.path().join("outside");
793 fs::create_dir(&outside).unwrap();
794 fs::write(
795 outside.join("plugin.toml"),
796 "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n",
797 )
798 .unwrap();
799 symlink(&outside, &plugin).unwrap();
800 assert!(swapped.trust("demo").is_err());
801
802 fs::remove_file(&plugin).unwrap();
803 fs::rename(&original, &plugin).unwrap();
804 let mut parent_swap = discover_with_config(&config);
805 fs::create_dir_all(config.state_path.parent().unwrap()).unwrap();
806 fs::set_permissions(
807 config.state_path.parent().unwrap(),
808 fs::Permissions::from_mode(0o700),
809 )
810 .unwrap();
811 let runtime_root = config.state_path.parent().unwrap().join(".runtime");
812 if runtime_root.exists() {
813 fs::remove_dir_all(&runtime_root).unwrap();
814 }
815 let runtime_outside = tmp.path().join("runtime-outside");
816 fs::create_dir(&runtime_outside).unwrap();
817 symlink(&runtime_outside, &runtime_root).unwrap();
818 assert!(parent_swap.trust("demo").is_err());
819
820 fs::remove_file(&runtime_root).unwrap();
821 let external_file = tmp.path().join("external.txt");
822 fs::write(&external_file, "reviewed-looking content").unwrap();
823 fs::hard_link(&external_file, plugin.join("hardlinked.txt")).unwrap();
824 let mut hardlinked = discover_with_config(&config);
825 assert!(hardlinked.trust("demo").is_err());
826 }
827
828 // ─────────────────────────────────────────────────────────────────────────────
829 // Install on-ramp integration (#5182)
830 // ─────────────────────────────────────────────────────────────────────────────
831
832 fn block_on<F: std::future::Future>(future: F) -> F::Output {
833 tokio::runtime::Builder::new_multi_thread()
834 .worker_threads(2)
835 .enable_all()
836 .build()
837 .unwrap()
838 .block_on(future)
839 }
840
841 fn allow_all_network() -> codewhale_net::network_policy::NetworkPolicy {
842 codewhale_net::network_policy::NetworkPolicy {
843 default: codewhale_net::network_policy::DecisionToml::Allow,
844 ..Default::default()
845 }
846 }
847
848 fn write_install_source(root: &Path, name: &str) -> PathBuf {
849 let source = root.join(format!("source/{name}"));
850 fs::create_dir_all(source.join("skills/hello")).unwrap();
851 fs::write(
852 source.join("plugin.toml"),
853 format!(
854 "schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n"
855 ),
856 )
857 .unwrap();
858 fs::write(
859 source.join("skills/hello/SKILL.md"),
860 "---\nname: hello\ndescription: hi\n---\nbody\n",
861 )
862 .unwrap();
863 source
864 }
865
866 #[test]
867 fn installed_bundles_land_disabled_and_untrusted_then_follow_the_trust_flow() {
868 let tmp = tempfile::tempdir().unwrap();
869 let config = config(tmp.path());
870 let source = write_install_source(tmp.path(), "demo");
871 let network = allow_all_network();
872
873 let outcome = block_on(super::install::install(
874 super::install::PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
875 &config.user_plugins_dir,
876 super::install::DEFAULT_MAX_SIZE_BYTES,
877 &network,
878 false,
879 &|_| None,
880 ))
881 .unwrap();
882 assert!(
883 matches!(outcome, super::install::PluginInstallOutcome::Installed(_)),
884 "local install must succeed"
885 );
886 assert!(
887 config
888 .user_plugins_dir
889 .join("demo")
890 .join(codewhale_skill_install::install::INSTALLED_FROM_MARKER)
891 .exists()
892 );
893
894 // The discovery invariant: freshly installed bits are disabled + untrusted.
895 let mut registry = discover_with_config(&config);
896 let plugin = registry.get("demo").unwrap();
897 assert!(!plugin.enabled);
898 assert!(!plugin.trusted());
899 assert!(registry.enable("demo").is_err());
900
901 registry.trust("demo").unwrap();
902 registry.enable("demo").unwrap();
903 assert!(registry.is_active("demo"));
904 assert_eq!(
905 registry
906 .get("demo")
907 .unwrap()
908 .skill_snapshots
909 .first()
910 .map(|snapshot| snapshot.name.as_str()),
911 Some("hello")
912 );
913 }
914
915 #[test]
916 fn mutation_uninstall_requires_disabled_then_deletes_bits_and_prunes_state() {
917 let tmp = tempfile::tempdir().unwrap();
918 let config = config(tmp.path());
919 let source = write_install_source(tmp.path(), "demo");
920 let network = allow_all_network();
921
922 let mut registry = discover_with_config(&config);
923 let ctx = super::mutation::PluginMutationContext {
924 network: &network,
925 max_size: super::install::DEFAULT_MAX_SIZE_BYTES,
926 };
927 let receipt = block_on(super::mutation::execute(
928 super::mutation::PluginMutationRequest::Install {
929 source: super::install::PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
930 },
931 &ctx,
932 &mut registry,
933 ))
934 .unwrap();
935 assert_eq!(
936 receipt.outcome,
937 super::mutation::PluginMutationOutcome::Installed
938 );
939
940 let mut registry = discover_with_config(&config);
941 registry.trust("demo").unwrap();
942 registry.enable("demo").unwrap();
943
944 // Enabled bundles are refused before anything is deleted.
945 let refused = block_on(super::mutation::execute(
946 super::mutation::PluginMutationRequest::Uninstall {
947 selector: "demo".to_string(),
948 },
949 &ctx,
950 &mut registry,
951 ));
952 assert!(refused.is_err(), "uninstall must require disabled");
953 assert!(config.user_plugins_dir.join("demo").exists());
954
955 registry.disable("demo").unwrap();
956 let receipt = block_on(super::mutation::execute(
957 super::mutation::PluginMutationRequest::Uninstall {
958 selector: "demo".to_string(),
959 },
960 &ctx,
961 &mut registry,
962 ))
963 .unwrap();
964 assert_eq!(
965 receipt.outcome,
966 super::mutation::PluginMutationOutcome::Uninstalled
967 );
968 assert!(!config.user_plugins_dir.join("demo").exists());
969
970 let rediscovered = discover_with_config(&config);
971 assert!(rediscovered.is_empty());
972 let raw = fs::read_to_string(&config.state_path).unwrap();
973 let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
974 assert!(
975 parsed["plugins"].as_object().unwrap().is_empty(),
976 "state entry must be pruned: {raw}"
977 );
978 }
979
980 #[test]
981 fn mutation_install_rejects_names_claimed_by_other_scopes() {
982 let tmp = tempfile::tempdir().unwrap();
983 let config = config(tmp.path());
984 // A hand-placed workspace bundle already owns the name `demo`.
985 let workspace_bundle = config.workspace_plugins_dir.join("demo");
986 fs::create_dir_all(&workspace_bundle).unwrap();
987 fs::write(
988 workspace_bundle.join("plugin.toml"),
989 "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n",
990 )
991 .unwrap();
992 let source = write_install_source(tmp.path(), "demo");
993 let network = allow_all_network();
994
995 let mut registry = discover_with_config(&config);
996 let ctx = super::mutation::PluginMutationContext {
997 network: &network,
998 max_size: super::install::DEFAULT_MAX_SIZE_BYTES,
999 };
1000 let err = block_on(super::mutation::execute(
1001 super::mutation::PluginMutationRequest::Install {
1002 source: super::install::PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
1003 },
1004 &ctx,
1005 &mut registry,
1006 ))
1007 .unwrap_err();
1008 assert!(
1009 format!("{err:#}").contains("already used by the workspace bundle"),
1010 "got: {err:#}"
1011 );
1012 assert!(!config.user_plugins_dir.join("demo").exists());
1013 }
1014
1015 #[test]
1016 fn mutation_update_accepts_unchanged_local_installs_and_refuses_foreign_scopes() {
1017 let tmp = tempfile::tempdir().unwrap();
1018 let config = config(tmp.path());
1019 let source = write_install_source(tmp.path(), "demo");
1020 let network = allow_all_network();
1021
1022 let mut registry = discover_with_config(&config);
1023 let ctx = super::mutation::PluginMutationContext {
1024 network: &network,
1025 max_size: super::install::DEFAULT_MAX_SIZE_BYTES,
1026 };
1027 block_on(super::mutation::execute(
1028 super::mutation::PluginMutationRequest::Install {
1029 source: super::install::PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
1030 },
1031 &ctx,
1032 &mut registry,
1033 ))
1034 .unwrap();
1035
1036 let installed = config.user_plugins_dir.join("demo");
1037 let before = [
1038 installed.join("plugin.toml"),
1039 installed.join("skills/hello/SKILL.md"),
1040 installed.join(codewhale_skill_install::install::INSTALLED_FROM_MARKER),
1041 ]
1042 .map(|path| {
1043 let bytes = fs::read(&path).unwrap();
1044 (path, bytes)
1045 });
1046 let state_before = fs::read(&config.state_path).ok();
1047 let mut registry = discover_with_config(&config);
1048 let receipt = block_on(super::mutation::execute(
1049 super::mutation::PluginMutationRequest::Update {
1050 selector: "demo".to_string(),
1051 },
1052 &ctx,
1053 &mut registry,
1054 ))
1055 .unwrap();
1056 assert_eq!(
1057 receipt.outcome,
1058 super::mutation::PluginMutationOutcome::NoChange
1059 );
1060 for (path, bytes) in before {
1061 assert_eq!(fs::read(path).unwrap(), bytes);
1062 }
1063 assert_eq!(fs::read(&config.state_path).ok(), state_before);
1064
1065 let workspace_bundle = config.workspace_plugins_dir.join("workspace-demo");
1066 fs::create_dir_all(&workspace_bundle).unwrap();
1067 let workspace_manifest =
1068 b"schema_version = 1\n[plugin]\nname = \"workspace-demo\"\nversion = \"1.0.0\"\n";
1069 fs::write(workspace_bundle.join("plugin.toml"), workspace_manifest).unwrap();
1070 let mut registry = discover_with_config(&config);
1071 let err = block_on(super::mutation::execute(
1072 super::mutation::PluginMutationRequest::Update {
1073 selector: "workspace-demo".to_string(),
1074 },
1075 &ctx,
1076 &mut registry,
1077 ))
1078 .unwrap_err();
1079 assert!(
1080 format!("{err:#}").contains("only user-scope bundles"),
1081 "got: {err:#}"
1082 );
1083 assert!(
1084 format!("{err:#}").contains("workspace bundle"),
1085 "got: {err:#}"
1086 );
1087 assert_eq!(
1088 fs::read(workspace_bundle.join("plugin.toml")).unwrap(),
1089 workspace_manifest
1090 );
1091 assert!(!config.user_plugins_dir.join("workspace-demo").exists());
1092
1093 let err = block_on(super::mutation::execute(
1094 super::mutation::PluginMutationRequest::Update {
1095 selector: "missing".to_string(),
1096 },
1097 &ctx,
1098 &mut registry,
1099 ))
1100 .unwrap_err();
1101 assert!(format!("{err:#}").contains("was not found"), "got: {err:#}");
1102 }
1103
1104 // ─────────────────────────────────────────────────────────────────────────────
1105 // Agent Plugins v1.0.0 (plugin.json / mcp.json) interop
1106 // ─────────────────────────────────────────────────────────────────────────────
1107
1108 fn write_json_bundle(config: &DiscoveryConfig, dir: &str, plugin_json: &str) -> PathBuf {
1109 let plugin = config.user_plugins_dir.join(dir);
1110 fs::create_dir_all(&plugin).unwrap();
1111 fs::write(plugin.join("plugin.json"), plugin_json).unwrap();
1112 plugin
1113 }
1114
1115 #[test]
1116 fn third_party_agent_plugin_with_unknown_extension_namespace_loads_cleanly() {
1117 let tmp = tempfile::tempdir().unwrap();
1118 let config = config(tmp.path());
1119 let plugin = write_json_bundle(
1120 &config,
1121 "third-party",
1122 r#"{
1123 "$schema": "https://agent-plugins.org/schemas/plugin.json",
1124 "name": "third-party",
1125 "version": "1.4.2",
1126 "description": "A plugin authored for another client",
1127 "author": {"name": "Other Client", "email": "plugins@other.example"},
1128 "keywords": ["browser", "remote"],
1129 "extensions": {
1130 "com.example.client": {"anything": [1, 2, 3], "nested": {"x": true}},
1131 "net.codewhale": {"capabilities": {"network_hosts": ["example.com"]}}
1132 }
1133 }"#,
1134 );
1135 fs::create_dir_all(plugin.join("skills/demo")).unwrap();
1136 fs::write(
1137 plugin.join("skills/demo/SKILL.md"),
1138 "---\nname: demo\ndescription: demo skill\n---\nbody\n",
1139 )
1140 .unwrap();
1141 fs::create_dir_all(plugin.join("bin")).unwrap();
1142 fs::write(
1143 plugin.join("mcp.json"),
1144 r#"{
1145 "$schema": "https://agent-plugins.org/schemas/mcp.json",
1146 "mcpServers": {
1147 "local": {
1148 "type": "stdio",
1149 "command": "run.sh",
1150 "args": ["--port", "8080"],
1151 "env": {"API_KEY": "${THIRD_PARTY_API_KEY}"},
1152 "cwd": "bin"
1153 },
1154 "remote": {
1155 "type": "sse",
1156 "url": "https://example.com/mcp",
1157 "extensions": {
1158 "net.codewhale": {"env_headers": {"Authorization": "THIRD_PARTY_REMOTE_TOKEN"}},
1159 "com.example.client": {"polling": true}
1160 }
1161 }
1162 }
1163 }"#,
1164 )
1165 .unwrap();
1166
1167 let registry = discover_with_config(&config);
1168 let errors: Vec<_> = registry
1169 .diagnostics()
1170 .iter()
1171 .filter(|diagnostic| diagnostic.level == super::types::PluginDiagnosticLevel::Error)
1172 .collect();
1173 assert!(
1174 errors.is_empty(),
1175 "unexpected error diagnostics: {errors:?}"
1176 );
1177
1178 let plugin = registry
1179 .get("third-party")
1180 .expect("third-party plugin loads");
1181 assert_eq!(
1182 plugin.manifest.plugin.author.as_deref(),
1183 Some("Other Client <plugins@other.example>")
1184 );
1185 assert_eq!(plugin.manifest.plugin.keywords, vec!["browser", "remote"]);
1186 assert_eq!(plugin.inventory.skills, 1);
1187 assert_eq!(plugin.inventory.mcp_servers, 2);
1188 assert_eq!(plugin.inventory.stdio_mcp_servers, 1);
1189 assert_eq!(plugin.inventory.remote_mcp_servers, 1);
1190 assert_eq!(plugin.skill_snapshots.len(), 1);
1191 assert_eq!(plugin.skill_snapshots[0].name, "demo");
1192
1193 let servers = plugin.manifest.mcp_servers.as_ref().unwrap();
1194 assert_eq!(servers["local"].command.as_deref(), Some("run.sh"));
1195 assert_eq!(servers["local"].env["API_KEY"], "${THIRD_PARTY_API_KEY}");
1196 assert_eq!(servers["remote"].transport.as_deref(), Some("sse"));
1197 assert_eq!(
1198 servers["remote"].env_headers["Authorization"],
1199 "THIRD_PARTY_REMOTE_TOKEN"
1200 );
1201 }
1202
1203 #[test]
1204 fn discovery_prefers_plugin_json_over_legacy_toml() {
1205 let tmp = tempfile::tempdir().unwrap();
1206 let config = config(tmp.path());
1207 let plugin = config.user_plugins_dir.join("dual");
1208 fs::create_dir_all(&plugin).unwrap();
1209 fs::write(
1210 plugin.join("plugin.toml"),
1211 "schema_version = 1\n[plugin]\nname = \"toml-legacy\"\nversion = \"1.0.0\"\n",
1212 )
1213 .unwrap();
1214 fs::write(
1215 plugin.join("plugin.json"),
1216 r#"{"$schema": "https://agent-plugins.org/schemas/plugin.json", "name": "json-native", "version": "1.0.0"}"#,
1217 )
1218 .unwrap();
1219
1220 let registry = discover_with_config(&config);
1221 assert!(registry.get("json-native").is_some());
1222 assert!(registry.get("toml-legacy").is_none());
1223 }
1224
1225 #[test]
1226 fn legacy_toml_names_with_double_hyphens_still_load() {
1227 let tmp = tempfile::tempdir().unwrap();
1228 let config = config(tmp.path());
1229 write_named_plugin(&config, "a--b", "");
1230 let registry = discover_with_config(&config);
1231 assert!(
1232 registry.get("a--b").is_some(),
1233 "the legacy plugin.toml name rule keeps `--` runs readable"
1234 );
1235 }
1236
1237 #[test]
1238 fn plugin_json_with_reserved_mcp_env_name_is_rejected() {
1239 let tmp = tempfile::tempdir().unwrap();
1240 let config = config(tmp.path());
1241 let plugin = write_json_bundle(
1242 &config,
1243 "env-bad",
1244 r#"{"$schema": "https://agent-plugins.org/schemas/plugin.json", "name": "env-bad", "version": "1.0.0"}"#,
1245 );
1246 fs::write(
1247 plugin.join("mcp.json"),
1248 r#"{"mcpServers": {"x": {"command": "run", "env": {"PLUGIN_ROOT": "/tmp"}}}}"#,
1249 )
1250 .unwrap();
1251
1252 let registry = discover_with_config(&config);
1253 assert!(registry.get("env-bad").is_none());
1254 assert!(
1255 registry.diagnostics().iter().any(|diagnostic| {
1256 diagnostic.level == super::types::PluginDiagnosticLevel::Error
1257 && diagnostic.message.contains("PLUGIN_ROOT")
1258 }),
1259 "expected a PLUGIN_ROOT diagnostic, got {:?}",
1260 registry.diagnostics()
1261 );
1262 }
1263
1264 #[test]
1265 fn export_writes_spec_valid_bundle_that_rediscovers() {
1266 let tmp = tempfile::tempdir().unwrap();
1267 let config = config(tmp.path());
1268 let plugin = write_named_plugin(
1269 &config,
1270 "demo",
1271 "[skills]\npath = \"skills\"\n\n[mcp_servers.local]\ncommand = \"run.sh\"\n",
1272 );
1273 fs::create_dir_all(plugin.join("skills/hello")).unwrap();
1274 fs::write(
1275 plugin.join("skills/hello/SKILL.md"),
1276 "---\nname: hello\ndescription: hello skill\n---\nbody\n",
1277 )
1278 .unwrap();
1279
1280 let registry = discover_with_config(&config);
1281 let loaded = registry.get("demo").cloned().unwrap();
1282 let target = tmp.path().join("exported/demo-export");
1283 let receipt =
1284 super::export::export_plugin_bundle(&loaded, &target, &Default::default()).unwrap();
1285 assert_eq!(receipt.exported_name, "demo");
1286 assert_eq!(receipt.display_name, None);
1287 assert!(receipt.wrote_mcp_json);
1288 assert!(!receipt.skills_normalized);
1289
1290 // The emitted documents exist, conform to the standard's shape, and the
1291 // legacy manifest is not carried over.
1292 let plugin_json: serde_json::Value =
1293 serde_json::from_str(&fs::read_to_string(target.join("plugin.json")).unwrap()).unwrap();
1294 super::agent_plugin::validate_plugin_json(&plugin_json).unwrap();
1295 assert_eq!(plugin_json["name"], "demo");
1296 let mcp_json: serde_json::Value =
1297 serde_json::from_str(&fs::read_to_string(target.join("mcp.json")).unwrap()).unwrap();
1298 super::agent_plugin::validate_mcp_json(&mcp_json).unwrap();
1299 assert_eq!(mcp_json["mcpServers"]["local"]["type"], "stdio");
1300 assert_eq!(mcp_json["mcpServers"]["local"]["command"], "run.sh");
1301 assert!(target.join("skills/hello/SKILL.md").is_file());
1302 assert!(!target.join("plugin.toml").exists());
1303
1304 // The exported bundle is itself discoverable as an Agent Plugins bundle.
1305 let rediscovery = DiscoveryConfig {
1306 workspace: tmp.path().join("project2"),
1307 user_plugins_dir: tmp.path().join("exported"),
1308 workspace_plugins_dir: tmp.path().join("workspace2"),
1309 builtin_plugin_dirs: Vec::new(),
1310 state_path: tmp.path().join("state2/plugin-state.json"),
1311 };
1312 let registry = discover_with_config(&rediscovery);
1313 let exported = registry.get("demo").expect("exported bundle rediscovers");
1314 assert_eq!(exported.inventory.skills, 1);
1315 assert_eq!(exported.inventory.mcp_servers, 1);
1316 assert_eq!(exported.inventory.stdio_mcp_servers, 1);
1317 assert_eq!(exported.skill_snapshots[0].name, "hello");
1318 }
1319
1320 #[test]
1321 fn export_slugifies_legacy_names_and_collision_is_an_error() {
1322 // Two legacy plugins whose names collide once slugified: exporting the
1323 // `a--b` bundle must fail, not silently rename.
1324 let tmp = tempfile::tempdir().unwrap();
1325 let pair_config = config(tmp.path());
1326 write_named_plugin(&pair_config, "a--b", "");
1327 write_named_plugin(&pair_config, "a-b", "");
1328 let registry = discover_with_config(&pair_config);
1329 let loaded = registry.get("a--b").cloned().unwrap();
1330 let existing: std::collections::BTreeSet<String> = registry
1331 .list()
1332 .iter()
1333 .map(|plugin| plugin.name().to_string())
1334 .filter(|name| name != "a--b")
1335 .collect();
1336 let target = tmp.path().join("out");
1337 let error = super::export::export_plugin_bundle(&loaded, &target, &existing).unwrap_err();
1338 assert!(error.contains("collides"), "{error}");
1339 assert!(
1340 !target.exists(),
1341 "a failed export leaves no directory behind"
1342 );
1343
1344 // Without the collision, the export slugifies and preserves the original
1345 // name as the display name.
1346 let tmp = tempfile::tempdir().unwrap();
1347 let solo_config = config(tmp.path());
1348 write_named_plugin(&solo_config, "a--b", "");
1349 let registry = discover_with_config(&solo_config);
1350 let loaded = registry.get("a--b").cloned().unwrap();
1351 let target = tmp.path().join("out");
1352 let receipt =
1353 super::export::export_plugin_bundle(&loaded, &target, &Default::default()).unwrap();
1354 assert_eq!(receipt.exported_name, "a-b");
1355 assert_eq!(receipt.display_name.as_deref(), Some("a--b"));
1356 let plugin_json: serde_json::Value =
1357 serde_json::from_str(&fs::read_to_string(target.join("plugin.json")).unwrap()).unwrap();
1358 super::agent_plugin::validate_plugin_json(&plugin_json).unwrap();
1359 assert_eq!(plugin_json["name"], "a-b");
1360 assert_eq!(
1361 plugin_json["extensions"]["net.codewhale"]["display_name"],
1362 "a--b"
1363 );
1364 }
1365
1366 #[test]
1367 fn export_moves_custom_skills_layout_to_the_standard_tree() {
1368 let tmp = tempfile::tempdir().unwrap();
1369 let config = config(tmp.path());
1370 let plugin = config.user_plugins_dir.join("custom-skills");
1371 fs::create_dir_all(plugin.join("prompts/my-skill")).unwrap();
1372 fs::write(
1373 plugin.join("plugin.toml"),
1374 "schema_version = 1\n[plugin]\nname = \"custom-skills\"\nversion = \"1.0.0\"\n[skills]\npath = \"prompts\"\n",
1375 )
1376 .unwrap();
1377 fs::write(
1378 plugin.join("prompts/my-skill/SKILL.md"),
1379 "---\nname: my-skill\ndescription: custom layout\n---\nbody\n",
1380 )
1381 .unwrap();
1382
1383 let registry = discover_with_config(&config);
1384 let loaded = registry.get("custom-skills").cloned().unwrap();
1385 assert_eq!(loaded.skill_snapshots.len(), 1);
1386
1387 let target = tmp.path().join("exported/custom-skills");
1388 let receipt =
1389 super::export::export_plugin_bundle(&loaded, &target, &Default::default()).unwrap();
1390 assert!(receipt.skills_normalized);
1391 assert!(target.join("skills/my-skill/SKILL.md").is_file());
1392 assert!(!target.join("prompts").exists());
1393 let plugin_json: serde_json::Value =
1394 serde_json::from_str(&fs::read_to_string(target.join("plugin.json")).unwrap()).unwrap();
1395 super::agent_plugin::validate_plugin_json(&plugin_json).unwrap();
1396 assert!(
1397 plugin_json.get("extensions").is_none(),
1398 "a standard-layout bundle emits no Codewhale extension at all: {plugin_json}"
1399 );
1400
1401 let rediscovery = DiscoveryConfig {
1402 workspace: tmp.path().join("project2"),
1403 user_plugins_dir: tmp.path().join("exported"),
1404 workspace_plugins_dir: tmp.path().join("workspace2"),
1405 builtin_plugin_dirs: Vec::new(),
1406 state_path: tmp.path().join("state2/plugin-state.json"),
1407 };
1408 let registry = discover_with_config(&rediscovery);
1409 let exported = registry
1410 .get("custom-skills")
1411 .expect("normalized bundle rediscovers");
1412 assert_eq!(exported.inventory.skills, 1);
1413 assert_eq!(exported.skill_snapshots[0].name, "my-skill");
1414 }
1415
1416 #[test]
1417 fn export_skills_normalization_collision_is_an_error() {
1418 let tmp = tempfile::tempdir().unwrap();
1419 let config = config(tmp.path());
1420 let plugin = config.user_plugins_dir.join("colliding-skills");
1421 fs::create_dir_all(plugin.join("skills/dup")).unwrap();
1422 fs::create_dir_all(plugin.join("prompts/dup")).unwrap();
1423 fs::write(
1424 plugin.join("plugin.toml"),
1425 "schema_version = 1\n[plugin]\nname = \"colliding-skills\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\npaths = [\"prompts\"]\n",
1426 )
1427 .unwrap();
1428 fs::write(
1429 plugin.join("skills/dup/SKILL.md"),
1430 "---\nname: first\ndescription: one\n---\nbody\n",
1431 )
1432 .unwrap();
1433 fs::write(
1434 plugin.join("prompts/dup/SKILL.md"),
1435 "---\nname: second\ndescription: two\n---\nbody\n",
1436 )
1437 .unwrap();
1438
1439 let registry = discover_with_config(&config);
1440 let loaded = registry.get("colliding-skills").cloned().unwrap();
1441 assert_eq!(loaded.skill_snapshots.len(), 2);
1442 let target = tmp.path().join("out");
1443 let error =
1444 super::export::export_plugin_bundle(&loaded, &target, &Default::default()).unwrap_err();
1445 assert!(error.contains("collision"), "{error}");
1446 assert!(
1447 !target.exists(),
1448 "a failed export removes the directory it created"
1449 );
1450 }
1451
1452 fn policy_path(config: &DiscoveryConfig) -> PathBuf {
1453 config
1454 .state_path
1455 .parent()
1456 .expect("state path has a parent")
1457 .join(MANAGED_POLICY_FILE_NAME)
1458 }
1459
1460 fn write_policy(path: &Path, policy: &ManagedPluginPolicy) {
1461 fs::create_dir_all(path.parent().expect("policy path has a parent")).unwrap();
1462 fs::write(path, serde_json::to_string_pretty(policy).unwrap()).unwrap();
1463 }
1464
1465 fn restrictive_policy() -> ManagedPluginPolicy {
1466 ManagedPluginPolicy {
1467 schema_version: MANAGED_POLICY_SCHEMA_VERSION,
1468 allowed_plugins: Default::default(),
1469 allow_unlisted: false,
1470 }
1471 }
1472
1473 #[test]
1474 fn absent_managed_policy_preserves_today_enablement() {
1475 let tmp = tempfile::tempdir().unwrap();
1476 let config = config(tmp.path());
1477 write_plugin(&config, "");
1478
1479 let mut registry = discover_with_config(&config);
1480 assert!(registry.managed_policy_error().is_none());
1481 assert_eq!(
1482 registry.managed_policy_path(),
1483 Some(policy_path(&config).as_path())
1484 );
1485 assert!(
1486 !registry
1487 .diagnostics()
1488 .iter()
1489 .any(|diagnostic| diagnostic.code == "policy-invalid"),
1490 "no policy file means no policy diagnostic"
1491 );
1492
1493 registry.trust("demo").unwrap();
1494 registry.enable("demo").unwrap();
1495 assert!(registry.is_active("demo"));
1496
1497 let reloaded = discover_with_config(&config);
1498 assert!(
1499 reloaded.is_active("demo"),
1500 "absent policy must keep today's restart behaviour"
1501 );
1502 }
1503
1504 #[test]
1505 fn managed_policy_refuses_unlisted_enable_with_named_reason() {
1506 let tmp = tempfile::tempdir().unwrap();
1507 let config = config(tmp.path());
1508 write_plugin(&config, "");
1509 write_named_plugin(&config, "extra", "");
1510
1511 // Review first: trust hardens the state directory, and the policy file
1512 // lands next to it afterwards, the way an organization delivery would.
1513 let mut registry = discover_with_config(&config);
1514 registry.trust("demo").unwrap();
1515 registry.trust("extra").unwrap();
1516 let extra_id = registry.get("extra").expect("extra plugin").id.clone();
1517
1518 write_policy(
1519 &policy_path(&config),
1520 &ManagedPluginPolicy {
1521 schema_version: MANAGED_POLICY_SCHEMA_VERSION,
1522 allowed_plugins: [extra_id].into_iter().collect(),
1523 allow_unlisted: false,
1524 },
1525 );
1526
1527 let mut registry = discover_with_config(&config);
1528
1529 let error = registry.enable("demo").unwrap_err();
1530 assert!(
1531 error.contains("managed plugin policy"),
1532 "refusal must name the policy: {error}"
1533 );
1534 assert!(
1535 error.contains("not on the plugin allowlist"),
1536 "refusal must say why: {error}"
1537 );
1538 assert!(!registry.is_enabled("demo"));
1539 assert!(!registry.is_active("demo"));
1540
1541 registry.enable("extra").unwrap();
1542 assert!(registry.is_active("extra"));
1543
1544 // Flipping the document to allow unlisted plugins applies to the live
1545 // registry: `enable` re-reads the policy instead of trusting its snapshot.
1546 write_policy(
1547 &policy_path(&config),
1548 &ManagedPluginPolicy {
1549 schema_version: MANAGED_POLICY_SCHEMA_VERSION,
1550 allowed_plugins: Default::default(),
1551 allow_unlisted: true,
1552 },
1553 );
1554 registry.enable("demo").unwrap();
1555 assert!(registry.is_active("demo"));
1556 }
1557
1558 #[test]
1559 fn plugin_enabled_before_policy_arrived_does_not_survive_rediscovery() {
1560 let tmp = tempfile::tempdir().unwrap();
1561 let config = config(tmp.path());
1562 write_plugin(&config, "");
1563
1564 let mut registry = discover_with_config(&config);
1565 registry.trust("demo").unwrap();
1566 registry.enable("demo").unwrap();
1567 assert!(registry.is_active("demo"));
1568
1569 let authority = registry.authority_for("demo").unwrap();
1570 assert!(super::registry::verify_plugin_state_authority(&authority).is_ok());
1571 let serialized = serde_json::to_value(&authority).unwrap();
1572 assert!(serialized.get("managed_policy_source").is_none());
1573 let unbound: codewhale_config::PluginAuthority = serde_json::from_value(serialized).unwrap();
1574 assert!(unbound.managed_policy_source.is_none());
1575 assert!(super::registry::verify_plugin_state_authority(&unbound).is_err());
1576
1577 write_policy(&policy_path(&config), &restrictive_policy());
1578 assert!(
1579 super::registry::verify_plugin_state_authority(&authority)
1580 .unwrap_err()
1581 .contains("managed plugin policy")
1582 );
1583 let mut redirected = authority.clone();
1584 redirected.managed_policy_path = Some(tmp.path().join("absent-policy.json"));
1585 assert!(
1586 super::registry::verify_plugin_state_authority(&redirected)
1587 .unwrap_err()
1588 .contains("trusted managed policy source")
1589 );
1590
1591 let reloaded = discover_with_config(&config);
1592 assert!(
1593 !reloaded.is_enabled("demo"),
1594 "a forbidden plugin must not come back enabled"
1595 );
1596 assert!(!reloaded.is_active("demo"));
1597 }
1598
1599 #[test]
1600 fn hand_edited_enabled_state_does_not_defeat_policy() {
1601 let tmp = tempfile::tempdir().unwrap();
1602 let config = config(tmp.path());
1603 write_plugin(&config, "");
1604
1605 let mut registry = discover_with_config(&config);
1606 registry.trust("demo").unwrap();
1607 let id = registry
1608 .get("demo")
1609 .expect("demo plugin")
1610 .id
1611 .as_str()
1612 .to_string();
1613
1614 // Forge the exact attack: flip the persisted bit by hand.
1615 let raw = fs::read_to_string(&config.state_path).unwrap();
1616 let mut state: serde_json::Value = serde_json::from_str(&raw).unwrap();
1617 state["plugins"][id.as_str()]["enabled"] = serde_json::Value::Bool(true);
1618 fs::write(
1619 &config.state_path,
1620 serde_json::to_string_pretty(&state).unwrap(),
1621 )
1622 .unwrap();
1623
1624 // Control: without a policy the forged bit comes back enabled and active.
1625 let unpoliced = discover_with_config(&config);
1626 assert!(unpoliced.is_enabled("demo"));
1627 assert!(unpoliced.is_active("demo"));
1628
1629 write_policy(&policy_path(&config), &restrictive_policy());
1630
1631 let policed = discover_with_config(&config);
1632 assert!(
1633 !policed.is_enabled("demo"),
1634 "hand-edited enabled:true must not survive a forbidding policy"
1635 );
1636 assert!(!policed.is_active("demo"));
1637 }
1638
1639 #[test]
1640 fn malformed_managed_policy_fails_closed() {
1641 let tmp = tempfile::tempdir().unwrap();
1642 let config = config(tmp.path());
1643 write_plugin(&config, "");
1644
1645 let mut registry = discover_with_config(&config);
1646 registry.trust("demo").unwrap();
1647 registry.enable("demo").unwrap();
1648 assert!(registry.is_active("demo"));
1649
1650 let path = policy_path(&config);
1651 fs::create_dir_all(path.parent().unwrap()).unwrap();
1652
1653 fs::write(&path, "{ malformed").unwrap();
1654 let mut registry = discover_with_config(&config);
1655 assert!(
1656 registry
1657 .managed_policy_error()
1658 .is_some_and(|error| error.contains("failed to parse")),
1659 "garbage policy must report a clear load error"
1660 );
1661 assert!(
1662 registry
1663 .diagnostics()
1664 .iter()
1665 .any(|diagnostic| diagnostic.code == "policy-invalid"),
1666 "garbage policy must leave a registry diagnostic"
1667 );
1668 assert!(
1669 !registry.is_enabled("demo"),
1670 "a malformed policy must not leave the plugin enabled"
1671 );
1672 assert!(!registry.is_active("demo"));
1673 let error = registry.enable("demo").unwrap_err();
1674 assert!(
1675 error.contains("Managed plugin policy"),
1676 "fail-closed refusal must name the policy: {error}"
1677 );
1678
1679 fs::write(
1680 &path,
1681 r#"{"schema_version":999,"allowed_plugins":[],"allow_unlisted":false}"#,
1682 )
1683 .unwrap();
1684 let registry = discover_with_config(&config);
1685 assert!(
1686 registry
1687 .managed_policy_error()
1688 .is_some_and(|error| error.contains("unsupported managed plugin policy schema")),
1689 "wrong-schema policy must fail closed with a clear error"
1690 );
1691 assert!(!registry.is_enabled("demo"));
1692
1693 fs::write(
1694 &path,
1695 r#"{"schema_version":1,"allowed_plugins":[],"allow_unlisted":false,"surprise":true}"#,
1696 )
1697 .unwrap();
1698 let registry = discover_with_config(&config);
1699 assert!(
1700 registry.managed_policy_error().is_some(),
1701 "unknown policy fields must fail closed like unknown state fields"
1702 );
1703 assert!(!registry.is_enabled("demo"));
1704 }
1705
1706 #[test]
1707 fn managed_policy_path_env_override_is_honored() {
1708 let tmp = tempfile::tempdir().unwrap();
1709 let config = config(tmp.path());
1710 write_plugin(&config, "");
1711
1712 let custom = tmp.path().join("custom-policy.json");
1713 write_policy(&custom, &restrictive_policy());
1714 assert!(
1715 !policy_path(&config).exists(),
1716 "the default sibling must stay absent so the override is proven"
1717 );
1718
1719 let environment = super::context::HostEnvironment::from_entries([(
1720 std::ffi::OsString::from(MANAGED_POLICY_PATH_ENV),
1721 custom.as_os_str().to_os_string(),
1722 )]);
1723 let context =
1724 super::context::PluginDiscoveryContext::from_config_and_environment(&config, environment);
1725 let mut registry = super::discovery::discover_with_context(&config, context);
1726 assert_eq!(
1727 registry.managed_policy_path(),
1728 Some(custom.as_path()),
1729 "the env override must win over the default sibling path"
1730 );
1731
1732 registry.trust("demo").unwrap();
1733 let error = registry.enable("demo").unwrap_err();
1734 assert!(
1735 error.contains("managed plugin policy"),
1736 "override policy must refuse with the named reason: {error}"
1737 );
1738 assert!(!registry.is_enabled("demo"));
1739 let relative = PathBuf::from("relative-managed-policy.json");
1740 let launch_directory = std::env::current_dir().unwrap();
1741 let environment = super::context::HostEnvironment::from_entries([(
1742 std::ffi::OsString::from(MANAGED_POLICY_PATH_ENV),
1743 relative.as_os_str().to_os_string(),
1744 )]);
1745 let context =
1746 super::context::PluginDiscoveryContext::from_config_and_environment(&config, environment);
1747 assert_eq!(
1748 context.managed_policy_source().unwrap(),
1749 launch_directory.join(relative)
1750 );
1751 assert!(context.managed_policy_source().unwrap().is_absolute());
1752 }
1753
1754 #[tokio::test]
1755 async fn component_file_names_list_files_not_folders() {
1756 let dir = tempfile::tempdir().expect("tempdir");
1757 let commands = dir.path().join("commands");
1758 std::fs::create_dir_all(&commands).expect("commands dir");
1759 std::fs::write(commands.join("Ship.md"), "x").expect("ship");
1760 std::fs::write(commands.join("notes.txt"), "x").expect("notes");
1761 let single = dir.path().join("solo.md");
1762 std::fs::write(&single, "x").expect("solo");
1763 let (names, cut) = crate::runtime::component_file_names(
1764 &[commands.clone(), single, dir.path().join("missing")],
1765 Some("md"),
1766 true,
1767 512,
1768 )
1769 .await;
1770 assert_eq!(names, vec!["ship".to_string(), "solo".to_string()]);
1771 assert!(!cut);
1772 let (limited, cut) = crate::runtime::component_file_names(&[commands], None, false, 1).await;
1773 assert_eq!(limited.len(), 1);
1774 assert!(cut);
1775 }
1776
1776 lines RUST