1use std::path::Path;
13
14use anyhow::{Context, Result, bail, ensure};
15
16use super::worker_binary::{
17 apply_staged_execution_setting, bridge_launch, container_upload_ownership_args, stage_profile,
18};
19use super::{Controller, execute_checked};
20use crate::targets::{self, CommandExecutor, CommandSpec, ProcessExecutor};
21use mj_core::worker_launch::{
22 REVIEWER_DIR, ReviewMcpDelivery, ReviewMcpServer, ReviewerLaunchConfig,
23 reviewer_staging_profile_home,
24};
25
26pub fn reviewer_stager() -> mj_client::session::ReviewerStager {
30 mj_client::session::ReviewerStager::new(ControllerReviewerStager)
31}
32
33struct ControllerReviewerStager;
34
35impl mj_client::session::ReviewerStagerBackend for ControllerReviewerStager {
36 fn stage(
37 &self,
38 _config: mj_core::config::Config,
39 session: mj_core::state::SessionRecord,
40 profile_id: String,
41 generation: u64,
42 cancelled: std::sync::Arc<std::sync::atomic::AtomicBool>,
43 ) -> Result<ReviewerLaunchConfig> {
44 let session_id = session.id.clone();
45 let controller = Controller::load()?;
46 let executor = crate::targets::CancellableProcessExecutor::new(cancelled)
47 .with_deadline(std::time::Duration::from_secs(90));
48 controller.stage_reviewer_profile_controlled(
49 &session_id,
50 &profile_id,
51 generation,
52 &[],
53 &executor,
54 )
55 }
56}
57
58impl Controller {
59 pub fn stage_reviewer_profile(
65 &self,
66 session_id: &str,
67 profile_id: &str,
68 generation: u64,
69 ) -> Result<ReviewerLaunchConfig> {
70 self.stage_reviewer_profile_controlled(
71 session_id,
72 profile_id,
73 generation,
74 &[],
75 &ProcessExecutor,
76 )
77 }
78
79 pub fn stage_reviewer_profile_with_mcp(
87 &self,
88 session_id: &str,
89 profile_id: &str,
90 generation: u64,
91 mcp_servers: &[ReviewMcpServer],
92 dispatch_tool: bool,
93 ) -> Result<ReviewerLaunchConfig> {
94 let mut servers = mcp_servers.to_vec();
95 if dispatch_tool {
96 let (_, worker_root) = self.worker_placement(session_id)?;
97 servers.push(review_dispatch_server(&worker_root));
98 }
99 self.stage_reviewer_profile_controlled(
100 session_id,
101 profile_id,
102 generation,
103 &servers,
104 &ProcessExecutor,
105 )
106 }
107
108 pub fn stage_reviewer_profile_controlled(
109 &self,
110 session_id: &str,
111 profile_id: &str,
112 generation: u64,
113 mcp_servers: &[ReviewMcpServer],
114 executor: &impl CommandExecutor,
115 ) -> Result<ReviewerLaunchConfig> {
116 let profile = self
117 .config
118 .profiles
119 .get(profile_id)
120 .with_context(|| format!("unknown profile {profile_id:?}"))?;
121 ensure!(
122 profile.enabled,
123 "reviewer profile {profile_id:?} is disabled"
124 );
125 let session = self
126 .state
127 .sessions
128 .get(session_id)
129 .with_context(|| format!("unknown session {session_id}"))?;
130 let target = session.target_runtime_settings(&self.config)?;
131 let execution_policy = profile
132 .kind
133 .effective_execution_policy(target.execution_policy);
134 if execution_policy.is_unconstrained() && !target.execution_policy.is_unconstrained() {
138 let session_unconstrained = self
139 .config
140 .profiles
141 .get(&session.last_profile)
142 .is_some_and(|session_profile| {
143 session_profile
144 .kind
145 .effective_execution_policy(target.execution_policy)
146 .is_unconstrained()
147 });
148 ensure!(
149 session_unconstrained,
150 "{} cannot review this session: it has no guardian approval mode, so it would run unconstrained while the session runs with approvals on target {:?}. Choose another reviewer, or run the session on a container target",
151 profile.kind.display_name(),
152 session.target_template_id
153 );
154 }
155 let (backend, worker_root) = self.worker_placement(session_id)?;
156
157 let staging = tempfile::tempdir().context("create reviewer staging directory")?;
158 let local = staging.path().join("profile");
159 profile.ensure_ready(profile_id)?;
160 stage_profile(profile, &local).with_context(|| format!("stage profile {profile_id:?}"))?;
161 apply_staged_execution_setting(profile.kind, execution_policy, &local)
162 .with_context(|| format!("stage profile {profile_id:?}"))?;
163 if !mcp_servers.is_empty()
167 && ReviewMcpDelivery::for_harness(profile.kind) == ReviewMcpDelivery::HarnessProfile
168 {
169 configure_staged_review_mcp(profile.kind, &local, mcp_servers)
170 .with_context(|| format!("configure reviewer MCP servers for {profile_id:?}"))?;
171 }
172 upload_reviewer_profile(executor, &backend, &worker_root, generation, &local)?;
173
174 let (bridge_command, bridge_args) = bridge_launch(profile.kind, execution_policy);
175 let mut environment = profile.environment.resolved().clone();
176 environment.remove(profile.home_env());
180 let excluded_environment = profile.exclude_harness_environment(&mut environment);
183 Ok(ReviewerLaunchConfig {
184 profile_id: profile_id.to_owned(),
185 harness: profile.kind,
186 bridge_command: bridge_command.into(),
187 bridge_args,
188 environment,
189 excluded_environment,
190 execution_policy,
191 model: None,
192 effort: None,
193 fast_mode: None,
194 generation,
195 mcp_servers: mcp_servers.to_vec(),
198 })
199 }
200}
201
202fn configure_staged_review_mcp(
210 harness: mj_core::config::HarnessKind,
211 profile_stage: &Path,
212 servers: &[ReviewMcpServer],
213) -> Result<()> {
214 let Some(file) = harness.mcp_config_file() else {
215 bail!("{harness:?} does not read MCP servers from its profile");
216 };
217 let kimi = harness == mj_core::config::HarnessKind::Kimi;
218 let path = profile_stage.join(file);
219 let mut document = match std::fs::read(&path) {
220 Ok(body) => serde_json::from_slice::<serde_json::Value>(&body)
221 .with_context(|| format!("parse staged reviewer configuration {}", path.display()))?,
222 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
223 serde_json::Value::Object(serde_json::Map::new())
224 }
225 Err(error) => {
226 return Err(error)
227 .with_context(|| format!("read staged reviewer configuration {}", path.display()));
228 }
229 };
230 let root = document.as_object_mut().with_context(|| {
231 format!(
232 "staged reviewer configuration {} must contain a JSON object",
233 path.display()
234 )
235 })?;
236 let configured = root
237 .entry("mcpServers")
238 .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
239 .as_object_mut()
240 .with_context(|| {
241 format!(
242 "mcpServers in staged reviewer configuration {} must be a JSON object",
243 path.display()
244 )
245 })?;
246 for server in servers {
247 let mut entry = serde_json::json!({
248 "command": server.command,
249 "args": server.args,
250 });
251 if kimi {
252 let object = entry
253 .as_object_mut()
254 .expect("the server entry is a JSON object");
255 object.insert("transport".into(), "stdio".into());
256 object.insert("runtime_id".into(), "local".into());
257 } else {
258 let object = entry
259 .as_object_mut()
260 .expect("the server entry is a JSON object");
261 object.insert("type".into(), "stdio".into());
262 }
263 configured.insert(server.name.clone(), entry);
264 }
265 let mut body = serde_json::to_vec_pretty(&document)?;
266 body.push(b'\n');
267 mj_core::config::atomic_write(&path, &body)
268 .with_context(|| format!("write staged reviewer configuration {}", path.display()))
269}
270
271fn review_dispatch_server(worker_root: &str) -> ReviewMcpServer {
275 let socket = format!(
276 "{worker_root}/{}/{}",
277 REVIEWER_DIR,
278 mj_core::review::mcp::REVIEW_DISPATCH_SOCKET
279 );
280 ReviewMcpServer {
281 name: mj_core::review::mcp::REVIEW_MCP_SERVER_NAME.to_owned(),
282 command: Path::new(worker_root).join("hel"),
283 args: vec![
284 "worker".to_owned(),
285 "review-mcp".to_owned(),
286 "--socket".to_owned(),
287 socket,
288 ],
289 }
290}
291
292fn reviewer_profile_home(worker_root: &str, generation: u64) -> String {
298 reviewer_staging_profile_home(Path::new(worker_root), generation)
299 .to_string_lossy()
300 .into_owned()
301}
302
303fn upload_reviewer_profile(
309 executor: &impl CommandExecutor,
310 locator: &targets::TargetLocator,
311 worker_root: &str,
312 generation: u64,
313 local: &Path,
314) -> Result<()> {
315 let home = reviewer_profile_home(worker_root, generation);
316 match locator {
317 targets::TargetLocator::LocalBare { .. } => {
318 for command in [
319 CommandSpec::new("rm", ["-rf", "--", &home])
320 .purpose("clear the local reviewer profile"),
321 CommandSpec::new("mkdir", ["-p", &home])
322 .purpose("create the local reviewer profile directory"),
323 CommandSpec::new(
324 "cp",
325 [
326 "-R".to_owned(),
327 format!("{}/.", local.display()),
328 home.clone(),
329 ],
330 )
331 .purpose("install the local reviewer profile"),
332 CommandSpec::new("chmod", ["-R", "go-rwx", &home])
333 .purpose("restrict local reviewer profile permissions"),
334 ] {
335 execute_checked(executor, command)?;
336 }
337 }
338 targets::TargetLocator::LocalPodman { container_id, .. }
339 | targets::TargetLocator::LocalDocker { container_id, .. }
340 | targets::TargetLocator::AppleContainer { container_id, .. } => {
341 let engine = match locator {
342 targets::TargetLocator::LocalPodman { .. } => "podman",
343 targets::TargetLocator::LocalDocker { .. } => "docker",
344 targets::TargetLocator::AppleContainer { .. } => "container",
345 _ => unreachable!("matched local container target"),
346 };
347 for arguments in [
348 vec![
349 "exec".to_owned(),
350 container_id.clone(),
351 "rm".to_owned(),
352 "-rf".to_owned(),
353 "--".to_owned(),
354 home.clone(),
355 ],
356 vec![
357 "exec".to_owned(),
358 container_id.clone(),
359 "mkdir".to_owned(),
360 "-p".to_owned(),
361 home.clone(),
362 ],
363 vec![
364 "cp".to_owned(),
365 format!("{}/.", local.display()),
366 format!("{container_id}:{home}"),
367 ],
368 container_upload_ownership_args(container_id, worker_root, &[&home]),
369 vec![
370 "exec".to_owned(),
371 container_id.clone(),
372 "chmod".to_owned(),
373 "-R".to_owned(),
374 "go-rwx".to_owned(),
375 home.clone(),
376 ],
377 ] {
378 execute_checked(
379 executor,
380 CommandSpec::new(engine, arguments).purpose("stage the reviewer profile"),
381 )?;
382 }
383 }
384 targets::TargetLocator::AwsEc2 { ssh, .. }
385 | targets::TargetLocator::SshBare { ssh, .. } => {
386 let incoming = format!("{home}.incoming");
387 execute_checked(
388 executor,
389 crate::targets::ssh_command(ssh, ["mkdir", "-p", worker_root])
390 .purpose("create the reviewer directory"),
391 )?;
392 execute_checked(
393 executor,
394 crate::targets::ssh_command(ssh, ["rm", "-rf", "--", &incoming, &home])
395 .purpose("clear the reviewer profile"),
396 )?;
397 execute_checked(
398 executor,
399 crate::targets::scp_upload(ssh, local, &incoming, true)
400 .purpose("upload the reviewer profile"),
401 )?;
402 execute_checked(
403 executor,
404 crate::targets::ssh_command(ssh, ["mv", &incoming, &home])
405 .purpose("install the reviewer profile"),
406 )?;
407 execute_checked(
408 executor,
409 crate::targets::ssh_command(ssh, ["chmod", "-R", "go-rwx", &home])
410 .purpose("restrict reviewer profile permissions"),
411 )?;
412 }
413 targets::TargetLocator::SshPodman {
414 ssh, container_id, ..
415 }
416 | targets::TargetLocator::SshDocker {
417 ssh, container_id, ..
418 } => {
419 let engine = match locator {
420 targets::TargetLocator::SshPodman { .. } => "podman",
421 targets::TargetLocator::SshDocker { .. } => "docker",
422 _ => unreachable!("matched remote container target"),
423 };
424 let upload = format!("{worker_root}/.reviewer-upload-{generation}");
425 execute_checked(
426 executor,
427 crate::targets::ssh_command(ssh, ["rm", "-rf", "--", &upload])
428 .purpose("clear remote reviewer staging"),
429 )?;
430 execute_checked(
431 executor,
432 crate::targets::scp_upload(ssh, local, &upload, true)
433 .purpose("upload the remote reviewer profile"),
434 )?;
435 for arguments in [
436 vec![
437 engine.to_owned(),
438 "exec".to_owned(),
439 container_id.clone(),
440 "rm".to_owned(),
441 "-rf".to_owned(),
442 "--".to_owned(),
443 home.clone(),
444 ],
445 vec![
446 engine.to_owned(),
447 "exec".to_owned(),
448 container_id.clone(),
449 "mkdir".to_owned(),
450 "-p".to_owned(),
451 home.clone(),
452 ],
453 vec![
454 engine.to_owned(),
455 "cp".to_owned(),
456 format!("{upload}/."),
457 format!("{container_id}:{home}"),
458 ],
459 std::iter::once(engine.to_owned())
460 .chain(container_upload_ownership_args(
461 container_id,
462 worker_root,
463 &[&home],
464 ))
465 .collect(),
466 vec![
467 engine.to_owned(),
468 "exec".to_owned(),
469 container_id.clone(),
470 "chmod".to_owned(),
471 "-R".to_owned(),
472 "go-rwx".to_owned(),
473 home.clone(),
474 ],
475 ] {
476 execute_checked(
477 executor,
478 crate::targets::ssh_command(ssh, arguments)
479 .purpose("stage the remote reviewer profile"),
480 )?;
481 }
482 execute_checked(
483 executor,
484 crate::targets::ssh_command(ssh, ["rm", "-rf", "--", &upload])
485 .purpose("remove remote reviewer staging"),
486 )?;
487 }
488 }
489 if home.trim().is_empty() {
490 bail!("the reviewer profile home resolved to an empty path");
491 }
492 Ok(())
493}
494
495#[cfg(test)]
496mod tests {
497 use std::cell::RefCell;
498 use std::collections::BTreeMap;
499
500 use super::*;
501 use crate::controller::test_support::checkpoint_test_session;
502 use mj_core::config::{Config, HarnessKind, HarnessProfile, TargetTemplate};
503 use mj_core::state::{SessionState, State};
504
505 use crate::targets::CommandOutput;
506
507 struct RecordingExecutor {
508 commands: RefCell<Vec<CommandSpec>>,
509 }
510
511 impl RecordingExecutor {
512 fn new() -> Self {
513 Self {
514 commands: RefCell::new(Vec::new()),
515 }
516 }
517
518 fn script(&self) -> Vec<String> {
520 self.commands
521 .borrow()
522 .iter()
523 .map(|command| format!("{} {}", command.program, command.args.join(" ")))
524 .collect()
525 }
526 }
527
528 impl CommandExecutor for RecordingExecutor {
529 fn execute(&self, command: &CommandSpec) -> Result<CommandOutput> {
530 self.commands.borrow_mut().push(command.clone());
531 Ok(CommandOutput {
532 status: 0,
533 stdout: Vec::new(),
534 stderr: Vec::new(),
535 })
536 }
537 }
538
539 const SESSION_ID: &str = "0123456789abcdef0123456789abcdef";
542
543 fn fixture(directory: &Path, locator: mj_core::state::TargetLocator) -> (Controller, String) {
544 let session_id = SESSION_ID;
545 let mut session = checkpoint_test_session(session_id);
546 session.target_template_id = "local".into();
547 session.state = SessionState::Running;
548 let template = match &locator {
549 mj_core::state::TargetLocator::LocalPodman { .. } => {
550 serde_json::from_str(r#"{"kind":"local-podman","image":"test"}"#).unwrap()
551 }
552 mj_core::state::TargetLocator::LocalDocker { .. } => {
553 serde_json::from_str(r#"{"kind":"local-docker","image":"test"}"#).unwrap()
554 }
555 _ => TargetTemplate::LocalBare,
556 };
557 session.target = Some(locator);
558 let mut config = Config::default();
559 config.targets.insert("local".into(), template);
560 for (id, kind) in [
561 ("codex", HarnessKind::Codex),
562 ("claude", HarnessKind::Claude),
563 ] {
564 let home = directory.join(id);
565 std::fs::create_dir_all(&home).unwrap();
566 config.profiles.insert(
567 id.to_owned(),
568 HarnessProfile {
569 enabled: true,
570 kind,
571 home,
572 environment: BTreeMap::from([("EXTRA".into(), "1".into())]).into(),
573 context_window_bytes: None,
574 subagents: Default::default(),
575 guardian_review_model: None,
576 },
577 );
578 }
579 (
580 Controller {
581 config,
582 state: State {
583 sessions: [(session_id.into(), session)].into_iter().collect(),
584 ..State::default()
585 },
586 },
587 session_id.to_owned(),
588 )
589 }
590
591 #[test]
592 fn staging_copies_the_chosen_profile_into_the_worker_root() {
593 let directory = tempfile::tempdir().unwrap();
594 let worker_root = directory.path().join(SESSION_ID);
595 std::fs::create_dir_all(directory.path().join("claude")).unwrap();
596 std::fs::write(directory.path().join("claude/CLAUDE.md"), b"reviewer").unwrap();
598 let (controller, session_id) = fixture(
599 directory.path(),
600 mj_core::state::TargetLocator::LocalBare {
601 worker_root: worker_root.clone(),
602 },
603 );
604 let executor = RecordingExecutor::new();
605
606 let config = controller
607 .stage_reviewer_profile_controlled(&session_id, "claude", 0, &[], &executor)
608 .unwrap();
609
610 assert_eq!(config.profile_id, "claude");
611 assert_eq!(config.harness, HarnessKind::Claude);
612 assert_eq!(config.generation, 0);
613 assert_eq!(config.model, None);
614 assert_eq!(config.effort, None);
615 assert!(
617 !config
618 .environment
619 .contains_key(HarnessKind::Claude.home_env())
620 );
621 assert_eq!(
622 config.environment.get("EXTRA").map(String::as_str),
623 Some("1")
624 );
625
626 let home = format!("{}/reviewer/profile", worker_root.display());
627 let script = executor.script();
628 let cleared = script
629 .iter()
630 .position(|line| line.starts_with("rm ") && line.contains(&home))
631 .expect("the previous reviewer profile is cleared");
632 let copied = script
633 .iter()
634 .position(|line| line.starts_with("cp ") && line.ends_with(&home))
635 .expect("the staged profile is installed");
636 assert!(
637 cleared < copied,
638 "a stale profile must go before the new one lands: {script:?}"
639 );
640 assert!(
641 script
642 .iter()
643 .any(|line| line.contains("go-rwx") && line.contains(&home)),
644 "the reviewer profile must not be world readable: {script:?}"
645 );
646 }
647
648 #[test]
649 fn local_container_targets_stage_the_reviewer_through_their_engine() {
650 let directory = tempfile::tempdir().unwrap();
651 let container_id = crate::targets::resource_name(SESSION_ID).unwrap();
652 for (locator, engine) in [
653 (
654 mj_core::state::TargetLocator::LocalPodman {
655 borrowed_from: None,
656 container_id: container_id.clone(),
657 workspace_storage: Default::default(),
658 },
659 "podman",
660 ),
661 (
662 mj_core::state::TargetLocator::LocalDocker {
663 borrowed_from: None,
664 container_id: container_id.clone(),
665 },
666 "docker",
667 ),
668 ] {
669 let (controller, session_id) = fixture(directory.path(), locator);
670 let executor = RecordingExecutor::new();
671
672 controller
673 .stage_reviewer_profile_controlled(&session_id, "codex", 3, &[], &executor)
674 .unwrap();
675
676 let script = executor.script();
677 assert!(
678 script
679 .iter()
680 .all(|line| line.starts_with(&format!("{engine} "))),
681 "a container target is reached only through its engine: {script:?}"
682 );
683 let home = script
684 .iter()
685 .find_map(|line| {
686 line.split(' ')
687 .find(|word| word.contains("/reviewer/profile"))
688 })
689 .expect("the reviewer profile is placed")
690 .to_owned();
691 assert!(
692 home.contains(&format!("/{session_id}")),
693 "the reviewer lives under this session's worker root: {home}"
694 );
695 assert!(
697 !script.iter().any(|line| {
698 line.contains("run") || line.contains("git") || line.contains("create")
699 }),
700 "staging a reviewer provisions nothing: {script:?}"
701 );
702 }
703 }
704
705 #[test]
706 fn reviewer_staging_preserves_owned_approval_for_both_mcp_delivery_paths() {
707 let directory = tempfile::tempdir().unwrap();
708 let (controller, session_id) = fixture(
709 directory.path(),
710 mj_core::state::TargetLocator::LocalBare {
711 worker_root: directory.path().join(SESSION_ID),
712 },
713 );
714 let mut servers =
715 mj_review::bifrost::review_mcp_servers(&[directory.path().to_owned()], "review");
716 servers.push(review_dispatch_server("/worker"));
717 for profile in ["codex", "claude"] {
718 let executor = RecordingExecutor::new();
719 let config = controller
720 .stage_reviewer_profile_controlled(&session_id, profile, 1, &servers, &executor)
721 .unwrap();
722 assert_eq!(config.mcp_servers, servers);
723 assert!(!config.mcp_servers[0].is_review_dispatch(Path::new("/worker/hel")));
724 assert!(config.mcp_servers[1].is_review_dispatch(Path::new("/worker/hel")));
725 }
726 }
727
728 #[test]
729 fn an_unconstrained_reviewer_is_refused_for_a_session_that_runs_with_approvals() {
730 let directory = tempfile::tempdir().unwrap();
731 let (mut controller, session_id) = fixture(
732 directory.path(),
733 mj_core::state::TargetLocator::LocalBare {
734 worker_root: directory.path().join(SESSION_ID),
735 },
736 );
737 controller.config.profiles.insert(
738 "muse".into(),
739 HarnessProfile {
740 enabled: true,
741 kind: HarnessKind::Muse,
742 home: directory.path().join("muse"),
743 environment: BTreeMap::new().into(),
744 context_window_bytes: None,
745 subagents: Default::default(),
746 guardian_review_model: None,
747 },
748 );
749 let executor = RecordingExecutor::new();
750
751 let error = controller
754 .stage_reviewer_profile_controlled(&session_id, "muse", 0, &[], &executor)
755 .unwrap_err();
756
757 assert!(
758 format!("{error:#}").contains("cannot review this session"),
759 "{error:#}"
760 );
761 assert!(executor.commands.borrow().is_empty());
762 }
763
764 #[test]
765 fn a_muse_reviewer_is_staged_with_the_permission_profile_its_policy_enforces() {
766 let directory = tempfile::tempdir().unwrap();
767 let worker_root = directory.path().join(SESSION_ID);
768 let (mut controller, session_id) = fixture(
769 directory.path(),
770 mj_core::state::TargetLocator::LocalBare {
771 worker_root: worker_root.clone(),
772 },
773 );
774 let home = directory.path().join("muse");
777 std::fs::create_dir_all(&home).unwrap();
778 std::fs::write(
779 home.join("settings.json"),
780 br#"{"schema_version":1,"permissions":{"schema_version":1,"default_profile":":auto-review"}}"#,
781 )
782 .unwrap();
783 controller.config.profiles.insert(
784 "muse".into(),
785 HarnessProfile {
786 enabled: true,
787 kind: HarnessKind::Muse,
788 home,
789 environment: BTreeMap::new().into(),
790 context_window_bytes: None,
791 subagents: Default::default(),
792 guardian_review_model: None,
793 },
794 );
795 controller
798 .state
799 .sessions
800 .get_mut(&session_id)
801 .unwrap()
802 .last_profile = "muse".into();
803
804 controller
805 .stage_reviewer_profile_controlled(&session_id, "muse", 0, &[], &ProcessExecutor)
806 .unwrap();
807
808 let staged: serde_json::Value = serde_json::from_slice(
809 &std::fs::read(worker_root.join("reviewer/profile/settings.json")).unwrap(),
810 )
811 .unwrap();
812 assert_eq!(staged["permissions"]["default_profile"], ":unrestricted");
813 }
814
815 #[test]
816 fn an_unknown_profile_is_refused_before_anything_is_copied() {
817 let directory = tempfile::tempdir().unwrap();
818 let (controller, session_id) = fixture(
819 directory.path(),
820 mj_core::state::TargetLocator::LocalBare {
821 worker_root: directory.path().join(SESSION_ID),
822 },
823 );
824 let executor = RecordingExecutor::new();
825
826 let error = controller
827 .stage_reviewer_profile_controlled(&session_id, "missing", 0, &[], &executor)
828 .unwrap_err();
829
830 assert!(format!("{error:#}").contains("unknown profile"));
831 assert!(executor.commands.borrow().is_empty());
832 }
833
834 #[test]
835 fn a_new_generation_travels_to_the_worker_so_it_starts_a_fresh_reviewer() {
836 let directory = tempfile::tempdir().unwrap();
837 let (controller, session_id) = fixture(
838 directory.path(),
839 mj_core::state::TargetLocator::LocalBare {
840 worker_root: directory.path().join(SESSION_ID),
841 },
842 );
843 let executor = RecordingExecutor::new();
844
845 let first = controller
846 .stage_reviewer_profile_controlled(&session_id, "codex", 0, &[], &executor)
847 .unwrap();
848 let second = controller
849 .stage_reviewer_profile_controlled(&session_id, "codex", 1, &[], &executor)
850 .unwrap();
851
852 assert!(first.reusable_for(&first));
853 assert!(
854 !first.reusable_for(&second),
855 "a new generation must not reload the old conversation"
856 );
857 }
858}