返回 CodeWhale
cohort_tests.rs
根目录 / crates / engine / src / extension_host / cohort_tests.rs
1 use std::path::{Path, PathBuf};
2 use std::sync::Arc;
3 use std::time::Duration;
4
5 use serde_json::json;
6
7 use super::protocol::DshService;
8 use super::registry::OwnerState;
9 use super::supervisor::HostSandbox;
10 use super::test_support::{
11 fake_authority, fixtures_dir, host_tool, node_for_tests, stub_builtin_commands,
12 };
13 use super::tier::{HostCohort, HostTier, PluginCohort};
14 use super::{ExtensionHostManager, ExtensionHostOptions, HostSlot};
15 use crate::command_catalog::CatalogGuard;
16 use crate::tools::spec::ToolContext;
17 use codewhale_config::OwnerRef;
18 use codewhale_config::extension_host::ExtensionHostRuntime;
19 use codewhale_plugins::PluginRegistry;
20 use codewhale_plugins::activation::TestPolicyGuard;
21 use codewhale_plugins::discovery::{DiscoveryConfig, discover_with_config};
22 use codewhale_plugins::host_services::{
23 AgentApproval, AgentPosture, PersonVia, PluginApprover, ReviewApproval,
24 };
25 use codewhale_plugins::install::{
26 DEFAULT_MAX_SIZE_BYTES, PluginInstallOutcome, PluginInstallSource, install,
27 };
28
29 const NODE: ExtensionHostRuntime = ExtensionHostRuntime::Node;
30
31 fn fast_supervision() -> super::SupervisionOptions {
32 super::SupervisionOptions {
33 heartbeat_interval: Duration::from_millis(50),
34 ping_timeout: Duration::from_secs(3),
35 hang_timeout: Duration::from_secs(8),
36 restart_backoff: Duration::from_millis(10),
37 crash_window: Duration::from_secs(10),
38 crash_limit: 3,
39 start_retry_cooldown: Duration::from_millis(10),
40 dirty_window: Duration::from_secs(10),
41 dirty_limit: 2,
42 memory_cap: super::supervisor::HOST_MEMORY_CAP,
43 tool_call_deadline: Duration::from_secs(20),
44 command_run_deadline: Duration::from_secs(3),
45 }
46 }
47
48 async fn wait_host(manager: &ExtensionHostManager, predicate: impl Fn() -> bool) {
49 tokio::time::timeout(Duration::from_secs(10), async {
50 while !predicate() {
51 tokio::time::sleep(Duration::from_millis(10)).await;
52 }
53 })
54 .await
55 .unwrap_or_else(|_| {
56 panic!("host wait timed out: status={:?}", manager.status());
57 });
58 }
59
60 fn cohort_pid(manager: &ExtensionHostManager, cohort: &HostCohort) -> Option<u32> {
61 let rt = manager.shared.cohort_runtime(cohort)?;
62 let slot = rt.host.lock().expect("host lock");
63 match &*slot {
64 HostSlot::Ready(host) => host.pid,
65 _ => None,
66 }
67 }
68
69 struct CohortTestFixture {
70 _temp: tempfile::TempDir,
71 workspace: PathBuf,
72 user: PathBuf,
73 home: PathBuf,
74 config: DiscoveryConfig,
75 _commands: CatalogGuard,
76 }
77
78 impl CohortTestFixture {
79 async fn new(names: &[&str]) -> Self {
80 let temp = tempfile::tempdir().unwrap();
81 let workspace = temp.path().join("project");
82 let user = temp.path().join("user");
83 let home = temp.path().join("home");
84 std::fs::create_dir_all(&workspace).unwrap();
85 std::fs::create_dir_all(&user).unwrap();
86 std::fs::create_dir_all(&home).unwrap();
87
88 for name in names {
89 let outcome = install(
90 PluginInstallSource::LocalPath(fixtures_dir().join(name)),
91 &user,
92 DEFAULT_MAX_SIZE_BYTES,
93 &codewhale_net::network_policy::NetworkPolicy::default(),
94 false,
95 &|_| None,
96 )
97 .await
98 .unwrap_or_else(|error| panic!("install {name}: {error:#}"));
99 assert!(
100 matches!(outcome, PluginInstallOutcome::Installed(ref installed) if installed.name == *name),
101 "install {name}: {outcome:?}"
102 );
103 }
104
105 let config = DiscoveryConfig {
106 workspace: workspace.clone(),
107 user_plugins_dir: user.clone(),
108 workspace_plugins_dir: workspace.join(".codewhale/plugins"),
109 builtin_plugin_dirs: Vec::new(),
110 state_path: temp.path().join("state/plugin-state.json"),
111 };
112
113 Self {
114 _temp: temp,
115 workspace,
116 user,
117 home,
118 config,
119 _commands: stub_builtin_commands(),
120 }
121 }
122
123 async fn subproject(&self, name: &str, names: &[&str]) -> Self {
124 let temp = tempfile::tempdir().unwrap();
125 let workspace = temp.path().join(name);
126 std::fs::create_dir_all(&workspace).unwrap();
127 for plugin in names {
128 let outcome = install(
129 PluginInstallSource::LocalPath(fixtures_dir().join(plugin)),
130 &self.user,
131 DEFAULT_MAX_SIZE_BYTES,
132 &codewhale_net::network_policy::NetworkPolicy::default(),
133 false,
134 &|_| None,
135 )
136 .await
137 .unwrap_or_else(|error| panic!("install {plugin}: {error:#}"));
138 assert!(
139 matches!(outcome, PluginInstallOutcome::Installed(ref installed) if installed.name == *plugin),
140 "install {plugin}: {outcome:?}"
141 );
142 }
143 let config = DiscoveryConfig {
144 workspace: workspace.clone(),
145 user_plugins_dir: self.user.clone(),
146 workspace_plugins_dir: workspace.join(".codewhale/plugins"),
147 builtin_plugin_dirs: Vec::new(),
148 state_path: self.config.state_path.clone(),
149 };
150 Self {
151 _temp: temp,
152 workspace,
153 user: self.user.clone(),
154 home: self.home.clone(),
155 config,
156 _commands: stub_builtin_commands(),
157 }
158 }
159
160 fn workspace(&self) -> &Path {
161 &self.workspace
162 }
163
164 fn registry(&self) -> Arc<PluginRegistry> {
165 Arc::new(discover_with_config(&self.config))
166 }
167
168 fn plugin_id(&self, name: &str) -> String {
169 self.registry().get(name).unwrap().id.as_str().to_string()
170 }
171
172 fn review_by_person(&self, name: &str) {
173 let mut registry = discover_with_config(&self.config);
174 let shown = registry.host_service_review(name).map(|r| r.token);
175 registry
176 .trust_reviewed(
177 name,
178 ReviewApproval {
179 approved_by: PluginApprover::person(PersonVia::Terminal),
180 host_services: shown,
181 },
182 )
183 .unwrap();
184 registry.enable(name).unwrap();
185 }
186
187 fn review_by_agent(&self, name: &str) {
188 let mut registry = discover_with_config(&self.config);
189 let approver = PluginApprover::Agent(AgentApproval {
190 posture: AgentPosture::FullAccess,
191 workspace: self.workspace.to_string_lossy().into_owned(),
192 thread_id: Some("thread".into()),
193 turn_id: Some("turn".into()),
194 tool_call_id: Some("call".into()),
195 });
196 let shown = registry
197 .host_service_review_for(name, &approver)
198 .map(|r| r.token);
199 registry
200 .trust_reviewed(
201 name,
202 ReviewApproval {
203 approved_by: approver.clone(),
204 host_services: shown,
205 },
206 )
207 .unwrap();
208 registry.enable_by(name, approver).unwrap();
209 }
210
211 fn review_by_marked_shell(&self, name: &str) {
212 let mut registry = discover_with_config(&self.config);
213 let approver = PluginApprover::command_line(Some(&self.workspace));
214 let shown = registry
215 .host_service_review_for(name, &approver)
216 .map(|r| r.token);
217 registry
218 .trust_reviewed(
219 name,
220 ReviewApproval {
221 approved_by: approver.clone(),
222 host_services: shown,
223 },
224 )
225 .unwrap();
226 registry.enable_by(name, approver).unwrap();
227 }
228
229 fn review_by_unmarked_shell(&self, name: &str) {
230 let mut registry = discover_with_config(&self.config);
231 let approver = PluginApprover::command_line(None);
232 registry
233 .trust_reviewed(
234 name,
235 ReviewApproval {
236 approved_by: approver.clone(),
237 host_services: None,
238 },
239 )
240 .unwrap();
241 registry.enable_by(name, approver).unwrap();
242 }
243
244 fn review_by_auto_review(&self, name: &str, workspace: &Path) {
245 let mut config = self.config.clone();
246 config.workspace = workspace.to_path_buf();
247 config.workspace_plugins_dir = workspace.join(".codewhale/plugins");
248 let mut registry = discover_with_config(&config);
249 let approver = PluginApprover::Agent(AgentApproval {
250 posture: AgentPosture::AutoReview,
251 workspace: workspace.to_string_lossy().into_owned(),
252 thread_id: Some("thread".into()),
253 turn_id: Some("turn".into()),
254 tool_call_id: Some("call".into()),
255 });
256 let shown = registry
257 .host_service_review_for(name, &approver)
258 .map(|r| r.token);
259 registry
260 .trust_reviewed(
261 name,
262 ReviewApproval {
263 approved_by: approver.clone(),
264 host_services: shown,
265 },
266 )
267 .unwrap();
268 registry.enable_by(name, approver).unwrap();
269 }
270
271 fn manager(&self, node: PathBuf) -> Arc<ExtensionHostManager> {
272 Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
273 runtime: NODE,
274 node_override: Some(node),
275 root: Some(self.home.clone()),
276 ..Default::default()
277 }))
278 }
279
280 fn manager_with_supervision(
281 &self,
282 node: PathBuf,
283 supervision: super::SupervisionOptions,
284 ) -> Arc<ExtensionHostManager> {
285 Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
286 runtime: NODE,
287 node_override: Some(node),
288 root: Some(self.home.clone()),
289 supervision,
290 ..Default::default()
291 }))
292 }
293 }
294
295 #[tokio::test]
296 async fn an_agent_approved_owner_never_loads_into_the_reviewed_host() {
297 let Some(node) = node_for_tests("an_agent_approved_owner_never_loads_into_the_reviewed_host")
298 else {
299 return;
300 };
301 let _policy = TestPolicyGuard::extension_host(true);
302 let fixture = CohortTestFixture::new(&["two-entries", "child-persona"]).await;
303
304 fixture.review_by_person("two-entries");
305 fixture.review_by_agent("child-persona");
306
307 let manager = fixture.manager(node);
308 let engine = manager.attach(fixture.registry());
309 engine.sync().await.unwrap();
310
311 let pid_reviewed =
312 cohort_pid(&manager, &HostCohort::reviewed()).expect("reviewed host must be running");
313 let cohort_agent = HostCohort::agent(fixture.workspace());
314 let pid_agent = cohort_pid(&manager, &cohort_agent).expect("agent host must be running");
315 assert_ne!(pid_reviewed, pid_agent);
316
317 {
318 let reg = manager.shared.registry.lock().unwrap();
319 let child_id = fixture.plugin_id("child-persona");
320 let entry = reg.owner(&child_id).expect("agent plugin must be present");
321 assert_eq!(entry.cohort, cohort_agent);
322 }
323
324 let tool = host_tool(&engine, fixture.workspace(), "two_first");
325 let result = tool
326 .execute(
327 json!({}),
328 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view()),
329 )
330 .await;
331 assert!(result.is_ok());
332 }
333
334 #[test]
335 fn a_ticket_minted_for_one_cohort_is_refused_by_another() {
336 use super::ticket::{Grant, Presented, Refusal, TicketKind, TicketTable};
337 let tickets = TicketTable::default();
338 let cohort1 = HostCohort::reviewed();
339 let cohort2 = HostCohort::agent("/workspace/test-proj");
340
341 let owner = OwnerRef {
342 plugin_id: "test-plugin".into(),
343 generation: 1,
344 owner_token: "tok".into(),
345 };
346
347 let target = json!({"path": "/some/path"});
348 let grant = Grant {
349 kind: TicketKind::Invocation,
350 cohort: cohort1.clone(),
351 host_generation: 1,
352 owner: owner.clone(),
353 method: "proc/read",
354 target: target.clone(),
355 ttl: Duration::from_secs(60),
356 uses: 1,
357 };
358 let ticket = tickets.mint(grant);
359
360 let presented_wrong_cohort = Presented {
361 ticket: ticket.expose(),
362 kind: TicketKind::Invocation,
363 cohort: cohort2.clone(),
364 host_generation: 1,
365 owner: &owner,
366 method: "proc/read",
367 target: Some(&target),
368 };
369
370 let result = tickets.redeem(&presented_wrong_cohort);
371 assert_eq!(result.unwrap_err().reason, Refusal::WrongCohort);
372
373 let presented_right_cohort = Presented {
374 ticket: ticket.expose(),
375 kind: TicketKind::Invocation,
376 cohort: cohort1,
377 host_generation: 1,
378 owner: &owner,
379 method: "proc/read",
380 target: Some(&target),
381 };
382 assert!(tickets.redeem(&presented_right_cohort).is_ok());
383 }
384
385 #[tokio::test]
386 async fn two_projects_agent_plugins_do_not_share_a_host() {
387 let Some(node) = node_for_tests("two_projects_agent_plugins_do_not_share_a_host") else {
388 return;
389 };
390 let _policy = TestPolicyGuard::extension_host(true);
391 let fixture1 = CohortTestFixture::new(&["two-entries", "child-persona"]).await;
392 let fixture2 = fixture1.subproject("project2", &["plugin-context"]).await;
393
394 fixture1.review_by_agent("two-entries");
395 fixture1.review_by_person("child-persona");
396 fixture2.review_by_agent("plugin-context");
397
398 let manager = fixture1.manager(node);
399 let engine1 = manager.attach(fixture1.registry());
400 let engine2 = manager.attach(fixture2.registry());
401
402 engine1.sync().await.unwrap();
403 engine2.sync().await.unwrap();
404
405 let cohort1 = HostCohort::agent(fixture1.workspace());
406 let cohort2 = HostCohort::agent(fixture2.workspace());
407 let cohort_reviewed = HostCohort::reviewed();
408
409 let pid1 = cohort_pid(&manager, &cohort1).expect("host for project 1 must be running");
410 let pid2 = cohort_pid(&manager, &cohort2).expect("host for project 2 must be running");
411 let pid_reviewed =
412 cohort_pid(&manager, &cohort_reviewed).expect("reviewed host must be running");
413 assert_ne!(pid1, pid2);
414 assert_ne!(pid1, pid_reviewed);
415 assert_ne!(pid2, pid_reviewed);
416
417 let tool1 = host_tool(&engine1, fixture1.workspace(), "two_first");
418 let outcome1 = tool1
419 .execute(
420 json!({}),
421 &ToolContext::new(fixture1.workspace()).with_plugin_registry(engine1.plugin_view()),
422 )
423 .await;
424 assert!(outcome1.is_ok());
425
426 let tool2 = host_tool(&engine2, fixture2.workspace(), "ctx_probe");
427 let outcome2 = tool2
428 .execute(
429 json!({}),
430 &ToolContext::new(fixture2.workspace()).with_plugin_registry(engine2.plugin_view()),
431 )
432 .await;
433 assert!(outcome2.is_ok());
434
435 let mut tools1 = crate::tools::ToolRegistry::new(ToolContext::new(fixture1.workspace()));
436 engine1.install_tools(&mut tools1);
437 assert!(tools1.get("two_first").is_some());
438 assert!(tools1.get("ctx_probe").is_none());
439
440 let mut tools2 = crate::tools::ToolRegistry::new(ToolContext::new(fixture2.workspace()));
441 engine2.install_tools(&mut tools2);
442 assert!(tools2.get("ctx_probe").is_some());
443 assert!(tools2.get("two_first").is_none());
444
445 let agent_cohorts = manager.shared.agent_cohorts.lock().unwrap();
446 assert_eq!(agent_cohorts.len(), 2);
447 }
448
449 #[tokio::test]
450 async fn a_person_review_moves_the_owner_and_its_data() {
451 let Some(node) = node_for_tests("a_person_review_moves_the_owner_and_its_data") else {
452 return;
453 };
454 let _policy = TestPolicyGuard::extension_host(true);
455 let fixture = CohortTestFixture::new(&["two-entries", "plugin-context", "crash-tool"]).await;
456 fixture.review_by_person("two-entries");
457 fixture.review_by_agent("plugin-context");
458 fixture.review_by_agent("crash-tool");
459
460 let manager = fixture.manager(node);
461 let engine = manager.attach(fixture.registry());
462 engine.sync().await.unwrap();
463
464 let pid_reviewed_before =
465 cohort_pid(&manager, &HostCohort::reviewed()).expect("reviewed host pre-started");
466 let agent_cohort = HostCohort::agent(fixture.workspace());
467 let pid_agent_before = cohort_pid(&manager, &agent_cohort).expect("agent host must be running");
468 assert_ne!(pid_reviewed_before, pid_agent_before);
469
470 let context = ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
471 let note_tool = host_tool(&engine, fixture.workspace(), "ctx_note");
472 let write_res = note_tool
473 .execute(json!({"text": "written by agent cohort"}), &context)
474 .await
475 .unwrap();
476 assert!(write_res.success);
477 let payload: serde_json::Value = serde_json::from_str(&write_res.content).unwrap();
478 assert_eq!(payload["text"], "written by agent cohort");
479
480 let plugin_id = fixture.plugin_id("plugin-context");
481 let agent_data = super::supervisor::owner_data_dir(
482 &fixture.home,
483 &agent_cohort,
484 &plugin_id,
485 "plugin-context",
486 );
487 assert!(agent_data.join("note.txt").exists());
488
489 fixture.review_by_person("plugin-context");
490 engine.set_plugins(fixture.registry());
491 engine.sync().await.ok();
492
493 let reviewed_data =
494 super::supervisor::plugin_data_dir(&fixture.home, &plugin_id, "plugin-context");
495 assert!(
496 !reviewed_data.exists(),
497 "migration deferred while agent host live"
498 );
499 assert!(
500 agent_data.join("note.txt").exists(),
501 "agent data intact while deferred"
502 );
503
504 let mut reg = (*fixture.registry()).clone();
505 reg.disable("crash-tool").unwrap();
506 engine.set_plugins(Arc::new(reg));
507 engine.sync().await.ok();
508
509 wait_host(&manager, || reviewed_data.exists() && !agent_data.exists()).await;
510
511 let content = std::fs::read_to_string(reviewed_data.join("note.txt")).unwrap();
512 assert_eq!(content, "written by agent cohort");
513
514 engine.sync().await.ok();
515 assert_eq!(
516 cohort_pid(&manager, &HostCohort::reviewed()),
517 Some(pid_reviewed_before),
518 "reviewed host remained running across migration"
519 );
520 let probe_tool = host_tool(&engine, fixture.workspace(), "ctx_probe");
521 let probe_context =
522 ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
523 let probe_res = probe_tool.execute(json!({}), &probe_context).await.unwrap();
524 assert!(probe_res.success);
525 let probe_payload: serde_json::Value = serde_json::from_str(&probe_res.content).unwrap();
526 assert_eq!(
527 probe_payload["dataDir"].as_str(),
528 Some(reviewed_data.to_string_lossy().as_ref())
529 );
530
531 let reviewed_note_tool = host_tool(&engine, fixture.workspace(), "ctx_note");
532 let second_write = reviewed_note_tool
533 .execute(json!({"text": "written in reviewed host"}), &probe_context)
534 .await
535 .unwrap();
536 assert!(second_write.success);
537 assert_eq!(
538 std::fs::read_to_string(reviewed_data.join("note.txt")).unwrap(),
539 "written in reviewed host"
540 );
541 }
542
543 #[tokio::test]
544 async fn a_crash_loop_in_an_agent_cohort_leaves_the_reviewed_host_running() {
545 let Some(node) =
546 node_for_tests("a_crash_loop_in_an_agent_cohort_leaves_the_reviewed_host_running")
547 else {
548 return;
549 };
550 let _policy = TestPolicyGuard::extension_host(true);
551 let fixture = CohortTestFixture::new(&["two-entries", "crash-tool"]).await;
552 fixture.review_by_person("two-entries");
553 fixture.review_by_agent("crash-tool");
554
555 let manager = fixture.manager_with_supervision(node, fast_supervision());
556 let engine = manager.attach(fixture.registry());
557 engine.sync().await.unwrap();
558
559 let pid_reviewed =
560 cohort_pid(&manager, &HostCohort::reviewed()).expect("reviewed host must be running");
561 let agent_cohort = HostCohort::agent(fixture.workspace());
562 let pid_agent = cohort_pid(&manager, &agent_cohort).expect("agent host must be running");
563 assert_ne!(pid_reviewed, pid_agent);
564
565 let mut prev_pid = pid_agent;
566 let mut dead_tool = None;
567 for crash in 0..3 {
568 let tool = host_tool(&engine, fixture.workspace(), "crash_probe");
569 let outcome = tool
570 .execute(
571 json!({}),
572 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view()),
573 )
574 .await;
575 assert!(outcome.is_err());
576 dead_tool = Some(tool);
577 if crash < 2 {
578 wait_host(&manager, || {
579 cohort_pid(&manager, &agent_cohort).is_some_and(|pid| pid != prev_pid)
580 && manager.live_tool_names().contains(&"crash_probe".into())
581 })
582 .await;
583 prev_pid = cohort_pid(&manager, &agent_cohort).expect("restarted agent host pid");
584 }
585 }
586
587 wait_host(&manager, || {
588 manager
589 .shared
590 .cohort_runtime(&agent_cohort)
591 .is_some_and(|rt| {
592 rt.host
593 .lock()
594 .map(|slot| matches!(&*slot, HostSlot::Failed { .. }))
595 .unwrap_or(false)
596 })
597 })
598 .await;
599
600 assert!(
601 !super::test_support::installed(&engine, fixture.workspace())
602 .contains(&"crash_probe".to_string())
603 );
604 let dead_outcome = dead_tool
605 .expect("crash_probe ran")
606 .execute(
607 json!({}),
608 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view()),
609 )
610 .await;
611 assert!(dead_outcome.is_err());
612
613 let pid_reviewed_after =
614 cohort_pid(&manager, &HostCohort::reviewed()).expect("reviewed host must still be running");
615 assert_eq!(pid_reviewed, pid_reviewed_after);
616
617 let tool2 = host_tool(&engine, fixture.workspace(), "two_first");
618 let outcome2 = tool2
619 .execute(
620 json!({}),
621 &ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view()),
622 )
623 .await;
624 assert!(
625 outcome2.is_ok(),
626 "reviewed host tool failed after agent crash loop: {:?} status={:?}",
627 outcome2.as_ref().err(),
628 manager.status()
629 );
630 }
631
632 #[tokio::test]
633 async fn a_departed_owner_retires_its_agent_host_when_idle() {
634 let Some(node) = node_for_tests("a_departed_owner_retires_its_agent_host_when_idle") else {
635 return;
636 };
637 let _policy = TestPolicyGuard::extension_host(true);
638 let fixture = CohortTestFixture::new(&["two-entries", "child-persona"]).await;
639 fixture.review_by_agent("two-entries");
640 fixture.review_by_agent("child-persona");
641
642 let manager = fixture.manager(node);
643 let engine = manager.attach(fixture.registry());
644 engine.sync().await.unwrap();
645
646 let agent_cohort = HostCohort::agent(fixture.workspace());
647 let pid1 = cohort_pid(&manager, &agent_cohort).expect("agent host running");
648 let gen1 = {
649 let rt = manager.shared.cohort_runtime(&agent_cohort).unwrap();
650 rt.host_generation.load(std::sync::atomic::Ordering::SeqCst)
651 };
652
653 let mut reg = discover_with_config(&fixture.config);
654 reg.disable("two-entries").unwrap();
655 engine.set_plugins(Arc::new(reg));
656 engine.sync().await.unwrap();
657
658 assert_eq!(
659 cohort_pid(&manager, &agent_cohort),
660 Some(pid1),
661 "disabling 1st owner does not stop agent host while 2nd owner remains"
662 );
663
664 let mut reg2 = discover_with_config(&fixture.config);
665 reg2.disable("two-entries").unwrap();
666 reg2.disable("child-persona").unwrap();
667 engine.set_plugins(Arc::new(reg2));
668 engine.sync().await.unwrap();
669
670 wait_host(&manager, || {
671 let rt = manager.shared.cohort_runtime(&agent_cohort);
672 rt.as_ref().is_none_or(|rt| {
673 rt.host
674 .lock()
675 .map(|slot| matches!(&*slot, HostSlot::Idle))
676 .unwrap_or(false)
677 })
678 })
679 .await;
680
681 let plugin_id = fixture.plugin_id("child-persona");
682 let agent_data = super::supervisor::owner_data_dir(
683 &fixture.home,
684 &agent_cohort,
685 &plugin_id,
686 "child-persona",
687 );
688 assert!(agent_data.parent().unwrap().exists());
689
690 fixture.review_by_agent("two-entries");
691 engine.set_plugins(fixture.registry());
692 engine.sync().await.unwrap();
693
694 let pid2 = cohort_pid(&manager, &agent_cohort).expect("agent host restarted");
695 assert_ne!(pid1, pid2);
696 let gen2 = {
697 let rt = manager.shared.cohort_runtime(&agent_cohort).unwrap();
698 rt.host_generation.load(std::sync::atomic::Ordering::SeqCst)
699 };
700 assert!(gen2 > gen1);
701 }
702
703 #[test]
704 fn granting_a_host_service_to_an_agent_cohort_grants_it_to_every_plugin_in_that_cohort_and_no_other_cohort()
705 {
706 let mut reg = super::registry::OwnerRegistry::default();
707
708 let cohort1 = HostCohort::agent("/workspace/alpha");
709 let cohort2 = HostCohort::agent("/workspace/beta");
710
711 let auth1 = fake_authority("plugin-a");
712 let auth2 = fake_authority("plugin-b");
713 let auth3 = fake_authority("plugin-c");
714
715 let owner1 = reg
716 .begin_owner(
717 cohort1.clone(),
718 "plugin-a",
719 "Plugin A",
720 Some(auth1),
721 "hash-a",
722 )
723 .unwrap();
724 let owner2 = reg
725 .begin_owner(
726 cohort1.clone(),
727 "plugin-b",
728 "Plugin B",
729 Some(auth2),
730 "hash-b",
731 )
732 .unwrap();
733 let owner3 = reg
734 .begin_owner(
735 cohort2.clone(),
736 "plugin-c",
737 "Plugin C",
738 Some(auth3),
739 "hash-c",
740 )
741 .unwrap();
742
743 reg.set_host_services(&owner1, vec![DshService::Network]);
744 reg.set_host_services(&owner2, vec![DshService::Network]);
745 reg.set_host_services(&owner3, vec![]);
746
747 assert!(reg.host_service_granted(&owner1, DshService::Network));
748 assert!(reg.host_service_granted(&owner2, DshService::Network));
749 assert!(!reg.host_service_granted(&owner3, DshService::Network));
750
751 reg.set_host_services(&owner2, vec![]);
752 assert!(!reg.host_service_granted(&owner1, DshService::Network));
753 assert!(!reg.host_service_granted(&owner2, DshService::Network));
754
755 reg.revoke_owner(&owner2.plugin_id);
756 assert!(!reg.host_service_granted(&owner1, DshService::Network));
757 reg.host_process_started(cohort1);
758 assert!(reg.host_service_granted(&owner1, DshService::Network));
759 }
760
761 #[tokio::test]
762 async fn an_agent_cohort_host_cannot_read_or_write_another_cohorts_data() {
763 let home = Path::new("/tmp/cw-cohort-home");
764 let cohort_a = HostCohort::agent("/proj/alpha");
765 let cohort_b = HostCohort::agent("/proj/beta");
766 let dir_a = super::supervisor::host_cohort_data_dir(home, &cohort_a).unwrap();
767 let dir_b = super::supervisor::host_cohort_data_dir(home, &cohort_b).unwrap();
768 let reviewed_dir =
769 super::supervisor::host_cohort_data_dir(home, HostCohort::reviewed()).unwrap();
770 let builtin_dir = super::supervisor::host_cohort_data_dir(home, &HostCohort::Builtin).unwrap();
771
772 assert_ne!(dir_a, dir_b);
773 assert_ne!(dir_a, reviewed_dir);
774 assert_ne!(dir_b, reviewed_dir);
775 assert_ne!(dir_a, builtin_dir);
776 assert!(dir_a.to_string_lossy().contains("data-agent"));
777 assert!(dir_b.to_string_lossy().contains("data-agent"));
778 assert!(reviewed_dir.to_string_lossy().ends_with("data"));
779
780 let temp_home = tempfile::tempdir().unwrap();
781 let (denied_paths, _) =
782 super::supervisor::host_denied_read_paths(&cohort_a, temp_home.path(), false);
783 let reviewed_path = super::supervisor::tier_data_dir(temp_home.path(), HostTier::Plugin);
784 let builtin_path = super::supervisor::tier_data_dir(temp_home.path(), HostTier::Builtin);
785 assert!(
786 denied_paths.contains(&reviewed_path),
787 "agent cohort must deny reviewed data path"
788 );
789 assert!(
790 denied_paths.contains(&builtin_path),
791 "agent cohort must deny builtin data path"
792 );
793
794 let Some(node) =
795 node_for_tests("an_agent_cohort_host_cannot_read_or_write_another_cohorts_data")
796 else {
797 return;
798 };
799 let _policy = TestPolicyGuard::extension_host(true);
800 let fixture = CohortTestFixture::new(&["secret-probe", "two-entries"]).await;
801 fixture.review_by_agent("secret-probe");
802 fixture.review_by_agent("two-entries");
803
804 let manager = fixture.manager(node);
805 let engine = manager.attach(fixture.registry());
806 engine.sync().await.unwrap();
807
808 let plugin_id = fixture.plugin_id("two-entries");
809 let agent_cohort = HostCohort::agent(fixture.workspace());
810 let agent_data =
811 super::supervisor::owner_data_dir(&fixture.home, &agent_cohort, &plugin_id, "two-entries");
812 std::fs::create_dir_all(&agent_data).unwrap();
813 std::fs::write(agent_data.join("agent_file.txt"), "agent data").unwrap();
814
815 let dest_dir = super::supervisor::plugin_data_dir(&fixture.home, &plugin_id, "two-entries");
816 std::fs::create_dir_all(&dest_dir).unwrap();
817 std::fs::write(dest_dir.join("existing.txt"), "pre-existing reviewed data").unwrap();
818
819 let is_sandboxed = manager
820 .shared
821 .cohort_runtime(&agent_cohort)
822 .and_then(|rt| {
823 rt.host.lock().ok().map(|slot| match &*slot {
824 HostSlot::Ready(h) => matches!(h.sandbox, HostSandbox::Wrapped(_)),
825 _ => false,
826 })
827 })
828 .unwrap_or(false);
829
830 if is_sandboxed {
831 let probe_read = host_tool(&engine, fixture.workspace(), "probe_read");
832 let probe_write = host_tool(&engine, fixture.workspace(), "probe_write");
833 let context =
834 ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
835
836 let sibling_after = super::supervisor::host_cohort_data_dir(
837 &fixture.home,
838 HostCohort::agent("/proj/created-after-start"),
839 )
840 .unwrap();
841 std::fs::create_dir_all(&sibling_after).unwrap();
842 std::fs::write(sibling_after.join("sibling.txt"), "sibling secret").unwrap();
843
844 let builtin_fixture_dir =
845 super::supervisor::host_cohort_data_dir(&fixture.home, &HostCohort::Builtin).unwrap();
846 std::fs::create_dir_all(&builtin_fixture_dir).unwrap();
847 std::fs::write(builtin_fixture_dir.join("builtin.txt"), "builtin secret").unwrap();
848
849 for (label, target) in [
850 ("reviewed", dest_dir.join("existing.txt")),
851 ("sibling", sibling_after.join("sibling.txt")),
852 ("builtin", builtin_fixture_dir.join("builtin.txt")),
853 ] {
854 let res = probe_read
855 .execute(json!({"path": target.to_string_lossy()}), &context)
856 .await
857 .unwrap();
858 let payload: serde_json::Value = serde_json::from_str(&res.content).unwrap();
859 assert_eq!(payload["ok"], false, "agent host cannot read {label} data");
860
861 let write_target = target.with_file_name("infiltrate.txt");
862 let res = probe_write
863 .execute(json!({"path": write_target.to_string_lossy()}), &context)
864 .await
865 .unwrap();
866 let payload: serde_json::Value = serde_json::from_str(&res.content).unwrap();
867 assert_eq!(payload["ok"], false, "agent host cannot write {label} data");
868 }
869
870 let secret_probe_id = fixture.plugin_id("secret-probe");
871 let own_data = super::supervisor::owner_data_dir(
872 &fixture.home,
873 &agent_cohort,
874 &secret_probe_id,
875 "secret-probe",
876 );
877 std::fs::create_dir_all(&own_data).unwrap();
878 let res = probe_write
879 .execute(
880 json!({"path": own_data.join("probe.txt").to_string_lossy()}),
881 &context,
882 )
883 .await
884 .unwrap();
885 let payload: serde_json::Value = serde_json::from_str(&res.content).unwrap();
886 assert_eq!(payload["ok"], true, "agent host can write its own data");
887 }
888
889 let secret_probe_id = fixture.plugin_id("secret-probe");
890 fixture.review_by_person("two-entries");
891 fixture.review_by_person("secret-probe");
892 engine.set_plugins(fixture.registry());
893 engine.sync().await.ok();
894
895 wait_host(&manager, || {
896 let reg = manager.shared.registry.lock().unwrap();
897 let failed = reg.owner(&plugin_id).is_some_and(
898 |e| matches!(&e.state, OwnerState::Failed(msg) if msg.contains("already exists")),
899 );
900 let reviewed_ready = reg
901 .owner(&secret_probe_id)
902 .is_some_and(|e| e.state == OwnerState::Active && e.cohort == HostCohort::reviewed());
903 failed && reviewed_ready
904 })
905 .await;
906
907 assert_eq!(
908 std::fs::read_to_string(dest_dir.join("existing.txt")).unwrap(),
909 "pre-existing reviewed data"
910 );
911 assert!(!dest_dir.join("agent_file.txt").exists());
912 assert_eq!(
913 std::fs::read_to_string(agent_data.join("agent_file.txt")).unwrap(),
914 "agent data"
915 );
916
917 let reviewed_sandboxed = manager
918 .shared
919 .cohort_runtime(&HostCohort::reviewed())
920 .and_then(|rt| {
921 rt.host.lock().ok().map(|slot| match &*slot {
922 HostSlot::Ready(h) => matches!(h.sandbox, HostSandbox::Wrapped(_)),
923 _ => false,
924 })
925 })
926 .unwrap_or(false);
927 if reviewed_sandboxed {
928 let probe_read = host_tool(&engine, fixture.workspace(), "probe_read");
929 let probe_write = host_tool(&engine, fixture.workspace(), "probe_write");
930 let context =
931 ToolContext::new(fixture.workspace()).with_plugin_registry(engine.plugin_view());
932
933 let res = probe_read
934 .execute(
935 json!({"path": agent_data.join("agent_file.txt").to_string_lossy()}),
936 &context,
937 )
938 .await
939 .unwrap();
940 let payload: serde_json::Value = serde_json::from_str(&res.content).unwrap();
941 assert_eq!(payload["ok"], false, "reviewed host cannot read agent data");
942
943 let res = probe_write
944 .execute(
945 json!({"path": agent_data.join("reviewed_write.txt").to_string_lossy()}),
946 &context,
947 )
948 .await
949 .unwrap();
950 let payload: serde_json::Value = serde_json::from_str(&res.content).unwrap();
951 assert_eq!(
952 payload["ok"], false,
953 "reviewed host cannot write agent data"
954 );
955 }
956 }
957
958 #[tokio::test]
959 async fn a_record_made_from_a_marked_shell_runs_in_the_agent_cohort_and_an_unmarked_one_in_the_reviewed_host()
960 {
961 let workspace = Path::new("/workspace/example");
962 let approver_marked = PluginApprover::command_line(Some(workspace));
963 assert_eq!(
964 approver_marked.cohort(),
965 PluginCohort::Agent {
966 workspace: workspace.to_string_lossy().into_owned()
967 }
968 );
969 assert_eq!(
970 HostCohort::from_plugin_cohort(approver_marked.cohort()),
971 HostCohort::agent(workspace)
972 );
973
974 let approver_unmarked = PluginApprover::command_line(None);
975 assert_eq!(approver_unmarked.cohort(), PluginCohort::Reviewed);
976 assert_eq!(
977 HostCohort::from_plugin_cohort(approver_unmarked.cohort()),
978 HostCohort::reviewed()
979 );
980
981 let approver_auto = PluginApprover::Agent(AgentApproval {
982 posture: AgentPosture::AutoReview,
983 workspace: workspace.to_string_lossy().into_owned(),
984 thread_id: Some("th".into()),
985 turn_id: Some("tu".into()),
986 tool_call_id: Some("tc".into()),
987 });
988 assert_eq!(
989 approver_auto.cohort(),
990 PluginCohort::Agent {
991 workspace: workspace.to_string_lossy().into_owned()
992 }
993 );
994
995 let Some(node) = node_for_tests(
996 "a_record_made_from_a_marked_shell_runs_in_the_agent_cohort_and_an_unmarked_one_in_the_reviewed_host",
997 ) else {
998 return;
999 };
1000 let _policy = TestPolicyGuard::extension_host(true);
1001 let fixture = CohortTestFixture::new(&[
1002 "two-entries",
1003 "child-persona",
1004 "plugin-context",
1005 "crash-tool",
1006 ])
1007 .await;
1008 fixture.review_by_marked_shell("two-entries");
1009 fixture.review_by_unmarked_shell("child-persona");
1010 fixture.review_by_auto_review("plugin-context", fixture.workspace());
1011 let other_workspace = fixture._temp.path().join("other-project");
1012 std::fs::create_dir_all(&other_workspace).unwrap();
1013 fixture.review_by_auto_review("crash-tool", &other_workspace);
1014
1015 let manager = fixture.manager(node);
1016 let engine = manager.attach(fixture.registry());
1017 engine.sync().await.unwrap();
1018
1019 let pid_agent = cohort_pid(&manager, &HostCohort::agent(fixture.workspace()))
1020 .expect("marked runs in agent cohort");
1021 let pid_reviewed =
1022 cohort_pid(&manager, &HostCohort::reviewed()).expect("unmarked runs in reviewed cohort");
1023 assert_ne!(pid_agent, pid_reviewed);
1024 assert!(
1025 cohort_pid(&manager, &HostCohort::agent(&other_workspace)).is_none(),
1026 "other-project agent record must load nowhere"
1027 );
1028 let reg = manager.shared.registry.lock().unwrap();
1029 let context_id = fixture.plugin_id("plugin-context");
1030 assert_eq!(
1031 reg.owner(&context_id).map(|e| &e.cohort),
1032 Some(&HostCohort::agent(fixture.workspace())),
1033 "auto_review record runs in agent cohort"
1034 );
1035 let crash_id = fixture.plugin_id("crash-tool");
1036 assert!(
1037 reg.owner(&crash_id).is_none(),
1038 "different project record must not load"
1039 );
1040 }
1041
1041 lines RUST