返回 CodeWhale
tests.rs
1 //! Extension host tests.
2 //!
3 //! Unit tests (protocol corpus, registry rules, tool gating) need no Node.
4 //! Integration tests spawn the *committed* bundle under a real Node ≥22.19:
5 //! they skip with a printed reason when none is found, unless
6 //! `CODEWHALE_EXT_HOST_TESTS=1` is set (CI), where a missing Node fails.
7
8 use std::collections::BTreeSet;
9 use std::path::{Path, PathBuf};
10 use std::sync::Arc;
11 use std::time::{Duration, Instant};
12
13 use serde_json::{Value, json};
14
15 use super::protocol::{
16 self, RegisterKind, RegisterParams, RegisterSpecWire, parse_core_message, parse_host_message,
17 };
18 use super::registry::{OwnerRegistry, OwnerState};
19 use super::test_support::*;
20 use super::tier::{HostCohort, HostTier};
21 use super::{ExtensionHostManager, ExtensionHostOptions, HostAttachment, HostStatus};
22 use crate::command_catalog::CatalogGuard;
23 use crate::tools::spec::{ApprovalRequirement, ToolContext, ToolError, ToolSpec};
24 use codewhale_config::OwnerRef;
25 use codewhale_plugins::PluginRegistry;
26 use codewhale_plugins::activation::TestPolicyGuard;
27 use codewhale_plugins::discovery::{DiscoveryConfig, discover_with_config};
28
29 /// The integration tests below run the host on Node unless they say
30 /// otherwise; the Bun ones pin Bun (`bun_for_tests`).
31 const NODE: codewhale_config::extension_host::ExtensionHostRuntime =
32 codewhale_config::extension_host::ExtensionHostRuntime::Node;
33
34 // ---------------------------------------------------------------------------
35 // Protocol
36 // ---------------------------------------------------------------------------
37
38 #[test]
39 fn protocol_corpus_parses_and_round_trips_in_both_directions() {
40 let dir = fixtures_dir().join("protocol");
41 let mut entries: Vec<_> = std::fs::read_dir(&dir)
42 .expect("corpus dir")
43 .map(|entry| entry.expect("entry").path())
44 .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
45 .collect();
46 entries.sort();
47 let (mut valid, mut invalid) = (0, 0);
48 for path in entries {
49 let case: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
50 let frame = case["frame"].clone();
51 let direction = case["direction"].as_str().unwrap();
52 let expect_valid = case["valid"].as_bool().unwrap();
53 let name = path.file_name().unwrap().to_string_lossy();
54 // Every method allows both tiers today, so a case reads the same under
55 // either (the tier rule itself is `protocol::tests`).
56 for tier in HostTier::ALL {
57 let reencoded = match direction {
58 "host_to_core" => parse_host_message(frame.clone(), tier).map(|m| m.to_value()),
59 "core_to_host" => parse_core_message(frame.clone(), tier).map(|m| m.to_value()),
60 other => panic!("unknown direction {other}"),
61 };
62 if expect_valid {
63 let reencoded = reencoded.unwrap_or_else(|e| panic!("{name} ({tier:?}): {e}"));
64 assert_eq!(
65 reencoded, frame,
66 "{name} ({tier:?}) must round-trip exactly"
67 );
68 } else {
69 assert!(reencoded.is_err(), "{name} ({tier:?}) must be rejected");
70 }
71 }
72 if expect_valid {
73 let bytes = protocol::encode_frame(&frame).unwrap();
74 assert_eq!(&bytes[..4], b"CWX1");
75 valid += 1;
76 } else {
77 invalid += 1;
78 }
79 }
80 assert!(
81 valid >= 15 && invalid >= 8,
82 "corpus too small: {valid} valid, {invalid} invalid"
83 );
84 }
85
86 #[tokio::test]
87 async fn route_service_moves_to_the_next_workspace_after_the_first_attachment_retires() {
88 let Some(node) = node_for_tests("route_workspace_handoff") else {
89 return;
90 };
91 let _policy = TestPolicyGuard::extension_host(true);
92 let fixture = FixturePlugins::new(&["slow-tool"]).await;
93 let manager = fixture.manager(node);
94 let a = fixture.registry();
95 let authority_a = a.authority_for("slow-tool").unwrap();
96 let workspace = fixture.workspace().with_file_name("workspace-b");
97 std::fs::create_dir_all(&workspace).unwrap();
98 let b = Arc::new(discover_with_config(&DiscoveryConfig {
99 workspace_plugins_dir: workspace.join(".codewhale/plugins"),
100 workspace,
101 ..fixture.config.clone()
102 }));
103 let authority_b = b.authority_for("slow-tool").unwrap();
104 assert_eq!(authority_a.plugin_id, authority_b.plugin_id);
105 let first = manager.attach_plugin_route(a, authority_a.clone());
106 first.reconcile().await.unwrap();
107 let second = manager.attach_plugin_route(b, authority_b.clone());
108 second.reconcile().await.unwrap();
109 assert_eq!(manager.native_service_state(&authority_a), "active");
110 assert_eq!(
111 manager.native_service_state(&authority_b),
112 "workspace_conflict"
113 );
114 assert!(
115 manager
116 .shared
117 .live_host_for_plugin_authority(&authority_b)
118 .await
119 .is_err()
120 );
121 drop(first);
122 second.reconcile().await.unwrap();
123 assert_eq!(manager.native_service_state(&authority_b), "active");
124 assert!(
125 manager
126 .shared
127 .live_host_for_plugin_authority(&authority_a)
128 .await
129 .is_err()
130 );
131 drop(second);
132 manager.reconcile().await.unwrap();
133 assert_eq!(manager.native_service_state(&authority_b), "not_started");
134 manager.shutdown().await;
135 }
136
137 #[tokio::test]
138 async fn frames_decode_in_order_and_violations_are_typed() {
139 let mut bytes = protocol::encode_frame(&json!({"a": 1})).unwrap();
140 bytes.extend(protocol::encode_frame(&json!({"b": "ü"})).unwrap());
141 let mut reader = bytes.as_slice();
142 assert_eq!(
143 protocol::read_frame(&mut reader).await.unwrap(),
144 Some(json!({"a": 1}))
145 );
146 assert_eq!(
147 protocol::read_frame(&mut reader).await.unwrap(),
148 Some(json!({"b": "ü"}))
149 );
150 assert_eq!(protocol::read_frame(&mut reader).await.unwrap(), None);
151
152 let mut bad = b"NOPE\0\0\0\0".as_slice();
153 assert!(matches!(
154 protocol::read_frame(&mut bad).await,
155 Err(protocol::FrameError::BadMagic)
156 ));
157 let mut huge = Vec::from(*b"CWX1");
158 huge.extend(((protocol::MAX_FRAME + 1) as u32).to_le_bytes());
159 assert!(matches!(
160 protocol::read_frame(&mut huge.as_slice()).await,
161 Err(protocol::FrameError::TooLarge(_))
162 ));
163 }
164
165 // ---------------------------------------------------------------------------
166 // Owner registry
167 // ---------------------------------------------------------------------------
168
169 fn register(registry: &mut OwnerRegistry, owner: &OwnerRef, name: &str) -> Result<u64, String> {
170 registry.register_tool(&RegisterParams {
171 scope: None,
172 owner: owner.clone(),
173 kind: RegisterKind::Tool,
174 spec: RegisterSpecWire {
175 name: name.to_string(),
176 description: "d".to_string(),
177 input_schema: json!({"type": "object", "properties": {}})
178 .as_object()
179 .cloned(),
180 argument_hint: None,
181 },
182 })
183 }
184
185 #[test]
186 fn registry_refuses_shadowing_and_foreign_names_and_undoes_exactly_one_entry() {
187 let mut registry = OwnerRegistry::new();
188 registry.add_native_names(["grep_files"]);
189 let a = registry
190 .begin_owner(
191 HostCohort::reviewed(),
192 "a",
193 "a",
194 Some(fake_authority("a")),
195 "hash-a",
196 )
197 .unwrap();
198 let b = registry
199 .begin_owner(
200 HostCohort::reviewed(),
201 "b",
202 "b",
203 Some(fake_authority("b")),
204 "hash-b",
205 )
206 .unwrap();
207
208 // Built-ins (static, snapshot, and case-folded) and reserved prefixes.
209 for name in [
210 "read_file",
211 "grep_files",
212 "READ",
213 "tool_search",
214 "mcp_x_y",
215 "ext_z",
216 ] {
217 assert!(
218 register(&mut registry, &a, name).is_err(),
219 "{name} must be refused"
220 );
221 }
222 assert!(register(&mut registry, &a, "bad name").is_err());
223
224 let first = register(&mut registry, &a, "shared_name").unwrap();
225 // Another owner cannot take it, in any case.
226 assert!(register(&mut registry, &b, "Shared_Name").is_err());
227 // Same owner re-registering retires the old handle.
228 let second = register(&mut registry, &a, "shared_name").unwrap();
229 assert_ne!(first, second);
230 registry.mark_active(&a);
231 registry.unregister(&a, first); // stale: must not remove the newer entry
232 assert_eq!(registry.live_tools().len(), 1);
233 assert!(registry.is_live(second, &a));
234 // A foreign owner cannot unregister it either.
235 registry.unregister(&b, second);
236 assert!(registry.is_live(second, &a));
237
238 // A stale token is refused.
239 let mut stale = a.clone();
240 stale.owner_token = "not-the-token".to_string();
241 assert!(register(&mut registry, &stale, "other").is_err());
242
243 // Revocation is synchronous and total.
244 assert_eq!(registry.revoke_owner("a"), Some(a.clone()));
245 assert!(!registry.is_live(second, &a));
246 assert!(registry.live_tools().is_empty());
247 assert!(register(&mut registry, &a, "after_revoke").is_err());
248 }
249
250 /// Names that the approval tables key by name must never reach an extension:
251 /// a `fetch_url` session grant for github.com is `net:github.com`, and a
252 /// plugin tool called `web_fetch` would otherwise get that same key.
253 #[test]
254 fn registry_refuses_names_the_approval_tables_special_case() {
255 let mut registry = OwnerRegistry::new();
256 let a = registry
257 .begin_owner(
258 HostCohort::reviewed(),
259 "a",
260 "a",
261 Some(fake_authority("a")),
262 "hash-a",
263 )
264 .unwrap();
265 // Special-cased by name somewhere in the approval path; some are also
266 // natives in some modes.
267 for name in [
268 "web_fetch",
269 "exec_wait",
270 "exec_interact",
271 "task_shell_start",
272 "web_search",
273 "run_tests",
274 "run_verifiers",
275 "fim_edit",
276 "Bash",
277 "read_workspace_deps",
278 "list_things",
279 "get_secret",
280 "start_mcp_server",
281 ] {
282 let refused =
283 register(&mut registry, &a, name).expect_err(&format!("{name} must be refused"));
284 assert!(
285 refused.contains("reserved") || refused.contains("collides with a built-in"),
286 "{name}: {refused}"
287 );
288 }
289 // Not natives in any mode: only the classifier probe refuses these.
290 for name in [
291 "web_fetch",
292 "exec_wait",
293 "exec_interact",
294 "read_workspace_deps",
295 ] {
296 let refused = register(&mut registry, &a, name).unwrap_err();
297 assert!(refused.contains("reserved"), "{name}: {refused}");
298 }
299 // The fetch-family key really is shared by name: this is what the refusal
300 // protects.
301 let input = json!({"url": "https://github.com/x"});
302 assert_eq!(
303 crate::tools::approval_cache::build_approval_grouping_key("web_fetch", &input),
304 crate::tools::approval_cache::build_approval_grouping_key("fetch_url", &input),
305 );
306 // Opaque names are admitted and keyed as themselves.
307 for name in ["load_workspace_dependencies", "slow_wait", "probe_read"] {
308 register(&mut registry, &a, name).unwrap_or_else(|e| panic!("{name}: {e}"));
309 }
310 }
311
312 #[test]
313 fn registry_reserves_creator_tool_names_for_creator_host_only() {
314 let mut registry = OwnerRegistry::new();
315 let plugin = registry
316 .begin_owner(
317 HostCohort::reviewed(),
318 "rogue-plugin",
319 "rogue-plugin",
320 Some(fake_authority("rogue-plugin")),
321 "hash-plugin",
322 )
323 .unwrap();
324 let other_builtin = registry
325 .begin_owner(
326 HostCohort::Builtin,
327 "host:harness",
328 "harness",
329 None,
330 "hash-h",
331 )
332 .unwrap();
333 let creator = registry
334 .begin_owner(
335 HostCohort::Builtin,
336 "host:creator",
337 "creator",
338 None,
339 "hash-c",
340 )
341 .unwrap();
342
343 for owner in [&plugin, &other_builtin] {
344 for name in [
345 "plugin_manager",
346 "PLUGIN_MANAGER",
347 "cordis_inspect_list",
348 "CORDIS_INSPECT_LIST",
349 "cordis_inspect_query",
350 "Cordis_Inspect_Query",
351 ] {
352 let err = register(&mut registry, owner, name)
353 .expect_err(&format!("{name} must be refused for {}", owner.plugin_id));
354 assert!(
355 err.contains("collides with a built-in tool"),
356 "{name}: {err}"
357 );
358 }
359 }
360
361 for name in crate::conversation_modes::CREATOR_TOOL_NAMES {
362 register(&mut registry, &creator, name).unwrap_or_else(|e| panic!("{name}: {e}"));
363 }
364 }
365
366 #[test]
367 fn registry_enforces_schema_and_count_caps() {
368 let mut registry = OwnerRegistry::new();
369 let a = registry
370 .begin_owner(
371 HostCohort::reviewed(),
372 "a",
373 "a",
374 Some(fake_authority("a")),
375 "hash-a",
376 )
377 .unwrap();
378 let mut params = RegisterParams {
379 scope: None,
380 owner: a.clone(),
381 kind: RegisterKind::Tool,
382 spec: RegisterSpecWire {
383 name: "big".to_string(),
384 description: "x".repeat(super::registry::MAX_DESCRIPTION_BYTES + 1),
385 input_schema: json!({"type": "object"}).as_object().cloned(),
386 argument_hint: None,
387 },
388 };
389 assert!(
390 registry
391 .register_tool(&params)
392 .unwrap_err()
393 .contains("description")
394 );
395 params.spec.description = "ok".to_string();
396 params.spec.input_schema =
397 json!({"type": "object", "description": "y".repeat(super::registry::MAX_SCHEMA_BYTES)})
398 .as_object()
399 .cloned();
400 assert!(
401 registry
402 .register_tool(&params)
403 .unwrap_err()
404 .contains("schema")
405 );
406 params.spec.input_schema = json!({"type": "string"}).as_object().cloned();
407 assert!(
408 registry
409 .register_tool(&params)
410 .unwrap_err()
411 .contains("object")
412 );
413 for index in 0..super::registry::MAX_TOOLS_PER_OWNER {
414 register(&mut registry, &a, &format!("t{index}")).unwrap();
415 }
416 assert!(
417 register(&mut registry, &a, "one_too_many")
418 .unwrap_err()
419 .contains("at most")
420 );
421 }
422
423 /// A tool registered through the real admission path, as the registry hands it
424 /// to `HostToolSpec`, with `schema` as its input schema.
425 fn admitted_tool(schema: Value) -> Result<super::registry::ToolRegistration, String> {
426 let mut registry = OwnerRegistry::new();
427 let owner = registry
428 .begin_owner(
429 HostCohort::reviewed(),
430 "probe",
431 "probe",
432 Some(fake_authority("probe")),
433 "hash-probe",
434 )
435 .unwrap();
436 registry.register_tool(&RegisterParams {
437 scope: None,
438 owner: owner.clone(),
439 kind: RegisterKind::Tool,
440 spec: RegisterSpecWire {
441 name: "probe_tool".to_string(),
442 description: "d".to_string(),
443 input_schema: schema.as_object().cloned(),
444 argument_hint: None,
445 },
446 })?;
447 assert!(registry.mark_active(&owner));
448 Ok(registry.live_tools().remove(0))
449 }
450
451 #[test]
452 fn an_uncompilable_tool_schema_is_refused_at_registration_with_a_reason() {
453 for (label, schema) in [
454 (
455 "an unknown type",
456 json!({"type": "object", "properties": {"a": {"type": "nonsense"}}}),
457 ),
458 (
459 "an external $ref the core will not fetch",
460 json!({"type": "object", "properties": {"a": {"$ref": "https://example.invalid/schema.json"}}}),
461 ),
462 (
463 "a required list that is not a list",
464 json!({"type": "object", "required": "a"}),
465 ),
466 ] {
467 let reason = admitted_tool(schema).expect_err(label);
468 assert!(
469 reason.contains("probe_tool") && reason.contains("not a valid JSON Schema"),
470 "{label}: {reason}"
471 );
472 }
473 admitted_tool(json!({"type": "object", "properties": {"a": {"type": "string"}}}))
474 .expect("a valid schema is admitted");
475 }
476
477 /// What the model gets back, and what the host never sees: the tool checks the
478 /// input against its registered schema in `prepare` (before any approval
479 /// card) and again in `execute`.
480 #[tokio::test]
481 async fn tool_input_is_checked_against_the_registered_schema_before_approval_and_execution() {
482 let registration = admitted_tool(json!({
483 "type": "object",
484 "properties": {
485 "name": {"type": "string"},
486 "count": {"type": "integer", "minimum": 0}
487 },
488 "required": ["name"],
489 "additionalProperties": false
490 }))
491 .unwrap();
492 // No host is running: a call that reached it would say so (`NotAvailable`).
493 let manager = ExtensionHostManager::new(ExtensionHostOptions::default());
494 let tool = super::tool::HostToolSpec::new(registration, Arc::clone(&manager.shared));
495 let context = ToolContext::new(Path::new("/w"));
496
497 let rejected = |input: Value, expect: &[&str]| {
498 let error = tool.prepare(input.clone(), &context).unwrap_err();
499 let ToolError::InvalidInput { message } = error else {
500 panic!("{input}: not an invalid-input error: {error:?}");
501 };
502 assert!(
503 message.contains("probe_tool") && expect.iter().all(|part| message.contains(part)),
504 "{input}: {message}"
505 );
506 input
507 };
508 // Valid input passes `prepare`, with the Rust-composed approval card.
509 let prepared = tool
510 .prepare(json!({"name": "x", "count": 2}), &context)
511 .expect("valid input is admitted");
512 assert_eq!(prepared.approval, ApprovalRequirement::Required);
513 // An extra property.
514 let extra = rejected(json!({"name": "x", "surprise": true}), &["surprise"]);
515 // A wrong type, and the path of the field.
516 let wrong_type = rejected(json!({"name": 7}), &["name"]);
517 rejected(json!({"name": "x", "count": -1}), &["count"]);
518 // A missing required field, and a non-object.
519 rejected(json!({}), &["name"]);
520 rejected(json!("name"), &[]);
521
522 // `execute` refuses the same inputs without touching the host (which is
523 // not running, so reaching it would be `NotAvailable`)...
524 for input in [extra, wrong_type] {
525 let error = tool.execute(input.clone(), &context).await.unwrap_err();
526 assert!(
527 matches!(error, ToolError::InvalidInput { .. }),
528 "{input}: {error:?}"
529 );
530 }
531 assert_eq!(manager.spawn_attempts(), 0);
532 // ...while valid input gets past the check and meets the dead host.
533 let error = tool
534 .execute(json!({"name": "x"}), &context)
535 .await
536 .unwrap_err();
537 assert!(matches!(error, ToolError::NotAvailable { .. }), "{error:?}");
538 }
539
540 // ---------------------------------------------------------------------------
541 // Licence notices for the embedded bundle
542 // ---------------------------------------------------------------------------
543
544 /// Every `node_modules/<package>` the bundle was built from, read from the
545 /// bundler's own `// node_modules/...` markers in the embedded bundle (not
546 /// from the generator that writes the notices).
547 fn bundled_packages() -> BTreeSet<String> {
548 let mut packages = BTreeSet::new();
549 for bytes in [
550 super::BUNDLE,
551 include_bytes!("../../extension-host/dist/builtin/mcp.mjs").as_slice(),
552 ] {
553 let text = std::str::from_utf8(bytes).expect("the bundle is UTF-8");
554 for line in text.lines() {
555 let Some(path) = line.strip_prefix("// ") else {
556 continue;
557 };
558 let Some((_, after)) = path.rsplit_once("node_modules/") else {
559 continue;
560 };
561 let mut parts = after.split('/');
562 let first = parts.next().unwrap_or_default();
563 let name = if first.starts_with('@') {
564 format!("{first}/{}", parts.next().unwrap_or_default())
565 } else {
566 first.to_string()
567 };
568 packages.insert(name);
569 }
570 }
571 packages
572 }
573
574 /// `name@version` of every package the embedded notices list.
575 fn noticed_packages() -> Vec<(String, String)> {
576 let text = std::str::from_utf8(super::NOTICES).expect("the notices are UTF-8");
577 let listed = text
578 .split_once("\nPackages:\n")
579 .expect("the notices list their packages")
580 .1;
581 listed
582 .lines()
583 .take_while(|line| line.starts_with(" "))
584 .map(|line| {
585 let entry = line.trim().split(" (").next().unwrap();
586 let (name, version) = entry.rsplit_once('@').expect("name@version");
587 (name.to_string(), version.to_string())
588 })
589 .collect()
590 }
591
592 #[test]
593 fn materialized_bundle_directory_carries_its_licence_notices() {
594 let home = tempfile::tempdir().unwrap();
595 let bundle = super::materialize_bundle(home.path()).unwrap();
596 let dir = bundle.parent().unwrap().to_path_buf();
597 assert_eq!(
598 dir,
599 super::supervisor::bundle_dir(home.path(), super::bundle_sha256()),
600 "the notices live in the bundle's own digest-named directory"
601 );
602 let notices = dir.join("LICENSES.txt");
603 assert_eq!(std::fs::read(&notices).unwrap(), super::NOTICES);
604 assert_eq!(std::fs::read(&bundle).unwrap(), super::BUNDLE);
605 let builtin = dir.join("builtin/mcp.mjs");
606 let builtin_bytes = include_bytes!("../../extension-host/dist/builtin/mcp.mjs");
607 assert_eq!(std::fs::read(&builtin).unwrap(), builtin_bytes);
608 let pinned = super::tier::BUILTIN_MODULES
609 .iter()
610 .find(|module| module.id == "mcp")
611 .unwrap();
612 assert_eq!(
613 super::hex(Sha256::digest(builtin_bytes)),
614 pinned.source_sha256
615 );
616 assert!(
617 std::str::from_utf8(super::NOTICES)
618 .unwrap()
619 .contains("Copyright (c) 2021-present Shigma"),
620 "the notices carry the licence text, not only package names"
621 );
622 // Written like the bundle: read-only, no staging files left behind.
623 #[cfg(unix)]
624 for path in [&bundle, &notices, &builtin] {
625 use std::os::unix::fs::PermissionsExt;
626 assert_eq!(
627 std::fs::metadata(path).unwrap().permissions().mode() & 0o777,
628 0o400,
629 "{}",
630 path.display()
631 );
632 }
633 let mut names: Vec<_> = std::fs::read_dir(&dir)
634 .unwrap()
635 .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
636 .collect();
637 names.sort();
638 assert_eq!(
639 names,
640 ["LICENSES.txt", "builtin", "codewhale-extension-host.mjs"]
641 );
642 assert_eq!(
643 std::fs::read_dir(dir.join("builtin")).unwrap().count(),
644 super::tier::BUILTIN_MODULES.len()
645 );
646 for module in super::tier::BUILTIN_MODULES {
647 let path = dir.join("builtin").join(format!("{}.mjs", module.id));
648 let bytes = std::fs::read(&path).unwrap();
649 assert_eq!(super::hex(Sha256::digest(&bytes)), module.source_sha256);
650 #[cfg(unix)]
651 {
652 use std::os::unix::fs::PermissionsExt;
653 assert_eq!(
654 std::fs::metadata(path).unwrap().permissions().mode() & 0o777,
655 0o400
656 );
657 }
658 }
659
660 // A directory from a build that wrote only the bundle gets its notices; a
661 // tampered or replaced notices file is rewritten, never trusted.
662 std::fs::remove_file(&notices).unwrap();
663 super::materialize_bundle(home.path()).unwrap();
664 assert_eq!(std::fs::read(&notices).unwrap(), super::NOTICES);
665 std::fs::remove_file(&notices).unwrap();
666 std::fs::write(&notices, "tampered").unwrap();
667 super::materialize_bundle(home.path()).unwrap();
668 assert_eq!(std::fs::read(&notices).unwrap(), super::NOTICES);
669 #[cfg(unix)]
670 {
671 let elsewhere = home.path().join("elsewhere.txt");
672 std::fs::write(&elsewhere, "not the notices").unwrap();
673 std::fs::remove_file(&notices).unwrap();
674 std::os::unix::fs::symlink(&elsewhere, &notices).unwrap();
675 super::materialize_bundle(home.path()).unwrap();
676 assert!(
677 !std::fs::symlink_metadata(&notices)
678 .unwrap()
679 .file_type()
680 .is_symlink(),
681 "a symlink at the notices name is replaced, not followed"
682 );
683 assert_eq!(std::fs::read(&notices).unwrap(), super::NOTICES);
684 assert_eq!(
685 std::fs::read_to_string(&elsewhere).unwrap(),
686 "not the notices",
687 "the symlink's target is never written through"
688 );
689 }
690 }
691
692 #[test]
693 fn every_package_in_the_bundle_has_a_licence_notice_and_a_third_party_entry() {
694 let bundled = bundled_packages();
695 assert!(
696 bundled.contains("@deepseek-ai/cordis"),
697 "the scan of the bundle found no packages: {bundled:?}"
698 );
699 let noticed = noticed_packages();
700 let third_party = std::fs::read_to_string(
701 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../THIRD_PARTY_NOTICES.md"),
702 )
703 .expect("THIRD_PARTY_NOTICES.md");
704 let notice_text = std::str::from_utf8(super::NOTICES).unwrap();
705 for package in &bundled {
706 let Some((_, version)) = noticed.iter().find(|(name, _)| name == package) else {
707 panic!("`{package}` is in the host bundle but not in dist/LICENSES.txt: {noticed:?}");
708 };
709 assert!(
710 third_party.contains(&format!("`{package}` {version}")),
711 "`{package}` {version} is bundled but THIRD_PARTY_NOTICES.md does not list it"
712 );
713 let heading = format!("{package}@{version} (");
714 assert!(
715 notice_text.matches(&heading).count() >= 2,
716 "dist/LICENSES.txt lists `{package}` but carries no section with its licence text"
717 );
718 }
719 // The verbatim excerpts are not node_modules inputs; the notices still
720 // name them, and THIRD_PARTY_NOTICES.md must too.
721 for (package, version) in &noticed {
722 assert!(
723 third_party.contains(&format!("`{package}` {version}")),
724 "`{package}` {version} is in dist/LICENSES.txt but not in THIRD_PARTY_NOTICES.md"
725 );
726 }
727 }
728
729 // ---------------------------------------------------------------------------
730 // Integration: real Node, real bundle
731 // ---------------------------------------------------------------------------
732
733 /// Start budget for `dsh_plugin_runs_end_to_end_behind_the_approval_gate`:
734 /// bundle materialization, the runtime probe, the launch plan (on Linux, the
735 /// bwrap probe), spawn, handshake and one plugin's activation, under
736 /// nextest's full-core load on every CI OS. The host alone is ready in
737 /// ~50 ms (the JS suite's `READY_BUDGET_MS` gates that), but Windows CI
738 /// under load has taken over 5 s to hand-shake (`HANDSHAKE_DEADLINE`).
739 /// 20 s fails a start drifting toward that 30 s deadline, whose miss
740 /// disables every extension for the session, without failing on CI load.
741 const HOST_START_BUDGET: Duration = Duration::from_secs(20);
742
743 /// Resident-size budget for a host with one plugin active, summed over its
744 /// process tree (bwrap's two processes included on Linux). 160 MiB is 2.4x
745 /// the largest idle host measured (67 MB, Node in a Linux container:
746 /// `supervisor::HOST_MEMORY_CAP`; 57 MiB Node 26 and 41 MiB Bun 1.4 with this
747 /// plugin on macOS arm64, 2026-09-30) and far below the 1 GiB cap. Not
748 /// checked where there is no `ps` (Windows).
749 const HOST_RSS_BUDGET_MIB: u64 = 160;
750
751 /// Resident size in KiB of `pid` and every process under it — under bwrap,
752 /// `pid` is bwrap's and the runtime two levels down — from `ps`; `None` where
753 /// `ps` is missing or does not list `pid`.
754 fn tree_rss_kib(pid: u32) -> Option<u64> {
755 let output = std::process::Command::new("ps")
756 .args(["-A", "-o", "pid=,ppid=,rss="])
757 .output()
758 .ok()?;
759 let rows: Vec<[u64; 3]> = String::from_utf8_lossy(&output.stdout)
760 .lines()
761 .filter_map(|line| {
762 let fields: Vec<u64> = line
763 .split_whitespace()
764 .filter_map(|field| field.parse().ok())
765 .collect();
766 <[u64; 3]>::try_from(fields).ok()
767 })
768 .collect();
769 let root = u64::from(pid);
770 if !rows.iter().any(|row| row[0] == root) {
771 return None;
772 }
773 let mut members = vec![root];
774 let mut next = 0;
775 while let Some(&parent) = members.get(next) {
776 members.extend(
777 rows.iter()
778 .filter(|row| row[1] == parent && row[0] != parent)
779 .map(|row| row[0]),
780 );
781 next += 1;
782 }
783 Some(
784 rows.iter()
785 .filter(|row| members.contains(&row[0]))
786 .map(|row| row[2])
787 .sum(),
788 )
789 }
790
791 #[tokio::test]
792 async fn dsh_plugin_runs_end_to_end_behind_the_approval_gate() {
793 let Some(node) = node_for_tests("dsh_plugin_runs_end_to_end_behind_the_approval_gate") else {
794 return;
795 };
796 let _policy = TestPolicyGuard::extension_host(true);
797 let fixture = FixturePlugins::new(&["dsh-workspace-deps"]).await;
798 let manager = fixture.manager(node);
799 assert_eq!(
800 manager.status(),
801 HostStatus::Idle,
802 "nothing starts before sync"
803 );
804
805 let started = Instant::now();
806 let engine = manager.attach(fixture.registry());
807 engine.sync().await.unwrap();
808 let elapsed = started.elapsed();
809 let pid = manager.host_pid().expect("host running");
810 let rss = tree_rss_kib(pid);
811 eprintln!(
812 "extension host: spawn + handshake + activation {:.1} ms (budget {HOST_START_BUDGET:?}); RSS {} KiB (budget {HOST_RSS_BUDGET_MIB} MiB)",
813 elapsed.as_secs_f64() * 1000.0,
814 rss.map_or_else(|| "?".to_string(), |kib| kib.to_string())
815 );
816 assert!(
817 elapsed <= HOST_START_BUDGET,
818 "the extension host took {elapsed:?} to start, over its {HOST_START_BUDGET:?} budget"
819 );
820 match rss {
821 Some(kib) => assert!(
822 kib <= HOST_RSS_BUDGET_MIB * 1024,
823 "the extension host is {kib} KiB resident, over its {HOST_RSS_BUDGET_MIB} MiB budget"
824 ),
825 None => eprintln!("extension host RSS budget not checked: no `ps` listing here"),
826 }
827 assert_eq!(
828 manager.live_tool_names(),
829 vec!["load_workspace_dependencies"]
830 );
831 assert_eq!(
832 manager.owner_state(
833 fixture
834 .registry()
835 .get("dsh-workspace-deps")
836 .unwrap()
837 .id
838 .as_str()
839 ),
840 Some(OwnerState::Active)
841 );
842
843 let tool = host_tool(&engine, fixture.workspace(), "load_workspace_dependencies");
844 assert_eq!(tool.registration_origin(), "extension:dsh-workspace-deps");
845 // The plugin declares `presentCall: kind 'read'`; approval stays Required.
846 assert_eq!(
847 tool.approval_requirement_for(&json!({})),
848 ApprovalRequirement::Required
849 );
850 assert!(!tool.is_read_only_for(&json!({})));
851 assert!(tool.defer_loading());
852 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
853 let prepared = tool.prepare(json!({}), &context).unwrap();
854 assert_eq!(prepared.approval, ApprovalRequirement::Required);
855 assert!(
856 prepared
857 .description
858 .contains("extension:dsh-workspace-deps")
859 );
860
861 let result = tool.execute(json!({}), &context).await.unwrap();
862 assert!(result.success);
863 let payload: Value = serde_json::from_str(&result.content).unwrap();
864 assert_eq!(payload["pythonDistributions"]["numpy"], "2.1.0");
865 assert!(payload["python"].as_str().unwrap().contains("dependencies"));
866 manager.shutdown().await;
867 }
868
869 /// A manifest may declare several `native` entries. They activate under one
870 /// owner, in order. Entry-scoped failure retires that entry without taking
871 /// away a sibling selected by another caller.
872 #[tokio::test]
873 async fn a_plugin_with_two_native_entries_activates_both_under_one_owner() {
874 let Some(node) = node_for_tests("a_plugin_with_two_native_entries") else {
875 return;
876 };
877 let _policy = TestPolicyGuard::extension_host(true);
878 let fixture = FixturePlugins::new(&["two-entries", "two-entries-failing"]).await;
879 let manager = fixture.manager(node);
880 let engine = manager.attach(fixture.registry());
881 engine.sync().await.unwrap();
882 let registry = fixture.registry();
883 let id = |name: &str| registry.get(name).unwrap().id.as_str().to_string();
884
885 // Both entries are live under the one owner.
886 assert_eq!(
887 manager.owner_state(&id("two-entries")),
888 Some(OwnerState::Active)
889 );
890 let mut tools = manager.live_tool_names();
891 tools.sort();
892 assert_eq!(tools, ["tef_first", "two_first", "two_second"]);
893 assert_eq!(manager.live_command_names(), ["two-hello"]);
894 let report = manager.owner_report(&id("two-entries")).unwrap();
895 assert!(
896 report.diagnostics.iter().any(
897 |line| line.contains("tools: two_first, two_second") && line.contains("/two-hello")
898 ),
899 "{:?}",
900 report.diagnostics
901 );
902 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
903 for (name, answer) in [("two_first", "first"), ("two_second", "second")] {
904 let result = host_tool(&engine, fixture.workspace(), name)
905 .execute(json!({}), &context)
906 .await
907 .unwrap();
908 assert_eq!(result.content, answer);
909 }
910
911 // The failing entry is retired while its already-active sibling survives.
912 let failing = id("two-entries-failing");
913 assert_eq!(manager.owner_state(&failing), Some(OwnerState::Active));
914 assert!(manager.live_tool_names().contains(&"tef_first".to_string()));
915 assert!(
916 manager
917 .shared
918 .registry
919 .lock()
920 .unwrap()
921 .owner(&failing)
922 .unwrap()
923 .scopes
924 .values()
925 .any(|state| matches!(state, OwnerState::Failed(_)))
926 );
927 // The healthy plugin sharing the host is untouched, and a later reconcile
928 // does not retry the failed bytes.
929 engine.sync().await.unwrap();
930 let mut tools = manager.live_tool_names();
931 tools.sort();
932 assert_eq!(tools, ["tef_first", "two_first", "two_second"]);
933 manager.shutdown().await;
934 }
935
936 fn plugin_settings(
937 name: &str,
938 config: &str,
939 ) -> std::collections::BTreeMap<String, codewhale_config::extension_host::PluginSettings> {
940 std::collections::BTreeMap::from([(
941 name.to_string(),
942 codewhale_config::extension_host::PluginSettings {
943 config: Some(toml::from_str(config).expect("config TOML")),
944 },
945 )])
946 }
947
948 /// Run an extension tool and parse its JSON answer.
949 async fn call_json(
950 tool: &Arc<dyn ToolSpec>,
951 input: Value,
952 workspace: &Path,
953 engine: &HostAttachment,
954 ) -> Value {
955 let result = tool
956 .execute(
957 input,
958 &ToolContext::new(workspace).with_plugin_registry(engine.plugin_view()),
959 )
960 .await
961 .unwrap_or_else(|error| panic!("{error:?}"));
962 serde_json::from_str(&result.content).expect("a JSON answer")
963 }
964
965 /// The plugin's settings come from the user's config file, are bounded, and
966 /// the keys (never the values) are what `/plugin show` can list.
967 #[test]
968 fn plugin_settings_are_read_from_the_user_config_and_bounded() {
969 use super::plugin_config::{MAX_PLUGIN_CONFIG_BYTES, PluginConfigs};
970 let dir = tempfile::tempdir().unwrap();
971 let path = dir.path().join("config.toml");
972 // Other keys are none of this reader's business; `[plugins]` is.
973 std::fs::write(
974 &path,
975 "model = \"x\"\n[plugins.\"greeter\".config]\ngreeting = \"Hi\"\nlimit = 3\n[plugins.\"greeter\".config.nested]\ntags = [\"a\", \"b\"]\n[plugins.\"quiet\"]\n",
976 )
977 .unwrap();
978 let settings = codewhale_runtime::config::read_plugin_settings(&path).unwrap();
979 let mut configs = PluginConfigs::default();
980 configs.replace(&settings, Some(path.clone()));
981 assert_eq!(configs.source(), Some(path.clone()));
982 let greeter = configs.select("greeter").unwrap();
983 assert_eq!(
984 greeter.value,
985 json!({"greeting": "Hi", "limit": 3, "nested": {"tags": ["a", "b"]}})
986 );
987 // Keys only, in order; a plugin with a table but no config has nothing to list.
988 assert_eq!(
989 configs.summary("greeter").unwrap().unwrap(),
990 ["greeting", "limit", "nested"]
991 );
992 assert!(configs.summary("quiet").is_none());
993 assert!(configs.summary("nobody").is_none());
994 // No settings is an empty object, with a digest of its own.
995 let none = configs.select("nobody").unwrap();
996 assert_eq!(none.value, json!({}));
997 assert_ne!(none.hash, greeter.hash);
998 // The digest follows the value: equal for the same settings, new for a change.
999 let mut again = PluginConfigs::default();
1000 again.replace(&settings, None);
1001 assert_eq!(again.select("greeter").unwrap().hash, greeter.hash);
1002 assert_eq!(again.source(), None, "a reload names no new source");
1003 configs.replace_reloaded(&plugin_settings("greeter", "greeting = \"Yo\""));
1004 assert_ne!(configs.select("greeter").unwrap().hash, greeter.hash);
1005 assert_eq!(
1006 configs.source(),
1007 Some(path.clone()),
1008 "the source survives a reload"
1009 );
1010
1011 // A missing file has no settings; an unreadable shape or a stray key fails loudly.
1012 assert!(
1013 codewhale_runtime::config::read_plugin_settings(&dir.path().join("absent.toml"))
1014 .unwrap()
1015 .is_empty()
1016 );
1017 std::fs::write(&path, "[plugins.\"greeter\"]\nenabled = true\n").unwrap();
1018 assert!(
1019 codewhale_runtime::config::read_plugin_settings(&path)
1020 .unwrap_err()
1021 .contains("cannot parse")
1022 );
1023
1024 // Refusals name the plugin and the rule; the config is never half-delivered.
1025 let refuse = |config: &str| -> String {
1026 let mut configs = PluginConfigs::default();
1027 configs.replace(&plugin_settings("greeter", config), None);
1028 configs.select("greeter").unwrap_err()
1029 };
1030 let big = refuse(&format!(
1031 "blob = \"{}\"",
1032 "x".repeat(MAX_PLUGIN_CONFIG_BYTES)
1033 ));
1034 assert!(
1035 big.contains("greeter") && big.contains("byte limit"),
1036 "{big}"
1037 );
1038 let at_limit = format!("blob = \"{}\"", "x".repeat(MAX_PLUGIN_CONFIG_BYTES - 20));
1039 let mut ok = PluginConfigs::default();
1040 ok.replace(&plugin_settings("greeter", &at_limit), None);
1041 assert!(
1042 ok.select("greeter").is_ok(),
1043 "just under the cap is accepted"
1044 );
1045 let when = refuse("when = 1979-05-27T07:32:00Z");
1046 assert!(when.contains("date-time"), "{when}");
1047 let deep = refuse(&format!("x = {}1{}", "[".repeat(20), "]".repeat(20)));
1048 assert!(deep.contains("nests deeper"), "{deep}");
1049 // A refused config has a digest too, so it is not retried every turn but is once the file changes.
1050 let refused: Result<super::plugin_config::PluginConfig, String> = Err(big);
1051 assert!(super::plugin_config::activation_hash(&refused).starts_with("refused:"));
1052 }
1053
1054 /// The plugin's context in a real host: its settings (checked by its own
1055 /// `Config` schema), the workspace of each call, and its own data directory;
1056 /// a change of settings re-activates it under a new generation; a refused one
1057 /// fails it with the reason.
1058 #[tokio::test]
1059 async fn plugin_context_reaches_the_plugin_and_changed_settings_reactivate_it() {
1060 let Some(node) = node_for_tests("plugin_context_reaches_the_plugin") else {
1061 return;
1062 };
1063 let _policy = TestPolicyGuard::extension_host(true);
1064 let fixture = FixturePlugins::new(&["plugin-context"]).await;
1065 let manager = fixture.manager(node);
1066 let _manager = super::TestManagerGuard::install(Arc::clone(&manager));
1067 let id = fixture
1068 .registry()
1069 .get("plugin-context")
1070 .unwrap()
1071 .id
1072 .as_str()
1073 .to_string();
1074 let generation = |manager: &ExtensionHostManager| {
1075 manager
1076 .shared
1077 .registry
1078 .lock()
1079 .unwrap()
1080 .owner(&id)
1081 .map(|entry| entry.owner.generation)
1082 };
1083 manager.set_plugin_settings(
1084 &plugin_settings("plugin-context", "greeting = \"Hi\""),
1085 None,
1086 );
1087 let engine = manager.attach(fixture.registry());
1088 engine.sync().await.unwrap();
1089 assert_eq!(manager.owner_state(&id), Some(OwnerState::Active));
1090 let first_generation = generation(&manager).unwrap();
1091
1092 let data_dir = super::supervisor::plugin_data_dir(&fixture.root, &id, "plugin-context");
1093 assert!(
1094 data_dir.is_dir(),
1095 "the core made the plugin's directory before activation"
1096 );
1097 assert!(
1098 data_dir.starts_with(fixture.root.join("extension-host/data/plugins")),
1099 "{}",
1100 data_dir.display()
1101 );
1102 #[cfg(unix)]
1103 {
1104 use std::os::unix::fs::PermissionsExt;
1105 assert_eq!(
1106 std::fs::metadata(&data_dir).unwrap().permissions().mode() & 0o777,
1107 0o700
1108 );
1109 }
1110
1111 let probe = host_tool(&engine, fixture.workspace(), "ctx_probe");
1112 let seen = call_json(&probe, json!({}), fixture.workspace(), &engine).await;
1113 // The plugin's own schema supplied the default for `limit`.
1114 assert_eq!(seen["config"], json!({"greeting": "Hi", "limit": 3}));
1115 assert_eq!(seen["workspace"], fixture.workspace().to_str().unwrap());
1116 assert_eq!(seen["dataDir"], data_dir.to_str().unwrap());
1117 // The workspace is the call's own, not the process's or the plugin's.
1118 let elsewhere = fixture.workspace().join("elsewhere");
1119 let seen = call_json(&probe, json!({}), &elsewhere, &engine).await;
1120 assert_eq!(seen["workspace"], elsewhere.to_str().unwrap());
1121 // Nothing else about the machine is in the context.
1122 assert_eq!(
1123 seen["keys"],
1124 json!(["args", "callId", "dataDir", "signal", "workspace"])
1125 );
1126 // The schema refuses an unknown field before the host is asked.
1127 let error = probe
1128 .execute(
1129 json!({"home": true}),
1130 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view()),
1131 )
1132 .await
1133 .unwrap_err();
1134 assert!(matches!(error, ToolError::InvalidInput { .. }), "{error:?}");
1135
1136 // The plugin can write in its own directory, inside the host's sandbox.
1137 let note = host_tool(&engine, fixture.workspace(), "ctx_note");
1138 let written = call_json(
1139 &note,
1140 json!({"text": "remember"}),
1141 fixture.workspace(),
1142 &engine,
1143 )
1144 .await;
1145 assert_eq!(written["file"], data_dir.join("note.txt").to_str().unwrap());
1146 assert_eq!(
1147 std::fs::read_to_string(data_dir.join("note.txt")).unwrap(),
1148 "remember"
1149 );
1150
1151 // A command is told the workspace it was loaded for, and the same directory.
1152 let entries = manager.commands_for_plugins(engine.plugin_view().as_ref());
1153 let command = entries
1154 .first()
1155 .expect("the plugin's command is live")
1156 .reference();
1157 let super::command::CommandOutcome::Show { text } =
1158 super::command::run(&manager.shared, &command, "", None)
1159 .await
1160 .unwrap()
1161 else {
1162 panic!("a show answer");
1163 };
1164 let said: Value = serde_json::from_str(&text).unwrap();
1165 assert_eq!(said["workspace"], fixture.workspace().to_str().unwrap());
1166 assert_eq!(said["dataDir"], data_dir.to_str().unwrap());
1167 assert_eq!(said["config"]["greeting"], "Hi");
1168
1169 // What `/plugin show` can list: keys, not values.
1170 assert_eq!(
1171 manager
1172 .plugin_config_summary("plugin-context")
1173 .unwrap()
1174 .unwrap(),
1175 ["greeting"]
1176 );
1177
1178 // Unchanged settings never churn the owner...
1179 manager.set_plugin_settings(
1180 &plugin_settings("plugin-context", "greeting = \"Hi\""),
1181 None,
1182 );
1183 engine.sync().await.unwrap();
1184 assert_eq!(generation(&manager), Some(first_generation));
1185 // ...a changed value is a new generation with the new value...
1186 manager.set_plugin_settings(
1187 &plugin_settings("plugin-context", "greeting = \"Yo\""),
1188 None,
1189 );
1190 engine.sync().await.unwrap();
1191 assert_eq!(manager.owner_state(&id), Some(OwnerState::Active));
1192 assert!(generation(&manager).unwrap() > first_generation);
1193 let probe = host_tool(&engine, fixture.workspace(), "ctx_probe");
1194 assert_eq!(
1195 call_json(&probe, json!({}), fixture.workspace(), &engine).await["config"]["greeting"],
1196 "Yo"
1197 );
1198 // The same directory serves every generation: the note survived.
1199 assert_eq!(
1200 std::fs::read_to_string(data_dir.join("note.txt")).unwrap(),
1201 "remember"
1202 );
1203
1204 // ...a config the plugin's own schema refuses fails it with the field named
1205 // and leaves nothing live...
1206 manager.set_plugin_settings(&plugin_settings("plugin-context", "limit = 99"), None);
1207 engine.sync().await.unwrap();
1208 assert!(
1209 matches!(manager.owner_state(&id), Some(OwnerState::Failed(ref reason)) if reason.contains("limit")),
1210 "{:?}",
1211 manager.owner_state(&id)
1212 );
1213 assert!(manager.live_tool_names().is_empty());
1214 assert!(
1215 manager
1216 .commands_for_plugins(engine.plugin_view().as_ref())
1217 .is_empty()
1218 );
1219 // ...so does one over the size cap (refused before the host is asked), and
1220 // `/plugin show` says why...
1221 manager.set_plugin_settings(
1222 &plugin_settings(
1223 "plugin-context",
1224 &format!(
1225 "blob = \"{}\"",
1226 "x".repeat(super::plugin_config::MAX_PLUGIN_CONFIG_BYTES)
1227 ),
1228 ),
1229 None,
1230 );
1231 engine.sync().await.unwrap();
1232 assert!(
1233 matches!(manager.owner_state(&id), Some(OwnerState::Failed(ref reason)) if reason.contains("byte limit")),
1234 "{:?}",
1235 manager.owner_state(&id)
1236 );
1237 assert!(
1238 manager
1239 .plugin_config_summary("plugin-context")
1240 .unwrap()
1241 .is_err()
1242 );
1243 // ...and fixing the settings brings it back, without a restart.
1244 manager.set_plugin_settings(
1245 &plugin_settings("plugin-context", "greeting = \"Hello again\""),
1246 None,
1247 );
1248 engine.sync().await.unwrap();
1249 assert_eq!(manager.owner_state(&id), Some(OwnerState::Active));
1250 manager.shutdown().await;
1251 }
1252
1253 #[tokio::test]
1254 async fn execute_tools_refuses_extension_tools_before_any_host_call() {
1255 let Some(node) = node_for_tests("execute_tools_refuses_extension_tools_before_any_host_call")
1256 else {
1257 return;
1258 };
1259 let _policy = TestPolicyGuard::extension_host(true);
1260 let fixture = FixturePlugins::new(&["slow-tool"]).await;
1261 let manager = fixture.manager(node);
1262 let engine = manager.attach(fixture.registry());
1263 engine.sync().await.unwrap();
1264 let mut registry = crate::tools::registry::ToolRegistryBuilder::new()
1265 .build(ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view()));
1266 engine.install_tools(&mut registry);
1267 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
1268 let started = Instant::now();
1269 let result = crate::tools::codemode::execute_tools_tool(
1270 &json!({"code": "return await tools.call('slow_wait', { ms: 5000 })"}),
1271 &registry,
1272 &context,
1273 )
1274 .await
1275 .unwrap();
1276 // Refused at the gate: had the call reached the host it would take 5 s.
1277 assert!(started.elapsed() < Duration::from_secs(4));
1278 assert!(!result.success, "{}", result.content);
1279 assert!(
1280 result.content.contains("can mutate") || result.content.contains("needs approval"),
1281 "{}",
1282 result.content
1283 );
1284 manager.shutdown().await;
1285 }
1286
1287 #[tokio::test]
1288 async fn disabling_mid_call_revokes_at_once_and_teardown_waits_for_async_disposers() {
1289 let Some(node) = node_for_tests("disabling_mid_call") else {
1290 return;
1291 };
1292 let _policy = TestPolicyGuard::extension_host(true);
1293 let fixture = FixturePlugins::new(&["slow-tool"]).await;
1294 let manager = fixture.manager(node);
1295 let engine = manager.attach(fixture.registry());
1296 engine.sync().await.unwrap();
1297 let tool = host_tool(&engine, fixture.workspace(), "slow_wait");
1298 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
1299 let call = tokio::spawn(async move { tool.execute(json!({}), &context).await });
1300 tokio::time::sleep(Duration::from_millis(1500)).await;
1301
1302 let disabled = fixture.disable("slow-tool");
1303 // The revocation scan (a full re-hash of the staged tree) runs first;
1304 // the clock for the 500 ms bound starts when the registry drops the
1305 // handle, which is the moment revocation takes effect. A plain thread
1306 // watches for it, because this runtime is single-threaded (the policy
1307 // override is thread-local) and would only look when `sync` yields.
1308 let watcher = {
1309 let manager = Arc::clone(&manager);
1310 std::thread::spawn(move || {
1311 let started = Instant::now();
1312 while !manager.live_tool_names().is_empty() {
1313 assert!(
1314 started.elapsed() < Duration::from_secs(10),
1315 "revocation never happened"
1316 );
1317 std::thread::yield_now();
1318 }
1319 Instant::now()
1320 })
1321 };
1322 let sync_started = Instant::now();
1323 engine.set_plugins(disabled);
1324 let sync = {
1325 let manager = Arc::clone(&manager);
1326 tokio::spawn(async move { manager.reconcile().await })
1327 };
1328 let outcome = tokio::time::timeout(Duration::from_secs(2), call)
1329 .await
1330 .expect("call resolves")
1331 .unwrap();
1332 let resolved_at = Instant::now();
1333 let revoked_at = watcher.join().unwrap();
1334 let call_resolved = resolved_at.saturating_duration_since(revoked_at);
1335 assert!(
1336 matches!(outcome, Err(ToolError::Cancelled { .. })),
1337 "{outcome:?}"
1338 );
1339 eprintln!(
1340 "extension host: in-flight call resolved as cancelled {:.1} ms after revocation",
1341 call_resolved.as_secs_f64() * 1000.0
1342 );
1343 assert!(
1344 call_resolved < Duration::from_millis(500),
1345 "{call_resolved:?}"
1346 );
1347 sync.await.unwrap().unwrap();
1348 let teardown = sync_started.elapsed();
1349 assert!(
1350 teardown >= Duration::from_millis(300),
1351 "ack must wait for the 300 ms async disposer (got {teardown:?})"
1352 );
1353 let diagnostics = manager.diagnostics();
1354 assert!(
1355 !diagnostics.iter().any(|d| d.contains("teardown")),
1356 "disposed with nothing leaked: {diagnostics:?}"
1357 );
1358 manager.shutdown().await;
1359 }
1360
1361 #[tokio::test]
1362 async fn killed_host_fails_calls_once_and_replays_with_fresh_owners() {
1363 let Some(node) = node_for_tests("killed_host") else {
1364 return;
1365 };
1366 let _policy = TestPolicyGuard::extension_host(true);
1367 let fixture = FixturePlugins::new(&["slow-tool"]).await;
1368 let manager = fixture.manager(node);
1369 let engine = manager.attach(fixture.registry());
1370 engine.sync().await.unwrap();
1371 assert_eq!(manager.spawn_attempts(), 1);
1372 let pid = manager.host_pid().unwrap();
1373 let generation = manager
1374 .shared
1375 .ready_host(&HostCohort::reviewed())
1376 .unwrap()
1377 .generation;
1378 let tool = host_tool(&engine, fixture.workspace(), "slow_wait");
1379 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
1380 let call = tokio::spawn(async move { tool.execute(json!({}), &context).await });
1381 tokio::time::sleep(Duration::from_millis(150)).await;
1382 #[cfg(unix)]
1383 let status = std::process::Command::new("kill")
1384 .args(["-9", &pid.to_string()])
1385 .status()
1386 .unwrap();
1387 #[cfg(windows)]
1388 let status = std::process::Command::new("taskkill")
1389 .args(["/F", "/PID", &pid.to_string()])
1390 .status()
1391 .unwrap();
1392 assert!(status.success());
1393 let outcome = tokio::time::timeout(Duration::from_secs(2), call)
1394 .await
1395 .expect("call resolves")
1396 .unwrap();
1397 match outcome {
1398 Err(ToolError::NotAvailable { message }) => {
1399 assert!(message.contains("plugin host exited"), "{message}")
1400 }
1401 other => panic!("expected a typed not-available error, got {other:?}"),
1402 }
1403 wait_host(&manager, || {
1404 manager.spawn_attempts() == 2 && manager.live_tool_names().contains(&"slow_wait".into())
1405 })
1406 .await;
1407 assert!(matches!(manager.status(), HostStatus::Ready { .. }));
1408 assert!(
1409 manager
1410 .shared
1411 .ready_host(&HostCohort::reviewed())
1412 .unwrap()
1413 .generation
1414 > generation
1415 );
1416 assert_eq!(
1417 manager
1418 .shared
1419 .plugin
1420 .supervision
1421 .lock()
1422 .unwrap()
1423 .crashes
1424 .len(),
1425 1
1426 );
1427 manager.shutdown().await;
1428 }
1429
1430 #[tokio::test]
1431 async fn approval_providing_plugin_fails_activation_and_leaves_nothing_registered() {
1432 let Some(node) = node_for_tests("approval_providing_plugin") else {
1433 return;
1434 };
1435 let _policy = TestPolicyGuard::extension_host(true);
1436 let fixture = FixturePlugins::new(&["refuses-approval", "clash-native"]).await;
1437 let manager = fixture.manager(node);
1438 let engine = manager.attach(fixture.registry());
1439 engine.sync().await.unwrap();
1440 let registry = fixture.registry();
1441 for (name, needle) in [
1442 ("refuses-approval", "approval"),
1443 ("clash-native", "read_file"),
1444 ] {
1445 let id = registry.get(name).unwrap().id.as_str().to_string();
1446 match manager.owner_state(&id) {
1447 Some(OwnerState::Failed(reason)) => {
1448 assert!(reason.contains(needle), "{name}: {reason}")
1449 }
1450 other => panic!("{name}: expected failed activation, got {other:?}"),
1451 }
1452 }
1453 assert!(manager.live_tool_names().is_empty());
1454 // A failed activation of the same bytes is not retried every turn.
1455 let attempts = manager.spawn_attempts();
1456 engine.sync().await.unwrap();
1457 assert_eq!(manager.spawn_attempts(), attempts);
1458 manager.shutdown().await;
1459 }
1460
1461 /// Stands in for a `~/.codewhale/tools` script tool.
1462 struct FakeScriptTool;
1463
1464 #[async_trait::async_trait]
1465 impl ToolSpec for FakeScriptTool {
1466 fn name(&self) -> &str {
1467 "fixture_script_tool"
1468 }
1469 fn registration_origin(&self) -> std::borrow::Cow<'_, str> {
1470 "plugin script fixture_script_tool".into()
1471 }
1472 fn description(&self) -> &str {
1473 "script"
1474 }
1475 fn input_schema(&self) -> Value {
1476 json!({"type": "object"})
1477 }
1478 fn capabilities(&self) -> Vec<crate::tools::spec::ToolCapability> {
1479 Vec::new()
1480 }
1481 async fn execute(
1482 &self,
1483 _input: Value,
1484 _context: &ToolContext,
1485 ) -> Result<crate::tools::spec::ToolResult, ToolError> {
1486 Ok(crate::tools::spec::ToolResult::success("from the script"))
1487 }
1488 }
1489
1490 #[tokio::test]
1491 async fn an_extension_named_like_a_script_tool_is_skipped_at_turn_build() {
1492 let Some(node) = node_for_tests("script_name_clash") else {
1493 return;
1494 };
1495 let _policy = TestPolicyGuard::extension_host(true);
1496 let fixture = FixturePlugins::new(&["clash-script"]).await;
1497 let manager = fixture.manager(node);
1498 let engine = manager.attach(fixture.registry());
1499 engine.sync().await.unwrap();
1500 assert_eq!(manager.live_tool_names(), vec!["fixture_script_tool"]);
1501 let mut registry = crate::tools::registry::ToolRegistryBuilder::new()
1502 .build(ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view()));
1503 registry.register(Arc::new(FakeScriptTool));
1504 let installed = engine.install_tools(&mut registry);
1505 assert!(installed.is_empty());
1506 assert_eq!(
1507 registry
1508 .get("fixture_script_tool")
1509 .unwrap()
1510 .registration_origin(),
1511 "plugin script fixture_script_tool",
1512 "the script tool is unaffected"
1513 );
1514 assert!(
1515 manager
1516 .diagnostics()
1517 .iter()
1518 .any(|d| d.contains("fixture_script_tool") && d.contains("skipped")),
1519 "{:?}",
1520 manager.diagnostics()
1521 );
1522 manager.shutdown().await;
1523 }
1524
1525 #[tokio::test]
1526 async fn with_no_native_plugin_the_host_is_never_spawned() {
1527 let _policy = TestPolicyGuard::extension_host(true);
1528 let temp = tempfile::tempdir().unwrap();
1529 let registry = Arc::new(PluginRegistry::empty(temp.path()));
1530 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
1531 node_override: None,
1532 root: Some(temp.path().join("home")),
1533 ..Default::default()
1534 }));
1535 let engine = manager.attach(registry);
1536 engine.sync().await.unwrap();
1537 assert_eq!(manager.spawn_attempts(), 0);
1538 assert_eq!(manager.status(), HostStatus::Idle);
1539 assert!(!temp.path().join("home").exists(), "nothing materialized");
1540 }
1541
1542 async fn probe(tool: &Arc<dyn ToolSpec>, path: &Path, context: &ToolContext) -> Value {
1543 let result = tool
1544 .execute(json!({"path": path.to_string_lossy()}), context)
1545 .await
1546 .unwrap();
1547 serde_json::from_str(&result.content).unwrap()
1548 }
1549
1550 #[tokio::test]
1551 async fn sandboxed_host_cannot_read_codewhale_secrets_or_write_outside_its_data_dir() {
1552 let Some(node) = node_for_tests("sandboxed_host") else {
1553 return;
1554 };
1555 sandboxed_host_boundary(NODE, node).await;
1556 }
1557
1558 /// Same actual Rust manager, review/activation, tool and filesystem scenario,
1559 /// using the exact compiled image selected by the existing Bun resolver.
1560 #[cfg(any(target_os = "linux", target_os = "macos", windows))]
1561 #[tokio::test]
1562 async fn compiled_native_host_cannot_read_secrets_or_write_outside_its_data_dir() {
1563 let Some(binary) = compiled_image_for_tests() else {
1564 return;
1565 };
1566 sandboxed_host_boundary(
1567 codewhale_config::extension_host::ExtensionHostRuntime::Bun,
1568 binary,
1569 )
1570 .await;
1571 // Emitted only after the complete actual Rust admission/tool scenario.
1572 // CI extracts this same full-run success output; no fake-Core promotion.
1573 eprintln!(
1574 "compiled-native-containment=passed platform={} arch={}",
1575 std::env::consts::OS,
1576 std::env::consts::ARCH
1577 );
1578 }
1579
1580 /// Resolve the exact requested image through the same production runtime
1581 /// admission for every compiled Native scenario. Required inputs cannot skip.
1582 #[cfg(any(target_os = "linux", target_os = "macos", windows))]
1583 fn compiled_image_for_tests() -> Option<PathBuf> {
1584 let Some(binary) = std::env::var_os("CODEWHALE_COMPILED_HOST_TEST_BINARY") else {
1585 assert!(
1586 std::env::var_os("CODEWHALE_EXT_HOST_TESTS").is_none(),
1587 "required compiled Native image input is missing"
1588 );
1589 eprintln!("compiled Native receipt unavailable: name a matching canonical compiled image");
1590 return None;
1591 };
1592 let binary = PathBuf::from(binary);
1593 let resolution = codewhale_dependencies::resolve_extension_host_runtime(
1594 codewhale_config::extension_host::ExtensionHostRuntime::Bun,
1595 None,
1596 Some(&binary),
1597 crate::extension_host::bundle_sha256(),
1598 );
1599 let runtime = resolution
1600 .selected
1601 .as_ref()
1602 .unwrap_or_else(|| panic!("compiled Native runtime: {}", resolution.failure()));
1603 assert!(
1604 runtime.compiled,
1605 "receipt requires an actual canonical compiled image, not system Bun"
1606 );
1607 Some(binary)
1608 }
1609
1610 async fn sandboxed_host_boundary(
1611 choice: codewhale_config::extension_host::ExtensionHostRuntime,
1612 runtime_path: PathBuf,
1613 ) {
1614 let _policy = TestPolicyGuard::extension_host(true);
1615 let fixture = FixturePlugins::new(&["secret-probe"]).await;
1616 // Synthetic credential stores created before launch remain outside read grants.
1617 let secrets = fixture.root.join("secrets");
1618 std::fs::create_dir_all(&secrets).unwrap();
1619 let token = secrets.join("token");
1620 std::fs::write(&token, "s3cret-value").unwrap();
1621 // Any other entry of the Codewhale home is denied too (config backups,
1622 // OAuth tokens, state), not only the named stores.
1623 let backup = fixture.root.join("config.toml.bak-20260925");
1624 std::fs::write(&backup, "api_key = \"s3cret-backup\"").unwrap();
1625 let tokens = fixture.root.join("tokens");
1626 std::fs::create_dir_all(&tokens).unwrap();
1627 std::fs::write(tokens.join("codex.json"), "s3cret-oauth").unwrap();
1628 // Native hosts refuse ungranted workspace reads on every platform.
1629 let readable = fixture.workspace().join("readable.txt");
1630 std::fs::write(&readable, "plain").unwrap();
1631 let dotenv = fixture.workspace().join(".env");
1632 std::fs::write(&dotenv, "TOKEN=synthetic-private-value").unwrap();
1633 #[cfg(unix)]
1634 let external_metadata = {
1635 let worktree = fixture.workspace().join("external-worktree");
1636 let common = fixture.workspace().join("external-repository/.git");
1637 let metadata = common.join("worktrees/external");
1638 std::fs::create_dir_all(&worktree).unwrap();
1639 std::fs::create_dir_all(&metadata).unwrap();
1640 let pointer = worktree.join(".git");
1641 std::fs::write(&pointer, format!("gitdir: {}\n", metadata.display())).unwrap();
1642 std::fs::write(metadata.join("commondir"), "../..\n").unwrap();
1643 std::fs::write(
1644 metadata.join("gitdir"),
1645 pointer.to_string_lossy().as_bytes(),
1646 )
1647 .unwrap();
1648 let data = fixture.root.join("extension-host/data");
1649 std::fs::create_dir_all(&data).unwrap();
1650 std::os::unix::fs::symlink(&pointer, data.join(".git")).unwrap();
1651 metadata
1652 };
1653
1654 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
1655 runtime: choice,
1656 node_override: (choice == NODE).then_some(runtime_path.clone()),
1657 bun_override: (choice == codewhale_config::extension_host::ExtensionHostRuntime::Bun)
1658 .then_some(runtime_path.clone()),
1659 root: Some(fixture.root.clone()),
1660 ..Default::default()
1661 }));
1662 let engine = manager.attach(fixture.registry());
1663 engine.sync().await.unwrap();
1664 let HostStatus::Ready { sandbox, .. } = manager.status() else {
1665 panic!("host not ready: {:?}", manager.status());
1666 };
1667 let sandbox = match sandbox {
1668 super::supervisor::HostSandbox::Wrapped(name) => name,
1669 super::supervisor::HostSandbox::Unsandboxed(reason) => {
1670 panic!("Native containment requires a verified sandbox: {reason}");
1671 }
1672 };
1673 assert!(super::render_status(&manager).contains(&format!("{sandbox} sandbox")));
1674
1675 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
1676 let read = host_tool(&engine, fixture.workspace(), "probe_read");
1677 let write = host_tool(&engine, fixture.workspace(), "probe_write");
1678
1679 let plain = probe(&read, &readable, &context).await;
1680 assert_eq!(
1681 plain["ok"], false,
1682 "Native hosts refuse ungranted workspace reads"
1683 );
1684 let late_project = fixture.workspace().join("late.env");
1685 std::fs::write(&late_project, "TOKEN=synthetic-private-value").unwrap();
1686 for denied in [
1687 token,
1688 backup,
1689 tokens.join("codex.json"),
1690 dotenv.clone(),
1691 late_project,
1692 ] {
1693 let secret = probe(&read, &denied, &context).await;
1694 assert_eq!(secret["ok"], false, "{} was readable", denied.display());
1695 assert!(
1696 !secret.to_string().contains("s3cret"),
1697 "{} leaked its contents",
1698 denied.display()
1699 );
1700 }
1701 // A store created after the host started remains outside read grants.
1702 let state = fixture.root.join("state");
1703 std::fs::create_dir_all(&state).unwrap();
1704 std::fs::write(state.join("late.json"), "s3cret-late").unwrap();
1705 let late = probe(&read, &state.join("late.json"), &context).await;
1706 assert_eq!(
1707 late["ok"], false,
1708 "a store created after start was readable"
1709 );
1710 // Migrated history can first appear after launch and remains unreadable.
1711 let history = fixture.root.join("composer_history.jsonl");
1712 std::fs::write(&history, "\"private synthetic prompt\"\n").unwrap();
1713 let late_history = probe(&read, &history, &context).await;
1714 assert_eq!(late_history["ok"], false, "new history was readable");
1715 // The Codex credential file Codewhale itself reads, when this machine has
1716 // one. Only `ok` is reported, never the content.
1717 let codex_auth = codewhale_runtime::oauth::auth_file_path();
1718 if codex_auth.is_file() {
1719 let codex = probe(&read, &codex_auth, &context).await;
1720 assert_eq!(codex["ok"], false, "code: {}", codex["code"]);
1721 }
1722
1723 let data = fixture.root.join("extension-host/data/probe.txt");
1724 assert_eq!(probe(&write, &data, &context).await["ok"], true);
1725 assert_eq!(
1726 probe(&read, &data, &context).await,
1727 json!({"ok": true, "text": "probe"})
1728 );
1729 let scratch = fixture.root.join("extension-host/data/tmp/probe.txt");
1730 assert_eq!(probe(&write, &scratch, &context).await["ok"], true);
1731 assert_eq!(probe(&read, &scratch, &context).await["ok"], true);
1732 #[cfg(unix)]
1733 {
1734 assert_eq!(
1735 probe(&read, &external_metadata.join("commondir"), &context).await["ok"],
1736 false
1737 );
1738 let escaped = external_metadata.join("native-write-escape");
1739 assert_eq!(probe(&write, &escaped, &context).await["ok"], false);
1740 assert!(!escaped.exists());
1741 let linked = fixture.root.join("extension-host/data/project-secret");
1742 std::os::unix::fs::symlink(&dotenv, &linked).unwrap();
1743 assert_eq!(probe(&read, &linked, &context).await["ok"], false);
1744 if choice == NODE {
1745 for (path, expected) in [(&data, true), (&dotenv, false), (&linked, false)] {
1746 let result = read
1747 .execute(
1748 json!({"path": path.to_string_lossy(), "child": true}),
1749 &context,
1750 )
1751 .await
1752 .unwrap();
1753 let result: Value = serde_json::from_str(&result.content).unwrap();
1754 assert_eq!(
1755 result["ok"],
1756 expected,
1757 "Native child read {}: {result}",
1758 path.display()
1759 );
1760 }
1761 }
1762 }
1763 let outside = fixture.workspace().join("native-write-escape");
1764 assert_eq!(probe(&write, &outside, &context).await["ok"], false);
1765 assert!(!outside.exists());
1766 // Outside the data directory: the crate's source directory, unless the
1767 // checkout itself sits in a temp directory.
1768 let crate_dir = std::fs::canonicalize(env!("CARGO_MANIFEST_DIR")).unwrap();
1769 let in_temp = [std::env::temp_dir(), PathBuf::from("/tmp")]
1770 .iter()
1771 .filter_map(|dir| std::fs::canonicalize(dir).ok())
1772 .any(|dir| crate_dir.starts_with(dir));
1773 if !in_temp {
1774 let escape = crate_dir.join(format!(".ext-host-probe-{}", uuid::Uuid::new_v4().simple()));
1775 let escaped = probe(&write, &escape, &context).await;
1776 let leaked = escape.exists();
1777 let _ = std::fs::remove_file(&escape);
1778 assert_eq!(escaped["ok"], false, "{escaped}");
1779 assert!(!leaked);
1780 }
1781 // Bun's TCP error adapter collapses Darwin's EPERM into ECONNREFUSED.
1782 // Its UDP adapter retains the OS errno, so use a real bound datagram
1783 // receiver there; every other runtime/platform keeps the TCP control.
1784 let (denied, accepted_count, protocol) = if cfg!(target_os = "macos")
1785 && choice == codewhale_config::extension_host::ExtensionHostRuntime::Bun
1786 {
1787 let listener = tokio::net::UdpSocket::bind(("127.0.0.1", 0)).await.unwrap();
1788 let address = listener.local_addr().unwrap();
1789 let positive = tokio::net::UdpSocket::bind(("127.0.0.1", 0)).await.unwrap();
1790 let marker = b"controller-network-probe";
1791 assert_eq!(
1792 positive.send_to(marker, address).await.unwrap(),
1793 marker.len()
1794 );
1795 let mut packet = [0_u8; 64];
1796 let (bytes, sender) =
1797 tokio::time::timeout(Duration::from_secs(2), listener.recv_from(&mut packet))
1798 .await
1799 .unwrap()
1800 .unwrap();
1801 assert_eq!(&packet[..bytes], marker);
1802 assert_eq!(sender, positive.local_addr().unwrap());
1803 let mut accepted_count = 1;
1804 let send = host_tool(&engine, fixture.workspace(), "probe_send");
1805 let result = tokio::time::timeout(
1806 Duration::from_secs(5),
1807 send.execute(json!({"port": address.port()}), &context),
1808 )
1809 .await
1810 .unwrap()
1811 .unwrap();
1812 let denied: Value = serde_json::from_str(&result.content).unwrap();
1813 if tokio::time::timeout(Duration::from_millis(100), listener.recv_from(&mut packet))
1814 .await
1815 .is_ok()
1816 {
1817 accepted_count += 1;
1818 }
1819 (denied, accepted_count, "udp")
1820 } else {
1821 // The unsandboxed controller reaches this actual listener. The Native
1822 // host must fail the same connection at its own OS sandbox boundary.
1823 let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
1824 .await
1825 .unwrap();
1826 let address = listener.local_addr().unwrap();
1827 let positive = tokio::net::TcpStream::connect(address).await.unwrap();
1828 let (accepted, _) = tokio::time::timeout(Duration::from_secs(2), listener.accept())
1829 .await
1830 .unwrap()
1831 .unwrap();
1832 let mut accepted_count = 1;
1833 drop(positive);
1834 drop(accepted);
1835 let connect = host_tool(&engine, fixture.workspace(), "probe_connect");
1836 let result = tokio::time::timeout(
1837 Duration::from_secs(5),
1838 connect.execute(json!({"port": address.port()}), &context),
1839 )
1840 .await
1841 .unwrap()
1842 .unwrap();
1843 let denied: Value = serde_json::from_str(&result.content).unwrap();
1844 if tokio::time::timeout(Duration::from_millis(100), listener.accept())
1845 .await
1846 .is_ok()
1847 {
1848 accepted_count += 1;
1849 }
1850 (denied, accepted_count, "tcp")
1851 };
1852 assert_eq!(
1853 denied["ok"], false,
1854 "Native host reached {protocol} controller: {denied}"
1855 );
1856 #[cfg(target_os = "linux")]
1857 {
1858 let controller = std::fs::read_link("/proc/self/ns/net").unwrap();
1859 let controller = controller.to_str().unwrap();
1860 let host = denied["network_namespace"].as_str().unwrap();
1861 let namespace_id = |name: &str| {
1862 name.strip_prefix("net:[")
1863 .and_then(|name| name.strip_suffix(']'))
1864 .and_then(|id| id.parse::<u64>().ok())
1865 .filter(|id| *id != 0)
1866 .expect("an actual bounded Linux kernel network namespace")
1867 };
1868 assert_ne!(
1869 namespace_id(host),
1870 namespace_id(controller),
1871 "Native host must remain in its isolated kernel network namespace"
1872 );
1873 assert_eq!(
1874 denied["code"], "ECONNREFUSED",
1875 "the isolated loopback cannot reach the controller: {denied}"
1876 );
1877 }
1878 #[cfg(not(target_os = "linux"))]
1879 assert!(
1880 matches!(denied["code"].as_str(), Some("EPERM" | "EACCES")),
1881 "connection must be refused by the OS sandbox: {denied}"
1882 );
1883 assert_eq!(
1884 accepted_count, 1,
1885 "only the controller reached the listener"
1886 );
1887 if choice == codewhale_config::extension_host::ExtensionHostRuntime::Bun {
1888 eprintln!(
1889 "compiled-native-network=passed controller_accepts=1 host_errno={} platform={} arch={} protocol={protocol}",
1890 denied["code"].as_str().unwrap(),
1891 std::env::consts::OS,
1892 std::env::consts::ARCH,
1893 );
1894 }
1895 manager.shutdown().await;
1896 }
1897
1898 // ---------------------------------------------------------------------------
1899 // Receipt-bound approval keys (design §4.3)
1900 // ---------------------------------------------------------------------------
1901
1902 fn keys_for(
1903 manager: &ExtensionHostManager,
1904 registration: super::registry::ToolRegistration,
1905 input: &Value,
1906 ) -> (String, String) {
1907 let name = registration.name.clone();
1908 let mut registry = crate::tools::ToolRegistry::new(ToolContext::new(Path::new("/w")));
1909 registry.register(Arc::new(super::tool::HostToolSpec::new(
1910 registration,
1911 Arc::clone(&manager.shared),
1912 )));
1913 let (exact, grouping) =
1914 crate::tools::approval_cache::approval_keys_for_call(Some(&registry), &name, input);
1915 (exact.0, grouping.0)
1916 }
1917
1918 /// A session grant for an extension tool covers one reviewed plugin build:
1919 /// an update of the plugin, or another plugin that later registers the same
1920 /// tool name, gets a different key and is asked again.
1921 #[test]
1922 fn extension_approval_keys_are_bound_to_the_plugin_receipt() {
1923 let manager = ExtensionHostManager::new(ExtensionHostOptions::default());
1924 let input = json!({"path": "x"});
1925 let mut owners = OwnerRegistry::new();
1926 let live = |owners: &mut OwnerRegistry, owner: &OwnerRef| {
1927 register(owners, owner, "shared_tool").unwrap();
1928 owners.mark_active(owner);
1929 owners.live_tools().pop().unwrap()
1930 };
1931
1932 let first = owners
1933 .begin_owner(
1934 HostCohort::reviewed(),
1935 "a",
1936 "a",
1937 Some(fake_authority("a")),
1938 "hash-a1",
1939 )
1940 .unwrap();
1941 let first = keys_for(&manager, live(&mut owners, &first), &input);
1942 assert!(
1943 first.0.starts_with("ext:a@hash-a1:") && first.0.contains(":shared_tool:"),
1944 "{first:?}"
1945 );
1946 assert_eq!(first.0, first.1, "a grant covers the exact call only");
1947 let generic = crate::tools::approval_cache::build_approval_grouping_key("shared_tool", &input);
1948 assert_ne!(first.1, generic.0, "never the name-derived family key");
1949
1950 // Same plugin, same input, updated bytes: a different grant.
1951 let updated = owners
1952 .begin_owner(
1953 HostCohort::reviewed(),
1954 "a",
1955 "a",
1956 Some(fake_authority("a")),
1957 "hash-a2",
1958 )
1959 .unwrap();
1960 let updated = keys_for(&manager, live(&mut owners, &updated), &input);
1961 assert_ne!(first.1, updated.1);
1962
1963 // Another plugin takes the name once the first is gone.
1964 owners.revoke_owner("a");
1965 let other = owners
1966 .begin_owner(
1967 HostCohort::reviewed(),
1968 "b",
1969 "b",
1970 Some(fake_authority("b")),
1971 "hash-a1",
1972 )
1973 .unwrap();
1974 let other = keys_for(&manager, live(&mut owners, &other), &input);
1975 assert_ne!(first.1, other.1);
1976 assert_ne!(updated.1, other.1);
1977
1978 // Tools without a scope keep their existing keys.
1979 let shell = json!({"command": "cargo build --release"});
1980 let (exact, grouping) =
1981 crate::tools::approval_cache::approval_keys_for_call(None, "exec_shell", &shell);
1982 assert_eq!(
1983 exact,
1984 crate::tools::approval_cache::build_approval_key("exec_shell", &shell)
1985 );
1986 assert_eq!(
1987 grouping,
1988 crate::tools::approval_cache::build_approval_grouping_key("exec_shell", &shell)
1989 );
1990 }
1991
1992 // ---------------------------------------------------------------------------
1993 // The native-entry rule at validate / review time
1994 // ---------------------------------------------------------------------------
1995
1996 fn native_bundle(user: &Path, name: &str, native_path: &str, files: &[&str]) {
1997 let root = user.join(name);
1998 for file in files {
1999 let path = root.join(file);
2000 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
2001 std::fs::write(
2002 &path,
2003 "export const name = 'x'\nexport function apply() {}\n",
2004 )
2005 .unwrap();
2006 }
2007 std::fs::write(
2008 root.join("plugin.json"),
2009 serde_json::to_vec_pretty(&json!({
2010 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2011 "name": name,
2012 "version": "0.1.0",
2013 "description": "native entry rule fixture",
2014 "license": "MIT",
2015 "extensions": {"net.codewhale": {"native": {"path": native_path}}}
2016 }))
2017 .unwrap(),
2018 )
2019 .unwrap();
2020 }
2021
2022 /// `/plugin validate` and the review screen read plugin diagnostics, so an
2023 /// entry that activation would refuse must fail there too, with the flag on;
2024 /// with it off `native` is inventory-only and any path stays valid.
2025 #[test]
2026 fn native_entry_rule_fails_validation_when_the_host_is_enabled() {
2027 let temp = tempfile::tempdir().unwrap();
2028 let user = temp.path().join("user");
2029 native_bundle(&user, "dir-entry", "lib", &["lib/index.mjs"]);
2030 native_bundle(&user, "ts-entry", "index.ts", &["index.ts"]);
2031 native_bundle(&user, "good-entry", "index.mjs", &["index.mjs"]);
2032 native_bundle(&user, "typed-entry", "index.mts", &["index.mts"]);
2033 let config = DiscoveryConfig {
2034 workspace: temp.path().join("project"),
2035 user_plugins_dir: user,
2036 workspace_plugins_dir: temp.path().join("project/.codewhale/plugins"),
2037 builtin_plugin_dirs: Vec::new(),
2038 state_path: temp.path().join("state/plugin-state.json"),
2039 };
2040 let native_errors = |registry: &PluginRegistry, name: &str| -> Vec<String> {
2041 registry
2042 .get(name)
2043 .unwrap_or_else(|| panic!("{name} not discovered: {:?}", registry.diagnostics()))
2044 .diagnostics
2045 .iter()
2046 .filter(|diagnostic| diagnostic.code == "native-entry-invalid")
2047 .map(|diagnostic| {
2048 assert_eq!(
2049 diagnostic.level,
2050 codewhale_plugins::types::PluginDiagnosticLevel::Error
2051 );
2052 diagnostic.message.clone()
2053 })
2054 .collect()
2055 };
2056
2057 {
2058 let _policy = TestPolicyGuard::extension_host(true);
2059 let registry = discover_with_config(&config);
2060 for name in ["dir-entry", "ts-entry"] {
2061 let errors = native_errors(&registry, name);
2062 assert_eq!(errors.len(), 1, "{name}: {errors:?}");
2063 assert!(
2064 errors[0].contains(".mjs, .js, .cjs, .mts or .cts"),
2065 "{name}: {errors:?}"
2066 );
2067 }
2068 assert!(native_errors(&registry, "good-entry").is_empty());
2069 assert!(native_errors(&registry, "typed-entry").is_empty());
2070 assert!(!registry.validation_is_clean());
2071 }
2072 let _policy = TestPolicyGuard::extension_host(false);
2073 let registry = discover_with_config(&config);
2074 for name in ["dir-entry", "ts-entry", "good-entry", "typed-entry"] {
2075 assert!(native_errors(&registry, name).is_empty(), "{name}");
2076 }
2077 }
2078
2079 #[test]
2080 fn owner_reports_keep_bounded_attributed_logs_and_ignore_stale_hosts() {
2081 use super::supervisor::HostEvents;
2082
2083 let manager = ExtensionHostManager::new(ExtensionHostOptions::default());
2084 manager
2085 .shared
2086 .plugin
2087 .host_generation
2088 .store(2, std::sync::atomic::Ordering::SeqCst);
2089 {
2090 let mut registry = manager.shared.registry.lock().unwrap();
2091 for id in ["alpha", "beta"] {
2092 let owner = registry
2093 .begin_owner(
2094 HostCohort::reviewed(),
2095 id,
2096 id,
2097 Some(fake_authority(id)),
2098 "hash",
2099 )
2100 .unwrap();
2101 registry.mark_active(&owner);
2102 register(&mut registry, &owner, &format!("{id}_probe")).unwrap();
2103 }
2104 }
2105 let current = super::Events {
2106 shared: Arc::downgrade(&manager.shared),
2107 cohort: HostCohort::reviewed(),
2108 generation: 2,
2109 };
2110 let stale = super::Events {
2111 shared: Arc::downgrade(&manager.shared),
2112 cohort: HostCohort::reviewed(),
2113 generation: 1,
2114 };
2115 for index in 0..25 {
2116 current.log(&protocol::LogParams {
2117 level: "warn".into(),
2118 msg: format!("alpha message {index}"),
2119 plugin_id: Some("alpha".into()),
2120 });
2121 }
2122 let mut log = protocol::LogParams {
2123 level: "error".into(),
2124 msg: "beta only".into(),
2125 plugin_id: Some("beta".into()),
2126 };
2127 current.log(&log);
2128 log.msg = "stale message".into();
2129 stale.log(&log);
2130 log.plugin_id = Some("unknown".into());
2131 current.log(&log);
2132 log.plugin_id = Some("alpha".into());
2133 log.level = "debug".into();
2134 current.log(&log);
2135 let alpha = manager.owner_report("alpha").unwrap();
2136 assert!(matches!(alpha.state, Some(OwnerState::Active)));
2137 assert_eq!(alpha.tools, ["alpha_probe"]);
2138 assert_eq!(alpha.diagnostics.len(), 20);
2139 assert_eq!(alpha.diagnostics[0], "warn: alpha message 5");
2140 assert_eq!(
2141 manager.owner_report("beta").unwrap().diagnostics,
2142 ["error: beta only"]
2143 );
2144 assert!(manager.owner_report("unknown").is_none());
2145 manager
2146 .shared
2147 .plugin_diagnostic(&"x".repeat(10_000), "oversized id".into());
2148 assert!(
2149 manager
2150 .shared
2151 .diagnostics
2152 .lock()
2153 .unwrap()
2154 .back()
2155 .unwrap()
2156 .plugin_id
2157 .is_none()
2158 );
2159 for _ in 0..80 {
2160 manager.shared.plugin_diagnostic("alpha", "🦀".repeat(3000));
2161 }
2162 assert_eq!(manager.diagnostics().len(), 64);
2163 assert!(
2164 manager
2165 .diagnostics()
2166 .iter()
2167 .all(|line| line.len() <= super::MAX_DIAGNOSTIC_BYTES + '…'.len_utf8())
2168 );
2169 assert!(
2170 manager
2171 .owner_report("alpha")
2172 .unwrap()
2173 .diagnostics
2174 .iter()
2175 .all(|line| line.ends_with('…'))
2176 );
2177 }
2178
2179 #[tokio::test]
2180 async fn typed_author_example_is_reviewed_before_its_tool_can_execute() {
2181 use codewhale_plugins::install::{DEFAULT_MAX_SIZE_BYTES, PluginInstallSource, install};
2182
2183 let Some(node) = node_for_tests("typed author example") else {
2184 return;
2185 };
2186 let _policy = TestPolicyGuard::extension_host(true);
2187 let fixture = FixturePlugins::new(&[]).await;
2188 let example =
2189 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/examples/plugins/hello-extension");
2190 install(
2191 PluginInstallSource::LocalPath(example),
2192 &fixture.config.user_plugins_dir,
2193 DEFAULT_MAX_SIZE_BYTES,
2194 &codewhale_net::network_policy::NetworkPolicy::default(),
2195 false,
2196 &|_| None,
2197 )
2198 .await
2199 .unwrap();
2200 let mut plugins = discover_with_config(&fixture.config);
2201 assert!(!plugins.is_active("hello-extension"));
2202 plugins.trust("hello-extension").unwrap();
2203 assert!(
2204 !plugins.is_active("hello-extension"),
2205 "trust alone does not enable code"
2206 );
2207 plugins.enable("hello-extension").unwrap();
2208 // This tests plugin review and typed loading, not hang detection. The
2209 // 600 ms watchdog used by supervision fault tests can kill a healthy
2210 // typed-plugin load on a busy runner before registration completes.
2211 let manager = fixture.manager(node);
2212 let engine = manager.attach(Arc::new(plugins));
2213 engine.sync().await.unwrap();
2214 let tool = host_tool(&engine, fixture.workspace(), "hello_greet");
2215 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Required);
2216 let result = tool
2217 .execute(
2218 json!({"name": "Codewhale"}),
2219 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view()),
2220 )
2221 .await
2222 .unwrap();
2223 let payload: Value = serde_json::from_str(&result.content).unwrap();
2224 assert_eq!(payload["greeting"], "Hello, Codewhale!");
2225 assert!(payload["callId"].as_str().is_some_and(|id| !id.is_empty()));
2226
2227 // The example registers a plain object whose schema says
2228 // `additionalProperties: false` and `name: string`. The core enforces it;
2229 // the example's own `execute` would have accepted either input. Neither
2230 // call reaches the host.
2231 let sent = manager.host_requests_started();
2232 for input in [
2233 json!({"name": "Codewhale", "surprise": true}),
2234 json!({"name": 7}),
2235 ] {
2236 let error = tool
2237 .execute(
2238 input.clone(),
2239 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view()),
2240 )
2241 .await
2242 .unwrap_err();
2243 assert!(
2244 matches!(error, ToolError::InvalidInput { ref message } if message.contains("hello_greet")),
2245 "{input}: {error:?}"
2246 );
2247 }
2248 assert_eq!(
2249 manager.host_requests_started(),
2250 sent,
2251 "a call the schema refuses sends the host nothing"
2252 );
2253 manager.shutdown().await;
2254 }
2255
2256 // ---------------------------------------------------------------------------
2257 // Engines sharing one process-wide host
2258 // ---------------------------------------------------------------------------
2259
2260 #[test]
2261 fn attachment_changes_discard_the_complete_scan_before_owner_side_effects() {
2262 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions::default()));
2263 let old = Arc::new(PluginRegistry::empty(Path::new("/old")));
2264 let current = Arc::new(PluginRegistry::empty(Path::new("/current")));
2265 let attachment = manager.attach(Arc::clone(&old));
2266 let scan = |plugins: &Arc<PluginRegistry>| super::DesiredScan {
2267 attachments: vec![(
2268 attachment.id,
2269 Arc::clone(plugins),
2270 [("plugin".into(), "hash-plugin".into())].into(),
2271 )],
2272 owners: [(
2273 "plugin".into(),
2274 super::DesiredOwner {
2275 cohort: HostCohort::reviewed(),
2276 plugin_name: "plugin".into(),
2277 authority: fake_authority("plugin"),
2278 entries: Vec::new(),
2279 host_services: Vec::new(),
2280 },
2281 )]
2282 .into(),
2283 errors: Vec::new(),
2284 };
2285
2286 // An old scan finishes after the engine has already changed workspace.
2287 attachment.set_plugins(Arc::clone(&current));
2288 let current_view = attachment.plugin_view();
2289 let mut attachments = manager.shared.attachments.lock().unwrap();
2290 assert!(scan(&old).publish(&mut attachments).is_none());
2291 assert!(attachments[&attachment.id].desired.is_empty());
2292 // A current scan publishes both the engine view and owner union.
2293 let (owners, _) = scan(&current_view).publish(&mut attachments).unwrap();
2294 assert!(owners.contains_key("plugin"));
2295 assert_eq!(attachments[&attachment.id].desired["plugin"], "hash-plugin");
2296 drop(attachments);
2297
2298 // A newly attached engine also invalidates the complete scan, even when
2299 // it uses the same snapshot: otherwise its owners could be revoked.
2300 let other = manager.attach(Arc::clone(&current));
2301 assert!(
2302 scan(&current_view)
2303 .publish(&mut manager.shared.attachments.lock().unwrap())
2304 .is_none()
2305 );
2306 drop(other);
2307 let stale = scan(&current_view);
2308 drop(attachment);
2309 assert!(
2310 stale
2311 .publish(&mut manager.shared.attachments.lock().unwrap())
2312 .is_none()
2313 );
2314 }
2315
2316 /// Two engines for different workspaces in one process: syncing either
2317 /// keeps the other's plugin active and its in-flight call running, neither
2318 /// receives the other's tools, and detaching one revokes only its plugin.
2319 #[tokio::test]
2320 async fn engines_in_one_process_never_revoke_each_others_plugins() {
2321 let Some(node) = node_for_tests("engines_in_one_process") else {
2322 return;
2323 };
2324 let _policy = TestPolicyGuard::extension_host(true);
2325 let slow = FixturePlugins::new(&["slow-tool"]).await;
2326 let deps = FixturePlugins::new(&["dsh-workspace-deps"]).await;
2327 let (slow_id, deps_id) = (
2328 plugin_id(&slow, "slow-tool"),
2329 plugin_id(&deps, "dsh-workspace-deps"),
2330 );
2331 let manager = slow.manager(node);
2332 let first = manager.attach(slow.registry());
2333 let second = manager.attach(deps.registry());
2334 first.sync().await.unwrap();
2335 let tool = host_tool(&first, slow.workspace(), "slow_wait");
2336 let context = ToolContext::new(slow.workspace()).with_plugin_registry(first.plugin_view());
2337 let call = tokio::spawn(async move { tool.execute(json!({"ms": 600}), &context).await });
2338 tokio::time::sleep(Duration::from_millis(100)).await;
2339
2340 // Both snapshot stores are granted at launch; the second engine syncs mid-call.
2341 second.sync().await.unwrap();
2342 assert_eq!(manager.owner_state(&slow_id), Some(OwnerState::Active));
2343 assert_eq!(manager.owner_state(&deps_id), Some(OwnerState::Active));
2344 let result = tokio::time::timeout(Duration::from_secs(5), call)
2345 .await
2346 .expect("call resolves")
2347 .unwrap()
2348 .expect("the first engine's in-flight call completes");
2349 assert!(result.success, "{}", result.content);
2350 assert!(result.content.contains("600"), "{}", result.content);
2351
2352 assert_eq!(installed(&first, slow.workspace()), vec!["slow_wait"]);
2353 assert_eq!(
2354 installed(&second, deps.workspace()),
2355 vec!["load_workspace_dependencies"]
2356 );
2357 first.sync().await.unwrap();
2358 assert_eq!(manager.owner_state(&deps_id), Some(OwnerState::Active));
2359 assert!(
2360 !manager.diagnostics().iter().any(|d| d.contains("revoked")),
2361 "{:?}",
2362 manager.diagnostics()
2363 );
2364
2365 #[cfg(not(windows))]
2366 {
2367 let late = FixturePlugins::new(&["clash-script"]).await;
2368 let late_id = plugin_id(&late, "clash-script");
2369 let late_engine = manager.attach(late.registry());
2370 late_engine.sync().await.unwrap();
2371 assert!(
2372 matches!(manager.owner_state(&late_id), Some(OwnerState::Failed(ref reason))
2373 if reason.contains("Native snapshot store was not granted to this host")
2374 && reason.contains("restart Codewhale")),
2375 "{:?}",
2376 manager.owner_state(&late_id)
2377 );
2378 assert_eq!(manager.owner_state(&slow_id), Some(OwnerState::Active));
2379 assert_eq!(manager.owner_state(&deps_id), Some(OwnerState::Active));
2380 assert_eq!(manager.spawn_attempts(), 1);
2381 }
2382
2383 // Detaching does not revoke by itself; the next reconcile revokes only
2384 // what no remaining engine desires.
2385 drop(second);
2386 assert_eq!(manager.owner_state(&deps_id), Some(OwnerState::Active));
2387 first.sync().await.unwrap();
2388 assert_eq!(manager.owner_state(&deps_id), None);
2389 assert_eq!(manager.owner_state(&slow_id), Some(OwnerState::Active));
2390 assert_eq!(manager.spawn_attempts(), 1);
2391 manager.shutdown().await;
2392 }
2393
2394 /// Each snapshot is re-verified against persisted plugin state, so a disable
2395 /// made through one engine's registry revokes the plugin for an engine still
2396 /// holding the older snapshot.
2397 #[tokio::test]
2398 async fn a_disable_through_either_registry_revokes_for_every_engine() {
2399 let Some(node) = node_for_tests("a_disable_through_either_registry") else {
2400 return;
2401 };
2402 let _policy = TestPolicyGuard::extension_host(true);
2403 let fixture = FixturePlugins::new(&["slow-tool"]).await;
2404 let id = plugin_id(&fixture, "slow-tool");
2405 let manager = fixture.manager(node);
2406 let first = manager.attach(fixture.registry());
2407 let second = manager.attach(fixture.registry());
2408 first.sync().await.unwrap();
2409 assert_eq!(installed(&first, fixture.workspace()), vec!["slow_wait"]);
2410 assert_eq!(installed(&second, fixture.workspace()), vec!["slow_wait"]);
2411
2412 second.set_plugins(fixture.disable("slow-tool"));
2413 second.sync().await.unwrap();
2414 assert_eq!(manager.owner_state(&id), None, "revoked and forgotten");
2415 assert!(installed(&first, fixture.workspace()).is_empty());
2416 assert!(installed(&second, fixture.workspace()).is_empty());
2417 manager.shutdown().await;
2418 }
2419
2420 fn fast_supervision() -> super::SupervisionOptions {
2421 super::SupervisionOptions {
2422 heartbeat_interval: Duration::from_millis(50),
2423 ping_timeout: Duration::from_millis(150),
2424 hang_timeout: Duration::from_millis(600),
2425 restart_backoff: Duration::from_millis(25),
2426 ..Default::default()
2427 }
2428 }
2429
2430 fn supervised_manager(fixture: &FixturePlugins, node: PathBuf) -> Arc<ExtensionHostManager> {
2431 Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
2432 runtime: NODE,
2433 node_override: Some(node),
2434 bun_override: None,
2435 root: Some(fixture.root.clone()),
2436 supervision: fast_supervision(),
2437 }))
2438 }
2439
2440 async fn wait_host(manager: &ExtensionHostManager, predicate: impl Fn() -> bool) {
2441 tokio::time::timeout(Duration::from_secs(60), async {
2442 while !predicate() {
2443 tokio::time::sleep(Duration::from_millis(10)).await;
2444 }
2445 })
2446 .await
2447 .unwrap_or_else(|_| {
2448 panic!(
2449 "host wait timed out: {:?}; {:?}",
2450 manager.status(),
2451 manager.diagnostics()
2452 )
2453 });
2454 }
2455
2456 #[test]
2457 fn crash_budget_is_bounded_and_expires_only_with_the_window() {
2458 let options = super::SupervisionOptions::default();
2459 let mut state = super::SupervisionState::default();
2460 let now = Instant::now();
2461 assert!(state.record_crash(now, &options));
2462 assert!(state.record_crash(now + Duration::from_secs(1), &options));
2463 assert!(!state.record_crash(now + Duration::from_secs(2), &options));
2464 assert_eq!(state.crashes.len(), 3);
2465 assert!(state.record_crash(
2466 now + options.crash_window + Duration::from_secs(3),
2467 &options
2468 ));
2469 assert_eq!(state.crashes.len(), 1);
2470 }
2471
2472 #[test]
2473 fn dirty_teardown_window_is_bounded_and_a_requested_restart_waits_for_idle() {
2474 let options = super::SupervisionOptions::default();
2475 let mut state = super::SupervisionState::default();
2476 let now = Instant::now();
2477 state.record_dirty_teardown(now, &options);
2478 assert!(!state.dirty_restart_pending);
2479 state.record_dirty_teardown(now + options.dirty_window, &options);
2480 assert!(!state.dirty_restart_pending, "the first event expired");
2481 state.record_dirty_teardown(
2482 now + options.dirty_window + Duration::from_secs(1),
2483 &options,
2484 );
2485 assert!(state.dirty_restart_pending);
2486 for second in 2..100 {
2487 state.record_dirty_teardown(
2488 now + options.dirty_window + Duration::from_secs(second),
2489 &options,
2490 );
2491 }
2492 assert_eq!(state.dirty_teardowns.len(), 2);
2493 state.record_dirty_teardown(now + options.dirty_window * 3, &options);
2494 assert!(
2495 state.dirty_restart_pending,
2496 "an idle request does not expire"
2497 );
2498 assert!(state.crashes.is_empty());
2499 }
2500
2501 #[tokio::test]
2502 async fn a_call_past_its_method_deadline_is_cancelled_and_the_host_stays_usable() {
2503 let Some(node) = node_for_tests("method deadline") else {
2504 return;
2505 };
2506 let _policy = TestPolicyGuard::extension_host(true);
2507 let fixture = FixturePlugins::new(&["slow-tool", "clash-script"]).await;
2508 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
2509 runtime: NODE,
2510 node_override: Some(node),
2511 bun_override: None,
2512 root: Some(fixture.root.clone()),
2513 supervision: super::SupervisionOptions {
2514 tool_call_deadline: Duration::from_millis(300),
2515 ..Default::default()
2516 },
2517 }));
2518 let engine = manager.attach(fixture.registry());
2519 engine.sync().await.unwrap();
2520 let pid = manager.host_pid();
2521 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
2522 // `slow_wait` answers after 30 s unless it is cancelled.
2523 let slow = host_tool(&engine, fixture.workspace(), "slow_wait");
2524 let started = Instant::now();
2525 let outcome = tokio::time::timeout(Duration::from_secs(5), slow.execute(json!({}), &context))
2526 .await
2527 .expect("the method deadline bounds the call");
2528 let elapsed = started.elapsed();
2529 assert!(
2530 matches!(outcome, Err(ToolError::Timeout { .. })),
2531 "{outcome:?}"
2532 );
2533 assert!(elapsed < Duration::from_secs(2), "{elapsed:?}");
2534 // The same host takes the next call.
2535 let quick = host_tool(&engine, fixture.workspace(), "fixture_script_tool");
2536 let result = quick.execute(json!({}), &context).await.unwrap();
2537 assert!(result.success, "{}", result.content);
2538 assert_eq!(manager.host_pid(), pid);
2539 assert_eq!(manager.spawn_attempts(), 1);
2540 // `slow-tool`'s disposer awaits its in-flight call, so a clean teardown
2541 // proves the host received `$/cancel` and aborted the timed-out call
2542 // (uncancelled, it outlives the host's 2 s dispose deadline).
2543 engine.set_plugins(fixture.disable("slow-tool"));
2544 engine.sync().await.unwrap();
2545 let diagnostics = manager.diagnostics();
2546 assert!(
2547 !diagnostics.iter().any(|line| line.contains("teardown")),
2548 "{diagnostics:?}"
2549 );
2550 manager.shutdown().await;
2551 }
2552
2553 #[tokio::test]
2554 async fn ordinary_exit_rejects_requests_from_a_drained_calls_waker() {
2555 use std::future::Future;
2556 use std::pin::Pin;
2557 use std::sync::Mutex;
2558 use std::task::{Context, Wake, Waker};
2559
2560 use super::supervisor::{HostCallError, HostProcess};
2561
2562 struct AdmissionProbe {
2563 host: Arc<HostProcess>,
2564 result: Mutex<Option<Result<(), HostCallError>>>,
2565 woke: tokio::sync::Notify,
2566 }
2567
2568 impl Wake for AdmissionProbe {
2569 fn wake(self: Arc<Self>) {
2570 self.wake_by_ref();
2571 }
2572
2573 fn wake_by_ref(self: &Arc<Self>) {
2574 let mut result = self.result.lock().unwrap();
2575 if result.is_none() {
2576 // oneshot send wakes synchronously: probe the exact gap after
2577 // the exit watcher drains pending and starts failing its calls.
2578 *result = Some(
2579 self.host
2580 .start_request(protocol::CoreRequest::Ping, None)
2581 .map(|(id, _)| self.host.forget(id)),
2582 );
2583 self.woke.notify_one();
2584 }
2585 }
2586 }
2587
2588 let Some(node) = node_for_tests("ordinary exit admission") else {
2589 return;
2590 };
2591 let _policy = TestPolicyGuard::extension_host(true);
2592 let fixture = FixturePlugins::new(&["slow-tool"]).await;
2593 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
2594 runtime: NODE,
2595 node_override: Some(node),
2596 bun_override: None,
2597 root: Some(fixture.root.clone()),
2598 supervision: super::SupervisionOptions {
2599 heartbeat_interval: Duration::from_secs(60),
2600 ..Default::default()
2601 },
2602 }));
2603 let engine = manager.attach(fixture.registry());
2604 engine.sync().await.unwrap();
2605 let host = manager.shared.ready_host(&HostCohort::reviewed()).unwrap();
2606 let registration = manager.shared.registry.lock().unwrap().live_tools()[0].clone();
2607 let (_, mut call) = host
2608 .start_request(
2609 protocol::CoreRequest::ToolCall(protocol::ToolCallParams {
2610 handle: registration.handle,
2611 call_id: "exit-admission".into(),
2612 input: json!({"ms": 30_000}),
2613 deadline_ms: 60_000,
2614 workspace: None,
2615 ticket: None,
2616 checkpoint_ticket: None,
2617 question_ticket: None,
2618 subagent_ticket: None,
2619 broker_tickets: None,
2620 caller_tools: None,
2621 session_id: None,
2622 agent_id: None,
2623 origin_turn_id: None,
2624 }),
2625 Some(registration.owner.plugin_id),
2626 )
2627 .unwrap();
2628 // A following response proves the writer flushed the slow call and is
2629 // waiting for another frame, so a closed outbound queue cannot mask the bug.
2630 host.call(protocol::CoreRequest::Ping, None).await.unwrap();
2631 let probe = Arc::new(AdmissionProbe {
2632 host: Arc::clone(&host),
2633 result: Mutex::new(None),
2634 woke: tokio::sync::Notify::new(),
2635 });
2636 let waker = Waker::from(Arc::clone(&probe));
2637 assert!(
2638 Pin::new(&mut call)
2639 .poll(&mut Context::from_waker(&waker))
2640 .is_pending()
2641 );
2642 assert!(
2643 !host.is_retiring(),
2644 "this exercises exit, not maintenance sealing"
2645 );
2646 host.terminate("ordinary exit admission regression".into());
2647 tokio::time::timeout(Duration::from_secs(5), probe.woke.notified())
2648 .await
2649 .expect("exit must fail the pending call");
2650 assert!(matches!(
2651 probe.result.lock().unwrap().take().unwrap(),
2652 Err(HostCallError::Exited(_))
2653 ));
2654 assert!(matches!(call.await.unwrap(), Err(HostCallError::Exited(_))));
2655 manager.shutdown().await;
2656 }
2657
2658 #[tokio::test]
2659 async fn idle_retirement_seals_admission_and_does_not_wait_for_heartbeat() {
2660 use futures_util::FutureExt;
2661
2662 let Some(node) = node_for_tests("idle admission") else {
2663 return;
2664 };
2665 let _policy = TestPolicyGuard::extension_host(true);
2666 let fixture = FixturePlugins::new(&["slow-tool"]).await;
2667 let manager = supervised_manager(&fixture, node);
2668 let engine = manager.attach(fixture.registry());
2669 engine.sync().await.unwrap();
2670 let host = manager.shared.ready_host(&HostCohort::reviewed()).unwrap();
2671 let registration = manager.shared.registry.lock().unwrap().live_tools()[0].clone();
2672 let (_, call) = host
2673 .start_request(
2674 protocol::CoreRequest::ToolCall(protocol::ToolCallParams {
2675 handle: registration.handle,
2676 call_id: "idle-admission".into(),
2677 input: json!({"ms": 100}),
2678 deadline_ms: 5000,
2679 workspace: None,
2680 ticket: None,
2681 checkpoint_ticket: None,
2682 question_ticket: None,
2683 subagent_ticket: None,
2684 broker_tickets: None,
2685 caller_tools: None,
2686 session_id: None,
2687 agent_id: None,
2688 origin_turn_id: None,
2689 }),
2690 Some(registration.owner.plugin_id),
2691 )
2692 .unwrap();
2693 assert!(!host.terminate_if_idle(super::DIRTY_RESTART_REASON));
2694 assert!(call.await.unwrap().is_ok());
2695 // No await between admission and retirement: this heartbeat is still in
2696 // the pending map, but it does not make the process busy.
2697 let (_, _heartbeat) = host
2698 .start_request(protocol::CoreRequest::Ping, None)
2699 .unwrap();
2700 assert!(host.terminate_if_idle(super::DIRTY_RESTART_REASON));
2701 assert!(matches!(
2702 manager.shared.ready_host(&HostCohort::reviewed()),
2703 Err(HostStatus::Restarting { .. })
2704 ));
2705 assert!(matches!(manager.status(), HostStatus::Restarting { .. }));
2706 // Poll without yielding to the exit watcher. A reconcile in this exact
2707 // gap must not start activation on the sealed process and falsely fail
2708 // a valid receipt before replay.
2709 assert!(
2710 manager
2711 .ensure_host(&HostCohort::reviewed(), true)
2712 .now_or_never()
2713 .unwrap()
2714 .is_err()
2715 );
2716 assert_eq!(
2717 manager.owner_state(&plugin_id(&fixture, "slow-tool")),
2718 Some(OwnerState::Active)
2719 );
2720 assert!(matches!(
2721 host.start_request(protocol::CoreRequest::Ping, None),
2722 Err(super::supervisor::HostCallError::Exited(_))
2723 ));
2724 assert!(!host.terminate_if_idle(super::DIRTY_RESTART_REASON));
2725 manager.shutdown().await;
2726 }
2727
2728 #[tokio::test]
2729 async fn two_dirty_teardowns_wait_for_a_live_call_then_replay_without_spending_crash_budget() {
2730 let Some(node) = node_for_tests("dirty teardown") else {
2731 return;
2732 };
2733 let _policy = TestPolicyGuard::extension_host(true);
2734 let fixture = FixturePlugins::new(&["dirty-dispose", "slow-tool"]).await;
2735 let manager = supervised_manager(&fixture, node);
2736 let engine = manager.attach(fixture.registry());
2737 engine.sync().await.unwrap();
2738 // An existing unexpected crash must survive planned maintenance.
2739 manager
2740 .shared
2741 .plugin
2742 .supervision
2743 .lock()
2744 .unwrap()
2745 .record_crash(Instant::now(), &manager.shared.options.supervision);
2746 engine.set_plugins(fixture.disable("dirty-dispose"));
2747 engine.sync().await.unwrap();
2748 assert_eq!(
2749 manager
2750 .shared
2751 .plugin
2752 .supervision
2753 .lock()
2754 .unwrap()
2755 .dirty_teardowns
2756 .len(),
2757 1
2758 );
2759 tokio::time::sleep(Duration::from_millis(150)).await;
2760 assert_eq!(
2761 manager.spawn_attempts(),
2762 1,
2763 "one dirty event is insufficient"
2764 );
2765
2766 let mut enabled = discover_with_config(&fixture.config);
2767 enabled.enable("dirty-dispose").unwrap();
2768 engine.set_plugins(Arc::new(enabled));
2769 engine.sync().await.unwrap();
2770 let old = host_tool(&engine, fixture.workspace(), "slow_wait");
2771 let host = manager.shared.ready_host(&HostCohort::reviewed()).unwrap();
2772 let registration = manager.shared.registry.lock().unwrap().live_tools()[0].clone();
2773 let (_, call) = host
2774 .start_request(
2775 protocol::CoreRequest::ToolCall(protocol::ToolCallParams {
2776 handle: registration.handle,
2777 call_id: "survives-dirty-teardown".into(),
2778 input: json!({"ms": 4000}),
2779 deadline_ms: 10000,
2780 workspace: None,
2781 ticket: None,
2782 checkpoint_ticket: None,
2783 question_ticket: None,
2784 subagent_ticket: None,
2785 broker_tickets: None,
2786 caller_tools: None,
2787 session_id: None,
2788 agent_id: None,
2789 origin_turn_id: None,
2790 }),
2791 Some(registration.owner.plugin_id.clone()),
2792 )
2793 .unwrap();
2794 engine.set_plugins(fixture.disable("dirty-dispose"));
2795 engine.sync().await.unwrap();
2796 assert!(
2797 manager
2798 .shared
2799 .plugin
2800 .supervision
2801 .lock()
2802 .unwrap()
2803 .dirty_restart_pending
2804 );
2805 tokio::time::sleep(Duration::from_millis(150)).await;
2806 assert_eq!(manager.spawn_attempts(), 1, "a live call defers retirement");
2807 let completed = tokio::time::timeout(Duration::from_secs(10), call)
2808 .await
2809 .unwrap()
2810 .unwrap()
2811 .unwrap();
2812 assert_eq!(completed["structured"]["waited"], 4000);
2813 wait_host(&manager, || {
2814 manager.spawn_attempts() == 2 && manager.live_tool_names().contains(&"slow_wait".into())
2815 })
2816 .await;
2817 assert_eq!(
2818 manager
2819 .shared
2820 .plugin
2821 .supervision
2822 .lock()
2823 .unwrap()
2824 .crashes
2825 .len(),
2826 1
2827 );
2828 assert!(
2829 !manager
2830 .shared
2831 .plugin
2832 .supervision
2833 .lock()
2834 .unwrap()
2835 .dirty_restart_pending
2836 );
2837 let replayed = manager.shared.registry.lock().unwrap().live_tools()[0].clone();
2838 assert_ne!(registration.owner, replayed.owner);
2839 assert_ne!(registration.handle, replayed.handle);
2840 assert!(matches!(
2841 old.execute(
2842 json!({"ms": 1}),
2843 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view())
2844 )
2845 .await,
2846 Err(ToolError::NotAvailable { .. })
2847 ));
2848 // A delayed outcome from the retired process cannot dirty its replacement.
2849 manager.shared.record_dirty_teardown(&host);
2850 assert!(
2851 manager
2852 .shared
2853 .plugin
2854 .supervision
2855 .lock()
2856 .unwrap()
2857 .dirty_teardowns
2858 .is_empty()
2859 );
2860 manager.shutdown().await;
2861 }
2862
2863 #[tokio::test]
2864 async fn failed_activation_cleanup_also_records_a_dirty_teardown() {
2865 let Some(node) = node_for_tests("failed activation teardown") else {
2866 return;
2867 };
2868 let _policy = TestPolicyGuard::extension_host(true);
2869 let fixture = FixturePlugins::new(&["clash-script"]).await;
2870 native_bundle(
2871 &fixture.config.user_plugins_dir,
2872 "failed-disposal",
2873 "index.mjs",
2874 &["index.mjs"],
2875 );
2876 std::fs::write(
2877 fixture.config.user_plugins_dir.join("failed-disposal/index.mjs"),
2878 "export const name = 'failed-disposal';\nexport function apply(ctx) {\n ctx.effect(() => () => new Promise(() => {}), 'unfinished activation cleanup');\n throw new Error('fixture activation failure');\n}\n",
2879 ).unwrap();
2880 let mut plugins = discover_with_config(&fixture.config);
2881 plugins.trust("failed-disposal").unwrap();
2882 plugins.enable("failed-disposal").unwrap();
2883 let manager = supervised_manager(&fixture, node);
2884 let engine = manager.attach(Arc::new(plugins));
2885 tokio::time::timeout(Duration::from_secs(15), engine.sync())
2886 .await
2887 .unwrap()
2888 .unwrap();
2889 assert!(matches!(
2890 manager.owner_state(&plugin_id(&fixture, "failed-disposal")),
2891 Some(OwnerState::Failed(_))
2892 ));
2893 assert_eq!(
2894 manager
2895 .shared
2896 .plugin
2897 .supervision
2898 .lock()
2899 .unwrap()
2900 .dirty_teardowns
2901 .len(),
2902 1
2903 );
2904 assert!(
2905 manager
2906 .shared
2907 .plugin
2908 .supervision
2909 .lock()
2910 .unwrap()
2911 .crashes
2912 .is_empty()
2913 );
2914 assert_eq!(manager.spawn_attempts(), 1);
2915 assert!(
2916 manager
2917 .live_tool_names()
2918 .contains(&"fixture_script_tool".into())
2919 );
2920 manager.shutdown().await;
2921 }
2922
2923 #[test]
2924 fn host_exit_preserves_failed_receipts_and_blames_only_the_activating_owner() {
2925 let mut registry = OwnerRegistry::new();
2926 let active = registry
2927 .begin_owner(
2928 HostCohort::reviewed(),
2929 "healthy",
2930 "healthy",
2931 Some(fake_authority("healthy")),
2932 "hash-healthy",
2933 )
2934 .unwrap();
2935 registry.mark_active(&active);
2936 register(&mut registry, &active, "healthy_probe").unwrap();
2937 let failed = registry
2938 .begin_owner(
2939 HostCohort::reviewed(),
2940 "failed",
2941 "failed",
2942 Some(fake_authority("failed")),
2943 "hash-failed",
2944 )
2945 .unwrap();
2946 registry.mark_failed(&failed, OwnerState::Faulted("existing fault".into()));
2947 registry
2948 .begin_owner(
2949 HostCohort::reviewed(),
2950 "activating",
2951 "activating",
2952 Some(fake_authority("activating")),
2953 "hash-activating",
2954 )
2955 .unwrap();
2956 registry.host_exited(HostCohort::reviewed(), "fixture crash");
2957 assert!(registry.owner("healthy").is_none());
2958 assert!(registry.live_tools().is_empty());
2959 assert!(matches!(
2960 registry.owner("failed").unwrap().state,
2961 OwnerState::Faulted(_)
2962 ));
2963 assert!(matches!(
2964 registry.owner("activating").unwrap().state,
2965 OwnerState::Failed(_)
2966 ));
2967 let replay = registry
2968 .begin_owner(
2969 HostCohort::reviewed(),
2970 "healthy",
2971 "healthy",
2972 Some(fake_authority("healthy")),
2973 "hash-healthy",
2974 )
2975 .unwrap();
2976 assert_ne!(replay.generation, active.generation);
2977 assert_ne!(replay.owner_token, active.owner_token);
2978 }
2979
2980 #[test]
2981 fn opening_an_engine_never_resets_a_crash_budget() {
2982 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions::default()));
2983 {
2984 *manager.shared.plugin.host.lock().unwrap() = super::HostSlot::Failed {
2985 reason: "budget".into(),
2986 stderr_tail: String::new(),
2987 };
2988 let mut state = manager.shared.plugin.supervision.lock().unwrap();
2989 for _ in 0..3 {
2990 state.record_crash(Instant::now(), &manager.shared.options.supervision);
2991 }
2992 }
2993 let _engine = manager.attach(Arc::new(PluginRegistry::empty(Path::new("/fixture"))));
2994 assert_eq!(
2995 manager
2996 .shared
2997 .plugin
2998 .supervision
2999 .lock()
3000 .unwrap()
3001 .crashes
3002 .len(),
3003 3
3004 );
3005 assert!(matches!(manager.status(), HostStatus::Failed { .. }));
3006 manager.retry();
3007 assert!(
3008 manager
3009 .shared
3010 .plugin
3011 .supervision
3012 .lock()
3013 .unwrap()
3014 .crashes
3015 .is_empty()
3016 );
3017 assert_eq!(manager.status(), HostStatus::Idle);
3018 }
3019
3020 /// One typed state, `HostStatus`, names why the host is down in `/plugin`
3021 /// and in the error a tool call routed to it gets.
3022 #[tokio::test]
3023 async fn a_host_that_is_down_names_why_in_plugin_status_and_tool_errors() {
3024 let policy = TestPolicyGuard::extension_host(true);
3025 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions::default()));
3026 let registration = {
3027 let mut registry = manager.shared.registry.lock().unwrap();
3028 let owner = registry
3029 .begin_owner(
3030 HostCohort::reviewed(),
3031 "probe",
3032 "probe",
3033 Some(fake_authority("probe")),
3034 "hash",
3035 )
3036 .unwrap();
3037 registry.mark_active(&owner);
3038 register(&mut registry, &owner, "probe_tool").unwrap();
3039 registry.live_tools()[0].clone()
3040 };
3041 let tool = super::tool::HostToolSpec::new(registration, Arc::clone(&manager.shared));
3042 let context = ToolContext::new(Path::new("/fixture"));
3043 let refused = "start failed: host did not apply the requested 1024 MiB kernel memory limit; initialization refused";
3044 for (slot, why) in [
3045 (
3046 super::HostSlot::Restarting {
3047 reason: "exited with signal: 9 (SIGKILL)".into(),
3048 },
3049 "restarting after: exited with signal: 9 (SIGKILL)".to_string(),
3050 ),
3051 (
3052 super::HostSlot::Failed {
3053 reason: refused.into(),
3054 stderr_tail: String::new(),
3055 },
3056 format!("{refused} (change or reload a plugin to retry)"),
3057 ),
3058 (super::HostSlot::Idle, "not started".to_string()),
3059 ] {
3060 *manager.shared.plugin.host.lock().unwrap() = slot;
3061 let report = super::render_status(&manager);
3062 assert!(
3063 report.starts_with(&format!("Plugin host (experimental): {why}")),
3064 "{report}"
3065 );
3066 match tool.execute(json!({}), &context).await {
3067 Err(ToolError::NotAvailable { message }) => assert!(
3068 message.starts_with(&format!("plugin host is down: {why}")),
3069 "{message}"
3070 ),
3071 other => panic!("expected a typed not-available error, got {other:?}"),
3072 }
3073 }
3074 drop(policy);
3075 let _off = TestPolicyGuard::extension_host(false);
3076 let disabled = "disabled by config ([features] extension_host is off)";
3077 assert_eq!(
3078 super::status_report(),
3079 format!("Plugin host (experimental): {disabled}")
3080 );
3081 match tool.execute(json!({}), &context).await {
3082 Err(ToolError::NotAvailable { message }) => {
3083 assert_eq!(message, format!("plugin host is down: {disabled}"))
3084 }
3085 other => panic!("expected a typed not-available error, got {other:?}"),
3086 }
3087 }
3088
3089 #[tokio::test]
3090 async fn three_crashes_stop_replay_until_explicit_retry() {
3091 let Some(node) = node_for_tests("crash budget") else {
3092 return;
3093 };
3094 let _policy = TestPolicyGuard::extension_host(true);
3095 let fixture = FixturePlugins::new(&["crash-tool", "refuses-approval"]).await;
3096 let manager = supervised_manager(&fixture, node);
3097 let engine = manager.attach(fixture.registry());
3098 engine.sync().await.unwrap();
3099 let failed_id = plugin_id(&fixture, "refuses-approval");
3100 let mut previous = None;
3101 for crash in 1..=3 {
3102 let tool = host_tool(&engine, fixture.workspace(), "crash_probe");
3103 let registration = manager
3104 .shared
3105 .registry
3106 .lock()
3107 .unwrap()
3108 .live_tools()
3109 .into_iter()
3110 .find(|t| t.name == "crash_probe")
3111 .unwrap();
3112 if let Some(old) = previous {
3113 assert_ne!(registration.owner, old);
3114 }
3115 previous = Some(registration.owner);
3116 let outcome = tool
3117 .execute(
3118 json!({}),
3119 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view()),
3120 )
3121 .await;
3122 assert!(matches!(outcome, Err(ToolError::NotAvailable { .. })));
3123 if crash < 3 {
3124 wait_host(&manager, || {
3125 manager.spawn_attempts() == crash + 1
3126 && manager.live_tool_names().contains(&"crash_probe".into())
3127 })
3128 .await;
3129 assert!(matches!(
3130 manager.owner_state(&failed_id),
3131 Some(OwnerState::Failed(_))
3132 ));
3133 } else {
3134 wait_host(&manager, || {
3135 matches!(manager.status(), HostStatus::Failed { .. })
3136 })
3137 .await;
3138 }
3139 }
3140 assert_eq!(manager.spawn_attempts(), 3);
3141 let _another = manager.attach(fixture.registry());
3142 engine.sync().await.ok();
3143 assert_eq!(manager.spawn_attempts(), 3);
3144 manager.retry();
3145 engine.sync().await.unwrap();
3146 assert_eq!(manager.spawn_attempts(), 4);
3147 assert!(
3148 manager
3149 .shared
3150 .plugin
3151 .supervision
3152 .lock()
3153 .unwrap()
3154 .crashes
3155 .is_empty()
3156 );
3157 manager.shutdown().await;
3158 }
3159
3160 #[tokio::test]
3161 async fn an_activation_crash_does_not_prevent_other_receipts_replaying() {
3162 let Some(node) = node_for_tests("activation crash") else {
3163 return;
3164 };
3165 let _policy = TestPolicyGuard::extension_host(true);
3166 let fixture = FixturePlugins::new(&["crash-activation", "clash-script"]).await;
3167 let manager = supervised_manager(&fixture, node);
3168 let engine = manager.attach(fixture.registry());
3169 engine.sync().await.unwrap();
3170 wait_host(&manager, || {
3171 manager.spawn_attempts() == 2
3172 && manager
3173 .live_tool_names()
3174 .contains(&"fixture_script_tool".into())
3175 })
3176 .await;
3177 assert!(matches!(
3178 manager.owner_state(&plugin_id(&fixture, "crash-activation")),
3179 Some(OwnerState::Failed(_))
3180 ));
3181 assert_eq!(
3182 manager
3183 .shared
3184 .plugin
3185 .supervision
3186 .lock()
3187 .unwrap()
3188 .crashes
3189 .len(),
3190 1
3191 );
3192 manager.shutdown().await;
3193 }
3194
3195 #[tokio::test]
3196 async fn heartbeat_recovers_a_delayed_pong_then_kills_a_hung_host() {
3197 let Some(node) = node_for_tests("heartbeat") else {
3198 return;
3199 };
3200 let _policy = TestPolicyGuard::extension_host(true);
3201 let fixture = FixturePlugins::new(&["hang-tool"]).await;
3202 let supervision = super::SupervisionOptions {
3203 hang_timeout: Duration::from_millis(2_500),
3204 ..fast_supervision()
3205 };
3206 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
3207 runtime: NODE,
3208 node_override: Some(node),
3209 bun_override: None,
3210 root: Some(fixture.root.clone()),
3211 supervision,
3212 }));
3213 let engine = manager.attach(fixture.registry());
3214 engine.sync().await.unwrap();
3215 let tool = host_tool(&engine, fixture.workspace(), "hang_probe");
3216 let workspace = fixture.workspace().to_path_buf();
3217 let plugins = engine.plugin_view();
3218 let task = tokio::spawn(async move {
3219 tool.execute(
3220 json!({"ms": 400}),
3221 &ToolContext::new(&workspace).with_plugin_registry(plugins),
3222 )
3223 .await
3224 });
3225 wait_host(&manager, || {
3226 matches!(manager.status(), HostStatus::Unresponsive { .. })
3227 })
3228 .await;
3229 let result = task.await.unwrap();
3230 assert!(result.is_ok(), "delayed live call failed: {result:?}");
3231 wait_host(&manager, || {
3232 matches!(manager.status(), HostStatus::Ready { .. })
3233 })
3234 .await;
3235 assert_eq!(manager.spawn_attempts(), 1);
3236 let tool = host_tool(&engine, fixture.workspace(), "hang_probe");
3237 let result = tokio::time::timeout(
3238 Duration::from_secs(10),
3239 tool.execute(
3240 json!({}),
3241 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view()),
3242 ),
3243 )
3244 .await
3245 .unwrap();
3246 assert!(matches!(result, Err(ToolError::NotAvailable { .. })));
3247 wait_host(&manager, || {
3248 manager.spawn_attempts() == 2 && manager.live_tool_names().contains(&"hang_probe".into())
3249 })
3250 .await;
3251 assert_eq!(
3252 manager
3253 .shared
3254 .plugin
3255 .supervision
3256 .lock()
3257 .unwrap()
3258 .crashes
3259 .len(),
3260 1
3261 );
3262 manager.shutdown().await;
3263 }
3264
3265 #[test]
3266 fn old_host_callbacks_cannot_fault_or_remove_a_new_owner() {
3267 use super::supervisor::HostEvents;
3268 let manager = ExtensionHostManager::new(ExtensionHostOptions::default());
3269 manager
3270 .shared
3271 .plugin
3272 .host_generation
3273 .store(2, std::sync::atomic::Ordering::SeqCst);
3274 let owner = {
3275 let mut registry = manager.shared.registry.lock().unwrap();
3276 let owner = registry
3277 .begin_owner(
3278 HostCohort::reviewed(),
3279 "fixture",
3280 "fixture",
3281 Some(fake_authority("fixture")),
3282 "hash-fixture",
3283 )
3284 .unwrap();
3285 registry.mark_active(&owner);
3286 register(&mut registry, &owner, "fixture_probe").unwrap();
3287 owner
3288 };
3289 let old = super::Events {
3290 shared: Arc::downgrade(&manager.shared),
3291 cohort: HostCohort::reviewed(),
3292 generation: 1,
3293 };
3294 old.faulted(&protocol::FaultedParams {
3295 owner,
3296 error: "stale fault".into(),
3297 });
3298 old.exited(1, "stale exit".into(), String::new());
3299 assert_eq!(manager.owner_state("fixture"), Some(OwnerState::Active));
3300 assert_eq!(manager.live_tool_names(), ["fixture_probe"]);
3301 assert!(
3302 manager
3303 .shared
3304 .plugin
3305 .supervision
3306 .lock()
3307 .unwrap()
3308 .crashes
3309 .is_empty()
3310 );
3311 }
3312
3313 #[test]
3314 fn a_new_attachment_retries_only_cooled_down_launch_failures() {
3315 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions::default()));
3316 *manager.shared.plugin.host.lock().unwrap() = super::HostSlot::Failed {
3317 reason: "missing Node".into(),
3318 stderr_tail: String::new(),
3319 };
3320 {
3321 let mut state = manager.shared.plugin.supervision.lock().unwrap();
3322 state.launch_failed = true;
3323 state.last_start = Some(Instant::now());
3324 }
3325 let plugins = Arc::new(PluginRegistry::empty(Path::new("/fixture")));
3326 let _first = manager.attach(Arc::clone(&plugins));
3327 assert!(matches!(manager.status(), HostStatus::Failed { .. }));
3328 manager.shared.plugin.supervision.lock().unwrap().last_start =
3329 Some(Instant::now() - Duration::from_secs(61));
3330 let _later = manager.attach(plugins);
3331 assert_eq!(manager.status(), HostStatus::Idle);
3332 }
3333
3334 #[tokio::test]
3335 async fn replay_rechecks_persisted_disable_and_keeps_workspace_tools_separate() {
3336 let Some(node) = node_for_tests("replay authority") else {
3337 return;
3338 };
3339 let _policy = TestPolicyGuard::extension_host(true);
3340 let a = FixturePlugins::new(&["crash-tool"]).await;
3341 let b = FixturePlugins::new(&["clash-script"]).await;
3342 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
3343 runtime: NODE,
3344 node_override: Some(node),
3345 bun_override: None,
3346 root: Some(a.root.clone()),
3347 supervision: super::SupervisionOptions {
3348 restart_backoff: Duration::from_secs(1),
3349 ..fast_supervision()
3350 },
3351 }));
3352 let first = manager.attach(a.registry());
3353 let second = manager.attach(b.registry());
3354 first.sync().await.unwrap();
3355 let tool = host_tool(&first, a.workspace(), "crash_probe");
3356 assert!(matches!(
3357 tool.execute(
3358 json!({}),
3359 &ToolContext::new(a.workspace()).with_plugin_registry(first.plugin_view())
3360 )
3361 .await,
3362 Err(ToolError::NotAvailable { .. })
3363 ));
3364 wait_host(&manager, || {
3365 matches!(manager.status(), HostStatus::Restarting { .. })
3366 })
3367 .await;
3368 // Keep the engine's snapshot stale deliberately. Replay must consult the
3369 // persisted state rather than restoring the previous owner's authority.
3370 a.disable("crash-tool");
3371 wait_host(&manager, || {
3372 manager.spawn_attempts() == 2
3373 && manager
3374 .live_tool_names()
3375 .contains(&"fixture_script_tool".into())
3376 })
3377 .await;
3378 assert!(installed(&first, a.workspace()).is_empty());
3379 assert_eq!(installed(&second, b.workspace()), ["fixture_script_tool"]);
3380 assert!(manager.owner_state(&plugin_id(&a, "crash-tool")).is_none());
3381 manager.shutdown().await;
3382 tokio::time::sleep(Duration::from_millis(100)).await;
3383 assert_eq!(manager.status(), HostStatus::Idle);
3384 assert_eq!(
3385 manager.spawn_attempts(),
3386 2,
3387 "planned shutdown never restarts"
3388 );
3389 }
3390
3391 #[tokio::test]
3392 async fn explicit_retry_refreshes_same_byte_authority_without_inheriting_old_handles() {
3393 let Some(node) = node_for_tests("same byte retry") else {
3394 return;
3395 };
3396 let _policy = TestPolicyGuard::extension_host(true);
3397 let fixture = FixturePlugins::new(&["clash-script"]).await;
3398 let manager = supervised_manager(&fixture, node);
3399 let engine = manager.attach(fixture.registry());
3400 engine.sync().await.unwrap();
3401 let old = host_tool(&engine, fixture.workspace(), "fixture_script_tool");
3402 let old_owner = manager.shared.registry.lock().unwrap().live_tools()[0]
3403 .owner
3404 .clone();
3405 let mut updated = discover_with_config(&fixture.config);
3406 updated.enable("clash-script").unwrap();
3407 manager.refresh_workspace(&Arc::new(updated));
3408 manager.retry();
3409 engine.sync().await.unwrap();
3410 let current_owner = manager.shared.registry.lock().unwrap().live_tools()[0]
3411 .owner
3412 .clone();
3413 assert_ne!(old_owner, current_owner);
3414 assert!(matches!(
3415 old.execute(
3416 json!({}),
3417 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view())
3418 )
3419 .await,
3420 Err(ToolError::NotAvailable { .. })
3421 ));
3422 let current = host_tool(&engine, fixture.workspace(), "fixture_script_tool");
3423 assert!(
3424 current
3425 .execute(
3426 json!({}),
3427 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view())
3428 )
3429 .await
3430 .is_ok()
3431 );
3432 assert_eq!(
3433 manager.spawn_attempts(),
3434 1,
3435 "a healthy process need not restart"
3436 );
3437 manager.shutdown().await;
3438 }
3439
3440 // ---------------------------------------------------------------------------
3441 // Runtime selection (Bun / Node) and the memory cap
3442 // ---------------------------------------------------------------------------
3443
3444 /// A Bun >= 1.4.0 for the Bun integration tests, or `None` (skip) unless
3445 /// `CODEWHALE_EXT_HOST_BUN_TESTS` requires one.
3446 fn bun_for_tests(test: &str) -> Option<PathBuf> {
3447 let resolution = codewhale_dependencies::resolve_extension_host_runtime(
3448 codewhale_config::extension_host::ExtensionHostRuntime::Bun,
3449 None,
3450 None,
3451 crate::extension_host::bundle_sha256(),
3452 );
3453 match resolution.selected {
3454 Some(runtime) => Some(runtime.path),
3455 None if std::env::var_os("CODEWHALE_EXT_HOST_BUN_TESTS").is_some() => panic!(
3456 "{test}: CODEWHALE_EXT_HOST_BUN_TESTS is set but {}",
3457 resolution.failure()
3458 ),
3459 None => {
3460 eprintln!("skipping {test}: {}", resolution.failure());
3461 None
3462 }
3463 }
3464 }
3465
3466 fn bun_manager(
3467 fixture: &FixturePlugins,
3468 bun: PathBuf,
3469 supervision: super::SupervisionOptions,
3470 ) -> Arc<ExtensionHostManager> {
3471 Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
3472 runtime: codewhale_config::extension_host::ExtensionHostRuntime::Bun,
3473 node_override: None,
3474 bun_override: Some(bun),
3475 root: Some(fixture.root.clone()),
3476 supervision,
3477 }))
3478 }
3479
3480 #[test]
3481 fn node_is_the_default_runtime_and_bun_is_an_opt_in() {
3482 use codewhale_config::extension_host::{ExtensionHostConfig, ExtensionHostRuntime as Choice};
3483 let parse = |text: &str| toml::from_str::<ExtensionHostConfig>(text).unwrap();
3484 // Bun is not the default until it is qualified on every platform.
3485 assert_eq!(parse("").effective_runtime(), Choice::Node);
3486 assert_eq!(
3487 parse("node = \"/opt/node\"").effective_runtime(),
3488 Choice::Node
3489 );
3490 // A table that names only a Bun asks for Bun.
3491 assert_eq!(parse("bun = \"/opt/bun\"").effective_runtime(), Choice::Bun);
3492 assert_eq!(
3493 parse("node = \"/n\"\nbun = \"/b\"").effective_runtime(),
3494 Choice::Node
3495 );
3496 assert_eq!(
3497 parse("runtime = \"bun\"\nnode = \"/n\"").effective_runtime(),
3498 Choice::Bun
3499 );
3500 assert_eq!(
3501 parse("runtime = \"auto\"").effective_runtime(),
3502 Choice::Auto
3503 );
3504 assert!(toml::from_str::<ExtensionHostConfig>("runtime = \"deno\"").is_err());
3505 let options = ExtensionHostOptions::from_config(Some(&parse("node = \"~/node\"")));
3506 assert_eq!(options.runtime, Choice::Node);
3507 assert!(!options.node_override.unwrap().starts_with("~"));
3508 assert_eq!(
3509 ExtensionHostOptions::from_config(None).runtime,
3510 Choice::Node
3511 );
3512 assert_eq!(ExtensionHostOptions::default().runtime, Choice::Node);
3513 }
3514
3515 #[test]
3516 fn launch_plan_gives_each_runtime_its_own_flags() {
3517 use codewhale_dependencies::{HostRuntime, HostRuntimeKind};
3518 let home = tempfile::tempdir().unwrap();
3519 let bundle = home.path().join("codewhale-extension-host.mjs");
3520 for (kind, expected) in [
3521 (
3522 HostRuntimeKind::Bun,
3523 vec!["--no-install", "--no-env-file", "--config=", "--no-addons"],
3524 ),
3525 (
3526 HostRuntimeKind::Node,
3527 [
3528 &[
3529 "--max-old-space-size=256",
3530 "--disable-proto=throw",
3531 "--no-addons",
3532 ][..],
3533 if cfg!(windows) {
3534 &["--preserve-symlinks", "--preserve-symlinks-main"][..]
3535 } else {
3536 &[][..]
3537 },
3538 &["--no-experimental-sqlite", "--no-experimental-ffi"][..],
3539 ]
3540 .concat(),
3541 ),
3542 ] {
3543 let runtime = HostRuntime {
3544 kind,
3545 path: PathBuf::from("/opt/runtime/bin").join(kind.name()),
3546 version: (1, 4, 0),
3547 compiled: false,
3548 native_code_flags: match kind {
3549 HostRuntimeKind::Bun => Vec::new(),
3550 HostRuntimeKind::Node => codewhale_dependencies::NODE_NATIVE_CODE_FLAGS.to_vec(),
3551 },
3552 };
3553 let launch = super::supervisor::plan_launch(
3554 &HostCohort::Builtin,
3555 &runtime,
3556 &bundle,
3557 home.path(),
3558 1 << 30,
3559 &[],
3560 )
3561 .unwrap();
3562 // Wrapped or not, the runtime's flags come right before the bundle.
3563 let at = launch
3564 .args
3565 .iter()
3566 .position(|arg| Path::new(arg) == bundle)
3567 .expect("bundle in argv");
3568 let flags = &launch.args[at - expected.len()..at];
3569 for (flag, want) in flags.iter().zip(&expected) {
3570 assert!(flag.starts_with(want), "{kind:?}: {flags:?}");
3571 }
3572 assert_eq!(launch.runtime, runtime);
3573 assert_eq!(launch.memory_cap, 1 << 30);
3574 assert_eq!(
3575 launch.memory,
3576 super::supervisor::MemoryEnforcement::planned(kind)
3577 );
3578 let shadow_realm_off = launch
3579 .runtime_env
3580 .contains(&("BUN_JSC_useShadowRealm".to_string(), "0".to_string()));
3581 // An inherited NODE_OPTIONS preload must not run before the lockdown.
3582 assert!(
3583 launch
3584 .runtime_env
3585 .contains(&("NODE_OPTIONS".to_string(), String::new())),
3586 "{:?}",
3587 launch.runtime_env
3588 );
3589 assert_eq!(shadow_realm_off, kind == HostRuntimeKind::Bun);
3590 if kind == HostRuntimeKind::Bun {
3591 assert!(
3592 !launch
3593 .args
3594 .iter()
3595 .any(|arg| arg.starts_with("--max-old-space"))
3596 );
3597 }
3598 }
3599 // Where the kernel limit comes from on each platform.
3600 use super::supervisor::MemoryEnforcement;
3601 let (bun, node) = (
3602 MemoryEnforcement::planned(HostRuntimeKind::Bun),
3603 MemoryEnforcement::planned(HostRuntimeKind::Node),
3604 );
3605 if cfg!(target_os = "macos") {
3606 assert_eq!(
3607 (bun, node),
3608 (MemoryEnforcement::Jetsam, MemoryEnforcement::Heartbeat)
3609 );
3610 } else if cfg!(target_os = "linux") {
3611 assert_eq!(
3612 (bun, node),
3613 (MemoryEnforcement::Rlimit, MemoryEnforcement::Rlimit)
3614 );
3615 } else if cfg!(windows) {
3616 assert_eq!(
3617 (bun, node),
3618 (MemoryEnforcement::JobObject, MemoryEnforcement::JobObject)
3619 );
3620 }
3621 }
3622
3623 #[tokio::test]
3624 async fn handshake_refuses_a_runtime_or_version_mismatch_and_an_unapplied_kernel_cap() {
3625 let Some(node) = node_for_tests("handshake_refuses_a_runtime_or_version_mismatch") else {
3626 return;
3627 };
3628 use codewhale_dependencies::HostRuntimeKind;
3629 let home = tempfile::tempdir().unwrap();
3630 let bundle = super::materialize_bundle(home.path()).unwrap();
3631 // Resolved, so the Node gets the native-code flags it accepts.
3632 let runtime = codewhale_dependencies::resolve_extension_host_runtime(
3633 NODE,
3634 Some(node.as_path()),
3635 None,
3636 crate::extension_host::bundle_sha256(),
3637 )
3638 .selected
3639 .expect("the test Node resolves");
3640 struct NoEvents;
3641 impl super::supervisor::HostEvents for NoEvents {
3642 fn register(&self, _: &protocol::RegisterParams) -> protocol::RegisterResult {
3643 unreachable!()
3644 }
3645 fn unregister(&self, _: &protocol::UnregisterParams) {}
3646 fn faulted(&self, _: &protocol::FaultedParams) {}
3647 fn log(&self, _: &protocol::LogParams) {}
3648 fn exited(&self, _: u64, _: String, _: String) {}
3649 }
3650 for case in ["runtime", "version", "cap"] {
3651 let mut launch = super::supervisor::plan_launch(
3652 &HostCohort::reviewed(),
3653 &runtime,
3654 &bundle,
3655 home.path(),
3656 1 << 30,
3657 &[],
3658 )
3659 .unwrap();
3660 let expected = match case {
3661 // The core believes it launched Bun; the host truthfully says Node.
3662 "runtime" => {
3663 launch.runtime.kind = HostRuntimeKind::Bun;
3664 "host reports runtime node but bun was launched"
3665 }
3666 // The pinned probe saw another version: the binary at that path
3667 // was replaced after it was probed.
3668 "version" => {
3669 launch.runtime.version = (0, 0, 1);
3670 "the runtime binary changed mid-session"
3671 }
3672 // An actual Node host reports no kernel cap. Even with matching
3673 // runtime/digest, the requested hard boundary must block admission.
3674 _ => {
3675 launch.memory = super::supervisor::MemoryEnforcement::Jetsam;
3676 "host did not apply the requested 1024 MiB kernel memory limit; initialization refused"
3677 }
3678 };
3679 let error = match super::supervisor::HostProcess::spawn(
3680 1,
3681 &launch,
3682 super::bundle_sha256(),
3683 Arc::new(NoEvents),
3684 )
3685 .await
3686 {
3687 Ok(_) => panic!("{expected}"),
3688 Err(error) => error,
3689 };
3690 assert!(error.contains(expected), "{error}");
3691 }
3692 }
3693
3694 /// A host that reports another tier than the one launched, or built-in module
3695 /// digests other than the ones the core pins, is refused at the handshake like
3696 /// a runtime mismatch: before initialization, with the reason.
3697 #[tokio::test]
3698 async fn handshake_refuses_a_tier_or_built_in_module_digest_mismatch() {
3699 let Some(node) = node_for_tests("handshake_refuses_a_tier_or_built_in_module_digest_mismatch")
3700 else {
3701 return;
3702 };
3703 // A table that pins a module the host bundle does not embed.
3704 const PINNED: &[super::tier::BuiltinModule] = &[super::tier::BuiltinModule {
3705 id: "demo",
3706 source_sha256: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
3707 tools: &[],
3708 services: &[],
3709 }];
3710 struct NoEvents;
3711 impl super::supervisor::HostEvents for NoEvents {
3712 fn register(&self, _: &protocol::RegisterParams) -> protocol::RegisterResult {
3713 unreachable!()
3714 }
3715 fn unregister(&self, _: &protocol::UnregisterParams) {}
3716 fn faulted(&self, _: &protocol::FaultedParams) {}
3717 fn log(&self, _: &protocol::LogParams) {}
3718 fn exited(&self, _: u64, _: String, _: String) {}
3719 }
3720 let home = tempfile::tempdir().unwrap();
3721 let bundle = super::materialize_bundle(home.path()).unwrap();
3722 let runtime = codewhale_dependencies::resolve_extension_host_runtime(
3723 NODE,
3724 Some(node.as_path()),
3725 None,
3726 crate::extension_host::bundle_sha256(),
3727 )
3728 .selected
3729 .expect("the test Node resolves");
3730 let launch_for = |tier: HostTier| {
3731 let cohort = match tier {
3732 HostTier::Plugin => HostCohort::reviewed(),
3733 HostTier::Builtin => HostCohort::Builtin,
3734 };
3735 super::supervisor::plan_launch(&cohort, &runtime, &bundle, home.path(), 1 << 30, &[])
3736 .unwrap()
3737 };
3738
3739 // Each tier reports its own tier and the exact embedded module digests.
3740 for tier in HostTier::ALL {
3741 let host = super::supervisor::HostProcess::spawn(
3742 1,
3743 &launch_for(tier),
3744 super::bundle_sha256(),
3745 Arc::new(NoEvents),
3746 )
3747 .await
3748 .unwrap_or_else(|error| panic!("{tier:?} host: {error}"));
3749 assert_eq!(host.tier, tier);
3750 host.shutdown().await;
3751 }
3752
3753 let mut embedded: Vec<_> = super::tier::BUILTIN_MODULES
3754 .iter()
3755 .map(|module| format!("{}={}", module.id, &module.source_sha256[..12]))
3756 .collect();
3757 embedded.sort();
3758 let module_mismatch = format!(
3759 "host bundle embeds the built-in module digests [{}] but the core pins [demo=0123456789ab]",
3760 embedded.join(", ")
3761 );
3762 for (case, expected) in [
3763 (
3764 "tier",
3765 "host reports the plugin tier but the builtin tier was launched",
3766 ),
3767 ("modules", module_mismatch.as_str()),
3768 ] {
3769 let mut launch = launch_for(HostTier::Plugin);
3770 match case {
3771 // The core believes it launched the builtin tier; the host, started
3772 // with `--tier=plugin`, truthfully says plugin.
3773 "tier" => launch.tier = HostTier::Builtin,
3774 _ => launch.builtin_modules = PINNED,
3775 }
3776 let error = match super::supervisor::HostProcess::spawn(
3777 1,
3778 &launch,
3779 super::bundle_sha256(),
3780 Arc::new(NoEvents),
3781 )
3782 .await
3783 {
3784 Ok(_) => panic!("{case}: {expected}"),
3785 Err(error) => error,
3786 };
3787 assert!(error.contains(expected), "{case}: {error}");
3788 }
3789 }
3790
3791 #[tokio::test]
3792 async fn bun_host_runs_the_dsh_plugin_reports_bun_and_restarts_on_bun() {
3793 let Some(bun) = bun_for_tests("bun_host_runs_the_dsh_plugin") else {
3794 return;
3795 };
3796 let _policy = TestPolicyGuard::extension_host(true);
3797 let fixture = FixturePlugins::new(&["dsh-workspace-deps"]).await;
3798 let manager = bun_manager(&fixture, bun.clone(), fast_supervision());
3799 let engine = manager.attach(fixture.registry());
3800 engine.sync().await.unwrap();
3801 let HostStatus::Ready {
3802 runtime,
3803 runtime_version,
3804 ..
3805 } = manager.status()
3806 else {
3807 panic!("{:?} {:?}", manager.status(), manager.diagnostics());
3808 };
3809 assert_eq!(runtime, "bun");
3810 let banner = std::process::Command::new(&bun)
3811 .arg("--version")
3812 .output()
3813 .unwrap();
3814 assert_eq!(
3815 runtime_version,
3816 String::from_utf8_lossy(&banner.stdout).trim()
3817 );
3818 let summary = manager.runtime_summary().unwrap();
3819 assert!(summary.starts_with("bun "), "{summary}");
3820 assert!(summary.contains("(runtime = \"bun\")"), "{summary}");
3821 let report = super::render_status(&manager);
3822 assert!(
3823 report.contains(&format!("· bun {runtime_version} ·")),
3824 "{report}"
3825 );
3826 assert!(report.contains("runtime: bun "), "{report}");
3827
3828 let tool = host_tool(&engine, fixture.workspace(), "load_workspace_dependencies");
3829 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
3830 let result = tool.execute(json!({}), &context).await.unwrap();
3831 assert!(result.success, "{}", result.content);
3832 let payload: Value = serde_json::from_str(&result.content).unwrap();
3833 assert_eq!(payload["pythonDistributions"]["numpy"], "2.1.0");
3834
3835 // A crash restarts on the pinned runtime; it is never re-resolved.
3836 let pid = manager.host_pid().unwrap();
3837 #[cfg(unix)]
3838 assert!(
3839 std::process::Command::new("kill")
3840 .args(["-9", &pid.to_string()])
3841 .status()
3842 .unwrap()
3843 .success()
3844 );
3845 #[cfg(windows)]
3846 assert!(
3847 std::process::Command::new("taskkill")
3848 .args(["/F", "/PID", &pid.to_string()])
3849 .status()
3850 .unwrap()
3851 .success()
3852 );
3853 wait_host(&manager, || {
3854 manager.spawn_attempts() == 2 && matches!(manager.status(), HostStatus::Ready { .. })
3855 })
3856 .await;
3857 assert!(matches!(
3858 manager.status(),
3859 HostStatus::Ready { runtime: "bun", .. }
3860 ));
3861 assert_eq!(manager.runtime_summary().unwrap(), summary);
3862 #[cfg(target_os = "macos")]
3863 {
3864 // This kill came from the operator, not the memory hog. The observed
3865 // signal and configured cap must not invent a cause for it.
3866 let diagnostics = manager.diagnostics();
3867 assert!(
3868 diagnostics
3869 .iter()
3870 .any(|line| line.contains("SIGKILL cause unavailable")),
3871 "{diagnostics:?}"
3872 );
3873 assert!(
3874 !diagnostics
3875 .iter()
3876 .any(|line| line.contains("exceeded its memory cap")),
3877 "{diagnostics:?}"
3878 );
3879 }
3880 manager.shutdown().await;
3881 }
3882
3883 /// `runtime = "auto"`: a Bun that passes the version probe but cannot start
3884 /// the host is reported once, and Node runs the host for the rest of the
3885 /// session. `runtime = "bun"` never falls back, and a launch that never
3886 /// completed a handshake pins nothing.
3887 #[cfg(unix)]
3888 #[tokio::test]
3889 async fn auto_uses_node_for_the_session_when_the_bun_host_fails_to_start() {
3890 use std::os::unix::fs::PermissionsExt;
3891 let Some(node) = node_for_tests("auto_uses_node_when_the_bun_host_fails_to_start") else {
3892 return;
3893 };
3894 let _policy = TestPolicyGuard::extension_host(true);
3895 let fixture = FixturePlugins::new(&["slow-tool"]).await;
3896 let bin = tempfile::tempdir().unwrap();
3897 let bun = bin.path().join("bun");
3898 std::fs::write(
3899 &bun,
3900 "#!/bin/sh\ncase \"$1\" in --version) echo 1.4.0;; *) echo 'simulated Bun start failure' >&2; exit 3;; esac\n",
3901 )
3902 .unwrap();
3903 std::fs::set_permissions(&bun, std::fs::Permissions::from_mode(0o755)).unwrap();
3904 let manager_for = |runtime| {
3905 Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
3906 runtime,
3907 node_override: Some(node.clone()),
3908 bun_override: Some(bun.clone()),
3909 root: Some(fixture.root.clone()),
3910 supervision: fast_supervision(),
3911 }))
3912 };
3913
3914 let manager = manager_for(codewhale_config::extension_host::ExtensionHostRuntime::Auto);
3915 let engine = manager.attach(fixture.registry());
3916 engine.sync().await.unwrap();
3917 assert!(
3918 matches!(
3919 manager.status(),
3920 HostStatus::Ready {
3921 runtime: "node",
3922 ..
3923 }
3924 ),
3925 "{:?} {:?}",
3926 manager.status(),
3927 manager.diagnostics()
3928 );
3929 let diagnostics = manager.diagnostics();
3930 let reported: Vec<_> = diagnostics
3931 .iter()
3932 .filter(|line| line.contains("uses Node for the rest of this session"))
3933 .collect();
3934 assert_eq!(reported.len(), 1, "{diagnostics:?}");
3935 assert!(
3936 reported[0].contains(&bun.display().to_string()),
3937 "{diagnostics:?}"
3938 );
3939 let summary = manager.runtime_summary().unwrap();
3940 assert!(summary.starts_with("node "), "{summary}");
3941 assert!(summary.contains("(runtime = \"auto\")"), "{summary}");
3942 assert!(
3943 summary.contains("Bun failed to start this session"),
3944 "{summary}"
3945 );
3946 assert_eq!(manager.spawn_attempts(), 2);
3947 manager.shutdown().await;
3948
3949 let explicit = manager_for(codewhale_config::extension_host::ExtensionHostRuntime::Bun);
3950 let engine = explicit.attach(fixture.registry());
3951 let _ = engine.sync().await;
3952 assert!(
3953 matches!(explicit.status(), HostStatus::Failed { .. }),
3954 "{:?} {:?}",
3955 explicit.status(),
3956 explicit.diagnostics()
3957 );
3958 assert_eq!(explicit.spawn_attempts(), 1);
3959 assert_eq!(explicit.runtime_summary(), None);
3960 }
3961
3962 /// The cap holds for memory outside the JS heap too (Buffers), which Node's
3963 /// `--max-old-space-size` never bounded. Linux and Windows: the kernel fails
3964 /// the allocation at 1 GiB. macOS: Bun's jetsam limit gets the host killed by
3965 /// the kernel; a Node host is killed by the heartbeat check.
3966 async fn memory_hog_is_stopped(
3967 manager: Arc<ExtensionHostManager>,
3968 fixture: &FixturePlugins,
3969 kind: codewhale_dependencies::HostRuntimeKind,
3970 ) {
3971 use super::supervisor::MemoryEnforcement;
3972 let engine = manager.attach(fixture.registry());
3973 engine.sync().await.unwrap();
3974 // The host confirmed the enforcement this platform plans for it (for
3975 // macOS + Bun: the jetsam limit it applied to itself, via `host/hello`).
3976 let HostStatus::Ready { memory, .. } = manager.status() else {
3977 panic!("{:?} {:?}", manager.status(), manager.diagnostics());
3978 };
3979 assert_eq!(memory, MemoryEnforcement::planned(kind));
3980 let tool = host_tool(&engine, fixture.workspace(), "memory_hog");
3981 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
3982 let outcome = tokio::time::timeout(
3983 Duration::from_secs(60),
3984 tool.execute(json!({"mib": 2048}), &context),
3985 )
3986 .await
3987 .expect("the hog is stopped well before 60 s");
3988 match &outcome {
3989 Ok(result) => assert!(
3990 !result.success,
3991 "allocating 2 GiB must not succeed under the cap: {}",
3992 result.content
3993 ),
3994 Err(ToolError::NotAvailable { message }) => {
3995 assert!(message.contains("plugin host exited"), "{message}");
3996 }
3997 // Linux (RLIMIT_DATA) and Windows (Job Object): the kernel refuses the
3998 // allocation, the runtime throws inside the tool, and the host lives on.
3999 Err(ToolError::ExecutionFailed { message, .. })
4000 if matches!(
4001 memory,
4002 MemoryEnforcement::Rlimit | MemoryEnforcement::JobObject
4003 ) =>
4004 {
4005 assert!(
4006 message.contains("allocation failed")
4007 || message.ends_with("RangeError: Failed to allocate memory")
4008 || (kind == codewhale_dependencies::HostRuntimeKind::Bun
4009 && message.ends_with("RangeError: Out of memory")),
4010 "{message}"
4011 );
4012 }
4013 Err(other) => panic!("unexpected error: {other:?}"),
4014 }
4015 let stopped_by = match memory {
4016 MemoryEnforcement::Jetsam => {
4017 Some("configured kernel memory limit: 400 MiB; SIGKILL cause unavailable")
4018 }
4019 MemoryEnforcement::Heartbeat => Some("exceeded its memory cap"),
4020 _ => None,
4021 };
4022 if let Some(stopped_by) = stopped_by {
4023 // Pending calls settle before the existing exit callback publishes
4024 // its diagnostic. Observe that callback rather than race its delivery.
4025 wait_host(&manager, || {
4026 manager
4027 .diagnostics()
4028 .iter()
4029 .any(|line| line.contains(stopped_by))
4030 })
4031 .await;
4032 }
4033 manager.shutdown().await;
4034 }
4035
4036 fn memory_cap_supervision() -> super::SupervisionOptions {
4037 super::SupervisionOptions {
4038 // Linux cannot start either runtime under much less than 1 GiB of
4039 // RLIMIT_DATA (see `HOST_MEMORY_CAP`); on macOS 400 MiB keeps the
4040 // test fast for both the jetsam limit and the heartbeat check.
4041 memory_cap: if cfg!(target_os = "macos") {
4042 400 << 20
4043 } else {
4044 super::supervisor::HOST_MEMORY_CAP
4045 },
4046 // Production hang detection. With the fast 600 ms hang timeout, a host
4047 // stalled in GC near its cap was killed for a missed heartbeat and
4048 // restarted before the memory limit itself stopped it, so the test
4049 // never observed the enforcement it exists to prove.
4050 ping_timeout: Duration::from_secs(3),
4051 hang_timeout: super::supervisor::PING_DEADLINE,
4052 ..fast_supervision()
4053 }
4054 }
4055
4056 #[cfg(any(target_os = "linux", target_os = "macos", windows))]
4057 #[tokio::test]
4058 async fn memory_cap_stops_a_node_host() {
4059 let Some(node) = node_for_tests("memory_cap_stops_a_node_host") else {
4060 return;
4061 };
4062 let _policy = TestPolicyGuard::extension_host(true);
4063 let fixture = FixturePlugins::new(&["memory-hog"]).await;
4064 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
4065 runtime: NODE,
4066 node_override: Some(node),
4067 bun_override: None,
4068 root: Some(fixture.root.clone()),
4069 supervision: memory_cap_supervision(),
4070 }));
4071 memory_hog_is_stopped(
4072 manager,
4073 &fixture,
4074 codewhale_dependencies::HostRuntimeKind::Node,
4075 )
4076 .await;
4077 }
4078
4079 #[cfg(any(target_os = "linux", target_os = "macos", windows))]
4080 #[tokio::test]
4081 async fn memory_cap_stops_a_bun_host() {
4082 let Some(bun) = bun_for_tests("memory_cap_stops_a_bun_host") else {
4083 return;
4084 };
4085 let _policy = TestPolicyGuard::extension_host(true);
4086 let fixture = FixturePlugins::new(&["memory-hog"]).await;
4087 let manager = bun_manager(&fixture, bun, memory_cap_supervision());
4088 memory_hog_is_stopped(
4089 manager,
4090 &fixture,
4091 codewhale_dependencies::HostRuntimeKind::Bun,
4092 )
4093 .await;
4094 }
4095
4096 /// Actual Rust containment/memory authority, using the same exact compiled
4097 /// image as the containment receipt rather than transferring system-Bun proof.
4098 #[cfg(any(target_os = "linux", target_os = "macos", windows))]
4099 #[tokio::test]
4100 async fn compiled_native_host_memory_cap_is_enforced() {
4101 let Some(binary) = compiled_image_for_tests() else {
4102 return;
4103 };
4104 let _policy = TestPolicyGuard::extension_host(true);
4105 let fixture = FixturePlugins::new(&["memory-hog"]).await;
4106 let manager = bun_manager(&fixture, binary, memory_cap_supervision());
4107 memory_hog_is_stopped(
4108 manager,
4109 &fixture,
4110 codewhale_dependencies::HostRuntimeKind::Bun,
4111 )
4112 .await;
4113 eprintln!(
4114 "compiled-native-memory=passed platform={} arch={}",
4115 std::env::consts::OS,
4116 std::env::consts::ARCH
4117 );
4118 }
4119
4120 // ---------------------------------------------------------------------------
4121 // Extension commands
4122 // ---------------------------------------------------------------------------
4123
4124 fn register_command(
4125 registry: &mut OwnerRegistry,
4126 owner: &OwnerRef,
4127 name: &str,
4128 hint: Option<&str>,
4129 ) -> Result<u64, String> {
4130 registry.register(&RegisterParams {
4131 scope: None,
4132 owner: owner.clone(),
4133 kind: RegisterKind::Command,
4134 spec: RegisterSpecWire {
4135 name: name.to_string(),
4136 description: "d".to_string(),
4137 input_schema: None,
4138 argument_hint: hint.map(str::to_string),
4139 },
4140 })
4141 }
4142
4143 #[test]
4144 fn command_registry_refuses_shadowing_and_undoes_exactly_one_entry() {
4145 let _catalog = stub_builtin_commands();
4146 let mut registry = OwnerRegistry::new();
4147 let a = registry
4148 .begin_owner(
4149 HostCohort::reviewed(),
4150 "a",
4151 "a",
4152 Some(fake_authority("a")),
4153 "hash-a",
4154 )
4155 .unwrap();
4156 let b = registry
4157 .begin_owner(
4158 HostCohort::reviewed(),
4159 "b",
4160 "b",
4161 Some(fake_authority("b")),
4162 "hash-b",
4163 )
4164 .unwrap();
4165
4166 // Built-in spellings remain protected while plugins receive distinct names.
4167 for name in ["help", "trust", "model", "jihua", "stub-alias"] {
4168 let handle = register_command(&mut registry, &a, name, None).unwrap();
4169 let _ = registry.mark_active(&a);
4170 let registered = registry.live_command(handle, "a", a.generation).unwrap();
4171 assert_eq!(registered.name, format!("plugin-a-{name}"));
4172 assert_eq!(registered.declared_name, name);
4173 registry.unregister(&a, handle);
4174 }
4175 let mut long_registry = OwnerRegistry::new();
4176 let long_name = "name".repeat(40);
4177 let long_owner = long_registry
4178 .begin_owner(
4179 HostCohort::reviewed(),
4180 "long-id",
4181 &long_name,
4182 Some(fake_authority("long-id")),
4183 "hash-long",
4184 )
4185 .unwrap();
4186 let long_help = register_command(&mut long_registry, &long_owner, "help", None).unwrap();
4187 let long_model = register_command(&mut long_registry, &long_owner, "model", None).unwrap();
4188 let _ = long_registry.mark_active(&long_owner);
4189 let help_name = long_registry
4190 .live_command(long_help, "long-id", long_owner.generation)
4191 .unwrap()
4192 .name;
4193 let model_name = long_registry
4194 .live_command(long_model, "long-id", long_owner.generation)
4195 .unwrap()
4196 .name;
4197 assert!(help_name.len() <= 64 && model_name.len() <= 64);
4198 assert_ne!(help_name, model_name);
4199 let aliased = register_command(&mut registry, &a, "help", None).unwrap();
4200 let clash = register_command(&mut registry, &a, "plugin-a-help", None).unwrap_err();
4201 assert!(clash.contains("namespaced alias"), "{clash}");
4202 assert!(registry.live_command(aliased, "a", a.generation).is_some());
4203 registry.unregister(&a, aliased);
4204 let explicit = register_command(&mut registry, &a, "plugin-a-help", None).unwrap();
4205 let clash = register_command(&mut registry, &a, "help", None).unwrap_err();
4206 assert!(clash.contains("namespaced alias"), "{clash}");
4207 registry.unregister(&a, explicit);
4208 // Names outside DSH's grammar (upper case, a leading digit or slash,
4209 // spaces), and over-long ones.
4210 for name in [
4211 "Hello",
4212 "9lives",
4213 "/slash",
4214 "two words",
4215 "",
4216 &"x".repeat(65),
4217 ] {
4218 let refused = register_command(&mut registry, &a, name, None)
4219 .expect_err(&format!("{name:?} must be refused"));
4220 assert!(refused.contains("invalid"), "{name:?}: {refused}");
4221 }
4222 // A command has no input schema; descriptions and hints are bounded,
4223 // non-empty, single-line text.
4224 let mut params = RegisterParams {
4225 scope: None,
4226 owner: a.clone(),
4227 kind: RegisterKind::Command,
4228 spec: RegisterSpecWire {
4229 name: "ok-name".to_string(),
4230 description: "fine".to_string(),
4231 input_schema: json!({"type": "object"}).as_object().cloned(),
4232 argument_hint: None,
4233 },
4234 };
4235 assert!(
4236 registry
4237 .register(&params)
4238 .unwrap_err()
4239 .contains("input schema")
4240 );
4241 params.spec.input_schema = None;
4242 for (description, hint, expect) in [
4243 (" ", None, "needs a description"),
4244 ("two\nlines", None, "control characters"),
4245 ("fine", Some(""), "must not be empty"),
4246 ("fine", Some("\u{1b}[31m<x>"), "control characters"),
4247 ] {
4248 params.spec.description = description.to_string();
4249 params.spec.argument_hint = hint.map(str::to_string);
4250 let refused = registry.register(&params).unwrap_err();
4251 assert!(
4252 refused.contains(expect),
4253 "{description:?}/{hint:?}: {refused}"
4254 );
4255 }
4256 params.spec.description = "x".repeat(super::registry::MAX_COMMAND_DESCRIPTION_BYTES + 1);
4257 params.spec.argument_hint = None;
4258 assert!(
4259 registry
4260 .register(&params)
4261 .unwrap_err()
4262 .contains("description")
4263 );
4264 params.spec.description = "fine".to_string();
4265 params.spec.argument_hint = Some("h".repeat(super::registry::MAX_COMMAND_HINT_BYTES + 1));
4266 assert!(
4267 registry
4268 .register(&params)
4269 .unwrap_err()
4270 .contains("argument hint")
4271 );
4272
4273 let first = register_command(&mut registry, &a, "shared-name", Some("<x>")).unwrap();
4274 // Another plugin cannot take it.
4275 let refused = register_command(&mut registry, &b, "shared-name", None).unwrap_err();
4276 assert!(
4277 refused.contains("already registered by plugin"),
4278 "{refused}"
4279 );
4280 // Commands and tools are separate namespaces: the model calls one, the
4281 // user the other.
4282 register(&mut registry, &b, "shared_name_tool").unwrap();
4283 register(&mut registry, &a, "shared-name").unwrap();
4284 // The same owner re-registering retires the old handle.
4285 let second = register_command(&mut registry, &a, "shared-name", None).unwrap();
4286 assert_ne!(first, second);
4287 registry.mark_active(&a);
4288 registry.unregister(&a, first); // stale: must not remove the newer entry
4289 let live = registry.live_commands();
4290 assert_eq!(live.len(), 1);
4291 assert_eq!(live[0].handle, second);
4292 assert!(registry.live_command(second, "a", a.generation).is_some());
4293 // A foreign owner cannot unregister it, and a stale generation finds nothing.
4294 registry.unregister(&b, second);
4295 assert!(registry.live_command(second, "a", a.generation).is_some());
4296 assert!(
4297 registry
4298 .live_command(second, "a", a.generation + 1)
4299 .is_none()
4300 );
4301 assert!(registry.live_command(second, "b", a.generation).is_none());
4302 // Unregistering a command leaves the same owner's tool alone.
4303 registry.unregister(&a, second);
4304 assert!(registry.live_commands().is_empty());
4305 let tools = registry.live_tools();
4306 assert_eq!(tools.len(), 1, "b is not active yet; a's tool stays");
4307 assert_eq!(tools[0].name, "shared-name");
4308
4309 // Caps.
4310 for index in 0..super::registry::MAX_COMMANDS_PER_OWNER {
4311 register_command(&mut registry, &a, &format!("c{index}"), None).unwrap();
4312 }
4313 assert!(
4314 register_command(&mut registry, &a, "one-too-many", None)
4315 .unwrap_err()
4316 .contains("at most")
4317 );
4318
4319 // Revocation is synchronous and total, and a revoked owner cannot register.
4320 registry.mark_active(&a);
4321 assert_eq!(
4322 registry.live_commands().len(),
4323 super::registry::MAX_COMMANDS_PER_OWNER
4324 );
4325 assert_eq!(registry.revoke_owner("a"), Some(a.clone()));
4326 assert!(registry.live_commands().is_empty());
4327 assert!(register_command(&mut registry, &a, "after-revoke", None).is_err());
4328
4329 // A host crash drops every command, whoever owned it.
4330 registry.mark_active(&b);
4331 let handle = register_command(&mut registry, &b, "survivor", None).unwrap();
4332 assert!(registry.live_command(handle, "b", b.generation).is_some());
4333 registry.host_exited(HostCohort::reviewed(), "exited");
4334 assert!(registry.live_commands().is_empty());
4335 assert!(registry.live_command(handle, "b", b.generation).is_none());
4336 }
4337
4338 /// The host protocol gains `command/run` without gaining any core
4339 /// authority: the lint that guards `METHODS` runs in `protocol::tests`; this
4340 /// pins what the new method's request and its answer look like.
4341 #[test]
4342 fn command_run_and_its_answers_have_the_documented_shapes() {
4343 let request = protocol::CoreRequest::CommandRun(protocol::CommandRunParams {
4344 handle: 7,
4345 command_id: "c".to_string(),
4346 raw_input: "args".to_string(),
4347 deadline_ms: 30_000,
4348 workspace: None,
4349 session_id: None,
4350 agent_id: None,
4351 origin_turn_id: None,
4352 });
4353 assert_eq!(request.method(), "command/run");
4354 assert_eq!(request.deadline(), Duration::from_secs(30));
4355 for (value, expect) in [
4356 (
4357 json!({"kind": "success", "text": "t"}),
4358 protocol::CommandResultWire::Success {
4359 text: Some("t".into()),
4360 },
4361 ),
4362 (
4363 json!({"kind": "success"}),
4364 protocol::CommandResultWire::Success { text: None },
4365 ),
4366 (
4367 json!({"kind": "error", "text": "no"}),
4368 protocol::CommandResultWire::Error { text: "no".into() },
4369 ),
4370 (
4371 json!({"kind": "submit", "prompt": "p"}),
4372 protocol::CommandResultWire::Submit {
4373 prompt: "p".into(),
4374 text: None,
4375 },
4376 ),
4377 ] {
4378 let parsed: protocol::CommandResultWire = serde_json::from_value(value.clone()).unwrap();
4379 assert_eq!(parsed, expect);
4380 assert_eq!(serde_json::to_value(&parsed).unwrap(), value);
4381 }
4382 assert!(
4383 serde_json::from_value::<protocol::CommandResultWire>(json!({"kind": "approve"})).is_err()
4384 );
4385 }
4386
4387 /// What a command shows is plugin-controlled text: escape sequences are
4388 /// stripped, and a prompt too large to submit whole is refused, not cut.
4389 #[tokio::test]
4390 async fn command_output_is_stripped_bounded_and_oversized_prompts_are_refused() {
4391 use super::command::{self, CommandOutcome};
4392 // The wire-to-outcome mapping needs a host to answer, so run it against
4393 // a stub that returns canned results for `command/run`.
4394 let Some(node) = node_for_tests("command_output") else {
4395 return;
4396 };
4397 let dir = tempfile::tempdir().unwrap();
4398 let plugin = dir.path().join("canned");
4399 std::fs::create_dir_all(&plugin).unwrap();
4400 std::fs::write(
4401 plugin.join("plugin.json"),
4402 r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"canned","version":"0.1.0","description":"canned results","license":"MIT","extensions":{"net.codewhale":{"native":{"path":"index.mjs"}}}}"#,
4403 )
4404 .unwrap();
4405 std::fs::write(
4406 plugin.join("index.mjs"),
4407 format!(
4408 r#"export const name = 'canned'
4409 export const inject = ['commands']
4410 export function apply(ctx) {{
4411 ctx.commands.register({{ name: 'big-text', description: 'd', handler: () => 'x'.repeat({}) }})
4412 ctx.commands.register({{ name: 'big-prompt', description: 'd', handler: () => ({{ kind: 'submit', prompt: 'p'.repeat({}) }}) }})
4413 ctx.commands.register({{ name: 'blank-prompt', description: 'd', handler: () => ({{ kind: 'submit', prompt: ' \u001b[0m ' }}) }})
4414 ctx.commands.register({{ name: 'bad-result', description: 'd', handler: () => ({{ kind: 'approve' }}) }})
4415 }}
4416 "#,
4417 command::MAX_TEXT_BYTES * 2,
4418 command::MAX_PROMPT_BYTES + 1
4419 ),
4420 )
4421 .unwrap();
4422 let _policy = TestPolicyGuard::extension_host(true);
4423 let fixture = FixturePlugins::new(&[]).await;
4424 codewhale_plugins::install::install(
4425 codewhale_plugins::install::PluginInstallSource::LocalPath(plugin),
4426 &fixture.config.user_plugins_dir,
4427 codewhale_plugins::install::DEFAULT_MAX_SIZE_BYTES,
4428 &codewhale_net::network_policy::NetworkPolicy::default(),
4429 false,
4430 &|_| None,
4431 )
4432 .await
4433 .unwrap();
4434 let mut plugins = discover_with_config(&fixture.config);
4435 plugins.trust("canned").unwrap();
4436 plugins.enable("canned").unwrap();
4437 let manager = fixture.manager(node);
4438 let engine = manager.attach(Arc::new(plugins));
4439 engine.sync().await.unwrap();
4440 let run = |name: &'static str| {
4441 let manager = Arc::clone(&manager);
4442 let plugins = engine.plugin_view();
4443 async move {
4444 let entry = manager
4445 .commands_for_plugins(plugins.as_ref())
4446 .into_iter()
4447 .find(|entry| entry.registration.name == name)
4448 .unwrap_or_else(|| panic!("{name} is not live"));
4449 command::run(&manager.shared, &entry.reference(), "", None).await
4450 }
4451 };
4452 match run("big-text").await.unwrap() {
4453 CommandOutcome::Show { text } => {
4454 assert!(
4455 text.ends_with("(output truncated)"),
4456 "{}",
4457 &text[text.len() - 40..]
4458 );
4459 assert!(text.len() < command::MAX_TEXT_BYTES + 64);
4460 }
4461 other => panic!("{other:?}"),
4462 }
4463 assert!(
4464 run("big-prompt")
4465 .await
4466 .unwrap_err()
4467 .contains("not submitted")
4468 );
4469 assert!(
4470 run("blank-prompt")
4471 .await
4472 .unwrap_err()
4473 .contains("empty prompt")
4474 );
4475 assert!(
4476 run("bad-result")
4477 .await
4478 .unwrap_err()
4479 .contains("unknown result kind")
4480 );
4481 manager.shutdown().await;
4482 }
4483
4484 /// With no built-in command catalog installed, a command cannot be checked
4485 /// against the built-in names, so its registration is refused (never accepted
4486 /// unchecked); tools are not affected. With one, the catalog decides.
4487 #[test]
4488 fn a_command_registration_is_refused_when_no_built_in_catalog_is_installed() {
4489 let owner = |registry: &mut OwnerRegistry| {
4490 registry
4491 .begin_owner(
4492 HostCohort::reviewed(),
4493 "a",
4494 "a",
4495 Some(fake_authority("a")),
4496 "hash-a",
4497 )
4498 .unwrap()
4499 };
4500 let _absent = CatalogGuard::absent();
4501 let mut registry = OwnerRegistry::new();
4502 let a = owner(&mut registry);
4503 let refused = register_command(&mut registry, &a, "fine-name", None).unwrap_err();
4504 assert!(
4505 refused.contains("no built-in command catalog is installed"),
4506 "{refused}"
4507 );
4508 assert!(registry.live_commands().is_empty());
4509 // A name the grammar refuses is refused for its own reason first.
4510 assert!(
4511 register_command(&mut registry, &a, "Not Valid", None)
4512 .unwrap_err()
4513 .contains("invalid")
4514 );
4515 // Tools do not consult the command table.
4516 register(&mut registry, &a, "a_tool").unwrap();
4517
4518 let _stub = stub_builtin_commands();
4519 register_command(&mut registry, &a, "fine-name", None).unwrap();
4520 let handle = register_command(&mut registry, &a, "help", None).unwrap();
4521 let _ = registry.mark_active(&a);
4522 assert_eq!(
4523 registry
4524 .live_command(handle, "a", a.generation)
4525 .unwrap()
4526 .name,
4527 "plugin-a-help"
4528 );
4529 }
4530
4531 /// A command from a host that is down says so immediately instead of
4532 /// hanging, and a revoked registration cannot be run.
4533 #[tokio::test]
4534 async fn a_command_from_a_dead_host_reports_host_down() {
4535 let _catalog = stub_builtin_commands();
4536 let policy = TestPolicyGuard::extension_host(true);
4537 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions::default()));
4538 let reference = {
4539 let mut registry = manager.shared.registry.lock().unwrap();
4540 let owner = registry
4541 .begin_owner(
4542 HostCohort::reviewed(),
4543 "probe",
4544 "probe",
4545 Some(fake_authority("probe")),
4546 "hash",
4547 )
4548 .unwrap();
4549 registry.mark_active(&owner);
4550 let handle = register_command(&mut registry, &owner, "probe-cmd", None).unwrap();
4551 super::command::ExtensionCommandRef {
4552 selection: None,
4553 scope: None,
4554 content_hash: String::new(),
4555 handle,
4556 plugin_id: "probe".into(),
4557 generation: owner.generation,
4558 origin: "extension:probe".into(),
4559 workspace: PathBuf::from("/w"),
4560 }
4561 };
4562 let refused = "start failed: no runtime";
4563 for (slot, why) in [
4564 (
4565 super::HostSlot::Restarting {
4566 reason: "exited with signal: 9 (SIGKILL)".into(),
4567 },
4568 "restarting after: exited with signal: 9 (SIGKILL)".to_string(),
4569 ),
4570 (
4571 super::HostSlot::Failed {
4572 reason: refused.into(),
4573 stderr_tail: String::new(),
4574 },
4575 format!("{refused} (change or reload a plugin to retry)"),
4576 ),
4577 (super::HostSlot::Idle, "not started".to_string()),
4578 ] {
4579 *manager.shared.plugin.host.lock().unwrap() = slot;
4580 let started = Instant::now();
4581 let error = super::command::run(&manager.shared, &reference, "", None)
4582 .await
4583 .unwrap_err();
4584 assert!(
4585 error.starts_with(&format!("plugin host is down: {why}")),
4586 "{error}"
4587 );
4588 assert!(started.elapsed() < Duration::from_secs(1));
4589 }
4590 drop(policy);
4591 let _off = TestPolicyGuard::extension_host(false);
4592 let error = super::command::run(&manager.shared, &reference, "", None)
4593 .await
4594 .unwrap_err();
4595 assert_eq!(
4596 error,
4597 "plugin host is down: disabled by config ([features] extension_host is off)"
4598 );
4599 assert!(super::live_commands_for(Path::new("/w")).is_empty());
4600 }
4601
4602 /// The call is bounded by `command_run_deadline` and cancelled in the host,
4603 /// which stays usable; an in-flight command fails with "host down" when the
4604 /// host is killed, and after the restart only a fresh reference works.
4605 #[tokio::test]
4606 async fn a_slow_command_is_cancelled_and_a_killed_host_fails_it_as_down() {
4607 let Some(node) = node_for_tests("slow_command") else {
4608 return;
4609 };
4610 let _policy = TestPolicyGuard::extension_host(true);
4611 let fixture = FixturePlugins::new(&["ext-commands"]).await;
4612 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
4613 runtime: NODE,
4614 node_override: Some(node.clone()),
4615 bun_override: None,
4616 root: Some(fixture.root.clone()),
4617 supervision: super::SupervisionOptions {
4618 command_run_deadline: Duration::from_millis(300),
4619 ..fast_supervision()
4620 },
4621 }));
4622 let engine = manager.attach(fixture.registry());
4623 engine.sync().await.unwrap();
4624 let reference = |manager: &ExtensionHostManager, engine: &HostAttachment, name: &str| {
4625 manager
4626 .commands_for_plugins(engine.plugin_view().as_ref())
4627 .into_iter()
4628 .find(|entry| entry.registration.name == name)
4629 .unwrap_or_else(|| panic!("{name} is not live"))
4630 .reference()
4631 };
4632 let pid = manager.host_pid();
4633 let slow = reference(&manager, &engine, "ext-slow");
4634 let started = Instant::now();
4635 let error = tokio::time::timeout(
4636 Duration::from_secs(5),
4637 super::command::run(&manager.shared, &slow, "30000", None),
4638 )
4639 .await
4640 .expect("the deadline bounds the command")
4641 .unwrap_err();
4642 assert!(error.contains("timed out"), "{error}");
4643 assert!(started.elapsed() < Duration::from_secs(2));
4644 // The same host takes the next command.
4645 let echo = reference(&manager, &engine, "ext-echo");
4646 assert_eq!(
4647 super::command::run(&manager.shared, &echo, "again", None).await,
4648 Ok(super::command::CommandOutcome::Show {
4649 text: "echo: again".to_string()
4650 })
4651 );
4652 assert_eq!(manager.host_pid(), pid);
4653 manager.shutdown().await;
4654
4655 // Kill the host under a running command with a longer deadline.
4656 let manager = supervised_manager(&fixture, node);
4657 let engine = manager.attach(fixture.registry());
4658 engine.sync().await.unwrap();
4659 let pid = manager.host_pid();
4660 let slow = reference(&manager, &engine, "ext-slow");
4661 let echo = reference(&manager, &engine, "ext-echo");
4662 let manager2 = Arc::clone(&manager);
4663 let running = {
4664 let slow = slow.clone();
4665 tokio::spawn(
4666 async move { super::command::run(&manager2.shared, &slow, "30000", None).await },
4667 )
4668 };
4669 tokio::time::sleep(Duration::from_millis(100)).await;
4670 #[cfg(unix)]
4671 let status = std::process::Command::new("kill")
4672 .args(["-9", &pid.unwrap().to_string()])
4673 .status()
4674 .unwrap();
4675 #[cfg(windows)]
4676 let status = std::process::Command::new("taskkill")
4677 .args(["/F", "/PID", &pid.unwrap().to_string()])
4678 .status()
4679 .unwrap();
4680 assert!(status.success());
4681 let error = tokio::time::timeout(Duration::from_secs(2), running)
4682 .await
4683 .expect("the call resolves")
4684 .unwrap()
4685 .unwrap_err();
4686 assert!(error.starts_with("plugin host is down: exited:"), "{error}");
4687 // The supervisor restarts the host and replays the plugin under a new
4688 // generation: the old reference is stale, a fresh one works.
4689 wait_host(&manager, || {
4690 manager.spawn_attempts() == 2 && manager.live_command_names().contains(&"ext-echo".into())
4691 })
4692 .await;
4693 let error = super::command::run(&manager.shared, &echo, "old", None)
4694 .await
4695 .unwrap_err();
4696 assert!(error.contains("no longer registered"), "{error}");
4697 let fresh = reference(&manager, &engine, "ext-echo");
4698 assert_ne!(fresh.generation, echo.generation);
4699 assert_eq!(
4700 super::command::run(&manager.shared, &fresh, "new", None).await,
4701 Ok(super::command::CommandOutcome::Show {
4702 text: "echo: new".to_string()
4703 })
4704 );
4705 manager.shutdown().await;
4706 }
4707
4708 // ---------------------------------------------------------------------------
4709 // Trust tiers: a plugin host and a built-in (tier 0) host, never one process
4710 // ---------------------------------------------------------------------------
4711
4712 use super::tier::{BuiltinModule, Tier0Tool};
4713 use sha2::{Digest, Sha256};
4714
4715 fn tier_register_params(owner: &OwnerRef, name: &str) -> RegisterParams {
4716 RegisterParams {
4717 scope: None,
4718 owner: owner.clone(),
4719 kind: RegisterKind::Tool,
4720 spec: RegisterSpecWire {
4721 name: name.to_string(),
4722 description: "d".to_string(),
4723 input_schema: json!({"type": "object", "properties": {}})
4724 .as_object()
4725 .cloned(),
4726 argument_hint: None,
4727 },
4728 }
4729 }
4730
4731 #[test]
4732 fn owners_are_bound_to_their_tier() {
4733 let mut registry = OwnerRegistry::new();
4734 let plugin_id = "user/0123456789ab/demo";
4735
4736 // A `host:` id on the plugin tier, and any other id on the builtin tier.
4737 let refused = registry
4738 .begin_owner(
4739 HostCohort::reviewed(),
4740 "host:mcp",
4741 "mcp",
4742 Some(fake_authority("host:mcp")),
4743 "h",
4744 )
4745 .unwrap_err();
4746 assert!(
4747 refused.contains("a plugin id can never use it"),
4748 "{refused}"
4749 );
4750 let refused = registry
4751 .begin_owner(HostCohort::Builtin, plugin_id, "demo", None, "h")
4752 .unwrap_err();
4753 assert!(
4754 refused.contains("not a built-in host module id"),
4755 "{refused}"
4756 );
4757 let refused = registry
4758 .begin_owner(HostCohort::Builtin, "demo", "demo", None, "h")
4759 .unwrap_err();
4760 assert!(
4761 refused.contains("not a built-in host module id"),
4762 "{refused}"
4763 );
4764 // The authority must fit the tier too.
4765 assert!(
4766 registry
4767 .begin_owner(HostCohort::reviewed(), plugin_id, "demo", None, "h")
4768 .unwrap_err()
4769 .contains("needs its reviewed plugin authority")
4770 );
4771 assert!(
4772 registry
4773 .begin_owner(
4774 HostCohort::Builtin,
4775 "host:mcp",
4776 "mcp",
4777 Some(fake_authority("host:mcp")),
4778 "h"
4779 )
4780 .unwrap_err()
4781 .contains("has no plugin authority")
4782 );
4783 assert!(
4784 registry.owners().next().is_none(),
4785 "a refused owner leaves nothing behind"
4786 );
4787
4788 let plugin = registry
4789 .begin_owner(
4790 HostCohort::reviewed(),
4791 plugin_id,
4792 "demo",
4793 Some(fake_authority(plugin_id)),
4794 "hash-demo",
4795 )
4796 .unwrap();
4797 let other_plugin = registry
4798 .begin_owner(
4799 HostCohort::reviewed(),
4800 "user/0123456789ab/other",
4801 "other",
4802 Some(fake_authority("user/0123456789ab/other")),
4803 "hash-other",
4804 )
4805 .unwrap();
4806 let builtin = registry
4807 .begin_owner(HostCohort::Builtin, "host:mcp", "mcp", None, "digest-mcp")
4808 .unwrap();
4809 for owner in [&plugin, &other_plugin, &builtin] {
4810 registry.mark_active(owner);
4811 }
4812 assert_eq!(
4813 registry.owner("host:mcp").unwrap().tier(),
4814 HostTier::Builtin
4815 );
4816 assert_eq!(registry.owner(plugin_id).unwrap().tier(), HostTier::Plugin);
4817 assert_eq!(registry.tier_of(&builtin), Some(HostTier::Builtin));
4818 assert!(registry.authority_for(&builtin).is_none());
4819 assert!(registry.authority_for(&plugin).is_some());
4820 // Plugins share a process with each other; a built-in module does not
4821 // share one with any plugin.
4822 assert_eq!(registry.other_active_owners(plugin_id), 1);
4823 assert_eq!(registry.other_active_owners("host:mcp"), 0);
4824
4825 let plugin_tool = register(&mut registry, &plugin, "zz_plugin_probe").unwrap();
4826 let builtin_tool = register(&mut registry, &builtin, "zz_builtin_probe").unwrap();
4827 let tiers: Vec<_> = registry
4828 .live_tools()
4829 .into_iter()
4830 .map(|tool| {
4831 let tier = tool.tier();
4832 (tool.name, tier)
4833 })
4834 .collect();
4835 assert_eq!(
4836 tiers,
4837 [
4838 ("zz_plugin_probe".to_string(), HostTier::Plugin),
4839 ("zz_builtin_probe".to_string(), HostTier::Builtin)
4840 ]
4841 );
4842 assert!(registry.is_live(plugin_tool, &plugin));
4843 assert!(registry.is_live(builtin_tool, &builtin));
4844
4845 // Each tier's host is its own process: a crash of one takes only its own
4846 // owners and registrations with it.
4847 registry.host_exited(HostCohort::reviewed(), "plugin host crashed");
4848 assert!(registry.owner(plugin_id).is_none());
4849 assert_eq!(
4850 registry.owner("host:mcp").unwrap().state,
4851 OwnerState::Active
4852 );
4853 assert!(registry.is_live(builtin_tool, &builtin));
4854 assert!(!registry.is_live(plugin_tool, &plugin));
4855 // ... and a shutdown of the builtin tier leaves the plugin tier's alone.
4856 let replay = registry
4857 .begin_owner(
4858 HostCohort::reviewed(),
4859 plugin_id,
4860 "demo",
4861 Some(fake_authority(plugin_id)),
4862 "hash-demo",
4863 )
4864 .unwrap();
4865 registry.mark_active(&replay);
4866 let again = register(&mut registry, &replay, "zz_plugin_probe").unwrap();
4867 registry.revoke_all(HostCohort::Builtin, "builtin host shut down");
4868 assert!(registry.is_live(again, &replay));
4869 assert!(matches!(
4870 registry.owner("host:mcp").unwrap().state,
4871 OwnerState::Failed(_)
4872 ));
4873 assert_eq!(registry.live_tools().len(), 1);
4874 }
4875
4876 /// A host answers for its own tier's owners only, even if it somehow named
4877 /// the other tier's: the registration, and the log line, are dropped.
4878 #[test]
4879 fn a_host_registers_and_logs_only_for_owners_of_its_own_tier() {
4880 use super::supervisor::HostEvents;
4881 let manager = ExtensionHostManager::new(ExtensionHostOptions::default());
4882 let (plugin, builtin) = {
4883 let mut registry = manager.shared.registry.lock().unwrap();
4884 let plugin = registry
4885 .begin_owner(
4886 HostCohort::reviewed(),
4887 "user/0123456789ab/demo",
4888 "demo",
4889 Some(fake_authority("user/0123456789ab/demo")),
4890 "hash",
4891 )
4892 .unwrap();
4893 let builtin = registry
4894 .begin_owner(HostCohort::Builtin, "host:mcp", "mcp", None, "digest")
4895 .unwrap();
4896 registry.mark_active(&plugin);
4897 registry.mark_active(&builtin);
4898 (plugin, builtin)
4899 };
4900 let events = |cohort| super::Events {
4901 shared: Arc::downgrade(&manager.shared),
4902 cohort,
4903 generation: 0,
4904 };
4905 let refused =
4906 events(HostCohort::reviewed()).register(&tier_register_params(&builtin, "zz_probe"));
4907 assert!(
4908 matches!(&refused, protocol::RegisterResult::Refused { refused }
4909 if refused.contains("belongs to")),
4910 "{refused:?}"
4911 );
4912 let refused = events(HostCohort::Builtin).register(&tier_register_params(&plugin, "zz_probe"));
4913 assert!(
4914 matches!(&refused, protocol::RegisterResult::Refused { refused }
4915 if refused.contains("belongs to")),
4916 "{refused:?}"
4917 );
4918 assert!(manager.live_tool_names().is_empty());
4919 assert!(matches!(
4920 events(HostCohort::Builtin).register(&tier_register_params(&builtin, "zz_probe")),
4921 protocol::RegisterResult::Admitted { .. }
4922 ));
4923 assert!(matches!(
4924 events(HostCohort::reviewed()).register(&tier_register_params(&plugin, "zz_other")),
4925 protocol::RegisterResult::Admitted { .. }
4926 ));
4927
4928 let warn = |plugin_id: &str| protocol::LogParams {
4929 level: "warn".into(),
4930 msg: "m".into(),
4931 plugin_id: Some(plugin_id.into()),
4932 };
4933 events(HostCohort::reviewed()).log(&warn("host:mcp"));
4934 events(HostCohort::Builtin).log(&warn("user/0123456789ab/demo"));
4935 assert!(
4936 manager
4937 .owner_report("host:mcp")
4938 .unwrap()
4939 .diagnostics
4940 .is_empty()
4941 );
4942 assert!(
4943 manager
4944 .owner_report("user/0123456789ab/demo")
4945 .unwrap()
4946 .diagnostics
4947 .is_empty()
4948 );
4949 events(HostCohort::Builtin).log(&warn("host:mcp"));
4950 assert_eq!(
4951 manager.owner_report("host:mcp").unwrap().diagnostics,
4952 ["warn: m"]
4953 );
4954 }
4955
4956 /// A manifest name cannot carry a `host:` prefix (names are lower-case ASCII
4957 /// letters, digits and internal `-`/`.`), so discovery never builds a `host:`
4958 /// id, and the plugin that tries fails validation instead of reaching the
4959 /// host.
4960 #[test]
4961 fn a_plugin_named_like_a_tier_zero_owner_fails_validation_and_never_reaches_the_host() {
4962 let _policy = TestPolicyGuard::extension_host(true);
4963 let temp = tempfile::tempdir().unwrap();
4964 let user = temp.path().join("user");
4965 native_bundle(&user, "evil", "index.mjs", &["index.mjs"]);
4966 native_bundle(&user, "fine", "index.mjs", &["index.mjs"]);
4967 // The directory is harmless; the manifest's name is the claim.
4968 let manifest = user.join("evil/plugin.json");
4969 let rewritten = std::fs::read_to_string(&manifest)
4970 .unwrap()
4971 .replace("\"name\": \"evil\"", "\"name\": \"host:evil\"");
4972 assert!(rewritten.contains("host:evil"));
4973 std::fs::write(&manifest, rewritten).unwrap();
4974 let config = DiscoveryConfig {
4975 workspace: temp.path().join("project"),
4976 user_plugins_dir: user,
4977 workspace_plugins_dir: temp.path().join("project/.codewhale/plugins"),
4978 builtin_plugin_dirs: Vec::new(),
4979 state_path: temp.path().join("state/plugin-state.json"),
4980 };
4981 let registry = discover_with_config(&config);
4982 assert!(
4983 registry.get("host:evil").is_none(),
4984 "a plugin named `host:evil` must not be discovered as a plugin"
4985 );
4986 assert!(
4987 registry
4988 .diagnostics()
4989 .iter()
4990 .any(|diagnostic| diagnostic.message.contains("host:evil")
4991 && diagnostic.message.contains("name")),
4992 "{:?}",
4993 registry.diagnostics()
4994 );
4995 assert!(registry.get("fine").is_some());
4996 // Whatever discovery yields, no desired owner is a tier-0 id.
4997 let (desired, _) = super::desired_owners(&registry);
4998 assert!(
4999 desired
5000 .keys()
5001 .all(|id| HostTier::Plugin.check_owner_id(id).is_ok())
5002 );
5003 }
5004
5005 #[test]
5006 fn launch_plans_carry_their_tier_and_use_a_data_directory_each() {
5007 #[cfg(not(windows))]
5008 use codewhale_dependencies::{HostRuntime, HostRuntimeKind};
5009 let home = tempfile::tempdir().unwrap();
5010 #[cfg(windows)]
5011 let bundle = super::materialize_bundle(home.path()).unwrap();
5012 #[cfg(not(windows))]
5013 let bundle = home.path().join("codewhale-extension-host.mjs");
5014 // Windows admission verifies the real copied runtime and exact bundle.
5015 #[cfg(windows)]
5016 let runtime = codewhale_dependencies::resolve_extension_host_runtime(
5017 NODE,
5018 None,
5019 None,
5020 crate::extension_host::bundle_sha256(),
5021 )
5022 .selected
5023 .expect("tier planning requires the test Node runtime on Windows");
5024 #[cfg(not(windows))]
5025 let runtime = HostRuntime {
5026 compiled: false,
5027 kind: HostRuntimeKind::Node,
5028 path: PathBuf::from("/opt/runtime/bin/node"),
5029 version: (22, 19, 0),
5030 native_code_flags: Vec::new(),
5031 };
5032 let mut dirs = Vec::new();
5033 for tier in HostTier::ALL {
5034 let cohort = match tier {
5035 HostTier::Builtin => HostCohort::Builtin,
5036 HostTier::Plugin => HostCohort::reviewed(),
5037 };
5038 let launch = match super::supervisor::plan_launch(
5039 &cohort,
5040 &runtime,
5041 &bundle,
5042 home.path(),
5043 1 << 30,
5044 &[],
5045 ) {
5046 Ok(launch) => launch,
5047 Err(error) if tier == HostTier::Plugin => {
5048 assert!(
5049 error.contains("Native plugins require a verified OS sandbox"),
5050 "{error}"
5051 );
5052 assert!(matches!(
5053 super::supervisor::planned_sandbox_tier(tier, &runtime, home.path()),
5054 Err(reason) if reason.contains("would create")
5055 ));
5056 let data = super::supervisor::tier_data_dir(home.path(), tier);
5057 assert!(data.is_dir());
5058 assert!(super::supervisor::tier_data_dir(home.path(), HostTier::Builtin).is_dir());
5059 dirs.push(data);
5060 continue;
5061 }
5062 Err(error) => panic!("pinned Builtin plan failed: {error}"),
5063 };
5064 assert_eq!(launch.tier, tier);
5065 // The runtime's own argv ends `<bundle> --tier=<tier>`, wrapped by the
5066 // OS sandbox or not.
5067 let at = launch
5068 .args
5069 .iter()
5070 .position(|arg| Path::new(arg) == bundle)
5071 .expect("bundle in argv");
5072 assert_eq!(launch.args[at + 1], format!("--tier={}", tier.name()));
5073 assert_eq!(launch.args.len(), at + 2, "the tier is the last argument");
5074 assert_eq!(
5075 launch.cwd,
5076 super::supervisor::tier_data_dir(home.path(), tier)
5077 );
5078 assert!(launch.cwd.is_dir(), "{}", launch.cwd.display());
5079 dirs.push(launch.cwd);
5080 }
5081 assert_ne!(dirs[0], dirs[1], "each tier has its own data directory");
5082 assert_eq!(HostTier::Plugin.argv_flag(), "--tier=plugin");
5083 assert_eq!(HostTier::Builtin.argv_flag(), "--tier=builtin");
5084 }
5085
5086 /// A built-in module table that pins `source`, for a test. Production has
5087 /// none: `BUILTIN_MODULES` is empty.
5088 fn test_builtin_table(source: &Path) -> &'static [BuiltinModule] {
5089 let digest = super::hex(Sha256::digest(std::fs::read(source).unwrap()));
5090 let tools: &'static [Tier0Tool] = Box::leak(Box::new([Tier0Tool {
5091 name: "zz_tier0_listed",
5092 approval: ApprovalRequirement::Auto,
5093 }]));
5094 Box::leak(Box::new([BuiltinModule {
5095 id: "tier0-module",
5096 source_sha256: Box::leak(digest.into_boxed_str()),
5097 tools,
5098 services: &[],
5099 }]))
5100 }
5101
5102 /// Put `bytes` where the core looks for built-in module `id`'s source under
5103 /// the home `root`.
5104 fn place_builtin_source(root: &Path, id: &str, bytes: &[u8]) {
5105 let path = super::supervisor::bundle_dir(root, super::bundle_sha256())
5106 .join("builtin")
5107 .join(format!("{id}.mjs"));
5108 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
5109 std::fs::write(path, bytes).unwrap();
5110 }
5111
5112 /// The production table pins MCP, but ordinary plugin attachment never
5113 /// starts that independent builtin backend until the Engine selects it.
5114 #[tokio::test]
5115 async fn plugin_attachment_never_spawns_the_independent_builtin_mcp_backend() {
5116 let manager = ExtensionHostManager::new(ExtensionHostOptions::default());
5117 assert_eq!(
5118 manager.shared.builtin_modules.len(),
5119 super::tier::BUILTIN_MODULES.len()
5120 );
5121 assert!(
5122 manager
5123 .shared
5124 .builtin_modules
5125 .iter()
5126 .any(|module| module.id == "mcp")
5127 );
5128 let Some(node) =
5129 node_for_tests("plugin_attachment_never_spawns_the_independent_builtin_mcp_backend")
5130 else {
5131 return;
5132 };
5133 let _policy = TestPolicyGuard::extension_host(true);
5134 let fixture = FixturePlugins::new(&["dsh-workspace-deps"]).await;
5135 let manager = fixture.manager(node);
5136 let engine = manager.attach(fixture.registry());
5137 engine.sync().await.unwrap();
5138 assert!(matches!(manager.status(), HostStatus::Ready { .. }));
5139 assert_eq!(manager.tier_spawn_attempts(HostTier::Plugin), 1);
5140 assert_eq!(manager.tier_spawn_attempts(HostTier::Builtin), 0);
5141 assert_eq!(manager.tier_status(HostTier::Builtin), HostStatus::Idle);
5142 // Planning creates an empty sibling so the Native sandbox can mask it,
5143 // including on Linux where bubblewrap requires the denied root to exist.
5144 // That directory is not evidence of a Builtin process or backend.
5145 let builtin_data = super::supervisor::tier_data_dir(&fixture.root, HostTier::Builtin);
5146 assert!(builtin_data.is_dir());
5147 assert_eq!(std::fs::read_dir(builtin_data).unwrap().count(), 0);
5148 let report = super::render_status(&manager);
5149 assert!(!report.contains("built-in host"), "{report}");
5150 manager.shutdown().await;
5151 }
5152
5153 /// A module whose source is not the digest the table pins, or is missing, is
5154 /// refused with the reason, and no host is started for it.
5155 #[tokio::test]
5156 async fn a_built_in_module_that_is_not_the_pinned_source_is_refused_and_starts_nothing() {
5157 let _policy = TestPolicyGuard::extension_host(true);
5158 let source = fixtures_dir().join("tier0-module/module.mjs");
5159 let modules = test_builtin_table(&source);
5160 for (case, bytes, expected) in [
5161 (
5162 "tampered",
5163 Some(&b"export const name = 'tier0-module'\nexport function apply() {}\n"[..]),
5164 "the core pins",
5165 ),
5166 ("missing", None, "cannot read the source"),
5167 ] {
5168 let temp = tempfile::tempdir().unwrap();
5169 let root = temp.path().join("home");
5170 if let Some(bytes) = bytes {
5171 place_builtin_source(&root, "tier0-module", bytes);
5172 }
5173 let manager = Arc::new(ExtensionHostManager::with_builtin_modules(
5174 ExtensionHostOptions {
5175 root: Some(root),
5176 ..Default::default()
5177 },
5178 modules,
5179 ));
5180 let engine = manager.attach(Arc::new(PluginRegistry::empty(temp.path())));
5181 engine.sync().await.unwrap();
5182 assert_eq!(manager.spawn_attempts(), 0, "{case}");
5183 assert_eq!(manager.tier_status(HostTier::Builtin), HostStatus::Idle);
5184 let Some(OwnerState::Failed(reason)) = manager.owner_state("host:tier0-module") else {
5185 panic!("{case}: {:?}", manager.owner_state("host:tier0-module"));
5186 };
5187 assert!(reason.contains(expected), "{case}: {reason}");
5188 assert!(manager.live_tool_names().is_empty());
5189 // Not retried every turn.
5190 engine.sync().await.unwrap();
5191 assert_eq!(
5192 manager.diagnostics().len(),
5193 1,
5194 "{:?}",
5195 manager.diagnostics()
5196 );
5197 }
5198 }
5199
5200 /// The two tiers are two processes under one manager: a built-in module
5201 /// activates under `host:<module>` in its own host, its tool's approval is
5202 /// whatever the table says (and `Required` where it says nothing), plugin
5203 /// tools stay `Required`, and crashing the plugin host disturbs nothing of
5204 /// the builtin one.
5205 #[tokio::test]
5206 async fn a_tier_zero_host_runs_apart_from_the_plugin_host_and_its_tool_approval_follows_the_table()
5207 {
5208 let Some(node) = node_for_tests("a_tier_zero_host_runs_apart") else {
5209 return;
5210 };
5211 let _policy = TestPolicyGuard::extension_host(true);
5212 let fixture = FixturePlugins::new(&["dsh-workspace-deps"]).await;
5213 let source = fixtures_dir().join("tier0-module/module.mjs");
5214 place_builtin_source(
5215 &fixture.root,
5216 "tier0-module",
5217 &std::fs::read(&source).unwrap(),
5218 );
5219 let manager = Arc::new(ExtensionHostManager::with_builtin_modules(
5220 ExtensionHostOptions {
5221 runtime: NODE,
5222 node_override: Some(node),
5223 root: Some(fixture.root.clone()),
5224 ..Default::default()
5225 },
5226 test_builtin_table(&source),
5227 ));
5228 assert_eq!(manager.tier_status(HostTier::Builtin), HostStatus::Idle);
5229 let engine = manager.attach(fixture.registry());
5230 engine.sync().await.unwrap();
5231
5232 // Two hosts, two processes, each launched once.
5233 let plugin_pid = manager.host_pid().expect("plugin host running");
5234 let builtin_pid = manager
5235 .shared
5236 .ready_host(&HostCohort::Builtin)
5237 .expect("builtin host running")
5238 .pid
5239 .expect("builtin pid");
5240 assert_ne!(plugin_pid, builtin_pid);
5241 assert_eq!(manager.tier_spawn_attempts(HostTier::Plugin), 1);
5242 assert_eq!(manager.tier_spawn_attempts(HostTier::Builtin), 1);
5243 let plugin_host_id = plugin_id(&fixture, "dsh-workspace-deps");
5244 assert_eq!(
5245 manager.owner_state("host:tier0-module"),
5246 Some(OwnerState::Active)
5247 );
5248 assert_eq!(
5249 manager.owner_state(&plugin_host_id),
5250 Some(OwnerState::Active)
5251 );
5252 {
5253 let registry = manager.shared.registry.lock().unwrap();
5254 assert_eq!(
5255 registry.owner("host:tier0-module").unwrap().tier(),
5256 HostTier::Builtin
5257 );
5258 assert_eq!(
5259 registry.owner(&plugin_host_id).unwrap().tier(),
5260 HostTier::Plugin
5261 );
5262 assert_eq!(
5263 registry.owner("host:tier0-module").unwrap().content_hash,
5264 test_builtin_table(&source)[0].source_sha256
5265 );
5266 }
5267 // The module's data directory is under the builtin tier's, apart from
5268 // every plugin's.
5269 assert!(
5270 super::supervisor::owner_data_dir(
5271 &fixture.root,
5272 HostCohort::Builtin,
5273 "host:tier0-module",
5274 "tier0-module"
5275 )
5276 .is_dir()
5277 );
5278
5279 // An engine installs plugin tools only; tier-0 tools are not offered to
5280 // the model by a plugin snapshot.
5281 let installed = installed(&engine, fixture.workspace());
5282 assert_eq!(installed, ["load_workspace_dependencies"]);
5283
5284 // Approval follows the table for tier 0, and stays Required for plugins.
5285 let registrations = manager.shared.registry.lock().unwrap().live_tools();
5286 let spec_for = |name: &str| {
5287 let registration = registrations
5288 .iter()
5289 .find(|tool| tool.name == name)
5290 .unwrap_or_else(|| panic!("{name} not registered"))
5291 .clone();
5292 super::tool::HostToolSpec::new(registration, Arc::clone(&manager.shared))
5293 };
5294 let listed = spec_for("zz_tier0_listed");
5295 let unlisted = spec_for("zz_tier0_unlisted");
5296 let plugin_tool = spec_for("load_workspace_dependencies");
5297 assert_eq!(listed.registration_origin(), "host:tier0-module");
5298 assert_eq!(listed.approval_requirement(), ApprovalRequirement::Auto);
5299 assert_eq!(
5300 listed.approval_requirement_for(&json!({})),
5301 ApprovalRequirement::Auto
5302 );
5303 assert_eq!(
5304 unlisted.approval_requirement(),
5305 ApprovalRequirement::Required
5306 );
5307 assert_eq!(
5308 plugin_tool.approval_requirement(),
5309 ApprovalRequirement::Required
5310 );
5311 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
5312 assert_eq!(
5313 listed.prepare(json!({}), &context).unwrap().approval,
5314 ApprovalRequirement::Auto
5315 );
5316 assert_eq!(
5317 unlisted.prepare(json!({}), &context).unwrap().approval,
5318 ApprovalRequirement::Required
5319 );
5320 // Even an Auto tool is host code: never read-only, never plan-mode safe.
5321 assert!(!listed.is_read_only_for(&json!({})));
5322
5323 // The call goes to the builtin host and comes back.
5324 let result = listed.execute(json!({}), &context).await.unwrap();
5325 assert!(result.success);
5326 assert_eq!(
5327 serde_json::from_str::<Value>(&result.content).unwrap(),
5328 json!({"tier": "zero", "listed": true})
5329 );
5330
5331 // Kill the plugin host: its owners go and come back, the builtin host and
5332 // its module are untouched, and its crash budget is not spent.
5333 #[cfg(unix)]
5334 let status = std::process::Command::new("kill")
5335 .args(["-9", &plugin_pid.to_string()])
5336 .status()
5337 .unwrap();
5338 #[cfg(windows)]
5339 let status = std::process::Command::new("taskkill")
5340 .args(["/F", "/PID", &plugin_pid.to_string()])
5341 .status()
5342 .unwrap();
5343 assert!(status.success());
5344 wait_host(&manager, || {
5345 manager.tier_spawn_attempts(HostTier::Plugin) == 2
5346 && manager
5347 .live_tool_names()
5348 .contains(&"load_workspace_dependencies".to_string())
5349 })
5350 .await;
5351 assert_eq!(
5352 manager.shared.ready_host(&HostCohort::Builtin).unwrap().pid,
5353 Some(builtin_pid)
5354 );
5355 assert_eq!(manager.tier_spawn_attempts(HostTier::Builtin), 1);
5356 assert_eq!(
5357 manager.owner_state("host:tier0-module"),
5358 Some(OwnerState::Active)
5359 );
5360 assert!(
5361 manager
5362 .shared
5363 .builtin
5364 .supervision
5365 .lock()
5366 .unwrap()
5367 .crashes
5368 .is_empty()
5369 );
5370 assert_eq!(
5371 manager
5372 .shared
5373 .plugin
5374 .supervision
5375 .lock()
5376 .unwrap()
5377 .crashes
5378 .len(),
5379 1
5380 );
5381 assert!(listed.execute(json!({}), &context).await.unwrap().success);
5382
5383 // The status page shows the builtin host and keeps its tools off the
5384 // plugin list.
5385 let report = super::render_status(&manager);
5386 assert!(
5387 report.contains("built-in host (tier 0): running"),
5388 "{report}"
5389 );
5390 assert!(!report.contains("tool zz_tier0_listed"), "{report}");
5391 assert!(!report.contains("command /"), "{report}");
5392 manager.shutdown().await;
5393 }
5394
5395 /// The existing installer, registry projection and final spec invocation use
5396 /// one attachment receipt. Two entry scopes under one owner never union into
5397 /// either caller, and withdrawing one does not cancel its sibling.
5398 #[tokio::test(flavor = "current_thread")]
5399 async fn native_preset_membership_filters_discovery_and_final_tool_invocation() {
5400 let Some(node) = node_for_tests("native_preset_membership") else {
5401 return;
5402 };
5403 let _policy = TestPolicyGuard::extension_host(true);
5404 let _catalog = stub_builtin_commands();
5405 let fixture = FixturePlugins::new(&["two-entries"]).await;
5406 let manager = fixture.manager(node);
5407 let _manager = super::TestManagerGuard::install(Arc::clone(&manager));
5408 let initial = manager.attach(fixture.registry());
5409 initial.sync().await.unwrap();
5410 let presets = super::native_presets_for_plugins(initial.plugin_view().as_ref());
5411 let first = presets
5412 .iter()
5413 .find(|(preset, _)| preset.entry.path.ends_with("tools.mjs"))
5414 .unwrap()
5415 .0
5416 .clone();
5417 let second = presets
5418 .iter()
5419 .find(|(preset, _)| preset.entry.path.ends_with("commands.mjs"))
5420 .unwrap()
5421 .0
5422 .clone();
5423 let a = manager.attach(Arc::new(
5424 fixture.registry().with_native_preset(first).unwrap(),
5425 ));
5426 let b = manager.attach(Arc::new(
5427 fixture.registry().with_native_preset(second).unwrap(),
5428 ));
5429 drop(initial);
5430 a.sync().await.unwrap();
5431 assert_eq!(installed(&a, fixture.workspace()), ["two_first"]);
5432 assert_eq!(installed(&b, fixture.workspace()), ["two_second"]);
5433 assert!(
5434 manager
5435 .commands_for_plugins(a.plugin_view().as_ref())
5436 .is_empty()
5437 );
5438 assert_eq!(
5439 manager.commands_for_plugins(b.plugin_view().as_ref())[0]
5440 .registration
5441 .name,
5442 "two-hello"
5443 );
5444 let old = host_tool(&a, fixture.workspace(), "two_first");
5445 let a_context = ToolContext::new(fixture.workspace()).with_plugin_registry(a.plugin_view());
5446 let b_context = ToolContext::new(fixture.workspace()).with_plugin_registry(b.plugin_view());
5447 assert!(
5448 old.prepare(json!({}), &b_context).is_err(),
5449 "a retained spec cannot execute under another caller"
5450 );
5451 assert_eq!(
5452 old.execute(json!({}), &a_context).await.unwrap().content,
5453 "first"
5454 );
5455 a.set_plugins(Arc::new(PluginRegistry::empty(fixture.workspace())));
5456 assert!(
5457 old.prepare(json!({}), &a_context).is_err(),
5458 "withdrawal rejects a retained approval/spec receipt before reconciliation"
5459 );
5460 a.sync().await.unwrap();
5461 assert_eq!(
5462 host_tool(&b, fixture.workspace(), "two_second")
5463 .execute(json!({}), &b_context)
5464 .await
5465 .unwrap()
5466 .content,
5467 "second"
5468 );
5469 // Rediscovery must preserve a now-invalid narrowed selector. A disabled
5470 // build never turns a selected caller into a broad default caller.
5471 manager.refresh_workspace(&fixture.disable("two-entries"));
5472 assert!(!b.plugin_view().selected_native_entries().is_empty());
5473 b.sync().await.unwrap();
5474 assert!(installed(&b, fixture.workspace()).is_empty());
5475 manager.shutdown().await;
5476 }
5477
5478 /// A real installed raw roster: initial default and two child snapshots share
5479 /// one owner but all five discovery paths and final invocation use one receipt.
5480 #[tokio::test(flavor = "current_thread")]
5481 async fn raw_agent_presets_use_one_default_and_all_five_caller_views() {
5482 let Some(node) = node_for_tests("raw_agent_presets_use_one_default_and_all_five_caller_views")
5483 else {
5484 return;
5485 };
5486 let _policy = TestPolicyGuard::extension_host(true);
5487 let _catalog = stub_builtin_commands();
5488 let fixture = FixturePlugins::new(&["raw-agent-presets"]).await;
5489 let original = fixture.registry();
5490 assert_eq!(original.selected_native_entries().len(), 1);
5491 assert!(
5492 Path::new(&original.selected_native_entries()[0].entry.path).file_name()
5493 == Some(std::ffi::OsStr::new("a.mjs"))
5494 );
5495 let manager = fixture.manager(node);
5496 let _manager = super::TestManagerGuard::install(Arc::clone(&manager));
5497 let a = manager.attach(Arc::clone(&original));
5498 a.sync().await.unwrap();
5499 let roster = super::native_presets_for_plugins(a.plugin_view().as_ref());
5500 assert_eq!(
5501 roster.len(),
5502 2,
5503 "roster discovery offers admitted alternatives without activating a union"
5504 );
5505 assert_eq!(a.prompt_sections().await.unwrap()[0].text, "A:a");
5506 let selected_b = roster
5507 .iter()
5508 .find(|(preset, _)| {
5509 Path::new(&preset.entry.path).file_name() == Some(std::ffi::OsStr::new("b.mjs"))
5510 })
5511 .unwrap()
5512 .0
5513 .clone();
5514 let b = manager.attach(Arc::new(original.with_native_preset(selected_b).unwrap()));
5515 b.sync().await.unwrap();
5516 let check = |view: &HostAttachment, expected: &str| {
5517 assert_eq!(installed(view, fixture.workspace()), ["preset_echo"]);
5518 let commands = manager.commands_for_plugins(view.plugin_view().as_ref());
5519 assert_eq!(commands.len(), 1);
5520 assert_eq!(commands[0].registration.name, "preset-echo");
5521 let roots = super::skills::roots_for_plugins(view.plugin_view().as_ref());
5522 assert_eq!(roots.len(), 1);
5523 assert!(roots[0].0.path.ends_with(expected));
5524 assert_eq!(roots[0].0.snapshots[0].name, "preset-note");
5525 };
5526 check(&a, "a");
5527 check(&b, "b");
5528 assert_eq!(a.prompt_sections().await.unwrap()[0].text, "A:a");
5529 assert_eq!(b.prompt_sections().await.unwrap()[0].text, "B:b");
5530 let hook_payload = protocol::HookCallPayload {
5531 name: "read".into(),
5532 call_id: "raw-preset-hook".into(),
5533 input: json!({}),
5534 mode: "Agent".into(),
5535 workspace: fixture.workspace().to_string_lossy().into_owned(),
5536 model: "fixture".into(),
5537 };
5538 let hooks_a = a.tool_before_hooks(hook_payload.clone()).await;
5539 let hooks_b = b.tool_before_hooks(hook_payload).await;
5540 assert_eq!(hooks_a.len(), 1);
5541 assert_eq!(hooks_b.len(), 1);
5542 assert_eq!(
5543 serde_json::from_str::<Value>(&hooks_a[0].stdout).unwrap()["additionalContext"],
5544 "A:a"
5545 );
5546 assert_eq!(
5547 serde_json::from_str::<Value>(&hooks_b[0].stdout).unwrap()["additionalContext"],
5548 "B:b"
5549 );
5550 let a_context = ToolContext::new(fixture.workspace()).with_plugin_registry(a.plugin_view());
5551 let b_context = ToolContext::new(fixture.workspace()).with_plugin_registry(b.plugin_view());
5552 let retained = host_tool(&a, fixture.workspace(), "preset_echo");
5553 assert!(retained.prepare(json!({}), &b_context).is_err());
5554 assert_eq!(
5555 retained
5556 .execute(json!({}), &a_context)
5557 .await
5558 .unwrap()
5559 .content,
5560 "A:a"
5561 );
5562 let command = manager.commands_for_plugins(a.plugin_view().as_ref())[0].reference();
5563 assert!(
5564 super::run_command_for_plugins(&command, "", None, b.plugin_view().as_ref())
5565 .await
5566 .is_err()
5567 );
5568 assert_eq!(
5569 super::run_command_for_plugins(&command, "", None, a.plugin_view().as_ref())
5570 .await
5571 .unwrap(),
5572 super::command::CommandOutcome::Show { text: "A:a".into() }
5573 );
5574 a.set_plugins(Arc::new(PluginRegistry::empty(fixture.workspace())));
5575 assert!(retained.prepare(json!({}), &a_context).is_err());
5576 a.sync().await.unwrap();
5577 assert!(a.prompt_sections().await.unwrap().is_empty());
5578 assert_eq!(
5579 host_tool(&b, fixture.workspace(), "preset_echo")
5580 .execute(json!({}), &b_context)
5581 .await
5582 .unwrap()
5583 .content,
5584 "B:b"
5585 );
5586 let disabled = fixture.disable("raw-agent-presets");
5587 manager.refresh_workspace(&disabled);
5588 assert!(!b.plugin_view().selected_native_entries().is_empty());
5589 b.sync().await.unwrap();
5590 assert!(installed(&b, fixture.workspace()).is_empty());
5591 assert!(b.prompt_sections().await.unwrap().is_empty());
5592 assert!(super::skills::roots_for_plugins(b.plugin_view().as_ref()).is_empty());
5593 assert!(
5594 manager
5595 .commands_for_plugins(b.plugin_view().as_ref())
5596 .is_empty()
5597 );
5598 assert!(
5599 b.tool_before_hooks(protocol::HookCallPayload {
5600 name: "read".into(),
5601 call_id: "withdrawn".into(),
5602 input: json!({}),
5603 mode: "Agent".into(),
5604 workspace: fixture.workspace().to_string_lossy().into_owned(),
5605 model: "fixture".into()
5606 })
5607 .await
5608 .is_empty()
5609 );
5610 manager.shutdown().await;
5611 }
5612
5613 /// No default is an upstream fact. Catalog discovery must neither start the
5614 /// host nor grant any contribution until the exact child receipt is selected.
5615 #[tokio::test(flavor = "current_thread")]
5616 async fn raw_agent_presets_without_default_require_explicit_child_selection() {
5617 let Some(node) =
5618 node_for_tests("raw_agent_presets_without_default_require_explicit_child_selection")
5619 else {
5620 return;
5621 };
5622 let _policy = TestPolicyGuard::extension_host(true);
5623 let _catalog = stub_builtin_commands();
5624 let fixture = FixturePlugins::new(&["raw-agent-presets-no-default"]).await;
5625 let original = fixture.registry();
5626 assert!(original.selected_native_entries().is_empty());
5627 let manager = fixture.manager(node);
5628 let _manager = super::TestManagerGuard::install(Arc::clone(&manager));
5629 let roster = super::native_presets_for_plugins(original.as_ref());
5630 assert_eq!(
5631 roster.len(),
5632 2,
5633 "healthy admitted catalog is available before a host exists"
5634 );
5635 let idle = manager.attach(Arc::clone(&original));
5636 idle.sync().await.unwrap();
5637 assert!(installed(&idle, fixture.workspace()).is_empty());
5638 assert!(idle.prompt_sections().await.unwrap().is_empty());
5639 assert!(
5640 manager
5641 .commands_for_plugins(idle.plugin_view().as_ref())
5642 .is_empty()
5643 );
5644 assert!(super::skills::roots_for_plugins(idle.plugin_view().as_ref()).is_empty());
5645 assert!(
5646 idle.tool_before_hooks(protocol::HookCallPayload {
5647 name: "read".into(),
5648 call_id: "unselected".into(),
5649 input: json!({}),
5650 mode: "Agent".into(),
5651 workspace: fixture.workspace().to_string_lossy().into_owned(),
5652 model: "fixture".into()
5653 })
5654 .await
5655 .is_empty()
5656 );
5657 let selected = roster
5658 .iter()
5659 .find(|(preset, _)| {
5660 Path::new(&preset.entry.path).file_name() == Some(std::ffi::OsStr::new("b.mjs"))
5661 })
5662 .unwrap()
5663 .0
5664 .clone();
5665 let child = manager.attach(Arc::new(original.with_native_preset(selected).unwrap()));
5666 child.sync().await.unwrap();
5667 assert_eq!(installed(&child, fixture.workspace()), ["preset_echo"]);
5668 assert_eq!(child.prompt_sections().await.unwrap()[0].text, "B:b");
5669 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(child.plugin_view());
5670 assert_eq!(
5671 host_tool(&child, fixture.workspace(), "preset_echo")
5672 .execute(json!({}), &context)
5673 .await
5674 .unwrap()
5675 .content,
5676 "B:b"
5677 );
5678 manager.refresh_workspace(&original);
5679 idle.sync().await.unwrap();
5680 assert!(idle.plugin_view().selected_native_entries().is_empty());
5681 assert!(
5682 installed(&idle, fixture.workspace()).is_empty(),
5683 "another caller's selected owner cannot broaden the catalog-only caller"
5684 );
5685 assert!(idle.prompt_sections().await.unwrap().is_empty());
5686 assert_eq!(
5687 super::native_presets_for_plugins(idle.plugin_view().as_ref()).len(),
5688 2
5689 );
5690 manager.shutdown().await;
5691 }
5692
5693 /// The real configured-hook consumers redeem the pinned Builtin across every
5694 /// existing firepoint, and a changed project receipt cannot fall back.
5695 #[cfg(unix)]
5696 #[tokio::test(flavor = "current_thread")]
5697 async fn all_fifteen_project_hook_events_use_the_pinned_runner_and_reject_changed_receipts() {
5698 let _env = crate::test_support::lock_test_env();
5699 let _policy = TestPolicyGuard::extension_host(true);
5700 let Some(node) = node_for_tests("all_fifteen_project_hook_events") else {
5701 return;
5702 };
5703 let home = tempfile::tempdir().unwrap();
5704 let workspace = home.path().join("workspace");
5705 std::fs::create_dir_all(workspace.join(".codewhale")).unwrap();
5706 let workspace = workspace.canonicalize().unwrap();
5707 let _config = crate::test_support::EnvVarGuard::set(
5708 "CODEWHALE_CONFIG_PATH",
5709 home.path().join("config.toml"),
5710 );
5711 let mut config = codewhale_config::hooks::HooksConfig {
5712 enabled: true,
5713 ..codewhale_config::hooks::HooksConfig::default()
5714 };
5715 for event in codewhale_config::hooks::ALL_HOOK_EVENTS {
5716 config.hooks.push(codewhale_config::hooks::Hook::new(
5717 event,
5718 &format!(
5719 "printf '%s|%s|%s' '{}' \"$DEEPSEEK_SESSION_ID\" \"$DEEPSEEK_TOOL_CALL_ID\"",
5720 event.as_str()
5721 ),
5722 ));
5723 }
5724 let hook_path = workspace.join(".codewhale/hooks.toml");
5725 std::fs::write(&hook_path, toml::to_string(&config).unwrap()).unwrap();
5726 codewhale_runtime::config::save_workspace_trust(&workspace).unwrap();
5727 let (reviewed, _) = crate::hooks::authority::review_project_hooks(&workspace).unwrap();
5728 crate::hooks::authority::approve_project_hooks(&workspace, &reviewed.digest).unwrap();
5729 let admitted = crate::hooks::config::load_with_project(
5730 codewhale_config::hooks::HooksConfig {
5731 enabled: true,
5732 ..codewhale_config::hooks::HooksConfig::default()
5733 },
5734 &workspace,
5735 );
5736 assert_eq!(admitted.hooks.len(), 16);
5737 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
5738 node_override: Some(node),
5739 root: Some(home.path().join("host")),
5740 ..ExtensionHostOptions::default()
5741 }));
5742 manager.bind_engine_handle(tokio::runtime::Handle::current());
5743 let _manager = super::TestManagerGuard::install(Arc::clone(&manager));
5744 let executor = crate::hooks::HookExecutor::new(admitted, workspace.clone());
5745 let context = crate::hooks::HookContext::new()
5746 .with_session_id("actual-session")
5747 .with_tool_call_id("actual-call")
5748 .with_caller(crate::hooks::HookCaller {
5749 workspace,
5750 plugins: None,
5751 session_id: Some("actual-session".into()),
5752 agent_id: Some("actual-agent".into()),
5753 origin_turn_id: Some("actual-turn".into()),
5754 origin_call_id: Some("actual-call".into()),
5755 });
5756 let env_scope = crate::test_support::env_scope_ticket();
5757 tokio::task::spawn_blocking(move || {
5758 let _env = crate::test_support::join_env_scope(env_scope);
5759 let _policy = codewhale_plugins::activation::PolicyScope::propagate(true);
5760 for event in codewhale_config::hooks::ALL_HOOK_EVENTS {
5761 let results = executor.execute(event, &context);
5762 assert_eq!(results.len(), 1, "{event:?}");
5763 assert!(results[0].success, "{event:?}: {:?}", results[0]);
5764 assert_eq!(
5765 results[0].stdout,
5766 format!("{}|actual-session|actual-call", event.as_str()),
5767 "{event:?}"
5768 );
5769 }
5770 std::fs::write(hook_path, "# changed after admission\n").unwrap();
5771 let rejected = executor.execute(codewhale_config::hooks::HookEvent::SessionStart, &context);
5772 assert_eq!(rejected.len(), 1);
5773 assert!(!rejected[0].success);
5774 assert!(rejected[0].stdout.is_empty());
5775 assert!(rejected[0].exit_code.is_none());
5776 })
5777 .await
5778 .unwrap();
5779 assert!(matches!(
5780 manager.tier_status(HostTier::Builtin),
5781 HostStatus::Ready { .. }
5782 ));
5783 assert!(!matches!(manager.status(), HostStatus::Ready { .. }));
5784 manager.shutdown().await;
5785 }
5786
5787 #[tokio::test]
5788 async fn sync_creator_within_signals_cancellation_at_safe_point_on_timeout() {
5789 let temp = tempfile::tempdir().unwrap();
5790 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
5791 root: Some(temp.path().join("home")),
5792 ..Default::default()
5793 }));
5794 let attachment = manager.attach(Arc::new(PluginRegistry::empty(temp.path())));
5795 assert!(attachment.set_creator_demand(true));
5796
5797 let hold = manager.shared.sync_lock.lock().await;
5798 let settled = attachment
5799 .sync_creator_within(Duration::from_millis(20))
5800 .await;
5801 assert!(!settled);
5802 drop(hold);
5803
5804 tokio::time::sleep(Duration::from_millis(50)).await;
5805 assert_eq!(manager.tier_spawn_attempts(HostTier::Builtin), 0);
5806 assert_eq!(manager.owner_state("host:creator"), None);
5807 assert!(manager.shared.sync_lock.try_lock().is_ok());
5808 assert!(
5809 manager
5810 .diagnostics()
5811 .iter()
5812 .any(|line| line.contains("timed out") && line.contains("cancellation"))
5813 );
5814 }
5815
5816 #[test]
5817 fn materialize_file_atomically_replaces_read_only_bundle_without_leaking_temp_files() {
5818 let temp = tempfile::tempdir().unwrap();
5819 let dir = temp.path().join("bundle");
5820 let first = super::materialize_file(&dir, "asset.mjs", b"export const v = 1;\n").unwrap();
5821 assert_eq!(std::fs::read(&first).unwrap(), b"export const v = 1;\n");
5822 #[cfg(unix)]
5823 {
5824 use std::os::unix::fs::PermissionsExt;
5825 assert_eq!(
5826 std::fs::metadata(&first).unwrap().permissions().mode() & 0o777,
5827 0o400
5828 );
5829 }
5830 let replaced = super::materialize_file(&dir, "asset.mjs", b"export const v = 2;\n").unwrap();
5831 assert_eq!(replaced, first);
5832 assert_eq!(std::fs::read(&replaced).unwrap(), b"export const v = 2;\n");
5833 let entries: Vec<_> = std::fs::read_dir(&dir)
5834 .unwrap()
5835 .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
5836 .collect();
5837 assert_eq!(entries, vec!["asset.mjs".to_string()]);
5838 }
5839
5839 lines RUST