Skip to main content

mj_controller/controller/
subagents.rs

1//! Registration and ownership rules for child sessions on a parent's target.
2
3use std::path::{Path, PathBuf};
4
5use anyhow::{Context, Result, ensure};
6
7use super::{Controller, now};
8use mj_core::config::HarnessKind;
9use mj_core::state::{SessionRecord, SessionState, new_session_id};
10use mj_core::subagent::SubagentRecord;
11
12#[derive(Debug, Clone)]
13pub struct RegisterSubagentRequest {
14    pub parent_session_id: String,
15    pub task_name: String,
16    pub profile_id: String,
17    pub model: Option<String>,
18    pub effort: Option<String>,
19    /// Empty means the parent's working directory. An absolute path is used
20    /// as-is; a relative path is resolved against the parent's working
21    /// directory. The path is interpreted on the parent's target and must
22    /// exist there; no other restriction applies.
23    pub working_directory: PathBuf,
24    pub initial_prompt: String,
25    pub request_key: String,
26    /// The absolute directory on the parent's target that holds its
27    /// children's report directories, from [`Controller::prepare_subagent_report_root`].
28    /// `None` registers a child without one.
29    pub report_root: Option<String>,
30}
31
32/// Creates a report directory on a target and prints its absolute path.
33///
34/// `$1` is the directory, which may be relative to the login home the way an
35/// SSH or EC2 workspace is. `$2`, when not empty, is a repository whose
36/// `info/exclude` must list [`mj_core::subagent::PROJECT_REPORT_ROOT_DIR`], so a
37/// report root inside a bare project never shows in `git status`. A directory
38/// that is not a repository has no status to keep clean. The absolute path is
39/// what the parent and child are told, because neither runs in the login home.
40const PREPARE_REPORT_DIR_SCRIPT: &str = r#"set -eu
41cd
42mkdir -p -- "$1"
43if [ -n "$2" ] && exclude=$(git -C "$2" rev-parse --git-path info/exclude 2>/dev/null); then
44  case "$exclude" in /*) ;; *) exclude="$2/$exclude" ;; esac
45  line="/$3/"
46  if ! grep -qxF -- "$line" "$exclude" 2>/dev/null; then
47    mkdir -p -- "$(dirname -- "$exclude")"
48    if [ -s "$exclude" ] && [ -n "$(tail -c 1 -- "$exclude")" ]; then
49      printf '
50' >> "$exclude"
51    fi
52    printf '%s
53' "$line" >> "$exclude"
54  fi
55fi
56cd -- "$1"
57pwd -P
58"#;
59
60/// The argv that runs [`PREPARE_REPORT_DIR_SCRIPT`] for `directory`, adding
61/// the exclude line to `exclude_in` when given.
62fn prepare_report_dir_argv(directory: &str, exclude_in: Option<&str>) -> Vec<String> {
63    vec![
64        "sh".into(),
65        "-c".into(),
66        PREPARE_REPORT_DIR_SCRIPT.into(),
67        "sh".into(),
68        directory.into(),
69        exclude_in.unwrap_or_default().into(),
70        mj_core::subagent::PROJECT_REPORT_ROOT_DIR.into(),
71    ]
72}
73
74/// Run [`PREPARE_REPORT_DIR_SCRIPT`] on `backend` and return the absolute
75/// directory it printed.
76fn prepare_report_dir(
77    executor: &impl mj_core::targets::CommandExecutor,
78    backend: &mj_core::targets::TargetLocator,
79    session_id: &str,
80    directory: &str,
81    exclude_in: Option<&str>,
82) -> Result<String> {
83    let command = mj_core::targets::command_on_locator(
84        backend,
85        session_id,
86        prepare_report_dir_argv(directory, exclude_in),
87        "create the sub-agent report directory",
88    )?;
89    let output = super::execute_checked(executor, command)?;
90    let absolute = String::from_utf8(output.stdout)
91        .context("the sub-agent report directory is not UTF-8")?
92        .trim_end_matches('\n')
93        .to_owned();
94    ensure!(
95        absolute.starts_with('/'),
96        "the target did not report an absolute sub-agent report directory: {absolute:?}"
97    );
98    Ok(absolute)
99}
100
101impl Controller {
102    /// Create the directory that holds a parent's children's report
103    /// directories on the parent's target, and return its absolute path.
104    ///
105    /// It sits outside every repository: under the workspace root that a
106    /// bundle session's repositories are checked out below, or, for a bare
107    /// project whose workspace root is the user's own directory, inside the
108    /// project under a path its `info/exclude` lists.
109    pub fn prepare_subagent_report_root(
110        &self,
111        parent_session_id: &str,
112        executor: &impl mj_core::targets::CommandExecutor,
113    ) -> Result<String> {
114        let parent = self
115            .state
116            .sessions
117            .get(parent_session_id)
118            .with_context(|| format!("unknown parent session {parent_session_id}"))?;
119        let locator = parent
120            .target
121            .as_ref()
122            .context("parent session has no live target")?;
123        let backend = super::backend::backend_locator(locator, parent, &self.config)?;
124        let (root, exclude_in) = subagent_report_root(parent, &backend);
125        prepare_report_dir(
126            executor,
127            &backend,
128            parent_session_id,
129            &root,
130            exclude_in.as_deref(),
131        )
132    }
133
134    /// Create a registered child's own report directory on its target. A
135    /// child registered without one has nothing to create.
136    pub(super) fn prepare_subagent_report_dir(
137        &self,
138        session_id: &str,
139        backend: &mj_core::targets::TargetLocator,
140        executor: &impl mj_core::targets::CommandExecutor,
141    ) -> Result<()> {
142        if crate::database::load_subagent(session_id)?.is_none() {
143            return Ok(());
144        }
145        let Some(directory) = crate::database::load_subagent_report(session_id)?.report_dir else {
146            return Ok(());
147        };
148        prepare_report_dir(executor, backend, session_id, &directory, None)?;
149        Ok(())
150    }
151
152    /// Register a child without provisioning another target or checkout.
153    pub fn register_subagent(
154        &mut self,
155        request: RegisterSubagentRequest,
156    ) -> Result<SubagentRecord> {
157        if let Some(existing) = crate::database::lookup_subagent_request(
158            &request.parent_session_id,
159            &request.request_key,
160        )? {
161            return Ok(existing);
162        }
163        ensure!(
164            !request.request_key.trim().is_empty(),
165            "sub-agent request key cannot be empty"
166        );
167        ensure!(
168            !request.task_name.trim().is_empty(),
169            "sub-agent task name cannot be empty"
170        );
171        ensure!(
172            !request.initial_prompt.trim().is_empty(),
173            "sub-agent instructions cannot be empty"
174        );
175        let parent = self
176            .state
177            .sessions
178            .get(&request.parent_session_id)
179            .with_context(|| format!("unknown parent session {}", request.parent_session_id))?
180            .clone();
181        ensure!(
182            matches!(
183                parent.harness_kind,
184                HarnessKind::Claude | HarnessKind::Codex
185            ),
186            "only Claude and Codex sessions can spawn sub-agents"
187        );
188        ensure_parent_may_delegate(&parent)?;
189        ensure!(
190            parent.state != SessionState::StartupCleanup,
191            "parent startup cleanup is pending"
192        );
193        if let Some(mj_core::subagent::SubagentPolicy::SingleModel { model, effort }) =
194            &parent.subagents
195        {
196            ensure!(
197                request.model.as_ref() == Some(model) && &request.effort == effort,
198                "child selectors must match the parent's fixed model and effort"
199            );
200        }
201        ensure!(parent.state.is_active(), "parent session is not active");
202        ensure!(parent.target.is_some(), "parent session has no live target");
203        ensure!(
204            crate::database::load_subagent(&parent.id)?.is_none(),
205            "sub-agents cannot spawn other sub-agents"
206        );
207        ensure!(
208            self.config
209                .subagents
210                .profile_is_eligible(&parent.last_profile, &request.profile_id),
211            "profile {:?} is not eligible for sub-agent use",
212            request.profile_id
213        );
214        let profile = self
215            .config
216            .enabled_profile(&request.profile_id)
217            .with_context(|| {
218                format!("sub-agent profile {:?} is unavailable", request.profile_id)
219            })?;
220        profile.ensure_ready(&request.profile_id)?;
221        if profile.kind == HarnessKind::Muse {
222            let multiple_roots = !parent.additional_mounts.is_empty()
223                || (parent.project_directory.is_none()
224                    && parent
225                        .project_bundle(&self.config)
226                        .is_some_and(|bundle| bundle.repositories.len() > 1));
227            ensure!(
228                !multiple_roots,
229                "{} ACP supports one workspace root; this parent exposes multiple roots",
230                profile.kind.display_name()
231            );
232        }
233        self.ensure_subagent_slot_available(&parent.id, None)?;
234
235        let child_id = new_session_id()?;
236        let target = borrowed_locator(
237            parent.target.as_ref().expect("live target checked above"),
238            &parent.id,
239            &child_id,
240        )?;
241        let created_at = now();
242        let session = SessionRecord {
243            project: parent.project.clone(),
244            target_runtime: Some(parent.target_runtime_settings(&self.config)?.into_owned()),
245            launch_base: None,
246            launch_branch: None,
247            checkout: None,
248            publication: None,
249            // A child shares its parent's container, so it shares the build
250            // cache that container was created with.
251            build_cache: parent.build_cache.clone(),
252            // A child never receives the Mjolnir sub-agent tools, so it can
253            // never spawn a grandchild.
254            subagents: Some(mj_core::subagent::SubagentPolicy::None),
255            create_managed_worktree: Some(false),
256            archived: false,
257            container_cpus: None,
258            container_memory: None,
259            // A child runs inside its parent's container, so it works in the
260            // parent's workspace, including the legacy shared one.
261            container_workspace: parent.container_workspace.clone(),
262            id: child_id.clone(),
263            workspace_id: parent.workspace_id.clone(),
264            title: request.task_name.clone(),
265            harness_kind: profile.kind,
266            last_profile: request.profile_id.clone(),
267            bundle_id: parent.bundle_id.clone(),
268            project_directory: parent.project_directory.clone(),
269            managed_worktree: None,
270            target_template_id: parent.target_template_id.clone(),
271            resource_allocation: parent.resource_allocation.clone(),
272            additional_mounts: parent.additional_mounts.clone(),
273            state: SessionState::Provisioning,
274            target: Some(target),
275            native_session_id: None,
276            acp_session_title: None,
277            session_title_override: Some(request.task_name.clone()),
278            created_at: created_at.clone(),
279            updated_at: created_at.clone(),
280            viewed_through_event_ordinal: 0,
281            draft_input: String::new(),
282            last_error: None,
283            last_checkpoint_error: None,
284            checkpoint: None,
285        };
286        let handback_tool = child_gets_handback_tool(profile.kind);
287        let report_dir = request
288            .report_root
289            .as_deref()
290            .map(|root| format!("{}/{child_id}", root.trim_end_matches('/')));
291        // The first prompt names the tool only when the child will have it.
292        let initial_prompt = match (handback_tool, &report_dir) {
293            (true, Some(report_dir)) => format!(
294                "{}\n\n{}",
295                mj_core::subagent::handback_prompt_note(report_dir),
296                request.initial_prompt
297            ),
298            _ => request.initial_prompt,
299        };
300        let relation = SubagentRecord {
301            child_session_id: child_id.clone(),
302            parent_session_id: parent.id,
303            task_name: request.task_name,
304            profile_id: request.profile_id,
305            model: request.model,
306            effort: request.effort,
307            working_directory: request.working_directory,
308            initial_prompt,
309            request_key: request.request_key,
310            created_at,
311            noticed_turn: None,
312            handback_tool,
313        };
314        crate::database::save_subagent_session(&session, &relation)?;
315        if let Some(report_dir) = &report_dir {
316            crate::database::record_subagent_report_dir(&child_id, report_dir)?;
317        }
318        self.state.sessions.insert(child_id, session);
319        self.state
320            .subagents
321            .insert(relation.child_session_id.clone(), relation.clone());
322        Ok(relation)
323    }
324
325    /// Refuse to start another child process tree for `parent_session_id`
326    /// when it already has the maximum number of live children.
327    ///
328    /// `starting` is the child a `send_input` is about to start again from
329    /// parked; it is not counted against itself. A spawn passes `None`.
330    ///
331    /// Every child whose worker may be holding processes in the parent's
332    /// container counts, idle or not: those processes are what the cap
333    /// protects (#1161). A parked, stopped, failed or lost child holds none.
334    pub fn ensure_subagent_slot_available(
335        &self,
336        parent_session_id: &str,
337        starting: Option<&str>,
338    ) -> Result<()> {
339        let live = crate::database::list_subagents(parent_session_id)?
340            .into_iter()
341            .filter(|child| Some(child.child_session_id.as_str()) != starting)
342            .filter_map(|child| {
343                let session = self.state.sessions.get(&child.child_session_id)?;
344                session.state.has_live_worker().then(|| LiveSubagent {
345                    child_session_id: child.child_session_id.clone(),
346                    title: session.listed_title().to_owned(),
347                    state: live_subagent_state(session),
348                })
349            })
350            .collect::<Vec<_>>();
351        let maximum = self.config.subagents.max_concurrent;
352        ensure!(live.len() < maximum, "{}", slot_refusal(&live, maximum));
353        Ok(())
354    }
355}
356
357/// One child that holds processes on its parent's target, as a cap refusal
358/// names it.
359struct LiveSubagent {
360    child_session_id: String,
361    title: String,
362    state: &'static str,
363}
364
365/// The word a cap refusal uses for a live child's state. An idle child is
366/// told apart from a working one, because only an idle child can be closed
367/// without losing work.
368fn live_subagent_state(session: &SessionRecord) -> &'static str {
369    match session.state {
370        SessionState::Provisioning => "starting",
371        SessionState::Checkpointing => "checkpointing",
372        SessionState::Closing | SessionState::Destroying | SessionState::StartupCleanup => {
373            "stopping"
374        }
375        SessionState::Disconnected => "disconnected",
376        _ => match crate::database::load_materialized_session_summary(&session.id) {
377            Ok(Some(summary))
378                if matches!(
379                    summary.execution,
380                    mj_core::state::MaterializedExecutionState::Idle
381                ) =>
382            {
383                "idle"
384            }
385            _ => "running",
386        },
387    }
388}
389
390/// The refusal a parent model reads when it asks for one child too many: how
391/// many are live, the maximum, which ones they are, and how a slot frees up.
392fn slot_refusal(live: &[LiveSubagent], maximum: usize) -> String {
393    let listed = live
394        .iter()
395        .map(|child| {
396            format!(
397                "{} \"{}\" ({})",
398                mj_core::state::short_id(&child.child_session_id),
399                child.title,
400                child.state
401            )
402        })
403        .collect::<Vec<_>>()
404        .join(", ");
405    format!(
406        "this session already has {} live sub-agents and the maximum is {maximum}. \
407         Live sub-agents: {listed}. A sub-agent frees its slot when it hands back its \
408         report (it is then parked and holds no processes until you send it input) or \
409         when you close it.",
410        live.len()
411    )
412}
413
414/// Whether a sub-agent child has handed back its report for its parent's
415/// newest task, from what the store holds; see
416/// [`mj_core::subagent::has_handed_back`]. A session that is not a child, or
417/// that has never finished a turn, has not.
418pub fn subagent_has_handed_back(child_session_id: &str) -> Result<bool> {
419    let Some(relation) = crate::database::load_subagent(child_session_id)? else {
420        return Ok(false);
421    };
422    // A child is parked only once its turn ended and its parent was told, so
423    // whatever the parent was going to get from it, it has.
424    if crate::database::load_session_state(child_session_id)? == Some(SessionState::Parked) {
425        return Ok(true);
426    }
427    let Some((execution, active_turn, last_turn)) =
428        crate::database::load_materialized_turn_outcome(child_session_id)?
429    else {
430        return Ok(false);
431    };
432    let report = crate::database::load_subagent_report(child_session_id)?;
433    let working = active_turn.is_some()
434        || !matches!(execution, mj_core::state::MaterializedExecutionState::Idle);
435    Ok(mj_core::subagent::has_handed_back(
436        relation.handback_tool,
437        &report,
438        working,
439        last_turn.as_ref(),
440        mj_core::clock::epoch_millis(),
441    ))
442}
443
444/// What a parent's record keeps about a child its suspend stops: the child's
445/// listed title, one line of its task, and whether it had handed back.
446pub fn stopped_subagent(
447    state: &mj_core::state::State,
448    child_session_id: &str,
449) -> Result<mj_core::subagent::StoppedSubagent> {
450    let relation = state
451        .subagents
452        .get(child_session_id)
453        .with_context(|| format!("unknown sub-agent session {child_session_id}"))?;
454    let title = state
455        .sessions
456        .get(child_session_id)
457        .map_or(relation.task_name.as_str(), SessionRecord::listed_title)
458        .to_owned();
459    let report_dir = crate::database::load_subagent_report(child_session_id)?.report_dir;
460    Ok(mj_core::subagent::StoppedSubagent {
461        child_session_id: child_session_id.to_owned(),
462        title,
463        task: mj_core::subagent::task_summary(&relation.initial_prompt, report_dir.as_deref()),
464        handed_back: subagent_has_handed_back(child_session_id)?,
465    })
466}
467
468fn sibling_path(path: &Path, parent_id: &str, child_id: &str) -> Result<PathBuf> {
469    ensure!(
470        path.ends_with(parent_id),
471        "parent target path does not end in its session id"
472    );
473    Ok(path
474        .parent()
475        .context("parent target path has no parent")?
476        .join(child_id))
477}
478
479fn borrowed_locator(
480    target: &mj_core::state::TargetLocator,
481    parent_id: &str,
482    child_id: &str,
483) -> Result<mj_core::state::TargetLocator> {
484    use mj_core::state::TargetLocator;
485    Ok(match target {
486        TargetLocator::LocalBare { worker_root } => TargetLocator::LocalBare {
487            worker_root: sibling_path(worker_root, parent_id, child_id)?,
488        },
489        TargetLocator::SshBare {
490            host,
491            workspace,
492            worker_id: _,
493        } => TargetLocator::SshBare {
494            host: host.clone(),
495            workspace: workspace.clone(),
496            worker_id: Some(child_id.to_owned()),
497        },
498        // A container child runs its own worker inside the parent's container
499        // and records the parent as the container's owner, so cleanup and
500        // whole-target operations stay with the parent.
501        TargetLocator::LocalPodman {
502            container_id,
503            workspace_storage,
504            ..
505        } => TargetLocator::LocalPodman {
506            container_id: container_id.clone(),
507            workspace_storage: workspace_storage.clone(),
508            borrowed_from: Some(parent_id.to_owned()),
509        },
510        TargetLocator::LocalDocker { container_id, .. } => TargetLocator::LocalDocker {
511            container_id: container_id.clone(),
512            borrowed_from: Some(parent_id.to_owned()),
513        },
514        TargetLocator::AppleContainer { container_id, .. } => TargetLocator::AppleContainer {
515            container_id: container_id.clone(),
516            borrowed_from: Some(parent_id.to_owned()),
517        },
518        TargetLocator::SshPodman {
519            host,
520            container_id,
521            workspace_storage,
522            ..
523        } => TargetLocator::SshPodman {
524            host: host.clone(),
525            container_id: container_id.clone(),
526            workspace_storage: workspace_storage.clone(),
527            borrowed_from: Some(parent_id.to_owned()),
528        },
529        TargetLocator::SshDocker {
530            host, container_id, ..
531        } => TargetLocator::SshDocker {
532            host: host.clone(),
533            container_id: container_id.clone(),
534            borrowed_from: Some(parent_id.to_owned()),
535        },
536        // EC2 children keep the parent's locator unchanged, as they did before
537        // container borrowing was recorded.
538        other @ TargetLocator::AwsEc2 { .. } => other.clone(),
539    })
540}
541
542/// Whether a child can be given the `handback` tool. Codex takes Mjolnir's MCP
543/// servers over ACP; Claude reads them from its staged profile, which every
544/// session has. Other harnesses keep reporting through their last message.
545fn child_gets_handback_tool(harness: HarnessKind) -> bool {
546    matches!(harness, HarnessKind::Codex | HarnessKind::Claude)
547}
548
549/// A parent may delegate to Mjolnir children only if its own stored choice
550/// says so; historical records without a policy use native delegation. A parent
551/// using its harness's native delegation never received the Mjolnir tools, so
552/// a request from it is stale.
553fn ensure_parent_may_delegate(parent: &SessionRecord) -> Result<()> {
554    ensure!(
555        parent
556            .subagents
557            .as_ref()
558            .is_some_and(mj_core::subagent::SubagentPolicy::uses_mjolnir),
559        "this session does not allow Mjolnir sub-agents"
560    );
561    Ok(())
562}
563
564/// Where a parent's children keep their report directories, before the target
565/// resolves it, and the repository whose `info/exclude` must list it.
566fn subagent_report_root(
567    parent: &SessionRecord,
568    backend: &mj_core::targets::TargetLocator,
569) -> (String, Option<String>) {
570    match &parent.project_directory {
571        Some(project) => {
572            let project = project.to_string_lossy().trim_end_matches('/').to_owned();
573            (
574                format!("{project}/{}", mj_core::subagent::PROJECT_REPORT_ROOT_DIR),
575                Some(project),
576            )
577        }
578        None => {
579            let workspace =
580                super::network_git::workspace_root(backend, parent.container_workspace.as_deref());
581            (
582                format!(
583                    "{}/{}",
584                    workspace.trim_end_matches('/'),
585                    mj_core::subagent::REPORT_ROOT_DIR
586                ),
587                None,
588            )
589        }
590    }
591}
592
593#[cfg(test)]
594mod tests {
595    use super::*;
596
597    fn run_prepare_script(directory: &Path, exclude_in: Option<&Path>) -> String {
598        let argv = prepare_report_dir_argv(
599            &directory.to_string_lossy(),
600            exclude_in
601                .map(|path| path.to_string_lossy().into_owned())
602                .as_deref(),
603        );
604        let output = std::process::Command::new(&argv[0])
605            .args(&argv[1..])
606            .output()
607            .expect("run the report directory script");
608        assert!(
609            output.status.success(),
610            "{}",
611            String::from_utf8_lossy(&output.stderr)
612        );
613        String::from_utf8(output.stdout)
614            .unwrap()
615            .trim_end()
616            .to_owned()
617    }
618
619    /// A bare project's report root is inside the project, so the script
620    /// lists it in the repository's `info/exclude` exactly once and the
621    /// project's `git status` stays clean.
622    #[test]
623    fn the_report_directory_script_creates_the_directory_and_keeps_git_status_clean() {
624        let temp = tempfile::tempdir().unwrap();
625        let project = temp.path().join("project");
626        std::fs::create_dir_all(&project).unwrap();
627        let git = |args: &[&str]| {
628            let output = std::process::Command::new("git")
629                .arg("-C")
630                .arg(&project)
631                .args(args)
632                .output()
633                .unwrap();
634            assert!(output.status.success(), "{output:?}");
635            String::from_utf8(output.stdout).unwrap()
636        };
637        git(&["init", "-q"]);
638        // An exclude file without a trailing newline must not have its last
639        // line joined to the new one.
640        std::fs::write(project.join(".git/info/exclude"), "*.tmp").unwrap();
641        let root = project.join(mj_core::subagent::PROJECT_REPORT_ROOT_DIR);
642        let printed = run_prepare_script(&root, Some(&project));
643        assert_eq!(
644            Path::new(&printed),
645            root.canonicalize().unwrap(),
646            "the script prints the absolute directory"
647        );
648        run_prepare_script(&root, Some(&project));
649        std::fs::write(root.join("report.md"), "details").unwrap();
650        let exclude = std::fs::read_to_string(project.join(".git/info/exclude")).unwrap();
651        assert_eq!(exclude, "*.tmp\n/.mj/agents/\n");
652        assert_eq!(git(&["status", "--porcelain", "--ignored=no"]), "");
653
654        // Outside a repository there is no exclude to write.
655        let plain = temp.path().join("plain");
656        std::fs::create_dir_all(&plain).unwrap();
657        let reports = plain.join(".mj/agents/child");
658        run_prepare_script(&reports, Some(&plain));
659        assert!(reports.is_dir());
660    }
661
662    #[test]
663    fn a_report_root_is_under_the_workspace_or_inside_a_bare_project() {
664        let mut parent = super::super::test_support::checkpoint_test_session("parent-1");
665        let backend = mj_core::targets::TargetLocator::LocalBare {
666            worker_root: "/var/lib/hel/workers/parent-1".into(),
667        };
668        parent.project_directory = None;
669        assert_eq!(
670            subagent_report_root(&parent, &backend),
671            ("/var/lib/hel/workers/parent-1/.mj-agents".to_owned(), None)
672        );
673        parent.project_directory = Some("/home/dev/project/".into());
674        assert_eq!(
675            subagent_report_root(&parent, &backend),
676            (
677                "/home/dev/project/.mj/agents".to_owned(),
678                Some("/home/dev/project".to_owned())
679            )
680        );
681    }
682
683    #[test]
684    fn a_container_child_borrows_its_parents_container() {
685        use mj_core::state::{PodmanWorkspaceLocator, TargetLocator};
686
687        let parent_id = "0123456789abcdef0123456789abcdef";
688        let child_id = "fedcba9876543210fedcba9876543210";
689        let container = mj_core::targets::resource_name(parent_id).unwrap();
690
691        let local = borrowed_locator(
692            &TargetLocator::LocalPodman {
693                container_id: container.clone(),
694                workspace_storage: PodmanWorkspaceLocator::Volume {
695                    name: "parent-volume".to_owned(),
696                },
697                borrowed_from: None,
698            },
699            parent_id,
700            child_id,
701        )
702        .unwrap();
703        assert_eq!(
704            local,
705            TargetLocator::LocalPodman {
706                container_id: container.clone(),
707                workspace_storage: PodmanWorkspaceLocator::Volume {
708                    name: "parent-volume".to_owned(),
709                },
710                borrowed_from: Some(parent_id.to_owned()),
711            }
712        );
713
714        let remote = borrowed_locator(
715            &TargetLocator::SshPodman {
716                host: "builder".to_owned(),
717                container_id: container.clone(),
718                workspace_storage: PodmanWorkspaceLocator::ContainerLayer,
719                borrowed_from: None,
720            },
721            parent_id,
722            child_id,
723        )
724        .unwrap();
725        assert_eq!(
726            remote,
727            TargetLocator::SshPodman {
728                host: "builder".to_owned(),
729                container_id: container,
730                workspace_storage: PodmanWorkspaceLocator::ContainerLayer,
731                borrowed_from: Some(parent_id.to_owned()),
732            }
733        );
734    }
735
736    #[test]
737    fn a_parent_using_native_delegation_cannot_spawn_mjolnir_children() {
738        let parent = |choice: Option<bool>| {
739            let mut session = crate::controller::test_support::checkpoint_test_session("parent");
740            session.subagents = choice.map(|enabled| {
741                if enabled {
742                    mj_core::subagent::SubagentPolicy::AllModels
743                } else {
744                    mj_core::subagent::SubagentPolicy::Native
745                }
746            });
747            session
748        };
749
750        assert_eq!(
751            ensure_parent_may_delegate(&parent(Some(false)))
752                .unwrap_err()
753                .to_string(),
754            "this session does not allow Mjolnir sub-agents"
755        );
756        assert_eq!(
757            ensure_parent_may_delegate(&parent(None))
758                .unwrap_err()
759                .to_string(),
760            "this session does not allow Mjolnir sub-agents"
761        );
762        assert!(ensure_parent_may_delegate(&parent(Some(true))).is_ok());
763    }
764
765    /// #1161: idle children held the processes that exhausted their parent's
766    /// container, yet did not count against the cap. Every child that holds
767    /// processes counts now; a parked one does not. The refusal is what the
768    /// parent model reads, so it names the live children and how to free a
769    /// slot.
770    #[test]
771    fn the_cap_counts_every_child_holding_processes_and_names_them() {
772        const MARKER: &str = "MJ_TEST_SUBAGENT_CAP_CHILD";
773        if std::env::var_os(MARKER).is_none() {
774            let directory = tempfile::tempdir().unwrap();
775            super::super::test_support::IsolatedTest::new(super::super::test_support::test_name(
776                module_path!(),
777                "the_cap_counts_every_child_holding_processes_and_names_them",
778            ))
779            .env(MARKER, "1")
780            .isolated_store(directory.path())
781            .run();
782            return;
783        }
784        let _writer = crate::database::install_isolated_test_writer();
785        let parent = super::super::test_support::checkpoint_test_session("parent-1");
786        crate::database::save_session(&parent).unwrap();
787        let children = [
788            ("aaaaaaaa-idle", "Audit the lockfile", SessionState::Running),
789            ("bbbbbbbb-busy", "Run the suite", SessionState::Running),
790            ("cccccccc-park", "Map the parser", SessionState::Parked),
791            ("dddddddd-done", "Old task", SessionState::Stopped),
792        ];
793        for (id, title, state) in children {
794            let mut child = super::super::test_support::checkpoint_test_session(id);
795            child.state = state;
796            child.session_title_override = Some(title.into());
797            crate::database::save_subagent_session(
798                &child,
799                &SubagentRecord {
800                    child_session_id: id.into(),
801                    parent_session_id: "parent-1".into(),
802                    task_name: title.into(),
803                    profile_id: "codex".into(),
804                    model: None,
805                    effort: None,
806                    working_directory: PathBuf::new(),
807                    initial_prompt: "do it".into(),
808                    request_key: format!("request-{id}"),
809                    created_at: "2026-09-25T00:00:00Z".into(),
810                    noticed_turn: None,
811                    handback_tool: true,
812                },
813            )
814            .unwrap();
815        }
816        let mut controller = Controller {
817            config: mj_core::config::Config::default(),
818            state: crate::database::load_state().unwrap(),
819        };
820        controller.config.subagents.max_concurrent = 2;
821
822        // Two live children fill a cap of two, idle or not.
823        let refusal = controller
824            .ensure_subagent_slot_available("parent-1", None)
825            .unwrap_err()
826            .to_string();
827        assert!(
828            refusal.contains("already has 2 live sub-agents and the maximum is 2"),
829            "{refusal}"
830        );
831        assert!(
832            refusal.contains("aaaaaaaa \"Audit the lockfile\"")
833                && refusal.contains("bbbbbbbb \"Run the suite\""),
834            "the refusal names every live child: {refusal}"
835        );
836        assert!(
837            !refusal.contains("Map the parser") && !refusal.contains("Old task"),
838            "parked and stopped children hold no processes: {refusal}"
839        );
840        assert!(
841            refusal.contains("hands back")
842                && refusal.contains("parked")
843                && refusal.contains("close it"),
844            "the refusal says how a slot frees up: {refusal}"
845        );
846        // Starting the parked child again is refused the same way.
847        assert!(
848            controller
849                .ensure_subagent_slot_available("parent-1", Some("cccccccc-park"))
850                .is_err()
851        );
852        // Input to a live child starts nothing, so the cap never refuses it.
853        controller
854            .ensure_subagent_slot_available("parent-1", Some("aaaaaaaa-idle"))
855            .unwrap();
856
857        // Once one live child is parked, a spawn and a restart both fit.
858        controller
859            .state
860            .sessions
861            .get_mut("aaaaaaaa-idle")
862            .unwrap()
863            .state = SessionState::Parked;
864        controller
865            .ensure_subagent_slot_available("parent-1", None)
866            .unwrap();
867        controller
868            .ensure_subagent_slot_available("parent-1", Some("cccccccc-park"))
869            .unwrap();
870    }
871
872    #[test]
873    fn borrowed_bare_locator_gets_a_private_worker_identity() {
874        let locator = mj_core::state::TargetLocator::LocalBare {
875            worker_root: PathBuf::from("/workers/parent"),
876        };
877        assert_eq!(
878            borrowed_locator(&locator, "parent", "child").unwrap(),
879            mj_core::state::TargetLocator::LocalBare {
880                worker_root: PathBuf::from("/workers/child")
881            }
882        );
883    }
884
885    #[test]
886    fn borrowed_ssh_locator_keeps_parent_workspace_with_private_worker_identity() {
887        let locator = mj_core::state::TargetLocator::SshBare {
888            host: "builder".into(),
889            workspace: PathBuf::from(".local/share/hel/workspaces/parent-session"),
890            worker_id: None,
891        };
892        assert_eq!(
893            borrowed_locator(&locator, "parent-session", "child-session").unwrap(),
894            mj_core::state::TargetLocator::SshBare {
895                host: "builder".into(),
896                workspace: PathBuf::from(".local/share/hel/workspaces/parent-session"),
897                worker_id: Some("child-session".into()),
898            }
899        );
900    }
901}