brokk-mj-controller 2.29.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
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
use super::*;
use crate::targets::CommandOutput;

/// Add lifecycle guidance only for targets that Hel destroys as a whole.
pub(super) fn append_hel_target_environment(
    harness: mj_core::config::HarnessKind,
    destination: &Path,
    target: &targets::TargetLocator,
) -> Result<()> {
    let environment = match target {
        targets::TargetLocator::LocalPodman { .. }
        | targets::TargetLocator::LocalDocker { .. }
        | targets::TargetLocator::AppleContainer { .. }
        | targets::TargetLocator::SshPodman { .. }
        | targets::TargetLocator::SshDocker { .. } => MJ_CONTAINER_ENVIRONMENT.to_owned(),
        targets::TargetLocator::AwsEc2 { workspace, .. } => format!(
            "## Mjolnir disposable environment\n\nThis session runs on a disposable Mjolnir EC2 instance. When the session closes, Mjolnir checkpoints everything in project workspace directories under `$HOME/{workspace}`, including committed work, staged and unstaged changes, and untracked files. Mjolnir then terminates the instance.\n\nEverything outside `$HOME/{workspace}`, including installed packages, the rest of `$HOME`, and `/tmp`, is ephemeral and will be lost. Keep durable results in the workspace or push them to a remote.\n\nNew workspaces start on their own session branch from the default network fetch remote’s default branch. Local unpublished commits and uncommitted files are not copied. Use normal git push to publish the current branch to the configured network push destination. Closing saves a checkpoint; it does not publish commits or update the original local checkout. Resumed sessions restore their saved work.\n"
        ),
        targets::TargetLocator::LocalBare { .. } | targets::TargetLocator::SshBare { .. } => {
            return Ok(());
        }
    };
    append_staged_instructions(harness, destination, &environment)
}

pub(super) fn append_container_storage_guidance(
    harness: HarnessKind,
    destination: &Path,
    target: &targets::TargetLocator,
    workspace: Option<&Path>,
    native_temporary_storage: bool,
) -> Result<()> {
    let podman_workspace = match target {
        targets::TargetLocator::LocalPodman {
            workspace_storage, ..
        }
        | targets::TargetLocator::SshPodman {
            workspace_storage, ..
        } => Some(workspace_storage),
        targets::TargetLocator::LocalDocker { .. } | targets::TargetLocator::SshDocker { .. } => {
            None
        }
        _ => return Ok(()),
    };
    let heading = "## Mjolnir container storage\n\n";
    let mut guidance = String::from(heading);
    if native_temporary_storage {
        guidance.push_str("`/tmp` is a private disk-backed volume outside the container's writable overlay. Use it for disposable temporary files. Its contents are excluded from checkpoints and are lost when the session stops or restarts.\n\n");
    }
    if podman_workspace
        .is_some_and(|storage| !matches!(storage, targets::PodmanWorkspaceLocator::ContainerLayer))
    {
        let workspace = targets::container_workspace_root(workspace);
        guidance.push_str(&format!(
            "The workspace storage is mounted at `{workspace}`. "
        ));
        if workspace != targets::CONTAINER_WORKSPACE {
            guidance.push_str(
                "The parent `/workspace` directory itself is on the container's writable overlay. ",
            );
        }
        guidance.push_str("Keep durable results inside the project repository directories; arbitrary files elsewhere on the workspace volume are not checkpointed.\n");
    }
    if guidance == heading {
        return Ok(());
    }
    append_staged_instructions(harness, destination, &guidance)
}

pub(super) fn append_subagent_policy(
    harness: mj_core::config::HarnessKind,
    destination: &Path,
    policy: &mj_core::subagent::SubagentPolicy,
    limit: usize,
) -> Result<()> {
    if matches!(
        policy,
        mj_core::subagent::SubagentPolicy::SingleModel { .. }
    ) {
        append_staged_instructions(
            harness,
            destination,
            &mj_core::subagent::delegation_policy(limit),
        )?;
    }
    Ok(())
}

pub(super) fn append_staged_instructions(
    harness: mj_core::config::HarnessKind,
    destination: &Path,
    text: &str,
) -> Result<()> {
    let path = destination.join(harness.agent_instructions_file());
    let separator = match std::fs::read_to_string(&path) {
        Ok(contents) if contents.contains(text) => return Ok(()),
        Ok(contents) if !contents.is_empty() && !contents.ends_with('\n') => "\n\n",
        Ok(contents) if !contents.is_empty() => "\n",
        Ok(_) => "",
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => "",
        Err(error) => return Err(error.into()),
    };
    use std::io::Write;

    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&path)
        .with_context(|| format!("open staged harness instructions {}", path.display()))?;
    file.write_all(separator.as_bytes())?;
    file.write_all(text.as_bytes())?;
    Ok(())
}

pub(super) fn copy_profile_entry(source: &Path, destination: &Path) -> Result<()> {
    copy_profile_entry_within(source, destination, &HashSet::new(), &[])
}

/// [`copy_profile_entry`], leaving out the paths in `excluded`. Each is
/// compared with the path the walk reaches it by, below `source` as given,
/// not with where a link resolves.
pub(super) fn copy_profile_entry_except(
    source: &Path,
    destination: &Path,
    excluded: &[PathBuf],
) -> Result<()> {
    copy_profile_entry_within(source, destination, &HashSet::new(), excluded)
}

/// Copy one profile entry, following symlinks so a profile home that links its
/// settings or instructions elsewhere still stages their contents. `entered`
/// holds the canonical paths of the directories already entered on this branch
/// of the recursion, which stops a symlinked directory cycle.
pub(super) fn copy_profile_entry_within(
    source: &Path,
    destination: &Path,
    entered: &HashSet<PathBuf>,
    excluded: &[PathBuf],
) -> Result<()> {
    std::fs::symlink_metadata(source)
        .with_context(|| format!("read staged profile entry metadata {}", source.display()))?;
    let metadata = match std::fs::metadata(source) {
        Ok(metadata) => metadata,
        // The entry exists but its link target does not; staging the rest of
        // the profile is more useful than failing on a stale link.
        Err(error) if error.kind() == ErrorKind::NotFound => {
            tracing::warn!(
                source = %source.display(),
                "skipping staged profile entry whose symlink target is missing"
            );
            return Ok(());
        }
        Err(error) => {
            return Err(anyhow::Error::new(error).context(format!(
                "read staged profile entry metadata {}",
                source.display()
            )));
        }
    };
    if metadata.is_file() {
        if let Some(parent) = destination.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("create staged profile directory {}", parent.display()))?;
        }
        std::fs::copy(source, destination).with_context(|| {
            format!(
                "copy staged profile file {} to {}",
                source.display(),
                destination.display()
            )
        })?;
        return Ok(());
    }
    if metadata.is_dir() {
        let canonical = std::fs::canonicalize(source)
            .with_context(|| format!("resolve staged profile directory {}", source.display()))?;
        if entered.contains(&canonical) {
            tracing::warn!(
                source = %source.display(),
                target = %canonical.display(),
                "skipping staged profile directory that links back into itself"
            );
            return Ok(());
        }
        let mut entered = entered.clone();
        entered.insert(canonical);
        std::fs::create_dir_all(destination).with_context(|| {
            format!("create staged profile directory {}", destination.display())
        })?;
        let entries = std::fs::read_dir(source)
            .with_context(|| format!("list staged profile directory {}", source.display()))?
            .collect::<std::io::Result<Vec<_>>>()
            .with_context(|| {
                format!(
                    "read staged profile directory entries in {}",
                    source.display()
                )
            })?;
        // Sibling entries in one directory are independent, so recurse in
        // parallel; this is the level most likely to hold many files (e.g. a
        // skills or plugins tree).
        entries
            .par_iter()
            .filter(|entry| !excluded.contains(&entry.path()))
            .try_for_each(|entry| {
                copy_profile_entry_within(
                    &entry.path(),
                    &destination.join(entry.file_name()),
                    &entered,
                    excluded,
                )
            })?;
        std::fs::set_permissions(destination, metadata.permissions()).with_context(|| {
            format!(
                "set permissions for staged profile directory {}",
                destination.display()
            )
        })?;
    }
    Ok(())
}

// Container copies may be root-owned while the worker directory belongs to a
// different user. Run this ownership-only operation as container root; normal
// Podman execs inherit the user recorded when each container was created.
pub(in crate::controller) fn container_upload_ownership_args(
    engine: &str,
    container_id: &str,
    worker_root: &str,
    paths: &[&str],
) -> Vec<String> {
    let root_user = if engine == "podman" { "0:0" } else { "0" };
    let mut args = vec![
        "exec".into(),
        "--user".into(),
        root_user.into(),
        container_id.into(),
        "sh".into(),
        "-c".into(),
        // GNU and BusyBox stat both support this numeric ownership format.
        r#"set -eu; owner=$(stat -c '%u:%g' -- "$1"); shift; chown -R "$owner" -- "$@""#.into(),
        "sh".into(),
        worker_root.into(),
    ];
    args.extend(paths.iter().map(|path| (*path).to_owned()));
    args
}

/// Link every mbx lookup to the one policy already reachable through the
/// shared cache mount. File symlinks follow atomic replacements at the source.
const MBX_CONFIG_SCRIPT: &str = r#"set -eu
source=$1
shift
[ -r "$source/config.toml" ] || { echo 'shared machine mbx configuration is missing' >&2; exit 1; }
for root in "$HOME/.config" "$@"; do
    mkdir -p -- "$root/mbx"
    link="$root/mbx/.config.mj-$$"
    ln -s -- "$source/config.toml" "$link"
    mv -Tf -- "$link" "$root/mbx/config.toml"
done
"#;

const CHECK_LEGACY_MBX_AND_LINK_CONFIG_SCRIPT: &str = r#"set -eu
bin=$1 source=$2
shift 2
scheme=new
if [ -f "$bin/mbx" ]; then
    if grep -Fqx '# mjolnir-mbx-shim' "$bin/mbx"; then
        scheme=new
    else
        grep_status=$?
        case "$grep_status" in
            1) scheme=legacy ;;
            *)
                echo "could not inspect the Mjolnir mbx shim marker in $bin/mbx (grep exited $grep_status)" >&2
                exit 1
                ;;
        esac
    fi
fi
if [ "$scheme" = legacy ]; then
    [ -r "$source/config.toml" ] || { echo 'shared machine mbx configuration is missing' >&2; exit 1; }
    for root in "$HOME/.config" "$@"; do
        mkdir -p -- "$root/mbx"
        link="$root/mbx/.config.mj-$$"
        ln -s -- "$source/config.toml" "$link"
        mv -Tf -- "$link" "$root/mbx/config.toml"
    done
    printf 'legacy'
else
    printf 'new'
fi
"#;

const INSTALL_MBX_SHIMS_SCRIPT: &str = r#"set -eu
bin=$1 cargo_body=$2 mbx_body=$3
mkdir -p -- "$bin"
write_shim() {
    target=$1 body=$2
    temporary=$(mktemp "${target}.mj-XXXXXX")
    trap 'rm -f -- "$temporary"' EXIT HUP INT TERM
    {
        printf '%s\n' '#!/bin/sh' '# mjolnir-mbx-shim'
        printf '%s\n' "$body"
    } >"$temporary"
    chmod 755 -- "$temporary"
    mv -f -- "$temporary" "$target"
    trap - EXIT HUP INT TERM
}
write_shim "$bin/cargo" "$cargo_body"
write_shim "$bin/mbx" "$mbx_body"
"#;

const REMOVE_MBX_SHIMS_SCRIPT: &str = r#"set -eu
bin=$1
for name in cargo mbx; do
    path="$bin/$name"
    if [ -f "$path" ] && [ ! -L "$path" ] && grep -Fqx '# mjolnir-mbx-shim' "$path"; then
        rm -f -- "$path"
    fi
done
"#;

/// Install marked Cargo and mbx launchers that use the shared cache copy.
pub(super) fn install_mbx_shims(
    executor: &impl CommandExecutor,
    locator: &targets::TargetLocator,
    worker_root: &str,
    mbx_binary: &Path,
    configuration: &Path,
    config_roots: &[PathBuf],
) -> Result<()> {
    ensure!(
        mbx_binary.is_absolute(),
        "shared cache mbx path is not absolute: {}",
        mbx_binary.display()
    );
    let bin = format!("{worker_root}/bin");
    let (engine, container_id, ssh) = match locator {
        targets::TargetLocator::LocalPodman { container_id, .. } => ("podman", container_id, None),
        targets::TargetLocator::LocalDocker { container_id, .. } => ("docker", container_id, None),
        targets::TargetLocator::SshPodman {
            ssh, container_id, ..
        } => ("podman", container_id, Some(ssh)),
        targets::TargetLocator::SshDocker {
            ssh, container_id, ..
        } => ("docker", container_id, Some(ssh)),
        targets::TargetLocator::LocalBare { .. }
        | targets::TargetLocator::AppleContainer { .. }
        | targets::TargetLocator::AwsEc2 { .. }
        | targets::TargetLocator::SshBare { .. } => {
            bail!("the build cache is only installed into Podman and Docker containers")
        }
    };
    let quoted_binary = targets::posix_quote(&mbx_binary.to_string_lossy());
    let cargo_body = format!(
        "MBX_CARGO_SHIM_MODE=1\nMBX_CARGO_SHIM_PATH=$(command -v \"$0\")\nexport MBX_CARGO_SHIM_MODE MBX_CARGO_SHIM_PATH\nexec {quoted_binary} \"$@\""
    );
    let mbx_body = format!("exec {quoted_binary} \"$@\"");
    let args = vec![
        engine.to_owned(),
        "exec".to_owned(),
        container_id.clone(),
        "sh".to_owned(),
        "-c".to_owned(),
        INSTALL_MBX_SHIMS_SCRIPT.to_owned(),
        "sh".to_owned(),
        bin,
        cargo_body,
        mbx_body,
    ];
    let command = match ssh {
        None => CommandSpec::new(args[0].clone(), args[1..].iter().cloned()),
        Some(ssh) => crate::targets::ssh_command(ssh, args),
    }
    .purpose("install the shared-cache mbx shims")
    .stage(ProvisionStage::Syncing);
    execute_checked(executor, command)?;
    link_mbx_configuration(executor, locator, configuration, config_roots)
}

pub(super) fn remove_generated_mbx_shims(
    executor: &impl CommandExecutor,
    locator: &targets::TargetLocator,
    worker_root: &str,
) -> Result<()> {
    let (engine, container_id, ssh) = match locator {
        targets::TargetLocator::LocalPodman { container_id, .. } => ("podman", container_id, None),
        targets::TargetLocator::LocalDocker { container_id, .. } => ("docker", container_id, None),
        targets::TargetLocator::SshPodman {
            ssh, container_id, ..
        } => ("podman", container_id, Some(ssh)),
        targets::TargetLocator::SshDocker {
            ssh, container_id, ..
        } => ("docker", container_id, Some(ssh)),
        targets::TargetLocator::LocalBare { .. }
        | targets::TargetLocator::AppleContainer { .. }
        | targets::TargetLocator::AwsEc2 { .. }
        | targets::TargetLocator::SshBare { .. } => {
            bail!("the build cache is only installed into Podman and Docker containers")
        }
    };
    let args = vec![
        engine.to_owned(),
        "exec".to_owned(),
        container_id.clone(),
        "sh".to_owned(),
        "-c".to_owned(),
        REMOVE_MBX_SHIMS_SCRIPT.to_owned(),
        "sh".to_owned(),
        format!("{worker_root}/bin"),
    ];
    let container_command = match ssh {
        None => CommandSpec::new(args[0].clone(), args[1..].iter().cloned()),
        Some(ssh) => crate::targets::ssh_command(ssh, args),
    }
    .purpose("remove marked mbx shims after cache verification failed")
    .stage(ProvisionStage::Syncing);
    execute_checked(executor, container_command)?;
    Ok(())
}

pub(super) fn verify_mbx_binary(
    executor: &impl CommandExecutor,
    locator: &targets::TargetLocator,
    mbx_binary: &Path,
    expected_version: &str,
) -> Result<()> {
    ensure!(
        mbx_binary.is_absolute(),
        "shared cache mbx path is not absolute: {}",
        mbx_binary.display()
    );
    let (engine, container_id, ssh) = match locator {
        targets::TargetLocator::LocalPodman { container_id, .. } => ("podman", container_id, None),
        targets::TargetLocator::LocalDocker { container_id, .. } => ("docker", container_id, None),
        targets::TargetLocator::SshPodman {
            ssh, container_id, ..
        } => ("podman", container_id, Some(ssh)),
        targets::TargetLocator::SshDocker {
            ssh, container_id, ..
        } => ("docker", container_id, Some(ssh)),
        targets::TargetLocator::LocalBare { .. }
        | targets::TargetLocator::AppleContainer { .. }
        | targets::TargetLocator::AwsEc2 { .. }
        | targets::TargetLocator::SshBare { .. } => {
            bail!("the build cache is only installed into Podman and Docker containers")
        }
    };
    let args = vec![
        engine.to_owned(),
        "exec".to_owned(),
        container_id.clone(),
        mbx_binary.to_string_lossy().into_owned(),
        "--version".to_owned(),
    ];
    let command = match ssh {
        None => CommandSpec::new(args[0].clone(), args[1..].iter().cloned()),
        Some(ssh) => crate::targets::ssh_command(ssh, args),
    }
    .purpose("verify the synchronized mbx inside the session container")
    .stage(ProvisionStage::Syncing);
    let output = executor.execute(&command)?;
    let container_version = reported_mbx_version(output, &command)?;
    ensure!(
        expected_version == container_version,
        "the container reports mbx {container_version}, but the synchronized host copy is mbx {expected_version}"
    );
    Ok(())
}

fn reported_mbx_version(output: CommandOutput, command: &CommandSpec) -> Result<String> {
    ensure!(
        output.status == 0,
        "{} failed with status {}: {}",
        command.purpose,
        output.status,
        String::from_utf8_lossy(&output.stderr).trim()
    );
    String::from_utf8_lossy(&output.stdout)
        .split_whitespace()
        .next_back()
        .map(str::to_owned)
        .context("mbx --version returned no version")
}

/// Upgrade configuration without touching an executable a live build may use.
pub(super) fn link_mbx_configuration(
    executor: &impl CommandExecutor,
    locator: &targets::TargetLocator,
    configuration: &Path,
    config_roots: &[PathBuf],
) -> Result<()> {
    let (engine, container_id, ssh) = match locator {
        targets::TargetLocator::LocalPodman { container_id, .. } => ("podman", container_id, None),
        targets::TargetLocator::LocalDocker { container_id, .. } => ("docker", container_id, None),
        targets::TargetLocator::SshPodman {
            ssh, container_id, ..
        } => ("podman", container_id, Some(ssh)),
        targets::TargetLocator::SshDocker {
            ssh, container_id, ..
        } => ("docker", container_id, Some(ssh)),
        targets::TargetLocator::LocalBare { .. }
        | targets::TargetLocator::AppleContainer { .. }
        | targets::TargetLocator::AwsEc2 { .. }
        | targets::TargetLocator::SshBare { .. } => {
            bail!("the build cache is only installed into Podman and Docker containers")
        }
    };
    {
        let mut args = vec![
            engine.to_owned(),
            "exec".into(),
            "-i".into(),
            container_id.clone(),
            "sh".into(),
            "-c".into(),
            MBX_CONFIG_SCRIPT.to_owned(),
            "mj-mbx-config".into(),
            configuration.to_string_lossy().into_owned(),
        ];
        args.extend(
            config_roots
                .iter()
                .map(|path| path.to_string_lossy().into_owned()),
        );
        let command = match ssh {
            None => CommandSpec::new(args[0].clone(), args[1..].iter().cloned()),
            Some(ssh) => crate::targets::ssh_command(ssh, args),
        }
        .purpose("link the shared machine mbx configuration")
        .stage(ProvisionStage::Syncing);
        execute_checked(executor, command)?;
    }
    Ok(())
}

/// Preserve legacy private mbx installations and link their shared config in
/// the same container command that distinguishes them from generated shims.
pub(super) fn link_legacy_mbx_configuration(
    executor: &impl CommandExecutor,
    locator: &targets::TargetLocator,
    worker_root: &str,
    configuration: &Path,
    config_roots: &[PathBuf],
) -> Result<bool> {
    let (engine, container_id, ssh) = match locator {
        targets::TargetLocator::LocalPodman { container_id, .. } => ("podman", container_id, None),
        targets::TargetLocator::LocalDocker { container_id, .. } => ("docker", container_id, None),
        targets::TargetLocator::SshPodman {
            ssh, container_id, ..
        } => ("podman", container_id, Some(ssh)),
        targets::TargetLocator::SshDocker {
            ssh, container_id, ..
        } => ("docker", container_id, Some(ssh)),
        targets::TargetLocator::LocalBare { .. }
        | targets::TargetLocator::AppleContainer { .. }
        | targets::TargetLocator::AwsEc2 { .. }
        | targets::TargetLocator::SshBare { .. } => {
            bail!("the build cache is only installed into Podman and Docker containers")
        }
    };
    let mut args = vec![
        engine.to_owned(),
        "exec".to_owned(),
        container_id.clone(),
        "sh".to_owned(),
        "-c".to_owned(),
        CHECK_LEGACY_MBX_AND_LINK_CONFIG_SCRIPT.to_owned(),
        "sh".to_owned(),
        format!("{worker_root}/bin"),
        configuration.to_string_lossy().into_owned(),
    ];
    args.extend(
        config_roots
            .iter()
            .map(|path| path.to_string_lossy().into_owned()),
    );
    let container_command = match ssh {
        None => CommandSpec::new(args[0].clone(), args[1..].iter().cloned()),
        Some(ssh) => crate::targets::ssh_command(ssh, args),
    }
    .purpose("inspect legacy mbx and relink its shared configuration")
    .stage(ProvisionStage::Syncing);
    let output = execute_checked(executor, container_command)?;
    match output.stdout.as_slice() {
        b"legacy" => Ok(true),
        b"new" => Ok(false),
        other => bail!(
            "container mbx scheme inspection returned unexpected output: {}",
            String::from_utf8_lossy(other)
        ),
    }
}

#[allow(clippy::too_many_arguments)]
pub(super) fn install_worker_files(
    executor: &impl CommandExecutor,
    locator: &targets::TargetLocator,
    session_id: &str,
    worker_root: &str,
    profile_home: &str,
    worker_binary: &Path,
    launch_config: &Path,
    ownership: &Path,
    profile_stage: &Path,
) -> Result<()> {
    verify_worker_build(worker_binary)?;
    crate::target_storage::ensure_room_for(
        locator,
        [worker_root],
        || super::file_size(worker_binary),
        "install the Mjolnir worker",
    )?;
    match locator {
        targets::TargetLocator::LocalBare { .. } => {
            if profile_stage.is_dir() {
                // A staged home that is a link to a profile home, left for a
                // session an earlier release started there, is replaced by a
                // directory of its own. Copying through it would write this
                // stage over the person's own configuration.
                if std::fs::symlink_metadata(profile_home)
                    .is_ok_and(|metadata| metadata.file_type().is_symlink())
                {
                    std::fs::remove_file(profile_home).with_context(|| {
                        format!("unlink the earlier session's profile home link {profile_home}")
                    })?;
                }
                std::fs::create_dir_all(profile_home).context("create isolated local profile")?;
                for entry in std::fs::read_dir(profile_stage)? {
                    let entry = entry?;
                    copy_profile_entry(
                        &entry.path(),
                        &Path::new(profile_home).join(entry.file_name()),
                    )?;
                }
            }
            for command in [
                CommandSpec::new("mkdir", ["-p", worker_root])
                    .purpose("create local bare worker directory"),
                CommandSpec::new(
                    "cp",
                    [
                        worker_binary.to_string_lossy().into_owned(),
                        format!("{worker_root}/hel"),
                    ],
                )
                .purpose("install local Mjolnir worker"),
                CommandSpec::new(
                    "cp",
                    [
                        launch_config.to_string_lossy().into_owned(),
                        format!("{worker_root}/launch.json"),
                    ],
                )
                .purpose("install local worker launch configuration"),
                CommandSpec::new(
                    "cp",
                    [
                        ownership.to_string_lossy().into_owned(),
                        format!("{worker_root}/ownership.json"),
                    ],
                )
                .purpose("install local worker ownership marker"),
                CommandSpec::new("chmod", ["700", &format!("{worker_root}/hel")])
                    .purpose("make local Mjolnir worker executable"),
            ] {
                execute_checked(executor, command)?;
            }
        }
        targets::TargetLocator::LocalPodman { container_id, .. }
        | targets::TargetLocator::LocalDocker { container_id, .. }
        | targets::TargetLocator::AppleContainer { container_id, .. } => {
            let engine = match locator {
                targets::TargetLocator::LocalPodman { .. } => "podman",
                targets::TargetLocator::LocalDocker { .. } => "docker",
                targets::TargetLocator::AppleContainer { .. } => "container",
                _ => unreachable!("matched local container target"),
            };
            for command in [
                CommandSpec::new(
                    engine,
                    [
                        "exec".into(),
                        container_id.clone(),
                        "mkdir".into(),
                        "-p".into(),
                        worker_root.into(),
                        profile_home.into(),
                    ],
                )
                .purpose("create target worker directories"),
                CommandSpec::new(
                    engine,
                    [
                        "cp".into(),
                        worker_binary.to_string_lossy().into_owned(),
                        format!("{container_id}:{worker_root}/hel"),
                    ],
                )
                .purpose("upload Mjolnir worker"),
                CommandSpec::new(
                    engine,
                    [
                        "cp".into(),
                        launch_config.to_string_lossy().into_owned(),
                        format!("{container_id}:{worker_root}/launch.json"),
                    ],
                )
                .purpose("upload worker launch configuration"),
                CommandSpec::new(
                    engine,
                    [
                        "cp".into(),
                        ownership.to_string_lossy().into_owned(),
                        format!("{container_id}:{worker_root}/ownership.json"),
                    ],
                )
                .purpose("upload worker ownership marker"),
                CommandSpec::new(
                    engine,
                    [
                        "cp".into(),
                        format!("{}/.", profile_stage.display()),
                        format!("{container_id}:{profile_home}"),
                    ],
                )
                .purpose("upload harness profile allowlist"),
                CommandSpec::new(
                    engine,
                    container_upload_ownership_args(
                        engine,
                        container_id,
                        worker_root,
                        &[
                            &format!("{worker_root}/hel"),
                            &format!("{worker_root}/launch.json"),
                            &format!("{worker_root}/ownership.json"),
                            profile_home,
                        ],
                    ),
                )
                .purpose("match uploaded files to the worker directory owner"),
                CommandSpec::new(
                    engine,
                    [
                        "exec".into(),
                        container_id.clone(),
                        "chmod".into(),
                        "700".into(),
                        format!("{worker_root}/hel"),
                    ],
                )
                .purpose("make Mjolnir worker executable"),
                CommandSpec::new(
                    engine,
                    [
                        "exec".into(),
                        container_id.clone(),
                        "chmod".into(),
                        "-R".into(),
                        "go-rwx".into(),
                        profile_home.into(),
                    ],
                )
                .purpose("restrict harness profile permissions"),
            ] {
                execute_checked(executor, command)?;
            }
        }
        // A disposable EC2 instance hosts one session and is terminated with
        // it, so a cache there would only hold a second copy of the worker.
        targets::TargetLocator::AwsEc2 { ssh, .. } => {
            install_worker_over_ssh(
                executor,
                ssh,
                None,
                worker_root,
                profile_home,
                worker_binary,
                launch_config,
                ownership,
                profile_stage,
            )?;
        }
        targets::TargetLocator::SshBare { ssh, .. } => {
            let cached_worker = cache_worker_on_ssh_host(executor, ssh, session_id, worker_binary)?;
            install_worker_over_ssh(
                executor,
                ssh,
                Some(&cached_worker),
                worker_root,
                profile_home,
                worker_binary,
                launch_config,
                ownership,
                profile_stage,
            )?;
        }
        targets::TargetLocator::SshPodman {
            ssh, container_id, ..
        }
        | targets::TargetLocator::SshDocker {
            ssh, container_id, ..
        } => {
            let engine = match locator {
                targets::TargetLocator::SshPodman { .. } => "podman",
                targets::TargetLocator::SshDocker { .. } => "docker",
                _ => unreachable!("matched remote container target"),
            };
            let cached_worker = cache_worker_on_ssh_host(executor, ssh, session_id, worker_binary)?;
            let upload = format!("{}/{session_id}", targets::REMOTE_UPLOAD_STAGING);
            execute_checked(
                executor,
                crate::targets::ssh_command(ssh, ["mkdir", "-p", &upload])
                    .purpose("create remote upload staging"),
            )?;
            for (source, name) in [
                (launch_config, "launch.json"),
                (ownership, "ownership.json"),
            ] {
                execute_checked(
                    executor,
                    crate::targets::scp_upload(ssh, source, &format!("{upload}/{name}"), false)
                        .purpose("upload remote container worker file"),
                )?;
            }
            execute_checked(
                executor,
                crate::targets::scp_upload(ssh, profile_stage, &format!("{upload}/profile"), true)
                    .purpose("upload remote container profile allowlist"),
            )?;
            let remote = [
                vec![
                    engine.into(),
                    "exec".into(),
                    container_id.clone(),
                    "mkdir".into(),
                    "-p".into(),
                    worker_root.into(),
                    profile_home.into(),
                ],
                vec![
                    engine.into(),
                    "cp".into(),
                    cached_worker.clone(),
                    format!("{container_id}:{worker_root}/hel"),
                ],
                vec![
                    engine.into(),
                    "cp".into(),
                    format!("{upload}/launch.json"),
                    format!("{container_id}:{worker_root}/launch.json"),
                ],
                vec![
                    engine.into(),
                    "cp".into(),
                    format!("{upload}/ownership.json"),
                    format!("{container_id}:{worker_root}/ownership.json"),
                ],
                vec![
                    engine.into(),
                    "cp".into(),
                    format!("{upload}/profile/."),
                    format!("{container_id}:{profile_home}"),
                ],
                std::iter::once(engine.to_owned())
                    .chain(container_upload_ownership_args(
                        engine,
                        container_id,
                        worker_root,
                        &[
                            &format!("{worker_root}/hel"),
                            &format!("{worker_root}/launch.json"),
                            &format!("{worker_root}/ownership.json"),
                            profile_home,
                        ],
                    ))
                    .collect(),
                vec![
                    engine.into(),
                    "exec".into(),
                    container_id.clone(),
                    "chmod".into(),
                    "700".into(),
                    format!("{worker_root}/hel"),
                ],
                vec![
                    engine.into(),
                    "exec".into(),
                    container_id.clone(),
                    "chmod".into(),
                    "-R".into(),
                    "go-rwx".into(),
                    profile_home.into(),
                ],
                vec!["rm".into(), "-rf".into(), "--".into(), upload.clone()],
            ];
            for args in remote {
                execute_checked(
                    executor,
                    crate::targets::ssh_command(ssh, args)
                        .purpose("install remote container worker"),
                )?;
            }
        }
    }
    Ok(())
}

/// Put the worker binary in the SSH host's content-addressed cache and answer
/// with its path there. The binary crosses the network only when the host
/// does not hold this build yet.
///
/// A worker binary is well over 100 MB and identical across sessions. Uploading
/// it once per session made each create on a slow link hold a daemon action
/// slot for minutes (R3-4). Every session on the host, SSH-bare or in a remote
/// container, copies its own worker from here instead.
///
/// Two sessions that find the cache empty at the same time each upload to
/// their own partial name and rename it into place, so the cached path only
/// ever names a complete file.
fn cache_worker_on_ssh_host(
    executor: &impl CommandExecutor,
    ssh: &SshTarget,
    session_id: &str,
    worker_binary: &Path,
) -> Result<String> {
    let digest = mj_core::worker_launch::worker_executable_digest(worker_binary)?;
    // Home-relative, not "~/": targets::ssh_command single-quotes every
    // argument, so a tilde would stay literal in the remote shell while scp
    // expands it, and the two sides would disagree. Both ssh commands (cwd is
    // the login home) and scp resolve a relative path against the remote home.
    let cache_dir = format!(".cache/mjolnir/workers/{digest}");
    let cached_worker = format!("{cache_dir}/hel");
    let cached = matches!(
        executor.execute(
            &crate::targets::ssh_command(ssh, ["test", "-f", &cached_worker])
                .purpose("probe cached remote Mjolnir worker"),
        ),
        Ok(output) if output.status == 0
    );
    if cached {
        return Ok(cached_worker);
    }
    execute_checked(
        executor,
        crate::targets::ssh_command(ssh, ["mkdir", "-p", &cache_dir])
            .purpose("create remote worker cache"),
    )?;
    let partial = format!("{cache_dir}/hel.partial-{session_id}");
    if let Err(error) = execute_checked(
        executor,
        crate::targets::scp_upload(ssh, worker_binary, &partial, false)
            .purpose("upload Mjolnir worker to the remote cache"),
    ) {
        // The partial file is outside every session's worker root, so no
        // session cleanup would ever remove it. Best effort: a connection
        // that failed the upload may fail this too.
        let _ = executor.execute(
            &crate::targets::ssh_command(ssh, ["rm", "-f", "--", &partial])
                .purpose("remove partial remote worker upload"),
        );
        return Err(error);
    }
    execute_checked(
        executor,
        crate::targets::ssh_command(ssh, ["mv", &partial, &cached_worker])
            .purpose("publish cached remote Mjolnir worker"),
    )?;
    Ok(cached_worker)
}

/// Install a worker on a host reached over SSH with no container.
///
/// `cached_worker` is the host's cached copy of the worker binary, from
/// [`cache_worker_on_ssh_host`]; the session gets its own copy of it, so its
/// worker root and cleanup are the same as with an upload. Without one, the
/// local binary is uploaded straight into the worker root.
#[allow(clippy::too_many_arguments)]
pub(super) fn install_worker_over_ssh(
    executor: &impl CommandExecutor,
    ssh: &SshTarget,
    cached_worker: Option<&str>,
    worker_root: &str,
    profile_home: &str,
    worker_binary: &Path,
    launch_config: &Path,
    ownership: &Path,
    profile_stage: &Path,
) -> Result<()> {
    execute_checked(
        executor,
        crate::targets::ssh_command(ssh, ["mkdir", "-p", worker_root, profile_home])
            .purpose("create SSH worker directories"),
    )?;
    let worker = format!("{worker_root}/hel");
    let install_worker = match cached_worker {
        Some(cached_worker) => crate::targets::ssh_command(ssh, ["cp", cached_worker, &worker])
            .purpose("copy cached Mjolnir worker into the session"),
        None => crate::targets::scp_upload(ssh, worker_binary, &worker, false)
            .purpose("upload SSH worker file"),
    };
    execute_checked(executor, install_worker)?;
    for (source, remote) in [
        (launch_config, format!("{worker_root}/launch.json")),
        (ownership, format!("{worker_root}/ownership.json")),
    ] {
        execute_checked(
            executor,
            crate::targets::scp_upload(ssh, source, &remote, false)
                .purpose("upload SSH worker file"),
        )?;
    }
    let incoming_profile = format!("{profile_home}.incoming");
    execute_checked(
        executor,
        crate::targets::scp_upload(ssh, profile_stage, &incoming_profile, true)
            .purpose("upload SSH harness profile allowlist"),
    )?;
    execute_checked(
        executor,
        crate::targets::ssh_command(
            ssh,
            ["cp", "-R", &format!("{incoming_profile}/."), profile_home],
        )
        .purpose("install SSH harness profile allowlist"),
    )?;
    execute_checked(
        executor,
        crate::targets::ssh_command(ssh, ["rm", "-rf", "--", &incoming_profile])
            .purpose("remove SSH profile staging"),
    )?;
    execute_checked(
        executor,
        crate::targets::ssh_command(ssh, ["chmod", "700", &format!("{worker_root}/hel")])
            .purpose("make SSH worker executable"),
    )?;
    execute_checked(
        executor,
        crate::targets::ssh_command(ssh, ["chmod", "-R", "go-rwx", profile_home])
            .purpose("restrict SSH harness profile permissions"),
    )?;
    Ok(())
}

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

    #[cfg(target_os = "linux")]
    fn execute_script(
        script: &str,
        arguments: impl IntoIterator<Item = String>,
        path: Option<&Path>,
        home: Option<&Path>,
    ) -> CommandOutput {
        let args = std::iter::once("-c".to_owned())
            .chain(std::iter::once(script.to_owned()))
            .chain(std::iter::once("sh".to_owned()))
            .chain(arguments)
            .collect::<Vec<_>>();
        let mut command = CommandSpec::new("sh", args);
        if let Some(path) = path {
            command
                .env
                .insert("PATH".into(), format!("{}:/usr/bin:/bin", path.display()));
        }
        if let Some(home) = home {
            command
                .env
                .insert("HOME".into(), home.to_string_lossy().into_owned());
        }
        targets::ProcessExecutor.execute(&command).unwrap()
    }

    #[cfg(target_os = "linux")]
    fn run_script(script: &str, arguments: impl IntoIterator<Item = String>) {
        let output = execute_script(script, arguments, None, None);
        assert_eq!(
            output.status,
            0,
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn only_marked_mbx_shims_are_removed() {
        let root = tempfile::tempdir().unwrap();
        let generated = root.path().join("generated");
        run_script(
            INSTALL_MBX_SHIMS_SCRIPT,
            [
                generated.to_string_lossy().into_owned(),
                "MBX_CARGO_SHIM_MODE=1\nMBX_CARGO_SHIM_PATH=$(command -v \"$0\")\nexport MBX_CARGO_SHIM_MODE MBX_CARGO_SHIM_PATH\nexec /cache/.mjolnir/bin/mbx \"$@\"".into(),
                "exec /cache/.mjolnir/bin/mbx \"$@\"".into(),
            ],
        );
        for name in ["cargo", "mbx"] {
            let script = std::fs::read_to_string(generated.join(name)).unwrap();
            assert!(script.lines().any(|line| line == "# mjolnir-mbx-shim"));
        }

        let legacy = root.path().join("legacy");
        std::fs::create_dir(&legacy).unwrap();
        std::fs::write(legacy.join("cargo"), b"legacy cargo binary").unwrap();
        std::fs::write(legacy.join("mbx"), b"legacy copied mbx binary").unwrap();

        run_script(
            REMOVE_MBX_SHIMS_SCRIPT,
            [generated.to_string_lossy().into_owned()],
        );
        run_script(
            REMOVE_MBX_SHIMS_SCRIPT,
            [legacy.to_string_lossy().into_owned()],
        );

        assert!(!generated.join("cargo").exists());
        assert!(!generated.join("mbx").exists());
        assert_eq!(
            std::fs::read(legacy.join("cargo")).unwrap(),
            b"legacy cargo binary"
        );
        assert_eq!(
            std::fs::read(legacy.join("mbx")).unwrap(),
            b"legacy copied mbx binary"
        );
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn legacy_detection_distinguishes_grep_miss_match_and_failure() {
        use std::os::unix::fs::PermissionsExt;

        let temp = tempfile::tempdir().unwrap();
        let source = temp.path().join("shared config");
        std::fs::create_dir_all(&source).unwrap();
        std::fs::write(source.join("config.toml"), "[cache]\n").unwrap();
        let roots = temp.path().join("config roots");
        let home = temp.path().join("home");
        let legacy = temp.path().join("legacy");
        std::fs::create_dir_all(&legacy).unwrap();
        std::fs::create_dir_all(&home).unwrap();
        std::fs::write(legacy.join("mbx"), b"private copied mbx binary").unwrap();
        let args = || {
            vec![
                legacy.to_string_lossy().into_owned(),
                source.to_string_lossy().into_owned(),
                roots.to_string_lossy().into_owned(),
            ]
        };

        let legacy_output = execute_script(
            CHECK_LEGACY_MBX_AND_LINK_CONFIG_SCRIPT,
            args(),
            None,
            Some(&home),
        );
        assert_eq!(legacy_output.status, 0);
        assert_eq!(legacy_output.stdout, b"legacy");

        std::fs::write(legacy.join("mbx"), "#!/bin/sh\n# mjolnir-mbx-shim\n").unwrap();
        let new_output = execute_script(
            CHECK_LEGACY_MBX_AND_LINK_CONFIG_SCRIPT,
            args(),
            None,
            Some(&home),
        );
        assert_eq!(new_output.status, 0);
        assert_eq!(new_output.stdout, b"new");

        let tools = temp.path().join("tools");
        std::fs::create_dir_all(&tools).unwrap();
        std::fs::write(tools.join("grep"), "#!/bin/sh\nexit 2\n").unwrap();
        std::fs::set_permissions(tools.join("grep"), std::fs::Permissions::from_mode(0o755))
            .unwrap();
        std::fs::write(legacy.join("mbx"), b"private copied mbx binary").unwrap();
        let failed = execute_script(
            CHECK_LEGACY_MBX_AND_LINK_CONFIG_SCRIPT,
            args(),
            Some(&tools),
            Some(&home),
        );
        assert_ne!(failed.status, 0);
        assert!(
            String::from_utf8_lossy(&failed.stderr).contains("grep exited 2"),
            "{}",
            String::from_utf8_lossy(&failed.stderr)
        );
    }

    #[test]
    fn legacy_detection_errors_are_returned_to_the_caller() {
        struct FailedInspection;
        impl crate::targets::CommandExecutor for FailedInspection {
            fn execute(&self, _command: &CommandSpec) -> anyhow::Result<CommandOutput> {
                Ok(CommandOutput {
                    status: 1,
                    stdout: Vec::new(),
                    stderr: b"could not inspect the Mjolnir mbx shim marker in /worker/bin/mbx (grep exited 2)".to_vec(),
                })
            }
        }

        let error = link_legacy_mbx_configuration(
            &FailedInspection,
            &targets::TargetLocator::LocalPodman {
                borrowed_from: None,
                container_id: "mj-test-container".into(),
                workspace_storage: targets::PodmanWorkspaceLocator::ContainerLayer,
            },
            "/worker",
            Path::new("/cache/.mjolnir/config/mbx"),
            &[],
        )
        .unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains("grep exited 2"), "{message}");
    }
}