brokk-mj-controller 2.22.0

Daemon-side controller, session manager, and web server for Mjolnir
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
//! Registration and ownership rules for child sessions on a parent's target.

use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail, ensure};

use super::{Controller, now};
use mj_core::config::HarnessKind;
use mj_core::state::{SessionRecord, SessionState, new_session_id};
use mj_core::subagent::SubagentRecord;

#[derive(Debug, Clone)]
pub struct RegisterSubagentRequest {
    pub parent_session_id: String,
    pub task_name: String,
    pub profile_id: String,
    pub model: Option<String>,
    pub effort: Option<String>,
    /// Empty means the parent's working directory. An absolute path is used
    /// as-is; a relative path is resolved against the parent's working
    /// directory. The path is interpreted on the parent's target and must
    /// exist there; no other restriction applies.
    pub working_directory: PathBuf,
    pub initial_prompt: String,
    pub request_key: String,
    /// The absolute directory on the parent's target that holds its
    /// children's report directories, from [`Controller::prepare_subagent_report_root`].
    /// `None` registers a child without one.
    pub report_root: Option<String>,
}

/// Creates a report directory on a target and prints its absolute path.
///
/// `$1` is the directory, which may be relative to the login home the way an
/// SSH or EC2 workspace is. `$2`, when not empty, is a repository whose
/// `info/exclude` must list [`mj_core::subagent::PROJECT_REPORT_ROOT_DIR`], so a
/// report root inside a bare project never shows in `git status`. A directory
/// that is not a repository has no status to keep clean. The absolute path is
/// what the parent and child are told, because neither runs in the login home.
const PREPARE_REPORT_DIR_SCRIPT: &str = r#"set -eu
cd
mkdir -p -- "$1"
if [ -n "$2" ] && exclude=$(git -C "$2" rev-parse --git-path info/exclude 2>/dev/null); then
  case "$exclude" in /*) ;; *) exclude="$2/$exclude" ;; esac
  line="/$3/"
  if ! grep -qxF -- "$line" "$exclude" 2>/dev/null; then
    mkdir -p -- "$(dirname -- "$exclude")"
    if [ -s "$exclude" ] && [ -n "$(tail -c 1 -- "$exclude")" ]; then
      printf '
' >> "$exclude"
    fi
    printf '%s
' "$line" >> "$exclude"
  fi
fi
cd -- "$1"
pwd -P
"#;

/// The argv that runs [`PREPARE_REPORT_DIR_SCRIPT`] for `directory`, adding
/// the exclude line to `exclude_in` when given.
fn prepare_report_dir_argv(directory: &str, exclude_in: Option<&str>) -> Vec<String> {
    vec![
        "sh".into(),
        "-c".into(),
        PREPARE_REPORT_DIR_SCRIPT.into(),
        "sh".into(),
        directory.into(),
        exclude_in.unwrap_or_default().into(),
        mj_core::subagent::PROJECT_REPORT_ROOT_DIR.into(),
    ]
}

/// Run [`PREPARE_REPORT_DIR_SCRIPT`] on `backend` and return the absolute
/// directory it printed.
fn prepare_report_dir(
    executor: &impl mj_core::targets::CommandExecutor,
    backend: &mj_core::targets::TargetLocator,
    session_id: &str,
    directory: &str,
    exclude_in: Option<&str>,
) -> Result<String> {
    let command = mj_core::targets::command_on_locator(
        backend,
        session_id,
        prepare_report_dir_argv(directory, exclude_in),
        "create the sub-agent report directory",
    )?;
    let output = super::execute_checked(executor, command)?;
    let absolute = String::from_utf8(output.stdout)
        .context("the sub-agent report directory is not UTF-8")?
        .trim_end_matches('\n')
        .to_owned();
    ensure!(
        absolute.starts_with('/'),
        "the target did not report an absolute sub-agent report directory: {absolute:?}"
    );
    Ok(absolute)
}

impl Controller {
    /// Create the directory that holds a parent's children's report
    /// directories on the parent's target, and return its absolute path.
    ///
    /// It sits outside every repository: under the workspace root that a
    /// bundle session's repositories are checked out below, or, for a bare
    /// project whose workspace root is the user's own directory, inside the
    /// project under a path its `info/exclude` lists.
    pub fn prepare_subagent_report_root(
        &self,
        parent_session_id: &str,
        executor: &impl mj_core::targets::CommandExecutor,
    ) -> Result<String> {
        let parent = self
            .state
            .sessions
            .get(parent_session_id)
            .with_context(|| format!("unknown parent session {parent_session_id}"))?;
        let locator = parent
            .target
            .as_ref()
            .context("parent session has no live target")?;
        let backend = super::backend::backend_locator(locator, parent, &self.config)?;
        let (root, exclude_in) = subagent_report_root(parent, &backend);
        prepare_report_dir(
            executor,
            &backend,
            parent_session_id,
            &root,
            exclude_in.as_deref(),
        )
    }

    /// Create a registered child's own report directory on its target. A
    /// child registered without one has nothing to create.
    pub(super) fn prepare_subagent_report_dir(
        &self,
        session_id: &str,
        backend: &mj_core::targets::TargetLocator,
        executor: &impl mj_core::targets::CommandExecutor,
    ) -> Result<()> {
        if crate::database::load_subagent(session_id)?.is_none() {
            return Ok(());
        }
        let Some(directory) = crate::database::load_subagent_report(session_id)?.report_dir else {
            return Ok(());
        };
        prepare_report_dir(executor, backend, session_id, &directory, None)?;
        Ok(())
    }

    /// Register a child without provisioning another target or checkout.
    pub fn register_subagent(
        &mut self,
        request: RegisterSubagentRequest,
    ) -> Result<SubagentRecord> {
        if let Some(existing) = crate::database::lookup_subagent_request(
            &request.parent_session_id,
            &request.request_key,
        )? {
            return Ok(existing);
        }
        ensure!(
            !request.request_key.trim().is_empty(),
            "sub-agent request key cannot be empty"
        );
        ensure!(
            !request.task_name.trim().is_empty(),
            "sub-agent task name cannot be empty"
        );
        ensure!(
            !request.initial_prompt.trim().is_empty(),
            "sub-agent instructions cannot be empty"
        );
        let parent = self
            .state
            .sessions
            .get(&request.parent_session_id)
            .with_context(|| format!("unknown parent session {}", request.parent_session_id))?
            .clone();
        ensure!(
            matches!(
                parent.harness_kind,
                HarnessKind::Claude | HarnessKind::Codex
            ),
            "only Claude and Codex sessions can spawn sub-agents"
        );
        ensure_parent_may_delegate(&parent)?;
        ensure!(parent.state.is_active(), "parent session is not active");
        ensure!(parent.target.is_some(), "parent session has no live target");
        ensure!(
            crate::database::load_subagent(&parent.id)?.is_none(),
            "sub-agents cannot spawn other sub-agents"
        );
        ensure!(
            self.config
                .subagents
                .profile_is_eligible(&parent.last_profile, &request.profile_id),
            "profile {:?} is not eligible for sub-agent use",
            request.profile_id
        );
        let profile = self
            .config
            .enabled_profile(&request.profile_id)
            .with_context(|| {
                format!("sub-agent profile {:?} is unavailable", request.profile_id)
            })?;
        if profile.kind == HarnessKind::Muse {
            let multiple_roots = !parent.additional_mounts.is_empty()
                || (parent.project_directory.is_none()
                    && self
                        .config
                        .bundles
                        .get(&parent.bundle_id)
                        .is_some_and(|bundle| bundle.repositories.len() > 1));
            ensure!(
                !multiple_roots,
                "{} ACP supports one workspace root; this parent exposes multiple roots",
                profile.kind.display_name()
            );
        }
        self.ensure_subagent_slot_available(&parent.id, None)?;

        let child_id = new_session_id()?;
        let target = borrowed_locator(
            parent.target.as_ref().expect("live target checked above"),
            &parent.id,
            &child_id,
        )?;
        let created_at = now();
        let session = SessionRecord {
            target_runtime: Some(parent.target_runtime_settings(&self.config)?.into_owned()),
            launch_base: None,
            launch_branch: None,
            publication: None,
            // A child shares its parent's container, so it shares the build
            // cache that container was created with.
            build_cache: parent.build_cache.clone(),
            // A child never receives the Mjolnir sub-agent tools, so it can
            // never spawn a grandchild.
            mjolnir_subagents: Some(false),
            create_managed_worktree: Some(false),
            archived: false,
            container_cpus: None,
            container_memory: None,
            // A child runs inside its parent's container, so it works in the
            // parent's workspace, including the legacy shared one.
            container_workspace: parent.container_workspace.clone(),
            id: child_id.clone(),
            workspace_id: parent.workspace_id.clone(),
            title: request.task_name.clone(),
            harness_kind: profile.kind,
            last_profile: request.profile_id.clone(),
            bundle_id: parent.bundle_id.clone(),
            project_directory: parent.project_directory.clone(),
            managed_worktree: None,
            target_template_id: parent.target_template_id.clone(),
            resource_allocation: parent.resource_allocation.clone(),
            additional_mounts: parent.additional_mounts.clone(),
            state: SessionState::Provisioning,
            target: Some(target),
            native_session_id: None,
            acp_session_title: None,
            session_title_override: Some(request.task_name.clone()),
            created_at: created_at.clone(),
            updated_at: created_at.clone(),
            viewed_through_event_ordinal: 0,
            draft_input: String::new(),
            last_error: None,
            last_checkpoint_error: None,
            checkpoint: None,
        };
        let handback_tool = child_gets_handback_tool(profile.kind);
        let report_dir = request
            .report_root
            .as_deref()
            .map(|root| format!("{}/{child_id}", root.trim_end_matches('/')));
        // The first prompt names the tool only when the child will have it.
        let initial_prompt = match (handback_tool, &report_dir) {
            (true, Some(report_dir)) => format!(
                "{}\n\n{}",
                mj_core::subagent::handback_prompt_note(report_dir),
                request.initial_prompt
            ),
            _ => request.initial_prompt,
        };
        let relation = SubagentRecord {
            child_session_id: child_id.clone(),
            parent_session_id: parent.id,
            task_name: request.task_name,
            profile_id: request.profile_id,
            model: request.model,
            effort: request.effort,
            working_directory: request.working_directory,
            initial_prompt,
            request_key: request.request_key,
            created_at,
            noticed_turn: None,
            handback_tool,
        };
        crate::database::save_subagent_session(&session, &relation)?;
        if let Some(report_dir) = &report_dir {
            crate::database::record_subagent_report_dir(&child_id, report_dir)?;
        }
        self.state.sessions.insert(child_id, session);
        self.state
            .subagents
            .insert(relation.child_session_id.clone(), relation.clone());
        Ok(relation)
    }

    /// Refuse to start another child process tree for `parent_session_id`
    /// when it already has the maximum number of live children.
    ///
    /// `starting` is the child a `send_input` is about to start again from
    /// parked; it is not counted against itself. A spawn passes `None`.
    ///
    /// Every child whose worker may be holding processes in the parent's
    /// container counts, idle or not: those processes are what the cap
    /// protects (#1161). A parked, stopped, failed or lost child holds none.
    pub fn ensure_subagent_slot_available(
        &self,
        parent_session_id: &str,
        starting: Option<&str>,
    ) -> Result<()> {
        let live = crate::database::list_subagents(parent_session_id)?
            .into_iter()
            .filter(|child| Some(child.child_session_id.as_str()) != starting)
            .filter_map(|child| {
                let session = self.state.sessions.get(&child.child_session_id)?;
                session.state.has_live_worker().then(|| LiveSubagent {
                    child_session_id: child.child_session_id.clone(),
                    title: session.listed_title().to_owned(),
                    state: live_subagent_state(session),
                })
            })
            .collect::<Vec<_>>();
        let maximum = self.config.subagents.max_concurrent;
        ensure!(live.len() < maximum, "{}", slot_refusal(&live, maximum));
        Ok(())
    }
}

/// One child that holds processes on its parent's target, as a cap refusal
/// names it.
struct LiveSubagent {
    child_session_id: String,
    title: String,
    state: &'static str,
}

/// The word a cap refusal uses for a live child's state. An idle child is
/// told apart from a working one, because only an idle child can be closed
/// without losing work.
fn live_subagent_state(session: &SessionRecord) -> &'static str {
    match session.state {
        SessionState::Provisioning => "starting",
        SessionState::Checkpointing => "checkpointing",
        SessionState::Closing | SessionState::Destroying => "stopping",
        SessionState::Disconnected => "disconnected",
        _ => match crate::database::load_materialized_session_summary(&session.id) {
            Ok(Some(summary))
                if matches!(
                    summary.execution,
                    mj_core::state::MaterializedExecutionState::Idle
                ) =>
            {
                "idle"
            }
            _ => "running",
        },
    }
}

/// The refusal a parent model reads when it asks for one child too many: how
/// many are live, the maximum, which ones they are, and how a slot frees up.
fn slot_refusal(live: &[LiveSubagent], maximum: usize) -> String {
    let listed = live
        .iter()
        .map(|child| {
            format!(
                "{} \"{}\" ({})",
                mj_core::state::short_id(&child.child_session_id),
                child.title,
                child.state
            )
        })
        .collect::<Vec<_>>()
        .join(", ");
    format!(
        "this session already has {} live sub-agents and the maximum is {maximum}. \
         Live sub-agents: {listed}. A sub-agent frees its slot when it hands back its \
         report (it is then parked and holds no processes until you send it input) or \
         when you close it.",
        live.len()
    )
}

/// Whether a sub-agent child has handed back its report for its parent's
/// newest task, from what the store holds; see
/// [`mj_core::subagent::has_handed_back`]. A session that is not a child, or
/// that has never finished a turn, has not.
pub fn subagent_has_handed_back(child_session_id: &str) -> Result<bool> {
    let Some(relation) = crate::database::load_subagent(child_session_id)? else {
        return Ok(false);
    };
    // A child is parked only once its turn ended and its parent was told, so
    // whatever the parent was going to get from it, it has.
    if crate::database::load_session_state(child_session_id)? == Some(SessionState::Parked) {
        return Ok(true);
    }
    let Some((execution, active_turn, last_turn)) =
        crate::database::load_materialized_turn_outcome(child_session_id)?
    else {
        return Ok(false);
    };
    let report = crate::database::load_subagent_report(child_session_id)?;
    let working = active_turn.is_some()
        || !matches!(execution, mj_core::state::MaterializedExecutionState::Idle);
    Ok(mj_core::subagent::has_handed_back(
        relation.handback_tool,
        &report,
        working,
        last_turn.as_ref(),
        mj_core::clock::epoch_millis(),
    ))
}

/// What a parent's record keeps about a child its suspend stops: the child's
/// listed title, one line of its task, and whether it had handed back.
pub fn stopped_subagent(
    state: &mj_core::state::State,
    child_session_id: &str,
) -> Result<mj_core::subagent::StoppedSubagent> {
    let relation = state
        .subagents
        .get(child_session_id)
        .with_context(|| format!("unknown sub-agent session {child_session_id}"))?;
    let title = state
        .sessions
        .get(child_session_id)
        .map_or(relation.task_name.as_str(), SessionRecord::listed_title)
        .to_owned();
    let report_dir = crate::database::load_subagent_report(child_session_id)?.report_dir;
    Ok(mj_core::subagent::StoppedSubagent {
        child_session_id: child_session_id.to_owned(),
        title,
        task: mj_core::subagent::task_summary(&relation.initial_prompt, report_dir.as_deref()),
        handed_back: subagent_has_handed_back(child_session_id)?,
    })
}

fn sibling_path(path: &Path, parent_id: &str, child_id: &str) -> Result<PathBuf> {
    ensure!(
        path.ends_with(parent_id),
        "parent target path does not end in its session id"
    );
    Ok(path
        .parent()
        .context("parent target path has no parent")?
        .join(child_id))
}

fn borrowed_locator(
    target: &mj_core::state::TargetLocator,
    parent_id: &str,
    child_id: &str,
) -> Result<mj_core::state::TargetLocator> {
    use mj_core::state::TargetLocator;
    Ok(match target {
        TargetLocator::LocalBare { worker_root } => TargetLocator::LocalBare {
            worker_root: sibling_path(worker_root, parent_id, child_id)?,
        },
        TargetLocator::SshBare {
            host,
            workspace,
            worker_id: _,
        } => TargetLocator::SshBare {
            host: host.clone(),
            workspace: workspace.clone(),
            worker_id: Some(child_id.to_owned()),
        },
        // A container child runs its own worker inside the parent's container
        // and records the parent as the container's owner, so cleanup and
        // whole-target operations stay with the parent.
        TargetLocator::LocalPodman {
            container_id,
            workspace_storage,
            ..
        } => TargetLocator::LocalPodman {
            container_id: container_id.clone(),
            workspace_storage: workspace_storage.clone(),
            borrowed_from: Some(parent_id.to_owned()),
        },
        TargetLocator::LocalDocker { container_id, .. } => TargetLocator::LocalDocker {
            container_id: container_id.clone(),
            borrowed_from: Some(parent_id.to_owned()),
        },
        TargetLocator::AppleContainer { container_id, .. } => TargetLocator::AppleContainer {
            container_id: container_id.clone(),
            borrowed_from: Some(parent_id.to_owned()),
        },
        TargetLocator::SshPodman {
            host,
            container_id,
            workspace_storage,
            ..
        } => TargetLocator::SshPodman {
            host: host.clone(),
            container_id: container_id.clone(),
            workspace_storage: workspace_storage.clone(),
            borrowed_from: Some(parent_id.to_owned()),
        },
        TargetLocator::SshDocker {
            host, container_id, ..
        } => TargetLocator::SshDocker {
            host: host.clone(),
            container_id: container_id.clone(),
            borrowed_from: Some(parent_id.to_owned()),
        },
        // EC2 children keep the parent's locator unchanged, as they did before
        // container borrowing was recorded.
        other @ TargetLocator::AwsEc2 { .. } => other.clone(),
    })
}

/// Whether a child can be given the `handback` tool. Codex takes Mjolnir's MCP
/// servers over ACP; Claude reads them from its staged profile, which every
/// session has. Other harnesses keep reporting through their last message.
fn child_gets_handback_tool(harness: HarnessKind) -> bool {
    matches!(harness, HarnessKind::Codex | HarnessKind::Claude)
}

/// A parent may delegate to Mjolnir children only if its own stored choice
/// says so; `None` means native sub-agents, same as `Some(false)`. A parent
/// using its harness's native delegation never received the Mjolnir tools, so
/// a request from it is stale.
fn ensure_parent_may_delegate(parent: &SessionRecord) -> Result<()> {
    match parent.mjolnir_subagents {
        Some(true) => Ok(()),
        _ => bail!("this session uses native sub-agents"),
    }
}

/// Where a parent's children keep their report directories, before the target
/// resolves it, and the repository whose `info/exclude` must list it.
fn subagent_report_root(
    parent: &SessionRecord,
    backend: &mj_core::targets::TargetLocator,
) -> (String, Option<String>) {
    match &parent.project_directory {
        Some(project) => {
            let project = project.to_string_lossy().trim_end_matches('/').to_owned();
            (
                format!("{project}/{}", mj_core::subagent::PROJECT_REPORT_ROOT_DIR),
                Some(project),
            )
        }
        None => {
            let workspace =
                super::network_git::workspace_root(backend, parent.container_workspace.as_deref());
            (
                format!(
                    "{}/{}",
                    workspace.trim_end_matches('/'),
                    mj_core::subagent::REPORT_ROOT_DIR
                ),
                None,
            )
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn run_prepare_script(directory: &Path, exclude_in: Option<&Path>) -> String {
        let argv = prepare_report_dir_argv(
            &directory.to_string_lossy(),
            exclude_in
                .map(|path| path.to_string_lossy().into_owned())
                .as_deref(),
        );
        let output = std::process::Command::new(&argv[0])
            .args(&argv[1..])
            .output()
            .expect("run the report directory script");
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8(output.stdout)
            .unwrap()
            .trim_end()
            .to_owned()
    }

    /// A bare project's report root is inside the project, so the script
    /// lists it in the repository's `info/exclude` exactly once and the
    /// project's `git status` stays clean.
    #[test]
    fn the_report_directory_script_creates_the_directory_and_keeps_git_status_clean() {
        let temp = tempfile::tempdir().unwrap();
        let project = temp.path().join("project");
        std::fs::create_dir_all(&project).unwrap();
        let git = |args: &[&str]| {
            let output = std::process::Command::new("git")
                .arg("-C")
                .arg(&project)
                .args(args)
                .output()
                .unwrap();
            assert!(output.status.success(), "{output:?}");
            String::from_utf8(output.stdout).unwrap()
        };
        git(&["init", "-q"]);
        // An exclude file without a trailing newline must not have its last
        // line joined to the new one.
        std::fs::write(project.join(".git/info/exclude"), "*.tmp").unwrap();
        let root = project.join(mj_core::subagent::PROJECT_REPORT_ROOT_DIR);
        let printed = run_prepare_script(&root, Some(&project));
        assert_eq!(
            Path::new(&printed),
            root.canonicalize().unwrap(),
            "the script prints the absolute directory"
        );
        run_prepare_script(&root, Some(&project));
        std::fs::write(root.join("report.md"), "details").unwrap();
        let exclude = std::fs::read_to_string(project.join(".git/info/exclude")).unwrap();
        assert_eq!(exclude, "*.tmp\n/.mj/agents/\n");
        assert_eq!(git(&["status", "--porcelain", "--ignored=no"]), "");

        // Outside a repository there is no exclude to write.
        let plain = temp.path().join("plain");
        std::fs::create_dir_all(&plain).unwrap();
        let reports = plain.join(".mj/agents/child");
        run_prepare_script(&reports, Some(&plain));
        assert!(reports.is_dir());
    }

    #[test]
    fn a_report_root_is_under_the_workspace_or_inside_a_bare_project() {
        let mut parent = super::super::test_support::checkpoint_test_session("parent-1");
        let backend = mj_core::targets::TargetLocator::LocalBare {
            worker_root: "/var/lib/hel/workers/parent-1".into(),
        };
        parent.project_directory = None;
        assert_eq!(
            subagent_report_root(&parent, &backend),
            ("/var/lib/hel/workers/parent-1/.mj-agents".to_owned(), None)
        );
        parent.project_directory = Some("/home/dev/project/".into());
        assert_eq!(
            subagent_report_root(&parent, &backend),
            (
                "/home/dev/project/.mj/agents".to_owned(),
                Some("/home/dev/project".to_owned())
            )
        );
    }

    #[test]
    fn a_container_child_borrows_its_parents_container() {
        use mj_core::state::{PodmanWorkspaceLocator, TargetLocator};

        let parent_id = "0123456789abcdef0123456789abcdef";
        let child_id = "fedcba9876543210fedcba9876543210";
        let container = mj_core::targets::resource_name(parent_id).unwrap();

        let local = borrowed_locator(
            &TargetLocator::LocalPodman {
                container_id: container.clone(),
                workspace_storage: PodmanWorkspaceLocator::Volume {
                    name: "parent-volume".to_owned(),
                },
                borrowed_from: None,
            },
            parent_id,
            child_id,
        )
        .unwrap();
        assert_eq!(
            local,
            TargetLocator::LocalPodman {
                container_id: container.clone(),
                workspace_storage: PodmanWorkspaceLocator::Volume {
                    name: "parent-volume".to_owned(),
                },
                borrowed_from: Some(parent_id.to_owned()),
            }
        );

        let remote = borrowed_locator(
            &TargetLocator::SshPodman {
                host: "builder".to_owned(),
                container_id: container.clone(),
                workspace_storage: PodmanWorkspaceLocator::ContainerLayer,
                borrowed_from: None,
            },
            parent_id,
            child_id,
        )
        .unwrap();
        assert_eq!(
            remote,
            TargetLocator::SshPodman {
                host: "builder".to_owned(),
                container_id: container,
                workspace_storage: PodmanWorkspaceLocator::ContainerLayer,
                borrowed_from: Some(parent_id.to_owned()),
            }
        );
    }

    #[test]
    fn a_parent_using_native_delegation_cannot_spawn_mjolnir_children() {
        let parent = |choice| {
            let mut session = crate::controller::test_support::checkpoint_test_session("parent");
            session.mjolnir_subagents = choice;
            session
        };

        assert_eq!(
            ensure_parent_may_delegate(&parent(Some(false)))
                .unwrap_err()
                .to_string(),
            "this session uses native sub-agents"
        );
        assert_eq!(
            ensure_parent_may_delegate(&parent(None))
                .unwrap_err()
                .to_string(),
            "this session uses native sub-agents"
        );
        assert!(ensure_parent_may_delegate(&parent(Some(true))).is_ok());
    }

    /// #1161: idle children held the processes that exhausted their parent's
    /// container, yet did not count against the cap. Every child that holds
    /// processes counts now; a parked one does not. The refusal is what the
    /// parent model reads, so it names the live children and how to free a
    /// slot.
    #[test]
    fn the_cap_counts_every_child_holding_processes_and_names_them() {
        const MARKER: &str = "MJ_TEST_SUBAGENT_CAP_CHILD";
        if std::env::var_os(MARKER).is_none() {
            let directory = tempfile::tempdir().unwrap();
            super::super::test_support::IsolatedTest::new(super::super::test_support::test_name(
                module_path!(),
                "the_cap_counts_every_child_holding_processes_and_names_them",
            ))
            .env(MARKER, "1")
            .isolated_store(directory.path())
            .run();
            return;
        }
        let _writer = crate::database::install_isolated_test_writer();
        let parent = super::super::test_support::checkpoint_test_session("parent-1");
        crate::database::save_session(&parent).unwrap();
        let children = [
            ("aaaaaaaa-idle", "Audit the lockfile", SessionState::Running),
            ("bbbbbbbb-busy", "Run the suite", SessionState::Running),
            ("cccccccc-park", "Map the parser", SessionState::Parked),
            ("dddddddd-done", "Old task", SessionState::Stopped),
        ];
        for (id, title, state) in children {
            let mut child = super::super::test_support::checkpoint_test_session(id);
            child.state = state;
            child.session_title_override = Some(title.into());
            crate::database::save_subagent_session(
                &child,
                &SubagentRecord {
                    child_session_id: id.into(),
                    parent_session_id: "parent-1".into(),
                    task_name: title.into(),
                    profile_id: "codex".into(),
                    model: None,
                    effort: None,
                    working_directory: PathBuf::new(),
                    initial_prompt: "do it".into(),
                    request_key: format!("request-{id}"),
                    created_at: "2026-09-25T00:00:00Z".into(),
                    noticed_turn: None,
                    handback_tool: true,
                },
            )
            .unwrap();
        }
        let mut controller = Controller {
            config: mj_core::config::Config::default(),
            state: crate::database::load_state().unwrap(),
        };
        controller.config.subagents.max_concurrent = 2;

        // Two live children fill a cap of two, idle or not.
        let refusal = controller
            .ensure_subagent_slot_available("parent-1", None)
            .unwrap_err()
            .to_string();
        assert!(
            refusal.contains("already has 2 live sub-agents and the maximum is 2"),
            "{refusal}"
        );
        assert!(
            refusal.contains("aaaaaaaa \"Audit the lockfile\"")
                && refusal.contains("bbbbbbbb \"Run the suite\""),
            "the refusal names every live child: {refusal}"
        );
        assert!(
            !refusal.contains("Map the parser") && !refusal.contains("Old task"),
            "parked and stopped children hold no processes: {refusal}"
        );
        assert!(
            refusal.contains("hands back")
                && refusal.contains("parked")
                && refusal.contains("close it"),
            "the refusal says how a slot frees up: {refusal}"
        );
        // Starting the parked child again is refused the same way.
        assert!(
            controller
                .ensure_subagent_slot_available("parent-1", Some("cccccccc-park"))
                .is_err()
        );
        // Input to a live child starts nothing, so the cap never refuses it.
        controller
            .ensure_subagent_slot_available("parent-1", Some("aaaaaaaa-idle"))
            .unwrap();

        // Once one live child is parked, a spawn and a restart both fit.
        controller
            .state
            .sessions
            .get_mut("aaaaaaaa-idle")
            .unwrap()
            .state = SessionState::Parked;
        controller
            .ensure_subagent_slot_available("parent-1", None)
            .unwrap();
        controller
            .ensure_subagent_slot_available("parent-1", Some("cccccccc-park"))
            .unwrap();
    }

    #[test]
    fn borrowed_bare_locator_gets_a_private_worker_identity() {
        let locator = mj_core::state::TargetLocator::LocalBare {
            worker_root: PathBuf::from("/workers/parent"),
        };
        assert_eq!(
            borrowed_locator(&locator, "parent", "child").unwrap(),
            mj_core::state::TargetLocator::LocalBare {
                worker_root: PathBuf::from("/workers/child")
            }
        );
    }

    #[test]
    fn borrowed_ssh_locator_keeps_parent_workspace_with_private_worker_identity() {
        let locator = mj_core::state::TargetLocator::SshBare {
            host: "builder".into(),
            workspace: PathBuf::from(".local/share/hel/workspaces/parent-session"),
            worker_id: None,
        };
        assert_eq!(
            borrowed_locator(&locator, "parent-session", "child-session").unwrap(),
            mj_core::state::TargetLocator::SshBare {
                host: "builder".into(),
                workspace: PathBuf::from(".local/share/hel/workspaces/parent-session"),
                worker_id: Some("child-session".into()),
            }
        );
    }
}